🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(connector-data): add Gmail client (#17322)
Neko3c42297798da
diff --git a/packages/connector-data/package.json b/packages/connector-data/package.jsonindex d857adc6efc..4512ba6229a 100644--- a/packages/connector-data/package.json+++ b/packages/connector-data/package.json@@ -11,6 +11,10 @@"./github": {"types": "./src/github/index.ts","default": "./src/github/index.ts"+ },+ "./gmail": {+ "types": "./src/gmail/index.ts",+ "default": "./src/gmail/index.ts"}},"main": "./src/index.ts",@@ -18,11 +22,17 @@"test": "vitest run --silent='passed-only'"},"dependencies": {+ "@lobechat/utils": "workspace:*","debug": "^4.4.3",+ "html-to-text": "^9.0.5","octokit": "^5.0.0",+ "xast-util-to-xml": "^4.0.0",+ "xastscript": "^4.0.0","zod": "^3.25.76"},"devDependencies": {- "@types/debug": "^4.1.13"+ "@types/debug": "^4.1.13",+ "@types/html-to-text": "^9.0.4",+ "@types/node": "^24.13.2"}}diff --git a/packages/connector-data/src/errors.ts b/packages/connector-data/src/errors.tsindex ac7272492e6..b38b8b2c93a 100644--- a/packages/connector-data/src/errors.ts+++ b/packages/connector-data/src/errors.ts@@ -1,4 +1,4 @@-export type ConnectorDataProvider = 'github';+export type ConnectorDataProvider = 'github' | 'gmail';export interface ConnectorDataErrorOptions {code: string;diff --git a/packages/connector-data/src/github/client.ts b/packages/connector-data/src/github/client.tsindex 11c982fce7d..41c3fb26919 100644--- a/packages/connector-data/src/github/client.ts+++ b/packages/connector-data/src/github/client.ts@@ -1,3 +1,4 @@+import { createRecoverableMemo } from '../memo';import type { GitHubConnectorTransport } from './graphql/client';import { createGitHubGraphQLClient, createOctokitTransport } from './graphql/client';import {@@ -35,18 +36,6 @@ export interface CreateGitHubConnectorClientOptions {transport?: GitHubConnectorTransport;}-const createRecoverableMemo = <T>(load: () => Promise<T>) => {- let promise: Promise<T> | undefined;-- return () => {- promise ??= load().catch((error) => {- promise = undefined;- throw error;- });- return promise;- };-};-export const createGitHubConnectorClient = ({accessToken,transport = createOctokitTransport(accessToken),diff --git a/packages/connector-data/src/gmail/account.test.ts b/packages/connector-data/src/gmail/account.test.tsnew file mode 100644index 00000000000..1a5d3a305f0--- /dev/null+++ b/packages/connector-data/src/gmail/account.test.ts@@ -0,0 +1,180 @@+import { describe, expect, it, vi } from 'vitest';++import { ConnectorDataError } from '../errors';+import { loadGmailAccount } from './account';++const loadAccount = (list: ReturnType<typeof vi.fn>, get = vi.fn()) =>+ loadGmailAccount({+ connectedAccountId: 'account-1',+ connectedAccounts: { get, list },+ userId: 'user-1',+ });++describe('loadGmailAccount', () => {+ it('loads an active Gmail account owned by the configured user', async () => {+ const list = vi.fn().mockResolvedValue({+ items: [+ {+ data: { email: 'Neko <[email protected]>', scopes: ['openid', 'gmail.readonly'] },+ id: 'account-1',+ status: 'ACTIVE',+ toolkit: { slug: 'GMAIL' },+ },+ ],+ totalPages: 1,+ });+ const get = vi.fn();++ await expect(loadAccount(list, get)).resolves.toEqual({+ email: '[email protected]',+ externalAccountId: 'account-1',+ scopes: ['gmail.readonly', 'openid'],+ });+ expect(list).toHaveBeenCalledWith({+ limit: 100,+ toolkitSlugs: ['gmail'],+ userIds: ['user-1'],+ });+ expect(get).not.toHaveBeenCalled();+ });++ it('follows ownership pages and loads missing account details', async () => {+ const list = vi+ .fn()+ .mockResolvedValueOnce({ items: [], nextCursor: 'page-2', totalPages: 9 })+ .mockResolvedValueOnce({+ items: [{ id: 'account-1', status: 'ACTIVE', toolkit: { slug: 'gmail' } }],+ totalPages: 9,+ });+ const get = vi.fn().mockResolvedValue({+ data: { email: '[email protected]', scope: 'openid,gmail.readonly' },+ id: 'account-1',+ status: 'ACTIVE',+ toolkit: { slug: 'gmail' },+ });++ await expect(loadAccount(list, get)).resolves.toEqual({+ email: '[email protected]',+ externalAccountId: 'account-1',+ scopes: ['gmail.readonly', 'openid'],+ });+ expect(list).toHaveBeenNthCalledWith(2, {+ cursor: 'page-2',+ limit: 100,+ toolkitSlugs: ['gmail'],+ userIds: ['user-1'],+ });+ expect(get).toHaveBeenCalledWith('account-1');+ });++ it('reads OAuth2 metadata without enumerating credentials or unrelated fields', async () => {+ let accessTokenRead = false;+ const account = {+ id: 'account-1',+ state: {+ authScheme: 'OAUTH2',+ val: {+ email: '[email protected]',+ scope: 'openid gmail.readonly',+ status: 'ACTIVE',+ get access_token(): never {+ accessTokenRead = true;+ throw new Error('access token must not be read');+ },+ },+ },+ toolkit: { slug: 'gmail' },+ get unrelated(): never {+ throw new Error('unrelated account field accessed');+ },+ };+ const list = vi.fn().mockResolvedValue({+ items: [account],+ totalPages: 1,+ get unrelated(): never {+ throw new Error('unrelated response field accessed');+ },+ });++ await expect(loadAccount(list)).resolves.toEqual({+ email: '[email protected]',+ externalAccountId: 'account-1',+ scopes: ['gmail.readonly', 'openid'],+ });+ expect(accessTokenRead).toBe(false);+ });++ it.each([+ {+ detailData: { scopes: ['gmail.readonly'] },+ expected: { email: '[email protected]', scopes: ['gmail.readonly'] },+ listData: { email: '[email protected]' },+ },+ {+ detailData: { email: '[email protected]' },+ expected: { email: '[email protected]', scopes: ['gmail.readonly'] },+ listData: { scopes: ['gmail.readonly'] },+ },+ ])(+ 'merges partially populated list and detail accounts',+ async ({ detailData, expected, listData }) => {+ const list = vi.fn().mockResolvedValue({+ items: [{ data: listData, id: 'account-1', status: 'ACTIVE', toolkit: { slug: 'gmail' } }],+ totalPages: 1,+ });+ const get = vi.fn().mockResolvedValue({+ data: detailData,+ id: 'account-1',+ status: 'ACTIVE',+ toolkit: { slug: 'gmail' },+ });++ await expect(loadAccount(list, get)).resolves.toMatchObject({+ externalAccountId: 'account-1',+ ...expected,+ });+ },+ );++ it('inspects at most 100 connected accounts per page', async () => {+ let accessedBeyondBound = false;+ const items = Array.from({ length: 100 }, (_, index) => ({+ id: `other-${index}`,+ status: 'ACTIVE',+ toolkit: { slug: 'gmail' },+ }));+ items.length = 1_000_000;+ const proxiedItems = new Proxy(items, {+ get: (target, property, receiver) => {+ if (property === '100') {+ accessedBeyondBound = true;+ throw new Error('account beyond page bound accessed');+ }+ return Reflect.get(target, property, receiver);+ },+ });++ await expect(+ loadAccount(vi.fn().mockResolvedValue({ items: proxiedItems, totalPages: 1 })),+ ).rejects.toBeInstanceOf(ConnectorDataError);+ expect(accessedBeyondBound).toBe(false);+ });++ it.each([+ { id: 'account-1', status: 'EXPIRED', toolkit: { slug: 'gmail' } },+ { id: 'account-1', status: 'ACTIVE', toolkit: { slug: 'github' } },+ { id: 'account-1', isDisabled: true, status: 'ACTIVE', toolkit: { slug: 'gmail' } },+ ])('rejects inactive, disabled, or non-Gmail accounts', async (account) => {+ const error = await loadAccount(+ vi.fn().mockResolvedValue({ items: [account], totalPages: 1 }),+ ).catch((reason) => reason);++ expect(error).toBeInstanceOf(ConnectorDataError);+ expect(error).toMatchObject({+ code: 'gmail_account_unavailable',+ operation: 'getAccount',+ provider: 'gmail',+ });+ expect(error.message).not.toMatch(/account-1|EXPIRED|github/);+ });+});diff --git a/packages/connector-data/src/gmail/account.ts b/packages/connector-data/src/gmail/account.tsnew file mode 100644index 00000000000..c13a40539fc--- /dev/null+++ b/packages/connector-data/src/gmail/account.ts@@ -0,0 +1,176 @@+import { toRecord } from '@lobechat/utils/object';++import { ConnectorDataError } from '../errors';+import { withConnectorRetry } from '../retry';+import { extractGmailEmail } from './normalize';+import type { GmailAccount } from './types';++const MAX_ACCOUNT_ID_LENGTH = 512;+const MAX_ACCOUNT_PAGES = 3;+const MAX_ACCOUNTS_PER_PAGE = 100;+const MAX_SCOPE_COUNT = 100;+const MAX_SCOPE_LENGTH = 256;++export interface GmailConnectedAccountListInput {+ cursor?: string;+ limit: number;+ toolkitSlugs: string[];+ userIds: string[];+}++export interface GmailComposioConnectedAccounts {+ get: (connectedAccountId: string) => Promise<unknown>;+ list: (input: GmailConnectedAccountListInput) => Promise<unknown>;+}++const readString = (+ record: Record<PropertyKey, unknown> | undefined,+ key: PropertyKey,+ limit: number,+) => {+ const value = record?.[key];+ return typeof value === 'string' ? value.slice(0, limit) : undefined;+};++const readScopes = (value: unknown) => {+ const values = Array.isArray(value)+ ? value.slice(0, MAX_SCOPE_COUNT)+ : typeof value === 'string'+ ? value.slice(0, 8000).split(/[\s,]+/)+ : [];+ return [+ ...new Set(+ values+ .filter((scope): scope is string => typeof scope === 'string')+ .map((scope) => scope.slice(0, MAX_SCOPE_LENGTH).trim())+ .filter(Boolean),+ ),+ ].sort();+};++const parseAccount = (value: unknown): GmailAccount | undefined => {+ const account = toRecord(value);+ if (!account) return undefined;+ const data = toRecord(account.data);+ const metadata = toRecord(account.metadata);+ const state = toRecord(account.state);+ const stateValue = toRecord(state?.val);+ const toolkit = toRecord(account.toolkit);+ const status = readString(account, 'status', 32) ?? readString(stateValue, 'status', 32);+ const toolkitSlug = readString(toolkit, 'slug', 32);+ if (+ account.isDisabled === true ||+ status?.toUpperCase() !== 'ACTIVE' ||+ toolkitSlug?.toLowerCase() !== 'gmail'+ ) {+ return undefined;+ }+ const id = readString(account, 'id', MAX_ACCOUNT_ID_LENGTH);+ if (!id) return undefined;+ const authScheme = readString(state, 'authScheme', 32)?.toUpperCase();+ const stateScope = authScheme === 'OAUTH2' ? stateValue?.scope : undefined;+ const stateEmail = authScheme === 'OAUTH2' ? stateValue?.email : undefined;+ const scopeValue = account.scopes ?? data?.scopes ?? account.scope ?? data?.scope ?? stateScope;++ return {+ email: extractGmailEmail(account.email ?? data?.email ?? metadata?.email ?? stateEmail),+ externalAccountId: id,+ scopes: readScopes(scopeValue),+ };+};++export interface LoadGmailAccountOptions {+ connectedAccountId: string;+ connectedAccounts: GmailComposioConnectedAccounts;+ userId: string;+}++export const loadGmailAccount = async ({+ connectedAccountId,+ connectedAccounts,+ userId,+}: LoadGmailAccountOptions): Promise<GmailAccount> => {+ try {+ let cursor: string | undefined;+ let ownedAccount: GmailAccount | undefined;++ for (let page = 0; page < MAX_ACCOUNT_PAGES; page += 1) {+ const response = await withConnectorRetry(+ () =>+ connectedAccounts.list({+ ...(cursor ? { cursor } : {}),+ limit: MAX_ACCOUNTS_PER_PAGE,+ toolkitSlugs: ['gmail'],+ userIds: [userId],+ }),+ {+ code: 'gmail_account_unavailable',+ operation: 'getAccount',+ provider: 'gmail',+ },+ );+ const responseRecord = toRecord(response);+ const items = responseRecord?.items;+ if (!Array.isArray(items)) break;+ let match: unknown;+ const itemLimit = Math.min(items.length, MAX_ACCOUNTS_PER_PAGE);+ for (let index = 0; index < itemLimit; index += 1) {+ const item = items[index];+ if (readString(toRecord(item), 'id', MAX_ACCOUNT_ID_LENGTH) === connectedAccountId) {+ match = item;+ break;+ }+ }+ if (match) {+ ownedAccount = parseAccount(match);+ break;+ }+ const nextCursor = readString(responseRecord, 'nextCursor', MAX_ACCOUNT_ID_LENGTH);+ const totalPages =+ typeof responseRecord?.totalPages === 'number' ? responseRecord.totalPages : undefined;+ if (!nextCursor || (totalPages !== undefined && page + 1 >= totalPages)) {+ break;+ }+ cursor = nextCursor;+ }++ if (!ownedAccount) {+ throw new ConnectorDataError({+ code: 'gmail_account_unavailable',+ operation: 'getAccount',+ provider: 'gmail',+ retryable: false,+ });+ }+ if (ownedAccount.email && ownedAccount.scopes.length > 0) return ownedAccount;++ const detail = parseAccount(+ await withConnectorRetry(() => connectedAccounts.get(connectedAccountId), {+ code: 'gmail_account_unavailable',+ operation: 'getAccount',+ provider: 'gmail',+ }),+ );+ if (!detail || detail.externalAccountId !== connectedAccountId) {+ throw new ConnectorDataError({+ code: 'gmail_account_unavailable',+ operation: 'getAccount',+ provider: 'gmail',+ retryable: false,+ });+ }+ return {+ email: ownedAccount.email ?? detail.email,+ externalAccountId: ownedAccount.externalAccountId,+ scopes: ownedAccount.scopes.length > 0 ? ownedAccount.scopes : detail.scopes,+ };+ } catch (error) {+ if (error instanceof ConnectorDataError) throw error;+ throw new ConnectorDataError({+ code: 'gmail_account_unavailable',+ operation: 'getAccount',+ provider: 'gmail',+ retryable: false,+ });+ }+};diff --git a/packages/connector-data/src/gmail/client.test.ts b/packages/connector-data/src/gmail/client.test.tsnew file mode 100644index 00000000000..70cfa368810--- /dev/null+++ b/packages/connector-data/src/gmail/client.test.ts@@ -0,0 +1,117 @@+import { describe, expect, it, vi } from 'vitest';++import { ConnectorDataError } from '../errors';+import { createGmailConnectorClient } from './client';++const createClient = (+ execute: ReturnType<typeof vi.fn>,+ options: { resolveVersion?: ReturnType<typeof vi.fn> } = {},+) =>+ createGmailConnectorClient({+ composio: {+ connectedAccounts: { get: vi.fn(), list: vi.fn() },+ tools: { execute, getRawComposioToolBySlug: options.resolveVersion },+ },+ connectedAccountId: 'account-1',+ ...(options.resolveVersion ? {} : { toolVersion: '20250909_00' }),+ userId: 'user-1',+ });++describe('createGmailConnectorClient', () => {+ it('executes a bounded Gmail search and normalizes nested messages', async () => {+ const execute = vi.fn().mockResolvedValue({+ result: {+ data: {+ messages: [+ {+ id: 'message-1',+ labelIds: ['INBOX'],+ sender: 'Sender <[email protected]>',+ subject: 'Status',+ },+ ],+ },+ },+ successful: true,+ });++ await expect(+ createClient(execute).searchMessages({ maxResults: 10_000, query: 'newer_than:90d' }),+ ).resolves.toEqual([+ {+ id: 'message-1',+ labels: ['INBOX'],+ sender: '[email protected]',+ sourceUrl: 'gmail:message:message-1',+ subject: 'Status',+ },+ ]);+ expect(execute).toHaveBeenCalledWith('GMAIL_FETCH_EMAILS', {+ arguments: { max_results: 25, query: 'newer_than:90d' },+ connectedAccountId: 'account-1',+ userId: 'user-1',+ version: '20250909_00',+ });+ });++ it.each([Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY])(+ 'falls back to the safe default for non-finite maxResults %s',+ async (maxResults) => {+ const execute = vi.fn().mockResolvedValue({ data: [], successful: true });++ await createClient(execute).searchMessages({ maxResults, query: 'receipt' });++ expect(execute).toHaveBeenCalledWith(+ 'GMAIL_FETCH_EMAILS',+ expect.objectContaining({ arguments: { max_results: 25, query: 'receipt' } }),+ );+ },+ );++ it('sanitizes resolved and rejected Composio search failures', async () => {+ const execute = vi+ .fn()+ .mockResolvedValueOnce({ error: 'token=secret', successful: false })+ .mockRejectedValueOnce(new Error('account-1 token=secret'));+ const client = createClient(execute);++ for (let attempt = 0; attempt < 2; attempt += 1) {+ const error = await client.searchMessages({ query: 'receipt' }).catch((reason) => reason);+ expect(error).toBeInstanceOf(ConnectorDataError);+ expect(error.message).toBe('gmail searchMessages failed');+ expect(error.message).not.toMatch(/secret|account-1/);+ }+ });++ it.each([+ { data: [] },+ { data: [], successful: 'true' },+ { data: { messages: [{ unexpected: true }] }, successful: true },+ { payload: { unexpected: true }, successful: true },+ ])('rejects malformed Composio search responses', async (response) => {+ await expect(+ createClient(vi.fn().mockResolvedValue(response)).searchMessages({ query: 'receipt' }),+ ).rejects.toMatchObject({+ operation: 'searchMessages',+ provider: 'gmail',+ retryable: false,+ });+ });++ it('resolves and caches an explicit Composio tool version', async () => {+ const resolveVersion = vi.fn().mockResolvedValue({ version: '20250909_00' });+ const execute = vi.fn().mockResolvedValue({ data: [], successful: true });+ const client = createClient(execute, { resolveVersion });++ await client.searchMessages({ query: 'receipt' });+ await client.searchMessages({ query: 'invoice' });++ expect(resolveVersion).toHaveBeenCalledOnce();+ expect(resolveVersion).toHaveBeenCalledWith('GMAIL_FETCH_EMAILS');+ expect(execute).toHaveBeenNthCalledWith(+ 2,+ 'GMAIL_FETCH_EMAILS',+ expect.objectContaining({ version: '20250909_00' }),+ );+ });+});diff --git a/packages/connector-data/src/gmail/client.ts b/packages/connector-data/src/gmail/client.tsnew file mode 100644index 00000000000..3c57efe6cc7--- /dev/null+++ b/packages/connector-data/src/gmail/client.ts@@ -0,0 +1,142 @@+import { ConnectorDataError } from '../errors';+import { createRecoverableMemo } from '../memo';+import { withConnectorRetry } from '../retry';+import type { GmailComposioConnectedAccounts } from './account';+import { loadGmailAccount } from './account';+import { parseGmailMessages } from './message';+import type { GmailAccount, GmailMessage } from './types';++const DEFAULT_MAX_RESULTS = 25;+const MAX_QUERY_LENGTH = 2048;+const MAX_TOOL_VERSION_LENGTH = 64;+const SAFE_TOOL_VERSION = /^[a-z0-9][\w.-]*$/i;+const SEARCH_TOOL_SLUG = 'GMAIL_FETCH_EMAILS';++const readToolVersion = (value: unknown): string | undefined => {+ if (typeof value !== 'string') return undefined;+ if (+ value.length > MAX_TOOL_VERSION_LENGTH ||+ !SAFE_TOOL_VERSION.test(value) ||+ value.toLowerCase() === 'latest'+ ) {+ return undefined;+ }+ return value;+};++export interface GmailComposioTools {+ execute: (+ toolSlug: string,+ input: {+ arguments: { max_results: number; query: string };+ connectedAccountId: string;+ userId: string;+ version: string;+ },+ ) => Promise<unknown>;+ getRawComposioToolBySlug?: (toolSlug: string) => Promise<unknown>;+}++export interface GmailComposioClient {+ connectedAccounts: GmailComposioConnectedAccounts;+ tools: GmailComposioTools;+}++export interface GmailSearchMessagesInput {+ maxResults?: number;+ query: string;+}++export interface GmailConnectorClient {+ getAccount: () => Promise<GmailAccount>;+ searchMessages: (input: GmailSearchMessagesInput) => Promise<GmailMessage[]>;+}++export interface CreateGmailConnectorClientOptions {+ composio: GmailComposioClient;+ connectedAccountId: string;+ toolVersion?: string;+ userId: string;+}++export const createGmailConnectorClient = ({+ composio,+ connectedAccountId,+ toolVersion,+ userId,+}: CreateGmailConnectorClientOptions): GmailConnectorClient => {+ const getToolVersion = createRecoverableMemo(async () => {+ const configured = readToolVersion(toolVersion);+ if (configured) return configured;+ const tool = await composio.tools.getRawComposioToolBySlug?.(SEARCH_TOOL_SLUG);+ const discovered =+ typeof tool === 'object' && tool !== null && 'version' in tool+ ? readToolVersion(tool.version)+ : undefined;+ if (discovered) return discovered;+ throw new ConnectorDataError({+ code: 'gmail_tool_version_unavailable',+ operation: 'searchMessages',+ provider: 'gmail',+ retryable: false,+ });+ });++ return {+ getAccount: () =>+ loadGmailAccount({+ connectedAccountId,+ connectedAccounts: composio.connectedAccounts,+ userId,+ }),+ searchMessages: async ({ maxResults = DEFAULT_MAX_RESULTS, query }) => {+ const finiteMaxResults = Number.isFinite(maxResults) ? maxResults : DEFAULT_MAX_RESULTS;+ const boundedMaxResults = Math.min(+ Math.max(1, Math.floor(finiteMaxResults)),+ DEFAULT_MAX_RESULTS,+ );+ return withConnectorRetry(+ async () => {+ const version = await getToolVersion();+ const response = await composio.tools.execute(SEARCH_TOOL_SLUG, {+ arguments: {+ max_results: boundedMaxResults,+ query: query.slice(0, MAX_QUERY_LENGTH),+ },+ connectedAccountId,+ userId,+ version,+ });+ if (+ typeof response !== 'object' ||+ response === null ||+ !('successful' in response) ||+ response.successful !== true+ ) {+ throw new ConnectorDataError({+ code: 'gmail_search_failed',+ operation: 'searchMessages',+ provider: 'gmail',+ retryable: false,+ });+ }+ const messages = parseGmailMessages(response, { maxCandidates: boundedMaxResults });+ if (!messages) {+ throw new ConnectorDataError({+ code: 'gmail_response_invalid',+ operation: 'searchMessages',+ provider: 'gmail',+ retryable: false,+ });+ }+ return messages;+ },+ {+ code: 'gmail_search_failed',+ operation: 'searchMessages',+ provider: 'gmail',+ },+ );+ },+ };+};diff --git a/packages/connector-data/src/gmail/constants.ts b/packages/connector-data/src/gmail/constants.tsnew file mode 100644index 00000000000..3127e651f02--- /dev/null+++ b/packages/connector-data/src/gmail/constants.ts@@ -0,0 +1,10 @@+export const GMAIL_BODY_PREVIEW_MAX_LENGTH = 520;+export const GMAIL_DATE_MAX_LENGTH = 256;+export const GMAIL_EMAIL_MAX_LENGTH = 320;+export const GMAIL_EMAIL_SOURCE_MAX_LENGTH = 2048;+export const GMAIL_LABEL_MAX_LENGTH = 80;+export const GMAIL_LABELS_MAX_COUNT = 20;+export const GMAIL_MESSAGE_ID_MAX_LENGTH = 256;+export const GMAIL_SNIPPET_MAX_LENGTH = 320;+export const GMAIL_SOURCE_URL_MAX_LENGTH = 500;+export const GMAIL_SUBJECT_MAX_LENGTH = 320;diff --git a/packages/connector-data/src/gmail/formatter.test.ts b/packages/connector-data/src/gmail/formatter.test.tsnew file mode 100644index 00000000000..e58d8803d11--- /dev/null+++ b/packages/connector-data/src/gmail/formatter.test.ts@@ -0,0 +1,131 @@+import { describe, expect, it } from 'vitest';++import { toGmailMessagesXml } from './formatter';+import type { GmailMessage } from './types';++const message = (+ id: string,+ sender: string,+ labels: string[] = ['CATEGORY_UPDATES'],+): GmailMessage => ({+ bodyPreview: `Body ${id}`,+ id,+ labels,+ sender,+ subject: `Subject ${id}`,+});++describe('toGmailMessagesXml', () => {+ it('escapes XML values and reports the selected message count', () => {+ const xml = toGmailMessagesXml([+ {+ bodyPreview: 'Body <unsafe> & useful',+ date: '2026-07-12T00:00:00.000Z',+ id: 'id<&',+ labels: ['R&D'],+ recipient: '[email protected]',+ sender: '[email protected]',+ snippet: 'One & two',+ sourceUrl: 'gmail:thread:thread<&',+ subject: 'R&D <status>',+ },+ ]);++ expect(xml).toContain('<gmailMessages count="1">');+ expect(xml).toContain('id="id<&"');+ expect(xml).toContain('<subject>R&D <status></subject>');+ expect(xml).toContain('<bodyPreview>Body <unsafe> & useful</bodyPreview>');+ });++ it('honors a hard length limit without producing invalid XML', () => {+ const messages = Array.from({ length: 20 }, (_, index) => ({+ ...message(`long-${index}`, `sender-${index}@example.test`),+ bodyPreview: '<&'.repeat(1000),+ }));+ const xml = toGmailMessagesXml(messages, { maxLength: 1200 });++ expect(xml.length).toBeLessThanOrEqual(1200);+ expect(xml).toMatch(/^<gmailMessages count="\d+">/);+ expect(xml).toMatch(/<\/gmailMessages>$/);+ const count = Number(xml.match(/count="(\d+)"/)?.[1]);+ expect(xml.match(/<message /g) ?? []).toHaveLength(count);+ });++ it('returns a valid empty root when no message can fit', () => {+ expect(toGmailMessagesXml([message('one', '[email protected]')], { maxLength: 41 })).toBe(+ '<gmailMessages count="0"></gmailMessages>',+ );+ });++ it.each([Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY])(+ 'uses the default hard ceiling for non-finite maxLength %s',+ (maxLength) => {+ const smallXml = toGmailMessagesXml([message('small', '[email protected]')], { maxLength });+ const largeXml = toGmailMessagesXml(+ [+ {+ ...message('large', '[email protected]'),+ bodyPreview: '<&'.repeat(100_000),+ },+ ],+ { maxLength },+ );++ expect(smallXml).toContain('<gmailMessages count="1">');+ expect(largeXml.length).toBeLessThanOrEqual(48_000);+ expect(largeXml).toContain('<gmailMessages count="1">');+ },+ );++ it('rejects a finite limit smaller than the minimum valid empty root', () => {+ expect(() => toGmailMessagesXml([], { maxLength: 40 })).toThrow(+ new RangeError('Gmail XML maxLength must be at least 41'),+ );+ });++ it('clips adversarial public message fields before XML serialization', () => {+ const xml = toGmailMessagesXml([+ {+ bodyPreview: `${'b'.repeat(1_000_000)}BODY_OVERFLOW`,+ date: `${'d'.repeat(1_000_000)}DATE_OVERFLOW`,+ id: `${'i'.repeat(1_000_000)}ID_OVERFLOW`,+ labels: [+ `${'l'.repeat(1_000_000)}LABEL_OVERFLOW`,+ ...Array.from({ length: 100 }, (_, index) => `EXTRA_LABEL_${index}`),+ ],+ recipient: `${'r'.repeat(1_000_000)}RECIPIENT_OVERFLOW`,+ sender: `${'s'.repeat(1_000_000)}SENDER_OVERFLOW`,+ snippet: `${'n'.repeat(1_000_000)}SNIPPET_OVERFLOW`,+ sourceUrl: `${'u'.repeat(1_000_000)}URL_OVERFLOW`,+ subject: `${'t'.repeat(1_000_000)}SUBJECT_OVERFLOW`,+ },+ ]);++ expect(xml.length).toBeLessThanOrEqual(48_000);+ expect(xml).not.toMatch(+ /BODY_OVERFLOW|DATE_OVERFLOW|ID_OVERFLOW|LABEL_OVERFLOW|RECIPIENT_OVERFLOW|SENDER_OVERFLOW|SNIPPET_OVERFLOW|URL_OVERFLOW|SUBJECT_OVERFLOW|EXTRA_LABEL_20/,+ );+ });++ it('reads at most 32 public messages before formatting', () => {+ let accessedBeyondBound = false;+ const messages = Array.from({ length: 32 }, (_, index) =>+ message(`bounded-${index}`, `sender-${index}@example.test`),+ );+ messages.length = 1_000_000;+ const proxiedMessages = new Proxy(messages, {+ get: (target, property, receiver) => {+ if (property === '32') {+ accessedBeyondBound = true;+ throw new Error('message beyond formatter bound accessed');+ }+ return Reflect.get(target, property, receiver);+ },+ });++ const xml = toGmailMessagesXml(proxiedMessages);++ expect(xml).toContain('<gmailMessages count="32">');+ expect(accessedBeyondBound).toBe(false);+ });+});diff --git a/packages/connector-data/src/gmail/formatter.ts b/packages/connector-data/src/gmail/formatter.tsnew file mode 100644index 00000000000..a9a4d080aa2--- /dev/null+++ b/packages/connector-data/src/gmail/formatter.ts@@ -0,0 +1,98 @@+import { toXml } from 'xast-util-to-xml';+import { x } from 'xastscript';++import {+ GMAIL_BODY_PREVIEW_MAX_LENGTH,+ GMAIL_DATE_MAX_LENGTH,+ GMAIL_EMAIL_MAX_LENGTH,+ GMAIL_LABEL_MAX_LENGTH,+ GMAIL_LABELS_MAX_COUNT,+ GMAIL_MESSAGE_ID_MAX_LENGTH,+ GMAIL_SNIPPET_MAX_LENGTH,+ GMAIL_SOURCE_URL_MAX_LENGTH,+ GMAIL_SUBJECT_MAX_LENGTH,+} from './constants';+import { clipGmailText } from './normalize';+import type { GmailMessage } from './types';++const DEFAULT_MAX_LENGTH = 48_000;+const MAX_MESSAGES = 32;++const normalizeMessage = (message: GmailMessage): GmailMessage => {+ const labels: string[] = [];+ const labelLimit = Math.min(message.labels.length, GMAIL_LABELS_MAX_COUNT);+ for (let index = 0; index < labelLimit; index += 1) {+ const label = clipGmailText(message.labels[index], GMAIL_LABEL_MAX_LENGTH);+ if (label) labels.push(label);+ }++ return {+ bodyPreview: clipGmailText(message.bodyPreview, GMAIL_BODY_PREVIEW_MAX_LENGTH),+ date: clipGmailText(message.date, GMAIL_DATE_MAX_LENGTH),+ id: clipGmailText(message.id, GMAIL_MESSAGE_ID_MAX_LENGTH) ?? '',+ labels,+ recipient: clipGmailText(message.recipient, GMAIL_EMAIL_MAX_LENGTH),+ sender: clipGmailText(message.sender, GMAIL_EMAIL_MAX_LENGTH),+ snippet: clipGmailText(message.snippet, GMAIL_SNIPPET_MAX_LENGTH),+ sourceUrl: clipGmailText(message.sourceUrl, GMAIL_SOURCE_URL_MAX_LENGTH),+ subject: clipGmailText(message.subject, GMAIL_SUBJECT_MAX_LENGTH) ?? '(No subject)',+ };+};++const createMessagesTree = (messages: GmailMessage[]) =>+ x(+ 'gmailMessages',+ { count: String(messages.length) },+ messages.map((message) => {+ const children = [x('subject', message.subject)];+ if (message.sender) children.push(x('sender', message.sender));+ if (message.recipient) children.push(x('recipient', message.recipient));+ if (message.labels.length > 0) {+ children.push(+ x(+ 'labels',+ message.labels.map((label) => x('label', label)),+ ),+ );+ }+ if (message.snippet) children.push(x('snippet', message.snippet));+ if (message.bodyPreview) children.push(x('bodyPreview', message.bodyPreview));++ const attributes = Object.fromEntries(+ Object.entries({+ date: message.date?.slice(0, 10),+ id: message.id,+ sourceUrl: message.sourceUrl,+ }).filter((entry): entry is [string, string] => entry[1] !== undefined),+ );+ return x('message', attributes, children);+ }),+ );++const EMPTY_MESSAGES_XML = toXml(createMessagesTree([]));+const MIN_XML_LENGTH = EMPTY_MESSAGES_XML.length;++export interface ToGmailMessagesXmlOptions {+ maxLength?: number;+}++export const toGmailMessagesXml = (+ messages: GmailMessage[],+ { maxLength = DEFAULT_MAX_LENGTH }: ToGmailMessagesXmlOptions = {},+) => {+ const finiteMaxLength = Number.isFinite(maxLength) ? maxLength : DEFAULT_MAX_LENGTH;+ const limit = Math.min(Math.floor(finiteMaxLength), DEFAULT_MAX_LENGTH);+ if (limit < MIN_XML_LENGTH) {+ throw new RangeError(`Gmail XML maxLength must be at least ${MIN_XML_LENGTH}`);+ }+ const selected: GmailMessage[] = [];+ const messageLimit = Math.min(messages.length, MAX_MESSAGES);+ for (let index = 0; index < messageLimit; index += 1) {+ const message = normalizeMessage(messages[index]);+ const candidate = [...selected, message];+ if (toXml(createMessagesTree(candidate)).length > limit) break;+ selected.push(message);+ }++ return toXml(createMessagesTree(selected));+};diff --git a/packages/connector-data/src/gmail/index.ts b/packages/connector-data/src/gmail/index.tsnew file mode 100644index 00000000000..e42a3160262--- /dev/null+++ b/packages/connector-data/src/gmail/index.ts@@ -0,0 +1,3 @@+export * from './client';+export * from './formatter';+export * from './types';diff --git a/packages/connector-data/src/gmail/message.test.ts b/packages/connector-data/src/gmail/message.test.tsnew file mode 100644index 00000000000..da69d27c3d6--- /dev/null+++ b/packages/connector-data/src/gmail/message.test.ts@@ -0,0 +1,236 @@+import { describe, expect, it, vi } from 'vitest';++import { parseGmailMessages } from './message';++const message = (id: string, sender = '[email protected]') => ({+ id,+ labelIds: ['CATEGORY_UPDATES'],+ sender,+ subject: `Subject ${id}`,+});++describe('parseGmailMessages', () => {+ it('handles nullable fields and nested Composio envelopes', () => {+ expect(+ parseGmailMessages({+ result: {+ data: {+ emails: [+ {+ date: '2026-07-10T12:00:00Z',+ internalDate: null,+ labels: null,+ messageId: 'nullable',+ messageText: null,+ messageTimestamp: null,+ payload: null,+ preview: { body: 'Fallback preview' },+ sender: null,+ subject: 'Nullable',+ },+ ],+ },+ },+ }),+ ).toEqual([+ {+ bodyPreview: 'Fallback preview',+ date: '2026-07-10T12:00:00.000Z',+ id: 'nullable',+ labels: [],+ sourceUrl: 'gmail:message:nullable',+ subject: 'Nullable',+ },+ ]);+ });++ it.each([+ [{ data_preview: [message('preview-direct')] }, 'preview-direct'],+ [+ { data: { results: [{ response: { data: { messages: [message('response-data')] } } }] } },+ 'response-data',+ ],+ [+ {+ data: {+ results: [{ response: { data_preview: { messages: [message('response-preview')] } } }],+ },+ },+ 'response-preview',+ ],+ ])('handles Composio preview and execution response envelopes', (envelope, id) => {+ expect(parseGmailMessages(envelope)).toMatchObject([{ id }]);+ });++ it('does not enumerate unrelated top-level envelope fields', () => {+ const envelope = {+ data: [message('safe-envelope')],+ get unrelated(): never {+ throw new Error('unrelated envelope field accessed');+ },+ };++ expect(parseGmailMessages(envelope)).toMatchObject([{ id: 'safe-envelope' }]);+ });++ it('never reads a candidate beyond the configured bound', () => {+ let accessedBeyondBound = false;+ const candidates = Array.from({ length: 25 }, (_, index) => message(`bounded-${index}`));+ candidates.length = 1_000_000;+ const proxiedCandidates = new Proxy(candidates, {+ get: (target, property, receiver) => {+ if (property === '25') {+ accessedBeyondBound = true;+ throw new Error('out-of-bound candidate accessed');+ }+ return Reflect.get(target, property, receiver);+ },+ });++ expect(parseGmailMessages({ data: proxiedCandidates })).toHaveLength(25);+ expect(accessedBeyondBound).toBe(false);+ });++ it('deduplicates IDs before reading an expensive duplicate payload', () => {+ const duplicate = {+ id: 'duplicate',+ get payload(): never {+ throw new Error('duplicate payload accessed');+ },+ };++ expect(parseGmailMessages({ data: [message('duplicate'), duplicate] })).toHaveLength(1);+ });++ it('clips multi-megabyte fields before normalization work', () => {+ const replaceAll = vi.spyOn(String.prototype, 'replaceAll');++ const result = parseGmailMessages({+ data: [+ {+ messageId: 'huge',+ messageText: `${'a'.repeat(3_000_000)}BODY_OVERFLOW`,+ sender: `${'s'.repeat(1_000_000)}@example.com`,+ snippet: `${'n'.repeat(1_000_000)}SNIPPET_OVERFLOW`,+ subject: `${'t'.repeat(1_000_000)}SUBJECT_OVERFLOW`,+ },+ ],+ })?.[0];+ const largestNormalizedInput = Math.max(+ ...replaceAll.mock.instances.map((value) => String(value).length),+ );+ replaceAll.mockRestore();++ expect(largestNormalizedInput).toBeLessThanOrEqual(32_000);+ expect(JSON.stringify(result)).not.toMatch(/BODY_OVERFLOW|SNIPPET_OVERFLOW|SUBJECT_OVERFLOW/);+ });++ it.each(['labelIds', 'labels'] as const)(+ 'reads at most 20 entries from a million-item %s array',+ (field) => {+ let accessedBeyondBound = false;+ const labels = Array.from({ length: 20 }, (_, index) => `LABEL_${index}`);+ labels.length = 1_000_000;+ const proxiedLabels = new Proxy(labels, {+ get: (target, property, receiver) => {+ if (property === '20') {+ accessedBeyondBound = true;+ throw new Error('label beyond bound accessed');+ }+ return Reflect.get(target, property, receiver);+ },+ });++ const result = parseGmailMessages({+ data: [{ [field]: proxiedLabels, id: `bounded-${field}`, subject: 'Bounded labels' }],+ })?.[0];++ expect(result?.labels).toHaveLength(20);+ expect(accessedBeyondBound).toBe(false);+ },+ );++ it('bounds MIME depth, child count, and total parts', () => {+ const unreachable = {+ get mimeType(): never {+ throw new Error('unreachable MIME part visited');+ },+ };+ let deepPart: Record<string, unknown> = unreachable;+ for (let depth = 0; depth < 20; depth += 1) deepPart = { parts: [deepPart] };+ const payload = {+ headers: [{ name: 'Subject', value: 'Bounded MIME' }],+ parts: [...Array.from({ length: 16 }, () => deepPart), unreachable],+ };++ expect(+ parseGmailMessages({ data: [{ id: 'bounded-mime', payload, snippet: 'usable' }] }),+ ).toEqual([+ {+ id: 'bounded-mime',+ labels: [],+ snippet: 'usable',+ sourceUrl: 'gmail:message:bounded-mime',+ subject: 'Bounded MIME',+ },+ ]);+ });++ it('does not enumerate unrelated MIME part fields', () => {+ const payload = {+ body: { data: Buffer.from('Safe MIME body').toString('base64url') },+ mimeType: 'text/plain',+ get unrelated(): never {+ throw new Error('unrelated MIME field accessed');+ },+ };++ expect(+ parseGmailMessages({ data: [{ id: 'safe-mime', payload, subject: 'Safe' }] }),+ ).toMatchObject([{ bodyPreview: 'Safe MIME body', id: 'safe-mime' }]);+ });++ it('decodes base64url text/plain before HTML and converts HTML as fallback', () => {+ const plain = Buffer.from('Plain <body> & useful').toString('base64url');+ const html = Buffer.from('<p>HTML <strong>fallback</strong> & useful</p>').toString(+ 'base64url',+ );++ expect(+ parseGmailMessages({+ data: [+ {+ id: 'plain',+ payload: {+ parts: [+ { body: { data: html }, mimeType: 'text/html' },+ { body: { data: plain }, mimeType: 'text/plain' },+ ],+ },+ subject: 'Plain',+ },+ {+ id: 'html',+ payload: { body: { data: html }, mimeType: 'text/html' },+ subject: 'HTML',+ },+ ],+ }),+ ).toMatchObject([+ { bodyPreview: 'Plain <body> & useful', id: 'plain' },+ { bodyPreview: 'HTML fallback & useful', id: 'html' },+ ]);+ });++ it('limits the number of inspected candidates', () => {+ expect(+ parseGmailMessages({ data: [message('first'), message('second')] }, { maxCandidates: 1 }),+ ).toMatchObject([{ id: 'first' }]);+ });++ it('rejects unsupported recursive envelope shapes', () => {+ expect(+ parseGmailMessages({ response: { items: [message('unexpected-recursive-envelope')] } }),+ ).toBeUndefined();+ });+});diff --git a/packages/connector-data/src/gmail/message.ts b/packages/connector-data/src/gmail/message.tsnew file mode 100644index 00000000000..f9d06d5765d--- /dev/null+++ b/packages/connector-data/src/gmail/message.ts@@ -0,0 +1,240 @@+import { toRecord } from '@lobechat/utils/object';+import { htmlToText } from 'html-to-text';+import { z } from 'zod';++import {+ GMAIL_BODY_PREVIEW_MAX_LENGTH,+ GMAIL_DATE_MAX_LENGTH,+ GMAIL_EMAIL_SOURCE_MAX_LENGTH,+ GMAIL_LABEL_MAX_LENGTH,+ GMAIL_LABELS_MAX_COUNT,+ GMAIL_MESSAGE_ID_MAX_LENGTH,+ GMAIL_SNIPPET_MAX_LENGTH,+ GMAIL_SOURCE_URL_MAX_LENGTH,+ GMAIL_SUBJECT_MAX_LENGTH,+} from './constants';+import { clipGmailText, extractGmailEmail } from './normalize';+import type { GmailMessage } from './types';++const MAX_HEADERS = 50;+const MAX_MIME_CHILDREN = 16;+const MAX_MIME_DEPTH = 8;+const MAX_MIME_PARTS = 128;+const MAX_RAW_BODY_LENGTH = 32_000;+const MAX_RAW_ENCODED_BODY_LENGTH = 48_000;+const MAX_RESPONSE_RESULTS = 8;+const MAX_SEARCH_MESSAGE_CANDIDATES = 25;++const boundedString = (limit: number) => z.string().transform((value) => value.slice(0, limit));+const boundedLabels = z.preprocess(+ (value) => (Array.isArray(value) ? value.slice(0, GMAIL_LABELS_MAX_COUNT) : value),+ z.array(boundedString(GMAIL_LABEL_MAX_LENGTH + 1)),+);++const messageSchema = z.object({+ bodyHtml: boundedString(MAX_RAW_BODY_LENGTH).nullish(),+ bodyText: boundedString(MAX_RAW_BODY_LENGTH).nullish(),+ date: boundedString(GMAIL_DATE_MAX_LENGTH).nullish(),+ from: boundedString(GMAIL_EMAIL_SOURCE_MAX_LENGTH).nullish(),+ html: boundedString(MAX_RAW_BODY_LENGTH).nullish(),+ id: boundedString(GMAIL_MESSAGE_ID_MAX_LENGTH + 1).nullish(),+ internalDate: z.union([boundedString(64), z.number()]).nullish(),+ labelIds: boundedLabels.nullish(),+ labels: boundedLabels.nullish(),+ messageId: boundedString(GMAIL_MESSAGE_ID_MAX_LENGTH + 1).nullish(),+ messageText: boundedString(MAX_RAW_BODY_LENGTH).nullish(),+ messageTimestamp: z.union([boundedString(64), z.number()]).nullish(),+ messageUrl: boundedString(GMAIL_SOURCE_URL_MAX_LENGTH + 1).nullish(),+ payload: z.unknown().nullish(),+ preview: z+ .union([+ boundedString(GMAIL_BODY_PREVIEW_MAX_LENGTH + 1),+ z.object({ body: boundedString(GMAIL_BODY_PREVIEW_MAX_LENGTH + 1).nullish() }),+ ])+ .nullish(),+ sender: boundedString(GMAIL_EMAIL_SOURCE_MAX_LENGTH).nullish(),+ snippet: boundedString(GMAIL_SNIPPET_MAX_LENGTH + 1).nullish(),+ subject: boundedString(GMAIL_SUBJECT_MAX_LENGTH + 1).nullish(),+ text: boundedString(MAX_RAW_BODY_LENGTH).nullish(),+ threadId: boundedString(GMAIL_MESSAGE_ID_MAX_LENGTH + 1).nullish(),+ to: boundedString(GMAIL_EMAIL_SOURCE_MAX_LENGTH).nullish(),+});++const messageCollectionSchema = z.union([+ z.custom<unknown[]>(Array.isArray),+ z.object({ messages: z.custom<unknown[]>(Array.isArray) }).transform(({ messages }) => messages),+ z.object({ emails: z.custom<unknown[]>(Array.isArray) }).transform(({ emails }) => emails),+ z.object({ items: z.custom<unknown[]>(Array.isArray) }).transform(({ items }) => items),+]);+const executionDataSchema = z.union([+ z.object({ data: messageCollectionSchema }).transform(({ data }) => data),+ z.object({ data_preview: messageCollectionSchema }).transform(({ data_preview }) => data_preview),+]);+const resultExecutionSchema = z+ .object({ result: executionDataSchema })+ .transform(({ result }) => result);+const batchExecutionSchema = z.object({+ data: z.object({ results: z.custom<unknown[]>(Array.isArray) }),+});++const getHeader = (payload: unknown, name: string) => {+ const record = toRecord(payload);+ if (!record || !Array.isArray(record.headers)) return undefined;+ for (const value of record.headers.slice(0, MAX_HEADERS)) {+ const header = toRecord(value);+ if (!header || typeof header.name !== 'string' || typeof header.value !== 'string') continue;+ if (header.name.slice(0, 80).toLowerCase() !== name.toLowerCase()) continue;+ return header.value.slice(0, MAX_RAW_BODY_LENGTH);+ }+};++const decodeGmailBody = (payload: unknown) => {+ const queue: Array<{ depth: number; part: unknown }> = [{ depth: 0, part: payload }];+ let html: string | undefined;+ let root: string | undefined;+ let visited = 0;++ while (queue.length > 0 && visited < MAX_MIME_PARTS) {+ const current = queue.shift()!;+ const part = toRecord(current.part);+ if (!part) continue;+ visited += 1;+ const body = toRecord(part.body);+ const data =+ typeof body?.data === 'string' ? body.data.slice(0, MAX_RAW_ENCODED_BODY_LENGTH) : undefined;+ const mimeType =+ typeof part.mimeType === 'string' ? part.mimeType.slice(0, 80).toLowerCase() : undefined;++ if (data && mimeType === 'text/plain') {+ return Buffer.from(data, 'base64url').toString('utf8').slice(0, MAX_RAW_BODY_LENGTH);+ }+ if (data && mimeType === 'text/html' && !html) html = data;+ if (data && current.depth === 0) root = data;+ if (current.depth >= MAX_MIME_DEPTH || !Array.isArray(part.parts)) continue;+ for (const child of part.parts.slice(0, MAX_MIME_CHILDREN)) {+ queue.push({ depth: current.depth + 1, part: child });+ }+ }++ if (html) {+ const decoded = Buffer.from(html, 'base64url').toString('utf8').slice(0, MAX_RAW_BODY_LENGTH);+ return htmlToText(decoded, { wordwrap: false });+ }+ return root+ ? Buffer.from(root, 'base64url').toString('utf8').slice(0, MAX_RAW_BODY_LENGTH)+ : undefined;+};++const normalizeDate = (value: string | number | null | undefined) => {+ if (value === undefined || value === null) return undefined;+ if (typeof value === 'string' && Number.isNaN(Number(value))) {+ const date = new Date(value);+ return Number.isNaN(date.valueOf()) ? undefined : date.toISOString();+ }+ const milliseconds = Number(value);+ if (!Number.isFinite(milliseconds) || milliseconds < 0) return undefined;+ const date = new Date(milliseconds);+ return Number.isNaN(date.valueOf()) ? undefined : date.toISOString();+};++const normalizeMessage = (input: unknown): GmailMessage | undefined => {+ const parsed = messageSchema.safeParse(input);+ if (!parsed.success) return undefined;+ const rawId = parsed.data.id ?? parsed.data.messageId;+ if (!rawId) return undefined;+ const id = clipGmailText(rawId, GMAIL_MESSAGE_ID_MAX_LENGTH)!;+ const rawSender =+ parsed.data.sender ?? parsed.data.from ?? getHeader(parsed.data.payload, 'From');+ const rawRecipient = parsed.data.to ?? getHeader(parsed.data.payload, 'To');+ const subject = clipGmailText(+ parsed.data.subject ?? getHeader(parsed.data.payload, 'Subject') ?? '(No subject)',+ GMAIL_SUBJECT_MAX_LENGTH,+ )!;+ const htmlBody = parsed.data.bodyHtml ?? parsed.data.html;+ const preview =+ typeof parsed.data.preview === 'string' ? parsed.data.preview : parsed.data.preview?.body;+ const directBody = parsed.data.messageText ?? parsed.data.bodyText ?? parsed.data.text;+ const body =+ directBody ||+ (htmlBody+ ? htmlToText(htmlBody.slice(0, MAX_RAW_BODY_LENGTH), { wordwrap: false })+ : (decodeGmailBody(parsed.data.payload) ?? preview));++ if (!rawSender && subject === '(No subject)' && !body && !parsed.data.snippet) return undefined;++ return {+ bodyPreview: clipGmailText(body ?? undefined, GMAIL_BODY_PREVIEW_MAX_LENGTH),+ date: normalizeDate(+ parsed.data.messageTimestamp ??+ parsed.data.internalDate ??+ parsed.data.date ??+ getHeader(parsed.data.payload, 'Date'),+ ),+ id,+ labels: (parsed.data.labelIds ?? parsed.data.labels ?? []).reduce<string[]>((labels, label) => {+ const normalized = clipGmailText(label, GMAIL_LABEL_MAX_LENGTH);+ if (normalized) labels.push(normalized);+ return labels;+ }, []),+ recipient: extractGmailEmail(rawRecipient),+ sender: extractGmailEmail(rawSender),+ snippet: clipGmailText(parsed.data.snippet ?? undefined, GMAIL_SNIPPET_MAX_LENGTH),+ sourceUrl: clipGmailText(+ parsed.data.messageUrl ??+ (parsed.data.threadId ? `gmail:thread:${parsed.data.threadId}` : `gmail:message:${id}`),+ GMAIL_SOURCE_URL_MAX_LENGTH,+ ),+ subject,+ };+};++export interface ParseGmailMessagesOptions {+ maxCandidates?: number;+}++export const parseGmailMessages = (+ value: unknown,+ { maxCandidates = MAX_SEARCH_MESSAGE_CANDIDATES }: ParseGmailMessagesOptions = {},+): GmailMessage[] | undefined => {+ const direct = messageCollectionSchema.safeParse(value);+ const execution = direct.success ? undefined : executionDataSchema.safeParse(value);+ const result =+ direct.success || execution?.success ? undefined : resultExecutionSchema.safeParse(value);+ let messages = direct.success ? direct.data : execution?.success ? execution.data : result?.data;++ if (!messages) {+ const batch = batchExecutionSchema.safeParse(value);+ if (batch.success) {+ const resultLimit = Math.min(batch.data.data.results.length, MAX_RESPONSE_RESULTS);+ for (let index = 0; index < resultLimit; index += 1) {+ const response = executionDataSchema.safeParse(+ toRecord(batch.data.data.results[index])?.response,+ );+ if (response.success) {+ messages = response.data;+ break;+ }+ }+ }+ }++ if (!messages) return undefined;+ const limit = Math.min(Math.max(0, Math.floor(maxCandidates)), MAX_SEARCH_MESSAGE_CANDIDATES);+ const deduplicated = new Map<string, GmailMessage>();++ for (let index = 0; index < Math.min(messages.length, limit); index += 1) {+ const candidate = messages[index];+ const candidateRecord = toRecord(candidate);+ const rawCandidateId = candidateRecord?.id ?? candidateRecord?.messageId;+ const id =+ typeof rawCandidateId === 'string'+ ? rawCandidateId.slice(0, GMAIL_MESSAGE_ID_MAX_LENGTH)+ : undefined;+ if (id && deduplicated.has(id)) continue;+ const message = normalizeMessage(candidate);+ if (message && !deduplicated.has(message.id)) deduplicated.set(message.id, message);+ }++ if (messages.length > 0 && limit > 0 && deduplicated.size === 0) return undefined;+ return [...deduplicated.values()];+};diff --git a/packages/connector-data/src/gmail/normalize.ts b/packages/connector-data/src/gmail/normalize.tsnew file mode 100644index 00000000000..042fc4178cd--- /dev/null+++ b/packages/connector-data/src/gmail/normalize.ts@@ -0,0 +1,16 @@+import { GMAIL_EMAIL_MAX_LENGTH, GMAIL_EMAIL_SOURCE_MAX_LENGTH } from './constants';++export const clipGmailText = (value: string | undefined, limit: number) => {+ if (!value) return undefined;+ const overflowed = value.length > limit;+ const clean = value.slice(0, limit).replaceAll('\u0000', '').trim();+ if (!clean || !overflowed) return clean;+ return `${clean.trimEnd()}...`;+};++export const extractGmailEmail = (value: unknown) => {+ if (typeof value !== 'string') return undefined;+ const bounded = value.slice(0, GMAIL_EMAIL_SOURCE_MAX_LENGTH);+ const match = bounded.match(/<([^>]+)>/);+ return (match?.[1] ?? bounded).toLowerCase().trim().slice(0, GMAIL_EMAIL_MAX_LENGTH) || undefined;+};diff --git a/packages/connector-data/src/gmail/types.ts b/packages/connector-data/src/gmail/types.tsnew file mode 100644index 00000000000..a3ca147e4cb--- /dev/null+++ b/packages/connector-data/src/gmail/types.ts@@ -0,0 +1,17 @@+export interface GmailAccount {+ email?: string;+ externalAccountId: string;+ scopes: string[];+}++export interface GmailMessage {+ bodyPreview?: string;+ date?: string;+ id: string;+ labels: string[];+ recipient?: string;+ sender?: string;+ snippet?: string;+ sourceUrl?: string;+ subject: string;+}diff --git a/packages/connector-data/src/index.ts b/packages/connector-data/src/index.tsindex 1ed6574a7c6..155d99c1a15 100644--- a/packages/connector-data/src/index.ts+++ b/packages/connector-data/src/index.ts@@ -1,3 +1,2 @@export * from './errors';-export * from './github';export * from './retry';diff --git a/packages/connector-data/src/memo.ts b/packages/connector-data/src/memo.tsnew file mode 100644index 00000000000..ad6507cdb4d--- /dev/null+++ b/packages/connector-data/src/memo.ts@@ -0,0 +1,11 @@+export const createRecoverableMemo = <T>(load: () => Promise<T>) => {+ let promise: Promise<T> | undefined;++ return () => {+ promise ??= load().catch((error) => {+ promise = undefined;+ throw error;+ });+ return promise;+ };+};