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