@superdurable/connector-intuit-mailchimp 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 +22 -2
- package/dex-connector.json +440 -0
- package/dist/chunk-Z4CC3JDG.js +355 -0
- package/dist/connection-CNe_v9QS.d.ts +372 -0
- package/dist/index.d.ts +505 -0
- package/dist/index.js +1239 -0
- package/dist/mock.d.ts +149 -0
- package/dist/mock.js +359 -0
- package/package.json +63 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1239 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CampaignSchema,
|
|
3
|
+
ConfigSchema,
|
|
4
|
+
Connection,
|
|
5
|
+
ConnectorID,
|
|
6
|
+
GetMemberBranch,
|
|
7
|
+
GetMemberBranchDefect,
|
|
8
|
+
GetMemberBranchFound,
|
|
9
|
+
GetMemberBranchInvalidResponse,
|
|
10
|
+
GetMemberBranchNotFound,
|
|
11
|
+
GetMemberBranchProviderRejected,
|
|
12
|
+
GetMemberDefinition,
|
|
13
|
+
GetMemberInputSchema,
|
|
14
|
+
GetMemberMetadata,
|
|
15
|
+
ListMembersBranch,
|
|
16
|
+
ListMembersBranchDefect,
|
|
17
|
+
ListMembersBranchInvalidResponse,
|
|
18
|
+
ListMembersBranchListed,
|
|
19
|
+
ListMembersBranchNotFound,
|
|
20
|
+
ListMembersBranchProviderRejected,
|
|
21
|
+
ListMembersDefinition,
|
|
22
|
+
ListMembersInputSchema,
|
|
23
|
+
ListMembersMetadata,
|
|
24
|
+
ListMembersOutputSchema,
|
|
25
|
+
MarketingPermissionInputSchema,
|
|
26
|
+
MemberSchema,
|
|
27
|
+
ProviderID,
|
|
28
|
+
SendCampaignBranch,
|
|
29
|
+
SendCampaignBranchAlreadySent,
|
|
30
|
+
SendCampaignBranchDefect,
|
|
31
|
+
SendCampaignBranchInvalidResponse,
|
|
32
|
+
SendCampaignBranchNotFound,
|
|
33
|
+
SendCampaignBranchNotSendable,
|
|
34
|
+
SendCampaignBranchProviderRejected,
|
|
35
|
+
SendCampaignBranchSent,
|
|
36
|
+
SendCampaignBranchUncertain,
|
|
37
|
+
SendCampaignDefinition,
|
|
38
|
+
SendCampaignInputSchema,
|
|
39
|
+
SendCampaignMetadata,
|
|
40
|
+
SendCampaignOutputSchema,
|
|
41
|
+
UpdateMemberTagsBranch,
|
|
42
|
+
UpdateMemberTagsBranchDefect,
|
|
43
|
+
UpdateMemberTagsBranchInvalidResponse,
|
|
44
|
+
UpdateMemberTagsBranchNotFound,
|
|
45
|
+
UpdateMemberTagsBranchProviderRejected,
|
|
46
|
+
UpdateMemberTagsBranchUpdated,
|
|
47
|
+
UpdateMemberTagsDefinition,
|
|
48
|
+
UpdateMemberTagsInputSchema,
|
|
49
|
+
UpdateMemberTagsMetadata,
|
|
50
|
+
UpdateMemberTagsOutputSchema,
|
|
51
|
+
UpsertMemberBranch,
|
|
52
|
+
UpsertMemberBranchDefect,
|
|
53
|
+
UpsertMemberBranchInvalidResponse,
|
|
54
|
+
UpsertMemberBranchProviderRejected,
|
|
55
|
+
UpsertMemberBranchUpserted,
|
|
56
|
+
UpsertMemberDefinition,
|
|
57
|
+
UpsertMemberInputSchema,
|
|
58
|
+
UpsertMemberMetadata,
|
|
59
|
+
UpsertMemberOutputSchema,
|
|
60
|
+
decodeCredentials,
|
|
61
|
+
newConnection,
|
|
62
|
+
newConnectionWithOperations,
|
|
63
|
+
newProjectConnection
|
|
64
|
+
} from "./chunk-Z4CC3JDG.js";
|
|
65
|
+
|
|
66
|
+
// src/schema.ts
|
|
67
|
+
import { z } from "zod";
|
|
68
|
+
var ListMembersInputSchema2 = ListMembersInputSchema.safeExtend({
|
|
69
|
+
changedSince: z.string().nullable().optional(),
|
|
70
|
+
optedInSince: z.string().nullable().optional()
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
// src/generated/steps.ts
|
|
74
|
+
import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
|
|
75
|
+
function newGetMemberStep(configuration) {
|
|
76
|
+
const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
|
|
77
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
78
|
+
return newQueryStep({ ...stepConfiguration, operation: connection.operations.getMember(), connection: connection.reference, branches: [
|
|
79
|
+
goToBranch("found", found),
|
|
80
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
81
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
82
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
83
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
84
|
+
] });
|
|
85
|
+
}
|
|
86
|
+
function newListMembersStep(configuration) {
|
|
87
|
+
const { connection, connectionName, listed, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
|
|
88
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
89
|
+
return newQueryStep({ ...stepConfiguration, operation: connection.operations.listMembers(), connection: connection.reference, branches: [
|
|
90
|
+
goToBranch("listed", listed),
|
|
91
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
92
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
93
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
94
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
95
|
+
] });
|
|
96
|
+
}
|
|
97
|
+
function newUpsertMemberStep(configuration) {
|
|
98
|
+
const { connection, connectionName, upserted, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
|
|
99
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
100
|
+
return newMutationStep({ ...stepConfiguration, operation: connection.operations.upsertMember(), connection: connection.reference, branches: [
|
|
101
|
+
goToBranch("upserted", upserted),
|
|
102
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
103
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
104
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
105
|
+
] });
|
|
106
|
+
}
|
|
107
|
+
function newUpdateMemberTagsStep(configuration) {
|
|
108
|
+
const { connection, connectionName, updated, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
|
|
109
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
110
|
+
return newMutationStep({ ...stepConfiguration, operation: connection.operations.updateMemberTags(), connection: connection.reference, branches: [
|
|
111
|
+
goToBranch("updated", updated),
|
|
112
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
113
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
114
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
115
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
116
|
+
] });
|
|
117
|
+
}
|
|
118
|
+
function newSendCampaignStep(configuration) {
|
|
119
|
+
const { connection, connectionName, sent, alreadySent, notSendable, notFound, providerRejected, invalidResponse, uncertain, defect, ...stepConfiguration } = configuration;
|
|
120
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
121
|
+
return newMutationStep({ ...stepConfiguration, operation: connection.operations.sendCampaign(), connection: connection.reference, branches: [
|
|
122
|
+
goToBranch("sent", sent),
|
|
123
|
+
...alreadySent ? [goToBranch("alreadySent", alreadySent)] : [],
|
|
124
|
+
...notSendable ? [goToBranch("notSendable", notSendable)] : [],
|
|
125
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
126
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
127
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
128
|
+
...uncertain ? [goToBranch("uncertain", uncertain)] : [],
|
|
129
|
+
...defect ? [goToBranch("defect", defect)] : []
|
|
130
|
+
] });
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// src/project.ts
|
|
134
|
+
import { SecretString } from "@superdurable/connectors-sdk";
|
|
135
|
+
import { z as z2 } from "zod";
|
|
136
|
+
|
|
137
|
+
// src/client.ts
|
|
138
|
+
import { AddressRefusal, BodyTooLargeError, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
|
|
139
|
+
|
|
140
|
+
// src/operations.ts
|
|
141
|
+
import { createHash } from "crypto";
|
|
142
|
+
import { newMutationBranch, newMutationRetry, newMutationUncertain, newQueryBranch, newQueryRetry, zeroReceipt } from "@superdurable/connectors-sdk";
|
|
143
|
+
|
|
144
|
+
// src/go-parity.ts
|
|
145
|
+
import { isIP } from "net";
|
|
146
|
+
var atomCharacter = /[\x21-\x7e]/;
|
|
147
|
+
var atomSpecials = /* @__PURE__ */ new Set([...'()<>[]:;@\\,"']);
|
|
148
|
+
function isGoBareEmailAddress(value) {
|
|
149
|
+
const separator = value.indexOf("@");
|
|
150
|
+
if (separator <= 0 || separator !== value.lastIndexOf("@")) return false;
|
|
151
|
+
const local = value.slice(0, separator);
|
|
152
|
+
const domain = value.slice(separator + 1);
|
|
153
|
+
const isAtom = (part) => !!part && !part.startsWith(".") && !part.endsWith(".") && !part.includes("..") && [...part].every((character) => {
|
|
154
|
+
const code = character.codePointAt(0);
|
|
155
|
+
return code >= 128 ? !(code >= 55296 && code <= 57343) : atomCharacter.test(character) && !atomSpecials.has(character);
|
|
156
|
+
});
|
|
157
|
+
if (!isAtom(local)) return false;
|
|
158
|
+
if (domain.startsWith("[") && domain.endsWith("]")) return isIP(domain.slice(1, -1)) !== 0;
|
|
159
|
+
return isAtom(domain);
|
|
160
|
+
}
|
|
161
|
+
function goSimpleLower(value) {
|
|
162
|
+
return [...value].map((character) => character === "\u0130" ? "i" : character.toLowerCase()).join("");
|
|
163
|
+
}
|
|
164
|
+
function goTrimSpace(value) {
|
|
165
|
+
return value.replace(/^\p{White_Space}+|\p{White_Space}+$/gu, "");
|
|
166
|
+
}
|
|
167
|
+
function goRFC3339UTC(value) {
|
|
168
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{1,2}):(\d{2}):(\d{2})(?:[.,](\d+))?(Z|[+-]\d{2}:\d{2})$/.exec(value);
|
|
169
|
+
if (!match) throw new Error("invalid timestamp");
|
|
170
|
+
const year = Number(match[1]);
|
|
171
|
+
const month = Number(match[2]);
|
|
172
|
+
const day = Number(match[3]);
|
|
173
|
+
const hour = Number(match[4]);
|
|
174
|
+
const minute = Number(match[5]);
|
|
175
|
+
const second = Number(match[6]);
|
|
176
|
+
const fractionText = match[7];
|
|
177
|
+
const zone = match[8];
|
|
178
|
+
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
179
|
+
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
180
|
+
if (month < 1 || month > 12 || day < 1 || day > days[month - 1] || hour > 23 || minute > 59 || second > 59) throw new Error("invalid timestamp");
|
|
181
|
+
const offsetHours = zone === "Z" ? 0 : Number(zone.slice(1, 3));
|
|
182
|
+
const offsetMinutes = zone === "Z" ? 0 : Number(zone.slice(4));
|
|
183
|
+
if (offsetHours > 24 || offsetMinutes > 60) throw new Error("invalid timestamp");
|
|
184
|
+
const instant = /* @__PURE__ */ new Date(0);
|
|
185
|
+
instant.setUTCFullYear(year, month - 1, day);
|
|
186
|
+
instant.setUTCHours(hour, minute, second);
|
|
187
|
+
instant.setTime(instant.getTime() - (zone.startsWith("-") ? -1 : 1) * (offsetHours * 60 + offsetMinutes) * 6e4);
|
|
188
|
+
if (Number.isNaN(instant.getTime()) || instant.getUTCFullYear() < 0 || instant.getUTCFullYear() > 9999) throw new Error("invalid timestamp");
|
|
189
|
+
const fraction = fractionText?.slice(0, 9).replace(/0+$/, "");
|
|
190
|
+
return instant.toISOString().slice(0, 19) + (fraction ? `.${fraction}` : "") + "Z";
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// src/operations.ts
|
|
194
|
+
var emptyMember = { subscriberHash: "", emailAddress: "", status: "", tagCount: 0, listId: "" };
|
|
195
|
+
var emptyPage = { members: [], totalItems: 0 };
|
|
196
|
+
var emptyUpsert = { member: emptyMember };
|
|
197
|
+
var emptyTags = { subscriberHash: "" };
|
|
198
|
+
var emptyCampaign = { id: "", type: "", status: "", recipientCount: 0, emailsSent: 0 };
|
|
199
|
+
var emptySend = { campaign: emptyCampaign };
|
|
200
|
+
var readableStatuses = /* @__PURE__ */ new Set(["subscribed", "unsubscribed", "pending", "transactional", "cleaned", "archived"]);
|
|
201
|
+
var writableStatuses = /* @__PURE__ */ new Set(["subscribed", "unsubscribed", "pending", "transactional"]);
|
|
202
|
+
var memberFields = "members.id,members.email_address,members.contact_id,members.full_name,members.web_id,members.email_type,members.status,members.merge_fields,members.vip,members.language,members.timestamp_signup,members.timestamp_opt,members.last_changed,members.tags_count,members.tags,members.list_id,list_id,total_items";
|
|
203
|
+
var campaignFields = "id,web_id,type,status,emails_sent,create_time,send_time,settings.title,settings.subject_line,recipients.list_id,recipients.list_name,recipients.recipient_count";
|
|
204
|
+
var GetMemberOperation = class {
|
|
205
|
+
/** Bind the client. */
|
|
206
|
+
constructor(client) {
|
|
207
|
+
this.client = client;
|
|
208
|
+
}
|
|
209
|
+
client;
|
|
210
|
+
/** Return the manifest definition. */
|
|
211
|
+
definition() {
|
|
212
|
+
return GetMemberDefinition;
|
|
213
|
+
}
|
|
214
|
+
/** Read by Mailchimp subscriber hash. */
|
|
215
|
+
async invoke(call, input) {
|
|
216
|
+
const operation2 = "getMember";
|
|
217
|
+
const validation = validateMemberAddress(input.listId, input.emailAddress);
|
|
218
|
+
if (validation) return newQueryBranch("defect", emptyMember, zeroReceipt(), mailchimpFailure(operation2, "VALIDATION", validation));
|
|
219
|
+
const connection = await this.client.resolveConnection(call);
|
|
220
|
+
if (!connection) return credentialQueryDefect(operation2, emptyMember);
|
|
221
|
+
const hash = subscriberHash(input.emailAddress);
|
|
222
|
+
const result = await this.client.exchange(call, connection, operation2, "GET", memberPath(input.listId, hash));
|
|
223
|
+
const receipt = this.client.receipt(call, result, hash);
|
|
224
|
+
const classified = queryExchange(result, receipt, emptyMember, true);
|
|
225
|
+
if (classified) return classified;
|
|
226
|
+
try {
|
|
227
|
+
return newQueryBranch("found", decodeMember(result.body, hash), receipt);
|
|
228
|
+
} catch {
|
|
229
|
+
return newQueryBranch("invalidResponse", emptyMember, receipt, mailchimpFailure(operation2, "PROTOCOL", "Mailchimp returned an invalid contact"));
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
var ListMembersOperation = class {
|
|
234
|
+
/** Bind the client. */
|
|
235
|
+
constructor(client) {
|
|
236
|
+
this.client = client;
|
|
237
|
+
}
|
|
238
|
+
client;
|
|
239
|
+
/** Return the manifest definition. */
|
|
240
|
+
definition() {
|
|
241
|
+
return ListMembersDefinition;
|
|
242
|
+
}
|
|
243
|
+
/** Read one page with optional status and time filters. */
|
|
244
|
+
async invoke(call, input) {
|
|
245
|
+
const operation2 = "listMembers";
|
|
246
|
+
const validation = validateListInput(input);
|
|
247
|
+
if (validation) return newQueryBranch("defect", emptyPage, zeroReceipt(), mailchimpFailure(operation2, "VALIDATION", validation));
|
|
248
|
+
const connection = await this.client.resolveConnection(call);
|
|
249
|
+
if (!connection) return credentialQueryDefect(operation2, emptyPage);
|
|
250
|
+
const pageSize = input.pageSize || 100;
|
|
251
|
+
const query = new URLSearchParams({ count: String(pageSize), offset: String(input.offset ?? 0), sort_field: "last_changed", sort_dir: "ASC", fields: memberFields });
|
|
252
|
+
if (input.status) query.set("status", input.status);
|
|
253
|
+
if (input.changedSince) query.set("since_last_changed", formatMailchimpTime(input.changedSince));
|
|
254
|
+
if (input.optedInSince) query.set("since_timestamp_opt", formatMailchimpTime(input.optedInSince));
|
|
255
|
+
const result = await this.client.exchange(call, connection, operation2, "GET", `/lists/${input.listId}/members`, query);
|
|
256
|
+
const receipt = this.client.receipt(call, result, input.listId);
|
|
257
|
+
const classified = queryExchange(result, receipt, emptyPage, true);
|
|
258
|
+
if (classified) return classified;
|
|
259
|
+
try {
|
|
260
|
+
const page = parseObject(result.body);
|
|
261
|
+
const wires = page.members ?? [];
|
|
262
|
+
if (!Array.isArray(wires) || !Number.isInteger(page.total_items) || Number(page.total_items) < 0 || wires.length > pageSize) throw new Error("invalid page");
|
|
263
|
+
const members = wires.map((wire) => decodeMemberObject(wire, ""));
|
|
264
|
+
const totalItems = Number(page.total_items);
|
|
265
|
+
const offset = (input.offset ?? 0) + members.length;
|
|
266
|
+
return newQueryBranch("listed", { members, totalItems, ...members.length > 0 && offset < totalItems ? { nextOffset: offset } : {} }, receipt);
|
|
267
|
+
} catch {
|
|
268
|
+
return newQueryBranch("invalidResponse", emptyPage, receipt, mailchimpFailure(operation2, "PROTOCOL", "Mailchimp returned an invalid page of contacts"));
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
var UpsertMemberOperation = class {
|
|
273
|
+
/** Bind the client. */
|
|
274
|
+
constructor(client) {
|
|
275
|
+
this.client = client;
|
|
276
|
+
}
|
|
277
|
+
client;
|
|
278
|
+
/** Return the manifest definition. */
|
|
279
|
+
definition() {
|
|
280
|
+
return UpsertMemberDefinition;
|
|
281
|
+
}
|
|
282
|
+
/** Use the stable Call ID for receipt correlation. */
|
|
283
|
+
idempotencyKey(callId) {
|
|
284
|
+
return callId;
|
|
285
|
+
}
|
|
286
|
+
/** Write one contact without changing an existing subscription unless requested. */
|
|
287
|
+
async invoke(call, input) {
|
|
288
|
+
const operation2 = "upsertMember";
|
|
289
|
+
const validation = validateUpsertInput(input);
|
|
290
|
+
if (validation) return newMutationBranch("defect", emptyUpsert, zeroReceipt(), mailchimpFailure(operation2, "VALIDATION", validation));
|
|
291
|
+
const connection = await this.client.resolveConnection(call);
|
|
292
|
+
if (!connection) return credentialMutationDefect(operation2, emptyUpsert);
|
|
293
|
+
const hash = subscriberHash(input.emailAddress);
|
|
294
|
+
const body = {
|
|
295
|
+
email_address: input.emailAddress,
|
|
296
|
+
status_if_new: input.statusIfNew,
|
|
297
|
+
...input.status ? { status: input.status } : {},
|
|
298
|
+
...input.mergeFields && Object.keys(input.mergeFields).length ? { merge_fields: input.mergeFields } : {},
|
|
299
|
+
...input.marketingPermissions?.length ? { marketing_permissions: input.marketingPermissions.map((permission) => ({ marketing_permission_id: permission.marketingPermissionId, enabled: permission.isEnabled })) } : {}
|
|
300
|
+
};
|
|
301
|
+
const query = input.shouldSkipMergeValidation ? new URLSearchParams({ skip_merge_validation: "true" }) : void 0;
|
|
302
|
+
const result = await this.client.exchange(call, connection, operation2, "PUT", memberPath(input.listId, hash), query, body);
|
|
303
|
+
const receipt = this.client.receipt(call, result, hash);
|
|
304
|
+
const classified = mutationExchange(result, receipt, emptyUpsert, false);
|
|
305
|
+
if (classified) return classified;
|
|
306
|
+
try {
|
|
307
|
+
return newMutationBranch("upserted", { member: decodeMember(result.body, hash) }, receipt);
|
|
308
|
+
} catch {
|
|
309
|
+
return newMutationBranch("invalidResponse", emptyUpsert, receipt, mailchimpFailure(operation2, "PROTOCOL", "Mailchimp accepted the contact but returned an invalid contact"));
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
};
|
|
313
|
+
var UpdateMemberTagsOperation = class {
|
|
314
|
+
/** Bind the client. */
|
|
315
|
+
constructor(client) {
|
|
316
|
+
this.client = client;
|
|
317
|
+
}
|
|
318
|
+
client;
|
|
319
|
+
/** Return the manifest definition. */
|
|
320
|
+
definition() {
|
|
321
|
+
return UpdateMemberTagsDefinition;
|
|
322
|
+
}
|
|
323
|
+
/** Use the stable Call ID for receipt correlation. */
|
|
324
|
+
idempotencyKey(callId) {
|
|
325
|
+
return callId;
|
|
326
|
+
}
|
|
327
|
+
/** Declare tag states for one contact. */
|
|
328
|
+
async invoke(call, input) {
|
|
329
|
+
const operation2 = "updateMemberTags";
|
|
330
|
+
const validation = validateTagsInput(input);
|
|
331
|
+
if (validation) return newMutationBranch("defect", emptyTags, zeroReceipt(), mailchimpFailure(operation2, "VALIDATION", validation));
|
|
332
|
+
const connection = await this.client.resolveConnection(call);
|
|
333
|
+
if (!connection) return credentialMutationDefect(operation2, emptyTags);
|
|
334
|
+
const hash = subscriberHash(input.emailAddress);
|
|
335
|
+
const tags = [...(input.addTags ?? []).map((name) => ({ name, status: "active" })), ...(input.removeTags ?? []).map((name) => ({ name, status: "inactive" }))];
|
|
336
|
+
const body = { tags, ...input.shouldSuppressAutomations ? { is_syncing: true } : {} };
|
|
337
|
+
const result = await this.client.exchange(call, connection, operation2, "POST", `${memberPath(input.listId, hash)}/tags`, void 0, body);
|
|
338
|
+
const receipt = this.client.receipt(call, result, hash);
|
|
339
|
+
const classified = mutationExchange(result, receipt, emptyTags, true);
|
|
340
|
+
if (classified) return classified;
|
|
341
|
+
return newMutationBranch("updated", {
|
|
342
|
+
subscriberHash: hash,
|
|
343
|
+
...input.addTags?.length ? { activeTags: input.addTags } : {},
|
|
344
|
+
...input.removeTags?.length ? { inactiveTags: input.removeTags } : {}
|
|
345
|
+
}, receipt);
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
var SendCampaignOperation = class {
|
|
349
|
+
/** Bind the client. */
|
|
350
|
+
constructor(client) {
|
|
351
|
+
this.client = client;
|
|
352
|
+
}
|
|
353
|
+
client;
|
|
354
|
+
/** Return the manifest definition. */
|
|
355
|
+
definition() {
|
|
356
|
+
return SendCampaignDefinition;
|
|
357
|
+
}
|
|
358
|
+
/** Use the stable Call ID for receipt correlation. */
|
|
359
|
+
idempotencyKey(callId) {
|
|
360
|
+
return callId;
|
|
361
|
+
}
|
|
362
|
+
/** Read status, checkpoint dispatch, and send only a draft. */
|
|
363
|
+
async invoke(call, input) {
|
|
364
|
+
const operation2 = "sendCampaign";
|
|
365
|
+
const validation = validateResourceID("campaignId", input.campaignId) || (input.expectedListId ? validateResourceID("expectedListId", input.expectedListId) : "");
|
|
366
|
+
if (validation) return newMutationBranch("defect", emptySend, zeroReceipt(), mailchimpFailure(operation2, "VALIDATION", validation));
|
|
367
|
+
const connection = await this.client.resolveConnection(call);
|
|
368
|
+
if (!connection) return credentialMutationDefect(operation2, emptySend);
|
|
369
|
+
const query = new URLSearchParams({ fields: campaignFields });
|
|
370
|
+
let earlier = false;
|
|
371
|
+
try {
|
|
372
|
+
const previous = call.context.hasLastHeartbeatValue() ? call.context.getLastHeartbeatValue() : void 0;
|
|
373
|
+
earlier = previous !== void 0 && previous !== null;
|
|
374
|
+
} catch {
|
|
375
|
+
earlier = true;
|
|
376
|
+
}
|
|
377
|
+
const read = await this.client.exchange(call, connection, operation2, "GET", `/campaigns/${input.campaignId}`, query);
|
|
378
|
+
const readReceipt = this.client.receipt(call, read, input.campaignId);
|
|
379
|
+
if (earlier) {
|
|
380
|
+
if (read.outcome === "succeeded") {
|
|
381
|
+
try {
|
|
382
|
+
const campaign2 = decodeCampaign(read.body, input.campaignId);
|
|
383
|
+
if (campaign2.status === "sending" || campaign2.status === "sent") return newMutationBranch("alreadySent", { campaign: campaign2 }, readReceipt);
|
|
384
|
+
return newMutationUncertain({ campaign: campaign2 }, mailchimpFailure(operation2, "TRANSPORT", "an earlier attempt may have sent the campaign"), readReceipt);
|
|
385
|
+
} catch {
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
return newMutationUncertain(emptySend, mailchimpFailure(operation2, "TRANSPORT", "an earlier attempt may have sent the campaign and its status could not be read"), readReceipt);
|
|
389
|
+
}
|
|
390
|
+
const classified = mutationExchange(read, readReceipt, emptySend, true);
|
|
391
|
+
if (classified) return classified;
|
|
392
|
+
let campaign;
|
|
393
|
+
try {
|
|
394
|
+
campaign = decodeCampaign(read.body, input.campaignId);
|
|
395
|
+
} catch {
|
|
396
|
+
return newMutationBranch("invalidResponse", emptySend, readReceipt, mailchimpFailure(operation2, "PROTOCOL", "Mailchimp returned an invalid campaign, so it was not sent"));
|
|
397
|
+
}
|
|
398
|
+
const output = { campaign };
|
|
399
|
+
if (campaign.status === "sending" || campaign.status === "sent") return newMutationBranch("alreadySent", output, readReceipt);
|
|
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(operation2, "CONFLICT", `${blocker}; nothing was sent`));
|
|
402
|
+
try {
|
|
403
|
+
await call.context.recordHeartbeat({ mailchimpDispatchedCallId: call.id });
|
|
404
|
+
} catch {
|
|
405
|
+
return newMutationRetry(mailchimpFailure(operation2, "AVAILABILITY", "Dex did not record the dispatch checkpoint; nothing was sent"));
|
|
406
|
+
}
|
|
407
|
+
const sent = await this.client.exchange(call, connection, operation2, "POST", `/campaigns/${input.campaignId}/actions/send`);
|
|
408
|
+
const receipt = this.client.receipt(call, sent, input.campaignId);
|
|
409
|
+
if (sent.outcome === "succeeded") return newMutationBranch("sent", output, receipt);
|
|
410
|
+
if (sent.outcome === "rateLimited" || sent.outcome === "notSent") {
|
|
411
|
+
try {
|
|
412
|
+
await call.context.recordHeartbeat(void 0);
|
|
413
|
+
} catch {
|
|
414
|
+
}
|
|
415
|
+
return newMutationRetry(sent.failure, sent.retryAfterMs);
|
|
416
|
+
}
|
|
417
|
+
if (sent.outcome === "unavailable" || sent.outcome === "invalid") return newMutationUncertain(output, sent.failure, receipt);
|
|
418
|
+
if (sent.outcome === "defect") return newMutationBranch("defect", output, receipt, sent.failure);
|
|
419
|
+
return newMutationBranch(sent.outcome === "notFound" ? "notFound" : "providerRejected", output, receipt, sent.failure);
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
function queryExchange(exchange, receipt, zero, hasNotFound) {
|
|
423
|
+
if (exchange.outcome === "succeeded") return void 0;
|
|
424
|
+
if (["rateLimited", "notSent", "unavailable"].includes(exchange.outcome)) return newQueryRetry(exchange.failure, exchange.retryAfterMs);
|
|
425
|
+
const branch = exchange.outcome === "notFound" && hasNotFound ? "notFound" : exchange.outcome === "invalid" ? "invalidResponse" : exchange.outcome === "defect" ? "defect" : "providerRejected";
|
|
426
|
+
return newQueryBranch(branch, zero, receipt, exchange.failure);
|
|
427
|
+
}
|
|
428
|
+
function mutationExchange(exchange, receipt, zero, hasNotFound) {
|
|
429
|
+
if (exchange.outcome === "succeeded") return void 0;
|
|
430
|
+
if (["rateLimited", "notSent", "unavailable"].includes(exchange.outcome)) return newMutationRetry(exchange.failure, exchange.retryAfterMs);
|
|
431
|
+
const branch = exchange.outcome === "notFound" && hasNotFound ? "notFound" : exchange.outcome === "invalid" ? "invalidResponse" : exchange.outcome === "defect" ? "defect" : "providerRejected";
|
|
432
|
+
return newMutationBranch(branch, zero, receipt, exchange.failure);
|
|
433
|
+
}
|
|
434
|
+
function credentialQueryDefect(operation2, zero) {
|
|
435
|
+
return newQueryBranch("defect", zero, zeroReceipt(), mailchimpFailure(operation2, "AUTHENTICATION", "connection credentials are unavailable"));
|
|
436
|
+
}
|
|
437
|
+
function credentialMutationDefect(operation2, zero) {
|
|
438
|
+
return newMutationBranch("defect", zero, zeroReceipt(), mailchimpFailure(operation2, "AUTHENTICATION", "connection credentials are unavailable"));
|
|
439
|
+
}
|
|
440
|
+
function validateResourceID(name, value) {
|
|
441
|
+
return /^[A-Za-z0-9]{1,64}$/.test(value) ? "" : `${name} must be a Mailchimp ID of 1 to 64 letters and digits`;
|
|
442
|
+
}
|
|
443
|
+
function validateEmail(value) {
|
|
444
|
+
if (!value || Buffer.byteLength(value) > 254) return "emailAddress must be one email address of at most 254 bytes";
|
|
445
|
+
if (!isGoBareEmailAddress(value)) return "emailAddress must be one bare email address such as jane@example.com";
|
|
446
|
+
return "";
|
|
447
|
+
}
|
|
448
|
+
function validateMemberAddress(listID, email) {
|
|
449
|
+
return validateResourceID("listId", listID) || validateEmail(email);
|
|
450
|
+
}
|
|
451
|
+
function subscriberHash(email) {
|
|
452
|
+
return createHash("md5").update(goSimpleLower(email), "utf8").digest("hex");
|
|
453
|
+
}
|
|
454
|
+
function memberPath(listID, hash) {
|
|
455
|
+
return `/lists/${listID}/members/${hash}`;
|
|
456
|
+
}
|
|
457
|
+
function validateListInput(input) {
|
|
458
|
+
if (validateResourceID("listId", input.listId)) return validateResourceID("listId", input.listId);
|
|
459
|
+
if (input.status && !readableStatuses.has(input.status)) return "status is not a Mailchimp contact status";
|
|
460
|
+
if (input.pageSize !== void 0 && (!Number.isInteger(input.pageSize) || input.pageSize < 0 || input.pageSize > 1e3)) return "pageSize must be 1 to 1000, or zero for 100";
|
|
461
|
+
if (input.offset !== void 0 && (!Number.isInteger(input.offset) || input.offset < 0 || input.offset > 2147483647)) return "offset must be a non-negative number of contacts";
|
|
462
|
+
for (const bound of [input.changedSince, input.optedInSince]) {
|
|
463
|
+
if (!bound) continue;
|
|
464
|
+
try {
|
|
465
|
+
if (timestamp(bound) === "0001-01-01T00:00:00Z") return "time bound is invalid";
|
|
466
|
+
} catch {
|
|
467
|
+
return "time bound is invalid";
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
return "";
|
|
471
|
+
}
|
|
472
|
+
function formatMailchimpTime(value) {
|
|
473
|
+
return timestamp(value).slice(0, 19) + "+00:00";
|
|
474
|
+
}
|
|
475
|
+
function validateUpsertInput(input) {
|
|
476
|
+
const addressError = validateMemberAddress(input.listId, input.emailAddress);
|
|
477
|
+
if (addressError) return addressError;
|
|
478
|
+
if (!writableStatuses.has(input.statusIfNew)) return "statusIfNew is required";
|
|
479
|
+
if (input.status && !writableStatuses.has(input.status)) return "status is invalid";
|
|
480
|
+
if ((input.status === "subscribed" || input.status === "pending") && !input.isResubscribeAllowed) return "isResubscribeAllowed is required";
|
|
481
|
+
if (input.mergeFields) {
|
|
482
|
+
if (Object.keys(input.mergeFields).length > 30) return "mergeFields holds at most 30 fields";
|
|
483
|
+
for (const [tag, value] of Object.entries(input.mergeFields)) {
|
|
484
|
+
if (!/^[A-Z0-9_]{1,50}$/.test(tag)) return `merge tag ${tag} is invalid`;
|
|
485
|
+
const validText = (text2) => Buffer.byteLength(text2) <= 1024 && !/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/.test(text2);
|
|
486
|
+
if (typeof value === "string" && validText(value)) continue;
|
|
487
|
+
if (typeof value === "number" && Number.isFinite(value)) continue;
|
|
488
|
+
if (value && typeof value === "object" && !Array.isArray(value) && Object.entries(value).every(([key, text2]) => /^[a-z][a-z0-9_]{0,31}$/.test(key) && typeof text2 === "string" && validText(text2))) continue;
|
|
489
|
+
return `merge field ${tag} is invalid`;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
if ((input.marketingPermissions?.length ?? 0) > 20) return "marketingPermissions holds at most 20 permissions";
|
|
493
|
+
const seen = /* @__PURE__ */ new Set();
|
|
494
|
+
for (const permission of input.marketingPermissions ?? []) {
|
|
495
|
+
const invalid = validateResourceID("marketingPermissionId", permission.marketingPermissionId);
|
|
496
|
+
if (invalid) return invalid;
|
|
497
|
+
if (seen.has(permission.marketingPermissionId)) return "marketing permission repeats";
|
|
498
|
+
seen.add(permission.marketingPermissionId);
|
|
499
|
+
}
|
|
500
|
+
return "";
|
|
501
|
+
}
|
|
502
|
+
function validateTagsInput(input) {
|
|
503
|
+
const addressError = validateMemberAddress(input.listId, input.emailAddress);
|
|
504
|
+
if (addressError) return addressError;
|
|
505
|
+
const tags = [...input.addTags ?? [], ...input.removeTags ?? []];
|
|
506
|
+
if (!tags.length || tags.length > 50) return "addTags and removeTags must hold 1 to 50 tags together";
|
|
507
|
+
const seen = /* @__PURE__ */ new Set();
|
|
508
|
+
for (const tag of tags) {
|
|
509
|
+
if (!tag || Buffer.byteLength(tag) > 100 || goTrimSpace(tag) !== tag || /[\u0000-\u001f\u007f-\u009f]/.test(tag)) return "tag name is invalid";
|
|
510
|
+
const lower = goSimpleLower(tag);
|
|
511
|
+
if (seen.has(lower)) return "tag appears more than once";
|
|
512
|
+
seen.add(lower);
|
|
513
|
+
}
|
|
514
|
+
return "";
|
|
515
|
+
}
|
|
516
|
+
function parseObject(body) {
|
|
517
|
+
const value = JSON.parse(Buffer.from(body).toString("utf8"));
|
|
518
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid object");
|
|
519
|
+
return value;
|
|
520
|
+
}
|
|
521
|
+
function text(object2, key) {
|
|
522
|
+
const value = object2[key];
|
|
523
|
+
if (value === void 0 || value === null) return "";
|
|
524
|
+
if (typeof value !== "string") throw new Error(`invalid ${key}`);
|
|
525
|
+
return value;
|
|
526
|
+
}
|
|
527
|
+
function number(object2, key) {
|
|
528
|
+
const value = object2[key];
|
|
529
|
+
if (value === void 0 || value === null) return 0;
|
|
530
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new Error(`invalid ${key}`);
|
|
531
|
+
return value;
|
|
532
|
+
}
|
|
533
|
+
function boolean(object2, key) {
|
|
534
|
+
const value = object2[key];
|
|
535
|
+
if (value === void 0 || value === null) return false;
|
|
536
|
+
if (typeof value !== "boolean") throw new Error(`invalid ${key}`);
|
|
537
|
+
return value;
|
|
538
|
+
}
|
|
539
|
+
function object(object2, key) {
|
|
540
|
+
const value = object2[key];
|
|
541
|
+
if (value === void 0 || value === null) return {};
|
|
542
|
+
if (typeof value !== "object" || Array.isArray(value)) throw new Error(`invalid ${key}`);
|
|
543
|
+
return value;
|
|
544
|
+
}
|
|
545
|
+
function timestamp(value) {
|
|
546
|
+
return value ? goRFC3339UTC(value) : void 0;
|
|
547
|
+
}
|
|
548
|
+
function decodeMember(body, hash) {
|
|
549
|
+
return decodeMemberObject(parseObject(body), hash);
|
|
550
|
+
}
|
|
551
|
+
function decodeMemberObject(value, expectedHash) {
|
|
552
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid contact");
|
|
553
|
+
const wire = value;
|
|
554
|
+
const id = text(wire, "id");
|
|
555
|
+
if (!/^[0-9a-f]{32}$/.test(id) || expectedHash && id !== expectedHash || !text(wire, "email_address") || !text(wire, "status")) throw new Error("invalid contact");
|
|
556
|
+
if (wire.tags !== void 0 && wire.tags !== null && !Array.isArray(wire.tags)) throw new Error("invalid tags");
|
|
557
|
+
const tags = Array.isArray(wire.tags) ? wire.tags.map((value2) => text(object({ tag: value2 }, "tag"), "name")) : [];
|
|
558
|
+
const mergeFields = wire.merge_fields === void 0 || wire.merge_fields === null ? void 0 : object(wire, "merge_fields");
|
|
559
|
+
return {
|
|
560
|
+
subscriberHash: id,
|
|
561
|
+
emailAddress: text(wire, "email_address"),
|
|
562
|
+
status: text(wire, "status"),
|
|
563
|
+
tagCount: number(wire, "tags_count"),
|
|
564
|
+
listId: text(wire, "list_id"),
|
|
565
|
+
...text(wire, "contact_id") ? { contactId: text(wire, "contact_id") } : {},
|
|
566
|
+
...text(wire, "full_name") ? { fullName: text(wire, "full_name") } : {},
|
|
567
|
+
...text(wire, "email_type") ? { emailType: text(wire, "email_type") } : {},
|
|
568
|
+
...mergeFields && Object.keys(mergeFields).length ? { mergeFields } : {},
|
|
569
|
+
...tags.length ? { tags } : {},
|
|
570
|
+
...boolean(wire, "vip") ? { isVip: true } : {},
|
|
571
|
+
...text(wire, "language") ? { language: text(wire, "language") } : {},
|
|
572
|
+
...number(wire, "web_id") ? { webId: number(wire, "web_id") } : {},
|
|
573
|
+
...timestamp(text(wire, "timestamp_signup")) ? { signedUpAt: timestamp(text(wire, "timestamp_signup")) } : {},
|
|
574
|
+
...timestamp(text(wire, "timestamp_opt")) ? { optedInAt: timestamp(text(wire, "timestamp_opt")) } : {},
|
|
575
|
+
...timestamp(text(wire, "last_changed")) ? { lastChangedAt: timestamp(text(wire, "last_changed")) } : {}
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
function decodeCampaign(body, expectedID) {
|
|
579
|
+
const wire = parseObject(body);
|
|
580
|
+
const settings = object(wire, "settings");
|
|
581
|
+
const recipients = object(wire, "recipients");
|
|
582
|
+
if (text(wire, "id") !== expectedID || !text(wire, "status") || !text(wire, "type")) throw new Error("invalid campaign");
|
|
583
|
+
return {
|
|
584
|
+
id: expectedID,
|
|
585
|
+
type: text(wire, "type"),
|
|
586
|
+
status: text(wire, "status"),
|
|
587
|
+
recipientCount: number(recipients, "recipient_count"),
|
|
588
|
+
emailsSent: number(wire, "emails_sent"),
|
|
589
|
+
...number(wire, "web_id") ? { webId: number(wire, "web_id") } : {},
|
|
590
|
+
...text(settings, "title") ? { title: text(settings, "title") } : {},
|
|
591
|
+
...text(settings, "subject_line") ? { subjectLine: text(settings, "subject_line") } : {},
|
|
592
|
+
...text(recipients, "list_id") ? { listId: text(recipients, "list_id") } : {},
|
|
593
|
+
...text(recipients, "list_name") ? { listName: text(recipients, "list_name") } : {},
|
|
594
|
+
...timestamp(text(wire, "create_time")) ? { createdAt: timestamp(text(wire, "create_time")) } : {},
|
|
595
|
+
...timestamp(text(wire, "send_time")) ? { sentAt: timestamp(text(wire, "send_time")) } : {}
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
// src/client.ts
|
|
600
|
+
function mailchimpFailure(operation2, kind, message) {
|
|
601
|
+
return { kind, provider: "mailchimp", operation: operation2, message };
|
|
602
|
+
}
|
|
603
|
+
var defaultPollIntervalMs = 3e4;
|
|
604
|
+
var MinimumPollIntervalMs = 5e3;
|
|
605
|
+
var MailchimpClient = class {
|
|
606
|
+
/** The memberChanged Trigger's delay between polls, in milliseconds. */
|
|
607
|
+
pollIntervalMs;
|
|
608
|
+
/** Receipt and Retry-After clock. */
|
|
609
|
+
now;
|
|
610
|
+
maxResponseBytes;
|
|
611
|
+
credentials;
|
|
612
|
+
apiBaseURL;
|
|
613
|
+
send;
|
|
614
|
+
/** Validate configuration and retain immutable dependencies. */
|
|
615
|
+
constructor(config, credentials, options = {}) {
|
|
616
|
+
if (!credentials) throw new TypeError("Mailchimp credential provider is required");
|
|
617
|
+
const maximum = config.maxResponseBytes ?? 4194304;
|
|
618
|
+
if (!Number.isSafeInteger(maximum) || maximum < 1) throw new TypeError("Mailchimp response limit must be positive");
|
|
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;
|
|
623
|
+
this.credentials = credentials;
|
|
624
|
+
this.apiBaseURL = options.apiBaseURL ? validateBaseURL(options.apiBaseURL) : void 0;
|
|
625
|
+
this.send = options.send ?? sendProviderRequest;
|
|
626
|
+
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
627
|
+
}
|
|
628
|
+
/** Bind the contact read. */
|
|
629
|
+
getMember() {
|
|
630
|
+
return new GetMemberOperation(this);
|
|
631
|
+
}
|
|
632
|
+
/** Bind the audience page read. */
|
|
633
|
+
listMembers() {
|
|
634
|
+
return new ListMembersOperation(this);
|
|
635
|
+
}
|
|
636
|
+
/** Bind the contact upsert. */
|
|
637
|
+
upsertMember() {
|
|
638
|
+
return new UpsertMemberOperation(this);
|
|
639
|
+
}
|
|
640
|
+
/** Bind the tag update. */
|
|
641
|
+
updateMemberTags() {
|
|
642
|
+
return new UpdateMemberTagsOperation(this);
|
|
643
|
+
}
|
|
644
|
+
/** Bind the guarded campaign send. */
|
|
645
|
+
sendCampaign() {
|
|
646
|
+
return new SendCampaignOperation(this);
|
|
647
|
+
}
|
|
648
|
+
/** Resolve the current API key and its data center without exposing it in failures. */
|
|
649
|
+
async resolveConnection(call) {
|
|
650
|
+
let key;
|
|
651
|
+
try {
|
|
652
|
+
key = (await this.credentials.resolve(call, call.context.cancellationSignal)).apiKey.reveal();
|
|
653
|
+
} catch {
|
|
654
|
+
return void 0;
|
|
655
|
+
}
|
|
656
|
+
const match = /^([A-Za-z0-9]{8,128})-([a-z]{2,10}[0-9]{1,4})$/.exec(key);
|
|
657
|
+
if (!match || !isHeaderSafeCredential(key)) return void 0;
|
|
658
|
+
return { key, baseURL: this.apiBaseURL ?? `https://${match[2]}.api.mailchimp.com/3.0` };
|
|
659
|
+
}
|
|
660
|
+
/** Send one request and classify the outcome before an operation chooses its branch. */
|
|
661
|
+
async exchange(call, connection, operation2, method, path, query, payload) {
|
|
662
|
+
const url = `${connection.baseURL}${path}${query && [...query.keys()].length ? `?${sortedQuery(query)}` : ""}`;
|
|
663
|
+
const headers = { Authorization: `Bearer ${connection.key}`, Accept: "application/json" };
|
|
664
|
+
if (payload !== void 0) headers["Content-Type"] = "application/json";
|
|
665
|
+
const request = {
|
|
666
|
+
url,
|
|
667
|
+
method,
|
|
668
|
+
headers,
|
|
669
|
+
maxResponseBytes: this.maxResponseBytes,
|
|
670
|
+
addressPolicy: this.apiBaseURL ? "privateNetworkHTTP" : "publicHTTPS",
|
|
671
|
+
timeoutMs: Math.min(25e3, call.context.deadline ? Math.max(1, call.context.deadline.getTime() - Date.now()) : 25e3),
|
|
672
|
+
signal: call.context.cancellationSignal,
|
|
673
|
+
...payload !== void 0 ? { body: Buffer.from(JSON.stringify(payload), "utf8") } : {}
|
|
674
|
+
};
|
|
675
|
+
let response;
|
|
676
|
+
try {
|
|
677
|
+
response = await this.send(request);
|
|
678
|
+
} catch (error) {
|
|
679
|
+
if (error instanceof BodyTooLargeError && error.status !== void 0 && error.headers !== void 0) {
|
|
680
|
+
response = { status: error.status, headers: error.headers, body: new Uint8Array() };
|
|
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 };
|
|
682
|
+
} else {
|
|
683
|
+
const isNotSent = error instanceof AddressRefusal || error instanceof ProviderTransportError && error.isProvablyNotSent;
|
|
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 };
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
const status = response.status;
|
|
688
|
+
const retryAfterMs = parseRetryAfter(header(response.headers, "retry-after"), this.now());
|
|
689
|
+
if (status >= 200 && status < 300) {
|
|
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 };
|
|
691
|
+
return { outcome: "succeeded", status, headers: response.headers, body: response.body, retryAfterMs: 0 };
|
|
692
|
+
}
|
|
693
|
+
const hasProblem = hasProblemDocument(response.body);
|
|
694
|
+
let outcome;
|
|
695
|
+
let kind;
|
|
696
|
+
if (status === 429 || status === 403 && !hasProblem) {
|
|
697
|
+
outcome = "rateLimited";
|
|
698
|
+
kind = "RATE_LIMIT";
|
|
699
|
+
} else if (status === 408 || status >= 500) {
|
|
700
|
+
outcome = "unavailable";
|
|
701
|
+
kind = "AVAILABILITY";
|
|
702
|
+
} else if (status === 404) {
|
|
703
|
+
outcome = "notFound";
|
|
704
|
+
kind = "NOT_FOUND";
|
|
705
|
+
} else {
|
|
706
|
+
outcome = "rejected";
|
|
707
|
+
kind = status === 401 ? "AUTHENTICATION" : status === 403 ? "AUTHORIZATION" : status === 409 ? "CONFLICT" : status === 400 ? "VALIDATION" : status >= 300 && status < 400 ? "PROTOCOL" : "PROVIDER_REJECTION";
|
|
708
|
+
}
|
|
709
|
+
return { outcome, status, headers: response.headers, body: new Uint8Array(), failure: mailchimpFailure(operation2, kind, `Mailchimp request failed (HTTP ${status})`), retryAfterMs };
|
|
710
|
+
}
|
|
711
|
+
/** Create a secret-free provider receipt. */
|
|
712
|
+
receipt(call, exchange, objectID) {
|
|
713
|
+
const requestID = header(exchange.headers, "x-request-id");
|
|
714
|
+
return {
|
|
715
|
+
callId: call.id,
|
|
716
|
+
provider: "mailchimp",
|
|
717
|
+
observedAt: goDate(this.now()),
|
|
718
|
+
...call.idempotencyKey ? { idempotencyKey: call.idempotencyKey } : {},
|
|
719
|
+
...objectID ? { providerObjectId: objectID } : {},
|
|
720
|
+
.../^[A-Za-z0-9._:-]{1,128}$/.test(requestID) ? { providerRequestId: requestID } : {}
|
|
721
|
+
};
|
|
722
|
+
}
|
|
723
|
+
};
|
|
724
|
+
function header(headers, name) {
|
|
725
|
+
const value = headers[name.toLowerCase()];
|
|
726
|
+
return Array.isArray(value) ? value[0] ?? "" : value ?? "";
|
|
727
|
+
}
|
|
728
|
+
function hasProblemDocument(body) {
|
|
729
|
+
try {
|
|
730
|
+
const document = JSON.parse(Buffer.from(body).toString("utf8"));
|
|
731
|
+
return typeof document.title === "string";
|
|
732
|
+
} catch {
|
|
733
|
+
return false;
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
function sortedQuery(query) {
|
|
737
|
+
return [...query.entries()].sort(([left], [right]) => Buffer.compare(Buffer.from(left), Buffer.from(right))).map(([key, value]) => `${goQueryEscape(key)}=${goQueryEscape(value)}`).join("&");
|
|
738
|
+
}
|
|
739
|
+
function goQueryEscape(value) {
|
|
740
|
+
return [...Buffer.from(value, "utf8")].map((byte) => byte >= 65 && byte <= 90 || byte >= 97 && byte <= 122 || byte >= 48 && byte <= 57 || [45, 46, 95, 126].includes(byte) ? String.fromCharCode(byte) : byte === 32 ? "+" : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`).join("");
|
|
741
|
+
}
|
|
742
|
+
function goDate(date) {
|
|
743
|
+
return date.toISOString().replace(/\.000Z$/, "Z");
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
// src/project.ts
|
|
747
|
+
function newProjectConnection2(project, connectionName, options = {}) {
|
|
748
|
+
return newProjectConnection(project, connectionName, (loadedProject, name) => {
|
|
749
|
+
const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "mailchimp" && entry.connectionName === name);
|
|
750
|
+
if (!selected) throw new TypeError("Mailchimp project connection is not configured");
|
|
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
|
+
};
|
|
756
|
+
const credentials = {
|
|
757
|
+
async resolve(call, signal) {
|
|
758
|
+
void call;
|
|
759
|
+
const fields = await loadedProject.resolveCredential("mailchimp", name, signal);
|
|
760
|
+
const decoded = z2.object({ api_key: z2.string().min(1) }).parse(fields);
|
|
761
|
+
return { apiKey: new SecretString(decoded.api_key) };
|
|
762
|
+
}
|
|
763
|
+
};
|
|
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` });
|
|
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 };
|
|
1150
|
+
}
|
|
1151
|
+
export {
|
|
1152
|
+
CampaignSchema,
|
|
1153
|
+
ConfigSchema,
|
|
1154
|
+
Connection,
|
|
1155
|
+
ConnectorID,
|
|
1156
|
+
GetMemberBranch,
|
|
1157
|
+
GetMemberBranchDefect,
|
|
1158
|
+
GetMemberBranchFound,
|
|
1159
|
+
GetMemberBranchInvalidResponse,
|
|
1160
|
+
GetMemberBranchNotFound,
|
|
1161
|
+
GetMemberBranchProviderRejected,
|
|
1162
|
+
GetMemberDefinition,
|
|
1163
|
+
GetMemberInputSchema,
|
|
1164
|
+
GetMemberMetadata,
|
|
1165
|
+
GetMemberOperation,
|
|
1166
|
+
ListMembersBranch,
|
|
1167
|
+
ListMembersBranchDefect,
|
|
1168
|
+
ListMembersBranchInvalidResponse,
|
|
1169
|
+
ListMembersBranchListed,
|
|
1170
|
+
ListMembersBranchNotFound,
|
|
1171
|
+
ListMembersBranchProviderRejected,
|
|
1172
|
+
ListMembersDefinition,
|
|
1173
|
+
ListMembersInputSchema2 as ListMembersInputSchema,
|
|
1174
|
+
ListMembersMetadata,
|
|
1175
|
+
ListMembersOperation,
|
|
1176
|
+
ListMembersOutputSchema,
|
|
1177
|
+
MailchimpClient,
|
|
1178
|
+
MarketingPermissionInputSchema,
|
|
1179
|
+
MemberChangedEventSchema,
|
|
1180
|
+
MemberChangedTriggerConfigurationSchema,
|
|
1181
|
+
MemberChangedTriggerDefinition,
|
|
1182
|
+
MemberSchema,
|
|
1183
|
+
MemberStatuses,
|
|
1184
|
+
MinimumPollIntervalMs,
|
|
1185
|
+
ProviderID,
|
|
1186
|
+
SendCampaignBranch,
|
|
1187
|
+
SendCampaignBranchAlreadySent,
|
|
1188
|
+
SendCampaignBranchDefect,
|
|
1189
|
+
SendCampaignBranchInvalidResponse,
|
|
1190
|
+
SendCampaignBranchNotFound,
|
|
1191
|
+
SendCampaignBranchNotSendable,
|
|
1192
|
+
SendCampaignBranchProviderRejected,
|
|
1193
|
+
SendCampaignBranchSent,
|
|
1194
|
+
SendCampaignBranchUncertain,
|
|
1195
|
+
SendCampaignDefinition,
|
|
1196
|
+
SendCampaignInputSchema,
|
|
1197
|
+
SendCampaignMetadata,
|
|
1198
|
+
SendCampaignOperation,
|
|
1199
|
+
SendCampaignOutputSchema,
|
|
1200
|
+
UIAudienceIDEntryPortAudienceID,
|
|
1201
|
+
UIMemberStatusPickerPortStatuses,
|
|
1202
|
+
UIUnitAudienceIDEntry,
|
|
1203
|
+
UIUnitMemberStatusPicker,
|
|
1204
|
+
UpdateMemberTagsBranch,
|
|
1205
|
+
UpdateMemberTagsBranchDefect,
|
|
1206
|
+
UpdateMemberTagsBranchInvalidResponse,
|
|
1207
|
+
UpdateMemberTagsBranchNotFound,
|
|
1208
|
+
UpdateMemberTagsBranchProviderRejected,
|
|
1209
|
+
UpdateMemberTagsBranchUpdated,
|
|
1210
|
+
UpdateMemberTagsDefinition,
|
|
1211
|
+
UpdateMemberTagsInputSchema,
|
|
1212
|
+
UpdateMemberTagsMetadata,
|
|
1213
|
+
UpdateMemberTagsOperation,
|
|
1214
|
+
UpdateMemberTagsOutputSchema,
|
|
1215
|
+
UpsertMemberBranch,
|
|
1216
|
+
UpsertMemberBranchDefect,
|
|
1217
|
+
UpsertMemberBranchInvalidResponse,
|
|
1218
|
+
UpsertMemberBranchProviderRejected,
|
|
1219
|
+
UpsertMemberBranchUpserted,
|
|
1220
|
+
UpsertMemberDefinition,
|
|
1221
|
+
UpsertMemberInputSchema,
|
|
1222
|
+
UpsertMemberMetadata,
|
|
1223
|
+
UpsertMemberOperation,
|
|
1224
|
+
UpsertMemberOutputSchema,
|
|
1225
|
+
decodeCredentials,
|
|
1226
|
+
decodeMemberChangedEventPayload,
|
|
1227
|
+
defineMemberChangedTriggerBinding,
|
|
1228
|
+
newConnection,
|
|
1229
|
+
newConnectionWithOperations,
|
|
1230
|
+
newGetMemberStep,
|
|
1231
|
+
newListMembersStep,
|
|
1232
|
+
newMemberChangedTrigger,
|
|
1233
|
+
newMemberTriggerRunner,
|
|
1234
|
+
newProjectConnection2 as newProjectConnection,
|
|
1235
|
+
newProjectMemberTriggerRunner,
|
|
1236
|
+
newSendCampaignStep,
|
|
1237
|
+
newUpdateMemberTagsStep,
|
|
1238
|
+
newUpsertMemberStep
|
|
1239
|
+
};
|