@superdurable/connector-google-gmail 0.2.2 → 0.4.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 CHANGED
@@ -33,8 +33,15 @@ __export(index_exports, {
33
33
  GmailMessageResourceSchema: () => GmailMessageResourceSchema,
34
34
  GmailProvider: () => GmailProvider,
35
35
  GoogleOAuthAuthMethodID: () => GoogleOAuthAuthMethodID,
36
+ MessageEventSchema: () => MessageEventSchema,
37
+ MessageMatcherSchema: () => MessageMatcherSchema,
38
+ MessageReceivedTriggerConfigurationSchema: () => MessageReceivedTriggerConfigurationSchema,
39
+ MessageReceivedTriggerDefinition: () => MessageReceivedTriggerDefinition,
36
40
  MessageSchema: () => MessageSchema,
41
+ MessageTriggerRunner: () => MessageTriggerRunner,
37
42
  ProviderID: () => ProviderID,
43
+ ReplyReceivedTriggerConfigurationSchema: () => ReplyReceivedTriggerConfigurationSchema,
44
+ ReplyReceivedTriggerDefinition: () => ReplyReceivedTriggerDefinition,
38
45
  ReplyToMessageBranch: () => ReplyToMessageBranch,
39
46
  ReplyToMessageDefinition: () => ReplyToMessageDefinition,
40
47
  ReplyToMessageInputSchema: () => ReplyToMessageInputSchema,
@@ -44,18 +51,30 @@ __export(index_exports, {
44
51
  SendMessageInputSchema: () => SendMessageInputSchema2,
45
52
  SendMessageOperation: () => SendMessageOperation,
46
53
  SendMessageOutputSchema: () => SendMessageOutputSchema2,
54
+ UIEmailListInputPortEmails: () => UIEmailListInputPortEmails,
55
+ UISearchQueryInputPortQuery: () => UISearchQueryInputPortQuery,
56
+ UITextInputPortText: () => UITextInputPortText,
57
+ UIUnitEmailListInput: () => UIUnitEmailListInput,
58
+ UIUnitSearchQueryInput: () => UIUnitSearchQueryInput,
59
+ UIUnitTextInput: () => UIUnitTextInput,
47
60
  WorkspaceDomainDelegationAuthMethodID: () => WorkspaceDomainDelegationAuthMethodID,
48
61
  buildMIMEMessage: () => buildMIMEMessage,
49
62
  buildReplyMIMEMessage: () => buildReplyMIMEMessage,
50
63
  decodeGmailMessage: () => decodeGmailMessage,
64
+ defineMessageReceivedTriggerBinding: () => defineMessageReceivedTriggerBinding,
65
+ defineReplyReceivedTriggerBinding: () => defineReplyReceivedTriggerBinding,
51
66
  emptyMessage: () => emptyMessage,
52
67
  gmailClientSettings: () => gmailClientSettings,
53
68
  gmailFailure: () => gmailFailure,
54
69
  gmailRequestID: () => gmailRequestID,
55
70
  gmailRetryAfterMs: () => gmailRetryAfterMs,
56
71
  newGetMessageStep: () => newGetMessageStep2,
72
+ newMessageReceivedTrigger: () => newMessageReceivedTrigger,
73
+ newMessageTriggerRunner: () => newMessageTriggerRunner,
57
74
  newProjectConnection: () => newProjectConnection,
58
75
  newProjectGmailClient: () => newProjectGmailClient,
76
+ newProjectMessageTriggerRunner: () => newProjectMessageTriggerRunner,
77
+ newReplyReceivedTrigger: () => newReplyReceivedTrigger,
59
78
  newReplyToMessageStep: () => newReplyToMessageStep2,
60
79
  newSendMessageStep: () => newSendMessageStep2,
61
80
  parseMailbox: () => parseMailbox,
@@ -276,7 +295,9 @@ var SendMessageDefinition = {
276
295
  { id: "providerRejected", description: "Gmail conclusively rejected the message.", optional: true },
277
296
  { id: "defect", description: "Local input, connection configuration, or connector definition is invalid.", optional: true }
278
297
  ],
279
- stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 5, totalDurationMs: 12e4 } }
298
+ stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 7, totalDurationMs: 3e5 } },
299
+ repeatOnUnknown: "limited",
300
+ maxSends: 3
280
301
  };
281
302
  var ReplyToMessageBranch = {
282
303
  Sent: "sent",
@@ -296,7 +317,9 @@ var ReplyToMessageDefinition = {
296
317
  { id: "invalidResponse", description: "Gmail returned an invalid or oversized source message response before sending the reply.", optional: true },
297
318
  { id: "defect", description: "Local input, connection configuration, or connector definition is invalid.", optional: true }
298
319
  ],
299
- stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 5, totalDurationMs: 12e4 } }
320
+ stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 7, totalDurationMs: 3e5 } },
321
+ repeatOnUnknown: "limited",
322
+ maxSends: 3
300
323
  };
301
324
 
302
325
  // src/message.ts
@@ -338,7 +361,8 @@ function decodeGmailMessage(resource) {
338
361
  ...textBodies.length ? { textBody: textBodies.join("\n") } : {},
339
362
  ...htmlBodies.length ? { htmlBody: htmlBodies.join("\n") } : {},
340
363
  ...resource.snippet ? { snippet: resource.snippet } : {},
341
- receivedAt: receivedAt.toISOString().replace(".000Z", "Z"),
364
+ // Go's time.Time JSON (RFC 3339 with trailing fractional zeros removed), such as .12Z for 120 ms.
365
+ receivedAt: receivedAt.toISOString().replace(/\.(\d*?)0*Z$/, (_match, digits) => digits ? `.${digits}Z` : "Z"),
342
366
  ...resource.labelIds?.length ? { labelIds: resource.labelIds } : {}
343
367
  };
344
368
  }
@@ -484,14 +508,20 @@ function gmailClientSettings(config = {}) {
484
508
  if (!Number.isSafeInteger(maxResponseBytes) || maxResponseBytes < 1 || !Number.isSafeInteger(maxMessageBytes) || maxMessageBytes < 1) {
485
509
  throw new TypeError("Gmail response and message limits must be positive integers");
486
510
  }
487
- if (config.pollIntervalMs !== void 0 && (!Number.isSafeInteger(config.pollIntervalMs) || config.pollIntervalMs < 1e3)) throw new TypeError("Gmail poll interval is invalid");
488
- if (config.pollPageSize !== void 0 && (!Number.isSafeInteger(config.pollPageSize) || config.pollPageSize < 1 || config.pollPageSize > 100)) throw new TypeError("Gmail poll page size is invalid");
489
- return Object.freeze({ endpoint, maxResponseBytes, maxMessageBytes, addressPolicy: endpoint.startsWith("http://") ? "privateNetworkHTTP" : "publicHTTPS" });
511
+ const pollIntervalMs = config.pollIntervalMs ?? 1e4;
512
+ const pollPageSize = config.pollPageSize ?? 25;
513
+ if (!Number.isSafeInteger(pollIntervalMs) || pollIntervalMs < 1e3) throw new TypeError("Gmail poll interval is invalid");
514
+ if (!Number.isSafeInteger(pollPageSize) || pollPageSize < 1 || pollPageSize > 100) throw new TypeError("Gmail poll page size is invalid");
515
+ return Object.freeze({ endpoint, maxResponseBytes, maxMessageBytes, addressPolicy: endpoint.startsWith("http://") ? "privateNetworkHTTP" : "publicHTTPS", pollIntervalMs, pollPageSize });
490
516
  }
