@superdurable/connector-google-gmail 0.0.0-stage → 0.1.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,1214 @@
1
+ // src/models.ts
2
+ import { z } from "zod";
3
+ var ConnectorID = "gmail";
4
+ var ProviderID = "google";
5
+ var GoogleOAuthAuthMethodID = "google-oauth";
6
+ var WorkspaceDomainDelegationAuthMethodID = "workspace-domain-delegation";
7
+ var GetMessageInputSchema = z.strictObject({ messageId: z.string() });
8
+ var SendMessageInputSchema = z.strictObject({
9
+ to: z.array(z.string()),
10
+ subject: z.string(),
11
+ textBody: z.string(),
12
+ htmlBody: z.string().optional()
13
+ });
14
+ var ReplyToMessageInputSchema = z.strictObject({
15
+ messageId: z.string(),
16
+ textBody: z.string(),
17
+ htmlBody: z.string().optional()
18
+ });
19
+ var MessageSchema = z.strictObject({
20
+ messageId: z.string(),
21
+ threadId: z.string(),
22
+ rfcMessageId: z.string().optional(),
23
+ inReplyTo: z.string().optional(),
24
+ references: z.string().optional(),
25
+ from: z.string(),
26
+ replyTo: z.string().optional(),
27
+ to: z.array(z.string()).optional(),
28
+ subject: z.string(),
29
+ textBody: z.string().optional(),
30
+ htmlBody: z.string().optional(),
31
+ snippet: z.string().optional(),
32
+ receivedAt: z.iso.datetime({ offset: true }),
33
+ labelIds: z.array(z.string()).optional()
34
+ });
35
+ var SendMessageOutputSchema = z.strictObject({
36
+ sender: z.string(),
37
+ recipients: z.array(z.string()),
38
+ messageId: z.string(),
39
+ threadId: z.string()
40
+ });
41
+
42
+ // src/definitions.ts
43
+ var GetMessageBranch = { Read: "read", NotFound: "notFound", ProviderRejected: "providerRejected", InvalidResponse: "invalidResponse", Defect: "defect" };
44
+ var SendMessageBranch = { Sent: "sent", ProviderRejected: "providerRejected", Defect: "defect" };
45
+ var ReplyToMessageBranch = { Sent: "sent", ProviderRejected: "providerRejected", InvalidResponse: "invalidResponse", Defect: "defect" };
46
+ var GetMessageDefinition = {
47
+ operation: { connectorId: ConnectorID, operationId: "getMessage" },
48
+ branches: [
49
+ { id: "read", description: "The Gmail message was read." },
50
+ { id: "notFound", description: "The Gmail message does not exist.", optional: true },
51
+ { id: "providerRejected", description: "Gmail conclusively rejected the message query.", optional: true },
52
+ { id: "invalidResponse", description: "Gmail returned an invalid or oversized message response.", optional: true },
53
+ { id: "defect", description: "Local input, connection configuration, or connector definition is invalid.", optional: true }
54
+ ],
55
+ stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "async" }
56
+ };
57
+ var SendMessageDefinition = {
58
+ operation: { connectorId: ConnectorID, operationId: "sendMessage" },
59
+ branches: [
60
+ { id: "sent", description: "Gmail accepted the message; its message and thread IDs can be empty when an unusable accepted response has no Sent Mail match." },
61
+ { id: "providerRejected", description: "Gmail conclusively rejected the message.", optional: true },
62
+ { id: "defect", description: "Local input, connection configuration, or connector definition is invalid.", optional: true }
63
+ ],
64
+ stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "async", executeRetry: {
65
+ initialIntervalMs: 1e3,
66
+ backoffCoefficient: 2,
67
+ maximumIntervalMs: 3e4,
68
+ maximumAttempts: 5,
69
+ totalDurationMs: 12e4
70
+ } }
71
+ };
72
+ var ReplyToMessageDefinition = {
73
+ operation: { connectorId: ConnectorID, operationId: "replyToMessage" },
74
+ branches: [
75
+ { id: "sent", description: "Gmail accepted the reply; its message ID can be empty when an unusable accepted response has no Sent Mail match, while the requested thread ID remains." },
76
+ { id: "providerRejected", description: "Gmail conclusively rejected the reply.", optional: true },
77
+ { id: "invalidResponse", description: "Gmail returned an invalid or oversized source message response before sending the reply.", optional: true },
78
+ { id: "defect", description: "Local input, connection configuration, or connector definition is invalid.", optional: true }
79
+ ],
80
+ stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "async", executeRetry: {
81
+ initialIntervalMs: 1e3,
82
+ backoffCoefficient: 2,
83
+ maximumIntervalMs: 3e4,
84
+ maximumAttempts: 5,
85
+ totalDurationMs: 12e4
86
+ } }
87
+ };
88
+
89
+ // src/message.ts
90
+ import { createHash } from "crypto";
91
+ import { z as z2 } from "zod";
92
+ var GmailMessagePartSchema = z2.lazy(() => z2.object({
93
+ mimeType: z2.string().nullish(),
94
+ headers: z2.array(z2.object({ name: z2.string(), value: z2.string() })).nullish(),
95
+ body: z2.object({ data: z2.string().nullish() }).nullish(),
96
+ parts: z2.array(GmailMessagePartSchema).nullish()
97
+ }));
98
+ var GmailMessageResourceSchema = z2.object({
99
+ id: z2.string().nullish().transform((value) => value ?? ""),
100
+ threadId: z2.string().nullish().transform((value) => value ?? ""),
101
+ labelIds: z2.array(z2.string()).nullish(),
102
+ snippet: z2.string().nullish(),
103
+ internalDate: z2.string().nullish(),
104
+ payload: GmailMessagePartSchema.nullish()
105
+ });
106
+ function decodeGmailMessage(resource) {
107
+ if (!resource.id || !resource.threadId || !resource.internalDate || !/^\d+$/.test(resource.internalDate)) throw new TypeError("Gmail message identity or date is missing");
108
+ const receivedAt = new Date(Number(resource.internalDate));
109
+ if (!Number.isFinite(receivedAt.getTime())) throw new TypeError("Gmail message date is invalid");
110
+ const headers = new Map((resource.payload?.headers ?? []).map((header) => [header.name.toLowerCase(), header.value]));
111
+ const textBodies = [];
112
+ const htmlBodies = [];
113
+ visitGmailBody(resource.payload ?? {}, textBodies, htmlBodies);
114
+ const to = splitAddressHeader(headers.get("to") ?? "");
115
+ return {
116
+ messageId: resource.id,
117
+ threadId: resource.threadId,
118
+ rfcMessageId: headers.get("message-id") ?? "",
119
+ inReplyTo: headers.get("in-reply-to") ?? "",
120
+ references: headers.get("references") ?? "",
121
+ from: headers.get("from") ?? "",
122
+ replyTo: headers.get("reply-to") ?? "",
123
+ to,
124
+ subject: decodeRFC2047Header(headers.get("subject") ?? ""),
125
+ textBody: textBodies.join("\n"),
126
+ htmlBody: htmlBodies.join("\n"),
127
+ snippet: resource.snippet ?? "",
128
+ receivedAt: receivedAt.toISOString().replace(".000Z", "Z"),
129
+ labelIds: resource.labelIds ?? []
130
+ };
131
+ }
132
+ function visitGmailBody(part, textBodies, htmlBodies) {
133
+ if (part.body?.data) {
134
+ const encoded = part.body.data;
135
+ if (!/^[A-Za-z0-9_-]*$/.test(encoded) || encoded.length % 4 === 1) throw new TypeError("Gmail body is not raw base64url");
136
+ const decoded = Buffer.from(encoded, "base64url").toString("utf8");
137
+ if (part.mimeType?.toLowerCase() === "text/plain") textBodies.push(decoded);
138
+ if (part.mimeType?.toLowerCase() === "text/html") htmlBodies.push(decoded);
139
+ }
140
+ for (const child of part.parts ?? []) visitGmailBody(child, textBodies, htmlBodies);
141
+ }
142
+ function decodeRFC2047Header(value) {
143
+ return value.replace(/=\?UTF-8\?([BQ])\?([^?]+)\?=/gi, (encoded, encoding, body) => {
144
+ try {
145
+ const bytes = encoding.toUpperCase() === "B" ? Buffer.from(body, "base64") : Buffer.from(body.replaceAll("_", " ").replace(/=([0-9A-Fa-f]{2})/g, (_match, hex) => String.fromCharCode(parseInt(hex, 16))), "binary");
146
+ return bytes.toString("utf8");
147
+ } catch {
148
+ return encoded;
149
+ }
150
+ });
151
+ }
152
+ function splitAddressHeader(value) {
153
+ if (!value || /[\r\n]/.test(value)) return [];
154
+ const addresses = value.split(/,\s*(?=(?:[^"]*"[^"]*")*[^"]*$)/).map((address) => address.trim());
155
+ const canonical = [];
156
+ for (const address of addresses) {
157
+ const parsed = parseMailbox(address);
158
+ if (!parsed) return [];
159
+ canonical.push(formatMailbox(parsed));
160
+ }
161
+ return canonical;
162
+ }
163
+ function parseMailbox(value) {
164
+ if (Array.from(value).some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127)) return void 0;
165
+ const trimmed = value.trim();
166
+ const angle = /^(.*?)<([^<>]+)>$/.exec(trimmed);
167
+ if (!angle && /[<>]/.test(trimmed)) return void 0;
168
+ const address = angle?.[2]?.trim() ?? trimmed;
169
+ if (!/^[^<>\s,;@]+@[^<>\s,;@]+$/.test(address)) return void 0;
170
+ let display = angle?.[1]?.trim() ?? "";
171
+ if (display.startsWith('"')) {
172
+ if (!/^"(?:[^"\\]|\\.)*"$/.test(display)) return void 0;
173
+ display = display.slice(1, -1).replace(/\\(.)/g, "$1");
174
+ } else if (/[,:;<>@"\\()[\]]/.test(display)) return void 0;
175
+ return { display, address };
176
+ }
177
+ function formatMailbox(mailbox) {
178
+ if (!mailbox.display) return `<${mailbox.address}>`;
179
+ const display = /[^\x20-\x7E]/.test(mailbox.display) ? encodeSubject(mailbox.display).replace("=?UTF-8?Q?", "=?utf-8?q?") : `"${mailbox.display.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
180
+ return `${display} <${mailbox.address}>`;
181
+ }
182
+ function replyRecipient(message) {
183
+ const recipient = message.replyTo || message.from;
184
+ const parsed = recipient ? parseMailbox(recipient) : void 0;
185
+ if (!parsed) throw new TypeError("Gmail source sender is invalid");
186
+ return formatMailbox(parsed);
187
+ }
188
+ function validateSendInput(input, sender) {
189
+ if (!sender.trim() || !input.subject.trim() || /[\r\n]/.test(input.subject) || !input.textBody.trim() || input.to.length === 0) {
190
+ throw new TypeError("sender, recipients, subject, and text body are required");
191
+ }
192
+ const senderAddress = parseMailbox(sender);
193
+ if (!senderAddress || senderAddress.address.toLowerCase() !== sender.trim().toLowerCase()) throw new TypeError("authorized primary email is invalid");
194
+ const seen = /* @__PURE__ */ new Set();
195
+ const recipients = [];
196
+ for (const recipient of input.to) {
197
+ const parsed = parseMailbox(recipient);
198
+ if (!parsed) throw new TypeError("recipient email is invalid");
199
+ const canonical = parsed.address.toLowerCase();
200
+ if (seen.has(canonical)) throw new TypeError("recipient email is duplicated");
201
+ seen.add(canonical);
202
+ recipients.push(formatMailbox(parsed));
203
+ }
204
+ return recipients;
205
+ }
206
+ function rfcMessageIDAddress(idempotencyKey, runId, flowStartedAt) {
207
+ const runIdentity = `${runId}\0${Math.floor(flowStartedAt.getTime() / 1e3)}`;
208
+ return `${createHash("sha256").update(`${idempotencyKey}\0${runIdentity}`).digest("hex")}@dex.superdurable.dev`;
209
+ }
210
+ function buildMIMEMessage(callId, idempotencyKey, messageIdAddress, sender, recipients, subject, textBody, htmlBody = "", replyHeaders) {
211
+ if (/[\r\n]/.test(sender + subject + messageIdAddress + recipients.join("") + (replyHeaders?.inReplyTo ?? "") + (replyHeaders?.references ?? ""))) throw new TypeError("MIME header contains a newline");
212
+ const headers = [`From: ${sender}`, `To: ${recipients.join(", ")}`, `Subject: ${encodeSubject(subject)}`, `Message-ID: <${messageIdAddress}>`];
213
+ if (replyHeaders) headers.push(`In-Reply-To: ${replyHeaders.inReplyTo}`, `References: ${replyHeaders.references}`);
214
+ headers.push(`X-Dex-Call-ID: ${callId}`, "MIME-Version: 1.0");
215
+ if (!htmlBody) {
216
+ headers.push('Content-Type: text/plain; charset="UTF-8"', "Content-Transfer-Encoding: 8bit");
217
+ return Buffer.from(`${headers.join("\r\n")}\r
218
+ \r
219
+ ${toCRLF(textBody)}`, "utf8");
220
+ }
221
+ const boundary = `dex-${createHash("sha256").update(idempotencyKey).digest("hex").slice(0, 24)}`;
222
+ headers.push(`Content-Type: multipart/alternative; boundary="${boundary}"`);
223
+ const body = [
224
+ `--${boundary}\r
225
+ Content-Type: text/plain; charset="UTF-8"\r
226
+ \r
227
+ ${toCRLF(textBody)}\r
228
+ `,
229
+ `--${boundary}\r
230
+ Content-Type: text/html; charset="UTF-8"\r
231
+ \r
232
+ ${toCRLF(htmlBody)}\r
233
+ `,
234
+ `--${boundary}--\r
235
+ `
236
+ ].join("");
237
+ return Buffer.from(`${headers.join("\r\n")}\r
238
+ \r
239
+ ${body}`, "utf8");
240
+ }
241
+ function buildReplyMIMEMessage(callId, idempotencyKey, messageIdAddress, sender, source, input) {
242
+ const recipient = replyRecipient(source);
243
+ const subject = /^re:/i.test(source.subject.trim()) ? source.subject : `Re: ${source.subject}`;
244
+ return buildMIMEMessage(callId, idempotencyKey, messageIdAddress, sender, [recipient], subject, input.textBody, input.htmlBody, {
245
+ inReplyTo: source.rfcMessageId ?? "",
246
+ references: `${source.references ?? ""} ${source.rfcMessageId ?? ""}`.trim()
247
+ });
248
+ }
249
+ function toCRLF(value) {
250
+ return value.replace(/\r\n|\r/g, "\n").replaceAll("\n", "\r\n");
251
+ }
252
+ function encodeSubject(value) {
253
+ if (/^[\x20-\x7E]*$/.test(value)) return value;
254
+ const bytes = Buffer.from(value, "utf8");
255
+ const encoded = Array.from(bytes, (byte) => {
256
+ if (byte === 32) return "_";
257
+ if (byte >= 33 && byte <= 126 && byte !== 61 && byte !== 63 && byte !== 95) return String.fromCharCode(byte);
258
+ return `=${byte.toString(16).toUpperCase().padStart(2, "0")}`;
259
+ }).join("");
260
+ return `=?UTF-8?Q?${encoded}?=`;
261
+ }
262
+
263
+ // src/http.ts
264
+ import { resolveCredential, resolveCredentialAfterRejection } from "@superdurable/connectors-sdk";
265
+ import {
266
+ BodyTooLargeError,
267
+ isHeaderSafeCredential,
268
+ sendProviderRequest,
269
+ validateBaseURL
270
+ } from "@superdurable/connectors-sdk/providerhttp";
271
+ function gmailClientSettings(config = {}) {
272
+ const endpoint = validateBaseURL(config.endpoint ?? "https://gmail.googleapis.com/gmail/v1");
273
+ const maxResponseBytes = config.maxResponseBytes ?? 1048576;
274
+ const maxMessageBytes = config.maxMessageBytes ?? 10485760;
275
+ if (!Number.isSafeInteger(maxResponseBytes) || maxResponseBytes < 1 || !Number.isSafeInteger(maxMessageBytes) || maxMessageBytes < 1) {
276
+ throw new TypeError("Gmail response and message limits must be positive integers");
277
+ }
278
+ if (config.pollIntervalMs !== void 0 && (!Number.isSafeInteger(config.pollIntervalMs) || config.pollIntervalMs < 1e3)) throw new TypeError("Gmail poll interval is invalid");
279
+ if (config.pollPageSize !== void 0 && (!Number.isSafeInteger(config.pollPageSize) || config.pollPageSize < 1 || config.pollPageSize > 100)) throw new TypeError("Gmail poll page size is invalid");
280
+ return Object.freeze({ endpoint, maxResponseBytes, maxMessageBytes, addressPolicy: endpoint.startsWith("http://") ? "privateNetworkHTTP" : "publicHTTPS" });
281
+ }
282
+ var GmailCredentialError = class extends Error {
283
+ constructor() {
284
+ super("connection credentials are unavailable");
285
+ this.name = "GmailCredentialError";
286
+ }
287
+ };
288
+ var GmailHTTPClient = class {
289
+ #settings;
290
+ #credentials;
291
+ #refreshDriver;
292
+ #transport;
293
+ /** Inject settings, host-managed credential store, refresh driver, and optional test transport. */
294
+ constructor(config, credentials, refreshDriver, transport = sendProviderRequest) {
295
+ if (!credentials || !refreshDriver || !transport) throw new TypeError("Gmail credential provider, refresh driver, and transport are required");
296
+ this.#settings = gmailClientSettings(config);
297
+ this.#credentials = credentials;
298
+ this.#refreshDriver = refreshDriver;
299
+ this.#transport = transport;
300
+ }
301
+ /** Return validated request and message bounds. */
302
+ settings() {
303
+ return this.#settings;
304
+ }
305
+ /** Resolve a private token at call time; never put it in a receipt or Flow value. */
306
+ async resolveCredentials(call, signal) {
307
+ try {
308
+ const credentials = await resolveCredential(this.#credentials, call, this.#refreshDriver, signal);
309
+ validateCredentials(credentials);
310
+ return credentials;
311
+ } catch {
312
+ throw new GmailCredentialError();
313
+ }
314
+ }
315
+ /** Send one authenticated request, refreshing at most once after a 401. */
316
+ async request(call, credentials, method, pathAndQuery, body, signal) {
317
+ let currentCredentials = credentials;
318
+ for (let attempt = 0; attempt < 2; attempt++) {
319
+ const token = currentCredentials.accessToken.reveal();
320
+ if (!isHeaderSafeCredential(token)) throw new GmailCredentialError();
321
+ const request = {
322
+ url: `${this.#settings.endpoint}${pathAndQuery}`,
323
+ method,
324
+ headers: { Authorization: `Bearer ${token}`, ...body ? { "Content-Type": "application/json" } : {} },
325
+ maxResponseBytes: this.#settings.maxResponseBytes,
326
+ addressPolicy: this.#settings.addressPolicy,
327
+ timeoutMs: 25e3,
328
+ ...body ? { body } : {},
329
+ ...signal ? { signal } : {}
330
+ };
331
+ let response;
332
+ try {
333
+ response = await this.#transport(request);
334
+ } catch (error) {
335
+ if (!(error instanceof BodyTooLargeError) || error.status !== 401) throw error;
336
+ response = { status: 401, headers: error.headers ?? {}, body: new Uint8Array() };
337
+ }
338
+ if (response.status !== 401 || attempt !== 0 || !("resolveAfterRejection" in this.#credentials)) return { response, credentials: currentCredentials };
339
+ try {
340
+ const refreshed = await resolveCredentialAfterRejection(this.#credentials, call, this.#refreshDriver, signal);
341
+ validateCredentials(refreshed);
342
+ currentCredentials = refreshed;
343
+ } catch {
344
+ return { response, credentials: currentCredentials };
345
+ }
346
+ }
347
+ throw new GmailCredentialError();
348
+ }
349
+ };
350
+ function statusFailureKind(status) {
351
+ switch (status) {
352
+ case 401:
353
+ return "AUTHENTICATION";
354
+ case 403:
355
+ return "AUTHORIZATION";
356
+ case 404:
357
+ return "NOT_FOUND";
358
+ case 409:
359
+ return "CONFLICT";
360
+ default:
361
+ return "PROVIDER_REJECTION";
362
+ }
363
+ }
364
+ function gmailRetryAfterMs(headers) {
365
+ const value = headers["retry-after"] ?? headers["Retry-After"];
366
+ if (value === void 0) return 0;
367
+ const text = Array.isArray(value) ? value[0] : value;
368
+ if (!text || !/^\d+$/.test(text)) throw new TypeError("Gmail returned an invalid Retry-After header");
369
+ const seconds = Number(text);
370
+ if (!Number.isSafeInteger(seconds)) throw new TypeError("Gmail returned an invalid Retry-After header");
371
+ return seconds * 1e3;
372
+ }
373
+ function gmailRequestID(headers) {
374
+ const value = headers["x-goog-request-id"] ?? headers["X-Goog-Request-Id"] ?? headers["x-request-id"] ?? headers["X-Request-Id"];
375
+ return (Array.isArray(value) ? value[0] : value) ?? "";
376
+ }
377
+ function validateCredentials(credentials) {
378
+ const token = credentials.accessToken.reveal();
379
+ if (!token || !isHeaderSafeCredential(token)) throw new GmailCredentialError();
380
+ const mailbox = parseMailbox(credentials.primaryEmail);
381
+ if (!mailbox || mailbox.address.toLowerCase() !== credentials.primaryEmail.trim().toLowerCase()) throw new GmailCredentialError();
382
+ if (credentials.authMethodId && ![GoogleOAuthAuthMethodID, WorkspaceDomainDelegationAuthMethodID].includes(credentials.authMethodId)) throw new GmailCredentialError();
383
+ }
384
+
385
+ // src/provider.ts
386
+ import { z as z3 } from "zod";
387
+ var SentMessageSchema = z3.object({ id: z3.string().optional(), threadId: z3.string().optional() });
388
+ var SentSearchSchema = z3.object({ messages: z3.array(SentMessageSchema).nullish() });
389
+ var GmailProvider = class {
390
+ #http;
391
+ /** Bind the shared authenticated transport. */
392
+ constructor(http) {
393
+ if (!http) throw new TypeError("Gmail HTTP client is required");
394
+ this.#http = http;
395
+ }
396
+ /** Read one full or metadata message, returning the raw response on refusal or malformed JSON. */
397
+ async readMessage(call, credentials, messageId, format, signal) {
398
+ const query = new URLSearchParams({ format });
399
+ if (format === "metadata") {
400
+ for (const header of ["Message-ID", "In-Reply-To", "References", "From", "Reply-To", "To", "Subject"]) query.append("metadataHeaders", header);
401
+ }
402
+ const path = `/users/me/messages/${encodeURIComponent(messageId)}?${query.toString()}`;
403
+ const result = await this.#http.request(call, credentials, "GET", path, void 0, signal);
404
+ const { response } = result;
405
+ if (response.status < 200 || response.status >= 300) return result;
406
+ try {
407
+ const document = JSON.parse(Buffer.from(response.body).toString("utf8"));
408
+ return { ...result, resource: GmailMessageResourceSchema.parse(document) };
409
+ } catch {
410
+ return result;
411
+ }
412
+ }
413
+ /** Search Sent Mail once for the run-specific RFC Message-ID. */
414
+ async findSentMessage(call, credentials, messageIdAddress, signal) {
415
+ const query = new URLSearchParams();
416
+ query.set("includeSpamTrash", "true");
417
+ query.set("maxResults", "1");
418
+ query.set("q", `in:sent rfc822msgid:${messageIdAddress}`);
419
+ const { response } = await this.#http.request(call, credentials, "GET", `/users/me/messages?${query.toString()}`, void 0, signal);
420
+ if (response.status !== 200) throw new Error("Gmail sent-message lookup did not return a usable response");
421
+ let document;
422
+ try {
423
+ document = JSON.parse(Buffer.from(response.body).toString("utf8"));
424
+ } catch {
425
+ throw new Error("Gmail sent-message lookup returned an invalid response");
426
+ }
427
+ const parsed = SentSearchSchema.safeParse(document);
428
+ if (!parsed.success) throw new Error("Gmail sent-message lookup returned an invalid response");
429
+ const message = parsed.data.messages?.find((candidate) => candidate.id);
430
+ return message?.id ? { id: message.id, threadId: message.threadId ?? "" } : void 0;
431
+ }
432
+ /** Post one encoded Gmail messages.send request without redirects or transport replay. */
433
+ async sendMessage(call, credentials, rawMessage, threadId = "", signal) {
434
+ const request = Buffer.from(JSON.stringify({ raw: Buffer.from(rawMessage).toString("base64url"), ...threadId ? { threadId } : {} }), "utf8");
435
+ return this.#http.request(call, credentials, "POST", "/users/me/messages/send", request, signal);
436
+ }
437
+ };
438
+ function parseSentResponse(response) {
439
+ try {
440
+ const document = JSON.parse(Buffer.from(response.body).toString("utf8"));
441
+ const parsed = SentMessageSchema.safeParse(document);
442
+ return parsed.success && parsed.data.id ? { id: parsed.data.id, threadId: parsed.data.threadId ?? "" } : void 0;
443
+ } catch {
444
+ return void 0;
445
+ }
446
+ }
447
+
448
+ // src/refresh.ts
449
+ import { ReauthorizationRequiredError } from "@superdurable/connectors-sdk";
450
+ import {
451
+ hasAllScopes,
452
+ isRefreshRequired,
453
+ parseRSAPrivateKeyPEM,
454
+ signJWTBearerAssertion,
455
+ TokenEndpoint
456
+ } from "@superdurable/connectors-sdk/oauthtoken";
457
+ import { z as z4 } from "zod";
458
+ var GoogleOAuthTokenEndpoint = "https://oauth2.googleapis.com/token";
459
+ var RequiredGmailScopes = ["https://www.googleapis.com/auth/gmail.readonly", "https://www.googleapis.com/auth/gmail.send"];
460
+ var TerminalErrorCodes = ["invalid_grant", "invalid_client", "unauthorized_client"];
461
+ var ServiceAccountKeySchema = z4.object({ client_email: z4.string().min(1), private_key: z4.string().min(1), token_uri: z4.url() });
462
+ var GmailCredentialRefreshDriver = class {
463
+ #fetch;
464
+ #now;
465
+ /** Inject the token request transport and clock for deterministic verification. */
466
+ constructor(fetchImplementation = fetch, now = () => /* @__PURE__ */ new Date()) {
467
+ if (!fetchImplementation || !now) throw new TypeError("Gmail token transport and clock are required");
468
+ this.#fetch = fetchImplementation;
469
+ this.#now = now;
470
+ }
471
+ /** Refresh absent credentials or tokens whose expiry is within five minutes. */
472
+ refreshRequired(state) {
473
+ return isRefreshRequired(Boolean(state.credentials.accessToken.reveal()), state.expiresAt, state.now, "refresh");
474
+ }
475
+ /** Make one Google token exchange after the host admits and serializes refresh. */
476
+ async refresh(state, signal) {
477
+ const credentials = state.credentials;
478
+ if (!credentials.authMethodId || credentials.authMethodId === GoogleOAuthAuthMethodID) {
479
+ if (!credentials.oauthClientId || !credentials.oauthClientSecret || !credentials.refreshToken) throw new ReauthorizationRequiredError();
480
+ const token2 = await this.#tokenEndpoint(GoogleOAuthTokenEndpoint).exchangeRefreshToken({
481
+ id: credentials.oauthClientId,
482
+ secret: credentials.oauthClientSecret,
483
+ authenticationMethod: "client_secret_post"
484
+ }, credentials.refreshToken, signal);
485
+ this.#verifyScopes(token2.scope);
486
+ return {
487
+ credentials: { ...credentials, accessToken: token2.accessToken, refreshToken: token2.nextRefreshToken(credentials.refreshToken) },
488
+ expiresAt: new Date(this.#now().getTime() + token2.expiresInMs)
489
+ };
490
+ }
491
+ if (credentials.authMethodId !== WorkspaceDomainDelegationAuthMethodID) throw new ReauthorizationRequiredError();
492
+ let key;
493
+ try {
494
+ key = ServiceAccountKeySchema.parse(JSON.parse(credentials.serviceAccountKey?.reveal() ?? ""));
495
+ } catch {
496
+ throw new ReauthorizationRequiredError();
497
+ }
498
+ if (new URL(key.token_uri).protocol !== "https:" || !parseMailbox(credentials.delegatedUser ?? "")) throw new ReauthorizationRequiredError();
499
+ let assertion;
500
+ try {
501
+ assertion = signJWTBearerAssertion({
502
+ issuer: key.client_email,
503
+ subject: credentials.delegatedUser,
504
+ audience: key.token_uri,
505
+ scope: RequiredGmailScopes.join(" "),
506
+ issuedAt: this.#now(),
507
+ lifetimeMs: 36e5
508
+ }, parseRSAPrivateKeyPEM(key.private_key));
509
+ } catch {
510
+ throw new ReauthorizationRequiredError();
511
+ }
512
+ const token = await this.#tokenEndpoint(key.token_uri).exchangeJWTBearerAssertion(assertion, signal);
513
+ this.#verifyScopes(token.scope);
514
+ return {
515
+ credentials: { ...credentials, accessToken: token.accessToken, primaryEmail: credentials.delegatedUser ?? "" },
516
+ expiresAt: new Date(this.#now().getTime() + token.expiresInMs)
517
+ };
518
+ }
519
+ #tokenEndpoint(url) {
520
+ return new TokenEndpoint({ providerName: "Google", url, terminalErrorCodes: TerminalErrorCodes, fetch: this.#fetch });
521
+ }
522
+ #verifyScopes(scope) {
523
+ if (scope && !hasAllScopes(scope, RequiredGmailScopes)) throw new ReauthorizationRequiredError();
524
+ }
525
+ };
526
+
527
+ // src/send.ts
528
+ import {
529
+ newMutationBranch,
530
+ newMutationRetry,
531
+ zeroReceipt
532
+ } from "@superdurable/connectors-sdk";
533
+ import { AddressRefusal, BodyTooLargeError as BodyTooLargeError2, ProviderTransportError } from "@superdurable/connectors-sdk/providerhttp";
534
+ import { CheckpointError, InsufficientTimeError, newFence } from "@superdurable/connectors-sdk/singledispatch";
535
+ import { setTimeout as delay } from "timers/promises";
536
+ var SendMessageOutcomes = {
537
+ operationId: "sendMessage",
538
+ requestName: "send",
539
+ rejectionMessage: "Gmail rejected the message",
540
+ sentBranch: SendMessageBranch.Sent,
541
+ providerRejectedBranch: SendMessageBranch.ProviderRejected
542
+ };
543
+ var ReplyToMessageOutcomes = {
544
+ operationId: "replyToMessage",
545
+ requestName: "reply",
546
+ rejectionMessage: "Gmail rejected the reply",
547
+ sentBranch: ReplyToMessageBranch.Sent,
548
+ providerRejectedBranch: ReplyToMessageBranch.ProviderRejected
549
+ };
550
+ var GmailSendAttemptBudget = class {
551
+ /** Read-back cutoff in Unix milliseconds. */
552
+ attemptDeadline;
553
+ /** POST cutoff in Unix milliseconds. */
554
+ sendDeadline;
555
+ /** Minimum remaining POST window in milliseconds. */
556
+ minimumSendMs;
557
+ #parentSignal;
558
+ /** Bound an attempt by both Dex's actual deadline and the manifest's Execute timeout. */
559
+ constructor(parentSignal, dexDeadline, now = /* @__PURE__ */ new Date(), executeTimeoutMs = 3e4) {
560
+ const available = Math.min(executeTimeoutMs, dexDeadline ? dexDeadline.getTime() - now.getTime() : executeTimeoutMs);
561
+ this.attemptDeadline = now.getTime() + available * 5 / 6;
562
+ this.sendDeadline = now.getTime() + available * 7 / 12;
563
+ this.minimumSendMs = available / 10;
564
+ this.#parentSignal = parentSignal;
565
+ }
566
+ /** Bound a read before POST so at least one tenth of the attempt remains to send. */
567
+ preSendSignal() {
568
+ return this.#boundedSignal(this.sendDeadline - this.minimumSendMs);
569
+ }
570
+ /** Bound the POST, or return undefined when too little attempt time remains. */
571
+ sendSignal() {
572
+ return this.minimumSendMs > 0 && this.sendDeadline - Date.now() >= this.minimumSendMs ? this.#boundedSignal(this.sendDeadline) : void 0;
573
+ }
574
+ /** Bound read-back and other work before the Result write. */
575
+ attemptSignal() {
576
+ return this.#boundedSignal(this.attemptDeadline);
577
+ }
578
+ #boundedSignal(deadline) {
579
+ const remaining = Math.ceil(deadline - Date.now());
580
+ if (remaining <= 0) return AbortSignal.abort();
581
+ return AbortSignal.any([this.#parentSignal, AbortSignal.timeout(remaining)]);
582
+ }
583
+ };
584
+ var SendMessageOperation = class {
585
+ /** Inject the provider sender used by each Dex attempt. */
586
+ constructor(sender) {
587
+ this.sender = sender;
588
+ if (!sender) throw new TypeError("Gmail sender is required");
589
+ }
590
+ sender;
591
+ /** Return the immutable manifest operation definition. */
592
+ definition() {
593
+ return SendMessageDefinition;
594
+ }
595
+ /** Use the stable connector Call ID as the send correlation key. */
596
+ idempotencyKey(callId, input) {
597
+ void input;
598
+ return callId;
599
+ }
600
+ /** Classify a send using Dex's public current-attempt deadline. */
601
+ invoke(call, input) {
602
+ return this.sender.sendMessage(call, input, call.context.deadline);
603
+ }
604
+ };
605
+ var ReplyToMessageOperation = class {
606
+ /** Inject the provider sender used by each Dex attempt. */
607
+ constructor(sender) {
608
+ this.sender = sender;
609
+ if (!sender) throw new TypeError("Gmail sender is required");
610
+ }
611
+ sender;
612
+ /** Return the immutable manifest operation definition. */
613
+ definition() {
614
+ return ReplyToMessageDefinition;
615
+ }
616
+ /** Use the stable connector Call ID as the reply correlation key. */
617
+ idempotencyKey(callId, input) {
618
+ void input;
619
+ return callId;
620
+ }
621
+ /** Classify a reply using Dex's public current-attempt deadline. */
622
+ invoke(call, input) {
623
+ return this.sender.replyToMessage(call, input, call.context.deadline);
624
+ }
625
+ };
626
+ var GmailSender = class {
627
+ #http;
628
+ #provider;
629
+ #now;
630
+ /** Inject the shared authenticated provider client and observation clock. */
631
+ constructor(http, provider, now = () => /* @__PURE__ */ new Date()) {
632
+ if (!http || !provider || !now) throw new TypeError("Gmail send dependencies are required");
633
+ this.#http = http;
634
+ this.#provider = provider;
635
+ this.#now = now;
636
+ }
637
+ /** Send one new message under the Dex attempt deadline. */
638
+ async sendMessage(call, input, dexDeadline) {
639
+ if (call.context.attempt < 1) return defect("sendMessage", "LOCAL_DEFECT", "Dex Execute attempt number is invalid");
640
+ const fence = newFence(call, SendMessageDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4);
641
+ if (fence.decide().kind === "failClosed") return defect("sendMessage", "LOCAL_DEFECT", "Dex send checkpoint is unreadable");
642
+ const budget = new GmailSendAttemptBudget(call.context.cancellationSignal, dexDeadline);
643
+ if (!budget.sendSignal()) {
644
+ await recordPreSendRetry(fence);
645
+ return newMutationRetry(failure("sendMessage", "AVAILABILITY", "too little of the Execute attempt is left to send safely, so nothing was sent"));
646
+ }
647
+ let credentials;
648
+ try {
649
+ credentials = await this.#http.resolveCredentials(call, budget.attemptSignal());
650
+ } catch {
651
+ return defect("sendMessage", "AUTHENTICATION", "connection credentials are unavailable");
652
+ }
653
+ let recipients;
654
+ try {
655
+ if (!SendMessageInputSchema.safeParse(input).success) throw new TypeError();
656
+ recipients = validateSendInput(input, credentials.primaryEmail);
657
+ } catch (error) {
658
+ return defect("sendMessage", "VALIDATION", error instanceof TypeError && error.message ? error.message : "sender, recipients, subject, and text body are required");
659
+ }
660
+ let raw;
661
+ try {
662
+ raw = buildMIMEMessage(call.id, call.idempotencyKey ?? call.id, this.#messageID(call), credentials.primaryEmail, recipients, input.subject, input.textBody, input.htmlBody);
663
+ } catch {
664
+ return defect("sendMessage", "VALIDATION", "message could not be encoded");
665
+ }
666
+ if (raw.length > this.#http.settings().maxMessageBytes) return defect("sendMessage", "VALIDATION", "message exceeds configured size limit");
667
+ return this.#sendAndConfirm(call, fence, budget, credentials, SendMessageOutcomes, { raw, recipients, requestedThreadId: "", hasPreSendSearch: false });
668
+ }
669
+ /** Read the source then reply in its Gmail thread under the Dex attempt deadline. */
670
+ async replyToMessage(call, input, dexDeadline) {
671
+ if (call.context.attempt < 1) return defect("replyToMessage", "LOCAL_DEFECT", "Dex Execute attempt number is invalid");
672
+ const fence = newFence(call, ReplyToMessageDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4);
673
+ if (fence.decide().kind === "failClosed") return defect("replyToMessage", "LOCAL_DEFECT", "Dex send checkpoint is unreadable");
674
+ const budget = new GmailSendAttemptBudget(call.context.cancellationSignal, dexDeadline);
675
+ if (!budget.sendSignal()) {
676
+ await recordPreSendRetry(fence);
677
+ return newMutationRetry(failure("replyToMessage", "AVAILABILITY", "too little of the Execute attempt is left to send safely, so nothing was sent"));
678
+ }
679
+ let credentials;
680
+ try {
681
+ credentials = await this.#http.resolveCredentials(call, budget.attemptSignal());
682
+ } catch {
683
+ return defect("replyToMessage", "AUTHENTICATION", "connection credentials are unavailable");
684
+ }
685
+ if (!ReplyToMessageInputSchema.safeParse(input).success || !input.messageId.trim() || !input.textBody.trim()) return defect("replyToMessage", "VALIDATION", "message ID and text body are required");
686
+ const priorProviderId = fence.decide().marker?.providerId;
687
+ if (fence.decide().kind === "readBackRequired" && priorProviderId) {
688
+ return this.#sentMessage(
689
+ call,
690
+ budget,
691
+ credentials,
692
+ ReplyToMessageOutcomes,
693
+ { raw: new Uint8Array(), recipients: [], requestedThreadId: "", hasPreSendSearch: true },
694
+ { id: priorProviderId, threadId: "" },
695
+ this.#receipt(call, "", priorProviderId)
696
+ );
697
+ }
698
+ if (call.context.attempt > 1 || fence.decide().kind === "readBackRequired") {
699
+ try {
700
+ const found = await this.#provider.findSentMessage(call, credentials, this.#messageID(call), budget.preSendSignal());
701
+ if (found) return this.#sentMessage(call, budget, credentials, ReplyToMessageOutcomes, { raw: new Uint8Array(), recipients: [], requestedThreadId: "", hasPreSendSearch: true }, found, this.#receipt(call));
702
+ } catch {
703
+ await recordPreSendRetry(fence);
704
+ return newMutationRetry(failure("replyToMessage", "AVAILABILITY", "Gmail sent-mail search did not answer before the reply"));
705
+ }
706
+ if (fence.decide().kind === "readBackRequired") return newMutationRetry(failure("replyToMessage", "AVAILABILITY", "Gmail reply outcome is unknown; the sent-mail search found no message"));
707
+ }
708
+ let source;
709
+ try {
710
+ source = await this.#provider.readMessage(call, credentials, input.messageId, "metadata", budget.preSendSignal());
711
+ } catch (error) {
712
+ if (error instanceof GmailCredentialError) return defect("replyToMessage", "AUTHENTICATION", "connection credentials are unavailable");
713
+ const status = error instanceof BodyTooLargeError2 ? error.status ?? 0 : 0;
714
+ const headers = error instanceof BodyTooLargeError2 ? error.headers ?? {} : {};
715
+ const result = classifySourceFailure(status, headers, this.#receipt(call));
716
+ if (result.kind === "retry") await recordPreSendRetry(fence);
717
+ return result;
718
+ }
719
+ credentials = source.credentials;
720
+ if (!source.resource) {
721
+ const result = classifySourceFailure(source.response.status, source.response.headers, this.#receipt(call, gmailRequestID(source.response.headers), input.messageId));
722
+ if (result.kind === "retry") await recordPreSendRetry(fence);
723
+ return result;
724
+ }
725
+ let message;
726
+ try {
727
+ message = decodeGmailMessage(source.resource);
728
+ } catch {
729
+ return newMutationBranch(ReplyToMessageBranch.InvalidResponse, emptySend(), this.#receipt(call, gmailRequestID(source.response.headers), input.messageId), failure("replyToMessage", "PROTOCOL", "source message lacks reply metadata"));
730
+ }
731
+ if (!message.threadId || !message.rfcMessageId) return newMutationBranch(ReplyToMessageBranch.InvalidResponse, emptySend(), this.#receipt(call, gmailRequestID(source.response.headers), input.messageId), failure("replyToMessage", "PROTOCOL", "source message lacks reply metadata"));
732
+ let recipient;
733
+ try {
734
+ recipient = replyRecipient(message);
735
+ } catch {
736
+ return newMutationBranch(ReplyToMessageBranch.InvalidResponse, emptySend(), this.#receipt(call, gmailRequestID(source.response.headers), input.messageId), failure("replyToMessage", "PROTOCOL", "Gmail returned an invalid source sender"));
737
+ }
738
+ if (/[\r\n]/.test(message.subject + message.rfcMessageId + (message.references ?? ""))) return newMutationBranch(ReplyToMessageBranch.InvalidResponse, emptySend(), this.#receipt(call, gmailRequestID(source.response.headers), input.messageId), failure("replyToMessage", "PROTOCOL", "Gmail returned invalid source reply headers"));
739
+ let raw;
740
+ try {
741
+ raw = buildReplyMIMEMessage(call.id, call.idempotencyKey ?? call.id, this.#messageID(call), credentials.primaryEmail, message, input);
742
+ } catch {
743
+ return defect("replyToMessage", "VALIDATION", "reply could not be encoded within the configured limit");
744
+ }
745
+ if (raw.length > this.#http.settings().maxMessageBytes) return defect("replyToMessage", "VALIDATION", "reply could not be encoded within the configured limit");
746
+ return this.#sendAndConfirm(call, fence, budget, credentials, ReplyToMessageOutcomes, { raw, recipients: [recipient], requestedThreadId: message.threadId, hasPreSendSearch: call.context.attempt > 1 });
747
+ }
748
+ async #sendAndConfirm(call, fence, budget, credentials, operation, message) {
749
+ const priorProviderId = fence.decide().marker?.providerId;
750
+ if (fence.decide().kind === "readBackRequired" && priorProviderId) {
751
+ return this.#sentMessage(
752
+ call,
753
+ budget,
754
+ credentials,
755
+ operation,
756
+ message,
757
+ { id: priorProviderId, threadId: message.requestedThreadId },
758
+ this.#receipt(call, "", priorProviderId)
759
+ );
760
+ }
761
+ if ((call.context.attempt > 1 || fence.decide().kind === "readBackRequired") && !message.hasPreSendSearch) {
762
+ try {
763
+ const found = await this.#provider.findSentMessage(call, credentials, this.#messageID(call), budget.preSendSignal());
764
+ if (found) return this.#sentMessage(call, budget, credentials, operation, message, found, this.#receipt(call));
765
+ } catch {
766
+ await recordPreSendRetry(fence);
767
+ return newMutationRetry(failure(operation.operationId, "AVAILABILITY", `Gmail sent-mail search did not answer before the ${operation.requestName}`));
768
+ }
769
+ }
770
+ if (fence.decide().kind === "readBackRequired") return newMutationRetry(failure(operation.operationId, "AVAILABILITY", `Gmail ${operation.requestName} outcome is unknown; the sent-mail search found no message`));
771
+ let response;
772
+ try {
773
+ response = await fence.dispatch((signal) => this.#provider.sendMessage(call, credentials, message.raw, message.requestedThreadId, signal));
774
+ } catch (error) {
775
+ if (error instanceof InsufficientTimeError || error instanceof CheckpointError) return newMutationRetry(failure(operation.operationId, "AVAILABILITY", "too little of the Execute attempt is left to send safely, so nothing was sent"));
776
+ if (error instanceof ProviderTransportError && error.isProvablyNotSent || error instanceof AddressRefusal) {
777
+ await recordSafeResend(fence);
778
+ return newMutationRetry(failure(operation.operationId, "TRANSPORT", `Gmail ${operation.requestName} request was not dispatched`));
779
+ }
780
+ if (error instanceof BodyTooLargeError2 && error.status) return this.#classifySendStatus(call, fence, budget, credentials, operation, message, error.status, error.headers ?? {}, void 0);
781
+ return this.#confirmPossiblySent(call, budget, credentials, operation, message, "TRANSPORT", `Gmail ${operation.requestName} outcome is unknown`, this.#receipt(call));
782
+ }
783
+ const receipt = this.#receipt(call, gmailRequestID(response.response.headers));
784
+ const isAccepted = response.response.status >= 200 && response.response.status < 300;
785
+ const sentResponse = isAccepted ? parseSentResponse(response.response) : void 0;
786
+ if (sentResponse?.id) await recordProviderIdentity(fence, sentResponse.id);
787
+ return this.#classifySendStatus(call, fence, budget, response.credentials, operation, message, response.response.status, response.response.headers, sentResponse, receipt);
788
+ }
789
+ async #classifySendStatus(call, fence, budget, credentials, operation, message, status, headers, sentResponse, receipt = this.#receipt(call)) {
790
+ if (status === 429) {
791
+ await recordSafeResend(fence);
792
+ return retryAfterRefusal(operation.operationId, "RATE_LIMIT", `Gmail temporarily rejected the ${operation.requestName}`, headers);
793
+ }
794
+ if (status === 503) {
795
+ const lookup = await this.#pollSentMessage(call, budget, credentials);
796
+ if (lookup.sent) return this.#sentMessage(call, budget, credentials, operation, message, lookup.sent, receipt);
797
+ await recordSafeResend(fence);
798
+ return retryAfterRefusal(operation.operationId, "AVAILABILITY", `Gmail ${operation.requestName} is temporarily unavailable`, headers);
799
+ }
800
+ if (status >= 500) return this.#confirmPossiblySent(call, budget, credentials, operation, message, "AVAILABILITY", `Gmail ${operation.requestName} outcome is unknown`, receipt);
801
+ if (status < 200 || status >= 300) {
802
+ if (call.context.attempt > 1) {
803
+ try {
804
+ const found = await this.#provider.findSentMessage(call, credentials, this.#messageID(call), budget.attemptSignal());
805
+ if (found) return this.#sentMessage(call, budget, credentials, operation, message, found, receipt);
806
+ } catch {
807
+ }
808
+ }
809
+ return newMutationBranch(operation.providerRejectedBranch, emptySend(), receipt, failure(operation.operationId, statusFailureKind(status), operation.rejectionMessage));
810
+ }
811
+ if (!sentResponse) {
812
+ const lookup = await this.#pollSentMessage(call, budget, credentials);
813
+ return this.#sentMessage(call, budget, credentials, operation, message, lookup.sent ?? { id: "", threadId: message.requestedThreadId }, receipt);
814
+ }
815
+ return this.#sentMessage(call, budget, credentials, operation, message, sentResponse, receipt);
816
+ }
817
+ async #confirmPossiblySent(call, budget, credentials, operation, message, kind, reason, receipt) {
818
+ const lookup = await this.#pollSentMessage(call, budget, credentials);
819
+ if (lookup.sent) return this.#sentMessage(call, budget, credentials, operation, message, lookup.sent, receipt);
820
+ const suffix = lookup.hadError ? "the sent-mail search did not answer" : "the sent-mail search found no message";
821
+ return newMutationRetry(failure(operation.operationId, kind, `${reason}; ${suffix}`));
822
+ }
823
+ async #sentMessage(call, budget, credentials, operation, message, sent, receipt) {
824
+ let threadId = sent.threadId;
825
+ if (!threadId && sent.id) {
826
+ try {
827
+ const read = await this.#provider.readMessage(call, credentials, sent.id, "minimal", budget.attemptSignal());
828
+ threadId = read.resource?.threadId ?? message.requestedThreadId;
829
+ } catch {
830
+ threadId = message.requestedThreadId;
831
+ }
832
+ }
833
+ return newMutationBranch(operation.sentBranch, { sender: credentials.primaryEmail, recipients: message.recipients, messageId: sent.id, threadId }, { ...receipt, providerObjectId: sent.id });
834
+ }
835
+ async #pollSentMessage(call, budget, credentials) {
836
+ let hadError = false;
837
+ for (let lookup = 0; lookup < 4; lookup++) {
838
+ if (lookup > 0) {
839
+ try {
840
+ await delay(75 * 2 ** (lookup - 1), void 0, { signal: budget.attemptSignal() });
841
+ } catch {
842
+ return { hadError: true };
843
+ }
844
+ }
845
+ try {
846
+ const found = await this.#provider.findSentMessage(call, credentials, this.#messageID(call), budget.attemptSignal());
847
+ if (found) return { sent: found, hadError: false };
848
+ hadError = false;
849
+ } catch {
850
+ hadError = true;
851
+ }
852
+ if (Date.now() >= budget.attemptDeadline || call.context.cancellationSignal.aborted) break;
853
+ }
854
+ return { hadError };
855
+ }
856
+ #messageID(call) {
857
+ return rfcMessageIDAddress(call.idempotencyKey ?? call.id, call.context.runId, call.context.flowStartedAt);
858
+ }
859
+ #receipt(call, requestId = "", objectId = "") {
860
+ return { callId: call.id, ...call.idempotencyKey ? { idempotencyKey: call.idempotencyKey } : {}, provider: "gmail", providerObjectId: objectId, providerRequestId: requestId, observedAt: this.#now().toISOString() };
861
+ }
862
+ };
863
+ function failure(operation, kind, message) {
864
+ return { kind, provider: "gmail", operation, message };
865
+ }
866
+ async function recordPreSendRetry(fence) {
867
+ if (fence.decide().kind !== "sendAllowed") return;
868
+ try {
869
+ await fence.recordNotSent();
870
+ } catch {
871
+ }
872
+ }
873
+ async function recordSafeResend(fence) {
874
+ try {
875
+ await fence.recordCanResend();
876
+ } catch {
877
+ }
878
+ }
879
+ async function recordProviderIdentity(fence, providerId) {
880
+ try {
881
+ await fence.recordProviderId(providerId);
882
+ } catch {
883
+ }
884
+ }
885
+ function emptySend() {
886
+ return { sender: "", recipients: [], messageId: "", threadId: "" };
887
+ }
888
+ function defect(operation, kind, message) {
889
+ return newMutationBranch("defect", emptySend(), zeroReceipt(), failure(operation, kind, message));
890
+ }
891
+ function retryAfterRefusal(operation, kind, message, headers) {
892
+ try {
893
+ return newMutationRetry(failure(operation, kind, message), gmailRetryAfterMs(headers));
894
+ } catch {
895
+ return newMutationRetry(failure(operation, "PROTOCOL", "Gmail returned an invalid Retry-After header"));
896
+ }
897
+ }
898
+ function classifySourceFailure(status, headers, receipt) {
899
+ if (status === 0 || status === 429 || status >= 500) return retryAfterRefusal("replyToMessage", "AVAILABILITY", "Gmail source message is temporarily unavailable", headers);
900
+ if (status >= 200 && status < 300) return newMutationBranch(ReplyToMessageBranch.InvalidResponse, emptySend(), receipt, failure("replyToMessage", "PROTOCOL", "Gmail returned an invalid source message response"));
901
+ return newMutationBranch(ReplyToMessageBranch.ProviderRejected, emptySend(), receipt, failure("replyToMessage", statusFailureKind(status), "Gmail rejected the source message lookup"));
902
+ }
903
+
904
+ // src/client.ts
905
+ import {
906
+ newQueryBranch,
907
+ newQueryRetry,
908
+ zeroReceipt as zeroReceipt2
909
+ } from "@superdurable/connectors-sdk";
910
+ import { BodyTooLargeError as BodyTooLargeError3 } from "@superdurable/connectors-sdk/providerhttp";
911
+ var GmailClient = class {
912
+ #http;
913
+ #provider;
914
+ #sender;
915
+ #now;
916
+ /** Validate settings and inject a host-owned credential source. */
917
+ constructor(config, credentials, options = {}) {
918
+ this.#http = new GmailHTTPClient(config, credentials, options.refreshDriver ?? new GmailCredentialRefreshDriver(), options.transport);
919
+ this.#provider = new GmailProvider(this.#http);
920
+ this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
921
+ this.#sender = new GmailSender(this.#http, this.#provider, this.#now);
922
+ }
923
+ /** Return the getMessage Query bound to this connection. */
924
+ getMessage() {
925
+ return new GetMessageOperation(this.#http, this.#provider, this.#now);
926
+ }
927
+ /** Return the sendMessage Mutation bound to this connection. */
928
+ sendMessage() {
929
+ return new SendMessageOperation(this.#sender);
930
+ }
931
+ /** Return the replyToMessage Mutation bound to this connection. */
932
+ replyToMessage() {
933
+ return new ReplyToMessageOperation(this.#sender);
934
+ }
935
+ };
936
+ var GetMessageOperation = class {
937
+ #http;
938
+ #provider;
939
+ #now;
940
+ /** Inject authenticated transport and observation clock. */
941
+ constructor(http, provider, now) {
942
+ if (!http || !provider || !now) throw new TypeError("Gmail query dependencies are required");
943
+ this.#http = http;
944
+ this.#provider = provider;
945
+ this.#now = now;
946
+ }
947
+ /** Return the immutable manifest operation definition. */
948
+ definition() {
949
+ return GetMessageDefinition;
950
+ }
951
+ /** Classify one Gmail message read as a branch or safe retry. */
952
+ async invoke(call, input) {
953
+ if (!GetMessageInputSchema.safeParse(input).success || !input.messageId.trim()) {
954
+ return newQueryBranch(GetMessageBranch.Defect, emptyMessage(), zeroReceipt2(), gmailFailure("getMessage", "VALIDATION", "message ID is required"));
955
+ }
956
+ let credentials;
957
+ try {
958
+ credentials = await this.#http.resolveCredentials(call, call.context.cancellationSignal);
959
+ } catch {
960
+ return newQueryBranch(GetMessageBranch.Defect, emptyMessage(), zeroReceipt2(), gmailFailure("getMessage", "AUTHENTICATION", "connection credentials are unavailable"));
961
+ }
962
+ let result;
963
+ try {
964
+ result = await this.#provider.readMessage(call, credentials, input.messageId, "full", call.context.cancellationSignal);
965
+ } catch (error) {
966
+ if (error instanceof GmailCredentialError) return newQueryBranch(GetMessageBranch.Defect, emptyMessage(), zeroReceipt2(), gmailFailure("getMessage", "AUTHENTICATION", "connection credentials are unavailable"));
967
+ if (error instanceof BodyTooLargeError3 && error.status && error.status >= 200 && error.status < 300) {
968
+ return newQueryBranch(GetMessageBranch.InvalidResponse, emptyMessage(), zeroReceipt2(), gmailFailure("getMessage", "PROTOCOL", "Gmail returned an invalid or oversized message response"));
969
+ }
970
+ const status = error instanceof BodyTooLargeError3 ? error.status ?? 0 : 0;
971
+ const headers = error instanceof BodyTooLargeError3 ? error.headers ?? {} : {};
972
+ return classifyReadFailure(status, headers);
973
+ }
974
+ if (!result.resource) return classifyReadFailure(result.response.status, result.response.headers);
975
+ let message;
976
+ try {
977
+ message = decodeGmailMessage(result.resource);
978
+ } catch {
979
+ return newQueryBranch(GetMessageBranch.InvalidResponse, emptyMessage(), receiptFor(call, this.#now(), gmailRequestID(result.response.headers), input.messageId), gmailFailure("getMessage", "PROTOCOL", "Gmail returned an invalid message"));
980
+ }
981
+ return newQueryBranch(GetMessageBranch.Read, message, {
982
+ provider: "gmail",
983
+ providerObjectId: message.messageId,
984
+ providerRequestId: gmailRequestID(result.response.headers),
985
+ observedAt: this.#now().toISOString()
986
+ });
987
+ }
988
+ };
989
+ function gmailFailure(operation, kind, message) {
990
+ return { kind, provider: "gmail", operation, message };
991
+ }
992
+ function receiptFor(call, observedAt, requestId = "", objectId = "") {
993
+ return {
994
+ callId: call.id,
995
+ ...call.idempotencyKey ? { idempotencyKey: call.idempotencyKey } : {},
996
+ provider: "gmail",
997
+ providerObjectId: objectId,
998
+ providerRequestId: requestId,
999
+ observedAt: observedAt.toISOString()
1000
+ };
1001
+ }
1002
+ function emptyMessage() {
1003
+ return { messageId: "", threadId: "", from: "", subject: "", receivedAt: "0001-01-01T00:00:00Z" };
1004
+ }
1005
+ function classifyReadFailure(status, headers) {
1006
+ if (status === 429 || status >= 500 || status === 0) {
1007
+ let retryAfterMs;
1008
+ try {
1009
+ retryAfterMs = gmailRetryAfterMs(headers);
1010
+ } catch {
1011
+ return newQueryRetry(gmailFailure("getMessage", "PROTOCOL", "Gmail returned an invalid Retry-After header"));
1012
+ }
1013
+ return newQueryRetry(gmailFailure("getMessage", "AVAILABILITY", "Gmail message is temporarily unavailable"), retryAfterMs);
1014
+ }
1015
+ if (status === 404) return newQueryBranch(GetMessageBranch.NotFound, emptyMessage(), zeroReceipt2());
1016
+ if (status >= 200 && status < 300) {
1017
+ return newQueryBranch(GetMessageBranch.InvalidResponse, emptyMessage(), zeroReceipt2(), gmailFailure("getMessage", "PROTOCOL", "Gmail returned an invalid or oversized message response"));
1018
+ }
1019
+ return newQueryBranch(GetMessageBranch.ProviderRejected, emptyMessage(), zeroReceipt2(), gmailFailure("getMessage", statusFailureKind(status), "Gmail message lookup failed"));
1020
+ }
1021
+
1022
+ // src/connection.ts
1023
+ import { ConnectionRefSchema } from "@superdurable/connectors-sdk";
1024
+ var GmailConnection = class {
1025
+ /** Stable logical credential reference. */
1026
+ reference;
1027
+ /** Provider or mock operation implementations. */
1028
+ operations;
1029
+ /** Bind operation implementations to a static named Google connection. */
1030
+ constructor(operations, reference) {
1031
+ if (!operations) throw new TypeError("Gmail connector operations are required");
1032
+ this.reference = ConnectionRefSchema.parse(reference);
1033
+ if (this.reference.provider !== "google") throw new TypeError("Gmail connection provider must be google");
1034
+ this.operations = operations;
1035
+ }
1036
+ };
1037
+
1038
+ // src/project.ts
1039
+ import { ConnectionRefSchema as ConnectionRefSchema2 } from "@superdurable/connectors-sdk";
1040
+ import { newRefreshingCredentialProvider } from "@superdurable/connectors-sdk/projectconfig";
1041
+ import { z as z6 } from "zod";
1042
+
1043
+ // src/credential_codec.ts
1044
+ import { SecretString } from "@superdurable/connectors-sdk";
1045
+ import { z as z5 } from "zod";
1046
+ var StoredCredentialsSchema = z5.object({
1047
+ auth_method: z5.string().optional(),
1048
+ oauth_client_id: z5.string().optional(),
1049
+ oauth_client_secret: z5.string().optional(),
1050
+ access_token: z5.string().optional(),
1051
+ refresh_token: z5.string().optional(),
1052
+ primary_email: z5.string().optional(),
1053
+ service_account_key: z5.string().optional(),
1054
+ delegated_user: z5.string().optional()
1055
+ });
1056
+ function decodeGmailCredentials(value) {
1057
+ return decodeCredentialFields(value, false);
1058
+ }
1059
+ function decodeGmailSharedCredentials(value) {
1060
+ return decodeCredentialFields(value, true);
1061
+ }
1062
+ function encodeGmailCredentials(credentials) {
1063
+ const fields = { auth_method: credentials.authMethodId ?? GoogleOAuthAuthMethodID };
1064
+ for (const [name, value] of [
1065
+ ["oauth_client_id", credentials.oauthClientId],
1066
+ ["oauth_client_secret", credentials.oauthClientSecret?.reveal()],
1067
+ ["access_token", credentials.accessToken.reveal()],
1068
+ ["refresh_token", credentials.refreshToken?.reveal()],
1069
+ ["primary_email", credentials.primaryEmail],
1070
+ ["service_account_key", credentials.serviceAccountKey?.reveal()],
1071
+ ["delegated_user", credentials.delegatedUser]
1072
+ ]) if (value) fields[name] = value;
1073
+ return fields;
1074
+ }
1075
+ function decodeCredentialFields(value, isShared) {
1076
+ const fields = StoredCredentialsSchema.safeParse(value);
1077
+ if (!fields.success) throw new TypeError("Gmail credential fields are invalid");
1078
+ const stored = fields.data;
1079
+ const credentials = {
1080
+ authMethodId: stored.auth_method || GoogleOAuthAuthMethodID,
1081
+ oauthClientId: stored.oauth_client_id ?? "",
1082
+ oauthClientSecret: new SecretString(stored.oauth_client_secret ?? ""),
1083
+ accessToken: new SecretString(stored.access_token ?? ""),
1084
+ refreshToken: new SecretString(stored.refresh_token ?? ""),
1085
+ primaryEmail: stored.primary_email ?? "",
1086
+ serviceAccountKey: new SecretString(stored.service_account_key ?? ""),
1087
+ delegatedUser: stored.delegated_user ?? ""
1088
+ };
1089
+ if (credentials.authMethodId === GoogleOAuthAuthMethodID) {
1090
+ if (!credentials.oauthClientId || !credentials.primaryEmail || !isShared && (!credentials.oauthClientSecret?.reveal() || !credentials.refreshToken?.reveal()) || !credentials.accessToken.reveal()) {
1091
+ throw new TypeError("Gmail OAuth connection credentials are incomplete");
1092
+ }
1093
+ } else if (credentials.authMethodId === WorkspaceDomainDelegationAuthMethodID) {
1094
+ if (!credentials.delegatedUser || (isShared ? !credentials.accessToken.reveal() : !credentials.serviceAccountKey?.reveal())) {
1095
+ throw new TypeError("Gmail Workspace connection credentials are incomplete");
1096
+ }
1097
+ } else throw new TypeError("Gmail authorization method is invalid");
1098
+ return credentials;
1099
+ }
1100
+
1101
+ // src/project.ts
1102
+ var ProjectGmailConfigurationSchema = z6.object({
1103
+ endpoint: z6.string().optional(),
1104
+ maxResponseBytes: z6.number().int().safe().optional(),
1105
+ maxMessageBytes: z6.number().int().safe().optional(),
1106
+ pollInterval: z6.number().int().safe().optional(),
1107
+ pollPageSize: z6.number().int().safe().optional()
1108
+ });
1109
+ function newProjectConnection(project, connectionName, options = {}) {
1110
+ return new GmailConnection(newProjectGmailClient(project, connectionName, options), { provider: ProviderID, name: connectionName });
1111
+ }
1112
+ function newProjectGmailClient(project, connectionName, options = {}) {
1113
+ if (!project) throw new TypeError("Gmail connection requires the loaded project configuration");
1114
+ ConnectionRefSchema2.parse({ provider: ProviderID, name: connectionName });
1115
+ const entry = project.configuration.connections.find((connection) => connection.connectorId === ConnectorID && connection.connectionName === connectionName);
1116
+ if (!entry) throw new TypeError("Gmail project connection is not configured");
1117
+ if (entry.provider !== ProviderID) throw new TypeError("Gmail project connection provider differs from the manifest");
1118
+ const fields = ProjectGmailConfigurationSchema.parse(entry.configuration);
1119
+ const config = {
1120
+ ...fields.endpoint ? { endpoint: fields.endpoint } : {},
1121
+ ...fields.maxResponseBytes ? { maxResponseBytes: fields.maxResponseBytes } : {},
1122
+ ...fields.maxMessageBytes ? { maxMessageBytes: fields.maxMessageBytes } : {},
1123
+ ...fields.pollInterval ? { pollIntervalMs: Math.ceil(fields.pollInterval / 1e6) } : {},
1124
+ ...fields.pollPageSize ? { pollPageSize: fields.pollPageSize } : {}
1125
+ };
1126
+ const provider = newRefreshingCredentialProvider(project.connections, { connectorId: ConnectorID, connectionName }, decodeGmailCredentials, encodeGmailCredentials, decodeGmailSharedCredentials);
1127
+ return new GmailClient(config, provider, options);
1128
+ }
1129
+
1130
+ // src/steps.ts
1131
+ import { newMutationStep, newQueryStep, goToBranch } from "@superdurable/connectors-sdk";
1132
+ function newGetMessageStep(configuration) {
1133
+ const { connectionName, connection, read, notFound, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
1134
+ validateNamedConnection(connectionName, connection);
1135
+ return newQueryStep({ ...stepConfiguration, connection: connection.reference, operation: connection.operations.getMessage(), branches: [
1136
+ goToBranch("read", read),
1137
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
1138
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
1139
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
1140
+ ...defect2 ? [goToBranch("defect", defect2)] : []
1141
+ ] });
1142
+ }
1143
+ function newSendMessageStep(configuration) {
1144
+ const { connectionName, connection, sent, providerRejected, defect: defect2, ...stepConfiguration } = configuration;
1145
+ validateNamedConnection(connectionName, connection);
1146
+ return newMutationStep({ ...stepConfiguration, connection: connection.reference, operation: connection.operations.sendMessage(), branches: [
1147
+ goToBranch("sent", sent),
1148
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
1149
+ ...defect2 ? [goToBranch("defect", defect2)] : []
1150
+ ] });
1151
+ }
1152
+ function newReplyToMessageStep(configuration) {
1153
+ const { connectionName, connection, sent, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
1154
+ validateNamedConnection(connectionName, connection);
1155
+ return newMutationStep({ ...stepConfiguration, connection: connection.reference, operation: connection.operations.replyToMessage(), branches: [
1156
+ goToBranch("sent", sent),
1157
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
1158
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
1159
+ ...defect2 ? [goToBranch("defect", defect2)] : []
1160
+ ] });
1161
+ }
1162
+ function validateNamedConnection(connectionName, connection) {
1163
+ if (!(connection instanceof GmailConnection) || !connectionName || connection.reference.name !== connectionName) {
1164
+ throw new TypeError("Gmail Step connection name must match its typed connection");
1165
+ }
1166
+ }
1167
+
1168
+ export {
1169
+ ConnectorID,
1170
+ ProviderID,
1171
+ GoogleOAuthAuthMethodID,
1172
+ WorkspaceDomainDelegationAuthMethodID,
1173
+ GetMessageInputSchema,
1174
+ SendMessageInputSchema,
1175
+ ReplyToMessageInputSchema,
1176
+ MessageSchema,
1177
+ SendMessageOutputSchema,
1178
+ GetMessageBranch,
1179
+ SendMessageBranch,
1180
+ ReplyToMessageBranch,
1181
+ GetMessageDefinition,
1182
+ SendMessageDefinition,
1183
+ ReplyToMessageDefinition,
1184
+ GmailMessageResourceSchema,
1185
+ decodeGmailMessage,
1186
+ parseMailbox,
1187
+ replyRecipient,
1188
+ validateSendInput,
1189
+ rfcMessageIDAddress,
1190
+ buildMIMEMessage,
1191
+ buildReplyMIMEMessage,
1192
+ gmailClientSettings,
1193
+ GmailCredentialError,
1194
+ GmailHTTPClient,
1195
+ statusFailureKind,
1196
+ gmailRetryAfterMs,
1197
+ gmailRequestID,
1198
+ GmailProvider,
1199
+ parseSentResponse,
1200
+ GmailCredentialRefreshDriver,
1201
+ SendMessageOperation,
1202
+ ReplyToMessageOperation,
1203
+ GmailClient,
1204
+ GetMessageOperation,
1205
+ gmailFailure,
1206
+ receiptFor,
1207
+ emptyMessage,
1208
+ GmailConnection,
1209
+ newProjectConnection,
1210
+ newProjectGmailClient,
1211
+ newGetMessageStep,
1212
+ newSendMessageStep,
1213
+ newReplyToMessageStep
1214
+ };