@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/README.md +15 -3
- package/dex-connector.json +28 -4
- package/dist/{chunk-OKDZ42YK.js → chunk-ALVG4HS2.js} +500 -38
- package/dist/index.cjs +495 -31
- package/dist/index.d.cts +212 -5
- package/dist/index.d.ts +212 -5
- 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:
|
|
209
|
+
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 7, totalDurationMs: 3e5 } },
|
|
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:
|
|
231
|
+
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 7, totalDurationMs: 3e5 } },
|
|
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
|
}
|
|
@@ -405,7 +410,7 @@ function encodeSubject(value) {
|
|
|
405
410
|
}
|
|
406
411
|
|
|
407
412
|
// src/http.ts
|
|
408
|
-
import { resolveCredential, resolveCredentialAfterRejection } from "@superdurable/connectors-sdk";
|
|
413
|
+
import { ReauthorizationRequiredError, resolveCredential, resolveCredentialAfterRejection } from "@superdurable/connectors-sdk";
|
|
409
414
|
import {
|
|
410
415
|
BodyTooLargeError,
|
|
411
416
|
isHeaderSafeCredential,
|
|
@@ -419,14 +424,20 @@ function gmailClientSettings(config = {}) {
|
|
|
419
424
|
if (!Number.isSafeInteger(maxResponseBytes) || maxResponseBytes < 1 || !Number.isSafeInteger(maxMessageBytes) || maxMessageBytes < 1) {
|
|
420
425
|
throw new TypeError("Gmail response and message limits must be positive integers");
|
|
421
426
|
}
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
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 });
|
|
425
432
|
}
|
|
426
433
|
var GmailCredentialError = class extends Error {
|
|
427
|
-
|
|
434
|
+
/** True when only reconnection can repair the failure: reauthorization or invalid material. */
|
|
435
|
+
isPermanent;
|
|
436
|
+
/** Create a secret-safe credential failure; omitted permanence means permanent. */
|
|
437
|
+
constructor(isPermanent = true) {
|
|
428
438
|
super("connection credentials are unavailable");
|
|
429
439
|
this.name = "GmailCredentialError";
|
|
440
|
+
this.isPermanent = isPermanent;
|
|
430
441
|
}
|
|
431
442
|
};
|
|
432
443
|
var GmailHTTPClient = class {
|
|
@@ -448,13 +459,18 @@ var GmailHTTPClient = class {
|
|
|
448
459
|
}
|
|
449
460
|
/** Resolve a private token at call time; never put it in a receipt or Flow value. */
|
|
450
461
|
async resolveCredentials(call, signal) {
|
|
462
|
+
let credentials;
|
|
463
|
+
try {
|
|
464
|
+
credentials = await resolveCredential(this.#credentials, call, this.#refreshDriver, signal);
|
|
465
|
+
} catch (error) {
|
|
466
|
+
throw new GmailCredentialError(error instanceof ReauthorizationRequiredError);
|
|
467
|
+
}
|
|
451
468
|
try {
|
|
452
|
-
const credentials = await resolveCredential(this.#credentials, call, this.#refreshDriver, signal);
|
|
453
469
|
validateCredentials(credentials);
|
|
454
|
-
return credentials;
|
|
455
470
|
} catch {
|
|
456
471
|
throw new GmailCredentialError();
|
|
457
472
|
}
|
|
473
|
+
return credentials;
|
|
458
474
|
}
|
|
459
475
|
/** Send one authenticated request, refreshing at most once after a 401. */
|
|
460
476
|
async request(call, credentials, method, pathAndQuery, body, signal) {
|
|
@@ -530,6 +546,7 @@ function validateCredentials(credentials) {
|
|
|
530
546
|
import { z as z4 } from "zod";
|
|
531
547
|
var SentMessageSchema = z4.object({ id: z4.string().optional(), threadId: z4.string().optional() });
|
|
532
548
|
var SentSearchSchema = z4.object({ messages: z4.array(SentMessageSchema).nullish() });
|
|
549
|
+
var MessageListSchema = z4.object({ messages: z4.array(z4.object({ id: z4.string().nullish(), threadId: z4.string().nullish() })).nullish() });
|
|
533
550
|
var GmailProvider = class {
|
|
534
551
|
#http;
|
|
535
552
|
/** Bind the shared authenticated transport. */
|
|
@@ -554,6 +571,23 @@ var GmailProvider = class {
|
|
|
554
571
|
return result;
|
|
555
572
|
}
|
|
556
573
|
}
|
|
574
|
+
/**
|
|
575
|
+
* List the newest inbox page that matches searchQuery, as the Go Trigger poller does. It rejects with
|
|
576
|
+
* an error that names no query value when Gmail does not answer 2xx with a usable listing.
|
|
577
|
+
*/
|
|
578
|
+
async listInboxMessages(call, credentials, searchQuery, pageSize, signal) {
|
|
579
|
+
const query = new URLSearchParams({ labelIds: "INBOX", maxResults: String(pageSize) });
|
|
580
|
+
if (searchQuery.trim()) query.set("q", searchQuery);
|
|
581
|
+
const result = await this.#http.request(call, credentials, "GET", `/users/me/messages?${query.toString()}`, void 0, signal);
|
|
582
|
+
if (result.response.status < 200 || result.response.status >= 300) throw new Error("Gmail message list is unavailable");
|
|
583
|
+
let parsed;
|
|
584
|
+
try {
|
|
585
|
+
parsed = MessageListSchema.parse(JSON.parse(Buffer.from(result.response.body).toString("utf8")));
|
|
586
|
+
} catch {
|
|
587
|
+
throw new Error("Gmail message list is invalid");
|
|
588
|
+
}
|
|
589
|
+
return { messages: (parsed.messages ?? []).map((message) => ({ id: message.id ?? "", threadId: message.threadId ?? "" })), credentials: result.credentials };
|
|
590
|
+
}
|
|
557
591
|
/** Search Sent Mail once for the run-specific RFC Message-ID. */
|
|
558
592
|
async findSentMessage(call, credentials, messageIdAddress, signal) {
|
|
559
593
|
const query = new URLSearchParams();
|
|
@@ -590,7 +624,7 @@ function parseSentResponse(response) {
|
|
|
590
624
|
}
|
|
591
625
|
|
|
592
626
|
// src/refresh.ts
|
|
593
|
-
import { ReauthorizationRequiredError } from "@superdurable/connectors-sdk";
|
|
627
|
+
import { ReauthorizationRequiredError as ReauthorizationRequiredError2 } from "@superdurable/connectors-sdk";
|
|
594
628
|
import { isRefreshRequired, ManifestCredentialRefreshDriver } from "@superdurable/connectors-sdk/oauthtoken";
|
|
595
629
|
|
|
596
630
|
// src/generated/refresh.ts
|
|
@@ -774,7 +808,7 @@ var GmailCredentialRefreshDriver = class {
|
|
|
774
808
|
if (method !== WorkspaceDomainDelegationAuthMethodID) return this.#manifestDriver.refresh(state, signal);
|
|
775
809
|
this.#validateServiceAccountKey(credentials.serviceAccountKey?.reveal() ?? "");
|
|
776
810
|
const delegatedUser = (credentials.delegatedUser ?? "").trim();
|
|
777
|
-
if (!delegatedUser || !delegatedUser.includes("@")) throw new
|
|
811
|
+
if (!delegatedUser || !delegatedUser.includes("@")) throw new ReauthorizationRequiredError2();
|
|
778
812
|
const result = await this.#manifestDriver.refresh({ ...state, credentials: { ...credentials, delegatedUser } }, signal);
|
|
779
813
|
return { ...result, credentials: { ...result.credentials, delegatedUser: credentials.delegatedUser } };
|
|
780
814
|
}
|
|
@@ -785,20 +819,21 @@ var GmailCredentialRefreshDriver = class {
|
|
|
785
819
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new TypeError();
|
|
786
820
|
key = parsed;
|
|
787
821
|
} catch {
|
|
788
|
-
throw new
|
|
822
|
+
throw new ReauthorizationRequiredError2();
|
|
789
823
|
}
|
|
790
|
-
if (typeof key.client_email !== "string" || !key.client_email || typeof key.private_key !== "string" || !key.private_key || typeof key.token_uri !== "string" || !key.token_uri) throw new
|
|
824
|
+
if (typeof key.client_email !== "string" || !key.client_email || typeof key.private_key !== "string" || !key.private_key || typeof key.token_uri !== "string" || !key.token_uri) throw new ReauthorizationRequiredError2();
|
|
791
825
|
try {
|
|
792
826
|
const endpoint = new URL(key.token_uri);
|
|
793
827
|
if (endpoint.protocol !== "https:" || !endpoint.hostname) throw new TypeError();
|
|
794
828
|
} catch {
|
|
795
|
-
throw new
|
|
829
|
+
throw new ReauthorizationRequiredError2();
|
|
796
830
|
}
|
|
797
831
|
}
|
|
798
832
|
};
|
|
799
833
|
|
|
800
834
|
// src/send.ts
|
|
801
835
|
import {
|
|
836
|
+
definitionMaxSends,
|
|
802
837
|
newMutationBranch,
|
|
803
838
|
newMutationRetry,
|
|
804
839
|
zeroReceipt
|
|
@@ -913,7 +948,7 @@ var GmailSender = class {
|
|
|
913
948
|
if (call.context.attempt < 1) return defect("sendMessage", "LOCAL_DEFECT", "Dex Execute attempt number is invalid");
|
|
914
949
|
const messageIdAddress = this.#messageID(call);
|
|
915
950
|
if (!messageIdAddress) return defect("sendMessage", "LOCAL_DEFECT", MissingRunIDMessage);
|
|
916
|
-
const fence = newFence(call, SendMessageDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4);
|
|
951
|
+
const fence = newFence(call, SendMessageDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4, { maxSends: definitionMaxSends(SendMessageDefinition) });
|
|
917
952
|
if (fence.decide().kind === "failClosed") return defect("sendMessage", "LOCAL_DEFECT", "Dex send checkpoint is unreadable");
|
|
918
953
|
const budget = new GmailSendAttemptBudget(call.context.cancellationSignal, dexDeadline);
|
|
919
954
|
if (!budget.sendSignal()) {
|
|
@@ -923,8 +958,8 @@ var GmailSender = class {
|
|
|
923
958
|
let credentials;
|
|
924
959
|
try {
|
|
925
960
|
credentials = await this.#http.resolveCredentials(call, budget.attemptSignal());
|
|
926
|
-
} catch {
|
|
927
|
-
return
|
|
961
|
+
} catch (error) {
|
|
962
|
+
return unavailableCredentials(fence, "sendMessage", error);
|
|
928
963
|
}
|
|
929
964
|
let recipients;
|
|
930
965
|
try {
|
|
@@ -947,7 +982,7 @@ var GmailSender = class {
|
|
|
947
982
|
if (call.context.attempt < 1) return defect("replyToMessage", "LOCAL_DEFECT", "Dex Execute attempt number is invalid");
|
|
948
983
|
const messageIdAddress = this.#messageID(call);
|
|
949
984
|
if (!messageIdAddress) return defect("replyToMessage", "LOCAL_DEFECT", MissingRunIDMessage);
|
|
950
|
-
const fence = newFence(call, ReplyToMessageDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4);
|
|
985
|
+
const fence = newFence(call, ReplyToMessageDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4, { maxSends: definitionMaxSends(ReplyToMessageDefinition) });
|
|
951
986
|
if (fence.decide().kind === "failClosed") return defect("replyToMessage", "LOCAL_DEFECT", "Dex send checkpoint is unreadable");
|
|
952
987
|
const budget = new GmailSendAttemptBudget(call.context.cancellationSignal, dexDeadline);
|
|
953
988
|
if (!budget.sendSignal()) {
|
|
@@ -957,12 +992,12 @@ var GmailSender = class {
|
|
|
957
992
|
let credentials;
|
|
958
993
|
try {
|
|
959
994
|
credentials = await this.#http.resolveCredentials(call, budget.attemptSignal());
|
|
960
|
-
} catch {
|
|
961
|
-
return
|
|
995
|
+
} catch (error) {
|
|
996
|
+
return unavailableCredentials(fence, "replyToMessage", error);
|
|
962
997
|
}
|
|
963
998
|
if (!ReplyToMessageInputSchema.safeParse(input).success || !input.messageId.trim() || !input.textBody.trim()) return defect("replyToMessage", "VALIDATION", "message ID and text body are required");
|
|
964
999
|
const priorProviderId = fence.decide().marker?.providerId;
|
|
965
|
-
if (fence
|
|
1000
|
+
if (isReadBackDecision(fence) && priorProviderId) {
|
|
966
1001
|
return this.#sentMessage(
|
|
967
1002
|
call,
|
|
968
1003
|
budget,
|
|
@@ -978,8 +1013,10 @@ var GmailSender = class {
|
|
|
978
1013
|
const found = await this.#provider.findSentMessage(call, credentials, messageIdAddress, budget.preSendSignal());
|
|
979
1014
|
if (found) return this.#sentMessage(call, budget, credentials, ReplyToMessageOutcomes, { raw: new Uint8Array(), recipients: [], requestedThreadId: "", hasPreSendSearch: true, messageIdAddress }, found, this.#receipt(call));
|
|
980
1015
|
} catch {
|
|
981
|
-
|
|
982
|
-
|
|
1016
|
+
if (fence.decide().kind !== "readBackThenResendAllowed") {
|
|
1017
|
+
await recordPreSendRetry(fence);
|
|
1018
|
+
return newMutationRetry(failure("replyToMessage", "AVAILABILITY", "Gmail sent-mail search did not answer before the reply"));
|
|
1019
|
+
}
|
|
983
1020
|
}
|
|
984
1021
|
if (fence.decide().kind === "readBackRequired") return newMutationRetry(failure("replyToMessage", "AVAILABILITY", "Gmail reply outcome is unknown; the sent-mail search found no message"));
|
|
985
1022
|
}
|
|
@@ -990,13 +1027,13 @@ var GmailSender = class {
|
|
|
990
1027
|
if (error instanceof GmailCredentialError) return defect("replyToMessage", "AUTHENTICATION", "connection credentials are unavailable");
|
|
991
1028
|
const status = error instanceof BodyTooLargeError2 ? error.status ?? 0 : 0;
|
|
992
1029
|
const headers = error instanceof BodyTooLargeError2 ? error.headers ?? {} : {};
|
|
993
|
-
const result = classifySourceFailure(status, headers, this.#receipt(call));
|
|
1030
|
+
const result = classifySourceFailure(fence, status, headers, this.#receipt(call));
|
|
994
1031
|
if (result.kind === "retry") await recordPreSendRetry(fence);
|
|
995
1032
|
return result;
|
|
996
1033
|
}
|
|
997
1034
|
credentials = source.credentials;
|
|
998
1035
|
if (!source.resource) {
|
|
999
|
-
const result = classifySourceFailure(source.response.status, source.response.headers, this.#receipt(call, gmailRequestID(source.response.headers), input.messageId));
|
|
1036
|
+
const result = classifySourceFailure(fence, source.response.status, source.response.headers, this.#receipt(call, gmailRequestID(source.response.headers), input.messageId));
|
|
1000
1037
|
if (result.kind === "retry") await recordPreSendRetry(fence);
|
|
1001
1038
|
return result;
|
|
1002
1039
|
}
|
|
@@ -1004,16 +1041,16 @@ var GmailSender = class {
|
|
|
1004
1041
|
try {
|
|
1005
1042
|
message = decodeGmailMessage(source.resource);
|
|
1006
1043
|
} catch {
|
|
1007
|
-
return
|
|
1044
|
+
return rejectUnlessEarlierSendIsUnconfirmed(fence, ReplyToMessageBranch.InvalidResponse, this.#receipt(call, gmailRequestID(source.response.headers), input.messageId), failure("replyToMessage", "PROTOCOL", "source message lacks reply metadata"));
|
|
1008
1045
|
}
|
|
1009
|
-
if (!message.threadId || !message.rfcMessageId) return
|
|
1046
|
+
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"));
|
|
1010
1047
|
let recipient;
|
|
1011
1048
|
try {
|
|
1012
1049
|
recipient = replyRecipient(message);
|
|
1013
1050
|
} catch {
|
|
1014
|
-
return
|
|
1051
|
+
return rejectUnlessEarlierSendIsUnconfirmed(fence, ReplyToMessageBranch.InvalidResponse, this.#receipt(call, gmailRequestID(source.response.headers), input.messageId), failure("replyToMessage", "PROTOCOL", "Gmail returned an invalid source sender"));
|
|
1015
1052
|
}
|
|
1016
|
-
if (/[\r\n]/.test(message.subject + message.rfcMessageId + (message.references ?? ""))) return
|
|
1053
|
+
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"));
|
|
1017
1054
|
let raw;
|
|
1018
1055
|
try {
|
|
1019
1056
|
raw = buildReplyMIMEMessage(call.id, call.idempotencyKey ?? call.id, messageIdAddress, credentials.primaryEmail, message, input);
|
|
@@ -1025,7 +1062,7 @@ var GmailSender = class {
|
|
|
1025
1062
|
}
|
|
1026
1063
|
async #sendAndConfirm(call, fence, budget, credentials, operation, message) {
|
|
1027
1064
|
const priorProviderId = fence.decide().marker?.providerId;
|
|
1028
|
-
if (fence
|
|
1065
|
+
if (isReadBackDecision(fence) && priorProviderId) {
|
|
1029
1066
|
return this.#sentMessage(
|
|
1030
1067
|
call,
|
|
1031
1068
|
budget,
|
|
@@ -1041,8 +1078,10 @@ var GmailSender = class {
|
|
|
1041
1078
|
const found = await this.#provider.findSentMessage(call, credentials, message.messageIdAddress, budget.preSendSignal());
|
|
1042
1079
|
if (found) return this.#sentMessage(call, budget, credentials, operation, message, found, this.#receipt(call));
|
|
1043
1080
|
} catch {
|
|
1044
|
-
|
|
1045
|
-
|
|
1081
|
+
if (fence.decide().kind !== "readBackThenResendAllowed") {
|
|
1082
|
+
await recordPreSendRetry(fence);
|
|
1083
|
+
return newMutationRetry(failure(operation.operationId, "AVAILABILITY", `Gmail sent-mail search did not answer before the ${operation.requestName}`));
|
|
1084
|
+
}
|
|
1046
1085
|
}
|
|
1047
1086
|
}
|
|
1048
1087
|
if (fence.decide().kind === "readBackRequired") return newMutationRetry(failure(operation.operationId, "AVAILABILITY", `Gmail ${operation.requestName} outcome is unknown; the sent-mail search found no message`));
|
|
@@ -1083,7 +1122,7 @@ var GmailSender = class {
|
|
|
1083
1122
|
} catch {
|
|
1084
1123
|
}
|
|
1085
1124
|
}
|
|
1086
|
-
return
|
|
1125
|
+
return rejectUnlessEarlierSendIsUnconfirmed(fence, operation.providerRejectedBranch, receipt, failure(operation.operationId, statusFailureKind(status), operation.rejectionMessage));
|
|
1087
1126
|
}
|
|
1088
1127
|
if (!sentResponse) {
|
|
1089
1128
|
const lookup = await this.#pollSentMessage(call, budget, credentials, message);
|
|
@@ -1147,6 +1186,10 @@ var GmailSender = class {
|
|
|
1147
1186
|
function failure(operation, kind, message) {
|
|
1148
1187
|
return { kind, provider: "gmail", operation, message };
|
|
1149
1188
|
}
|
|
1189
|
+
function isReadBackDecision(fence) {
|
|
1190
|
+
const kind = fence.decide().kind;
|
|
1191
|
+
return kind === "readBackRequired" || kind === "readBackThenResendAllowed";
|
|
1192
|
+
}
|
|
1150
1193
|
async function recordPreSendRetry(fence) {
|
|
1151
1194
|
if (fence.decide().kind !== "sendAllowed") return;
|
|
1152
1195
|
try {
|
|
@@ -1179,14 +1222,24 @@ function retryAfterRefusal(operation, kind, message, headers) {
|
|
|
1179
1222
|
return newMutationRetry(failure(operation, "PROTOCOL", "Gmail returned an invalid Retry-After header"));
|
|
1180
1223
|
}
|
|
1181
1224
|
}
|
|
1182
|
-
function
|
|
1225
|
+
function unavailableCredentials(fence, operation, error) {
|
|
1226
|
+
const isPermanent = !(error instanceof GmailCredentialError) || error.isPermanent;
|
|
1227
|
+
if (!isPermanent && (fence.decide().priorSendUpperBound ?? 0) > 0) return newMutationRetry(failure(operation, "AUTHENTICATION", "Gmail credentials are temporarily unavailable; an earlier send may still be delivered"));
|
|
1228
|
+
return defect(operation, "AUTHENTICATION", "connection credentials are unavailable");
|
|
1229
|
+
}
|
|
1230
|
+
function rejectUnlessEarlierSendIsUnconfirmed(fence, branch, receipt, rejection) {
|
|
1231
|
+
if ((fence.decide().priorSendUpperBound ?? 0) > 0) return newMutationRetry({ ...rejection, message: `${rejection.message}; an earlier send may still be delivered` });
|
|
1232
|
+
return newMutationBranch(branch, emptySend(), receipt, rejection);
|
|
1233
|
+
}
|
|
1234
|
+
function classifySourceFailure(fence, status, headers, receipt) {
|
|
1183
1235
|
if (status === 0 || status === 429 || status >= 500) return retryAfterRefusal("replyToMessage", "AVAILABILITY", "Gmail source message is temporarily unavailable", headers);
|
|
1184
|
-
if (status >= 200 && status < 300) return
|
|
1185
|
-
return
|
|
1236
|
+
if (status >= 200 && status < 300) return rejectUnlessEarlierSendIsUnconfirmed(fence, ReplyToMessageBranch.InvalidResponse, receipt, failure("replyToMessage", "PROTOCOL", "Gmail returned an invalid source message response"));
|
|
1237
|
+
return rejectUnlessEarlierSendIsUnconfirmed(fence, ReplyToMessageBranch.ProviderRejected, receipt, failure("replyToMessage", statusFailureKind(status), "Gmail rejected the source message lookup"));
|
|
1186
1238
|
}
|
|
1187
1239
|
|
|
1188
1240
|
// src/client.ts
|
|
1189
1241
|
import {
|
|
1242
|
+
defaultTriggerLogger,
|
|
1190
1243
|
newQueryBranch,
|
|
1191
1244
|
newQueryRetry,
|
|
1192
1245
|
zeroReceipt as zeroReceipt2
|
|
@@ -1197,12 +1250,19 @@ var GmailClient = class {
|
|
|
1197
1250
|
#provider;
|
|
1198
1251
|
#sender;
|
|
1199
1252
|
#now;
|
|
1253
|
+
/** Trigger record destination. */
|
|
1254
|
+
triggerLogger;
|
|
1200
1255
|
/** Validate settings and inject a host-owned credential source. */
|
|
1201
1256
|
constructor(config, credentials, options = {}) {
|
|
1202
1257
|
this.#http = new GmailHTTPClient(config, credentials, options.refreshDriver ?? new GmailCredentialRefreshDriver(), options.transport);
|
|
1203
1258
|
this.#provider = new GmailProvider(this.#http);
|
|
1204
1259
|
this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
1205
1260
|
this.#sender = new GmailSender(this.#http, this.#provider, this.#now);
|
|
1261
|
+
this.triggerLogger = options.logger ?? defaultTriggerLogger;
|
|
1262
|
+
}
|
|
1263
|
+
/** @internal The authenticated transport and provider methods that the Trigger pollers share. */
|
|
1264
|
+
triggerTransport() {
|
|
1265
|
+
return { http: this.#http, provider: this.#provider };
|
|
1206
1266
|
}
|
|
1207
1267
|
/** Return the getMessage Query bound to this connection. */
|
|
1208
1268
|
getMessage() {
|
|
@@ -1469,6 +1529,389 @@ function newReplyToMessageStep2(configuration) {
|
|
|
1469
1529
|
return newReplyToMessageStep(configuration);
|
|
1470
1530
|
}
|
|
1471
1531
|
|
|
1532
|
+
// src/trigger.ts
|
|
1533
|
+
import {
|
|
1534
|
+
mustTriggerBindingDefinition,
|
|
1535
|
+
newTrigger
|
|
1536
|
+
} from "@superdurable/connectors-sdk";
|
|
1537
|
+
import { decodeTriggerConfiguration, newDurableTriggerTarget, parseTriggerPayloadJSON } from "@superdurable/connectors-sdk/projectconfig";
|
|
1538
|
+
import { z as z6 } from "zod";
|
|
1539
|
+
|
|
1540
|
+
// src/trigger_source.ts
|
|
1541
|
+
import { createHash as createHash2 } from "crypto";
|
|
1542
|
+
import {
|
|
1543
|
+
TriggerDeliveryAbortedError,
|
|
1544
|
+
createTriggerCall,
|
|
1545
|
+
isTriggerUndeliverable,
|
|
1546
|
+
logTriggerRecord,
|
|
1547
|
+
prepareTriggerDelivery,
|
|
1548
|
+
throwIfTriggerAborted,
|
|
1549
|
+
triggerAttempt,
|
|
1550
|
+
triggerErrorAttributes,
|
|
1551
|
+
waitForTriggerDelay,
|
|
1552
|
+
withTriggerLogAttributes,
|
|
1553
|
+
withTriggerLoggerAttributes
|
|
1554
|
+
} from "@superdurable/connectors-sdk";
|
|
1555
|
+
var GmailPollError = class extends Error {
|
|
1556
|
+
constructor(message, cause) {
|
|
1557
|
+
super(message, cause === void 0 ? void 0 : { cause });
|
|
1558
|
+
this.name = "GmailPollError";
|
|
1559
|
+
}
|
|
1560
|
+
};
|
|
1561
|
+
var uuidNamespaceURL = Buffer.from("6ba7b8119dad11d180b400c04fd430c8", "hex");
|
|
1562
|
+
var MessagePollingTriggerSource = class {
|
|
1563
|
+
#client;
|
|
1564
|
+
#connection;
|
|
1565
|
+
#searchQuery;
|
|
1566
|
+
#matcher;
|
|
1567
|
+
#requiresReply;
|
|
1568
|
+
#logger;
|
|
1569
|
+
#triggerName;
|
|
1570
|
+
#delivered = /* @__PURE__ */ new Set();
|
|
1571
|
+
// Every later poll delivers this event before any listed message, until the target consumes it.
|
|
1572
|
+
#retry;
|
|
1573
|
+
#pollFailures = 0;
|
|
1574
|
+
/** Bind one binding's query and matcher; an empty bindingName omits the binding log attribute. */
|
|
1575
|
+
constructor(client, connection, triggerName, bindingName, searchQuery, matcher, requiresReply) {
|
|
1576
|
+
this.#client = client;
|
|
1577
|
+
this.#connection = connection;
|
|
1578
|
+
this.#triggerName = triggerName;
|
|
1579
|
+
this.#searchQuery = searchQuery;
|
|
1580
|
+
this.#matcher = matcher;
|
|
1581
|
+
this.#requiresReply = requiresReply;
|
|
1582
|
+
this.#logger = withTriggerLoggerAttributes(client.triggerLogger, { connector: ConnectorID, connection: connection.name, trigger: triggerName, ...bindingName ? { binding: bindingName } : {} });
|
|
1583
|
+
}
|
|
1584
|
+
/** Scan, then wait one poll interval, until the context ends. */
|
|
1585
|
+
async run(context, target) {
|
|
1586
|
+
await runMessageTriggerRoutes(context, () => this.scan(context, target), this.#pollIntervalMs());
|
|
1587
|
+
}
|
|
1588
|
+
/** List the inbox and deliver the listed messages. */
|
|
1589
|
+
async scan(context, target) {
|
|
1590
|
+
await this.deliver(context, target, await this.list(context));
|
|
1591
|
+
}
|
|
1592
|
+
/** Read the newest inbox page that matches the source's search query. */
|
|
1593
|
+
async list(context) {
|
|
1594
|
+
const { http, provider } = this.#client.triggerTransport();
|
|
1595
|
+
const call = this.#credentialCall(context.signal);
|
|
1596
|
+
let credentials;
|
|
1597
|
+
try {
|
|
1598
|
+
credentials = await http.resolveCredentials(call, context.signal);
|
|
1599
|
+
} catch (error) {
|
|
1600
|
+
throw this.#pollFailed(context, new GmailPollError("Gmail Trigger credentials are unavailable", error));
|
|
1601
|
+
}
|
|
1602
|
+
try {
|
|
1603
|
+
const listed = await provider.listInboxMessages(call, credentials, this.#searchQuery, http.settings().pollPageSize, context.signal);
|
|
1604
|
+
return { credentials: listed.credentials, messages: listed.messages };
|
|
1605
|
+
} catch (error) {
|
|
1606
|
+
throw this.#pollFailed(context, new GmailPollError("Gmail message list is unavailable", error));
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
/**
|
|
1610
|
+
* Hand target the event that failed on an earlier poll, if any, then every new matching message in
|
|
1611
|
+
* listing, oldest first. It stops at the first failure, so the next poll retries that event before any
|
|
1612
|
+
* later message, even after newer mail pushes it off the listed page.
|
|
1613
|
+
*/
|
|
1614
|
+
async deliver(context, target, listing) {
|
|
1615
|
+
if (this.#retry) await this.#handle(context, target, this.#retry.event);
|
|
1616
|
+
const { provider } = this.#client.triggerTransport();
|
|
1617
|
+
let credentials = listing.credentials;
|
|
1618
|
+
const current = /* @__PURE__ */ new Set();
|
|
1619
|
+
for (let index = listing.messages.length - 1; index >= 0; index--) {
|
|
1620
|
+
const reference = listing.messages[index];
|
|
1621
|
+
if (!reference.id) continue;
|
|
1622
|
+
current.add(reference.id);
|
|
1623
|
+
if (this.#delivered.has(reference.id)) continue;
|
|
1624
|
+
const messageAttributes = { thread_id: reference.threadId, event_id: reference.id };
|
|
1625
|
+
let message;
|
|
1626
|
+
try {
|
|
1627
|
+
const read = await provider.readMessage(this.#credentialCall(context.signal), credentials, reference.id, "metadata", context.signal);
|
|
1628
|
+
credentials = read.credentials;
|
|
1629
|
+
if (!read.resource) throw new GmailPollError("Gmail message lookup failed");
|
|
1630
|
+
message = decodeGmailMessage(read.resource);
|
|
1631
|
+
} catch (error) {
|
|
1632
|
+
throw this.#pollFailed(context, error instanceof GmailPollError ? error : new GmailPollError("Gmail message lookup failed", error), messageAttributes);
|
|
1633
|
+
}
|
|
1634
|
+
const isReply = (message.inReplyTo ?? "").trim() !== "" || (message.references ?? "").trim() !== "";
|
|
1635
|
+
const reason = this.#ignoreReason(isReply, message);
|
|
1636
|
+
if (reason) {
|
|
1637
|
+
this.#log(context, "debug", "trigger event ignored", { ...messageAttributes, reason });
|
|
1638
|
+
continue;
|
|
1639
|
+
}
|
|
1640
|
+
const event = {
|
|
1641
|
+
id: message.messageId,
|
|
1642
|
+
occurredAt: new Date(message.receivedAt),
|
|
1643
|
+
payload: {
|
|
1644
|
+
primaryEmail: credentials.primaryEmail,
|
|
1645
|
+
messageId: message.messageId,
|
|
1646
|
+
threadId: message.threadId,
|
|
1647
|
+
from: message.from,
|
|
1648
|
+
subject: message.subject,
|
|
1649
|
+
...message.snippet ? { snippet: message.snippet } : {},
|
|
1650
|
+
receivedAt: message.receivedAt,
|
|
1651
|
+
isReply
|
|
1652
|
+
}
|
|
1653
|
+
};
|
|
1654
|
+
try {
|
|
1655
|
+
await prepareTriggerDelivery(context, target, event);
|
|
1656
|
+
} catch (error) {
|
|
1657
|
+
throw this.#pollFailed(context, new GmailPollError("Gmail Trigger delivery could not be recorded", error), messageAttributes);
|
|
1658
|
+
}
|
|
1659
|
+
await this.#handle(context, target, event);
|
|
1660
|
+
}
|
|
1661
|
+
this.#delivered = current;
|
|
1662
|
+
this.#pollFailures = 0;
|
|
1663
|
+
}
|
|
1664
|
+
#pollIntervalMs() {
|
|
1665
|
+
return this.#client.triggerTransport().http.settings().pollIntervalMs;
|
|
1666
|
+
}
|
|
1667
|
+
/**
|
|
1668
|
+
* Make one delivery attempt and log its outcome. It resolves when target consumes the event, and
|
|
1669
|
+
* otherwise keeps the event as the source's retry and rethrows. A durable inbox or a newTrigger runner
|
|
1670
|
+
* logs the undeliverable events it consumes itself, so the source then logs no recovery.
|
|
1671
|
+
*/
|
|
1672
|
+
async #handle(context, target, event) {
|
|
1673
|
+
const failures = this.#retry?.event.id === event.id ? this.#retry.failures : 0;
|
|
1674
|
+
const threadAttributes = { thread_id: event.payload.threadId };
|
|
1675
|
+
const messageAttributes = { ...threadAttributes, event_id: event.id };
|
|
1676
|
+
const attempt = triggerAttempt(withTriggerLogAttributes(context, threadAttributes));
|
|
1677
|
+
try {
|
|
1678
|
+
await target.handleTrigger(attempt.context, event);
|
|
1679
|
+
if (failures > 0 && !attempt.wasSkipped()) this.#log(context, "info", "trigger delivered after retry", { ...messageAttributes, attempts: failures + 1 });
|
|
1680
|
+
} catch (error) {
|
|
1681
|
+
if (isTriggerUndeliverable(error)) {
|
|
1682
|
+
this.#log(context, "warn", "trigger event skipped: undeliverable", { ...messageAttributes, ...triggerErrorAttributes(error) });
|
|
1683
|
+
} else if (context.signal.aborted) {
|
|
1684
|
+
throw error;
|
|
1685
|
+
} else {
|
|
1686
|
+
this.#pollFailures = 0;
|
|
1687
|
+
this.#retry = { event, failures: failures + 1 };
|
|
1688
|
+
this.#log(context, "warn", "trigger delivery failed; retrying", { ...messageAttributes, attempt: failures + 1, delay_ms: this.#pollIntervalMs(), ...triggerErrorAttributes(error) });
|
|
1689
|
+
throw error;
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
this.#retry = void 0;
|
|
1693
|
+
this.#delivered.add(event.id);
|
|
1694
|
+
}
|
|
1695
|
+
/** Explain why the source does not deliver a listed message, or return '' when it matches. */
|
|
1696
|
+
#ignoreReason(isReply, message) {
|
|
1697
|
+
if (this.#requiresReply && !isReply) return "not_a_reply";
|
|
1698
|
+
if (!this.#requiresReply && isReply) return "not_a_root";
|
|
1699
|
+
if (!messageMatcherMatches(this.#matcher, message)) return "matcher_mismatch";
|
|
1700
|
+
return "";
|
|
1701
|
+
}
|
|
1702
|
+
/** Log a poll that ended early and return error; the next poll, one interval later, retries. */
|
|
1703
|
+
#pollFailed(context, error, attributes = {}) {
|
|
1704
|
+
if (context.signal.aborted) return new TriggerDeliveryAbortedError();
|
|
1705
|
+
this.#pollFailures++;
|
|
1706
|
+
const causeAttributes = error.cause === void 0 ? {} : { error_cause_type: triggerErrorAttributes(error.cause).error_type ?? "Error" };
|
|
1707
|
+
this.#log(context, "warn", "gmail poll failed; retrying", { ...attributes, attempt: this.#pollFailures, delay_ms: this.#pollIntervalMs(), error: error.message, ...causeAttributes });
|
|
1708
|
+
return error;
|
|
1709
|
+
}
|
|
1710
|
+
#log(context, level, message, attributes) {
|
|
1711
|
+
logTriggerRecord(this.#logger, context, level, message, attributes);
|
|
1712
|
+
}
|
|
1713
|
+
/** The Go connector's stable credential call: a version 5 UUID of the connection and Trigger. */
|
|
1714
|
+
#credentialCall(signal) {
|
|
1715
|
+
const identity = ["https://superdurable.dev/dex-connectors/trigger-credential/v1", this.#connection.provider, this.#connection.name, this.#triggerName].join("/");
|
|
1716
|
+
return createTriggerCall(this.#connection, { connectorId: ConnectorID, operationId: this.#triggerName }, nameBasedUUID(identity), signal);
|
|
1717
|
+
}
|
|
1718
|
+
};
|
|
1719
|
+
function messageMatcherMatches(matcher, message) {
|
|
1720
|
+
if (matcher.messageContains) {
|
|
1721
|
+
const haystack = `${message.subject}
|
|
1722
|
+
${message.snippet ?? ""}`.toLowerCase();
|
|
1723
|
+
if (!haystack.includes(matcher.messageContains.toLowerCase())) return false;
|
|
1724
|
+
}
|
|
1725
|
+
const senders = matcher.senderEmails ?? [];
|
|
1726
|
+
if (senders.length === 0) return true;
|
|
1727
|
+
const sender = parseMailbox(message.from)?.address.toLowerCase();
|
|
1728
|
+
if (!sender) return false;
|
|
1729
|
+
return senders.some((allowed) => parseMailbox(allowed)?.address.toLowerCase() === sender);
|
|
1730
|
+
}
|
|
1731
|
+
async function runMessageTriggerRoutes(context, poll, intervalMs) {
|
|
1732
|
+
for (; ; ) {
|
|
1733
|
+
throwIfTriggerAborted(context.signal);
|
|
1734
|
+
try {
|
|
1735
|
+
await poll();
|
|
1736
|
+
} catch {
|
|
1737
|
+
throwIfTriggerAborted(context.signal);
|
|
1738
|
+
}
|
|
1739
|
+
await waitForTriggerDelay(context.signal, intervalMs);
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
async function pollMessageTriggerRoutes(context, rootRoutes, replyRoutes) {
|
|
1743
|
+
const replyListings = [];
|
|
1744
|
+
for (const route of replyRoutes) replyListings.push(await route.source.list(context));
|
|
1745
|
+
for (const route of rootRoutes) await route.source.scan(context, route.target);
|
|
1746
|
+
for (const [index, route] of replyRoutes.entries()) await route.source.deliver(context, route.target, replyListings[index]);
|
|
1747
|
+
}
|
|
1748
|
+
async function replayMessageTriggerRoutes(context, routes) {
|
|
1749
|
+
for (const route of routes) {
|
|
1750
|
+
if (!route.target.replayTriggerDeliveries) continue;
|
|
1751
|
+
try {
|
|
1752
|
+
await route.target.replayTriggerDeliveries(context);
|
|
1753
|
+
} catch (error) {
|
|
1754
|
+
if (error instanceof TriggerDeliveryAbortedError) throw error;
|
|
1755
|
+
throw new Error(`replay Gmail Trigger deliveries: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1756
|
+
}
|
|
1757
|
+
}
|
|
1758
|
+
}
|
|
1759
|
+
function nameBasedUUID(name) {
|
|
1760
|
+
const bytes = createHash2("sha1").update(uuidNamespaceURL).update(name, "utf8").digest().subarray(0, 16);
|
|
1761
|
+
bytes[6] = bytes[6] & 15 | 80;
|
|
1762
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
1763
|
+
const hex = bytes.toString("hex");
|
|
1764
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
1765
|
+
}
|
|
1766
|
+
|
|
1767
|
+
// src/trigger.ts
|
|
1768
|
+
var MessageMatcherSchema = z6.strictObject({
|
|
1769
|
+
/** Case-insensitive substring of the subject or snippet, required when non-empty. */
|
|
1770
|
+
messageContains: z6.string().optional(),
|
|
1771
|
+
/** Sender addresses allowed to match when non-empty; compared case-insensitively. */
|
|
1772
|
+
senderEmails: z6.array(z6.string()).nullable().optional()
|
|
1773
|
+
});
|
|
1774
|
+
var MessageReceivedTriggerConfigurationSchema = z6.strictObject({ searchQuery: z6.string().optional(), messageMatcher: MessageMatcherSchema.optional() }).superRefine((configuration, context) => validateMessageMatcher(configuration.messageMatcher, context));
|
|
1775
|
+
var ReplyReceivedTriggerConfigurationSchema = z6.strictObject({ searchQuery: z6.string().optional(), replyMatcher: MessageMatcherSchema.optional() }).superRefine((configuration, context) => validateMessageMatcher(configuration.replyMatcher, context));
|
|
1776
|
+
var MessageEventSchema = z6.object({
|
|
1777
|
+
/** Mailbox that received the message. */
|
|
1778
|
+
primaryEmail: z6.string(),
|
|
1779
|
+
/** Gmail message ID. */
|
|
1780
|
+
messageId: z6.string(),
|
|
1781
|
+
/** Gmail thread ID. */
|
|
1782
|
+
threadId: z6.string(),
|
|
1783
|
+
/** Sender header. */
|
|
1784
|
+
from: z6.string(),
|
|
1785
|
+
/** Decoded subject. */
|
|
1786
|
+
subject: z6.string(),
|
|
1787
|
+
/** Gmail snippet, omitted when empty. */
|
|
1788
|
+
snippet: z6.string().optional(),
|
|
1789
|
+
/** Receive time as RFC 3339 UTC. */
|
|
1790
|
+
receivedAt: z6.string(),
|
|
1791
|
+
/** Whether the message has In-Reply-To or References headers. */
|
|
1792
|
+
isReply: z6.boolean()
|
|
1793
|
+
});
|
|
1794
|
+
var MessageReceivedTriggerDefinition = { trigger: { connectorId: ConnectorID, triggerName: "messageReceived" }, description: "Receive a matching message that begins a Gmail thread." };
|
|
1795
|
+
var ReplyReceivedTriggerDefinition = { trigger: { connectorId: ConnectorID, triggerName: "replyReceived" }, description: "Receive a matching reply in an existing Gmail thread." };
|
|
1796
|
+
var UIUnitSearchQueryInput = "searchQueryInput";
|
|
1797
|
+
var UISearchQueryInputPortQuery = "query";
|
|
1798
|
+
var UIUnitEmailListInput = "emailListInput";
|
|
1799
|
+
var UIEmailListInputPortEmails = "emails";
|
|
1800
|
+
var UIUnitTextInput = "textInput";
|
|
1801
|
+
var UITextInputPortText = "text";
|
|
1802
|
+
function defineMessageReceivedTriggerBinding(config) {
|
|
1803
|
+
return mustTriggerBindingDefinition({ definition: MessageReceivedTriggerDefinition, ...config });
|
|
1804
|
+
}
|
|
1805
|
+
function defineReplyReceivedTriggerBinding(config) {
|
|
1806
|
+
return mustTriggerBindingDefinition({ definition: ReplyReceivedTriggerDefinition, ...config });
|
|
1807
|
+
}
|
|
1808
|
+
function newMessageReceivedTrigger(config) {
|
|
1809
|
+
const configuration = MessageReceivedTriggerConfigurationSchema.parse(config.configuration);
|
|
1810
|
+
return newStandaloneTrigger(config, MessageReceivedTriggerDefinition, configuration.searchQuery ?? "", configuration.messageMatcher ?? {}, false);
|
|
1811
|
+
}
|
|
1812
|
+
function newReplyReceivedTrigger(config) {
|
|
1813
|
+
const configuration = ReplyReceivedTriggerConfigurationSchema.parse(config.configuration);
|
|
1814
|
+
return newStandaloneTrigger(config, ReplyReceivedTriggerDefinition, configuration.searchQuery ?? "", configuration.replyMatcher ?? {}, true);
|
|
1815
|
+
}
|
|
1816
|
+
function newStandaloneTrigger(config, definition, searchQuery, matcher, requiresReply) {
|
|
1817
|
+
const client = gmailClientOf(config.connection);
|
|
1818
|
+
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}"`);
|
|
1819
|
+
const source = new MessagePollingTriggerSource(client, config.connection.reference, definition.trigger.triggerName, "", searchQuery, matcher, requiresReply);
|
|
1820
|
+
const triggerSource = { run: (context, target) => source.run(context, target) };
|
|
1821
|
+
return newTrigger({ definition, binding: { connection: config.connection.reference, trigger: definition.trigger, name: config.bindingName }, source: triggerSource, target: config.target, logger: client.triggerLogger });
|
|
1822
|
+
}
|
|
1823
|
+
var MessageTriggerRunner = class {
|
|
1824
|
+
#rootRoutes;
|
|
1825
|
+
#replyRoutes;
|
|
1826
|
+
#pollIntervalMs;
|
|
1827
|
+
/** @internal Use newMessageTriggerRunner or newProjectMessageTriggerRunner. */
|
|
1828
|
+
constructor(rootRoutes, replyRoutes, pollIntervalMs) {
|
|
1829
|
+
this.#rootRoutes = rootRoutes;
|
|
1830
|
+
this.#replyRoutes = replyRoutes;
|
|
1831
|
+
this.#pollIntervalMs = pollIntervalMs;
|
|
1832
|
+
}
|
|
1833
|
+
/**
|
|
1834
|
+
* Replay each route's durable inbox in order, roots first, then poll until the context ends. Each poll
|
|
1835
|
+
* lists every reply route before any root route, then delivers every root before any reply, and ends
|
|
1836
|
+
* at the first failure. Every later poll retries the failed event before that route's listed messages,
|
|
1837
|
+
* even after Gmail stops listing it. Gmail receives a thread's root before any reply to it, so the
|
|
1838
|
+
* root of every listed reply is in the later root listing and reaches Dex first.
|
|
1839
|
+
*
|
|
1840
|
+
* It logs through the client's logger: WARN "gmail poll failed; retrying" with the consecutive failed
|
|
1841
|
+
* polls as attempt and the poll interval as delay_ms when a list or read fails, WARN "trigger delivery
|
|
1842
|
+
* failed; retrying" with the attempt number when a target fails, INFO "trigger delivered after retry"
|
|
1843
|
+
* when a later poll delivers that message, DEBUG "trigger event ignored" with its reason, and the
|
|
1844
|
+
* durable inbox records. It rejects with TriggerDeliveryAbortedError once the context ends, and when
|
|
1845
|
+
* an inbox replay fails.
|
|
1846
|
+
*/
|
|
1847
|
+
async run(context) {
|
|
1848
|
+
await replayMessageTriggerRoutes(context, [...this.#rootRoutes, ...this.#replyRoutes]);
|
|
1849
|
+
await runMessageTriggerRoutes(context, () => pollMessageTriggerRoutes(context, this.#rootRoutes, this.#replyRoutes), this.#pollIntervalMs);
|
|
1850
|
+
}
|
|
1851
|
+
};
|
|
1852
|
+
function newMessageTriggerRunner(config) {
|
|
1853
|
+
const client = gmailClientOf(config.connection);
|
|
1854
|
+
const bindingKeys = /* @__PURE__ */ new Set();
|
|
1855
|
+
const route = (triggerName, bindingName, target, searchQuery, matcher, requiresReply) => {
|
|
1856
|
+
const trimmedBindingName = bindingName?.trim();
|
|
1857
|
+
if (!trimmedBindingName || !target) throw new TypeError("Gmail message Trigger binding name and target are required");
|
|
1858
|
+
const bindingKey = `${triggerName}\0${trimmedBindingName}`;
|
|
1859
|
+
if (bindingKeys.has(bindingKey)) throw new TypeError(`Gmail message Trigger binding name "${trimmedBindingName}" is duplicated`);
|
|
1860
|
+
bindingKeys.add(bindingKey);
|
|
1861
|
+
return { source: new MessagePollingTriggerSource(client, config.connection.reference, triggerName, bindingName, searchQuery ?? "", matcher ?? {}, requiresReply), target };
|
|
1862
|
+
};
|
|
1863
|
+
const rootRoutes = (config.messageReceivedRoutes ?? []).map((root) => {
|
|
1864
|
+
const configuration = MessageReceivedTriggerConfigurationSchema.parse(root.configuration);
|
|
1865
|
+
return route("messageReceived", root.bindingName, root.target, configuration.searchQuery, configuration.messageMatcher, false);
|
|
1866
|
+
});
|
|
1867
|
+
const replyRoutes = (config.replyReceivedRoutes ?? []).map((reply) => {
|
|
1868
|
+
const configuration = ReplyReceivedTriggerConfigurationSchema.parse(reply.configuration);
|
|
1869
|
+
return route("replyReceived", reply.bindingName, reply.target, configuration.searchQuery, configuration.replyMatcher, true);
|
|
1870
|
+
});
|
|
1871
|
+
if (rootRoutes.length + replyRoutes.length === 0) throw new TypeError("Gmail message Trigger routes are required");
|
|
1872
|
+
return new MessageTriggerRunner(rootRoutes, replyRoutes, client.triggerTransport().http.settings().pollIntervalMs);
|
|
1873
|
+
}
|
|
1874
|
+
function newProjectMessageTriggerRunner(project, connectionName, config, options = {}) {
|
|
1875
|
+
const connection = newProjectConnection(project, connectionName, options);
|
|
1876
|
+
const client = gmailClientOf(connection);
|
|
1877
|
+
const durable = (triggerName, bindingName, target, schema) => {
|
|
1878
|
+
const key = { connectorId: ConnectorID, connectionName, triggerName, bindingName };
|
|
1879
|
+
let configuration;
|
|
1880
|
+
try {
|
|
1881
|
+
configuration = decodeTriggerConfiguration(project.configuration, key, schema);
|
|
1882
|
+
} catch (error) {
|
|
1883
|
+
throw new Error(`gmail ${triggerName} binding "${bindingName}" configuration: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1884
|
+
}
|
|
1885
|
+
const durableTarget = newDurableTriggerTarget(project.triggerInbox(key), key, target, { logger: client.triggerLogger, decodePayload: (_payloadJSON, payloadBytes) => MessageEventSchema.parse(parseTriggerPayloadJSON(payloadBytes)) });
|
|
1886
|
+
return { bindingName, configuration, target: durableTarget };
|
|
1887
|
+
};
|
|
1888
|
+
return newMessageTriggerRunner({
|
|
1889
|
+
connection,
|
|
1890
|
+
messageReceivedRoutes: (config.messageReceivedRoutes ?? []).map((route) => durable("messageReceived", route.bindingName, route.target, MessageReceivedTriggerConfigurationSchema)),
|
|
1891
|
+
replyReceivedRoutes: (config.replyReceivedRoutes ?? []).map((route) => durable("replyReceived", route.bindingName, route.target, ReplyReceivedTriggerConfigurationSchema))
|
|
1892
|
+
});
|
|
1893
|
+
}
|
|
1894
|
+
function gmailClientOf(connection) {
|
|
1895
|
+
if (!(connection?.operations instanceof GmailClient)) throw new TypeError("Gmail Triggers require a connection bound to a GmailClient");
|
|
1896
|
+
return connection.operations;
|
|
1897
|
+
}
|
|
1898
|
+
function validateMessageMatcher(matcher, context) {
|
|
1899
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1900
|
+
for (const sender of matcher?.senderEmails ?? []) {
|
|
1901
|
+
const address = parseMailbox(sender)?.address;
|
|
1902
|
+
if (!address) {
|
|
1903
|
+
context.addIssue({ code: "custom", message: "Gmail sender email is invalid" });
|
|
1904
|
+
return;
|
|
1905
|
+
}
|
|
1906
|
+
const canonical = address.toLowerCase();
|
|
1907
|
+
if (seen.has(canonical)) {
|
|
1908
|
+
context.addIssue({ code: "custom", message: "Gmail sender emails must be unique" });
|
|
1909
|
+
return;
|
|
1910
|
+
}
|
|
1911
|
+
seen.add(canonical);
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
|
|
1472
1915
|
export {
|
|
1473
1916
|
GetMessageInputSchema,
|
|
1474
1917
|
MessageSchema,
|
|
@@ -1517,5 +1960,24 @@ export {
|
|
|
1517
1960
|
newProjectGmailClient,
|
|
1518
1961
|
newGetMessageStep2 as newGetMessageStep,
|
|
1519
1962
|
newSendMessageStep2 as newSendMessageStep,
|
|
1520
|
-
newReplyToMessageStep2 as newReplyToMessageStep
|
|
1963
|
+
newReplyToMessageStep2 as newReplyToMessageStep,
|
|
1964
|
+
MessageMatcherSchema,
|
|
1965
|
+
MessageReceivedTriggerConfigurationSchema,
|
|
1966
|
+
ReplyReceivedTriggerConfigurationSchema,
|
|
1967
|
+
MessageEventSchema,
|
|
1968
|
+
MessageReceivedTriggerDefinition,
|
|
1969
|
+
ReplyReceivedTriggerDefinition,
|
|
1970
|
+
UIUnitSearchQueryInput,
|
|
1971
|
+
UISearchQueryInputPortQuery,
|
|
1972
|
+
UIUnitEmailListInput,
|
|
1973
|
+
UIEmailListInputPortEmails,
|
|
1974
|
+
UIUnitTextInput,
|
|
1975
|
+
UITextInputPortText,
|
|
1976
|
+
defineMessageReceivedTriggerBinding,
|
|
1977
|
+
defineReplyReceivedTriggerBinding,
|
|
1978
|
+
newMessageReceivedTrigger,
|
|
1979
|
+
newReplyReceivedTrigger,
|
|
1980
|
+
MessageTriggerRunner,
|
|
1981
|
+
newMessageTriggerRunner,
|
|
1982
|
+
newProjectMessageTriggerRunner
|
|
1521
1983
|
};
|