@superdurable/connector-google-gmail 0.2.1 → 0.3.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/README.md +14 -2
- package/dex-connector.json +27 -3
- package/dist/{chunk-KVNIQW5Y.js → chunk-PW3NTBVH.js} +466 -23
- package/dist/index.cjs +468 -22
- package/dist/index.d.cts +218 -6
- package/dist/index.d.ts +218 -6
- package/dist/index.js +39 -1
- package/dist/mock/index.cjs +75 -2
- package/dist/mock/index.js +1 -1
- package/package.json +5 -4
|
@@ -206,7 +206,9 @@ var SendMessageDefinition = {
|
|
|
206
206
|
{ id: "providerRejected", description: "Gmail conclusively rejected the message.", optional: true },
|
|
207
207
|
{ id: "defect", description: "Local input, connection configuration, or connector definition is invalid.", optional: true }
|
|
208
208
|
],
|
|
209
|
-
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 5, totalDurationMs: 12e4 } }
|
|
209
|
+
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 5, totalDurationMs: 12e4 } },
|
|
210
|
+
repeatOnUnknown: "limited",
|
|
211
|
+
maxSends: 3
|
|
210
212
|
};
|
|
211
213
|
var ReplyToMessageBranch = {
|
|
212
214
|
Sent: "sent",
|
|
@@ -226,7 +228,9 @@ var ReplyToMessageDefinition = {
|
|
|
226
228
|
{ id: "invalidResponse", description: "Gmail returned an invalid or oversized source message response before sending the reply.", optional: true },
|
|
227
229
|
{ id: "defect", description: "Local input, connection configuration, or connector definition is invalid.", optional: true }
|
|
228
230
|
],
|
|
229
|
-
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 5, totalDurationMs: 12e4 } }
|
|
231
|
+
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 5, totalDurationMs: 12e4 } },
|
|
232
|
+
repeatOnUnknown: "limited",
|
|
233
|
+
maxSends: 3
|
|
230
234
|
};
|
|
231
235
|
|
|
232
236
|
// src/message.ts
|
|
@@ -268,7 +272,8 @@ function decodeGmailMessage(resource) {
|
|
|
268
272
|
...textBodies.length ? { textBody: textBodies.join("\n") } : {},
|
|
269
273
|
...htmlBodies.length ? { htmlBody: htmlBodies.join("\n") } : {},
|
|
270
274
|
...resource.snippet ? { snippet: resource.snippet } : {},
|
|
271
|
-
|
|
275
|
+
// Go's time.Time JSON (RFC 3339 with trailing fractional zeros removed), such as .12Z for 120 ms.
|
|
276
|
+
receivedAt: receivedAt.toISOString().replace(/\.(\d*?)0*Z$/, (_match, digits) => digits ? `.${digits}Z` : "Z"),
|
|
272
277
|
...resource.labelIds?.length ? { labelIds: resource.labelIds } : {}
|
|
273
278
|
};
|
|
274
279
|
}
|
|
@@ -347,7 +352,8 @@ function validateSendInput(input, sender) {
|
|
|
347
352
|
return recipients;
|
|
348
353
|
}
|
|
349
354
|
function rfcMessageIDAddress(idempotencyKey, runId, flowStartedAt) {
|
|
350
|
-
|
|
355
|
+
if (!runId) throw new TypeError("Dex run ID is required");
|
|
356
|
+
const runIdentity = flowStartedAt instanceof Date && Number.isFinite(flowStartedAt.getTime()) ? `${runId}\0${Math.floor(flowStartedAt.getTime() / 1e3)}` : `${runId}\0no-flow-start`;
|
|
351
357
|
return `${createHash("sha256").update(`${idempotencyKey}\0${runIdentity}`).digest("hex")}@dex.superdurable.dev`;
|
|
352
358
|
}
|
|
353
359
|
function buildMIMEMessage(callId, idempotencyKey, messageIdAddress, sender, recipients, subject, textBody, htmlBody = "", replyHeaders) {
|
|
@@ -418,9 +424,11 @@ function gmailClientSettings(config = {}) {
|
|
|
418
424
|
if (!Number.isSafeInteger(maxResponseBytes) || maxResponseBytes < 1 || !Number.isSafeInteger(maxMessageBytes) || maxMessageBytes < 1) {
|
|
419
425
|
throw new TypeError("Gmail response and message limits must be positive integers");
|
|
420
426
|
}
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
427
|
+
const pollIntervalMs = config.pollIntervalMs ?? 1e4;
|
|
428
|
+
const pollPageSize = config.pollPageSize ?? 25;
|
|
429
|
+
if (!Number.isSafeInteger(pollIntervalMs) || pollIntervalMs < 1e3) throw new TypeError("Gmail poll interval is invalid");
|
|
430
|
+
if (!Number.isSafeInteger(pollPageSize) || pollPageSize < 1 || pollPageSize > 100) throw new TypeError("Gmail poll page size is invalid");
|
|
431
|
+
return Object.freeze({ endpoint, maxResponseBytes, maxMessageBytes, addressPolicy: endpoint.startsWith("http://") ? "privateNetworkHTTP" : "publicHTTPS", pollIntervalMs, pollPageSize });
|
|
424
432
|
}
|
|
425
433
|
var GmailCredentialError = class extends Error {
|
|
426
434
|
constructor() {
|
|
@@ -529,6 +537,7 @@ function validateCredentials(credentials) {
|
|
|
529
537
|
import { z as z4 } from "zod";
|
|
530
538
|
var SentMessageSchema = z4.object({ id: z4.string().optional(), threadId: z4.string().optional() });
|
|
531
539
|
var SentSearchSchema = z4.object({ messages: z4.array(SentMessageSchema).nullish() });
|
|
540
|
+
var MessageListSchema = z4.object({ messages: z4.array(z4.object({ id: z4.string().nullish(), threadId: z4.string().nullish() })).nullish() });
|
|
532
541
|
var GmailProvider = class {
|
|
533
542
|
#http;
|
|
534
543
|
/** Bind the shared authenticated transport. */
|
|
@@ -553,6 +562,23 @@ var GmailProvider = class {
|
|
|
553
562
|
return result;
|
|
554
563
|
}
|
|
555
564
|
}
|
|
565
|
+
/**
|
|
566
|
+
* List the newest inbox page that matches searchQuery, as the Go Trigger poller does. It rejects with
|
|
567
|
+
* an error that names no query value when Gmail does not answer 2xx with a usable listing.
|
|
568
|
+
*/
|
|
569
|
+
async listInboxMessages(call, credentials, searchQuery, pageSize, signal) {
|
|
570
|
+
const query = new URLSearchParams({ labelIds: "INBOX", maxResults: String(pageSize) });
|
|
571
|
+
if (searchQuery.trim()) query.set("q", searchQuery);
|
|
572
|
+
const result = await this.#http.request(call, credentials, "GET", `/users/me/messages?${query.toString()}`, void 0, signal);
|
|
573
|
+
if (result.response.status < 200 || result.response.status >= 300) throw new Error("Gmail message list is unavailable");
|
|
574
|
+
let parsed;
|
|
575
|
+
try {
|
|
576
|
+
parsed = MessageListSchema.parse(JSON.parse(Buffer.from(result.response.body).toString("utf8")));
|
|
577
|
+
} catch {
|
|
578
|
+
throw new Error("Gmail message list is invalid");
|
|
579
|
+
}
|
|
580
|
+
return { messages: (parsed.messages ?? []).map((message) => ({ id: message.id ?? "", threadId: message.threadId ?? "" })), credentials: result.credentials };
|
|
581
|
+
}
|
|
556
582
|
/** Search Sent Mail once for the run-specific RFC Message-ID. */
|
|
557
583
|
async findSentMessage(call, credentials, messageIdAddress, signal) {
|
|
558
584
|
const query = new URLSearchParams();
|
|
@@ -819,6 +845,7 @@ var ReplyToMessageOutcomes = {
|
|
|
819
845
|
sentBranch: ReplyToMessageBranch.Sent,
|
|
820
846
|
providerRejectedBranch: ReplyToMessageBranch.ProviderRejected
|
|
821
847
|
};
|
|
848
|
+
var MissingRunIDMessage = "the Dex call context has no run ID, so nothing was sent";
|
|
822
849
|
var GmailSendAttemptBudget = class {
|
|
823
850
|
/** Read-back cutoff in Unix milliseconds. */
|
|
824
851
|
attemptDeadline;
|
|
@@ -909,6 +936,8 @@ var GmailSender = class {
|
|
|
909
936
|
/** Send one new message under the Dex attempt deadline. */
|
|
910
937
|
async sendMessage(call, input, dexDeadline) {
|
|
911
938
|
if (call.context.attempt < 1) return defect("sendMessage", "LOCAL_DEFECT", "Dex Execute attempt number is invalid");
|
|
939
|
+
const messageIdAddress = this.#messageID(call);
|
|
940
|
+
if (!messageIdAddress) return defect("sendMessage", "LOCAL_DEFECT", MissingRunIDMessage);
|
|
912
941
|
const fence = newFence(call, SendMessageDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4);
|
|
913
942
|
if (fence.decide().kind === "failClosed") return defect("sendMessage", "LOCAL_DEFECT", "Dex send checkpoint is unreadable");
|
|
914
943
|
const budget = new GmailSendAttemptBudget(call.context.cancellationSignal, dexDeadline);
|
|
@@ -931,16 +960,18 @@ var GmailSender = class {
|
|
|
931
960
|
}
|
|
932
961
|
let raw;
|
|
933
962
|
try {
|
|
934
|
-
raw = buildMIMEMessage(call.id, call.idempotencyKey ?? call.id,
|
|
963
|
+
raw = buildMIMEMessage(call.id, call.idempotencyKey ?? call.id, messageIdAddress, credentials.primaryEmail, recipients, input.subject, input.textBody, input.htmlBody);
|
|
935
964
|
} catch {
|
|
936
965
|
return defect("sendMessage", "VALIDATION", "message could not be encoded");
|
|
937
966
|
}
|
|
938
967
|
if (raw.length > this.#http.settings().maxMessageBytes) return defect("sendMessage", "VALIDATION", "message exceeds configured size limit");
|
|
939
|
-
return this.#sendAndConfirm(call, fence, budget, credentials, SendMessageOutcomes, { raw, recipients, requestedThreadId: "", hasPreSendSearch: false });
|
|
968
|
+
return this.#sendAndConfirm(call, fence, budget, credentials, SendMessageOutcomes, { raw, recipients, requestedThreadId: "", hasPreSendSearch: false, messageIdAddress });
|
|
940
969
|
}
|
|
941
970
|
/** Read the source then reply in its Gmail thread under the Dex attempt deadline. */
|
|
942
971
|
async replyToMessage(call, input, dexDeadline) {
|
|
943
972
|
if (call.context.attempt < 1) return defect("replyToMessage", "LOCAL_DEFECT", "Dex Execute attempt number is invalid");
|
|
973
|
+
const messageIdAddress = this.#messageID(call);
|
|
974
|
+
if (!messageIdAddress) return defect("replyToMessage", "LOCAL_DEFECT", MissingRunIDMessage);
|
|
944
975
|
const fence = newFence(call, ReplyToMessageDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4);
|
|
945
976
|
if (fence.decide().kind === "failClosed") return defect("replyToMessage", "LOCAL_DEFECT", "Dex send checkpoint is unreadable");
|
|
946
977
|
const budget = new GmailSendAttemptBudget(call.context.cancellationSignal, dexDeadline);
|
|
@@ -962,15 +993,15 @@ var GmailSender = class {
|
|
|
962
993
|
budget,
|
|
963
994
|
credentials,
|
|
964
995
|
ReplyToMessageOutcomes,
|
|
965
|
-
{ raw: new Uint8Array(), recipients: [], requestedThreadId: "", hasPreSendSearch: true },
|
|
996
|
+
{ raw: new Uint8Array(), recipients: [], requestedThreadId: "", hasPreSendSearch: true, messageIdAddress },
|
|
966
997
|
{ id: priorProviderId, threadId: "" },
|
|
967
998
|
this.#receipt(call, "", priorProviderId)
|
|
968
999
|
);
|
|
969
1000
|
}
|
|
970
1001
|
if (call.context.attempt > 1 || fence.decide().kind === "readBackRequired") {
|
|
971
1002
|
try {
|
|
972
|
-
const found = await this.#provider.findSentMessage(call, credentials,
|
|
973
|
-
if (found) return this.#sentMessage(call, budget, credentials, ReplyToMessageOutcomes, { raw: new Uint8Array(), recipients: [], requestedThreadId: "", hasPreSendSearch: true }, found, this.#receipt(call));
|
|
1003
|
+
const found = await this.#provider.findSentMessage(call, credentials, messageIdAddress, budget.preSendSignal());
|
|
1004
|
+
if (found) return this.#sentMessage(call, budget, credentials, ReplyToMessageOutcomes, { raw: new Uint8Array(), recipients: [], requestedThreadId: "", hasPreSendSearch: true, messageIdAddress }, found, this.#receipt(call));
|
|
974
1005
|
} catch {
|
|
975
1006
|
await recordPreSendRetry(fence);
|
|
976
1007
|
return newMutationRetry(failure("replyToMessage", "AVAILABILITY", "Gmail sent-mail search did not answer before the reply"));
|
|
@@ -1010,12 +1041,12 @@ var GmailSender = class {
|
|
|
1010
1041
|
if (/[\r\n]/.test(message.subject + message.rfcMessageId + (message.references ?? ""))) return newMutationBranch(ReplyToMessageBranch.InvalidResponse, emptySend(), this.#receipt(call, gmailRequestID(source.response.headers), input.messageId), failure("replyToMessage", "PROTOCOL", "Gmail returned invalid source reply headers"));
|
|
1011
1042
|
let raw;
|
|
1012
1043
|
try {
|
|
1013
|
-
raw = buildReplyMIMEMessage(call.id, call.idempotencyKey ?? call.id,
|
|
1044
|
+
raw = buildReplyMIMEMessage(call.id, call.idempotencyKey ?? call.id, messageIdAddress, credentials.primaryEmail, message, input);
|
|
1014
1045
|
} catch {
|
|
1015
1046
|
return defect("replyToMessage", "VALIDATION", "reply could not be encoded within the configured limit");
|
|
1016
1047
|
}
|
|
1017
1048
|
if (raw.length > this.#http.settings().maxMessageBytes) return defect("replyToMessage", "VALIDATION", "reply could not be encoded within the configured limit");
|
|
1018
|
-
return this.#sendAndConfirm(call, fence, budget, credentials, ReplyToMessageOutcomes, { raw, recipients: [recipient], requestedThreadId: message.threadId, hasPreSendSearch: call.context.attempt > 1 });
|
|
1049
|
+
return this.#sendAndConfirm(call, fence, budget, credentials, ReplyToMessageOutcomes, { raw, recipients: [recipient], requestedThreadId: message.threadId, hasPreSendSearch: call.context.attempt > 1, messageIdAddress });
|
|
1019
1050
|
}
|
|
1020
1051
|
async #sendAndConfirm(call, fence, budget, credentials, operation, message) {
|
|
1021
1052
|
const priorProviderId = fence.decide().marker?.providerId;
|
|
@@ -1032,7 +1063,7 @@ var GmailSender = class {
|
|
|
1032
1063
|
}
|
|
1033
1064
|
if ((call.context.attempt > 1 || fence.decide().kind === "readBackRequired") && !message.hasPreSendSearch) {
|
|
1034
1065
|
try {
|
|
1035
|
-
const found = await this.#provider.findSentMessage(call, credentials,
|
|
1066
|
+
const found = await this.#provider.findSentMessage(call, credentials, message.messageIdAddress, budget.preSendSignal());
|
|
1036
1067
|
if (found) return this.#sentMessage(call, budget, credentials, operation, message, found, this.#receipt(call));
|
|
1037
1068
|
} catch {
|
|
1038
1069
|
await recordPreSendRetry(fence);
|
|
@@ -1064,7 +1095,7 @@ var GmailSender = class {
|
|
|
1064
1095
|
return retryAfterRefusal(operation.operationId, "RATE_LIMIT", `Gmail temporarily rejected the ${operation.requestName}`, headers);
|
|
1065
1096
|
}
|
|
1066
1097
|
if (status === 503) {
|
|
1067
|
-
const lookup = await this.#pollSentMessage(call, budget, credentials);
|
|
1098
|
+
const lookup = await this.#pollSentMessage(call, budget, credentials, message);
|
|
1068
1099
|
if (lookup.sent) return this.#sentAfterDispatch(call, fence, budget, credentials, operation, message, lookup.sent, receipt);
|
|
1069
1100
|
return retryAfterRefusal(operation.operationId, "AVAILABILITY", `Gmail ${operation.requestName} is temporarily unavailable`, headers);
|
|
1070
1101
|
}
|
|
@@ -1072,7 +1103,7 @@ var GmailSender = class {
|
|
|
1072
1103
|
if (status < 200 || status >= 300) {
|
|
1073
1104
|
if (call.context.attempt > 1) {
|
|
1074
1105
|
try {
|
|
1075
|
-
const found = await this.#provider.findSentMessage(call, credentials,
|
|
1106
|
+
const found = await this.#provider.findSentMessage(call, credentials, message.messageIdAddress, budget.attemptSignal());
|
|
1076
1107
|
if (found) return this.#sentMessage(call, budget, credentials, operation, message, found, receipt);
|
|
1077
1108
|
} catch {
|
|
1078
1109
|
}
|
|
@@ -1080,14 +1111,14 @@ var GmailSender = class {
|
|
|
1080
1111
|
return newMutationBranch(operation.providerRejectedBranch, emptySend(), receipt, failure(operation.operationId, statusFailureKind(status), operation.rejectionMessage));
|
|
1081
1112
|
}
|
|
1082
1113
|
if (!sentResponse) {
|
|
1083
|
-
const lookup = await this.#pollSentMessage(call, budget, credentials);
|
|
1114
|
+
const lookup = await this.#pollSentMessage(call, budget, credentials, message);
|
|
1084
1115
|
if (lookup.sent) return this.#sentAfterDispatch(call, fence, budget, credentials, operation, message, lookup.sent, receipt);
|
|
1085
1116
|
return this.#sentMessage(call, budget, credentials, operation, message, { id: "", threadId: message.requestedThreadId }, receipt);
|
|
1086
1117
|
}
|
|
1087
1118
|
return this.#sentMessage(call, budget, credentials, operation, message, sentResponse, receipt);
|
|
1088
1119
|
}
|
|
1089
1120
|
async #confirmPossiblySent(call, fence, budget, credentials, operation, message, kind, reason, receipt) {
|
|
1090
|
-
const lookup = await this.#pollSentMessage(call, budget, credentials);
|
|
1121
|
+
const lookup = await this.#pollSentMessage(call, budget, credentials, message);
|
|
1091
1122
|
if (lookup.sent) return this.#sentAfterDispatch(call, fence, budget, credentials, operation, message, lookup.sent, receipt);
|
|
1092
1123
|
const suffix = lookup.hadError ? "the sent-mail search did not answer" : "the sent-mail search found no message";
|
|
1093
1124
|
return newMutationRetry(failure(operation.operationId, kind, `${reason}; ${suffix}`));
|
|
@@ -1108,7 +1139,7 @@ var GmailSender = class {
|
|
|
1108
1139
|
}
|
|
1109
1140
|
return newMutationBranch(operation.sentBranch, { sender: credentials.primaryEmail, recipients: message.recipients, messageId: sent.id, threadId }, { ...receipt, providerObjectId: sent.id });
|
|
1110
1141
|
}
|
|
1111
|
-
async #pollSentMessage(call, budget, credentials) {
|
|
1142
|
+
async #pollSentMessage(call, budget, credentials, message) {
|
|
1112
1143
|
let hadError = false;
|
|
1113
1144
|
for (let lookup = 0; lookup < 4; lookup++) {
|
|
1114
1145
|
if (lookup > 0) {
|
|
@@ -1119,7 +1150,7 @@ var GmailSender = class {
|
|
|
1119
1150
|
}
|
|
1120
1151
|
}
|
|
1121
1152
|
try {
|
|
1122
|
-
const found = await this.#provider.findSentMessage(call, credentials,
|
|
1153
|
+
const found = await this.#provider.findSentMessage(call, credentials, message.messageIdAddress, budget.attemptSignal());
|
|
1123
1154
|
if (found) return { sent: found, hadError: false };
|
|
1124
1155
|
hadError = false;
|
|
1125
1156
|
} catch {
|
|
@@ -1130,7 +1161,9 @@ var GmailSender = class {
|
|
|
1130
1161
|
return { hadError };
|
|
1131
1162
|
}
|
|
1132
1163
|
#messageID(call) {
|
|
1133
|
-
|
|
1164
|
+
const { runId, flowStartedAt } = call.context;
|
|
1165
|
+
if (typeof runId !== "string" || !runId) return void 0;
|
|
1166
|
+
return rfcMessageIDAddress(call.idempotencyKey ?? call.id, runId, flowStartedAt);
|
|
1134
1167
|
}
|
|
1135
1168
|
#receipt(call, requestId = "", objectId = "") {
|
|
1136
1169
|
return { callId: call.id, ...call.idempotencyKey ? { idempotencyKey: call.idempotencyKey } : {}, provider: "gmail", providerObjectId: objectId, providerRequestId: requestId, observedAt: this.#now().toISOString() };
|
|
@@ -1179,6 +1212,7 @@ function classifySourceFailure(status, headers, receipt) {
|
|
|
1179
1212
|
|
|
1180
1213
|
// src/client.ts
|
|
1181
1214
|
import {
|
|
1215
|
+
defaultTriggerLogger,
|
|
1182
1216
|
newQueryBranch,
|
|
1183
1217
|
newQueryRetry,
|
|
1184
1218
|
zeroReceipt as zeroReceipt2
|
|
@@ -1189,12 +1223,19 @@ var GmailClient = class {
|
|
|
1189
1223
|
#provider;
|
|
1190
1224
|
#sender;
|
|
1191
1225
|
#now;
|
|
1226
|
+
/** Trigger record destination. */
|
|
1227
|
+
triggerLogger;
|
|
1192
1228
|
/** Validate settings and inject a host-owned credential source. */
|
|
1193
1229
|
constructor(config, credentials, options = {}) {
|
|
1194
1230
|
this.#http = new GmailHTTPClient(config, credentials, options.refreshDriver ?? new GmailCredentialRefreshDriver(), options.transport);
|
|
1195
1231
|
this.#provider = new GmailProvider(this.#http);
|
|
1196
1232
|
this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
1197
1233
|
this.#sender = new GmailSender(this.#http, this.#provider, this.#now);
|
|
1234
|
+
this.triggerLogger = options.logger ?? defaultTriggerLogger;
|
|
1235
|
+
}
|
|
1236
|
+
/** @internal The authenticated transport and provider methods that the Trigger pollers share. */
|
|
1237
|
+
triggerTransport() {
|
|
1238
|
+
return { http: this.#http, provider: this.#provider };
|
|
1198
1239
|
}
|
|
1199
1240
|
/** Return the getMessage Query bound to this connection. */
|
|
1200
1241
|
getMessage() {
|
|
@@ -1461,6 +1502,389 @@ function newReplyToMessageStep2(configuration) {
|
|
|
1461
1502
|
return newReplyToMessageStep(configuration);
|
|
1462
1503
|
}
|
|
1463
1504
|
|
|
1505
|
+
// src/trigger.ts
|
|
1506
|
+
import {
|
|
1507
|
+
mustTriggerBindingDefinition,
|
|
1508
|
+
newTrigger
|
|
1509
|
+
} from "@superdurable/connectors-sdk";
|
|
1510
|
+
import { decodeTriggerConfiguration, newDurableTriggerTarget, parseTriggerPayloadJSON } from "@superdurable/connectors-sdk/projectconfig";
|
|
1511
|
+
import { z as z6 } from "zod";
|
|
1512
|
+
|
|
1513
|
+
// src/trigger_source.ts
|
|
1514
|
+
import { createHash as createHash2 } from "crypto";
|
|
1515
|
+
import {
|
|
1516
|
+
TriggerDeliveryAbortedError,
|
|
1517
|
+
createTriggerCall,
|
|
1518
|
+
isTriggerUndeliverable,
|
|
1519
|
+
logTriggerRecord,
|
|
1520
|
+
prepareTriggerDelivery,
|
|
1521
|
+
throwIfTriggerAborted,
|
|
1522
|
+
triggerAttempt,
|
|
1523
|
+
triggerErrorAttributes,
|
|
1524
|
+
waitForTriggerDelay,
|
|
1525
|
+
withTriggerLogAttributes,
|
|
1526
|
+
withTriggerLoggerAttributes
|
|
1527
|
+
} from "@superdurable/connectors-sdk";
|
|
1528
|
+
var GmailPollError = class extends Error {
|
|
1529
|
+
constructor(message, cause) {
|
|
1530
|
+
super(message, cause === void 0 ? void 0 : { cause });
|
|
1531
|
+
this.name = "GmailPollError";
|
|
1532
|
+
}
|
|
1533
|
+
};
|
|
1534
|
+
var uuidNamespaceURL = Buffer.from("6ba7b8119dad11d180b400c04fd430c8", "hex");
|
|
1535
|
+
var MessagePollingTriggerSource = class {
|
|
1536
|
+
#client;
|
|
1537
|
+
#connection;
|
|
1538
|
+
#searchQuery;
|
|
1539
|
+
#matcher;
|
|
1540
|
+
#requiresReply;
|
|
1541
|
+
#logger;
|
|
1542
|
+
#triggerName;
|
|
1543
|
+
#delivered = /* @__PURE__ */ new Set();
|
|
1544
|
+
// Every later poll delivers this event before any listed message, until the target consumes it.
|
|
1545
|
+
#retry;
|
|
1546
|
+
#pollFailures = 0;
|
|
1547
|
+
/** Bind one binding's query and matcher; an empty bindingName omits the binding log attribute. */
|
|
1548
|
+
constructor(client, connection, triggerName, bindingName, searchQuery, matcher, requiresReply) {
|
|
1549
|
+
this.#client = client;
|
|
1550
|
+
this.#connection = connection;
|
|
1551
|
+
this.#triggerName = triggerName;
|
|
1552
|
+
this.#searchQuery = searchQuery;
|
|
1553
|
+
this.#matcher = matcher;
|
|
1554
|
+
this.#requiresReply = requiresReply;
|
|
1555
|
+
this.#logger = withTriggerLoggerAttributes(client.triggerLogger, { connector: ConnectorID, connection: connection.name, trigger: triggerName, ...bindingName ? { binding: bindingName } : {} });
|
|
1556
|
+
}
|
|
1557
|
+
/** Scan, then wait one poll interval, until the context ends. */
|
|
1558
|
+
async run(context, target) {
|
|
1559
|
+
await runMessageTriggerRoutes(context, () => this.scan(context, target), this.#pollIntervalMs());
|
|
1560
|
+
}
|
|
1561
|
+
/** List the inbox and deliver the listed messages. */
|
|
1562
|
+
async scan(context, target) {
|
|
1563
|
+
await this.deliver(context, target, await this.list(context));
|
|
1564
|
+
}
|
|
1565
|
+
/** Read the newest inbox page that matches the source's search query. */
|
|
1566
|
+
async list(context) {
|
|
1567
|
+
const { http, provider } = this.#client.triggerTransport();
|
|
1568
|
+
const call = this.#credentialCall(context.signal);
|
|
1569
|
+
let credentials;
|
|
1570
|
+
try {
|
|
1571
|
+
credentials = await http.resolveCredentials(call, context.signal);
|
|
1572
|
+
} catch (error) {
|
|
1573
|
+
throw this.#pollFailed(context, new GmailPollError("Gmail Trigger credentials are unavailable", error));
|
|
1574
|
+
}
|
|
1575
|
+
try {
|
|
1576
|
+
const listed = await provider.listInboxMessages(call, credentials, this.#searchQuery, http.settings().pollPageSize, context.signal);
|
|
1577
|
+
return { credentials: listed.credentials, messages: listed.messages };
|
|
1578
|
+
} catch (error) {
|
|
1579
|
+
throw this.#pollFailed(context, new GmailPollError("Gmail message list is unavailable", error));
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
1582
|
+
/**
|
|
1583
|
+
* Hand target the event that failed on an earlier poll, if any, then every new matching message in
|
|
1584
|
+
* listing, oldest first. It stops at the first failure, so the next poll retries that event before any
|
|
1585
|
+
* later message, even after newer mail pushes it off the listed page.
|
|
1586
|
+
*/
|
|
1587
|
+
async deliver(context, target, listing) {
|
|
1588
|
+
if (this.#retry) await this.#handle(context, target, this.#retry.event);
|
|
1589
|
+
const { provider } = this.#client.triggerTransport();
|
|
1590
|
+
let credentials = listing.credentials;
|
|
1591
|
+
const current = /* @__PURE__ */ new Set();
|
|
1592
|
+
for (let index = listing.messages.length - 1; index >= 0; index--) {
|
|
1593
|
+
const reference = listing.messages[index];
|
|
1594
|
+
if (!reference.id) continue;
|
|
1595
|
+
current.add(reference.id);
|
|
1596
|
+
if (this.#delivered.has(reference.id)) continue;
|
|
1597
|
+
const messageAttributes = { thread_id: reference.threadId, event_id: reference.id };
|
|
1598
|
+
let message;
|
|
1599
|
+
try {
|
|
1600
|
+
const read = await provider.readMessage(this.#credentialCall(context.signal), credentials, reference.id, "metadata", context.signal);
|
|
1601
|
+
credentials = read.credentials;
|
|
1602
|
+
if (!read.resource) throw new GmailPollError("Gmail message lookup failed");
|
|
1603
|
+
message = decodeGmailMessage(read.resource);
|
|
1604
|
+
} catch (error) {
|
|
1605
|
+
throw this.#pollFailed(context, error instanceof GmailPollError ? error : new GmailPollError("Gmail message lookup failed", error), messageAttributes);
|
|
1606
|
+
}
|
|
1607
|
+
const isReply = (message.inReplyTo ?? "").trim() !== "" || (message.references ?? "").trim() !== "";
|
|
1608
|
+
const reason = this.#ignoreReason(isReply, message);
|
|
1609
|
+
if (reason) {
|
|
1610
|
+
this.#log(context, "debug", "trigger event ignored", { ...messageAttributes, reason });
|
|
1611
|
+
continue;
|
|
1612
|
+
}
|
|
1613
|
+
const event = {
|
|
1614
|
+
id: message.messageId,
|
|
1615
|
+
occurredAt: new Date(message.receivedAt),
|
|
1616
|
+
payload: {
|
|
1617
|
+
primaryEmail: credentials.primaryEmail,
|
|
1618
|
+
messageId: message.messageId,
|
|
1619
|
+
threadId: message.threadId,
|
|
1620
|
+
from: message.from,
|
|
1621
|
+
subject: message.subject,
|
|
1622
|
+
...message.snippet ? { snippet: message.snippet } : {},
|
|
1623
|
+
receivedAt: message.receivedAt,
|
|
1624
|
+
isReply
|
|
1625
|
+
}
|
|
1626
|
+
};
|
|
1627
|
+
try {
|
|
1628
|
+
await prepareTriggerDelivery(context, target, event);
|
|
1629
|
+
} catch (error) {
|
|
1630
|
+
throw this.#pollFailed(context, new GmailPollError("Gmail Trigger delivery could not be recorded", error), messageAttributes);
|
|
1631
|
+
}
|
|
1632
|
+
await this.#handle(context, target, event);
|
|
1633
|
+
}
|
|
1634
|
+
this.#delivered = current;
|
|
1635
|
+
this.#pollFailures = 0;
|
|
1636
|
+
}
|
|
1637
|
+
#pollIntervalMs() {
|
|
1638
|
+
return this.#client.triggerTransport().http.settings().pollIntervalMs;
|
|
1639
|
+
}
|
|
1640
|
+
/**
|
|
1641
|
+
* Make one delivery attempt and log its outcome. It resolves when target consumes the event, and
|
|
1642
|
+
* otherwise keeps the event as the source's retry and rethrows. A durable inbox or a newTrigger runner
|
|
1643
|
+
* logs the undeliverable events it consumes itself, so the source then logs no recovery.
|
|
1644
|
+
*/
|
|
1645
|
+
async #handle(context, target, event) {
|
|
1646
|
+
const failures = this.#retry?.event.id === event.id ? this.#retry.failures : 0;
|
|
1647
|
+
const threadAttributes = { thread_id: event.payload.threadId };
|
|
1648
|
+
const messageAttributes = { ...threadAttributes, event_id: event.id };
|
|
1649
|
+
const attempt = triggerAttempt(withTriggerLogAttributes(context, threadAttributes));
|
|
1650
|
+
try {
|
|
1651
|
+
await target.handleTrigger(attempt.context, event);
|
|
1652
|
+
if (failures > 0 && !attempt.wasSkipped()) this.#log(context, "info", "trigger delivered after retry", { ...messageAttributes, attempts: failures + 1 });
|
|
1653
|
+
} catch (error) {
|
|
1654
|
+
if (isTriggerUndeliverable(error)) {
|
|
1655
|
+
this.#log(context, "warn", "trigger event skipped: undeliverable", { ...messageAttributes, ...triggerErrorAttributes(error) });
|
|
1656
|
+
} else if (context.signal.aborted) {
|
|
1657
|
+
throw error;
|
|
1658
|
+
} else {
|
|
1659
|
+
this.#pollFailures = 0;
|
|
1660
|
+
this.#retry = { event, failures: failures + 1 };
|
|
1661
|
+
this.#log(context, "warn", "trigger delivery failed; retrying", { ...messageAttributes, attempt: failures + 1, delay_ms: this.#pollIntervalMs(), ...triggerErrorAttributes(error) });
|
|
1662
|
+
throw error;
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
this.#retry = void 0;
|
|
1666
|
+
this.#delivered.add(event.id);
|
|
1667
|
+
}
|
|
1668
|
+
/** Explain why the source does not deliver a listed message, or return '' when it matches. */
|
|
1669
|
+
#ignoreReason(isReply, message) {
|
|
1670
|
+
if (this.#requiresReply && !isReply) return "not_a_reply";
|
|
1671
|
+
if (!this.#requiresReply && isReply) return "not_a_root";
|
|
1672
|
+
if (!messageMatcherMatches(this.#matcher, message)) return "matcher_mismatch";
|
|
1673
|
+
return "";
|
|
1674
|
+
}
|
|
1675
|
+
/** Log a poll that ended early and return error; the next poll, one interval later, retries. */
|
|
1676
|
+
#pollFailed(context, error, attributes = {}) {
|
|
1677
|
+
if (context.signal.aborted) return new TriggerDeliveryAbortedError();
|
|
1678
|
+
this.#pollFailures++;
|
|
1679
|
+
const causeAttributes = error.cause === void 0 ? {} : { error_cause_type: triggerErrorAttributes(error.cause).error_type ?? "Error" };
|
|
1680
|
+
this.#log(context, "warn", "gmail poll failed; retrying", { ...attributes, attempt: this.#pollFailures, delay_ms: this.#pollIntervalMs(), error: error.message, ...causeAttributes });
|
|
1681
|
+
return error;
|
|
1682
|
+
}
|
|
1683
|
+
#log(context, level, message, attributes) {
|
|
1684
|
+
logTriggerRecord(this.#logger, context, level, message, attributes);
|
|
1685
|
+
}
|
|
1686
|
+
/** The Go connector's stable credential call: a version 5 UUID of the connection and Trigger. */
|
|
1687
|
+
#credentialCall(signal) {
|
|
1688
|
+
const identity = ["https://superdurable.dev/dex-connectors/trigger-credential/v1", this.#connection.provider, this.#connection.name, this.#triggerName].join("/");
|
|
1689
|
+
return createTriggerCall(this.#connection, { connectorId: ConnectorID, operationId: this.#triggerName }, nameBasedUUID(identity), signal);
|
|
1690
|
+
}
|
|
1691
|
+
};
|
|
1692
|
+
function messageMatcherMatches(matcher, message) {
|
|
1693
|
+
if (matcher.messageContains) {
|
|
1694
|
+
const haystack = `${message.subject}
|
|
1695
|
+
${message.snippet ?? ""}`.toLowerCase();
|
|
1696
|
+
if (!haystack.includes(matcher.messageContains.toLowerCase())) return false;
|
|
1697
|
+
}
|
|
1698
|
+
const senders = matcher.senderEmails ?? [];
|
|
1699
|
+
if (senders.length === 0) return true;
|
|
1700
|
+
const sender = parseMailbox(message.from)?.address.toLowerCase();
|
|
1701
|
+
if (!sender) return false;
|
|
1702
|
+
return senders.some((allowed) => parseMailbox(allowed)?.address.toLowerCase() === sender);
|
|
1703
|
+
}
|
|
1704
|
+
async function runMessageTriggerRoutes(context, poll, intervalMs) {
|
|
1705
|
+
for (; ; ) {
|
|
1706
|
+
throwIfTriggerAborted(context.signal);
|
|
1707
|
+
try {
|
|
1708
|
+
await poll();
|
|
1709
|
+
} catch {
|
|
1710
|
+
throwIfTriggerAborted(context.signal);
|
|
1711
|
+
}
|
|
1712
|
+
await waitForTriggerDelay(context.signal, intervalMs);
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
async function pollMessageTriggerRoutes(context, rootRoutes, replyRoutes) {
|
|
1716
|
+
const replyListings = [];
|
|
1717
|
+
for (const route of replyRoutes) replyListings.push(await route.source.list(context));
|
|
1718
|
+
for (const route of rootRoutes) await route.source.scan(context, route.target);
|
|
1719
|
+
for (const [index, route] of replyRoutes.entries()) await route.source.deliver(context, route.target, replyListings[index]);
|
|
1720
|
+
}
|
|
1721
|
+
async function replayMessageTriggerRoutes(context, routes) {
|
|
1722
|
+
for (const route of routes) {
|
|
1723
|
+
if (!route.target.replayTriggerDeliveries) continue;
|
|
1724
|
+
try {
|
|
1725
|
+
await route.target.replayTriggerDeliveries(context);
|
|
1726
|
+
} catch (error) {
|
|
1727
|
+
if (error instanceof TriggerDeliveryAbortedError) throw error;
|
|
1728
|
+
throw new Error(`replay Gmail Trigger deliveries: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
function nameBasedUUID(name) {
|
|
1733
|
+
const bytes = createHash2("sha1").update(uuidNamespaceURL).update(name, "utf8").digest().subarray(0, 16);
|
|
1734
|
+
bytes[6] = bytes[6] & 15 | 80;
|
|
1735
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
1736
|
+
const hex = bytes.toString("hex");
|
|
1737
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
// src/trigger.ts
|
|
1741
|
+
var MessageMatcherSchema = z6.strictObject({
|
|
1742
|
+
/** Case-insensitive substring of the subject or snippet, required when non-empty. */
|
|
1743
|
+
messageContains: z6.string().optional(),
|
|
1744
|
+
/** Sender addresses allowed to match when non-empty; compared case-insensitively. */
|
|
1745
|
+
senderEmails: z6.array(z6.string()).nullable().optional()
|
|
1746
|
+
});
|
|
1747
|
+
var MessageReceivedTriggerConfigurationSchema = z6.strictObject({ searchQuery: z6.string().optional(), messageMatcher: MessageMatcherSchema.optional() }).superRefine((configuration, context) => validateMessageMatcher(configuration.messageMatcher, context));
|
|
1748
|
+
var ReplyReceivedTriggerConfigurationSchema = z6.strictObject({ searchQuery: z6.string().optional(), replyMatcher: MessageMatcherSchema.optional() }).superRefine((configuration, context) => validateMessageMatcher(configuration.replyMatcher, context));
|
|
1749
|
+
var MessageEventSchema = z6.object({
|
|
1750
|
+
/** Mailbox that received the message. */
|
|
1751
|
+
primaryEmail: z6.string(),
|
|
1752
|
+
/** Gmail message ID. */
|
|
1753
|
+
messageId: z6.string(),
|
|
1754
|
+
/** Gmail thread ID. */
|
|
1755
|
+
threadId: z6.string(),
|
|
1756
|
+
/** Sender header. */
|
|
1757
|
+
from: z6.string(),
|
|
1758
|
+
/** Decoded subject. */
|
|
1759
|
+
subject: z6.string(),
|
|
1760
|
+
/** Gmail snippet, omitted when empty. */
|
|
1761
|
+
snippet: z6.string().optional(),
|
|
1762
|
+
/** Receive time as RFC 3339 UTC. */
|
|
1763
|
+
receivedAt: z6.string(),
|
|
1764
|
+
/** Whether the message has In-Reply-To or References headers. */
|
|
1765
|
+
isReply: z6.boolean()
|
|
1766
|
+
});
|
|
1767
|
+
var MessageReceivedTriggerDefinition = { trigger: { connectorId: ConnectorID, triggerName: "messageReceived" }, description: "Receive a matching message that begins a Gmail thread." };
|
|
1768
|
+
var ReplyReceivedTriggerDefinition = { trigger: { connectorId: ConnectorID, triggerName: "replyReceived" }, description: "Receive a matching reply in an existing Gmail thread." };
|
|
1769
|
+
var UIUnitSearchQueryInput = "searchQueryInput";
|
|
1770
|
+
var UISearchQueryInputPortQuery = "query";
|
|
1771
|
+
var UIUnitEmailListInput = "emailListInput";
|
|
1772
|
+
var UIEmailListInputPortEmails = "emails";
|
|
1773
|
+
var UIUnitTextInput = "textInput";
|
|
1774
|
+
var UITextInputPortText = "text";
|
|
1775
|
+
function defineMessageReceivedTriggerBinding(config) {
|
|
1776
|
+
return mustTriggerBindingDefinition({ definition: MessageReceivedTriggerDefinition, ...config });
|
|
1777
|
+
}
|
|
1778
|
+
function defineReplyReceivedTriggerBinding(config) {
|
|
1779
|
+
return mustTriggerBindingDefinition({ definition: ReplyReceivedTriggerDefinition, ...config });
|
|
1780
|
+
}
|
|
1781
|
+
function newMessageReceivedTrigger(config) {
|
|
1782
|
+
const configuration = MessageReceivedTriggerConfigurationSchema.parse(config.configuration);
|
|
1783
|
+
return newStandaloneTrigger(config, MessageReceivedTriggerDefinition, configuration.searchQuery ?? "", configuration.messageMatcher ?? {}, false);
|
|
1784
|
+
}
|
|
1785
|
+
function newReplyReceivedTrigger(config) {
|
|
1786
|
+
const configuration = ReplyReceivedTriggerConfigurationSchema.parse(config.configuration);
|
|
1787
|
+
return newStandaloneTrigger(config, ReplyReceivedTriggerDefinition, configuration.searchQuery ?? "", configuration.replyMatcher ?? {}, true);
|
|
1788
|
+
}
|
|
1789
|
+
function newStandaloneTrigger(config, definition, searchQuery, matcher, requiresReply) {
|
|
1790
|
+
const client = gmailClientOf(config.connection);
|
|
1791
|
+
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}"`);
|
|
1792
|
+
const source = new MessagePollingTriggerSource(client, config.connection.reference, definition.trigger.triggerName, "", searchQuery, matcher, requiresReply);
|
|
1793
|
+
const triggerSource = { run: (context, target) => source.run(context, target) };
|
|
1794
|
+
return newTrigger({ definition, binding: { connection: config.connection.reference, trigger: definition.trigger, name: config.bindingName }, source: triggerSource, target: config.target, logger: client.triggerLogger });
|
|
1795
|
+
}
|
|
1796
|
+
var MessageTriggerRunner = class {
|
|
1797
|
+
#rootRoutes;
|
|
1798
|
+
#replyRoutes;
|
|
1799
|
+
#pollIntervalMs;
|
|
1800
|
+
/** @internal Use newMessageTriggerRunner or newProjectMessageTriggerRunner. */
|
|
1801
|
+
constructor(rootRoutes, replyRoutes, pollIntervalMs) {
|
|
1802
|
+
this.#rootRoutes = rootRoutes;
|
|
1803
|
+
this.#replyRoutes = replyRoutes;
|
|
1804
|
+
this.#pollIntervalMs = pollIntervalMs;
|
|
1805
|
+
}
|
|
1806
|
+
/**
|
|
1807
|
+
* Replay each route's durable inbox in order, roots first, then poll until the context ends. Each poll
|
|
1808
|
+
* lists every reply route before any root route, then delivers every root before any reply, and ends
|
|
1809
|
+
* at the first failure. Every later poll retries the failed event before that route's listed messages,
|
|
1810
|
+
* even after Gmail stops listing it. Gmail receives a thread's root before any reply to it, so the
|
|
1811
|
+
* root of every listed reply is in the later root listing and reaches Dex first.
|
|
1812
|
+
*
|
|
1813
|
+
* It logs through the client's logger: WARN "gmail poll failed; retrying" with the consecutive failed
|
|
1814
|
+
* polls as attempt and the poll interval as delay_ms when a list or read fails, WARN "trigger delivery
|
|
1815
|
+
* failed; retrying" with the attempt number when a target fails, INFO "trigger delivered after retry"
|
|
1816
|
+
* when a later poll delivers that message, DEBUG "trigger event ignored" with its reason, and the
|
|
1817
|
+
* durable inbox records. It rejects with TriggerDeliveryAbortedError once the context ends, and when
|
|
1818
|
+
* an inbox replay fails.
|
|
1819
|
+
*/
|
|
1820
|
+
async run(context) {
|
|
1821
|
+
await replayMessageTriggerRoutes(context, [...this.#rootRoutes, ...this.#replyRoutes]);
|
|
1822
|
+
await runMessageTriggerRoutes(context, () => pollMessageTriggerRoutes(context, this.#rootRoutes, this.#replyRoutes), this.#pollIntervalMs);
|
|
1823
|
+
}
|
|
1824
|
+
};
|
|
1825
|
+
function newMessageTriggerRunner(config) {
|
|
1826
|
+
const client = gmailClientOf(config.connection);
|
|
1827
|
+
const bindingKeys = /* @__PURE__ */ new Set();
|
|
1828
|
+
const route = (triggerName, bindingName, target, searchQuery, matcher, requiresReply) => {
|
|
1829
|
+
const trimmedBindingName = bindingName?.trim();
|
|
1830
|
+
if (!trimmedBindingName || !target) throw new TypeError("Gmail message Trigger binding name and target are required");
|
|
1831
|
+
const bindingKey = `${triggerName}\0${trimmedBindingName}`;
|
|
1832
|
+
if (bindingKeys.has(bindingKey)) throw new TypeError(`Gmail message Trigger binding name "${trimmedBindingName}" is duplicated`);
|
|
1833
|
+
bindingKeys.add(bindingKey);
|
|
1834
|
+
return { source: new MessagePollingTriggerSource(client, config.connection.reference, triggerName, bindingName, searchQuery ?? "", matcher ?? {}, requiresReply), target };
|
|
1835
|
+
};
|
|
1836
|
+
const rootRoutes = (config.messageReceivedRoutes ?? []).map((root) => {
|
|
1837
|
+
const configuration = MessageReceivedTriggerConfigurationSchema.parse(root.configuration);
|
|
1838
|
+
return route("messageReceived", root.bindingName, root.target, configuration.searchQuery, configuration.messageMatcher, false);
|
|
1839
|
+
});
|
|
1840
|
+
const replyRoutes = (config.replyReceivedRoutes ?? []).map((reply) => {
|
|
1841
|
+
const configuration = ReplyReceivedTriggerConfigurationSchema.parse(reply.configuration);
|
|
1842
|
+
return route("replyReceived", reply.bindingName, reply.target, configuration.searchQuery, configuration.replyMatcher, true);
|
|
1843
|
+
});
|
|
1844
|
+
if (rootRoutes.length + replyRoutes.length === 0) throw new TypeError("Gmail message Trigger routes are required");
|
|
1845
|
+
return new MessageTriggerRunner(rootRoutes, replyRoutes, client.triggerTransport().http.settings().pollIntervalMs);
|
|
1846
|
+
}
|
|
1847
|
+
function newProjectMessageTriggerRunner(project, connectionName, config, options = {}) {
|
|
1848
|
+
const connection = newProjectConnection(project, connectionName, options);
|
|
1849
|
+
const client = gmailClientOf(connection);
|
|
1850
|
+
const durable = (triggerName, bindingName, target, schema) => {
|
|
1851
|
+
const key = { connectorId: ConnectorID, connectionName, triggerName, bindingName };
|
|
1852
|
+
let configuration;
|
|
1853
|
+
try {
|
|
1854
|
+
configuration = decodeTriggerConfiguration(project.configuration, key, schema);
|
|
1855
|
+
} catch (error) {
|
|
1856
|
+
throw new Error(`gmail ${triggerName} binding "${bindingName}" configuration: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1857
|
+
}
|
|
1858
|
+
const durableTarget = newDurableTriggerTarget(project.triggerInbox(key), key, target, { logger: client.triggerLogger, decodePayload: (_payloadJSON, payloadBytes) => MessageEventSchema.parse(parseTriggerPayloadJSON(payloadBytes)) });
|
|
1859
|
+
return { bindingName, configuration, target: durableTarget };
|
|
1860
|
+
};
|
|
1861
|
+
return newMessageTriggerRunner({
|
|
1862
|
+
connection,
|
|
1863
|
+
messageReceivedRoutes: (config.messageReceivedRoutes ?? []).map((route) => durable("messageReceived", route.bindingName, route.target, MessageReceivedTriggerConfigurationSchema)),
|
|
1864
|
+
replyReceivedRoutes: (config.replyReceivedRoutes ?? []).map((route) => durable("replyReceived", route.bindingName, route.target, ReplyReceivedTriggerConfigurationSchema))
|
|
1865
|
+
});
|
|
1866
|
+
}
|
|
1867
|
+
function gmailClientOf(connection) {
|
|
1868
|
+
if (!(connection?.operations instanceof GmailClient)) throw new TypeError("Gmail Triggers require a connection bound to a GmailClient");
|
|
1869
|
+
return connection.operations;
|
|
1870
|
+
}
|
|
1871
|
+
function validateMessageMatcher(matcher, context) {
|
|
1872
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1873
|
+
for (const sender of matcher?.senderEmails ?? []) {
|
|
1874
|
+
const address = parseMailbox(sender)?.address;
|
|
1875
|
+
if (!address) {
|
|
1876
|
+
context.addIssue({ code: "custom", message: "Gmail sender email is invalid" });
|
|
1877
|
+
return;
|
|
1878
|
+
}
|
|
1879
|
+
const canonical = address.toLowerCase();
|
|
1880
|
+
if (seen.has(canonical)) {
|
|
1881
|
+
context.addIssue({ code: "custom", message: "Gmail sender emails must be unique" });
|
|
1882
|
+
return;
|
|
1883
|
+
}
|
|
1884
|
+
seen.add(canonical);
|
|
1885
|
+
}
|
|
1886
|
+
}
|
|
1887
|
+
|
|
1464
1888
|
export {
|
|
1465
1889
|
GetMessageInputSchema,
|
|
1466
1890
|
MessageSchema,
|
|
@@ -1509,5 +1933,24 @@ export {
|
|
|
1509
1933
|
newProjectGmailClient,
|
|
1510
1934
|
newGetMessageStep2 as newGetMessageStep,
|
|
1511
1935
|
newSendMessageStep2 as newSendMessageStep,
|
|
1512
|
-
newReplyToMessageStep2 as newReplyToMessageStep
|
|
1936
|
+
newReplyToMessageStep2 as newReplyToMessageStep,
|
|
1937
|
+
MessageMatcherSchema,
|
|
1938
|
+
MessageReceivedTriggerConfigurationSchema,
|
|
1939
|
+
ReplyReceivedTriggerConfigurationSchema,
|
|
1940
|
+
MessageEventSchema,
|
|
1941
|
+
MessageReceivedTriggerDefinition,
|
|
1942
|
+
ReplyReceivedTriggerDefinition,
|
|
1943
|
+
UIUnitSearchQueryInput,
|
|
1944
|
+
UISearchQueryInputPortQuery,
|
|
1945
|
+
UIUnitEmailListInput,
|
|
1946
|
+
UIEmailListInputPortEmails,
|
|
1947
|
+
UIUnitTextInput,
|
|
1948
|
+
UITextInputPortText,
|
|
1949
|
+
defineMessageReceivedTriggerBinding,
|
|
1950
|
+
defineReplyReceivedTriggerBinding,
|
|
1951
|
+
newMessageReceivedTrigger,
|
|
1952
|
+
newReplyReceivedTrigger,
|
|
1953
|
+
MessageTriggerRunner,
|
|
1954
|
+
newMessageTriggerRunner,
|
|
1955
|
+
newProjectMessageTriggerRunner
|
|
1513
1956
|
};
|