@superdurable/connector-twilio-messaging 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +90 -2
- package/dex-connector.json +139 -0
- package/dist/chunk-6KLMYDTX.js +173 -0
- package/dist/connection-BQ9-3dhC.d.ts +143 -0
- package/dist/index.d.ts +283 -0
- package/dist/index.js +991 -0
- package/dist/mock.d.ts +60 -0
- package/dist/mock.js +137 -0
- package/package.json +62 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,991 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ConfigSchema,
|
|
3
|
+
Connection,
|
|
4
|
+
ConnectorID,
|
|
5
|
+
GetMessageBranch,
|
|
6
|
+
GetMessageDefinition,
|
|
7
|
+
GetMessageInputSchema,
|
|
8
|
+
MessageSchema,
|
|
9
|
+
SendMessageBranch,
|
|
10
|
+
SendMessageDefinition,
|
|
11
|
+
SendMessageInputSchema,
|
|
12
|
+
decodeCredentials,
|
|
13
|
+
newConnection,
|
|
14
|
+
newConnectionWithOperations
|
|
15
|
+
} from "./chunk-6KLMYDTX.js";
|
|
16
|
+
|
|
17
|
+
// src/client.ts
|
|
18
|
+
import { AddressRefusal, BodyTooLargeError, MaxErrorBodyBytes, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, readErrorTokens, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
|
|
19
|
+
import { SecretString, resolveCredentialAfterRejection } from "@superdurable/connectors-sdk";
|
|
20
|
+
|
|
21
|
+
// src/operations.ts
|
|
22
|
+
import { newMutationBranch, newMutationRetry, newMutationUncertain, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
|
|
23
|
+
import { CheckpointError, Fence, InsufficientTimeError } from "@superdurable/connectors-sdk/singledispatch";
|
|
24
|
+
var messagePattern = /^(SM|MM)[0-9a-f]{32}$/;
|
|
25
|
+
function requestedMessage(client, to, sender) {
|
|
26
|
+
return {
|
|
27
|
+
accountSid: client.accountSid,
|
|
28
|
+
to,
|
|
29
|
+
createdAt: zeroMessage.createdAt,
|
|
30
|
+
sentAt: zeroMessage.sentAt,
|
|
31
|
+
updatedAt: zeroMessage.updatedAt,
|
|
32
|
+
...sender?.fromAddress ? { from: sender.fromAddress } : {},
|
|
33
|
+
...sender?.messagingServiceSid ? { messagingServiceSid: sender.messagingServiceSid } : {}
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
function rejection(operation, subject, status, code) {
|
|
37
|
+
const kind = status === 401 ? "AUTHENTICATION" : status === 403 ? "AUTHORIZATION" : status === 404 ? "NOT_FOUND" : status === 409 ? "CONFLICT" : "PROVIDER_REJECTION";
|
|
38
|
+
return twilioFailure(operation, kind, `Twilio rejected the ${subject}${code > 0 ? ` with error ${code}` : ""}`);
|
|
39
|
+
}
|
|
40
|
+
var SendMessageOperation = class {
|
|
41
|
+
/** Bind one client. */
|
|
42
|
+
constructor(client) {
|
|
43
|
+
this.client = client;
|
|
44
|
+
}
|
|
45
|
+
client;
|
|
46
|
+
/** Stable manifest definition. */
|
|
47
|
+
definition() {
|
|
48
|
+
return SendMessageDefinition;
|
|
49
|
+
}
|
|
50
|
+
/** Receipt identity only; Twilio does not accept an idempotency header. */
|
|
51
|
+
idempotencyKey(callId) {
|
|
52
|
+
return callId;
|
|
53
|
+
}
|
|
54
|
+
/** Classify one fenced provider attempt. */
|
|
55
|
+
async invoke(call, input) {
|
|
56
|
+
let fence;
|
|
57
|
+
try {
|
|
58
|
+
fence = new Fence(call, SendMessageDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4);
|
|
59
|
+
} catch {
|
|
60
|
+
return newMutationBranch("defect", zeroMessage, {}, twilioFailure("sendMessage", "LOCAL_DEFECT", "Twilio dispatch fence could not be initialized"));
|
|
61
|
+
}
|
|
62
|
+
const decision = fence.decide();
|
|
63
|
+
let requested = requestedMessage(this.client, input.to?.trim() ?? "");
|
|
64
|
+
if (decision.kind === "failClosed") return newMutationUncertain(requested, twilioFailure("sendMessage", "TRANSPORT", "Twilio send checkpoint cannot confirm its outcome"), this.client.receipt(call));
|
|
65
|
+
if (decision.kind === "readBackRequired") {
|
|
66
|
+
const providerId = decision.marker?.providerId ?? "";
|
|
67
|
+
if (decision.marker?.callId !== call.id || !messagePattern.test(providerId)) return newMutationUncertain(requested, twilioFailure("sendMessage", "TRANSPORT", "Twilio send outcome cannot be confirmed"), this.client.receipt(call));
|
|
68
|
+
const auth2 = await this.client.authorization(call, "sendMessage");
|
|
69
|
+
if ("failure" in auth2) {
|
|
70
|
+
if (auth2.isTransient) return newMutationRetry(auth2.failure);
|
|
71
|
+
return newMutationUncertain(requested, twilioFailure("sendMessage", "AUTHENTICATION", "Twilio accepted message cannot be read; reconnect the connection"), this.client.receipt(call, void 0, providerId));
|
|
72
|
+
}
|
|
73
|
+
const exchange2 = await this.client.exchange(call, auth2.authorization, "GET", `${this.client.messagesURL}/${providerId}.json`);
|
|
74
|
+
if ("error" in exchange2 || exchange2.isBodyReadFailed || exchange2.response.status === 408 || exchange2.response.status === 429 || exchange2.response.status >= 500) return newMutationRetry(twilioFailure("sendMessage", "AVAILABILITY", "Twilio accepted message read-back is temporarily unavailable"));
|
|
75
|
+
if (exchange2.response.status !== 200 || exchange2.isTooLarge) return newMutationUncertain(requested, twilioFailure("sendMessage", "PROTOCOL", "Twilio accepted message could not be confirmed"), this.client.receipt(call, exchange2.response, providerId));
|
|
76
|
+
try {
|
|
77
|
+
const message = this.client.decodeMessage(exchange2.response.body, auth2.authorization);
|
|
78
|
+
if (message.sid !== providerId || message.to !== requested.to) throw new TypeError("read-back mismatch");
|
|
79
|
+
return newMutationBranch("accepted", message, this.client.receipt(call, exchange2.response, providerId));
|
|
80
|
+
} catch {
|
|
81
|
+
return newMutationUncertain(requested, twilioFailure("sendMessage", "PROTOCOL", "Twilio accepted message could not be confirmed"), this.client.receipt(call, exchange2.response, providerId));
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
let sendRequest;
|
|
85
|
+
try {
|
|
86
|
+
sendRequest = buildSendRequest(input, this.client.defaultSender);
|
|
87
|
+
} catch (cause) {
|
|
88
|
+
return newMutationBranch("defect", zeroMessage, {}, twilioFailure("sendMessage", "VALIDATION", cause instanceof Error ? cause.message : "invalid message"));
|
|
89
|
+
}
|
|
90
|
+
requested = requestedMessage(this.client, sendRequest.recipient, sendRequest.sender);
|
|
91
|
+
const auth = await this.client.authorization(call, "sendMessage");
|
|
92
|
+
if ("failure" in auth) {
|
|
93
|
+
try {
|
|
94
|
+
await fence.recordNotSent();
|
|
95
|
+
} catch {
|
|
96
|
+
return newMutationRetry(auth.failure);
|
|
97
|
+
}
|
|
98
|
+
return auth.isTransient ? newMutationRetry(auth.failure) : newMutationBranch("defect", zeroMessage, {}, auth.failure);
|
|
99
|
+
}
|
|
100
|
+
let exchange;
|
|
101
|
+
try {
|
|
102
|
+
exchange = await fence.dispatch((signal) => this.client.exchange(call, auth.authorization, "POST", `${this.client.messagesURL}.json`, sendRequest.form, signal));
|
|
103
|
+
} catch (cause) {
|
|
104
|
+
if (cause instanceof CheckpointError || cause instanceof InsufficientTimeError || cause instanceof AggregateError) return newMutationRetry(twilioFailure("sendMessage", "TRANSPORT", "Twilio dispatch checkpoint or attempt time is unavailable"));
|
|
105
|
+
return newMutationUncertain(requested, twilioFailure("sendMessage", "TRANSPORT", "Twilio message outcome is unknown"), this.client.receipt(call));
|
|
106
|
+
}
|
|
107
|
+
if ("error" in exchange) {
|
|
108
|
+
if (exchange.isProvablyNotSent) {
|
|
109
|
+
try {
|
|
110
|
+
await fence.recordCanResend();
|
|
111
|
+
} catch {
|
|
112
|
+
return newMutationRetry(twilioFailure("sendMessage", "TRANSPORT", "Twilio could not be reached and its dispatch checkpoint is unavailable"));
|
|
113
|
+
}
|
|
114
|
+
return newMutationRetry(twilioFailure("sendMessage", "TRANSPORT", "Twilio could not be reached, so no message was sent"));
|
|
115
|
+
}
|
|
116
|
+
return newMutationUncertain(requested, twilioFailure("sendMessage", "TRANSPORT", "Twilio message outcome is unknown"), this.client.receipt(call));
|
|
117
|
+
}
|
|
118
|
+
const response = exchange.response;
|
|
119
|
+
if (response.status >= 200 && response.status < 300) {
|
|
120
|
+
if (exchange.isTooLarge) return newMutationUncertain(requested, twilioFailure("sendMessage", "RESPONSE_TOO_LARGE", "Twilio accepted the request but its response exceeds the configured size limit"), this.client.receipt(call, response));
|
|
121
|
+
if (exchange.isBodyReadFailed) return newMutationUncertain(requested, twilioFailure("sendMessage", "TRANSPORT", "Twilio accepted the request but its response was interrupted"), this.client.receipt(call, response));
|
|
122
|
+
try {
|
|
123
|
+
const message = this.client.decodeMessage(response.body, auth.authorization);
|
|
124
|
+
try {
|
|
125
|
+
await fence.recordProviderId(message.sid ?? "");
|
|
126
|
+
} catch {
|
|
127
|
+
}
|
|
128
|
+
return newMutationBranch("accepted", message, this.client.receipt(call, response, message.sid));
|
|
129
|
+
} catch {
|
|
130
|
+
return newMutationUncertain(requested, twilioFailure("sendMessage", "PROTOCOL", "Twilio accepted the request but returned an unusable message"), this.client.receipt(call, response));
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if (response.status === 429 || response.status === 503) {
|
|
134
|
+
let checkpointFailed = false;
|
|
135
|
+
try {
|
|
136
|
+
await fence.recordCanResend();
|
|
137
|
+
} catch {
|
|
138
|
+
checkpointFailed = true;
|
|
139
|
+
}
|
|
140
|
+
const message = response.status === 429 ? `Twilio rate limited the message before creating it${checkpointFailed ? "; retry checkpoint is unavailable" : ""}` : checkpointFailed ? "Twilio service and retry checkpoint are temporarily unavailable" : "Twilio service is temporarily unavailable";
|
|
141
|
+
return newMutationRetry(twilioFailure("sendMessage", response.status === 429 ? "RATE_LIMIT" : "AVAILABILITY", message), retryAfter(response, this.client.currentTime()));
|
|
142
|
+
}
|
|
143
|
+
if (response.status === 401) {
|
|
144
|
+
const refreshed = await this.client.authorizationAfterRejection(call);
|
|
145
|
+
if ("authorization" in refreshed && (refreshed.authorization.username !== auth.authorization.username || refreshed.authorization.password !== auth.authorization.password)) {
|
|
146
|
+
try {
|
|
147
|
+
await fence.recordCanResend();
|
|
148
|
+
} catch {
|
|
149
|
+
return newMutationRetry(twilioFailure("sendMessage", "AUTHENTICATION", "Twilio credential changed but retry checkpoint is unavailable"));
|
|
150
|
+
}
|
|
151
|
+
return newMutationRetry(twilioFailure("sendMessage", "AUTHENTICATION", "Twilio credential changed after its rejection"));
|
|
152
|
+
}
|
|
153
|
+
const code = errorCode(response.body);
|
|
154
|
+
requested = { ...requested, ...code ? { errorCode: code } : {} };
|
|
155
|
+
return newMutationBranch("providerRejected", requested, this.client.receipt(call, response, "", code), twilioFailure("sendMessage", "AUTHENTICATION", "failure" in refreshed ? refreshed.failure.message : "Twilio rejected the message credentials; update the connection"));
|
|
156
|
+
}
|
|
157
|
+
if (response.status >= 400 && response.status < 500 && response.status !== 408 && response.status !== 409) {
|
|
158
|
+
const code = errorCode(response.body);
|
|
159
|
+
requested = { ...requested, ...code ? { errorCode: code } : {} };
|
|
160
|
+
return newMutationBranch("providerRejected", requested, this.client.receipt(call, response, "", code), rejection("sendMessage", "message", response.status, code));
|
|
161
|
+
}
|
|
162
|
+
return newMutationUncertain(requested, twilioFailure("sendMessage", "AVAILABILITY", "Twilio message outcome is unknown"), this.client.receipt(call, response));
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
var GetMessageOperation = class {
|
|
166
|
+
/** Bind one client. */
|
|
167
|
+
constructor(client) {
|
|
168
|
+
this.client = client;
|
|
169
|
+
}
|
|
170
|
+
client;
|
|
171
|
+
/** Stable manifest definition. */
|
|
172
|
+
definition() {
|
|
173
|
+
return GetMessageDefinition;
|
|
174
|
+
}
|
|
175
|
+
/** Classify one provider read. */
|
|
176
|
+
async invoke(call, input) {
|
|
177
|
+
const sid = input.messageSid?.trim() ?? "";
|
|
178
|
+
if (!messagePattern.test(sid)) return newQueryBranch("defect", zeroMessage, {}, twilioFailure("getMessage", "VALIDATION", "message SID must be SM or MM followed by 32 lowercase hexadecimal characters"));
|
|
179
|
+
const auth = await this.client.authorization(call, "getMessage");
|
|
180
|
+
if ("failure" in auth) return auth.isTransient ? newQueryRetry(auth.failure) : newQueryBranch("defect", zeroMessage, {}, auth.failure);
|
|
181
|
+
const exchange = await this.client.exchange(call, auth.authorization, "GET", `${this.client.messagesURL}/${sid}.json`);
|
|
182
|
+
if ("error" in exchange) return newQueryRetry(twilioFailure("getMessage", "TRANSPORT", "Twilio message status is temporarily unavailable"));
|
|
183
|
+
const response = exchange.response;
|
|
184
|
+
if (response.status >= 200 && response.status < 300) {
|
|
185
|
+
if (exchange.isBodyReadFailed) return newQueryRetry(twilioFailure("getMessage", "TRANSPORT", "Twilio message response was interrupted"));
|
|
186
|
+
if (exchange.isTooLarge) return newQueryBranch("invalidResponse", zeroMessage, this.client.receipt(call, response, sid), twilioFailure("getMessage", "RESPONSE_TOO_LARGE", "Twilio message response exceeds the configured size limit"));
|
|
187
|
+
try {
|
|
188
|
+
const message = this.client.decodeMessage(response.body, auth.authorization);
|
|
189
|
+
if (message.sid !== sid) throw new TypeError("message SID mismatch");
|
|
190
|
+
return newQueryBranch("found", message, this.client.receipt(call, response, sid));
|
|
191
|
+
} catch {
|
|
192
|
+
return newQueryBranch("invalidResponse", zeroMessage, this.client.receipt(call, response, sid), twilioFailure("getMessage", "PROTOCOL", "Twilio returned an invalid message"));
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (response.status === 404) return newQueryBranch("notFound", zeroMessage, this.client.receipt(call, response, sid, errorCode(response.body)), twilioFailure("getMessage", "NOT_FOUND", "Twilio has no message with that SID"));
|
|
196
|
+
if (response.status === 429) return newQueryRetry(twilioFailure("getMessage", "RATE_LIMIT", "Twilio rate limited the message query"), retryAfter(response, this.client.currentTime()));
|
|
197
|
+
if (response.status === 408 || response.status >= 500) return newQueryRetry(twilioFailure("getMessage", "AVAILABILITY", "Twilio message status is temporarily unavailable"));
|
|
198
|
+
if (response.status >= 400 && response.status < 500) {
|
|
199
|
+
const code = errorCode(response.body);
|
|
200
|
+
return newQueryBranch("providerRejected", zeroMessage, this.client.receipt(call, response, sid, code), rejection("getMessage", "message query", response.status, code));
|
|
201
|
+
}
|
|
202
|
+
return newQueryBranch("invalidResponse", zeroMessage, this.client.receipt(call, response, sid), twilioFailure("getMessage", "PROTOCOL", "Twilio returned an unexpected HTTP status"));
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
// src/client.ts
|
|
207
|
+
var accountPattern = /^AC[0-9a-f]{32}$/;
|
|
208
|
+
var keyPattern = /^SK[0-9a-f]{32}$/;
|
|
209
|
+
var messagePattern2 = /^(SM|MM)[0-9a-f]{32}$/;
|
|
210
|
+
var servicePattern = /^MG[0-9a-f]{32}$/;
|
|
211
|
+
var phonePattern = /^\+[1-9][0-9]{6,14}$/;
|
|
212
|
+
var zeroTime = "0001-01-01T00:00:00Z";
|
|
213
|
+
var defaultEndpoint = "https://api.twilio.com/2010-04-01";
|
|
214
|
+
var defaultMaxResponseBytes = 1048576;
|
|
215
|
+
var requestTimeoutMs = 2e4;
|
|
216
|
+
var defaultPollIntervalMs = 3e4;
|
|
217
|
+
var minimumPollIntervalMs = 5e3;
|
|
218
|
+
var staticCredentialRefresh = {
|
|
219
|
+
refreshRequired: () => false,
|
|
220
|
+
refresh: async () => {
|
|
221
|
+
throw new Error("Twilio credentials require manual rotation");
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
var TwilioClient = class {
|
|
225
|
+
/** Account SID used in the Messages path. */
|
|
226
|
+
accountSid;
|
|
227
|
+
/** Fully qualified Messages collection URL. */
|
|
228
|
+
messagesURL;
|
|
229
|
+
/** Optional default sender. */
|
|
230
|
+
defaultSender;
|
|
231
|
+
/** Maximum successful response size. */
|
|
232
|
+
maxResponseBytes;
|
|
233
|
+
/** Delay between messageReceived polls in milliseconds: pollIntervalMs, 30000 when omitted or zero, at least 5000. */
|
|
234
|
+
pollIntervalMs;
|
|
235
|
+
credentials;
|
|
236
|
+
send;
|
|
237
|
+
now;
|
|
238
|
+
addressPolicy;
|
|
239
|
+
/** Validate config and retain provider dependencies. */
|
|
240
|
+
constructor(config, credentials, options = {}) {
|
|
241
|
+
const accountSid = config.accountSid?.trim();
|
|
242
|
+
if (!accountPattern.test(accountSid)) throw new TypeError("Twilio accountSid must be AC followed by 32 lowercase hexadecimal characters");
|
|
243
|
+
this.accountSid = accountSid;
|
|
244
|
+
const endpoint = validateBaseURL(config.endpoint || defaultEndpoint);
|
|
245
|
+
this.messagesURL = `${endpoint}/Accounts/${accountSid}/Messages`;
|
|
246
|
+
this.addressPolicy = "privateNetworkHTTP";
|
|
247
|
+
this.maxResponseBytes = config.maxResponseBytes || defaultMaxResponseBytes;
|
|
248
|
+
if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0) throw new TypeError("Twilio maxResponseBytes must be positive");
|
|
249
|
+
this.pollIntervalMs = config.pollIntervalMs || defaultPollIntervalMs;
|
|
250
|
+
if (!Number.isSafeInteger(this.pollIntervalMs) || this.pollIntervalMs < minimumPollIntervalMs) throw new TypeError("Twilio pollInterval must be at least 5s");
|
|
251
|
+
this.defaultSender = config.defaultSender?.trim() ? parseSender(config.defaultSender) : { fromAddress: "", messagingServiceSid: "" };
|
|
252
|
+
if (!credentials) throw new TypeError("credential provider is required");
|
|
253
|
+
this.credentials = credentials;
|
|
254
|
+
this.send = options.send ?? sendProviderRequest;
|
|
255
|
+
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
256
|
+
}
|
|
257
|
+
/** Bind the non-idempotent send mutation. */
|
|
258
|
+
sendMessage() {
|
|
259
|
+
return new SendMessageOperation(this);
|
|
260
|
+
}
|
|
261
|
+
/** Bind the message status query. */
|
|
262
|
+
getMessage() {
|
|
263
|
+
return new GetMessageOperation(this);
|
|
264
|
+
}
|
|
265
|
+
/** Resolve current credentials without leaking lookup errors. */
|
|
266
|
+
async authorization(call, operation) {
|
|
267
|
+
let credentials;
|
|
268
|
+
try {
|
|
269
|
+
credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
|
|
270
|
+
} catch (error) {
|
|
271
|
+
if (error instanceof Error && (error.name === "ReauthorizationRequiredError" || error.message.includes("reauthorization required"))) return { failure: twilioFailure(operation, "AUTHENTICATION", "Twilio connection credentials require reauthorization; reconnect the connection"), isTransient: false };
|
|
272
|
+
return { failure: twilioFailure(operation, "AVAILABILITY", "Twilio credential lookup is temporarily unavailable"), isTransient: true };
|
|
273
|
+
}
|
|
274
|
+
return this.validateAuthorization(credentials, operation);
|
|
275
|
+
}
|
|
276
|
+
/** Ask the credential host for a newer credential after a rejected send. */
|
|
277
|
+
async authorizationAfterRejection(call) {
|
|
278
|
+
let credentials;
|
|
279
|
+
try {
|
|
280
|
+
credentials = await resolveCredentialAfterRejection(this.credentials, call, staticCredentialRefresh, call.context.cancellationSignal);
|
|
281
|
+
} catch (error) {
|
|
282
|
+
if (error instanceof TypeError && error.message.includes("does not support refresh")) return { failure: twilioFailure("sendMessage", "AUTHENTICATION", "Twilio credential cannot be refreshed after rejection"), isTransient: false };
|
|
283
|
+
if (error instanceof Error && error.name === "ReauthorizationRequiredError") return { failure: twilioFailure("sendMessage", "AUTHENTICATION", "Twilio connection credentials require reauthorization; reconnect the connection"), isTransient: false };
|
|
284
|
+
if (error instanceof Error && error.name === "RejectedCredentialNotRefreshedError") return { failure: twilioFailure("sendMessage", "AUTHENTICATION", "Twilio rejected the message credentials; update the connection"), isTransient: false };
|
|
285
|
+
return { failure: twilioFailure("sendMessage", "AVAILABILITY", "Twilio credential refresh is temporarily unavailable"), isTransient: true };
|
|
286
|
+
}
|
|
287
|
+
return this.validateAuthorization(credentials, "sendMessage");
|
|
288
|
+
}
|
|
289
|
+
validateAuthorization(credentials, operation) {
|
|
290
|
+
let username = "";
|
|
291
|
+
let password = "";
|
|
292
|
+
if (credentials.authMethodId === "auth-token" && credentials.authToken instanceof SecretString) {
|
|
293
|
+
username = this.accountSid;
|
|
294
|
+
password = credentials.authToken.reveal();
|
|
295
|
+
} else if (credentials.authMethodId === "api-key" && credentials.apiKeySecret instanceof SecretString) {
|
|
296
|
+
username = credentials.apiKeySid?.trim() ?? "";
|
|
297
|
+
password = credentials.apiKeySecret.reveal();
|
|
298
|
+
if (!keyPattern.test(username)) return { failure: twilioFailure(operation, "AUTHENTICATION", "Twilio api_key_sid must be SK followed by 32 lowercase hexadecimal characters"), isTransient: false };
|
|
299
|
+
} else return { failure: twilioFailure(operation, "AUTHENTICATION", "Twilio connection credentials are incomplete; update or reconnect the connection"), isTransient: false };
|
|
300
|
+
if (!isHeaderSafeCredential(password)) return { failure: twilioFailure(operation, "AUTHENTICATION", "Twilio credential secret is malformed"), isTransient: false };
|
|
301
|
+
return { authorization: { username, password } };
|
|
302
|
+
}
|
|
303
|
+
/** Send one request; only successful responses use the configured body limit. */
|
|
304
|
+
async exchange(call, authorization, method, url, form, signal) {
|
|
305
|
+
const body = form ? Buffer.from(encodeGoForm(form), "utf8") : void 0;
|
|
306
|
+
const request = {
|
|
307
|
+
url,
|
|
308
|
+
method,
|
|
309
|
+
headers: { Authorization: `Basic ${Buffer.from(`${authorization.username}:${authorization.password}`).toString("base64")}`, Accept: "application/json", ...body ? { "Content-Type": "application/x-www-form-urlencoded" } : {} },
|
|
310
|
+
...body ? { body } : {},
|
|
311
|
+
maxResponseBytes: Math.max(this.maxResponseBytes, MaxErrorBodyBytes),
|
|
312
|
+
addressPolicy: this.addressPolicy,
|
|
313
|
+
timeoutMs: requestTimeoutMs,
|
|
314
|
+
signal: signal ?? call.context.cancellationSignal
|
|
315
|
+
};
|
|
316
|
+
try {
|
|
317
|
+
const response = await this.send(request);
|
|
318
|
+
return { response, isTooLarge: response.status >= 200 && response.status < 300 && response.body.length > this.maxResponseBytes, isBodyReadFailed: false };
|
|
319
|
+
} catch (error) {
|
|
320
|
+
if (error instanceof BodyTooLargeError && error.status !== void 0 && error.headers) {
|
|
321
|
+
if (error.status < 200 || error.status >= 300) return { response: { status: error.status, headers: error.headers, body: Buffer.alloc(0) }, isTooLarge: false, isBodyReadFailed: false };
|
|
322
|
+
return { response: { status: error.status, headers: error.headers, body: Buffer.alloc(0) }, isTooLarge: true, isBodyReadFailed: false };
|
|
323
|
+
}
|
|
324
|
+
const safe = error instanceof Error ? error : new Error("Twilio transport failed");
|
|
325
|
+
return { error: safe, isProvablyNotSent: error instanceof AddressRefusal || error instanceof ProviderTransportError && error.isProvablyNotSent };
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
/** Decode a safe Twilio Message subset. */
|
|
329
|
+
decodeMessage(body, authorization) {
|
|
330
|
+
let parsed;
|
|
331
|
+
try {
|
|
332
|
+
parsed = parseTwilioJSON(Buffer.from(body).toString("utf8"));
|
|
333
|
+
} catch {
|
|
334
|
+
throw new TypeError("Twilio returned an invalid message");
|
|
335
|
+
}
|
|
336
|
+
return this.convertMessageResource(parsed.value, parsed.rawIntegerTokens, authorization);
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Validate one decoded Message resource of this account and keep its safe view. rawIntegerTokens holds the
|
|
340
|
+
* source text of numeric count fields from parseTwilioJSON. Throws TypeError for another account, a
|
|
341
|
+
* malformed field, or a field that reflects the credential.
|
|
342
|
+
*/
|
|
343
|
+
convertMessageResource(value, rawIntegerTokens, authorization) {
|
|
344
|
+
const resource = value;
|
|
345
|
+
if (!resource || typeof resource !== "object" || Array.isArray(resource)) throw new TypeError("Twilio returned an invalid message");
|
|
346
|
+
const required = (key) => {
|
|
347
|
+
const value2 = resource[key];
|
|
348
|
+
if (typeof value2 !== "string") throw new TypeError("Twilio returned an invalid message");
|
|
349
|
+
return value2;
|
|
350
|
+
};
|
|
351
|
+
const optional = (key) => {
|
|
352
|
+
const value2 = resource[key];
|
|
353
|
+
if (value2 == null) return "";
|
|
354
|
+
if (typeof value2 !== "string") throw new TypeError("Twilio returned an invalid message");
|
|
355
|
+
return value2;
|
|
356
|
+
};
|
|
357
|
+
const sid = required("sid");
|
|
358
|
+
const accountSid = required("account_sid");
|
|
359
|
+
const to = required("to");
|
|
360
|
+
const status = required("status");
|
|
361
|
+
if (!messagePattern2.test(sid) || accountSid !== this.accountSid || !/^[a-z_]{1,32}$/.test(status) || !safeAddress(to)) throw new TypeError("Twilio returned an invalid message");
|
|
362
|
+
const service = optional("messaging_service_sid");
|
|
363
|
+
const from = optional("from");
|
|
364
|
+
const direction = optional("direction");
|
|
365
|
+
const price = optional("price");
|
|
366
|
+
const priceUnit = optional("price_unit");
|
|
367
|
+
if (service && !servicePattern.test(service) || from && !safeAddress(from)) throw new TypeError("Twilio returned an invalid message");
|
|
368
|
+
const message = {
|
|
369
|
+
sid,
|
|
370
|
+
accountSid,
|
|
371
|
+
to,
|
|
372
|
+
status,
|
|
373
|
+
createdAt: twilioTime(optional("date_created")),
|
|
374
|
+
sentAt: twilioTime(optional("date_sent")),
|
|
375
|
+
updatedAt: twilioTime(optional("date_updated")),
|
|
376
|
+
...service ? { messagingServiceSid: service } : {},
|
|
377
|
+
...from ? { from } : {},
|
|
378
|
+
.../^[a-z-]{1,32}$/.test(direction) ? { direction } : {},
|
|
379
|
+
.../^-?[0-9]{1,12}(\.[0-9]{1,12})?$/.test(price) ? { price } : {},
|
|
380
|
+
.../^[A-Z]{3}$/.test(priceUnit) ? { priceUnit } : {}
|
|
381
|
+
};
|
|
382
|
+
for (const [key, target] of [["error_code", "errorCode"], ["num_segments", "segmentCount"], ["num_media", "mediaCount"]]) {
|
|
383
|
+
const value2 = resource[key];
|
|
384
|
+
if (value2 !== null && value2 !== void 0) {
|
|
385
|
+
const decimalText = typeof value2 === "number" ? rawIntegerTokens.get(resource)?.get(key) : value2;
|
|
386
|
+
if (typeof value2 !== "string" && typeof value2 !== "number" || value2 !== "" && !/^[0-9]{1,9}$/.test(String(decimalText))) throw new TypeError("Twilio returned an invalid message");
|
|
387
|
+
const count = Number(value2);
|
|
388
|
+
if (count !== 0) message[target] = count;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
if ([message.sid, message.accountSid, message.messagingServiceSid, message.from, message.to, message.status, message.direction, message.price, message.priceUnit].some((value2) => value2 !== void 0 && value2.includes(authorization.password))) throw new TypeError("Twilio returned an invalid message");
|
|
392
|
+
return message;
|
|
393
|
+
}
|
|
394
|
+
/** Make a safe receipt with exact provider IDs. */
|
|
395
|
+
receipt(call, response, objectId = "", errorCode2 = 0) {
|
|
396
|
+
const raw = response?.headers["twilio-request-id"];
|
|
397
|
+
const requestId = Array.isArray(raw) ? raw[0] : raw;
|
|
398
|
+
return {
|
|
399
|
+
callId: call.id,
|
|
400
|
+
idempotencyKey: call.idempotencyKey ?? "",
|
|
401
|
+
provider: "twilio",
|
|
402
|
+
observedAt: this.now().toISOString(),
|
|
403
|
+
...objectId ? { providerObjectId: objectId } : {},
|
|
404
|
+
...requestId && safeAddress(requestId) ? { providerRequestId: requestId } : {},
|
|
405
|
+
...errorCode2 > 0 ? { metadata: { twilioErrorCode: String(errorCode2) } } : {}
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
/** Current receipt time for Retry-After. */
|
|
409
|
+
currentTime() {
|
|
410
|
+
return this.now();
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
function parseTwilioJSON(text) {
|
|
414
|
+
const rawIntegerTokens = /* @__PURE__ */ new WeakMap();
|
|
415
|
+
const parseWithSource = JSON.parse;
|
|
416
|
+
const value = parseWithSource(text, function(key, value2, context) {
|
|
417
|
+
if (key === "error_code" || key === "num_segments" || key === "num_media") {
|
|
418
|
+
let tokens = rawIntegerTokens.get(this);
|
|
419
|
+
if (!tokens) {
|
|
420
|
+
tokens = /* @__PURE__ */ new Map();
|
|
421
|
+
rawIntegerTokens.set(this, tokens);
|
|
422
|
+
}
|
|
423
|
+
tokens.set(key, context.source ?? "");
|
|
424
|
+
}
|
|
425
|
+
return value2;
|
|
426
|
+
});
|
|
427
|
+
return { value, rawIntegerTokens };
|
|
428
|
+
}
|
|
429
|
+
function isE164PhoneNumber(value) {
|
|
430
|
+
return phonePattern.test(value);
|
|
431
|
+
}
|
|
432
|
+
function twilioFailure(operation, kind, message) {
|
|
433
|
+
return { kind, provider: "twilio", operation, message };
|
|
434
|
+
}
|
|
435
|
+
function parseSender(value) {
|
|
436
|
+
const sender = value.trim();
|
|
437
|
+
if (servicePattern.test(sender)) return { fromAddress: "", messagingServiceSid: sender };
|
|
438
|
+
if (phonePattern.test(sender) || isWhatsApp(sender)) return { fromAddress: sender, messagingServiceSid: "" };
|
|
439
|
+
throw new TypeError("sender must be an E.164 phone number, a whatsapp:+E.164 address, or an MG Messaging Service SID");
|
|
440
|
+
}
|
|
441
|
+
function isWhatsApp(value) {
|
|
442
|
+
return value.startsWith("whatsapp:") && phonePattern.test(value.slice(9));
|
|
443
|
+
}
|
|
444
|
+
function buildSendRequest(input, defaultSender) {
|
|
445
|
+
const recipient = input.to.trim();
|
|
446
|
+
const isWhatsAppRecipient = isWhatsApp(recipient);
|
|
447
|
+
if (!phonePattern.test(recipient) && !isWhatsAppRecipient) throw new TypeError("recipient must be an E.164 phone number or a whatsapp:+E.164 address");
|
|
448
|
+
const sender = input.sender?.trim() ? parseSender(input.sender) : defaultSender;
|
|
449
|
+
if (!sender.fromAddress && !sender.messagingServiceSid) throw new TypeError("sender is required: set defaultSender on the connection or sender on the input");
|
|
450
|
+
if (sender.fromAddress && isWhatsApp(sender.fromAddress) !== isWhatsAppRecipient) throw new TypeError("sender and recipient must both be whatsapp: addresses or both be phone numbers");
|
|
451
|
+
const body = input.body ?? "";
|
|
452
|
+
const media = input.mediaUrls ?? [];
|
|
453
|
+
if ([...body].length > 1600) throw new TypeError("body cannot exceed 1600 characters");
|
|
454
|
+
if (!body.trim() && media.length === 0) throw new TypeError("body or at least one media URL is required");
|
|
455
|
+
if (media.length > 10) throw new TypeError("at most 10 media URLs are allowed");
|
|
456
|
+
const form = new URLSearchParams();
|
|
457
|
+
if (body) form.append("Body", body);
|
|
458
|
+
if (sender.fromAddress) form.append("From", sender.fromAddress);
|
|
459
|
+
else form.append("MessagingServiceSid", sender.messagingServiceSid);
|
|
460
|
+
for (const value of media) {
|
|
461
|
+
validateMediaURL(value);
|
|
462
|
+
form.append("MediaUrl", value);
|
|
463
|
+
}
|
|
464
|
+
form.append("To", recipient);
|
|
465
|
+
form.sort();
|
|
466
|
+
return { recipient, sender, form };
|
|
467
|
+
}
|
|
468
|
+
function encodeGoForm(form) {
|
|
469
|
+
const queryEscape = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g, "+");
|
|
470
|
+
return [...form].map(([key, value]) => `${queryEscape(key)}=${queryEscape(value)}`).join("&");
|
|
471
|
+
}
|
|
472
|
+
function validateMediaURL(value) {
|
|
473
|
+
if (Buffer.byteLength(value) > 2048 || !/^[!-~]+$/.test(value)) throw new TypeError("media URLs must be printable ASCII without spaces and at most 2048 bytes");
|
|
474
|
+
if (!/^https:\/\/[^/?#@\\]+(?:[/?#]|$)/.test(value)) throw new TypeError("media URLs must be absolute HTTPS URLs without credentials");
|
|
475
|
+
let parsed;
|
|
476
|
+
try {
|
|
477
|
+
parsed = new URL(value);
|
|
478
|
+
} catch {
|
|
479
|
+
throw new TypeError("media URLs must be absolute HTTPS URLs without credentials");
|
|
480
|
+
}
|
|
481
|
+
if (parsed.protocol !== "https:" || !parsed.hostname || parsed.username || parsed.password) throw new TypeError("media URLs must be absolute HTTPS URLs without credentials");
|
|
482
|
+
}
|
|
483
|
+
function safeAddress(value) {
|
|
484
|
+
return Buffer.byteLength(value) > 0 && Buffer.byteLength(value) <= 64 && /^[\x20-\x7e]+$/.test(value);
|
|
485
|
+
}
|
|
486
|
+
function twilioTime(value) {
|
|
487
|
+
const parts = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{2}):(\d{2}):(\d{2}) ([+-])(\d{2})(\d{2})$/.exec(value);
|
|
488
|
+
if (!parts) return zeroTime;
|
|
489
|
+
const [, dayText, monthText, yearText, hourText, minuteText, secondText, sign, offsetHourText, offsetMinuteText] = parts;
|
|
490
|
+
const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
|
491
|
+
const year = Number(yearText), month = months.indexOf(monthText ?? ""), day = Number(dayText), hour = Number(hourText), minute = Number(minuteText), second = Number(secondText);
|
|
492
|
+
const offsetHours = Number(offsetHourText), offsetMinutes = Number(offsetMinuteText);
|
|
493
|
+
const monthEnd = /* @__PURE__ */ new Date(0);
|
|
494
|
+
monthEnd.setUTCFullYear(year, month + 1, 0);
|
|
495
|
+
const daysInMonth = monthEnd.getUTCDate();
|
|
496
|
+
if (day < 1 || day > daysInMonth || hour > 23 || minute > 59 || second > 59 || offsetMinutes > 59) return zeroTime;
|
|
497
|
+
const instant = /* @__PURE__ */ new Date(0);
|
|
498
|
+
instant.setUTCFullYear(year, month, day);
|
|
499
|
+
instant.setUTCHours(hour, minute, second, 0);
|
|
500
|
+
const offset = (offsetHours * 60 + offsetMinutes) * 6e4;
|
|
501
|
+
const adjusted = new Date(instant.getTime() + (sign === "+" ? -offset : offset));
|
|
502
|
+
return adjusted.toISOString().replace(".000Z", "Z");
|
|
503
|
+
}
|
|
504
|
+
function errorCode(body) {
|
|
505
|
+
const value = readErrorTokens(body, ["/code"])[0];
|
|
506
|
+
return value && /^[0-9]{1,9}$/.test(value) ? Number(value) : 0;
|
|
507
|
+
}
|
|
508
|
+
function retryAfter(response, now) {
|
|
509
|
+
const raw = response.headers["retry-after"];
|
|
510
|
+
return parseRetryAfter(Array.isArray(raw) ? raw[0] ?? "" : raw ?? "", now);
|
|
511
|
+
}
|
|
512
|
+
var zeroMessage = { accountSid: "", to: "", createdAt: zeroTime, sentAt: zeroTime, updatedAt: zeroTime };
|
|
513
|
+
|
|
514
|
+
// src/project.ts
|
|
515
|
+
import { newCredentialProvider } from "@superdurable/connectors-sdk/projectconfig";
|
|
516
|
+
import { z } from "zod";
|
|
517
|
+
function newConnection2(client, name) {
|
|
518
|
+
return newConnection(client, { provider: "twilio", name });
|
|
519
|
+
}
|
|
520
|
+
function newProjectConnection(project, connectionName, options = {}) {
|
|
521
|
+
const selected = project.configuration.connections.find((entry) => entry.connectorId === "twilio-messaging" && entry.connectionName === connectionName);
|
|
522
|
+
if (!selected || selected.provider !== "twilio") throw new TypeError("Twilio project connection is not configured");
|
|
523
|
+
const settings = z.object({
|
|
524
|
+
accountSid: z.string(),
|
|
525
|
+
defaultSender: z.string().optional(),
|
|
526
|
+
endpoint: z.string().optional(),
|
|
527
|
+
maxResponseBytes: z.number().int().optional(),
|
|
528
|
+
// pollInterval is a Go time.Duration in integer nanoseconds, as Go's json.Unmarshal reads it; zero keeps the default.
|
|
529
|
+
pollInterval: z.number().int().safe().optional()
|
|
530
|
+
}).parse(selected.configuration);
|
|
531
|
+
const { pollInterval, ...configured } = settings;
|
|
532
|
+
const config = ConfigSchema.parse({ ...configured, ...pollInterval ? { pollIntervalMs: Math.ceil(pollInterval / 1e6) } : {} });
|
|
533
|
+
const credentialProvider = newCredentialProvider(project.connections, { connectorId: "twilio-messaging", connectionName }, decodeCredentials);
|
|
534
|
+
return newConnection2(new TwilioClient(config, credentialProvider, options), connectionName);
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// src/generated/steps.ts
|
|
538
|
+
import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
|
|
539
|
+
function newSendMessageStep(configuration) {
|
|
540
|
+
const { connection, connectionName, accepted, providerRejected, uncertain, defect, ...stepConfiguration } = configuration;
|
|
541
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
542
|
+
return newMutationStep({ ...stepConfiguration, operation: connection.operations.sendMessage(), connection: connection.reference, branches: [
|
|
543
|
+
goToBranch("accepted", accepted),
|
|
544
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
545
|
+
...uncertain ? [goToBranch("uncertain", uncertain)] : [],
|
|
546
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
547
|
+
] });
|
|
548
|
+
}
|
|
549
|
+
function newGetMessageStep(configuration) {
|
|
550
|
+
const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
|
|
551
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
552
|
+
return newQueryStep({ ...stepConfiguration, operation: connection.operations.getMessage(), connection: connection.reference, branches: [
|
|
553
|
+
goToBranch("found", found),
|
|
554
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
555
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
556
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
557
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
558
|
+
] });
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// src/trigger.ts
|
|
562
|
+
import {
|
|
563
|
+
mustTriggerBindingDefinition,
|
|
564
|
+
newTrigger
|
|
565
|
+
} from "@superdurable/connectors-sdk";
|
|
566
|
+
import { newBindingPoller, newBindingTriggerSource, newMemoryCursorStore, newRunner } from "@superdurable/connectors-sdk/pollingtrigger";
|
|
567
|
+
import { ObjectNotFoundError, decodeTriggerConfiguration, newDurableTriggerTarget, parseTriggerPayloadJSON } from "@superdurable/connectors-sdk/projectconfig";
|
|
568
|
+
import { z as z2 } from "zod";
|
|
569
|
+
|
|
570
|
+
// src/inbound_message_fetcher.ts
|
|
571
|
+
import { createHash } from "crypto";
|
|
572
|
+
import {
|
|
573
|
+
MaxChangesPerPage,
|
|
574
|
+
applyKeyedSnapshotChanges,
|
|
575
|
+
markCursorInvalid,
|
|
576
|
+
markRateLimited,
|
|
577
|
+
newTriggerCredentialCall,
|
|
578
|
+
waitForPollRequest
|
|
579
|
+
} from "@superdurable/connectors-sdk/pollingtrigger";
|
|
580
|
+
import { encodeGoJSONValue } from "@superdurable/connectors-sdk/projectconfig";
|
|
581
|
+
var inboundListPageSize = 200;
|
|
582
|
+
var maximumWindowPages = 10;
|
|
583
|
+
var maximumWindowNarrowings = 34;
|
|
584
|
+
var inboundLookbackSeconds = 120;
|
|
585
|
+
var receivingHoldLimitMs = 10 * 6e4;
|
|
586
|
+
var zeroTime2 = "0001-01-01T00:00:00Z";
|
|
587
|
+
var int64Minimum = -(2n ** 63n);
|
|
588
|
+
var int64Maximum = 2n ** 63n - 1n;
|
|
589
|
+
var loneSurrogatePattern = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
|
|
590
|
+
var resourceStringFields = ["sid", "account_sid", "messaging_service_sid", "from", "to", "status", "direction", "price", "price_unit", "date_created", "date_sent", "date_updated", "body"];
|
|
591
|
+
var inboundSnapshotOptions = {};
|
|
592
|
+
function messageReceivedEventId(messageSid) {
|
|
593
|
+
return `twilio-message-${messageSid}`;
|
|
594
|
+
}
|
|
595
|
+
function newMessageReceivedTriggerEvent(message, body, now) {
|
|
596
|
+
const dated = [message.sentAt, message.createdAt].find((value) => value !== zeroTime2);
|
|
597
|
+
const occurredAt = dated === void 0 ? now : new Date(dated);
|
|
598
|
+
return { id: messageReceivedEventId(message.sid ?? ""), occurredAt, payload: { message: MessageSchema.parse(message), ...body ? { body } : {} } };
|
|
599
|
+
}
|
|
600
|
+
var InboundSnapshotKey = class {
|
|
601
|
+
/** Wrap one dated message key. */
|
|
602
|
+
constructor(key) {
|
|
603
|
+
this.key = key;
|
|
604
|
+
}
|
|
605
|
+
key;
|
|
606
|
+
/** The dated message key. */
|
|
607
|
+
snapshotKey() {
|
|
608
|
+
return this.key;
|
|
609
|
+
}
|
|
610
|
+
/** A hash of the key; a delivered message never changes its entry. */
|
|
611
|
+
snapshotHash() {
|
|
612
|
+
return createHash("sha256").update(this.key, "utf8").digest("hex").slice(0, 16);
|
|
613
|
+
}
|
|
614
|
+
/** Undefined because entries keep no values. */
|
|
615
|
+
snapshotValue() {
|
|
616
|
+
return void 0;
|
|
617
|
+
}
|
|
618
|
+
};
|
|
619
|
+
function inboundSnapshotKeyFor(listed) {
|
|
620
|
+
const second = listed.sentAtSecond < 0 ? `-${String(-listed.sentAtSecond).padStart(10, "0")}` : String(listed.sentAtSecond).padStart(11, "0");
|
|
621
|
+
return `${second}-${listed.message.sid ?? ""}`;
|
|
622
|
+
}
|
|
623
|
+
function inboundSnapshotKeySecond(key) {
|
|
624
|
+
const separator = key.indexOf("-");
|
|
625
|
+
if (separator < 0) return void 0;
|
|
626
|
+
const prefix = key.slice(0, separator);
|
|
627
|
+
if (!/^[+-]?[0-9]+$/.test(prefix)) return void 0;
|
|
628
|
+
const second = BigInt(prefix);
|
|
629
|
+
return second < int64Minimum || second > int64Maximum ? void 0 : Number(second);
|
|
630
|
+
}
|
|
631
|
+
function latestSentAtSecond(messages) {
|
|
632
|
+
return messages.reduce((latest, listed) => Math.max(latest, listed.sentAtSecond), 0);
|
|
633
|
+
}
|
|
634
|
+
function unixSecond(moment) {
|
|
635
|
+
return Math.floor(moment.getTime() / 1e3);
|
|
636
|
+
}
|
|
637
|
+
function formatRFC3339Second(second) {
|
|
638
|
+
return new Date(second * 1e3).toISOString().replace(".000Z", "Z");
|
|
639
|
+
}
|
|
640
|
+
function goQueryEscape(value) {
|
|
641
|
+
return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g, "+");
|
|
642
|
+
}
|
|
643
|
+
function encodeGoQuery(query) {
|
|
644
|
+
return Object.keys(query).sort().map((name) => `${goQueryEscape(name)}=${goQueryEscape(query[name] ?? "")}`).join("&");
|
|
645
|
+
}
|
|
646
|
+
function decodeInboundMessageCursorToken(token) {
|
|
647
|
+
const watermarkSources = /* @__PURE__ */ new Map();
|
|
648
|
+
let position;
|
|
649
|
+
try {
|
|
650
|
+
const parseWithSource = JSON.parse;
|
|
651
|
+
position = parseWithSource(token, function(key, value, context) {
|
|
652
|
+
if (key.toLowerCase() === "watermark" && typeof value === "number") watermarkSources.set(this, context.source ?? "");
|
|
653
|
+
return value;
|
|
654
|
+
});
|
|
655
|
+
} catch {
|
|
656
|
+
return void 0;
|
|
657
|
+
}
|
|
658
|
+
if (position === null || typeof position !== "object" || Array.isArray(position)) return void 0;
|
|
659
|
+
let accountSid = "", to = "", watermark = 0;
|
|
660
|
+
for (const [name, value] of Object.entries(position)) {
|
|
661
|
+
const fieldName = name.toLowerCase();
|
|
662
|
+
if (value === null || !["accountsid", "to", "watermark"].includes(fieldName)) continue;
|
|
663
|
+
if (fieldName === "watermark") {
|
|
664
|
+
const source = watermarkSources.get(position) ?? "";
|
|
665
|
+
if (typeof value !== "number" || !/^-?(0|[1-9][0-9]*)$/.test(source)) return void 0;
|
|
666
|
+
const parsed = BigInt(source);
|
|
667
|
+
if (parsed < int64Minimum || parsed > int64Maximum) return void 0;
|
|
668
|
+
watermark = Number(parsed);
|
|
669
|
+
} else if (typeof value !== "string") return void 0;
|
|
670
|
+
else if (fieldName === "accountsid") accountSid = value;
|
|
671
|
+
else to = value;
|
|
672
|
+
}
|
|
673
|
+
return watermark > 0 ? { accountSid, to, watermark } : void 0;
|
|
674
|
+
}
|
|
675
|
+
var InboundMessageFetcher = class {
|
|
676
|
+
/** Bind the client, the connection whose credential each request uses, and the receiving address. */
|
|
677
|
+
constructor(client, connection, to) {
|
|
678
|
+
this.client = client;
|
|
679
|
+
this.connection = connection;
|
|
680
|
+
this.to = to;
|
|
681
|
+
}
|
|
682
|
+
client;
|
|
683
|
+
connection;
|
|
684
|
+
to;
|
|
685
|
+
/** List the lookback before now and record every inbound message in it as already delivered. */
|
|
686
|
+
async seedCursor(context) {
|
|
687
|
+
const now = unixSecond(this.client.currentTime());
|
|
688
|
+
const since = now - inboundLookbackSeconds;
|
|
689
|
+
const window = await this.listWindow(context, since, 0);
|
|
690
|
+
if (window.upperBound !== 0) throw new Error(`Twilio listed more than ${inboundListPageSize * maximumWindowPages} messages within the baseline lookback`);
|
|
691
|
+
const watermark = Math.max(now, latestSentAtSecond(window.messages));
|
|
692
|
+
const delivered = window.messages.filter((listed) => this.isReceivedHere(listed) && listed.sentAtSecond >= since).map((listed) => new InboundSnapshotKey(inboundSnapshotKeyFor(listed)));
|
|
693
|
+
return this.encodeCursor(watermark, void 0, delivered);
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* Return, oldest first, up to MaxChangesPerPage inbound messages dated from the watermark minus the lookback.
|
|
697
|
+
* A message still in receiving holds the watermark until received or ten minutes old. An undecodable cursor,
|
|
698
|
+
* or one for another account or receiving address, is marked invalid.
|
|
699
|
+
*/
|
|
700
|
+
async fetchChanges(context, cursor) {
|
|
701
|
+
const position = decodeInboundMessageCursorToken(cursor.token);
|
|
702
|
+
if (!position) throw markCursorInvalid(new Error("Twilio messageReceived cursor is not decodable"));
|
|
703
|
+
if (position.accountSid !== this.client.accountSid || position.to !== this.to) throw markCursorInvalid(new Error("Twilio messageReceived cursor belongs to another account or receiving address"));
|
|
704
|
+
const since = position.watermark - inboundLookbackSeconds;
|
|
705
|
+
const window = await this.listWindow(context, since, position.watermark + 1);
|
|
706
|
+
const now = this.client.currentTime();
|
|
707
|
+
const delivered = new Set((cursor.snapshot?.entries ?? []).map((entry) => entry.key));
|
|
708
|
+
let holdBound = 0;
|
|
709
|
+
const holdAt = (second) => {
|
|
710
|
+
if (holdBound === 0 || second < holdBound) holdBound = second;
|
|
711
|
+
};
|
|
712
|
+
let pending = [];
|
|
713
|
+
for (const listed of window.messages) {
|
|
714
|
+
if (!this.isReceivedHere(listed)) continue;
|
|
715
|
+
if (listed.sentAtSecond === 0) holdAt(position.watermark);
|
|
716
|
+
else if (listed.sentAtSecond < since || delivered.has(inboundSnapshotKeyFor(listed))) continue;
|
|
717
|
+
else if (listed.message.status === MessageStatusReceiving && now.getTime() - Date.parse(listed.message.sentAt) < receivingHoldLimitMs) holdAt(listed.sentAtSecond);
|
|
718
|
+
else pending.push(listed);
|
|
719
|
+
}
|
|
720
|
+
pending.sort((left, right) => left.sentAtSecond - right.sentAtSecond || ((left.message.sid ?? "") < (right.message.sid ?? "") ? -1 : (left.message.sid ?? "") > (right.message.sid ?? "") ? 1 : 0));
|
|
721
|
+
let watermark;
|
|
722
|
+
let hasMorePages = false;
|
|
723
|
+
const isPageFull = pending.length > MaxChangesPerPage;
|
|
724
|
+
if (isPageFull) {
|
|
725
|
+
pending = pending.slice(0, MaxChangesPerPage);
|
|
726
|
+
watermark = pending[pending.length - 1].sentAtSecond;
|
|
727
|
+
hasMorePages = true;
|
|
728
|
+
} else if (window.upperBound !== 0) {
|
|
729
|
+
watermark = window.upperBound;
|
|
730
|
+
hasMorePages = true;
|
|
731
|
+
} else watermark = latestSentAtSecond(window.messages);
|
|
732
|
+
if (holdBound !== 0 && watermark > holdBound) {
|
|
733
|
+
watermark = holdBound;
|
|
734
|
+
hasMorePages = isPageFull;
|
|
735
|
+
}
|
|
736
|
+
watermark = Math.max(watermark, position.watermark);
|
|
737
|
+
const changes = pending.map((listed) => newMessageReceivedTriggerEvent(listed.message, listed.body, now));
|
|
738
|
+
const upserted = pending.map((listed) => new InboundSnapshotKey(inboundSnapshotKeyFor(listed)));
|
|
739
|
+
return { changes, next: this.encodeCursor(watermark, cursor.snapshot, upserted), hasMorePages };
|
|
740
|
+
}
|
|
741
|
+
/** Report an inbound message to the watched address, or to any address when none is set. */
|
|
742
|
+
isReceivedHere(listed) {
|
|
743
|
+
return listed.message.direction === InboundMessageDirection && (this.to === "" || listed.message.to === this.to);
|
|
744
|
+
}
|
|
745
|
+
/** List every message dated from since, halving the upper bound toward the floor when there are too many. */
|
|
746
|
+
async listWindow(context, since, minimumUpperBound) {
|
|
747
|
+
const floor = minimumUpperBound !== 0 ? Math.max(minimumUpperBound, since) : since;
|
|
748
|
+
let span = Math.max(unixSecond(this.client.currentTime()) - floor, 0);
|
|
749
|
+
let upperBound = 0;
|
|
750
|
+
for (let narrowing = 0; narrowing <= maximumWindowNarrowings; narrowing++) {
|
|
751
|
+
const { messages, isTruncated } = await this.listMessages(context, since, upperBound);
|
|
752
|
+
if (!isTruncated) return { messages, upperBound };
|
|
753
|
+
if (upperBound === floor) break;
|
|
754
|
+
span = Math.floor(span / 2);
|
|
755
|
+
upperBound = floor + span;
|
|
756
|
+
}
|
|
757
|
+
throw new Error(`Twilio listed more than ${inboundListPageSize * maximumWindowPages} messages within 2m0s of the watermark; the messageReceived Trigger cannot page through them`);
|
|
758
|
+
}
|
|
759
|
+
/**
|
|
760
|
+
* Follow next_page_uri for at most ten pages and report whether more remain. Twilio lists newest first by
|
|
761
|
+
* DateSent, so a page reaching a message dated before since ends the listing. Bounds are inclusive and also
|
|
762
|
+
* applied locally, since Twilio documents them as dates.
|
|
763
|
+
*/
|
|
764
|
+
async listMessages(context, since, upperBound) {
|
|
765
|
+
const query = { PageSize: String(inboundListPageSize), "DateSent>": formatRFC3339Second(since) };
|
|
766
|
+
if (upperBound !== 0) query["DateSent<"] = formatRFC3339Second(upperBound);
|
|
767
|
+
if (this.to) query.To = this.to;
|
|
768
|
+
let target = `${this.client.messagesURL}.json?${encodeGoQuery(query)}`;
|
|
769
|
+
const messages = [];
|
|
770
|
+
for (let pageNumber = 0; pageNumber < maximumWindowPages; pageNumber++) {
|
|
771
|
+
const { listed, nextPageURI } = await this.listPage(context, target);
|
|
772
|
+
let hasReachedSince = false;
|
|
773
|
+
for (const entry of listed) {
|
|
774
|
+
if (entry.sentAtSecond !== 0 && entry.sentAtSecond < since) {
|
|
775
|
+
hasReachedSince = true;
|
|
776
|
+
continue;
|
|
777
|
+
}
|
|
778
|
+
if (entry.sentAtSecond !== 0 && upperBound !== 0 && entry.sentAtSecond > upperBound) continue;
|
|
779
|
+
messages.push(entry);
|
|
780
|
+
}
|
|
781
|
+
if (!nextPageURI || hasReachedSince) return { messages, isTruncated: false };
|
|
782
|
+
target = this.resolveNextPage(nextPageURI);
|
|
783
|
+
}
|
|
784
|
+
return { messages, isTruncated: true };
|
|
785
|
+
}
|
|
786
|
+
/** Accept only a next page of this account's Messages list on the configured host. */
|
|
787
|
+
resolveNextPage(nextPageURI) {
|
|
788
|
+
const base = new URL(`${this.client.messagesURL}.json`);
|
|
789
|
+
const withoutFragment = nextPageURI.split("#")[0] ?? "";
|
|
790
|
+
const queryStart = withoutFragment.indexOf("?");
|
|
791
|
+
const path = queryStart < 0 ? withoutFragment : withoutFragment.slice(0, queryStart);
|
|
792
|
+
const query = queryStart < 0 ? "" : withoutFragment.slice(queryStart + 1);
|
|
793
|
+
if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(nextPageURI) || nextPageURI.startsWith("//") || path !== base.pathname || !query) {
|
|
794
|
+
throw new Error("Twilio Messages list returned an unexpected next_page_uri");
|
|
795
|
+
}
|
|
796
|
+
return `${base.protocol}//${base.host}${path}?${query}`;
|
|
797
|
+
}
|
|
798
|
+
/** Send one Messages list request; a 429 pauses the connection for Retry-After or backs off exponentially. */
|
|
799
|
+
async listPage(context, target) {
|
|
800
|
+
await waitForPollRequest(context);
|
|
801
|
+
const call = newTriggerCredentialCall(this.connection, MessageReceivedTriggerDefinition.trigger, context.signal);
|
|
802
|
+
const resolved = await this.client.authorization(call, MessageReceivedTriggerDefinition.trigger.triggerName);
|
|
803
|
+
if ("failure" in resolved) throw new Error(resolved.isTransient ? "Twilio messageReceived credentials are unavailable" : resolved.failure.message);
|
|
804
|
+
const exchange = await this.client.exchange(call, resolved.authorization, "GET", target, void 0, context.signal);
|
|
805
|
+
if ("error" in exchange) {
|
|
806
|
+
if (context.signal.aborted) throw exchange.error;
|
|
807
|
+
throw new Error("Twilio Messages list request failed before a response");
|
|
808
|
+
}
|
|
809
|
+
const { response } = exchange;
|
|
810
|
+
if (response.status === 429) {
|
|
811
|
+
throw markRateLimited(new Error(`Twilio Messages list returned HTTP 429 (error ${errorCode(response.body)})`), retryAfter(response, this.client.currentTime()));
|
|
812
|
+
}
|
|
813
|
+
if (response.status === 401 || response.status === 403) {
|
|
814
|
+
throw new Error(`Twilio rejected the Messages list credentials (HTTP ${response.status}, error ${errorCode(response.body)}); update the connection or grant the API key Messages read access`);
|
|
815
|
+
}
|
|
816
|
+
if (response.status < 200 || response.status >= 300) throw new Error(`Twilio Messages list returned HTTP ${response.status} (error ${errorCode(response.body)})`);
|
|
817
|
+
if (exchange.isBodyReadFailed) throw new Error("Twilio Messages list response was interrupted");
|
|
818
|
+
if (exchange.isTooLarge) throw new Error("Twilio Messages list page exceeds maxResponseBytes; raise it on the connection");
|
|
819
|
+
return this.decodePage(response.body, resolved.authorization);
|
|
820
|
+
}
|
|
821
|
+
decodePage(contents, authorization) {
|
|
822
|
+
const invalidJSON = "Twilio Messages list page is not valid JSON";
|
|
823
|
+
let parsed;
|
|
824
|
+
try {
|
|
825
|
+
parsed = parseTwilioJSON(Buffer.from(contents).toString("utf8"));
|
|
826
|
+
} catch {
|
|
827
|
+
throw new Error(invalidJSON);
|
|
828
|
+
}
|
|
829
|
+
const page = parsed.value;
|
|
830
|
+
if (page === null || typeof page !== "object" || Array.isArray(page)) throw new Error(invalidJSON);
|
|
831
|
+
const { messages: resources, next_page_uri: nextPageURI } = page;
|
|
832
|
+
if (!Array.isArray(resources) || nextPageURI !== void 0 && nextPageURI !== null && typeof nextPageURI !== "string") throw new Error(invalidJSON);
|
|
833
|
+
for (const resource of resources) {
|
|
834
|
+
if (resource === null || typeof resource !== "object" || Array.isArray(resource)) throw new Error(invalidJSON);
|
|
835
|
+
const fields = resource;
|
|
836
|
+
if (resourceStringFields.some((name) => fields[name] !== void 0 && fields[name] !== null && typeof fields[name] !== "string")) throw new Error(invalidJSON);
|
|
837
|
+
}
|
|
838
|
+
const listed = resources.map((resource) => {
|
|
839
|
+
let message;
|
|
840
|
+
try {
|
|
841
|
+
message = this.client.convertMessageResource(resource, parsed.rawIntegerTokens, authorization);
|
|
842
|
+
} catch {
|
|
843
|
+
throw new Error("Twilio Messages list page has an invalid message");
|
|
844
|
+
}
|
|
845
|
+
let body = (typeof resource.body === "string" ? resource.body : "").replace(loneSurrogatePattern, "\uFFFD");
|
|
846
|
+
if (authorization.password && body.includes(authorization.password)) body = "";
|
|
847
|
+
const sentAtSecond = message.sentAt === zeroTime2 ? 0 : unixSecond(new Date(message.sentAt));
|
|
848
|
+
return { message, body, sentAtSecond };
|
|
849
|
+
});
|
|
850
|
+
return { listed, nextPageURI: typeof nextPageURI === "string" ? nextPageURI : "" };
|
|
851
|
+
}
|
|
852
|
+
/** Add upserted to the snapshot and drop keys dated before the new lookback. */
|
|
853
|
+
encodeCursor(watermark, previous, upserted) {
|
|
854
|
+
const cutoff = watermark - inboundLookbackSeconds;
|
|
855
|
+
const expired = (previous?.entries ?? []).filter((entry) => {
|
|
856
|
+
const second = inboundSnapshotKeySecond(entry.key);
|
|
857
|
+
return second === void 0 || second < cutoff;
|
|
858
|
+
}).map((entry) => entry.key);
|
|
859
|
+
let snapshot;
|
|
860
|
+
try {
|
|
861
|
+
snapshot = applyKeyedSnapshotChanges(previous, upserted, expired, inboundSnapshotOptions);
|
|
862
|
+
} catch (error) {
|
|
863
|
+
throw new Error(`Twilio messageReceived snapshot: ${error instanceof Error ? error.message : "invalid"}`, { cause: error });
|
|
864
|
+
}
|
|
865
|
+
const to = this.to ? `,"to":${encodeGoJSONValue(this.to)}` : "";
|
|
866
|
+
return { token: `{"accountSid":${encodeGoJSONValue(this.client.accountSid)}${to},"watermark":${watermark}}`, snapshot };
|
|
867
|
+
}
|
|
868
|
+
};
|
|
869
|
+
|
|
870
|
+
// src/trigger.ts
|
|
871
|
+
var InboundMessageDirection = "inbound";
|
|
872
|
+
var MessageStatusReceiving = "receiving";
|
|
873
|
+
var MessageStatusReceived = "received";
|
|
874
|
+
var UIUnitReceivingAddressInput = "receivingAddressInput";
|
|
875
|
+
var UIReceivingAddressInputPortTo = "to";
|
|
876
|
+
var MessageReceivedTriggerConfigurationSchema = z2.strictObject({
|
|
877
|
+
/** The receiving number or WhatsApp sender; blank receives every inbound message of the account. */
|
|
878
|
+
to: z2.string().refine((value) => value === value.trim(), "messageReceived to must not have surrounding whitespace").refine((value) => value === "" || isE164PhoneNumber(value) || isWhatsApp(value), "messageReceived to must be an E.164 phone number or a whatsapp:+E.164 address").optional()
|
|
879
|
+
});
|
|
880
|
+
var MessageReceivedEventSchema = z2.strictObject({
|
|
881
|
+
/** The safe message view; status is received, or receiving when processing outlasted the hold limit. */
|
|
882
|
+
message: MessageSchema,
|
|
883
|
+
/** The inbound text, omitted for a media-only MMS; Twilio may redact it per the account's retention settings. */
|
|
884
|
+
body: z2.string().optional()
|
|
885
|
+
});
|
|
886
|
+
var MessageReceivedTriggerDefinition = {
|
|
887
|
+
trigger: { connectorId: ConnectorID, triggerName: "messageReceived" },
|
|
888
|
+
description: "Receive each inbound SMS, MMS, or WhatsApp message to the account, or to one Twilio number, read by polling the Twilio Messages list; the first run records a baseline and delivers no existing messages."
|
|
889
|
+
};
|
|
890
|
+
function defineMessageReceivedTriggerBinding(config) {
|
|
891
|
+
return mustTriggerBindingDefinition({ definition: MessageReceivedTriggerDefinition, ...config });
|
|
892
|
+
}
|
|
893
|
+
function decodeMessageReceivedPayload(_payloadJSON, payloadBytes) {
|
|
894
|
+
const decoded = MessageReceivedEventSchema.parse(parseTriggerPayloadJSON(payloadBytes));
|
|
895
|
+
if (!decoded.message.sid) throw new TypeError("stored Twilio inbound message is invalid");
|
|
896
|
+
return decoded;
|
|
897
|
+
}
|
|
898
|
+
function twilioClientOf(connection) {
|
|
899
|
+
if (!(connection?.operations instanceof TwilioClient)) throw new TypeError("Twilio Messaging Triggers require a connection from newConnection or newProjectConnection, not a mock connection");
|
|
900
|
+
return connection.operations;
|
|
901
|
+
}
|
|
902
|
+
function pollScheduleOf(client) {
|
|
903
|
+
return { intervalMs: client.pollIntervalMs };
|
|
904
|
+
}
|
|
905
|
+
function parseMessageReceivedTriggerConfiguration(configuration) {
|
|
906
|
+
const parsed = MessageReceivedTriggerConfigurationSchema.safeParse(configuration ?? {});
|
|
907
|
+
if (!parsed.success) throw new TypeError(`twilio-messaging messageReceived configuration: ${parsed.error.issues[0]?.message ?? "invalid"}`);
|
|
908
|
+
return parsed.data;
|
|
909
|
+
}
|
|
910
|
+
function newMessageTriggerRunner(connection, routes, logger) {
|
|
911
|
+
const client = twilioClientOf(connection);
|
|
912
|
+
if (!routes?.length) throw new TypeError("Twilio messageReceived routes are required");
|
|
913
|
+
const pollers = routes.map((route) => {
|
|
914
|
+
if (!route.bindingName?.trim() || !route.target) throw new TypeError("Twilio messageReceived binding name and target are required");
|
|
915
|
+
const configuration = parseMessageReceivedTriggerConfiguration(route.configuration);
|
|
916
|
+
return newBindingPoller({
|
|
917
|
+
definition: MessageReceivedTriggerDefinition,
|
|
918
|
+
binding: { connection: connection.reference, trigger: MessageReceivedTriggerDefinition.trigger, name: route.bindingName },
|
|
919
|
+
cursor: route.cursor ?? newMemoryCursorStore(),
|
|
920
|
+
fetcher: new InboundMessageFetcher(client, connection.reference, configuration.to ?? ""),
|
|
921
|
+
target: route.target,
|
|
922
|
+
snapshot: inboundSnapshotOptions
|
|
923
|
+
});
|
|
924
|
+
});
|
|
925
|
+
return newRunner({ connection: connection.reference, schedule: pollScheduleOf(client), pollers, ...logger ? { logger } : {} });
|
|
926
|
+
}
|
|
927
|
+
function newProjectMessageTriggerRunner(project, connection, routes, logger) {
|
|
928
|
+
if (!project) throw new TypeError("Twilio Trigger runner requires the loaded project configuration");
|
|
929
|
+
twilioClientOf(connection);
|
|
930
|
+
const triggerName = MessageReceivedTriggerDefinition.trigger.triggerName;
|
|
931
|
+
return newMessageTriggerRunner(connection, (routes ?? []).map((route) => {
|
|
932
|
+
if (!route.target) throw new TypeError(`Twilio messageReceived binding "${route.bindingName}" target is required`);
|
|
933
|
+
const key = { connectorId: ConnectorID, connectionName: connection.reference.name, triggerName, bindingName: route.bindingName };
|
|
934
|
+
let configuration = {};
|
|
935
|
+
try {
|
|
936
|
+
configuration = decodeTriggerConfiguration(project.configuration, key, MessageReceivedTriggerConfigurationSchema);
|
|
937
|
+
} catch (error) {
|
|
938
|
+
if (!(error instanceof ObjectNotFoundError)) throw new TypeError(`twilio-messaging messageReceived binding "${route.bindingName}" configuration: ${error instanceof Error ? error.message : "invalid"}`);
|
|
939
|
+
}
|
|
940
|
+
const target = newDurableTriggerTarget(project.triggerInbox(key), key, route.target, { decodePayload: decodeMessageReceivedPayload, ...logger ? { logger } : {} });
|
|
941
|
+
return { bindingName: route.bindingName, configuration, target, cursor: project.pollCursorStore(key) };
|
|
942
|
+
}), logger);
|
|
943
|
+
}
|
|
944
|
+
function newMessageReceivedTrigger(config) {
|
|
945
|
+
if (config.connectionName !== config.connection.reference.name) throw new TypeError(`twilio-messaging connector trigger connectionName "${config.connectionName}" must equal its connection's name "${config.connection.reference.name}"`);
|
|
946
|
+
const client = twilioClientOf(config.connection);
|
|
947
|
+
const configuration = parseMessageReceivedTriggerConfiguration(config.configuration);
|
|
948
|
+
const binding = { connection: config.connection.reference, trigger: MessageReceivedTriggerDefinition.trigger, name: config.bindingName };
|
|
949
|
+
const source = newBindingTriggerSource({
|
|
950
|
+
definition: MessageReceivedTriggerDefinition,
|
|
951
|
+
binding,
|
|
952
|
+
cursor: newMemoryCursorStore(),
|
|
953
|
+
fetcher: new InboundMessageFetcher(client, config.connection.reference, configuration.to ?? ""),
|
|
954
|
+
snapshot: inboundSnapshotOptions
|
|
955
|
+
}, pollScheduleOf(client), config.logger);
|
|
956
|
+
return newTrigger({ definition: MessageReceivedTriggerDefinition, binding, source, target: config.target, ...config.logger ? { logger: config.logger } : {} });
|
|
957
|
+
}
|
|
958
|
+
export {
|
|
959
|
+
ConfigSchema,
|
|
960
|
+
Connection,
|
|
961
|
+
GetMessageBranch,
|
|
962
|
+
GetMessageDefinition,
|
|
963
|
+
GetMessageInputSchema,
|
|
964
|
+
GetMessageOperation,
|
|
965
|
+
InboundMessageDirection,
|
|
966
|
+
MessageReceivedEventSchema,
|
|
967
|
+
MessageReceivedTriggerConfigurationSchema,
|
|
968
|
+
MessageReceivedTriggerDefinition,
|
|
969
|
+
MessageSchema,
|
|
970
|
+
MessageStatusReceived,
|
|
971
|
+
MessageStatusReceiving,
|
|
972
|
+
SendMessageBranch,
|
|
973
|
+
SendMessageDefinition,
|
|
974
|
+
SendMessageInputSchema,
|
|
975
|
+
SendMessageOperation,
|
|
976
|
+
TwilioClient,
|
|
977
|
+
UIReceivingAddressInputPortTo,
|
|
978
|
+
UIUnitReceivingAddressInput,
|
|
979
|
+
decodeCredentials,
|
|
980
|
+
decodeMessageReceivedPayload,
|
|
981
|
+
defineMessageReceivedTriggerBinding,
|
|
982
|
+
isE164PhoneNumber,
|
|
983
|
+
newConnection2 as newConnection,
|
|
984
|
+
newConnectionWithOperations,
|
|
985
|
+
newGetMessageStep,
|
|
986
|
+
newMessageReceivedTrigger,
|
|
987
|
+
newMessageTriggerRunner,
|
|
988
|
+
newProjectConnection,
|
|
989
|
+
newProjectMessageTriggerRunner,
|
|
990
|
+
newSendMessageStep
|
|
991
|
+
};
|