@superdurable/connector-intuit-mailchimp 0.1.0 → 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/README.md +15 -3
- package/dex-connector.json +236 -7
- package/dist/{chunk-FFHIGEZ2.js → chunk-Z4CC3JDG.js} +9 -4
- package/dist/{connection-CR-ewlWK.d.ts → connection-CNe_v9QS.d.ts} +3 -0
- package/dist/index.d.ts +146 -12
- package/dist/index.js +455 -45
- package/dist/mock.d.ts +1 -1
- package/dist/mock.js +1 -1
- package/package.json +7 -5
package/dist/index.js
CHANGED
|
@@ -61,7 +61,7 @@ import {
|
|
|
61
61
|
newConnection,
|
|
62
62
|
newConnectionWithOperations,
|
|
63
63
|
newProjectConnection
|
|
64
|
-
} from "./chunk-
|
|
64
|
+
} from "./chunk-Z4CC3JDG.js";
|
|
65
65
|
|
|
66
66
|
// src/schema.ts
|
|
67
67
|
import { z } from "zod";
|
|
@@ -213,20 +213,20 @@ var GetMemberOperation = class {
|
|
|
213
213
|
}
|
|
214
214
|
/** Read by Mailchimp subscriber hash. */
|
|
215
215
|
async invoke(call, input) {
|
|
216
|
-
const
|
|
216
|
+
const operation2 = "getMember";
|
|
217
217
|
const validation = validateMemberAddress(input.listId, input.emailAddress);
|
|
218
|
-
if (validation) return newQueryBranch("defect", emptyMember, zeroReceipt(), mailchimpFailure(
|
|
218
|
+
if (validation) return newQueryBranch("defect", emptyMember, zeroReceipt(), mailchimpFailure(operation2, "VALIDATION", validation));
|
|
219
219
|
const connection = await this.client.resolveConnection(call);
|
|
220
|
-
if (!connection) return credentialQueryDefect(
|
|
220
|
+
if (!connection) return credentialQueryDefect(operation2, emptyMember);
|
|
221
221
|
const hash = subscriberHash(input.emailAddress);
|
|
222
|
-
const result = await this.client.exchange(call, connection,
|
|
222
|
+
const result = await this.client.exchange(call, connection, operation2, "GET", memberPath(input.listId, hash));
|
|
223
223
|
const receipt = this.client.receipt(call, result, hash);
|
|
224
224
|
const classified = queryExchange(result, receipt, emptyMember, true);
|
|
225
225
|
if (classified) return classified;
|
|
226
226
|
try {
|
|
227
227
|
return newQueryBranch("found", decodeMember(result.body, hash), receipt);
|
|
228
228
|
} catch {
|
|
229
|
-
return newQueryBranch("invalidResponse", emptyMember, receipt, mailchimpFailure(
|
|
229
|
+
return newQueryBranch("invalidResponse", emptyMember, receipt, mailchimpFailure(operation2, "PROTOCOL", "Mailchimp returned an invalid contact"));
|
|
230
230
|
}
|
|
231
231
|
}
|
|
232
232
|
};
|
|
@@ -242,17 +242,17 @@ var ListMembersOperation = class {
|
|
|
242
242
|
}
|
|
243
243
|
/** Read one page with optional status and time filters. */
|
|
244
244
|
async invoke(call, input) {
|
|
245
|
-
const
|
|
245
|
+
const operation2 = "listMembers";
|
|
246
246
|
const validation = validateListInput(input);
|
|
247
|
-
if (validation) return newQueryBranch("defect", emptyPage, zeroReceipt(), mailchimpFailure(
|
|
247
|
+
if (validation) return newQueryBranch("defect", emptyPage, zeroReceipt(), mailchimpFailure(operation2, "VALIDATION", validation));
|
|
248
248
|
const connection = await this.client.resolveConnection(call);
|
|
249
|
-
if (!connection) return credentialQueryDefect(
|
|
249
|
+
if (!connection) return credentialQueryDefect(operation2, emptyPage);
|
|
250
250
|
const pageSize = input.pageSize || 100;
|
|
251
251
|
const query = new URLSearchParams({ count: String(pageSize), offset: String(input.offset ?? 0), sort_field: "last_changed", sort_dir: "ASC", fields: memberFields });
|
|
252
252
|
if (input.status) query.set("status", input.status);
|
|
253
253
|
if (input.changedSince) query.set("since_last_changed", formatMailchimpTime(input.changedSince));
|
|
254
254
|
if (input.optedInSince) query.set("since_timestamp_opt", formatMailchimpTime(input.optedInSince));
|
|
255
|
-
const result = await this.client.exchange(call, connection,
|
|
255
|
+
const result = await this.client.exchange(call, connection, operation2, "GET", `/lists/${input.listId}/members`, query);
|
|
256
256
|
const receipt = this.client.receipt(call, result, input.listId);
|
|
257
257
|
const classified = queryExchange(result, receipt, emptyPage, true);
|
|
258
258
|
if (classified) return classified;
|
|
@@ -265,7 +265,7 @@ var ListMembersOperation = class {
|
|
|
265
265
|
const offset = (input.offset ?? 0) + members.length;
|
|
266
266
|
return newQueryBranch("listed", { members, totalItems, ...members.length > 0 && offset < totalItems ? { nextOffset: offset } : {} }, receipt);
|
|
267
267
|
} catch {
|
|
268
|
-
return newQueryBranch("invalidResponse", emptyPage, receipt, mailchimpFailure(
|
|
268
|
+
return newQueryBranch("invalidResponse", emptyPage, receipt, mailchimpFailure(operation2, "PROTOCOL", "Mailchimp returned an invalid page of contacts"));
|
|
269
269
|
}
|
|
270
270
|
}
|
|
271
271
|
};
|
|
@@ -285,11 +285,11 @@ var UpsertMemberOperation = class {
|
|
|
285
285
|
}
|
|
286
286
|
/** Write one contact without changing an existing subscription unless requested. */
|
|
287
287
|
async invoke(call, input) {
|
|
288
|
-
const
|
|
288
|
+
const operation2 = "upsertMember";
|
|
289
289
|
const validation = validateUpsertInput(input);
|
|
290
|
-
if (validation) return newMutationBranch("defect", emptyUpsert, zeroReceipt(), mailchimpFailure(
|
|
290
|
+
if (validation) return newMutationBranch("defect", emptyUpsert, zeroReceipt(), mailchimpFailure(operation2, "VALIDATION", validation));
|
|
291
291
|
const connection = await this.client.resolveConnection(call);
|
|
292
|
-
if (!connection) return credentialMutationDefect(
|
|
292
|
+
if (!connection) return credentialMutationDefect(operation2, emptyUpsert);
|
|
293
293
|
const hash = subscriberHash(input.emailAddress);
|
|
294
294
|
const body = {
|
|
295
295
|
email_address: input.emailAddress,
|
|
@@ -299,14 +299,14 @@ var UpsertMemberOperation = class {
|
|
|
299
299
|
...input.marketingPermissions?.length ? { marketing_permissions: input.marketingPermissions.map((permission) => ({ marketing_permission_id: permission.marketingPermissionId, enabled: permission.isEnabled })) } : {}
|
|
300
300
|
};
|
|
301
301
|
const query = input.shouldSkipMergeValidation ? new URLSearchParams({ skip_merge_validation: "true" }) : void 0;
|
|
302
|
-
const result = await this.client.exchange(call, connection,
|
|
302
|
+
const result = await this.client.exchange(call, connection, operation2, "PUT", memberPath(input.listId, hash), query, body);
|
|
303
303
|
const receipt = this.client.receipt(call, result, hash);
|
|
304
304
|
const classified = mutationExchange(result, receipt, emptyUpsert, false);
|
|
305
305
|
if (classified) return classified;
|
|
306
306
|
try {
|
|
307
307
|
return newMutationBranch("upserted", { member: decodeMember(result.body, hash) }, receipt);
|
|
308
308
|
} catch {
|
|
309
|
-
return newMutationBranch("invalidResponse", emptyUpsert, receipt, mailchimpFailure(
|
|
309
|
+
return newMutationBranch("invalidResponse", emptyUpsert, receipt, mailchimpFailure(operation2, "PROTOCOL", "Mailchimp accepted the contact but returned an invalid contact"));
|
|
310
310
|
}
|
|
311
311
|
}
|
|
312
312
|
};
|
|
@@ -326,15 +326,15 @@ var UpdateMemberTagsOperation = class {
|
|
|
326
326
|
}
|
|
327
327
|
/** Declare tag states for one contact. */
|
|
328
328
|
async invoke(call, input) {
|
|
329
|
-
const
|
|
329
|
+
const operation2 = "updateMemberTags";
|
|
330
330
|
const validation = validateTagsInput(input);
|
|
331
|
-
if (validation) return newMutationBranch("defect", emptyTags, zeroReceipt(), mailchimpFailure(
|
|
331
|
+
if (validation) return newMutationBranch("defect", emptyTags, zeroReceipt(), mailchimpFailure(operation2, "VALIDATION", validation));
|
|
332
332
|
const connection = await this.client.resolveConnection(call);
|
|
333
|
-
if (!connection) return credentialMutationDefect(
|
|
333
|
+
if (!connection) return credentialMutationDefect(operation2, emptyTags);
|
|
334
334
|
const hash = subscriberHash(input.emailAddress);
|
|
335
335
|
const tags = [...(input.addTags ?? []).map((name) => ({ name, status: "active" })), ...(input.removeTags ?? []).map((name) => ({ name, status: "inactive" }))];
|
|
336
336
|
const body = { tags, ...input.shouldSuppressAutomations ? { is_syncing: true } : {} };
|
|
337
|
-
const result = await this.client.exchange(call, connection,
|
|
337
|
+
const result = await this.client.exchange(call, connection, operation2, "POST", `${memberPath(input.listId, hash)}/tags`, void 0, body);
|
|
338
338
|
const receipt = this.client.receipt(call, result, hash);
|
|
339
339
|
const classified = mutationExchange(result, receipt, emptyTags, true);
|
|
340
340
|
if (classified) return classified;
|
|
@@ -361,11 +361,11 @@ var SendCampaignOperation = class {
|
|
|
361
361
|
}
|
|
362
362
|
/** Read status, checkpoint dispatch, and send only a draft. */
|
|
363
363
|
async invoke(call, input) {
|
|
364
|
-
const
|
|
364
|
+
const operation2 = "sendCampaign";
|
|
365
365
|
const validation = validateResourceID("campaignId", input.campaignId) || (input.expectedListId ? validateResourceID("expectedListId", input.expectedListId) : "");
|
|
366
|
-
if (validation) return newMutationBranch("defect", emptySend, zeroReceipt(), mailchimpFailure(
|
|
366
|
+
if (validation) return newMutationBranch("defect", emptySend, zeroReceipt(), mailchimpFailure(operation2, "VALIDATION", validation));
|
|
367
367
|
const connection = await this.client.resolveConnection(call);
|
|
368
|
-
if (!connection) return credentialMutationDefect(
|
|
368
|
+
if (!connection) return credentialMutationDefect(operation2, emptySend);
|
|
369
369
|
const query = new URLSearchParams({ fields: campaignFields });
|
|
370
370
|
let earlier = false;
|
|
371
371
|
try {
|
|
@@ -374,18 +374,18 @@ var SendCampaignOperation = class {
|
|
|
374
374
|
} catch {
|
|
375
375
|
earlier = true;
|
|
376
376
|
}
|
|
377
|
-
const read = await this.client.exchange(call, connection,
|
|
377
|
+
const read = await this.client.exchange(call, connection, operation2, "GET", `/campaigns/${input.campaignId}`, query);
|
|
378
378
|
const readReceipt = this.client.receipt(call, read, input.campaignId);
|
|
379
379
|
if (earlier) {
|
|
380
380
|
if (read.outcome === "succeeded") {
|
|
381
381
|
try {
|
|
382
382
|
const campaign2 = decodeCampaign(read.body, input.campaignId);
|
|
383
383
|
if (campaign2.status === "sending" || campaign2.status === "sent") return newMutationBranch("alreadySent", { campaign: campaign2 }, readReceipt);
|
|
384
|
-
return newMutationUncertain({ campaign: campaign2 }, mailchimpFailure(
|
|
384
|
+
return newMutationUncertain({ campaign: campaign2 }, mailchimpFailure(operation2, "TRANSPORT", "an earlier attempt may have sent the campaign"), readReceipt);
|
|
385
385
|
} catch {
|
|
386
386
|
}
|
|
387
387
|
}
|
|
388
|
-
return newMutationUncertain(emptySend, mailchimpFailure(
|
|
388
|
+
return newMutationUncertain(emptySend, mailchimpFailure(operation2, "TRANSPORT", "an earlier attempt may have sent the campaign and its status could not be read"), readReceipt);
|
|
389
389
|
}
|
|
390
390
|
const classified = mutationExchange(read, readReceipt, emptySend, true);
|
|
391
391
|
if (classified) return classified;
|
|
@@ -393,18 +393,18 @@ var SendCampaignOperation = class {
|
|
|
393
393
|
try {
|
|
394
394
|
campaign = decodeCampaign(read.body, input.campaignId);
|
|
395
395
|
} catch {
|
|
396
|
-
return newMutationBranch("invalidResponse", emptySend, readReceipt, mailchimpFailure(
|
|
396
|
+
return newMutationBranch("invalidResponse", emptySend, readReceipt, mailchimpFailure(operation2, "PROTOCOL", "Mailchimp returned an invalid campaign, so it was not sent"));
|
|
397
397
|
}
|
|
398
398
|
const output = { campaign };
|
|
399
399
|
if (campaign.status === "sending" || campaign.status === "sent") return newMutationBranch("alreadySent", output, readReceipt);
|
|
400
400
|
const blocker = campaign.status !== "save" ? "the campaign is not a draft" : !["regular", "plaintext", "absplit", "variate"].includes(campaign.type) ? "the campaign type does not send immediately" : input.expectedListId && campaign.listId !== input.expectedListId ? "the campaign targets another audience than expectedListId" : "";
|
|
401
|
-
if (blocker) return newMutationBranch("notSendable", output, readReceipt, mailchimpFailure(
|
|
401
|
+
if (blocker) return newMutationBranch("notSendable", output, readReceipt, mailchimpFailure(operation2, "CONFLICT", `${blocker}; nothing was sent`));
|
|
402
402
|
try {
|
|
403
403
|
await call.context.recordHeartbeat({ mailchimpDispatchedCallId: call.id });
|
|
404
404
|
} catch {
|
|
405
|
-
return newMutationRetry(mailchimpFailure(
|
|
405
|
+
return newMutationRetry(mailchimpFailure(operation2, "AVAILABILITY", "Dex did not record the dispatch checkpoint; nothing was sent"));
|
|
406
406
|
}
|
|
407
|
-
const sent = await this.client.exchange(call, connection,
|
|
407
|
+
const sent = await this.client.exchange(call, connection, operation2, "POST", `/campaigns/${input.campaignId}/actions/send`);
|
|
408
408
|
const receipt = this.client.receipt(call, sent, input.campaignId);
|
|
409
409
|
if (sent.outcome === "succeeded") return newMutationBranch("sent", output, receipt);
|
|
410
410
|
if (sent.outcome === "rateLimited" || sent.outcome === "notSent") {
|
|
@@ -431,11 +431,11 @@ function mutationExchange(exchange, receipt, zero, hasNotFound) {
|
|
|
431
431
|
const branch = exchange.outcome === "notFound" && hasNotFound ? "notFound" : exchange.outcome === "invalid" ? "invalidResponse" : exchange.outcome === "defect" ? "defect" : "providerRejected";
|
|
432
432
|
return newMutationBranch(branch, zero, receipt, exchange.failure);
|
|
433
433
|
}
|
|
434
|
-
function credentialQueryDefect(
|
|
435
|
-
return newQueryBranch("defect", zero, zeroReceipt(), mailchimpFailure(
|
|
434
|
+
function credentialQueryDefect(operation2, zero) {
|
|
435
|
+
return newQueryBranch("defect", zero, zeroReceipt(), mailchimpFailure(operation2, "AUTHENTICATION", "connection credentials are unavailable"));
|
|
436
436
|
}
|
|
437
|
-
function credentialMutationDefect(
|
|
438
|
-
return newMutationBranch("defect", zero, zeroReceipt(), mailchimpFailure(
|
|
437
|
+
function credentialMutationDefect(operation2, zero) {
|
|
438
|
+
return newMutationBranch("defect", zero, zeroReceipt(), mailchimpFailure(operation2, "AUTHENTICATION", "connection credentials are unavailable"));
|
|
439
439
|
}
|
|
440
440
|
function validateResourceID(name, value) {
|
|
441
441
|
return /^[A-Za-z0-9]{1,64}$/.test(value) ? "" : `${name} must be a Mailchimp ID of 1 to 64 letters and digits`;
|
|
@@ -597,21 +597,29 @@ function decodeCampaign(body, expectedID) {
|
|
|
597
597
|
}
|
|
598
598
|
|
|
599
599
|
// src/client.ts
|
|
600
|
-
function mailchimpFailure(
|
|
601
|
-
return { kind, provider: "mailchimp", operation, message };
|
|
600
|
+
function mailchimpFailure(operation2, kind, message) {
|
|
601
|
+
return { kind, provider: "mailchimp", operation: operation2, message };
|
|
602
602
|
}
|
|
603
|
+
var defaultPollIntervalMs = 3e4;
|
|
604
|
+
var MinimumPollIntervalMs = 5e3;
|
|
603
605
|
var MailchimpClient = class {
|
|
606
|
+
/** The memberChanged Trigger's delay between polls, in milliseconds. */
|
|
607
|
+
pollIntervalMs;
|
|
608
|
+
/** Receipt and Retry-After clock. */
|
|
609
|
+
now;
|
|
604
610
|
maxResponseBytes;
|
|
605
611
|
credentials;
|
|
606
612
|
apiBaseURL;
|
|
607
613
|
send;
|
|
608
|
-
now;
|
|
609
614
|
/** Validate configuration and retain immutable dependencies. */
|
|
610
615
|
constructor(config, credentials, options = {}) {
|
|
611
616
|
if (!credentials) throw new TypeError("Mailchimp credential provider is required");
|
|
612
617
|
const maximum = config.maxResponseBytes ?? 4194304;
|
|
613
618
|
if (!Number.isSafeInteger(maximum) || maximum < 1) throw new TypeError("Mailchimp response limit must be positive");
|
|
614
619
|
this.maxResponseBytes = maximum;
|
|
620
|
+
const pollIntervalMs = config.pollIntervalMs || defaultPollIntervalMs;
|
|
621
|
+
if (!Number.isFinite(pollIntervalMs) || pollIntervalMs < MinimumPollIntervalMs) throw new TypeError("Mailchimp pollInterval must be at least 5s");
|
|
622
|
+
this.pollIntervalMs = pollIntervalMs;
|
|
615
623
|
this.credentials = credentials;
|
|
616
624
|
this.apiBaseURL = options.apiBaseURL ? validateBaseURL(options.apiBaseURL) : void 0;
|
|
617
625
|
this.send = options.send ?? sendProviderRequest;
|
|
@@ -650,7 +658,7 @@ var MailchimpClient = class {
|
|
|
650
658
|
return { key, baseURL: this.apiBaseURL ?? `https://${match[2]}.api.mailchimp.com/3.0` };
|
|
651
659
|
}
|
|
652
660
|
/** Send one request and classify the outcome before an operation chooses its branch. */
|
|
653
|
-
async exchange(call, connection,
|
|
661
|
+
async exchange(call, connection, operation2, method, path, query, payload) {
|
|
654
662
|
const url = `${connection.baseURL}${path}${query && [...query.keys()].length ? `?${sortedQuery(query)}` : ""}`;
|
|
655
663
|
const headers = { Authorization: `Bearer ${connection.key}`, Accept: "application/json" };
|
|
656
664
|
if (payload !== void 0) headers["Content-Type"] = "application/json";
|
|
@@ -670,16 +678,16 @@ var MailchimpClient = class {
|
|
|
670
678
|
} catch (error) {
|
|
671
679
|
if (error instanceof BodyTooLargeError && error.status !== void 0 && error.headers !== void 0) {
|
|
672
680
|
response = { status: error.status, headers: error.headers, body: new Uint8Array() };
|
|
673
|
-
if (response.status >= 200 && response.status < 300) return { outcome: "invalid", status: response.status, headers: response.headers, body: response.body, failure: mailchimpFailure(
|
|
681
|
+
if (response.status >= 200 && response.status < 300) return { outcome: "invalid", status: response.status, headers: response.headers, body: response.body, failure: mailchimpFailure(operation2, "RESPONSE_TOO_LARGE", "Mailchimp response exceeds the configured maxResponseBytes limit"), retryAfterMs: 0 };
|
|
674
682
|
} else {
|
|
675
683
|
const isNotSent = error instanceof AddressRefusal || error instanceof ProviderTransportError && error.isProvablyNotSent;
|
|
676
|
-
return { outcome: isNotSent ? "notSent" : "unavailable", status: 0, headers: {}, body: new Uint8Array(), failure: mailchimpFailure(
|
|
684
|
+
return { outcome: isNotSent ? "notSent" : "unavailable", status: 0, headers: {}, body: new Uint8Array(), failure: mailchimpFailure(operation2, "TRANSPORT", isNotSent ? "Mailchimp could not be reached; no request was sent" : "Mailchimp request failed before a response arrived"), retryAfterMs: 0 };
|
|
677
685
|
}
|
|
678
686
|
}
|
|
679
687
|
const status = response.status;
|
|
680
688
|
const retryAfterMs = parseRetryAfter(header(response.headers, "retry-after"), this.now());
|
|
681
689
|
if (status >= 200 && status < 300) {
|
|
682
|
-
if (Buffer.from(response.body).includes(Buffer.from(connection.key))) return { outcome: "invalid", status, headers: response.headers, body: new Uint8Array(), failure: mailchimpFailure(
|
|
690
|
+
if (Buffer.from(response.body).includes(Buffer.from(connection.key))) return { outcome: "invalid", status, headers: response.headers, body: new Uint8Array(), failure: mailchimpFailure(operation2, "PROTOCOL", "Mailchimp response reflected the connection credential"), retryAfterMs: 0 };
|
|
683
691
|
return { outcome: "succeeded", status, headers: response.headers, body: response.body, retryAfterMs: 0 };
|
|
684
692
|
}
|
|
685
693
|
const hasProblem = hasProblemDocument(response.body);
|
|
@@ -698,7 +706,7 @@ var MailchimpClient = class {
|
|
|
698
706
|
outcome = "rejected";
|
|
699
707
|
kind = status === 401 ? "AUTHENTICATION" : status === 403 ? "AUTHORIZATION" : status === 409 ? "CONFLICT" : status === 400 ? "VALIDATION" : status >= 300 && status < 400 ? "PROTOCOL" : "PROVIDER_REJECTION";
|
|
700
708
|
}
|
|
701
|
-
return { outcome, status, headers: response.headers, body: new Uint8Array(), failure: mailchimpFailure(
|
|
709
|
+
return { outcome, status, headers: response.headers, body: new Uint8Array(), failure: mailchimpFailure(operation2, kind, `Mailchimp request failed (HTTP ${status})`), retryAfterMs };
|
|
702
710
|
}
|
|
703
711
|
/** Create a secret-free provider receipt. */
|
|
704
712
|
receipt(call, exchange, objectID) {
|
|
@@ -736,11 +744,15 @@ function goDate(date) {
|
|
|
736
744
|
}
|
|
737
745
|
|
|
738
746
|
// src/project.ts
|
|
739
|
-
function newProjectConnection2(project, connectionName) {
|
|
747
|
+
function newProjectConnection2(project, connectionName, options = {}) {
|
|
740
748
|
return newProjectConnection(project, connectionName, (loadedProject, name) => {
|
|
741
749
|
const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "mailchimp" && entry.connectionName === name);
|
|
742
750
|
if (!selected) throw new TypeError("Mailchimp project connection is not configured");
|
|
743
|
-
const
|
|
751
|
+
const stored = z2.object({ maxResponseBytes: z2.number().int().optional(), pollInterval: z2.number().int().nullable().optional() }).parse(selected.configuration);
|
|
752
|
+
const config = {
|
|
753
|
+
...stored.maxResponseBytes !== void 0 ? { maxResponseBytes: stored.maxResponseBytes } : {},
|
|
754
|
+
...typeof stored.pollInterval === "number" ? { pollIntervalMs: stored.pollInterval / 1e6 } : {}
|
|
755
|
+
};
|
|
744
756
|
const credentials = {
|
|
745
757
|
async resolve(call, signal) {
|
|
746
758
|
void call;
|
|
@@ -749,8 +761,392 @@ function newProjectConnection2(project, connectionName) {
|
|
|
749
761
|
return { apiKey: new SecretString(decoded.api_key) };
|
|
750
762
|
}
|
|
751
763
|
};
|
|
752
|
-
return new MailchimpClient(config, credentials);
|
|
764
|
+
return new MailchimpClient(config, credentials, options);
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
// src/member_snapshot.ts
|
|
769
|
+
import { createHash as createHash2 } from "crypto";
|
|
770
|
+
import { z as z3 } from "zod";
|
|
771
|
+
var MemberStatuses = ["subscribed", "unsubscribed", "cleaned", "pending", "transactional", "archived"];
|
|
772
|
+
var MemberChangedTriggerConfigurationSchema = z3.strictObject({
|
|
773
|
+
/** The watched audience, Mailchimp's list_id, such as 57afe96172. It is required. */
|
|
774
|
+
audienceId: z3.string(),
|
|
775
|
+
/**
|
|
776
|
+
* Keeps only contacts whose status after the change is one of these, such as subscribed; empty delivers
|
|
777
|
+
* changed contacts in every status. A filtered-out change still moves the cursor.
|
|
778
|
+
*/
|
|
779
|
+
statuses: z3.array(z3.string()).nullable().optional()
|
|
780
|
+
}).superRefine((configuration, context) => {
|
|
781
|
+
if (!/^[A-Za-z0-9]{1,64}$/.test(configuration.audienceId)) context.addIssue({ code: "custom", message: "audienceId must be a Mailchimp ID of 1 to 64 letters and digits" });
|
|
782
|
+
const statuses = configuration.statuses ?? [];
|
|
783
|
+
statuses.forEach((status, index) => {
|
|
784
|
+
if (!MemberStatuses.includes(status)) context.addIssue({ code: "custom", message: `statuses[${index}] ${goJSON(status)} is not a Mailchimp contact status` });
|
|
785
|
+
else if (statuses.slice(0, index).includes(status)) context.addIssue({ code: "custom", message: `statuses lists ${goJSON(status)} twice` });
|
|
753
786
|
});
|
|
787
|
+
});
|
|
788
|
+
var MemberChangedEventSchema = z3.object({
|
|
789
|
+
/** The watched audience. */
|
|
790
|
+
audienceId: z3.string().min(1),
|
|
791
|
+
/** The contact as Mailchimp listed it after the change; member.lastChangedAt is the change time. */
|
|
792
|
+
member: MemberSchema
|
|
793
|
+
});
|
|
794
|
+
function acceptsMemberStatus(configuration, status) {
|
|
795
|
+
const statuses = configuration.statuses ?? [];
|
|
796
|
+
return statuses.length === 0 || statuses.includes(status);
|
|
797
|
+
}
|
|
798
|
+
function goJSON(value) {
|
|
799
|
+
if (value === null || value === void 0) return "null";
|
|
800
|
+
if (typeof value === "boolean") return value ? "true" : "false";
|
|
801
|
+
if (typeof value === "string") return goStringJSON(value);
|
|
802
|
+
if (typeof value === "number") return goFloatJSON(value);
|
|
803
|
+
if (Array.isArray(value)) return `[${value.map(goJSON).join(",")}]`;
|
|
804
|
+
if (typeof value === "object") {
|
|
805
|
+
const entries = Object.entries(value).map(([key, item]) => [wellFormed(key), item]);
|
|
806
|
+
entries.sort(([left], [right]) => Buffer.compare(Buffer.from(left, "utf8"), Buffer.from(right, "utf8")));
|
|
807
|
+
return `{${entries.map(([key, item]) => `${goStringJSON(key)}:${goJSON(item)}`).join(",")}}`;
|
|
808
|
+
}
|
|
809
|
+
throw new TypeError("a merge field value is not JSON");
|
|
810
|
+
}
|
|
811
|
+
function goStringJSON(value) {
|
|
812
|
+
return JSON.stringify(wellFormed(value)).replace(/[<>&\u2028\u2029]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
813
|
+
}
|
|
814
|
+
function goFloatJSON(value) {
|
|
815
|
+
if (!Number.isFinite(value)) throw new TypeError("a merge field number is not finite");
|
|
816
|
+
if (Object.is(value, -0)) return "-0";
|
|
817
|
+
return String(value);
|
|
818
|
+
}
|
|
819
|
+
function wellFormed(value) {
|
|
820
|
+
return value.replace(/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g, "\uFFFD");
|
|
821
|
+
}
|
|
822
|
+
function memberJSON(member) {
|
|
823
|
+
const fields = [["subscriberHash", goStringJSON(member.subscriberHash)], ["emailAddress", goStringJSON(member.emailAddress)]];
|
|
824
|
+
if (member.contactId) fields.push(["contactId", goStringJSON(member.contactId)]);
|
|
825
|
+
if (member.fullName) fields.push(["fullName", goStringJSON(member.fullName)]);
|
|
826
|
+
fields.push(["status", goStringJSON(member.status)]);
|
|
827
|
+
if (member.emailType) fields.push(["emailType", goStringJSON(member.emailType)]);
|
|
828
|
+
if (member.mergeFields && Object.keys(member.mergeFields).length) fields.push(["mergeFields", goJSON(member.mergeFields)]);
|
|
829
|
+
if (member.tags?.length) {
|
|
830
|
+
const tags = member.tags.map(wellFormed).sort((left, right) => Buffer.compare(Buffer.from(left, "utf8"), Buffer.from(right, "utf8")));
|
|
831
|
+
fields.push(["tags", goJSON(tags)]);
|
|
832
|
+
}
|
|
833
|
+
fields.push(["tagCount", String(member.tagCount)]);
|
|
834
|
+
if (member.isVip) fields.push(["isVip", "true"]);
|
|
835
|
+
if (member.language) fields.push(["language", goStringJSON(member.language)]);
|
|
836
|
+
fields.push(["listId", goStringJSON(member.listId)]);
|
|
837
|
+
if (member.webId) fields.push(["webId", String(member.webId)]);
|
|
838
|
+
for (const [name, moment] of [["signedUpAt", member.signedUpAt], ["optedInAt", member.optedInAt], ["lastChangedAt", member.lastChangedAt]]) {
|
|
839
|
+
if (moment) fields.push([name, `"${moment}"`]);
|
|
840
|
+
}
|
|
841
|
+
return `{${fields.map(([name, encoded]) => `"${name}":${encoded}`).join(",")}}`;
|
|
842
|
+
}
|
|
843
|
+
function memberVersionDigest(audienceId, member, bytes) {
|
|
844
|
+
const digest = createHash2("sha256").update(Buffer.from(wellFormed(audienceId), "utf8")).update(Buffer.from([0])).update(Buffer.from(memberJSON(member), "utf8")).digest();
|
|
845
|
+
return digest.subarray(0, bytes).toString("hex");
|
|
846
|
+
}
|
|
847
|
+
function memberChangeID(audienceId, member) {
|
|
848
|
+
return `mailchimp-${memberVersionDigest(audienceId, member, 16)}`;
|
|
849
|
+
}
|
|
850
|
+
var MemberSnapshotItem = class {
|
|
851
|
+
/** Bind the audience and the listed contact. */
|
|
852
|
+
constructor(audienceId, member) {
|
|
853
|
+
this.audienceId = audienceId;
|
|
854
|
+
this.member = member;
|
|
855
|
+
}
|
|
856
|
+
audienceId;
|
|
857
|
+
member;
|
|
858
|
+
/** The subscriber hash. */
|
|
859
|
+
snapshotKey() {
|
|
860
|
+
return this.member.subscriberHash;
|
|
861
|
+
}
|
|
862
|
+
/** An 8-byte SHA-256 prefix of the contact version. */
|
|
863
|
+
snapshotHash() {
|
|
864
|
+
return memberVersionDigest(this.audienceId, this.member, 8);
|
|
865
|
+
}
|
|
866
|
+
/** No value is kept. */
|
|
867
|
+
snapshotValue() {
|
|
868
|
+
return void 0;
|
|
869
|
+
}
|
|
870
|
+
};
|
|
871
|
+
function newMemberChangedTriggerEvent(audienceId, member) {
|
|
872
|
+
return { id: memberChangeID(audienceId, member), occurredAt: new Date(member.lastChangedAt), payload: { audienceId, member } };
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
// src/trigger.ts
|
|
876
|
+
import {
|
|
877
|
+
mustTriggerBindingDefinition,
|
|
878
|
+
newTrigger
|
|
879
|
+
} from "@superdurable/connectors-sdk";
|
|
880
|
+
import { newBindingPoller, newBindingTriggerSource, newMemoryCursorStore, newRunner } from "@superdurable/connectors-sdk/pollingtrigger";
|
|
881
|
+
import { ObjectNotFoundError, decodeTriggerConfiguration, newDurableTriggerTarget } from "@superdurable/connectors-sdk/projectconfig";
|
|
882
|
+
|
|
883
|
+
// src/member_change_fetcher.ts
|
|
884
|
+
import { TriggerDeliveryAbortedError } from "@superdurable/connectors-sdk";
|
|
885
|
+
import {
|
|
886
|
+
applyKeyedSnapshotChanges,
|
|
887
|
+
markCursorInvalid,
|
|
888
|
+
markRateLimited,
|
|
889
|
+
newTriggerCredentialCall,
|
|
890
|
+
waitForPollRequest
|
|
891
|
+
} from "@superdurable/connectors-sdk/pollingtrigger";
|
|
892
|
+
var MemberPollPageSize = 250;
|
|
893
|
+
var memberPollLookbackNs = 5n * 60n * 1000000000n;
|
|
894
|
+
var maximumMemberPollOffset = 1e6;
|
|
895
|
+
var secondNs = 1000000000n;
|
|
896
|
+
var MemberSnapshotOptions = { evictLeastRecentlySeen: true };
|
|
897
|
+
var operation = "memberChanged";
|
|
898
|
+
var MemberChangeFetcher = class {
|
|
899
|
+
/** Bind the client, the connection and Trigger the credential call names, and the binding configuration. */
|
|
900
|
+
constructor(client, connection, trigger, configuration) {
|
|
901
|
+
this.client = client;
|
|
902
|
+
this.connection = connection;
|
|
903
|
+
this.trigger = trigger;
|
|
904
|
+
this.configuration = configuration;
|
|
905
|
+
}
|
|
906
|
+
client;
|
|
907
|
+
connection;
|
|
908
|
+
trigger;
|
|
909
|
+
configuration;
|
|
910
|
+
/**
|
|
911
|
+
* Record the newest change second as the baseline and snapshot the contacts changed in it, so a contact
|
|
912
|
+
* changed later in that second is still delivered. An empty audience has no baseline. When a whole page
|
|
913
|
+
* shares the newest second, the baseline moves one second later and none of that second is delivered.
|
|
914
|
+
*/
|
|
915
|
+
async seedCursor(context) {
|
|
916
|
+
const page = await this.listMembers(context, new URLSearchParams({ count: String(MemberPollPageSize), offset: "0", sort_field: "last_changed", sort_dir: "DESC", fields: memberFields }));
|
|
917
|
+
const audienceId = this.configuration.audienceId;
|
|
918
|
+
const cursor = { audienceId, baseline: "", watermark: "", passSince: "", passOffset: 0 };
|
|
919
|
+
let newest;
|
|
920
|
+
let seeded = [];
|
|
921
|
+
for (const member of page.members) {
|
|
922
|
+
if (!member.lastChangedAt) continue;
|
|
923
|
+
const changedAt = instantNs(member.lastChangedAt);
|
|
924
|
+
newest ??= changedAt;
|
|
925
|
+
if (changedAt !== newest) break;
|
|
926
|
+
seeded.push(new MemberSnapshotItem(audienceId, member));
|
|
927
|
+
}
|
|
928
|
+
if (newest === void 0) return { token: encodeCursor(cursor) };
|
|
929
|
+
cursor.baseline = cursor.watermark = formatCursorTime(newest);
|
|
930
|
+
if (seeded.length === page.members.length && page.members.length === MemberPollPageSize) {
|
|
931
|
+
cursor.baseline = formatCursorTime(newest + secondNs);
|
|
932
|
+
seeded = [];
|
|
933
|
+
}
|
|
934
|
+
return { token: encodeCursor(cursor), snapshot: applyKeyedSnapshotChanges(void 0, seeded, [], MemberSnapshotOptions) };
|
|
935
|
+
}
|
|
936
|
+
/** Read one ascending page of changed contacts after the cursor's pass start. */
|
|
937
|
+
async fetchChanges(context, cursor) {
|
|
938
|
+
let position;
|
|
939
|
+
let since;
|
|
940
|
+
try {
|
|
941
|
+
position = this.decodeCursor(cursor.token);
|
|
942
|
+
since = passStart(position);
|
|
943
|
+
} catch (error) {
|
|
944
|
+
throw markCursorInvalid(error);
|
|
945
|
+
}
|
|
946
|
+
const query = new URLSearchParams({ count: String(MemberPollPageSize), offset: String(position.passOffset), sort_field: "last_changed", sort_dir: "ASC", fields: memberFields });
|
|
947
|
+
if (since !== void 0) query.set("since_last_changed", `${formatCursorTime(since).slice(0, 19)}+00:00`);
|
|
948
|
+
const page = await this.listMembers(context, query);
|
|
949
|
+
return this.buildChangePage(position, since, page, cursor.snapshot);
|
|
950
|
+
}
|
|
951
|
+
buildChangePage(position, since, page, snapshot) {
|
|
952
|
+
const audienceId = this.configuration.audienceId;
|
|
953
|
+
const baseline = parseCursorTime(position.baseline);
|
|
954
|
+
let watermark = parseCursorTime(position.watermark);
|
|
955
|
+
const stored = new Map((snapshot?.entries ?? []).map((entry) => [entry.key, entry.hash]));
|
|
956
|
+
const changes = [];
|
|
957
|
+
const upserted = [];
|
|
958
|
+
const listed = [];
|
|
959
|
+
for (const member of page.members) {
|
|
960
|
+
if (!member.lastChangedAt) continue;
|
|
961
|
+
const changedAt = instantNs(member.lastChangedAt);
|
|
962
|
+
listed.push(member);
|
|
963
|
+
if (watermark === void 0 || changedAt > watermark) watermark = changedAt;
|
|
964
|
+
const item = new MemberSnapshotItem(audienceId, member);
|
|
965
|
+
if (baseline !== void 0 && changedAt < baseline) continue;
|
|
966
|
+
if (stored.get(item.snapshotKey()) === item.snapshotHash()) continue;
|
|
967
|
+
upserted.push(item);
|
|
968
|
+
if (acceptsMemberStatus(this.configuration, member.status)) changes.push(newMemberChangedTriggerEvent(audienceId, member));
|
|
969
|
+
}
|
|
970
|
+
const nextSnapshot = applyKeyedSnapshotChanges(snapshot, upserted, [], MemberSnapshotOptions);
|
|
971
|
+
const next = { audienceId: position.audienceId, baseline: position.baseline, watermark: watermark === void 0 ? "" : formatCursorTime(watermark), passSince: "", passOffset: 0 };
|
|
972
|
+
const hasMorePages = page.members.length === MemberPollPageSize && position.passOffset + page.members.length < page.totalItems;
|
|
973
|
+
if (hasMorePages) [next.passSince, next.passOffset] = continuePass(since, position.passOffset, page.members.length, listed);
|
|
974
|
+
return { changes, next: { token: encodeCursor(next), snapshot: nextSnapshot }, hasMorePages };
|
|
975
|
+
}
|
|
976
|
+
decodeCursor(token) {
|
|
977
|
+
let value;
|
|
978
|
+
try {
|
|
979
|
+
value = JSON.parse(token);
|
|
980
|
+
} catch {
|
|
981
|
+
throw new Error("Mailchimp memberChanged cursor is not valid JSON");
|
|
982
|
+
}
|
|
983
|
+
if (value === null) value = {};
|
|
984
|
+
if (typeof value !== "object" || Array.isArray(value)) throw new Error("Mailchimp memberChanged cursor is not valid JSON");
|
|
985
|
+
const raw = value;
|
|
986
|
+
const texts = ["audienceId", "baseline", "watermark", "passSince"].map((name) => {
|
|
987
|
+
const text2 = raw[name] ?? "";
|
|
988
|
+
if (typeof text2 !== "string") throw new Error("Mailchimp memberChanged cursor is not valid JSON");
|
|
989
|
+
return text2;
|
|
990
|
+
});
|
|
991
|
+
const offset = raw.passOffset ?? 0;
|
|
992
|
+
if (typeof offset !== "number" || !Number.isSafeInteger(offset)) throw new Error("Mailchimp memberChanged cursor is not valid JSON");
|
|
993
|
+
const position = { audienceId: texts[0], baseline: texts[1], watermark: texts[2], passSince: texts[3], passOffset: offset };
|
|
994
|
+
if (position.audienceId !== this.configuration.audienceId) throw new Error("Mailchimp memberChanged cursor belongs to another audience");
|
|
995
|
+
for (const text2 of [position.baseline, position.watermark, position.passSince]) parseCursorTime(text2);
|
|
996
|
+
if (position.passOffset < 0 || position.passOffset > maximumMemberPollOffset) throw new Error("Mailchimp memberChanged cursor offset is out of range");
|
|
997
|
+
return position;
|
|
998
|
+
}
|
|
999
|
+
/** Send one GET /lists/{list_id}/members and classify its failure for the kit. */
|
|
1000
|
+
async listMembers(context, query) {
|
|
1001
|
+
await waitForPollRequest(context);
|
|
1002
|
+
const call = newTriggerCredentialCall(this.connection, this.trigger, context.signal);
|
|
1003
|
+
const connection = await this.client.resolveConnection(call);
|
|
1004
|
+
if (!connection) throw new Error("connection credentials are unavailable");
|
|
1005
|
+
const exchange = await this.client.exchange(call, connection, operation, "GET", `/lists/${this.configuration.audienceId}/members`, query);
|
|
1006
|
+
if (context.signal.aborted) throw new TriggerDeliveryAbortedError();
|
|
1007
|
+
const message = exchange.failure?.message ?? "Mailchimp request failed";
|
|
1008
|
+
if (exchange.outcome === "succeeded") {
|
|
1009
|
+
try {
|
|
1010
|
+
return decodeMemberPage(exchange.body);
|
|
1011
|
+
} catch (error) {
|
|
1012
|
+
throw new Error(`Mailchimp returned an invalid page of contacts: ${error instanceof Error ? error.message : String(error)}`);
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
if (exchange.outcome === "rateLimited") throw markRateLimited(new Error(message), exchange.retryAfterMs);
|
|
1016
|
+
if (exchange.outcome === "rejected" && exchange.status === 400) throw markCursorInvalid(new Error(message));
|
|
1017
|
+
throw new Error(message);
|
|
1018
|
+
}
|
|
1019
|
+
};
|
|
1020
|
+
function decodeMemberPage(body) {
|
|
1021
|
+
const page = parseObject(body);
|
|
1022
|
+
const wires = page.members ?? [];
|
|
1023
|
+
if (!Array.isArray(wires) || typeof page.total_items !== "number" || !Number.isSafeInteger(page.total_items) || page.total_items < 0 || wires.length > MemberPollPageSize) {
|
|
1024
|
+
throw new Error("the page has no total_items or more contacts than requested");
|
|
1025
|
+
}
|
|
1026
|
+
return { members: wires.map((wire) => decodeMemberObject(wire, "")), totalItems: page.total_items };
|
|
1027
|
+
}
|
|
1028
|
+
function passStart(position) {
|
|
1029
|
+
if (position.passSince || position.passOffset) return parseCursorTime(position.passSince);
|
|
1030
|
+
const watermark = parseCursorTime(position.watermark);
|
|
1031
|
+
if (watermark === void 0) return void 0;
|
|
1032
|
+
let start = watermark - memberPollLookbackNs;
|
|
1033
|
+
const baseline = parseCursorTime(position.baseline);
|
|
1034
|
+
if (baseline !== void 0 && start < baseline - secondNs) start = baseline - secondNs;
|
|
1035
|
+
return start;
|
|
1036
|
+
}
|
|
1037
|
+
function continuePass(since, offset, pageLength, listed) {
|
|
1038
|
+
if (listed.length) {
|
|
1039
|
+
const last = instantNs(listed[listed.length - 1].lastChangedAt);
|
|
1040
|
+
const first = instantNs(listed[0].lastChangedAt);
|
|
1041
|
+
const restart = last - secondNs;
|
|
1042
|
+
if (first < last && (since === void 0 || restart > since)) return [formatCursorTime(restart), 0];
|
|
1043
|
+
}
|
|
1044
|
+
if (offset + pageLength > maximumMemberPollOffset) throw new Error(`more than ${maximumMemberPollOffset} Mailchimp contacts changed within one second`);
|
|
1045
|
+
return [since === void 0 ? "" : formatCursorTime(since), offset + pageLength];
|
|
1046
|
+
}
|
|
1047
|
+
function encodeCursor(position) {
|
|
1048
|
+
const fields = [`"audienceId":${JSON.stringify(position.audienceId)}`];
|
|
1049
|
+
for (const [name, value] of [["baseline", position.baseline], ["watermark", position.watermark], ["passSince", position.passSince]]) {
|
|
1050
|
+
if (value) fields.push(`"${name}":"${value}"`);
|
|
1051
|
+
}
|
|
1052
|
+
if (position.passOffset) fields.push(`"passOffset":${position.passOffset}`);
|
|
1053
|
+
return `{${fields.join(",")}}`;
|
|
1054
|
+
}
|
|
1055
|
+
function instantNs(timestamp2) {
|
|
1056
|
+
const match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?Z$/.exec(timestamp2);
|
|
1057
|
+
if (!match) throw new Error("a contact timestamp is not canonical UTC");
|
|
1058
|
+
const seconds = BigInt(Date.parse(`${match[1]}Z`) / 1e3);
|
|
1059
|
+
return seconds * secondNs + BigInt((match[2] ?? "").padEnd(9, "0") || "0");
|
|
1060
|
+
}
|
|
1061
|
+
function formatCursorTime(instant) {
|
|
1062
|
+
const seconds = instant >= 0n ? instant / secondNs : -((-instant + secondNs - 1n) / secondNs);
|
|
1063
|
+
return new Date(Number(seconds) * 1e3).toISOString().slice(0, 19) + "Z";
|
|
1064
|
+
}
|
|
1065
|
+
function parseCursorTime(value) {
|
|
1066
|
+
if (!value) return void 0;
|
|
1067
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})$/.exec(value);
|
|
1068
|
+
const parsed = match ? Date.parse(value) : Number.NaN;
|
|
1069
|
+
if (!match || Number.isNaN(parsed)) throw new Error("Mailchimp memberChanged cursor holds an invalid time");
|
|
1070
|
+
const fraction = BigInt((match[7] ?? "").slice(0, 9).padEnd(9, "0") || "0");
|
|
1071
|
+
return BigInt(Math.floor(parsed / 1e3)) * secondNs + fraction;
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
// src/trigger.ts
|
|
1075
|
+
var MemberChangedTriggerDefinition = {
|
|
1076
|
+
trigger: { connectorId: ConnectorID, triggerName: "memberChanged" },
|
|
1077
|
+
description: "Receive each contact added to or changed in one Mailchimp audience, including subscribes, unsubscribes, profile and tag changes, and cleaned addresses, read by polling contacts by last change time; the first run records a baseline and delivers no existing contacts."
|
|
1078
|
+
};
|
|
1079
|
+
var UIUnitAudienceIDEntry = "audienceIdEntry";
|
|
1080
|
+
var UIAudienceIDEntryPortAudienceID = "audienceId";
|
|
1081
|
+
var UIUnitMemberStatusPicker = "memberStatusPicker";
|
|
1082
|
+
var UIMemberStatusPickerPortStatuses = "statuses";
|
|
1083
|
+
function defineMemberChangedTriggerBinding(config) {
|
|
1084
|
+
return mustTriggerBindingDefinition({ definition: MemberChangedTriggerDefinition, ...config });
|
|
1085
|
+
}
|
|
1086
|
+
function newMemberTriggerRunner(connection, routes, options = {}) {
|
|
1087
|
+
const client = mailchimpClientOf(connection);
|
|
1088
|
+
if (!routes?.length) throw new TypeError("Mailchimp memberChanged routes are required");
|
|
1089
|
+
const pollers = routes.map((route) => {
|
|
1090
|
+
if (!route?.bindingName?.trim() || !route.target) throw new TypeError("Mailchimp memberChanged binding name and target are required");
|
|
1091
|
+
const configuration = parseConfiguration(route.configuration);
|
|
1092
|
+
return newBindingPoller({
|
|
1093
|
+
definition: MemberChangedTriggerDefinition,
|
|
1094
|
+
binding: { connection: connection.reference, trigger: MemberChangedTriggerDefinition.trigger, name: route.bindingName },
|
|
1095
|
+
cursor: route.cursor ?? newMemoryCursorStore(),
|
|
1096
|
+
fetcher: new MemberChangeFetcher(client, connection.reference, MemberChangedTriggerDefinition.trigger, configuration),
|
|
1097
|
+
target: route.target,
|
|
1098
|
+
snapshot: MemberSnapshotOptions
|
|
1099
|
+
});
|
|
1100
|
+
});
|
|
1101
|
+
return newRunner({ connection: connection.reference, schedule: pollSchedule(client), pollers, ...options.logger ? { logger: options.logger } : {} });
|
|
1102
|
+
}
|
|
1103
|
+
function newProjectMemberTriggerRunner(project, connection, routes, options = {}) {
|
|
1104
|
+
if (!project) throw new TypeError("Mailchimp memberChanged runner requires the loaded project configuration");
|
|
1105
|
+
const durableRoutes = (routes ?? []).map((route) => {
|
|
1106
|
+
if (!route?.target) throw new TypeError(`Mailchimp memberChanged binding ${JSON.stringify(route?.bindingName)} target is required`);
|
|
1107
|
+
const key = { connectorId: ConnectorID, connectionName: connection.reference.name, triggerName: MemberChangedTriggerDefinition.trigger.triggerName, bindingName: route.bindingName };
|
|
1108
|
+
let configuration;
|
|
1109
|
+
try {
|
|
1110
|
+
configuration = decodeTriggerConfiguration(project.configuration, key, MemberChangedTriggerConfigurationSchema);
|
|
1111
|
+
} catch (error) {
|
|
1112
|
+
if (error instanceof ObjectNotFoundError) throw new TypeError(`mailchimp memberChanged binding ${JSON.stringify(route.bindingName)} has no saved audience; enter its audience ID in Dex Web Connections`);
|
|
1113
|
+
throw new TypeError(`mailchimp memberChanged binding ${JSON.stringify(route.bindingName)} configuration: ${error instanceof Error ? error.message : String(error)}`);
|
|
1114
|
+
}
|
|
1115
|
+
const target = newDurableTriggerTarget(project.triggerInbox(key), key, route.target, { decodePayload: decodeMemberChangedEventPayload, ...options.logger ? { logger: options.logger } : {} });
|
|
1116
|
+
return { bindingName: route.bindingName, configuration, target, cursor: project.pollCursorStore(key) };
|
|
1117
|
+
});
|
|
1118
|
+
return newMemberTriggerRunner(connection, durableRoutes, options);
|
|
1119
|
+
}
|
|
1120
|
+
function newMemberChangedTrigger(config) {
|
|
1121
|
+
const client = mailchimpClientOf(config.connection);
|
|
1122
|
+
if (!config.bindingName?.trim() || !config.target) throw new TypeError("Mailchimp memberChanged binding name and target are required");
|
|
1123
|
+
const configuration = parseConfiguration(config.configuration);
|
|
1124
|
+
const binding = { connection: config.connection.reference, trigger: MemberChangedTriggerDefinition.trigger, name: config.bindingName };
|
|
1125
|
+
const source = newBindingTriggerSource({
|
|
1126
|
+
definition: MemberChangedTriggerDefinition,
|
|
1127
|
+
binding,
|
|
1128
|
+
cursor: newMemoryCursorStore(),
|
|
1129
|
+
fetcher: new MemberChangeFetcher(client, config.connection.reference, MemberChangedTriggerDefinition.trigger, configuration),
|
|
1130
|
+
snapshot: MemberSnapshotOptions
|
|
1131
|
+
}, pollSchedule(client), config.logger);
|
|
1132
|
+
return newTrigger({ definition: MemberChangedTriggerDefinition, binding, source, target: config.target, ...config.logger ? { logger: config.logger } : {} });
|
|
1133
|
+
}
|
|
1134
|
+
function decodeMemberChangedEventPayload(payloadJSON) {
|
|
1135
|
+
const parsed = MemberChangedEventSchema.safeParse(JSON.parse(payloadJSON));
|
|
1136
|
+
if (!parsed.success) throw new TypeError("stored Mailchimp memberChanged payload is invalid");
|
|
1137
|
+
return parsed.data;
|
|
1138
|
+
}
|
|
1139
|
+
function parseConfiguration(configuration) {
|
|
1140
|
+
const parsed = MemberChangedTriggerConfigurationSchema.safeParse(configuration ?? {});
|
|
1141
|
+
if (!parsed.success) throw new TypeError(`mailchimp memberChanged configuration: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`);
|
|
1142
|
+
return parsed.data;
|
|
1143
|
+
}
|
|
1144
|
+
function mailchimpClientOf(connection) {
|
|
1145
|
+
if (!(connection?.operations instanceof MailchimpClient)) throw new TypeError("Mailchimp memberChanged Trigger requires a connection from newProjectConnection or newConnection with a MailchimpClient");
|
|
1146
|
+
return connection.operations;
|
|
1147
|
+
}
|
|
1148
|
+
function pollSchedule(client) {
|
|
1149
|
+
return { intervalMs: client.pollIntervalMs };
|
|
754
1150
|
}
|
|
755
1151
|
export {
|
|
756
1152
|
CampaignSchema,
|
|
@@ -780,7 +1176,12 @@ export {
|
|
|
780
1176
|
ListMembersOutputSchema,
|
|
781
1177
|
MailchimpClient,
|
|
782
1178
|
MarketingPermissionInputSchema,
|
|
1179
|
+
MemberChangedEventSchema,
|
|
1180
|
+
MemberChangedTriggerConfigurationSchema,
|
|
1181
|
+
MemberChangedTriggerDefinition,
|
|
783
1182
|
MemberSchema,
|
|
1183
|
+
MemberStatuses,
|
|
1184
|
+
MinimumPollIntervalMs,
|
|
784
1185
|
ProviderID,
|
|
785
1186
|
SendCampaignBranch,
|
|
786
1187
|
SendCampaignBranchAlreadySent,
|
|
@@ -796,6 +1197,10 @@ export {
|
|
|
796
1197
|
SendCampaignMetadata,
|
|
797
1198
|
SendCampaignOperation,
|
|
798
1199
|
SendCampaignOutputSchema,
|
|
1200
|
+
UIAudienceIDEntryPortAudienceID,
|
|
1201
|
+
UIMemberStatusPickerPortStatuses,
|
|
1202
|
+
UIUnitAudienceIDEntry,
|
|
1203
|
+
UIUnitMemberStatusPicker,
|
|
799
1204
|
UpdateMemberTagsBranch,
|
|
800
1205
|
UpdateMemberTagsBranchDefect,
|
|
801
1206
|
UpdateMemberTagsBranchInvalidResponse,
|
|
@@ -818,11 +1223,16 @@ export {
|
|
|
818
1223
|
UpsertMemberOperation,
|
|
819
1224
|
UpsertMemberOutputSchema,
|
|
820
1225
|
decodeCredentials,
|
|
1226
|
+
decodeMemberChangedEventPayload,
|
|
1227
|
+
defineMemberChangedTriggerBinding,
|
|
821
1228
|
newConnection,
|
|
822
1229
|
newConnectionWithOperations,
|
|
823
1230
|
newGetMemberStep,
|
|
824
1231
|
newListMembersStep,
|
|
1232
|
+
newMemberChangedTrigger,
|
|
1233
|
+
newMemberTriggerRunner,
|
|
825
1234
|
newProjectConnection2 as newProjectConnection,
|
|
1235
|
+
newProjectMemberTriggerRunner,
|
|
826
1236
|
newSendCampaignStep,
|
|
827
1237
|
newUpdateMemberTagsStep,
|
|
828
1238
|
newUpsertMemberStep
|