@superdurable/connector-google-gmail 0.2.2 → 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-OKDZ42YK.js → chunk-PW3NTBVH.js} +442 -7
- package/dist/index.cjs +444 -6
- package/dist/index.d.cts +208 -4
- package/dist/index.d.ts +208 -4
- 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
package/dist/index.cjs
CHANGED
|
@@ -33,8 +33,15 @@ __export(index_exports, {
|
|
|
33
33
|
GmailMessageResourceSchema: () => GmailMessageResourceSchema,
|
|
34
34
|
GmailProvider: () => GmailProvider,
|
|
35
35
|
GoogleOAuthAuthMethodID: () => GoogleOAuthAuthMethodID,
|
|
36
|
+
MessageEventSchema: () => MessageEventSchema,
|
|
37
|
+
MessageMatcherSchema: () => MessageMatcherSchema,
|
|
38
|
+
MessageReceivedTriggerConfigurationSchema: () => MessageReceivedTriggerConfigurationSchema,
|
|
39
|
+
MessageReceivedTriggerDefinition: () => MessageReceivedTriggerDefinition,
|
|
36
40
|
MessageSchema: () => MessageSchema,
|
|
41
|
+
MessageTriggerRunner: () => MessageTriggerRunner,
|
|
37
42
|
ProviderID: () => ProviderID,
|
|
43
|
+
ReplyReceivedTriggerConfigurationSchema: () => ReplyReceivedTriggerConfigurationSchema,
|
|
44
|
+
ReplyReceivedTriggerDefinition: () => ReplyReceivedTriggerDefinition,
|
|
38
45
|
ReplyToMessageBranch: () => ReplyToMessageBranch,
|
|
39
46
|
ReplyToMessageDefinition: () => ReplyToMessageDefinition,
|
|
40
47
|
ReplyToMessageInputSchema: () => ReplyToMessageInputSchema,
|
|
@@ -44,18 +51,30 @@ __export(index_exports, {
|
|
|
44
51
|
SendMessageInputSchema: () => SendMessageInputSchema2,
|
|
45
52
|
SendMessageOperation: () => SendMessageOperation,
|
|
46
53
|
SendMessageOutputSchema: () => SendMessageOutputSchema2,
|
|
54
|
+
UIEmailListInputPortEmails: () => UIEmailListInputPortEmails,
|
|
55
|
+
UISearchQueryInputPortQuery: () => UISearchQueryInputPortQuery,
|
|
56
|
+
UITextInputPortText: () => UITextInputPortText,
|
|
57
|
+
UIUnitEmailListInput: () => UIUnitEmailListInput,
|
|
58
|
+
UIUnitSearchQueryInput: () => UIUnitSearchQueryInput,
|
|
59
|
+
UIUnitTextInput: () => UIUnitTextInput,
|
|
47
60
|
WorkspaceDomainDelegationAuthMethodID: () => WorkspaceDomainDelegationAuthMethodID,
|
|
48
61
|
buildMIMEMessage: () => buildMIMEMessage,
|
|
49
62
|
buildReplyMIMEMessage: () => buildReplyMIMEMessage,
|
|
50
63
|
decodeGmailMessage: () => decodeGmailMessage,
|
|
64
|
+
defineMessageReceivedTriggerBinding: () => defineMessageReceivedTriggerBinding,
|
|
65
|
+
defineReplyReceivedTriggerBinding: () => defineReplyReceivedTriggerBinding,
|
|
51
66
|
emptyMessage: () => emptyMessage,
|
|
52
67
|
gmailClientSettings: () => gmailClientSettings,
|
|
53
68
|
gmailFailure: () => gmailFailure,
|
|
54
69
|
gmailRequestID: () => gmailRequestID,
|
|
55
70
|
gmailRetryAfterMs: () => gmailRetryAfterMs,
|
|
56
71
|
newGetMessageStep: () => newGetMessageStep2,
|
|
72
|
+
newMessageReceivedTrigger: () => newMessageReceivedTrigger,
|
|
73
|
+
newMessageTriggerRunner: () => newMessageTriggerRunner,
|
|
57
74
|
newProjectConnection: () => newProjectConnection,
|
|
58
75
|
newProjectGmailClient: () => newProjectGmailClient,
|
|
76
|
+
newProjectMessageTriggerRunner: () => newProjectMessageTriggerRunner,
|
|
77
|
+
newReplyReceivedTrigger: () => newReplyReceivedTrigger,
|
|
59
78
|
newReplyToMessageStep: () => newReplyToMessageStep2,
|
|
60
79
|
newSendMessageStep: () => newSendMessageStep2,
|
|
61
80
|
parseMailbox: () => parseMailbox,
|
|
@@ -276,7 +295,9 @@ var SendMessageDefinition = {
|
|
|
276
295
|
{ id: "providerRejected", description: "Gmail conclusively rejected the message.", optional: true },
|
|
277
296
|
{ id: "defect", description: "Local input, connection configuration, or connector definition is invalid.", optional: true }
|
|
278
297
|
],
|
|
279
|
-
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 5, totalDurationMs: 12e4 } }
|
|
298
|
+
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 5, totalDurationMs: 12e4 } },
|
|
299
|
+
repeatOnUnknown: "limited",
|
|
300
|
+
maxSends: 3
|
|
280
301
|
};
|
|
281
302
|
var ReplyToMessageBranch = {
|
|
282
303
|
Sent: "sent",
|
|
@@ -296,7 +317,9 @@ var ReplyToMessageDefinition = {
|
|
|
296
317
|
{ id: "invalidResponse", description: "Gmail returned an invalid or oversized source message response before sending the reply.", optional: true },
|
|
297
318
|
{ id: "defect", description: "Local input, connection configuration, or connector definition is invalid.", optional: true }
|
|
298
319
|
],
|
|
299
|
-
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 5, totalDurationMs: 12e4 } }
|
|
320
|
+
stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 5, totalDurationMs: 12e4 } },
|
|
321
|
+
repeatOnUnknown: "limited",
|
|
322
|
+
maxSends: 3
|
|
300
323
|
};
|
|
301
324
|
|
|
302
325
|
// src/message.ts
|
|
@@ -338,7 +361,8 @@ function decodeGmailMessage(resource) {
|
|
|
338
361
|
...textBodies.length ? { textBody: textBodies.join("\n") } : {},
|
|
339
362
|
...htmlBodies.length ? { htmlBody: htmlBodies.join("\n") } : {},
|
|
340
363
|
...resource.snippet ? { snippet: resource.snippet } : {},
|
|
341
|
-
|
|
364
|
+
// Go's time.Time JSON (RFC 3339 with trailing fractional zeros removed), such as .12Z for 120 ms.
|
|
365
|
+
receivedAt: receivedAt.toISOString().replace(/\.(\d*?)0*Z$/, (_match, digits) => digits ? `.${digits}Z` : "Z"),
|
|
342
366
|
...resource.labelIds?.length ? { labelIds: resource.labelIds } : {}
|
|
343
367
|
};
|
|
344
368
|
}
|
|
@@ -484,9 +508,11 @@ function gmailClientSettings(config = {}) {
|
|
|
484
508
|
if (!Number.isSafeInteger(maxResponseBytes) || maxResponseBytes < 1 || !Number.isSafeInteger(maxMessageBytes) || maxMessageBytes < 1) {
|
|
485
509
|
throw new TypeError("Gmail response and message limits must be positive integers");
|
|
486
510
|
}
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
511
|
+
const pollIntervalMs = config.pollIntervalMs ?? 1e4;
|
|
512
|
+
const pollPageSize = config.pollPageSize ?? 25;
|
|
513
|
+
if (!Number.isSafeInteger(pollIntervalMs) || pollIntervalMs < 1e3) throw new TypeError("Gmail poll interval is invalid");
|
|
514
|
+
if (!Number.isSafeInteger(pollPageSize) || pollPageSize < 1 || pollPageSize > 100) throw new TypeError("Gmail poll page size is invalid");
|
|
515
|
+
return Object.freeze({ endpoint, maxResponseBytes, maxMessageBytes, addressPolicy: endpoint.startsWith("http://") ? "privateNetworkHTTP" : "publicHTTPS", pollIntervalMs, pollPageSize });
|
|
490
516
|
}
|
|
491
517
|
var GmailCredentialError = class extends Error {
|
|
492
518
|
constructor() {
|
|
@@ -595,6 +621,7 @@ function validateCredentials(credentials) {
|
|
|
595
621
|
var import_zod4 = require("zod");
|
|
596
622
|
var SentMessageSchema = import_zod4.z.object({ id: import_zod4.z.string().optional(), threadId: import_zod4.z.string().optional() });
|
|
597
623
|
var SentSearchSchema = import_zod4.z.object({ messages: import_zod4.z.array(SentMessageSchema).nullish() });
|
|
624
|
+
var MessageListSchema = import_zod4.z.object({ messages: import_zod4.z.array(import_zod4.z.object({ id: import_zod4.z.string().nullish(), threadId: import_zod4.z.string().nullish() })).nullish() });
|
|
598
625
|
var GmailProvider = class {
|
|
599
626
|
#http;
|
|
600
627
|
/** Bind the shared authenticated transport. */
|
|
@@ -619,6 +646,23 @@ var GmailProvider = class {
|
|
|
619
646
|
return result;
|
|
620
647
|
}
|
|
621
648
|
}
|
|
649
|
+
/**
|
|
650
|
+
* List the newest inbox page that matches searchQuery, as the Go Trigger poller does. It rejects with
|
|
651
|
+
* an error that names no query value when Gmail does not answer 2xx with a usable listing.
|
|
652
|
+
*/
|
|
653
|
+
async listInboxMessages(call, credentials, searchQuery, pageSize, signal) {
|
|
654
|
+
const query = new URLSearchParams({ labelIds: "INBOX", maxResults: String(pageSize) });
|
|
655
|
+
if (searchQuery.trim()) query.set("q", searchQuery);
|
|
656
|
+
const result = await this.#http.request(call, credentials, "GET", `/users/me/messages?${query.toString()}`, void 0, signal);
|
|
657
|
+
if (result.response.status < 200 || result.response.status >= 300) throw new Error("Gmail message list is unavailable");
|
|
658
|
+
let parsed;
|
|
659
|
+
try {
|
|
660
|
+
parsed = MessageListSchema.parse(JSON.parse(Buffer.from(result.response.body).toString("utf8")));
|
|
661
|
+
} catch {
|
|
662
|
+
throw new Error("Gmail message list is invalid");
|
|
663
|
+
}
|
|
664
|
+
return { messages: (parsed.messages ?? []).map((message) => ({ id: message.id ?? "", threadId: message.threadId ?? "" })), credentials: result.credentials };
|
|
665
|
+
}
|
|
622
666
|
/** Search Sent Mail once for the run-specific RFC Message-ID. */
|
|
623
667
|
async findSentMessage(call, credentials, messageIdAddress, signal) {
|
|
624
668
|
const query = new URLSearchParams();
|
|
@@ -1254,12 +1298,19 @@ var GmailClient = class {
|
|
|
1254
1298
|
#provider;
|
|
1255
1299
|
#sender;
|
|
1256
1300
|
#now;
|
|
1301
|
+
/** Trigger record destination. */
|
|
1302
|
+
triggerLogger;
|
|
1257
1303
|
/** Validate settings and inject a host-owned credential source. */
|
|
1258
1304
|
constructor(config, credentials, options = {}) {
|
|
1259
1305
|
this.#http = new GmailHTTPClient(config, credentials, options.refreshDriver ?? new GmailCredentialRefreshDriver(), options.transport);
|
|
1260
1306
|
this.#provider = new GmailProvider(this.#http);
|
|
1261
1307
|
this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
1262
1308
|
this.#sender = new GmailSender(this.#http, this.#provider, this.#now);
|
|
1309
|
+
this.triggerLogger = options.logger ?? import_connectors_sdk5.defaultTriggerLogger;
|
|
1310
|
+
}
|
|
1311
|
+
/** @internal The authenticated transport and provider methods that the Trigger pollers share. */
|
|
1312
|
+
triggerTransport() {
|
|
1313
|
+
return { http: this.#http, provider: this.#provider };
|
|
1263
1314
|
}
|
|
1264
1315
|
/** Return the getMessage Query bound to this connection. */
|
|
1265
1316
|
getMessage() {
|
|
@@ -1525,6 +1576,374 @@ function newReplyToMessageStep2(configuration) {
|
|
|
1525
1576
|
requireGmailConnection(configuration.connection, configuration.connectionName);
|
|
1526
1577
|
return newReplyToMessageStep(configuration);
|
|
1527
1578
|
}
|
|
1579
|
+
|
|
1580
|
+
// src/trigger.ts
|
|
1581
|
+
var import_connectors_sdk12 = require("@superdurable/connectors-sdk");
|
|
1582
|
+
var import_projectconfig2 = require("@superdurable/connectors-sdk/projectconfig");
|
|
1583
|
+
var import_zod6 = require("zod");
|
|
1584
|
+
|
|
1585
|
+
// src/trigger_source.ts
|
|
1586
|
+
var import_node_crypto2 = require("crypto");
|
|
1587
|
+
var import_connectors_sdk11 = require("@superdurable/connectors-sdk");
|
|
1588
|
+
var GmailPollError = class extends Error {
|
|
1589
|
+
constructor(message, cause) {
|
|
1590
|
+
super(message, cause === void 0 ? void 0 : { cause });
|
|
1591
|
+
this.name = "GmailPollError";
|
|
1592
|
+
}
|
|
1593
|
+
};
|
|
1594
|
+
var uuidNamespaceURL = Buffer.from("6ba7b8119dad11d180b400c04fd430c8", "hex");
|
|
1595
|
+
var MessagePollingTriggerSource = class {
|
|
1596
|
+
#client;
|
|
1597
|
+
#connection;
|
|
1598
|
+
#searchQuery;
|
|
1599
|
+
#matcher;
|
|
1600
|
+
#requiresReply;
|
|
1601
|
+
#logger;
|
|
1602
|
+
#triggerName;
|
|
1603
|
+
#delivered = /* @__PURE__ */ new Set();
|
|
1604
|
+
// Every later poll delivers this event before any listed message, until the target consumes it.
|
|
1605
|
+
#retry;
|
|
1606
|
+
#pollFailures = 0;
|
|
1607
|
+
/** Bind one binding's query and matcher; an empty bindingName omits the binding log attribute. */
|
|
1608
|
+
constructor(client, connection, triggerName, bindingName, searchQuery, matcher, requiresReply) {
|
|
1609
|
+
this.#client = client;
|
|
1610
|
+
this.#connection = connection;
|
|
1611
|
+
this.#triggerName = triggerName;
|
|
1612
|
+
this.#searchQuery = searchQuery;
|
|
1613
|
+
this.#matcher = matcher;
|
|
1614
|
+
this.#requiresReply = requiresReply;
|
|
1615
|
+
this.#logger = (0, import_connectors_sdk11.withTriggerLoggerAttributes)(client.triggerLogger, { connector: ConnectorID, connection: connection.name, trigger: triggerName, ...bindingName ? { binding: bindingName } : {} });
|
|
1616
|
+
}
|
|
1617
|
+
/** Scan, then wait one poll interval, until the context ends. */
|
|
1618
|
+
async run(context, target) {
|
|
1619
|
+
await runMessageTriggerRoutes(context, () => this.scan(context, target), this.#pollIntervalMs());
|
|
1620
|
+
}
|
|
1621
|
+
/** List the inbox and deliver the listed messages. */
|
|
1622
|
+
async scan(context, target) {
|
|
1623
|
+
await this.deliver(context, target, await this.list(context));
|
|
1624
|
+
}
|
|
1625
|
+
/** Read the newest inbox page that matches the source's search query. */
|
|
1626
|
+
async list(context) {
|
|
1627
|
+
const { http, provider } = this.#client.triggerTransport();
|
|
1628
|
+
const call = this.#credentialCall(context.signal);
|
|
1629
|
+
let credentials;
|
|
1630
|
+
try {
|
|
1631
|
+
credentials = await http.resolveCredentials(call, context.signal);
|
|
1632
|
+
} catch (error) {
|
|
1633
|
+
throw this.#pollFailed(context, new GmailPollError("Gmail Trigger credentials are unavailable", error));
|
|
1634
|
+
}
|
|
1635
|
+
try {
|
|
1636
|
+
const listed = await provider.listInboxMessages(call, credentials, this.#searchQuery, http.settings().pollPageSize, context.signal);
|
|
1637
|
+
return { credentials: listed.credentials, messages: listed.messages };
|
|
1638
|
+
} catch (error) {
|
|
1639
|
+
throw this.#pollFailed(context, new GmailPollError("Gmail message list is unavailable", error));
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
/**
|
|
1643
|
+
* Hand target the event that failed on an earlier poll, if any, then every new matching message in
|
|
1644
|
+
* listing, oldest first. It stops at the first failure, so the next poll retries that event before any
|
|
1645
|
+
* later message, even after newer mail pushes it off the listed page.
|
|
1646
|
+
*/
|
|
1647
|
+
async deliver(context, target, listing) {
|
|
1648
|
+
if (this.#retry) await this.#handle(context, target, this.#retry.event);
|
|
1649
|
+
const { provider } = this.#client.triggerTransport();
|
|
1650
|
+
let credentials = listing.credentials;
|
|
1651
|
+
const current = /* @__PURE__ */ new Set();
|
|
1652
|
+
for (let index = listing.messages.length - 1; index >= 0; index--) {
|
|
1653
|
+
const reference = listing.messages[index];
|
|
1654
|
+
if (!reference.id) continue;
|
|
1655
|
+
current.add(reference.id);
|
|
1656
|
+
if (this.#delivered.has(reference.id)) continue;
|
|
1657
|
+
const messageAttributes = { thread_id: reference.threadId, event_id: reference.id };
|
|
1658
|
+
let message;
|
|
1659
|
+
try {
|
|
1660
|
+
const read = await provider.readMessage(this.#credentialCall(context.signal), credentials, reference.id, "metadata", context.signal);
|
|
1661
|
+
credentials = read.credentials;
|
|
1662
|
+
if (!read.resource) throw new GmailPollError("Gmail message lookup failed");
|
|
1663
|
+
message = decodeGmailMessage(read.resource);
|
|
1664
|
+
} catch (error) {
|
|
1665
|
+
throw this.#pollFailed(context, error instanceof GmailPollError ? error : new GmailPollError("Gmail message lookup failed", error), messageAttributes);
|
|
1666
|
+
}
|
|
1667
|
+
const isReply = (message.inReplyTo ?? "").trim() !== "" || (message.references ?? "").trim() !== "";
|
|
1668
|
+
const reason = this.#ignoreReason(isReply, message);
|
|
1669
|
+
if (reason) {
|
|
1670
|
+
this.#log(context, "debug", "trigger event ignored", { ...messageAttributes, reason });
|
|
1671
|
+
continue;
|
|
1672
|
+
}
|
|
1673
|
+
const event = {
|
|
1674
|
+
id: message.messageId,
|
|
1675
|
+
occurredAt: new Date(message.receivedAt),
|
|
1676
|
+
payload: {
|
|
1677
|
+
primaryEmail: credentials.primaryEmail,
|
|
1678
|
+
messageId: message.messageId,
|
|
1679
|
+
threadId: message.threadId,
|
|
1680
|
+
from: message.from,
|
|
1681
|
+
subject: message.subject,
|
|
1682
|
+
...message.snippet ? { snippet: message.snippet } : {},
|
|
1683
|
+
receivedAt: message.receivedAt,
|
|
1684
|
+
isReply
|
|
1685
|
+
}
|
|
1686
|
+
};
|
|
1687
|
+
try {
|
|
1688
|
+
await (0, import_connectors_sdk11.prepareTriggerDelivery)(context, target, event);
|
|
1689
|
+
} catch (error) {
|
|
1690
|
+
throw this.#pollFailed(context, new GmailPollError("Gmail Trigger delivery could not be recorded", error), messageAttributes);
|
|
1691
|
+
}
|
|
1692
|
+
await this.#handle(context, target, event);
|
|
1693
|
+
}
|
|
1694
|
+
this.#delivered = current;
|
|
1695
|
+
this.#pollFailures = 0;
|
|
1696
|
+
}
|
|
1697
|
+
#pollIntervalMs() {
|
|
1698
|
+
return this.#client.triggerTransport().http.settings().pollIntervalMs;
|
|
1699
|
+
}
|
|
1700
|
+
/**
|
|
1701
|
+
* Make one delivery attempt and log its outcome. It resolves when target consumes the event, and
|
|
1702
|
+
* otherwise keeps the event as the source's retry and rethrows. A durable inbox or a newTrigger runner
|
|
1703
|
+
* logs the undeliverable events it consumes itself, so the source then logs no recovery.
|
|
1704
|
+
*/
|
|
1705
|
+
async #handle(context, target, event) {
|
|
1706
|
+
const failures = this.#retry?.event.id === event.id ? this.#retry.failures : 0;
|
|
1707
|
+
const threadAttributes = { thread_id: event.payload.threadId };
|
|
1708
|
+
const messageAttributes = { ...threadAttributes, event_id: event.id };
|
|
1709
|
+
const attempt = (0, import_connectors_sdk11.triggerAttempt)((0, import_connectors_sdk11.withTriggerLogAttributes)(context, threadAttributes));
|
|
1710
|
+
try {
|
|
1711
|
+
await target.handleTrigger(attempt.context, event);
|
|
1712
|
+
if (failures > 0 && !attempt.wasSkipped()) this.#log(context, "info", "trigger delivered after retry", { ...messageAttributes, attempts: failures + 1 });
|
|
1713
|
+
} catch (error) {
|
|
1714
|
+
if ((0, import_connectors_sdk11.isTriggerUndeliverable)(error)) {
|
|
1715
|
+
this.#log(context, "warn", "trigger event skipped: undeliverable", { ...messageAttributes, ...(0, import_connectors_sdk11.triggerErrorAttributes)(error) });
|
|
1716
|
+
} else if (context.signal.aborted) {
|
|
1717
|
+
throw error;
|
|
1718
|
+
} else {
|
|
1719
|
+
this.#pollFailures = 0;
|
|
1720
|
+
this.#retry = { event, failures: failures + 1 };
|
|
1721
|
+
this.#log(context, "warn", "trigger delivery failed; retrying", { ...messageAttributes, attempt: failures + 1, delay_ms: this.#pollIntervalMs(), ...(0, import_connectors_sdk11.triggerErrorAttributes)(error) });
|
|
1722
|
+
throw error;
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
this.#retry = void 0;
|
|
1726
|
+
this.#delivered.add(event.id);
|
|
1727
|
+
}
|
|
1728
|
+
/** Explain why the source does not deliver a listed message, or return '' when it matches. */
|
|
1729
|
+
#ignoreReason(isReply, message) {
|
|
1730
|
+
if (this.#requiresReply && !isReply) return "not_a_reply";
|
|
1731
|
+
if (!this.#requiresReply && isReply) return "not_a_root";
|
|
1732
|
+
if (!messageMatcherMatches(this.#matcher, message)) return "matcher_mismatch";
|
|
1733
|
+
return "";
|
|
1734
|
+
}
|
|
1735
|
+
/** Log a poll that ended early and return error; the next poll, one interval later, retries. */
|
|
1736
|
+
#pollFailed(context, error, attributes = {}) {
|
|
1737
|
+
if (context.signal.aborted) return new import_connectors_sdk11.TriggerDeliveryAbortedError();
|
|
1738
|
+
this.#pollFailures++;
|
|
1739
|
+
const causeAttributes = error.cause === void 0 ? {} : { error_cause_type: (0, import_connectors_sdk11.triggerErrorAttributes)(error.cause).error_type ?? "Error" };
|
|
1740
|
+
this.#log(context, "warn", "gmail poll failed; retrying", { ...attributes, attempt: this.#pollFailures, delay_ms: this.#pollIntervalMs(), error: error.message, ...causeAttributes });
|
|
1741
|
+
return error;
|
|
1742
|
+
}
|
|
1743
|
+
#log(context, level, message, attributes) {
|
|
1744
|
+
(0, import_connectors_sdk11.logTriggerRecord)(this.#logger, context, level, message, attributes);
|
|
1745
|
+
}
|
|
1746
|
+
/** The Go connector's stable credential call: a version 5 UUID of the connection and Trigger. */
|
|
1747
|
+
#credentialCall(signal) {
|
|
1748
|
+
const identity = ["https://superdurable.dev/dex-connectors/trigger-credential/v1", this.#connection.provider, this.#connection.name, this.#triggerName].join("/");
|
|
1749
|
+
return (0, import_connectors_sdk11.createTriggerCall)(this.#connection, { connectorId: ConnectorID, operationId: this.#triggerName }, nameBasedUUID(identity), signal);
|
|
1750
|
+
}
|
|
1751
|
+
};
|
|
1752
|
+
function messageMatcherMatches(matcher, message) {
|
|
1753
|
+
if (matcher.messageContains) {
|
|
1754
|
+
const haystack = `${message.subject}
|
|
1755
|
+
${message.snippet ?? ""}`.toLowerCase();
|
|
1756
|
+
if (!haystack.includes(matcher.messageContains.toLowerCase())) return false;
|
|
1757
|
+
}
|
|
1758
|
+
const senders = matcher.senderEmails ?? [];
|
|
1759
|
+
if (senders.length === 0) return true;
|
|
1760
|
+
const sender = parseMailbox(message.from)?.address.toLowerCase();
|
|
1761
|
+
if (!sender) return false;
|
|
1762
|
+
return senders.some((allowed) => parseMailbox(allowed)?.address.toLowerCase() === sender);
|
|
1763
|
+
}
|
|
1764
|
+
async function runMessageTriggerRoutes(context, poll, intervalMs) {
|
|
1765
|
+
for (; ; ) {
|
|
1766
|
+
(0, import_connectors_sdk11.throwIfTriggerAborted)(context.signal);
|
|
1767
|
+
try {
|
|
1768
|
+
await poll();
|
|
1769
|
+
} catch {
|
|
1770
|
+
(0, import_connectors_sdk11.throwIfTriggerAborted)(context.signal);
|
|
1771
|
+
}
|
|
1772
|
+
await (0, import_connectors_sdk11.waitForTriggerDelay)(context.signal, intervalMs);
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
async function pollMessageTriggerRoutes(context, rootRoutes, replyRoutes) {
|
|
1776
|
+
const replyListings = [];
|
|
1777
|
+
for (const route of replyRoutes) replyListings.push(await route.source.list(context));
|
|
1778
|
+
for (const route of rootRoutes) await route.source.scan(context, route.target);
|
|
1779
|
+
for (const [index, route] of replyRoutes.entries()) await route.source.deliver(context, route.target, replyListings[index]);
|
|
1780
|
+
}
|
|
1781
|
+
async function replayMessageTriggerRoutes(context, routes) {
|
|
1782
|
+
for (const route of routes) {
|
|
1783
|
+
if (!route.target.replayTriggerDeliveries) continue;
|
|
1784
|
+
try {
|
|
1785
|
+
await route.target.replayTriggerDeliveries(context);
|
|
1786
|
+
} catch (error) {
|
|
1787
|
+
if (error instanceof import_connectors_sdk11.TriggerDeliveryAbortedError) throw error;
|
|
1788
|
+
throw new Error(`replay Gmail Trigger deliveries: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1789
|
+
}
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1792
|
+
function nameBasedUUID(name) {
|
|
1793
|
+
const bytes = (0, import_node_crypto2.createHash)("sha1").update(uuidNamespaceURL).update(name, "utf8").digest().subarray(0, 16);
|
|
1794
|
+
bytes[6] = bytes[6] & 15 | 80;
|
|
1795
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
1796
|
+
const hex = bytes.toString("hex");
|
|
1797
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
1798
|
+
}
|
|
1799
|
+
|
|
1800
|
+
// src/trigger.ts
|
|
1801
|
+
var MessageMatcherSchema = import_zod6.z.strictObject({
|
|
1802
|
+
/** Case-insensitive substring of the subject or snippet, required when non-empty. */
|
|
1803
|
+
messageContains: import_zod6.z.string().optional(),
|
|
1804
|
+
/** Sender addresses allowed to match when non-empty; compared case-insensitively. */
|
|
1805
|
+
senderEmails: import_zod6.z.array(import_zod6.z.string()).nullable().optional()
|
|
1806
|
+
});
|
|
1807
|
+
var MessageReceivedTriggerConfigurationSchema = import_zod6.z.strictObject({ searchQuery: import_zod6.z.string().optional(), messageMatcher: MessageMatcherSchema.optional() }).superRefine((configuration, context) => validateMessageMatcher(configuration.messageMatcher, context));
|
|
1808
|
+
var ReplyReceivedTriggerConfigurationSchema = import_zod6.z.strictObject({ searchQuery: import_zod6.z.string().optional(), replyMatcher: MessageMatcherSchema.optional() }).superRefine((configuration, context) => validateMessageMatcher(configuration.replyMatcher, context));
|
|
1809
|
+
var MessageEventSchema = import_zod6.z.object({
|
|
1810
|
+
/** Mailbox that received the message. */
|
|
1811
|
+
primaryEmail: import_zod6.z.string(),
|
|
1812
|
+
/** Gmail message ID. */
|
|
1813
|
+
messageId: import_zod6.z.string(),
|
|
1814
|
+
/** Gmail thread ID. */
|
|
1815
|
+
threadId: import_zod6.z.string(),
|
|
1816
|
+
/** Sender header. */
|
|
1817
|
+
from: import_zod6.z.string(),
|
|
1818
|
+
/** Decoded subject. */
|
|
1819
|
+
subject: import_zod6.z.string(),
|
|
1820
|
+
/** Gmail snippet, omitted when empty. */
|
|
1821
|
+
snippet: import_zod6.z.string().optional(),
|
|
1822
|
+
/** Receive time as RFC 3339 UTC. */
|
|
1823
|
+
receivedAt: import_zod6.z.string(),
|
|
1824
|
+
/** Whether the message has In-Reply-To or References headers. */
|
|
1825
|
+
isReply: import_zod6.z.boolean()
|
|
1826
|
+
});
|
|
1827
|
+
var MessageReceivedTriggerDefinition = { trigger: { connectorId: ConnectorID, triggerName: "messageReceived" }, description: "Receive a matching message that begins a Gmail thread." };
|
|
1828
|
+
var ReplyReceivedTriggerDefinition = { trigger: { connectorId: ConnectorID, triggerName: "replyReceived" }, description: "Receive a matching reply in an existing Gmail thread." };
|
|
1829
|
+
var UIUnitSearchQueryInput = "searchQueryInput";
|
|
1830
|
+
var UISearchQueryInputPortQuery = "query";
|
|
1831
|
+
var UIUnitEmailListInput = "emailListInput";
|
|
1832
|
+
var UIEmailListInputPortEmails = "emails";
|
|
1833
|
+
var UIUnitTextInput = "textInput";
|
|
1834
|
+
var UITextInputPortText = "text";
|
|
1835
|
+
function defineMessageReceivedTriggerBinding(config) {
|
|
1836
|
+
return (0, import_connectors_sdk12.mustTriggerBindingDefinition)({ definition: MessageReceivedTriggerDefinition, ...config });
|
|
1837
|
+
}
|
|
1838
|
+
function defineReplyReceivedTriggerBinding(config) {
|
|
1839
|
+
return (0, import_connectors_sdk12.mustTriggerBindingDefinition)({ definition: ReplyReceivedTriggerDefinition, ...config });
|
|
1840
|
+
}
|
|
1841
|
+
function newMessageReceivedTrigger(config) {
|
|
1842
|
+
const configuration = MessageReceivedTriggerConfigurationSchema.parse(config.configuration);
|
|
1843
|
+
return newStandaloneTrigger(config, MessageReceivedTriggerDefinition, configuration.searchQuery ?? "", configuration.messageMatcher ?? {}, false);
|
|
1844
|
+
}
|
|
1845
|
+
function newReplyReceivedTrigger(config) {
|
|
1846
|
+
const configuration = ReplyReceivedTriggerConfigurationSchema.parse(config.configuration);
|
|
1847
|
+
return newStandaloneTrigger(config, ReplyReceivedTriggerDefinition, configuration.searchQuery ?? "", configuration.replyMatcher ?? {}, true);
|
|
1848
|
+
}
|
|
1849
|
+
function newStandaloneTrigger(config, definition, searchQuery, matcher, requiresReply) {
|
|
1850
|
+
const client = gmailClientOf(config.connection);
|
|
1851
|
+
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}"`);
|
|
1852
|
+
const source = new MessagePollingTriggerSource(client, config.connection.reference, definition.trigger.triggerName, "", searchQuery, matcher, requiresReply);
|
|
1853
|
+
const triggerSource = { run: (context, target) => source.run(context, target) };
|
|
1854
|
+
return (0, import_connectors_sdk12.newTrigger)({ definition, binding: { connection: config.connection.reference, trigger: definition.trigger, name: config.bindingName }, source: triggerSource, target: config.target, logger: client.triggerLogger });
|
|
1855
|
+
}
|
|
1856
|
+
var MessageTriggerRunner = class {
|
|
1857
|
+
#rootRoutes;
|
|
1858
|
+
#replyRoutes;
|
|
1859
|
+
#pollIntervalMs;
|
|
1860
|
+
/** @internal Use newMessageTriggerRunner or newProjectMessageTriggerRunner. */
|
|
1861
|
+
constructor(rootRoutes, replyRoutes, pollIntervalMs) {
|
|
1862
|
+
this.#rootRoutes = rootRoutes;
|
|
1863
|
+
this.#replyRoutes = replyRoutes;
|
|
1864
|
+
this.#pollIntervalMs = pollIntervalMs;
|
|
1865
|
+
}
|
|
1866
|
+
/**
|
|
1867
|
+
* Replay each route's durable inbox in order, roots first, then poll until the context ends. Each poll
|
|
1868
|
+
* lists every reply route before any root route, then delivers every root before any reply, and ends
|
|
1869
|
+
* at the first failure. Every later poll retries the failed event before that route's listed messages,
|
|
1870
|
+
* even after Gmail stops listing it. Gmail receives a thread's root before any reply to it, so the
|
|
1871
|
+
* root of every listed reply is in the later root listing and reaches Dex first.
|
|
1872
|
+
*
|
|
1873
|
+
* It logs through the client's logger: WARN "gmail poll failed; retrying" with the consecutive failed
|
|
1874
|
+
* polls as attempt and the poll interval as delay_ms when a list or read fails, WARN "trigger delivery
|
|
1875
|
+
* failed; retrying" with the attempt number when a target fails, INFO "trigger delivered after retry"
|
|
1876
|
+
* when a later poll delivers that message, DEBUG "trigger event ignored" with its reason, and the
|
|
1877
|
+
* durable inbox records. It rejects with TriggerDeliveryAbortedError once the context ends, and when
|
|
1878
|
+
* an inbox replay fails.
|
|
1879
|
+
*/
|
|
1880
|
+
async run(context) {
|
|
1881
|
+
await replayMessageTriggerRoutes(context, [...this.#rootRoutes, ...this.#replyRoutes]);
|
|
1882
|
+
await runMessageTriggerRoutes(context, () => pollMessageTriggerRoutes(context, this.#rootRoutes, this.#replyRoutes), this.#pollIntervalMs);
|
|
1883
|
+
}
|
|
1884
|
+
};
|
|
1885
|
+
function newMessageTriggerRunner(config) {
|
|
1886
|
+
const client = gmailClientOf(config.connection);
|
|
1887
|
+
const bindingKeys = /* @__PURE__ */ new Set();
|
|
1888
|
+
const route = (triggerName, bindingName, target, searchQuery, matcher, requiresReply) => {
|
|
1889
|
+
const trimmedBindingName = bindingName?.trim();
|
|
1890
|
+
if (!trimmedBindingName || !target) throw new TypeError("Gmail message Trigger binding name and target are required");
|
|
1891
|
+
const bindingKey = `${triggerName}\0${trimmedBindingName}`;
|
|
1892
|
+
if (bindingKeys.has(bindingKey)) throw new TypeError(`Gmail message Trigger binding name "${trimmedBindingName}" is duplicated`);
|
|
1893
|
+
bindingKeys.add(bindingKey);
|
|
1894
|
+
return { source: new MessagePollingTriggerSource(client, config.connection.reference, triggerName, bindingName, searchQuery ?? "", matcher ?? {}, requiresReply), target };
|
|
1895
|
+
};
|
|
1896
|
+
const rootRoutes = (config.messageReceivedRoutes ?? []).map((root) => {
|
|
1897
|
+
const configuration = MessageReceivedTriggerConfigurationSchema.parse(root.configuration);
|
|
1898
|
+
return route("messageReceived", root.bindingName, root.target, configuration.searchQuery, configuration.messageMatcher, false);
|
|
1899
|
+
});
|
|
1900
|
+
const replyRoutes = (config.replyReceivedRoutes ?? []).map((reply) => {
|
|
1901
|
+
const configuration = ReplyReceivedTriggerConfigurationSchema.parse(reply.configuration);
|
|
1902
|
+
return route("replyReceived", reply.bindingName, reply.target, configuration.searchQuery, configuration.replyMatcher, true);
|
|
1903
|
+
});
|
|
1904
|
+
if (rootRoutes.length + replyRoutes.length === 0) throw new TypeError("Gmail message Trigger routes are required");
|
|
1905
|
+
return new MessageTriggerRunner(rootRoutes, replyRoutes, client.triggerTransport().http.settings().pollIntervalMs);
|
|
1906
|
+
}
|
|
1907
|
+
function newProjectMessageTriggerRunner(project, connectionName, config, options = {}) {
|
|
1908
|
+
const connection = newProjectConnection(project, connectionName, options);
|
|
1909
|
+
const client = gmailClientOf(connection);
|
|
1910
|
+
const durable = (triggerName, bindingName, target, schema) => {
|
|
1911
|
+
const key = { connectorId: ConnectorID, connectionName, triggerName, bindingName };
|
|
1912
|
+
let configuration;
|
|
1913
|
+
try {
|
|
1914
|
+
configuration = (0, import_projectconfig2.decodeTriggerConfiguration)(project.configuration, key, schema);
|
|
1915
|
+
} catch (error) {
|
|
1916
|
+
throw new Error(`gmail ${triggerName} binding "${bindingName}" configuration: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
1917
|
+
}
|
|
1918
|
+
const durableTarget = (0, import_projectconfig2.newDurableTriggerTarget)(project.triggerInbox(key), key, target, { logger: client.triggerLogger, decodePayload: (_payloadJSON, payloadBytes) => MessageEventSchema.parse((0, import_projectconfig2.parseTriggerPayloadJSON)(payloadBytes)) });
|
|
1919
|
+
return { bindingName, configuration, target: durableTarget };
|
|
1920
|
+
};
|
|
1921
|
+
return newMessageTriggerRunner({
|
|
1922
|
+
connection,
|
|
1923
|
+
messageReceivedRoutes: (config.messageReceivedRoutes ?? []).map((route) => durable("messageReceived", route.bindingName, route.target, MessageReceivedTriggerConfigurationSchema)),
|
|
1924
|
+
replyReceivedRoutes: (config.replyReceivedRoutes ?? []).map((route) => durable("replyReceived", route.bindingName, route.target, ReplyReceivedTriggerConfigurationSchema))
|
|
1925
|
+
});
|
|
1926
|
+
}
|
|
1927
|
+
function gmailClientOf(connection) {
|
|
1928
|
+
if (!(connection?.operations instanceof GmailClient)) throw new TypeError("Gmail Triggers require a connection bound to a GmailClient");
|
|
1929
|
+
return connection.operations;
|
|
1930
|
+
}
|
|
1931
|
+
function validateMessageMatcher(matcher, context) {
|
|
1932
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1933
|
+
for (const sender of matcher?.senderEmails ?? []) {
|
|
1934
|
+
const address = parseMailbox(sender)?.address;
|
|
1935
|
+
if (!address) {
|
|
1936
|
+
context.addIssue({ code: "custom", message: "Gmail sender email is invalid" });
|
|
1937
|
+
return;
|
|
1938
|
+
}
|
|
1939
|
+
const canonical = address.toLowerCase();
|
|
1940
|
+
if (seen.has(canonical)) {
|
|
1941
|
+
context.addIssue({ code: "custom", message: "Gmail sender emails must be unique" });
|
|
1942
|
+
return;
|
|
1943
|
+
}
|
|
1944
|
+
seen.add(canonical);
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1528
1947
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1529
1948
|
0 && (module.exports = {
|
|
1530
1949
|
ConnectorID,
|
|
@@ -1540,8 +1959,15 @@ function newReplyToMessageStep2(configuration) {
|
|
|
1540
1959
|
GmailMessageResourceSchema,
|
|
1541
1960
|
GmailProvider,
|
|
1542
1961
|
GoogleOAuthAuthMethodID,
|
|
1962
|
+
MessageEventSchema,
|
|
1963
|
+
MessageMatcherSchema,
|
|
1964
|
+
MessageReceivedTriggerConfigurationSchema,
|
|
1965
|
+
MessageReceivedTriggerDefinition,
|
|
1543
1966
|
MessageSchema,
|
|
1967
|
+
MessageTriggerRunner,
|
|
1544
1968
|
ProviderID,
|
|
1969
|
+
ReplyReceivedTriggerConfigurationSchema,
|
|
1970
|
+
ReplyReceivedTriggerDefinition,
|
|
1545
1971
|
ReplyToMessageBranch,
|
|
1546
1972
|
ReplyToMessageDefinition,
|
|
1547
1973
|
ReplyToMessageInputSchema,
|
|
@@ -1551,18 +1977,30 @@ function newReplyToMessageStep2(configuration) {
|
|
|
1551
1977
|
SendMessageInputSchema,
|
|
1552
1978
|
SendMessageOperation,
|
|
1553
1979
|
SendMessageOutputSchema,
|
|
1980
|
+
UIEmailListInputPortEmails,
|
|
1981
|
+
UISearchQueryInputPortQuery,
|
|
1982
|
+
UITextInputPortText,
|
|
1983
|
+
UIUnitEmailListInput,
|
|
1984
|
+
UIUnitSearchQueryInput,
|
|
1985
|
+
UIUnitTextInput,
|
|
1554
1986
|
WorkspaceDomainDelegationAuthMethodID,
|
|
1555
1987
|
buildMIMEMessage,
|
|
1556
1988
|
buildReplyMIMEMessage,
|
|
1557
1989
|
decodeGmailMessage,
|
|
1990
|
+
defineMessageReceivedTriggerBinding,
|
|
1991
|
+
defineReplyReceivedTriggerBinding,
|
|
1558
1992
|
emptyMessage,
|
|
1559
1993
|
gmailClientSettings,
|
|
1560
1994
|
gmailFailure,
|
|
1561
1995
|
gmailRequestID,
|
|
1562
1996
|
gmailRetryAfterMs,
|
|
1563
1997
|
newGetMessageStep,
|
|
1998
|
+
newMessageReceivedTrigger,
|
|
1999
|
+
newMessageTriggerRunner,
|
|
1564
2000
|
newProjectConnection,
|
|
1565
2001
|
newProjectGmailClient,
|
|
2002
|
+
newProjectMessageTriggerRunner,
|
|
2003
|
+
newReplyReceivedTrigger,
|
|
1566
2004
|
newReplyToMessageStep,
|
|
1567
2005
|
newSendMessageStep,
|
|
1568
2006
|
parseMailbox,
|