491
517
  var GmailCredentialError = class extends Error {
492
- constructor() {
518
+ /** True when only reconnection can repair the failure: reauthorization or invalid material. */
519
+ isPermanent;
520
+ /** Create a secret-safe credential failure; omitted permanence means permanent. */
521
+ constructor(isPermanent = true) {
493
522
  super("connection credentials are unavailable");
494
523
  this.name = "GmailCredentialError";
524
+ this.isPermanent = isPermanent;
495
525
  }
496
526
  };
497
527
  var GmailHTTPClient = class {
@@ -513,13 +543,18 @@ var GmailHTTPClient = class {
513
543
  }
514
544
  /** Resolve a private token at call time; never put it in a receipt or Flow value. */
515
545
  async resolveCredentials(call, signal) {
546
+ let credentials;
547
+ try {
548
+ credentials = await (0, import_connectors_sdk2.resolveCredential)(this.#credentials, call, this.#refreshDriver, signal);
549
+ } catch (error) {
550
+ throw new GmailCredentialError(error instanceof import_connectors_sdk2.ReauthorizationRequiredError);
551
+ }
516
552
  try {
517
- const credentials = await (0, import_connectors_sdk2.resolveCredential)(this.#credentials, call, this.#refreshDriver, signal);
518
553
  validateCredentials(credentials);
519
- return credentials;
520
554
  } catch {
521
555
  throw new GmailCredentialError();
522
556
  }
557
+ return credentials;
523
558
  }
524
559
  /** Send one authenticated request, refreshing at most once after a 401. */
525
560
  async request(call, credentials, method, pathAndQuery, body, signal) {
@@ -595,6 +630,7 @@ function validateCredentials(credentials) {
595
630
  var import_zod4 = require("zod");
596
631
  var SentMessageSchema = import_zod4.z.object({ id: import_zod4.z.string().optional(), threadId: import_zod4.z.string().optional() });
597
632
  var SentSearchSchema = import_zod4.z.object({ messages: import_zod4.z.array(SentMessageSchema).nullish() });
633
+ var MessageListSchema = import_zod4.z.object({ messages: import_zod4.z.array(import_zod4.z.object({ id: import_zod4.z.string().nullish(), threadId: import_zod4.z.string().nullish() })).nullish() });
598
634
  var GmailProvider = class {
599
635
  #http;
600
636
  /** Bind the shared authenticated transport. */
@@ -619,6 +655,23 @@ var GmailProvider = class {
619
655
  return result;
620
656
  }
621
657
  }
658
+ /**
659
+ * List the newest inbox page that matches searchQuery, as the Go Trigger poller does. It rejects with
660
+ * an error that names no query value when Gmail does not answer 2xx with a usable listing.
661
+ */
662
+ async listInboxMessages(call, credentials, searchQuery, pageSize, signal) {
663
+ const query = new URLSearchParams({ labelIds: "INBOX", maxResults: String(pageSize) });
664
+ if (searchQuery.trim()) query.set("q", searchQuery);
665
+ const result = await this.#http.request(call, credentials, "GET", `/users/me/messages?${query.toString()}`, void 0, signal);
666
+ if (result.response.status < 200 || result.response.status >= 300) throw new Error("Gmail message list is unavailable");
667
+ let parsed;
668
+ try {
669
+ parsed = MessageListSchema.parse(JSON.parse(Buffer.from(result.response.body).toString("utf8")));
670
+ } catch {
671
+ throw new Error("Gmail message list is invalid");
672
+ }
673
+ return { messages: (parsed.messages ?? []).map((message) => ({ id: message.id ?? "", threadId: message.threadId ?? "" })), credentials: result.credentials };
674
+ }
622
675
  /** Search Sent Mail once for the run-specific RFC Message-ID. */
623
676
  async findSentMessage(call, credentials, messageIdAddress, signal) {
624
677
  const query = new URLSearchParams();
@@ -974,7 +1027,7 @@ var GmailSender = class {
974
1027
  if (call.context.attempt < 1) return defect("sendMessage", "LOCAL_DEFECT", "Dex Execute attempt number is invalid");
975
1028
  const messageIdAddress = this.#messageID(call);
976
1029
  if (!messageIdAddress) return defect("sendMessage", "LOCAL_DEFECT", MissingRunIDMessage);
977
- const fence = (0, import_singledispatch.newFence)(call, SendMessageDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4);
1030
+ const fence = (0, import_singledispatch.newFence)(call, SendMessageDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4, { maxSends: (0, import_connectors_sdk4.definitionMaxSends)(SendMessageDefinition) });
978
1031
  if (fence.decide().kind === "failClosed") return defect("sendMessage", "LOCAL_DEFECT", "Dex send checkpoint is unreadable");
979
1032
  const budget = new GmailSendAttemptBudget(call.context.cancellationSignal, dexDeadline);
980
1033
  if (!budget.sendSignal()) {
@@ -984,8 +1037,8 @@ var GmailSender = class {
984
1037
  let credentials;
985
1038
  try {
986
1039
  credentials = await this.#http.resolveCredentials(call, budget.attemptSignal());
987
- } catch {
988
- return defect("sendMessage", "AUTHENTICATION", "connection credentials are unavailable");
1040
+ } catch (error) {
1041
+ return unavailableCredentials(fence, "sendMessage", error);
989
1042
  }
990
1043
  let recipients;
991
1044
  try {
@@ -1008,7 +1061,7 @@ var GmailSender = class {
1008
1061
  if (call.context.attempt < 1) return defect("replyToMessage", "LOCAL_DEFECT", "Dex Execute attempt number is invalid");
1009
1062
  const messageIdAddress = this.#messageID(call);
1010
1063
  if (!messageIdAddress) return defect("replyToMessage", "LOCAL_DEFECT", MissingRunIDMessage);
1011
- const fence = (0, import_singledispatch.newFence)(call, ReplyToMessageDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4);
1064
+ const fence = (0, import_singledispatch.newFence)(call, ReplyToMessageDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4, { maxSends: (0, import_connectors_sdk4.definitionMaxSends)(ReplyToMessageDefinition) });
1012
1065
  if (fence.decide().kind === "failClosed") return defect("replyToMessage", "LOCAL_DEFECT", "Dex send checkpoint is unreadable");
1013
1066
  const budget = new GmailSendAttemptBudget(call.context.cancellationSignal, dexDeadline);
1014
1067
  if (!budget.sendSignal()) {
@@ -1018,12 +1071,12 @@ var GmailSender = class {
1018
1071
  let credentials;
1019
1072
  try {
1020
1073
  credentials = await this.#http.resolveCredentials(call, budget.attemptSignal());
1021
- } catch {
1022
- return defect("replyToMessage", "AUTHENTICATION", "connection credentials are unavailable");
1074
+ } catch (error) {
1075
+ return unavailableCredentials(fence, "replyToMessage", error);
1023
1076
  }
1024
1077
  if (!ReplyToMessageInputSchema.safeParse(input).success || !input.messageId.trim() || !input.textBody.trim()) return defect("replyToMessage", "VALIDATION", "message ID and text body are required");
1025
1078
  const priorProviderId = fence.decide().marker?.providerId;
1026
- if (fence.decide().kind === "readBackRequired" && priorProviderId) {
1079
+ if (isReadBackDecision(fence) && priorProviderId) {
1027
1080
  return this.#sentMessage(
1028
1081
  call,
1029
1082
  budget,
@@ -1039,8 +1092,10 @@ var GmailSender = class {
1039
1092
  const found = await this.#provider.findSentMessage(call, credentials, messageIdAddress, budget.preSendSignal());
1040
1093
  if (found) return this.#sentMessage(call, budget, credentials, ReplyToMessageOutcomes, { raw: new Uint8Array(), recipients: [], requestedThreadId: "", hasPreSendSearch: true, messageIdAddress }, found, this.#receipt(call));
1041
1094
  } catch {
1042
- await recordPreSendRetry(fence);
1043
- return (0, import_connectors_sdk4.newMutationRetry)(failure("replyToMessage", "AVAILABILITY", "Gmail sent-mail search did not answer before the reply"));
1095
+ if (fence.decide().kind !== "readBackThenResendAllowed") {
1096
+ await recordPreSendRetry(fence);
1097
+ return (0, import_connectors_sdk4.newMutationRetry)(failure("replyToMessage", "AVAILABILITY", "Gmail sent-mail search did not answer before the reply"));
1098
+ }
1044
1099
  }
1045
1100
  if (fence.decide().kind === "readBackRequired") return (0, import_connectors_sdk4.newMutationRetry)(failure("replyToMessage", "AVAILABILITY", "Gmail reply outcome is unknown; the sent-mail search found no message"));
1046
1101
  }
@@ -1051,13 +1106,13 @@ var GmailSender = class {
1051
1106
  if (error instanceof GmailCredentialError) return defect("replyToMessage", "AUTHENTICATION", "connection credentials are unavailable");
1052
1107
  const status = error instanceof import_providerhttp2.BodyTooLargeError ? error.status ?? 0 : 0;
1053
1108
  const headers = error instanceof import_providerhttp2.BodyTooLargeError ? error.headers ?? {} : {};
1054
- const result = classifySourceFailure(status, headers, this.#receipt(call));
1109
+ const result = classifySourceFailure(fence, status, headers, this.#receipt(call));
1055
1110
  if (result.kind === "retry") await recordPreSendRetry(fence);
1056
1111
  return result;
1057
1112
  }
1058
1113
  credentials = source.credentials;
1059
1114
  if (!source.resource) {
1060
- const result = classifySourceFailure(source.response.status, source.response.headers, this.#receipt(call, gmailRequestID(source.response.headers), input.messageId));
1115
+ const result = classifySourceFailure(fence, source.response.status, source.response.headers, this.#receipt(call, gmailRequestID(source.response.headers), input.messageId));
1061
1116
  if (result.kind === "retry") await recordPreSendRetry(fence);
1062
1117
  return result;
1063
1118
  }
@@ -1065,16 +1120,16 @@ var GmailSender = class {
1065
1120
  try {
1066
1121
  message = decodeGmailMessage(source.resource);
1067
1122
  } catch {
1068
- return (0, import_connectors_sdk4.newMutationBranch)(ReplyToMessageBranch.InvalidResponse, emptySend(), this.#receipt(call, gmailRequestID(source.response.headers), input.messageId), failure("replyToMessage", "PROTOCOL", "source message lacks reply metadata"));
1123
+ return rejectUnlessEarlierSendIsUnconfirmed(fence, ReplyToMessageBranch.InvalidResponse, this.#receipt(call, gmailRequestID(source.response.headers), input.messageId), failure("replyToMessage", "PROTOCOL", "source message lacks reply metadata"));
1069
1124
  }
1070
- if (!message.threadId || !message.rfcMessageId) return (0, import_connectors_sdk4.newMutationBranch)(ReplyToMessageBranch.InvalidResponse, emptySend(), this.#receipt(call, gmailRequestID(source.response.headers), input.messageId), failure("replyToMessage", "PROTOCOL", "source message lacks reply metadata"));
1125
+ if (!message.threadId || !message.rfcMessageId) return rejectUnlessEarlierSendIsUnconfirmed(fence, ReplyToMessageBranch.InvalidResponse, this.#receipt(call, gmailRequestID(source.response.headers), input.messageId), failure("replyToMessage", "PROTOCOL", "source message lacks reply metadata"));
1071
1126
  let recipient;
1072
1127
  try {
1073
1128
  recipient = replyRecipient(message);
1074
1129
  } catch {
1075
- return (0, import_connectors_sdk4.newMutationBranch)(ReplyToMessageBranch.InvalidResponse, emptySend(), this.#receipt(call, gmailRequestID(source.response.headers), input.messageId), failure("replyToMessage", "PROTOCOL", "Gmail returned an invalid source sender"));
1130
+ return rejectUnlessEarlierSendIsUnconfirmed(fence, ReplyToMessageBranch.InvalidResponse, this.#receipt(call, gmailRequestID(source.response.headers), input.messageId), failure("replyToMessage", "PROTOCOL", "Gmail returned an invalid source sender"));
1076
1131
  }
1077
- if (/[\r\n]/.test(message.subject + message.rfcMessageId + (message.references ?? ""))) return (0, import_connectors_sdk4.newMutationBranch)(ReplyToMessageBranch.InvalidResponse, emptySend(), this.#receipt(call, gmailRequestID(source.response.headers), input.messageId), failure("replyToMessage", "PROTOCOL", "Gmail returned invalid source reply headers"));
1132
+ if (/[\r\n]/.test(message.subject + message.rfcMessageId + (message.references ?? ""))) return rejectUnlessEarlierSendIsUnconfirmed(fence, ReplyToMessageBranch.InvalidResponse, this.#receipt(call, gmailRequestID(source.response.headers), input.messageId), failure("replyToMessage", "PROTOCOL", "Gmail returned invalid source reply headers"));
1078
1133
  let raw;
1079
1134
  try {
1080
1135
  raw = buildReplyMIMEMessage(call.id, call.idempotencyKey ?? call.id, messageIdAddress, credentials.primaryEmail, message, input);
@@ -1086,7 +1141,7 @@ var GmailSender = class {
1086
1141
  }
1087
1142
  async #sendAndConfirm(call, fence, budget, credentials, operation, message) {
1088
1143
  const priorProviderId = fence.decide().marker?.providerId;
1089
- if (fence.decide().kind === "readBackRequired" && priorProviderId) {
1144
+ if (isReadBackDecision(fence) && priorProviderId) {
1090
1145
  return this.#sentMessage(
1091
1146
  call,
1092
1147
  budget,
@@ -1102,8 +1157,10 @@ var GmailSender = class {
1102
1157
  const found = await this.#provider.findSentMessage(call, credentials, message.messageIdAddress, budget.preSendSignal());
1103
1158
  if (found) return this.#sentMessage(call, budget, credentials, operation, message, found, this.#receipt(call));
1104
1159
  } catch {
1105
- await recordPreSendRetry(fence);
1106
- return (0, import_connectors_sdk4.newMutationRetry)(failure(operation.operationId, "AVAILABILITY", `Gmail sent-mail search did not answer before the ${operation.requestName}`));
1160
+ if (fence.decide().kind !== "readBackThenResendAllowed") {
1161
+ await recordPreSendRetry(fence);
1162
+ return (0, import_connectors_sdk4.newMutationRetry)(failure(operation.operationId, "AVAILABILITY", `Gmail sent-mail search did not answer before the ${operation.requestName}`));
1163
+ }
1107
1164
  }
1108
1165
  }
1109
1166
  if (fence.decide().kind === "readBackRequired") return (0, import_connectors_sdk4.newMutationRetry)(failure(operation.operationId, "AVAILABILITY", `Gmail ${operation.requestName} outcome is unknown; the sent-mail search found no message`));
@@ -1144,7 +1201,7 @@ var GmailSender = class {
1144
1201
  } catch {
1145
1202
  }
1146
1203
  }
1147
- return (0, import_connectors_sdk4.newMutationBranch)(operation.providerRejectedBranch, emptySend(), receipt, failure(operation.operationId, statusFailureKind(status), operation.rejectionMessage));
1204
+ return rejectUnlessEarlierSendIsUnconfirmed(fence, operation.providerRejectedBranch, receipt, failure(operation.operationId, statusFailureKind(status), operation.rejectionMessage));
1148
1205
  }
1149
1206
  if (!sentResponse) {
1150
1207
  const lookup = await this.#pollSentMessage(call, budget, credentials, message);
@@ -1208,6 +1265,10 @@ var GmailSender = class {
1208
1265
  function failure(operation, kind, message) {
1209
1266
  return { kind, provider: "gmail", operation, message };
1210
1267
  }
1268
+ function isReadBackDecision(fence) {
1269
+ const kind = fence.decide().kind;
1270
+ return kind === "readBackRequired" || kind === "readBackThenResendAllowed";
1271
+ }
1211
1272
  async function recordPreSendRetry(fence) {
1212
1273
  if (fence.decide().kind !== "sendAllowed") return;
1213
1274
  try {
@@ -1240,10 +1301,19 @@ function retryAfterRefusal(operation, kind, message, headers) {
1240
1301
  return (0, import_connectors_sdk4.newMutationRetry)(failure(operation, "PROTOCOL", "Gmail returned an invalid Retry-After header"));
1241
1302
  }
1242
1303
  }
1243
- function classifySourceFailure(status, headers, receipt) {
1304
+ function unavailableCredentials(fence, operation, error) {
1305
+ const isPermanent = !(error instanceof GmailCredentialError) || error.isPermanent;
1306
+ if (!isPermanent && (fence.decide().priorSendUpperBound ?? 0) > 0) return (0, import_connectors_sdk4.newMutationRetry)(failure(operation, "AUTHENTICATION", "Gmail credentials are temporarily unavailable; an earlier send may still be delivered"));
1307
+ return defect(operation, "AUTHENTICATION", "connection credentials are unavailable");
1308
+ }
1309
+ function rejectUnlessEarlierSendIsUnconfirmed(fence, branch, receipt, rejection) {
1310
+ if ((fence.decide().priorSendUpperBound ?? 0) > 0) return (0, import_connectors_sdk4.newMutationRetry)({ ...rejection, message: `${rejection.message}; an earlier send may still be delivered` });
1311
+ return (0, import_connectors_sdk4.newMutationBranch)(branch, emptySend(), receipt, rejection);
1312
+ }
1313
+ function classifySourceFailure(fence, status, headers, receipt) {
1244
1314
  if (status === 0 || status === 429 || status >= 500) return retryAfterRefusal("replyToMessage", "AVAILABILITY", "Gmail source message is temporarily unavailable", headers);
1245
- if (status >= 200 && status < 300) return (0, import_connectors_sdk4.newMutationBranch)(ReplyToMessageBranch.InvalidResponse, emptySend(), receipt, failure("replyToMessage", "PROTOCOL", "Gmail returned an invalid source message response"));
1246
- return (0, import_connectors_sdk4.newMutationBranch)(ReplyToMessageBranch.ProviderRejected, emptySend(), receipt, failure("replyToMessage", statusFailureKind(status), "Gmail rejected the source message lookup"));
1315
+ if (status >= 200 && status < 300) return rejectUnlessEarlierSendIsUnconfirmed(fence, ReplyToMessageBranch.InvalidResponse, receipt, failure("replyToMessage", "PROTOCOL", "Gmail returned an invalid source message response"));
1316
+ return rejectUnlessEarlierSendIsUnconfirmed(fence, ReplyToMessageBranch.ProviderRejected, receipt, failure("replyToMessage", statusFailureKind(status), "Gmail rejected the source message lookup"));
1247
1317
  }
1248
1318
 
1249
1319
  // src/client.ts
@@ -1254,12 +1324,19 @@ var GmailClient = class {
1254
1324
  #provider;
1255
1325
  #sender;
1256
1326
  #now;
1327
+ /** Trigger record destination. */
1328
+ triggerLogger;
1257
1329
  /** Validate settings and inject a host-owned credential source. */
1258
1330
  constructor(config, credentials, options = {}) {
1259
1331
  this.#http = new GmailHTTPClient(config, credentials, options.refreshDriver ?? new GmailCredentialRefreshDriver(), options.transport);
1260
1332
  this.#provider = new GmailProvider(this.#http);
1261
1333
  this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
1262
1334
  this.#sender = new GmailSender(this.#http, this.#provider, this.#now);
1335
+ this.triggerLogger = options.logger ?? import_connectors_sdk5.defaultTriggerLogger;
1336
+ }
1337
+ /** @internal The authenticated transport and provider methods that the Trigger pollers share. */
1338
+ triggerTransport() {
1339
+ return { http: this.#http, provider: this.#provider };
1263
1340
  }
1264
1341
  /** Return the getMessage Query bound to this connection. */
1265
1342
  getMessage() {
@@ -1525,6 +1602,374 @@ function newReplyToMessageStep2(configuration) {
1525
1602
  requireGmailConnection(configuration.connection, configuration.connectionName);
1526
1603
  return newReplyToMessageStep(configuration);
1527
1604
  }
1605
+
1606
+ // src/trigger.ts
1607
+ var import_connectors_sdk12 = require("@superdurable/connectors-sdk");
1608
+ var import_projectconfig2 = require("@superdurable/connectors-sdk/projectconfig");
1609
+ var import_zod6 = require("zod");
1610
+
1611
+ // src/trigger_source.ts
1612
+ var import_node_crypto2 = require("crypto");
1613
+ var import_connectors_sdk11 = require("@superdurable/connectors-sdk");
1614
+ var GmailPollError = class extends Error {
1615
+ constructor(message, cause) {
1616
+ super(message, cause === void 0 ? void 0 : { cause });
1617
+ this.name = "GmailPollError";
1618
+ }
1619
+ };
1620
+ var uuidNamespaceURL = Buffer.from("6ba7b8119dad11d180b400c04fd430c8", "hex");
1621
+ var MessagePollingTriggerSource = class {
1622
+ #client;
1623
+ #connection;
1624
+ #searchQuery;
1625
+ #matcher;
1626
+ #requiresReply;
1627
+ #logger;
1628
+ #triggerName;
1629
+ #delivered = /* @__PURE__ */ new Set();
1630
+ // Every later poll delivers this event before any listed message, until the target consumes it.
1631
+ #retry;
1632
+ #pollFailures = 0;
1633
+ /** Bind one binding's query and matcher; an empty bindingName omits the binding log attribute. */
1634
+ constructor(client, connection, triggerName, bindingName, searchQuery, matcher, requiresReply) {
1635
+ this.#client = client;
1636
+ this.#connection = connection;
1637
+ this.#triggerName = triggerName;
1638
+ this.#searchQuery = searchQuery;
1639
+ this.#matcher = matcher;
1640
+ this.#requiresReply = requiresReply;
1641
+ this.#logger = (0, import_connectors_sdk11.withTriggerLoggerAttributes)(client.triggerLogger, { connector: ConnectorID, connection: connection.name, trigger: triggerName, ...bindingName ? { binding: bindingName } : {} });
1642
+ }
1643
+ /** Scan, then wait one poll interval, until the context ends. */
1644
+ async run(context, target) {
1645
+ await runMessageTriggerRoutes(context, () => this.scan(context, target), this.#pollIntervalMs());
1646
+ }
1647
+ /** List the inbox and deliver the listed messages. */
1648
+ async scan(context, target) {
1649
+ await this.deliver(context, target, await this.list(context));
1650
+ }
1651
+ /** Read the newest inbox page that matches the source's search query. */
1652
+ async list(context) {
1653
+ const { http, provider } = this.#client.triggerTransport();
1654
+ const call = this.#credentialCall(context.signal);
1655
+ let credentials;
1656
+ try {
1657
+ credentials = await http.resolveCredentials(call, context.signal);
1658
+ } catch (error) {
1659
+ throw this.#pollFailed(context, new GmailPollError("Gmail Trigger credentials are unavailable", error));
1660
+ }
1661
+ try {
1662
+ const listed = await provider.listInboxMessages(call, credentials, this.#searchQuery, http.settings().pollPageSize, context.signal);
1663
+ return { credentials: listed.credentials, messages: listed.messages };
1664
+ } catch (error) {
1665
+ throw this.#pollFailed(context, new GmailPollError("Gmail message list is unavailable", error));
1666
+ }
1667
+ }
1668
+ /**
1669
+ * Hand target the event that failed on an earlier poll, if any, then every new matching message in
1670
+ * listing, oldest first. It stops at the first failure, so the next poll retries that event before any
1671
+ * later message, even after newer mail pushes it off the listed page.
1672
+ */
1673
+ async deliver(context, target, listing) {
1674
+ if (this.#retry) await this.#handle(context, target, this.#retry.event);
1675
+ const { provider } = this.#client.triggerTransport();
1676
+ let credentials = listing.credentials;
1677
+ const current = /* @__PURE__ */ new Set();
1678
+ for (let index = listing.messages.length - 1; index >= 0; index--) {
1679
+ const reference = listing.messages[index];
1680
+ if (!reference.id) continue;
1681
+ current.add(reference.id);
1682
+ if (this.#delivered.has(reference.id)) continue;
1683
+ const messageAttributes = { thread_id: reference.threadId, event_id: reference.id };
1684
+ let message;
1685
+ try {
1686
+ const read = await provider.readMessage(this.#credentialCall(context.signal), credentials, reference.id, "metadata", context.signal);
1687
+ credentials = read.credentials;
1688
+ if (!read.resource) throw new GmailPollError("Gmail message lookup failed");
1689
+ message = decodeGmailMessage(read.resource);
1690
+ } catch (error) {
1691
+ throw this.#pollFailed(context, error instanceof GmailPollError ? error : new GmailPollError("Gmail message lookup failed", error), messageAttributes);
1692
+ }
1693
+ const isReply = (message.inReplyTo ?? "").trim() !== "" || (message.references ?? "").trim() !== "";
1694
+ const reason = this.#ignoreReason(isReply, message);
1695
+ if (reason) {
1696
+ this.#log(context, "debug", "trigger event ignored", { ...messageAttributes, reason });
1697
+ continue;
1698
+ }
1699
+ const event = {
1700
+ id: message.messageId,
1701
+ occurredAt: new Date(message.receivedAt),
1702
+ payload: {
1703
+ primaryEmail: credentials.primaryEmail,
1704
+ messageId: message.messageId,
1705
+ threadId: message.threadId,
1706
+ from: message.from,
1707
+ subject: message.subject,
1708
+ ...message.snippet ? { snippet: message.snippet } : {},
1709
+ receivedAt: message.receivedAt,
1710
+ isReply
1711
+ }
1712
+ };
1713
+ try {
1714
+ await (0, import_connectors_sdk11.prepareTriggerDelivery)(context, target, event);
1715
+ } catch (error) {
1716
+ throw this.#pollFailed(context, new GmailPollError("Gmail Trigger delivery could not be recorded", error), messageAttributes);
1717
+ }
1718
+ await this.#handle(context, target, event);
1719
+ }
1720
+ this.#delivered = current;
1721
+ this.#pollFailures = 0;
1722
+ }
1723
+ #pollIntervalMs() {
1724
+ return this.#client.triggerTransport().http.settings().pollIntervalMs;
1725
+ }
1726
+ /**
1727
+ * Make one delivery attempt and log its outcome. It resolves when target consumes the event, and
1728
+ * otherwise keeps the event as the source's retry and rethrows. A durable inbox or a newTrigger runner
1729
+ * logs the undeliverable events it consumes itself, so the source then logs no recovery.
1730
+ */
1731
+ async #handle(context, target, event) {
1732
+ const failures = this.#retry?.event.id === event.id ? this.#retry.failures : 0;
1733
+ const threadAttributes = { thread_id: event.payload.threadId };
1734
+ const messageAttributes = { ...threadAttributes, event_id: event.id };
1735
+ const attempt = (0, import_connectors_sdk11.triggerAttempt)((0, import_connectors_sdk11.withTriggerLogAttributes)(context, threadAttributes));
1736
+ try {
1737
+ await target.handleTrigger(attempt.context, event);
1738
+ if (failures > 0 && !attempt.wasSkipped()) this.#log(context, "info", "trigger delivered after retry", { ...messageAttributes, attempts: failures + 1 });
1739
+ } catch (error) {
1740
+ if ((0, import_connectors_sdk11.isTriggerUndeliverable)(error)) {
1741
+ this.#log(context, "warn", "trigger event skipped: undeliverable", { ...messageAttributes, ...(0, import_connectors_sdk11.triggerErrorAttributes)(error) });
1742
+ } else if (context.signal.aborted) {
1743
+ throw error;
1744
+ } else {
1745
+ this.#pollFailures = 0;
1746
+ this.#retry = { event, failures: failures + 1 };
1747
+ this.#log(context, "warn", "trigger delivery failed; retrying", { ...messageAttributes, attempt: failures + 1, delay_ms: this.#pollIntervalMs(), ...(0, import_connectors_sdk11.triggerErrorAttributes)(error) });
1748
+ throw error;
1749
+ }
1750
+ }
1751
+ this.#retry = void 0;
1752
+ this.#delivered.add(event.id);
1753
+ }
1754
+ /** Explain why the source does not deliver a listed message, or return '' when it matches. */
1755
+ #ignoreReason(isReply, message) {
1756
+ if (this.#requiresReply && !isReply) return "not_a_reply";
1757
+ if (!this.#requiresReply && isReply) return "not_a_root";
1758
+ if (!messageMatcherMatches(this.#matcher, message)) return "matcher_mismatch";
1759
+ return "";
1760
+ }
1761
+ /** Log a poll that ended early and return error; the next poll, one interval later, retries. */
1762
+ #pollFailed(context, error, attributes = {}) {
1763
+ if (context.signal.aborted) return new import_connectors_sdk11.TriggerDeliveryAbortedError();
1764
+ this.#pollFailures++;
1765
+ const causeAttributes = error.cause === void 0 ? {} : { error_cause_type: (0, import_connectors_sdk11.triggerErrorAttributes)(error.cause).error_type ?? "Error" };
1766
+ this.#log(context, "warn", "gmail poll failed; retrying", { ...attributes, attempt: this.#pollFailures, delay_ms: this.#pollIntervalMs(), error: error.message, ...causeAttributes });
1767
+ return error;
1768
+ }
1769
+ #log(context, level, message, attributes) {
1770
+ (0, import_connectors_sdk11.logTriggerRecord)(this.#logger, context, level, message, attributes);
1771
+ }
1772
+ /** The Go connector's stable credential call: a version 5 UUID of the connection and Trigger. */
1773
+ #credentialCall(signal) {
1774
+ const identity = ["https://superdurable.dev/dex-connectors/trigger-credential/v1", this.#connection.provider, this.#connection.name, this.#triggerName].join("/");
1775
+ return (0, import_connectors_sdk11.createTriggerCall)(this.#connection, { connectorId: ConnectorID, operationId: this.#triggerName }, nameBasedUUID(identity), signal);
1776
+ }
1777
+ };
1778
+ function messageMatcherMatches(matcher, message) {
1779
+ if (matcher.messageContains) {
1780
+ const haystack = `${message.subject}
1781
+ ${message.snippet ?? ""}`.toLowerCase();
1782
+ if (!haystack.includes(matcher.messageContains.toLowerCase())) return false;
1783
+ }
1784
+ const senders = matcher.senderEmails ?? [];
1785
+ if (senders.length === 0) return true;
1786
+ const sender = parseMailbox(message.from)?.address.toLowerCase();
1787
+ if (!sender) return false;
1788
+ return senders.some((allowed) => parseMailbox(allowed)?.address.toLowerCase() === sender);
1789
+ }
1790
+ async function runMessageTriggerRoutes(context, poll, intervalMs) {
1791
+ for (; ; ) {
1792
+ (0, import_connectors_sdk11.throwIfTriggerAborted)(context.signal);
1793
+ try {
1794
+ await poll();
1795
+ } catch {
1796
+ (0, import_connectors_sdk11.throwIfTriggerAborted)(context.signal);
1797
+ }
1798
+ await (0, import_connectors_sdk11.waitForTriggerDelay)(context.signal, intervalMs);
1799
+ }
1800
+ }
1801
+ async function pollMessageTriggerRoutes(context, rootRoutes, replyRoutes) {
1802
+ const replyListings = [];
1803
+ for (const route of replyRoutes) replyListings.push(await route.source.list(context));
1804
+ for (const route of rootRoutes) await route.source.scan(context, route.target);
1805
+ for (const [index, route] of replyRoutes.entries()) await route.source.deliver(context, route.target, replyListings[index]);
1806
+ }
1807
+ async function replayMessageTriggerRoutes(context, routes) {
1808
+ for (const route of routes) {
1809
+ if (!route.target.replayTriggerDeliveries) continue;
1810
+ try {
1811
+ await route.target.replayTriggerDeliveries(context);
1812
+ } catch (error) {
1813
+ if (error instanceof import_connectors_sdk11.TriggerDeliveryAbortedError) throw error;
1814
+ throw new Error(`replay Gmail Trigger deliveries: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
1815
+ }
1816
+ }
1817
+ }
1818
+ function nameBasedUUID(name) {
1819
+ const bytes = (0, import_node_crypto2.createHash)("sha1").update(uuidNamespaceURL).update(name, "utf8").digest().subarray(0, 16);
1820
+ bytes[6] = bytes[6] & 15 | 80;
1821
+ bytes[8] = bytes[8] & 63 | 128;
1822
+ const hex = bytes.toString("hex");
1823
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
1824
+ }
1825
+
1826
+ // src/trigger.ts
1827
+ var MessageMatcherSchema = import_zod6.z.strictObject({
1828
+ /** Case-insensitive substring of the subject or snippet, required when non-empty. */
1829
+ messageContains: import_zod6.z.string().optional(),
1830
+ /** Sender addresses allowed to match when non-empty; compared case-insensitively. */
1831
+ senderEmails: import_zod6.z.array(import_zod6.z.string()).nullable().optional()
1832
+ });
1833
+ var MessageReceivedTriggerConfigurationSchema = import_zod6.z.strictObject({ searchQuery: import_zod6.z.string().optional(), messageMatcher: MessageMatcherSchema.optional() }).superRefine((configuration, context) => validateMessageMatcher(configuration.messageMatcher, context));
1834
+ var ReplyReceivedTriggerConfigurationSchema = import_zod6.z.strictObject({ searchQuery: import_zod6.z.string().optional(), replyMatcher: MessageMatcherSchema.optional() }).superRefine((configuration, context) => validateMessageMatcher(configuration.replyMatcher, context));
1835
+ var MessageEventSchema = import_zod6.z.object({
1836
+ /** Mailbox that received the message. */
1837
+ primaryEmail: import_zod6.z.string(),
1838
+ /** Gmail message ID. */
1839
+ messageId: import_zod6.z.string(),
1840
+ /** Gmail thread ID. */
1841
+ threadId: import_zod6.z.string(),
1842
+ /** Sender header. */
1843
+ from: import_zod6.z.string(),
1844
+ /** Decoded subject. */
1845
+ subject: import_zod6.z.string(),
1846
+ /** Gmail snippet, omitted when empty. */
1847
+ snippet: import_zod6.z.string().optional(),
1848
+ /** Receive time as RFC 3339 UTC. */
1849
+ receivedAt: import_zod6.z.string(),
1850
+ /** Whether the message has In-Reply-To or References headers. */
1851
+ isReply: import_zod6.z.boolean()
1852
+ });
1853
+ var MessageReceivedTriggerDefinition = { trigger: { connectorId: ConnectorID, triggerName: "messageReceived" }, description: "Receive a matching message that begins a Gmail thread." };
1854
+ var ReplyReceivedTriggerDefinition = { trigger: { connectorId: ConnectorID, triggerName: "replyReceived" }, description: "Receive a matching reply in an existing Gmail thread." };
1855
+ var UIUnitSearchQueryInput = "searchQueryInput";
1856
+ var UISearchQueryInputPortQuery = "query";
1857
+ var UIUnitEmailListInput = "emailListInput";
1858
+ var UIEmailListInputPortEmails = "emails";
1859
+ var UIUnitTextInput = "textInput";
1860
+ var UITextInputPortText = "text";
1861
+ function defineMessageReceivedTriggerBinding(config) {
1862
+ return (0, import_connectors_sdk12.mustTriggerBindingDefinition)({ definition: MessageReceivedTriggerDefinition, ...config });
1863
+ }
1864
+ function defineReplyReceivedTriggerBinding(config) {
1865
+ return (0, import_connectors_sdk12.mustTriggerBindingDefinition)({ definition: ReplyReceivedTriggerDefinition, ...config });
1866
+ }
1867
+ function newMessageReceivedTrigger(config) {
1868
+ const configuration = MessageReceivedTriggerConfigurationSchema.parse(config.configuration);
1869
+ return newStandaloneTrigger(config, MessageReceivedTriggerDefinition, configuration.searchQuery ?? "", configuration.messageMatcher ?? {}, false);
1870
+ }
1871
+ function newReplyReceivedTrigger(config) {
1872
+ const configuration = ReplyReceivedTriggerConfigurationSchema.parse(config.configuration);
1873
+ return newStandaloneTrigger(config, ReplyReceivedTriggerDefinition, configuration.searchQuery ?? "", configuration.replyMatcher ?? {}, true);
1874
+ }
1875
+ function newStandaloneTrigger(config, definition, searchQuery, matcher, requiresReply) {
1876
+ const client = gmailClientOf(config.connection);
1877
+ if (config.connectionName !== config.connection.reference.name) throw new TypeError(`gmail connector trigger connectionName "${config.connectionName}" must equal its connection's name "${config.connection.reference.name}"`);
1878
+ const source = new MessagePollingTriggerSource(client, config.connection.reference, definition.trigger.triggerName, "", searchQuery, matcher, requiresReply);
1879
+ const triggerSource = { run: (context, target) => source.run(context, target) };
1880
+ return (0, import_connectors_sdk12.newTrigger)({ definition, binding: { connection: config.connection.reference, trigger: definition.trigger, name: config.bindingName }, source: triggerSource, target: config.target, logger: client.triggerLogger });
1881
+ }
1882
+ var MessageTriggerRunner = class {
1883
+ #rootRoutes;
1884
+ #replyRoutes;
1885
+ #pollIntervalMs;
1886
+ /** @internal Use newMessageTriggerRunner or newProjectMessageTriggerRunner. */
1887
+ constructor(rootRoutes, replyRoutes, pollIntervalMs) {
1888
+ this.#rootRoutes = rootRoutes;
1889
+ this.#replyRoutes = replyRoutes;
1890
+ this.#pollIntervalMs = pollIntervalMs;
1891
+ }
1892
+ /**
1893
+ * Replay each route's durable inbox in order, roots first, then poll until the context ends. Each poll
1894
+ * lists every reply route before any root route, then delivers every root before any reply, and ends
1895
+ * at the first failure. Every later poll retries the failed event before that route's listed messages,
1896
+ * even after Gmail stops listing it. Gmail receives a thread's root before any reply to it, so the
1897
+ * root of every listed reply is in the later root listing and reaches Dex first.
1898
+ *
1899
+ * It logs through the client's logger: WARN "gmail poll failed; retrying" with the consecutive failed
1900
+ * polls as attempt and the poll interval as delay_ms when a list or read fails, WARN "trigger delivery
1901
+ * failed; retrying" with the attempt number when a target fails, INFO "trigger delivered after retry"
1902
+ * when a later poll delivers that message, DEBUG "trigger event ignored" with its reason, and the
1903
+ * durable inbox records. It rejects with TriggerDeliveryAbortedError once the context ends, and when
1904
+ * an inbox replay fails.
1905
+ */
1906
+ async run(context) {
1907
+ await replayMessageTriggerRoutes(context, [...this.#rootRoutes, ...this.#replyRoutes]);
1908
+ await runMessageTriggerRoutes(context, () => pollMessageTriggerRoutes(context, this.#rootRoutes, this.#replyRoutes), this.#pollIntervalMs);
1909
+ }
1910
+ };
1911
+ function newMessageTriggerRunner(config) {
1912
+ const client = gmailClientOf(config.connection);
1913
+ const bindingKeys = /* @__PURE__ */ new Set();
1914
+ const route = (triggerName, bindingName, target, searchQuery, matcher, requiresReply) => {
1915
+ const trimmedBindingName = bindingName?.trim();
1916
+ if (!trimmedBindingName || !target) throw new TypeError("Gmail message Trigger binding name and target are required");
1917
+ const bindingKey = `${triggerName}\0${trimmedBindingName}`;
1918
+ if (bindingKeys.has(bindingKey)) throw new TypeError(`Gmail message Trigger binding name "${trimmedBindingName}" is duplicated`);
1919
+ bindingKeys.add(bindingKey);
1920
+ return { source: new MessagePollingTriggerSource(client, config.connection.reference, triggerName, bindingName, searchQuery ?? "", matcher ?? {}, requiresReply), target };
1921
+ };
1922
+ const rootRoutes = (config.messageReceivedRoutes ?? []).map((root) => {
1923
+ const configuration = MessageReceivedTriggerConfigurationSchema.parse(root.configuration);
1924
+ return route("messageReceived", root.bindingName, root.target, configuration.searchQuery, configuration.messageMatcher, false);
1925
+ });
1926
+ const replyRoutes = (config.replyReceivedRoutes ?? []).map((reply) => {
1927
+ const configuration = ReplyReceivedTriggerConfigurationSchema.parse(reply.configuration);
1928
+ return route("replyReceived", reply.bindingName, reply.target, configuration.searchQuery, configuration.replyMatcher, true);
1929
+ });
1930
+ if (rootRoutes.length + replyRoutes.length === 0) throw new TypeError("Gmail message Trigger routes are required");
1931
+ return new MessageTriggerRunner(rootRoutes, replyRoutes, client.triggerTransport().http.settings().pollIntervalMs);
1932
+ }
1933
+ function newProjectMessageTriggerRunner(project, connectionName, config, options = {}) {
1934
+ const connection = newProjectConnection(project, connectionName, options);
1935
+ const client = gmailClientOf(connection);
1936
+ const durable = (triggerName, bindingName, target, schema) => {
1937
+ const key = { connectorId: ConnectorID, connectionName, triggerName, bindingName };
1938
+ let configuration;
1939
+ try {
1940
+ configuration = (0, import_projectconfig2.decodeTriggerConfiguration)(project.configuration, key, schema);
1941
+ } catch (error) {
1942
+ throw new Error(`gmail ${triggerName} binding "${bindingName}" configuration: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
1943
+ }
1944
+ const durableTarget = (0, import_projectconfig2.newDurableTriggerTarget)(project.triggerInbox(key), key, target, { logger: client.triggerLogger, decodePayload: (_payloadJSON, payloadBytes) => MessageEventSchema.parse((0, import_projectconfig2.parseTriggerPayloadJSON)(payloadBytes)) });
1945
+ return { bindingName, configuration, target: durableTarget };
1946
+ };
1947
+ return newMessageTriggerRunner({
1948
+ connection,
1949
+ messageReceivedRoutes: (config.messageReceivedRoutes ?? []).map((route) => durable("messageReceived", route.bindingName, route.target, MessageReceivedTriggerConfigurationSchema)),
1950
+ replyReceivedRoutes: (config.replyReceivedRoutes ?? []).map((route) => durable("replyReceived", route.bindingName, route.target, ReplyReceivedTriggerConfigurationSchema))
1951
+ });
1952
+ }
1953
+ function gmailClientOf(connection) {
1954
+ if (!(connection?.operations instanceof GmailClient)) throw new TypeError("Gmail Triggers require a connection bound to a GmailClient");
1955
+ return connection.operations;
1956
+ }
1957
+ function validateMessageMatcher(matcher, context) {
1958
+ const seen = /* @__PURE__ */ new Set();
1959
+ for (const sender of matcher?.senderEmails ?? []) {
1960
+ const address = parseMailbox(sender)?.address;
1961
+ if (!address) {
1962
+ context.addIssue({ code: "custom", message: "Gmail sender email is invalid" });
1963
+ return;
1964
+ }
1965
+ const canonical = address.toLowerCase();
1966
+ if (seen.has(canonical)) {
1967
+ context.addIssue({ code: "custom", message: "Gmail sender emails must be unique" });
1968
+ return;
1969
+ }
1970
+ seen.add(canonical);
1971
+ }
1972
+ }
1528
1973
  // Annotate the CommonJS export names for ESM import in node:
1529
1974
  0 && (module.exports = {
1530
1975
  ConnectorID,
@@ -1540,8 +1985,15 @@ function newReplyToMessageStep2(configuration) {
1540
1985
  GmailMessageResourceSchema,
1541
1986
  GmailProvider,
1542
1987
  GoogleOAuthAuthMethodID,
1988
+ MessageEventSchema,
1989
+ MessageMatcherSchema,
1990
+ MessageReceivedTriggerConfigurationSchema,
1991
+ MessageReceivedTriggerDefinition,
1543
1992
  MessageSchema,
1993
+ MessageTriggerRunner,
1544
1994
  ProviderID,
1995
+ ReplyReceivedTriggerConfigurationSchema,
1996
+ ReplyReceivedTriggerDefinition,
1545
1997
  ReplyToMessageBranch,
1546
1998
  ReplyToMessageDefinition,
1547
1999
  ReplyToMessageInputSchema,
@@ -1551,18 +2003,30 @@ function newReplyToMessageStep2(configuration) {
1551
2003
  SendMessageInputSchema,
1552
2004
  SendMessageOperation,
1553
2005
  SendMessageOutputSchema,
2006
+ UIEmailListInputPortEmails,
2007
+ UISearchQueryInputPortQuery,
2008
+ UITextInputPortText,
2009
+ UIUnitEmailListInput,
2010
+ UIUnitSearchQueryInput,
2011
+ UIUnitTextInput,
1554
2012
  WorkspaceDomainDelegationAuthMethodID,
1555
2013
  buildMIMEMessage,
1556
2014
  buildReplyMIMEMessage,
1557
2015
  decodeGmailMessage,
2016
+ defineMessageReceivedTriggerBinding,
2017
+ defineReplyReceivedTriggerBinding,
1558
2018
  emptyMessage,
1559
2019
  gmailClientSettings,
1560
2020
  gmailFailure,
1561
2021
  gmailRequestID,
1562
2022
  gmailRetryAfterMs,
1563
2023
  newGetMessageStep,
2024
+ newMessageReceivedTrigger,
2025
+ newMessageTriggerRunner,
1564
2026
  newProjectConnection,
1565
2027
  newProjectGmailClient,
2028
+ newProjectMessageTriggerRunner,
2029
+ newReplyReceivedTrigger,
1566
2030
  newReplyToMessageStep,
1567
2031
  newSendMessageStep,
1568
2032
  parseMailbox,