@superdurable/connector-brevo 0.1.1 → 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/dist/index.js CHANGED
@@ -1,9 +1,32 @@
1
1
  import {
2
+ AttributeChangeResultSchema,
3
+ AttributeEnumerationValueSchema,
4
+ AttributeIdentitySchema,
5
+ AttributesListSchema,
2
6
  ConfigSchema,
3
7
  Connection,
4
8
  ConnectorID,
9
+ ContactChangeResultSchema,
10
+ ContactIdentitySchema,
5
11
  ContactSchema,
6
12
  ContactWriteResultSchema,
13
+ ContactsListSchema,
14
+ CreateAttributeBranch,
15
+ CreateAttributeBranchCreated,
16
+ CreateAttributeBranchDefect,
17
+ CreateAttributeBranchProviderRejected,
18
+ CreateAttributeBranchUncertain,
19
+ CreateAttributeDefinition,
20
+ CreateAttributeInputSchema,
21
+ CreateAttributeMetadata,
22
+ CreateContactBranch,
23
+ CreateContactBranchCreated,
24
+ CreateContactBranchDefect,
25
+ CreateContactBranchProviderRejected,
26
+ CreateContactBranchUncertain,
27
+ CreateContactDefinition,
28
+ CreateContactInputSchema,
29
+ CreateContactMetadata,
7
30
  CreateOrUpdateContactBranch,
8
31
  CreateOrUpdateContactBranchDefect,
9
32
  CreateOrUpdateContactBranchInvalidResponse,
@@ -12,6 +35,40 @@ import {
12
35
  CreateOrUpdateContactDefinition,
13
36
  CreateOrUpdateContactInputSchema,
14
37
  CreateOrUpdateContactMetadata,
38
+ CreateSenderBranch,
39
+ CreateSenderBranchCreated,
40
+ CreateSenderBranchDefect,
41
+ CreateSenderBranchProviderRejected,
42
+ CreateSenderBranchUncertain,
43
+ CreateSenderDefinition,
44
+ CreateSenderInputSchema,
45
+ CreateSenderMetadata,
46
+ CredentialMaterialError,
47
+ DeleteAttributeBranch,
48
+ DeleteAttributeBranchDefect,
49
+ DeleteAttributeBranchDeleted,
50
+ DeleteAttributeBranchNotFound,
51
+ DeleteAttributeBranchProviderRejected,
52
+ DeleteAttributeDefinition,
53
+ DeleteAttributeInputSchema,
54
+ DeleteAttributeMetadata,
55
+ DeleteContactBranch,
56
+ DeleteContactBranchDefect,
57
+ DeleteContactBranchDeleted,
58
+ DeleteContactBranchNotFound,
59
+ DeleteContactBranchProviderRejected,
60
+ DeleteContactDefinition,
61
+ DeleteContactInputSchema,
62
+ DeleteContactMetadata,
63
+ DeleteSenderBranch,
64
+ DeleteSenderBranchDefect,
65
+ DeleteSenderBranchDeleted,
66
+ DeleteSenderBranchNotFound,
67
+ DeleteSenderBranchProviderRejected,
68
+ DeleteSenderDefinition,
69
+ DeleteSenderInputSchema,
70
+ DeleteSenderMetadata,
71
+ EmailSendResultSchema,
15
72
  GetContactBranch,
16
73
  GetContactBranchDefect,
17
74
  GetContactBranchFound,
@@ -21,44 +78,270 @@ import {
21
78
  GetContactDefinition,
22
79
  GetContactInputSchema,
23
80
  GetContactMetadata,
81
+ ListAttributesBranch,
82
+ ListAttributesBranchDefect,
83
+ ListAttributesBranchInvalidResponse,
84
+ ListAttributesBranchListed,
85
+ ListAttributesBranchProviderRejected,
86
+ ListAttributesDefinition,
87
+ ListAttributesInputSchema,
88
+ ListAttributesMetadata,
89
+ ListContactsBranch,
90
+ ListContactsBranchDefect,
91
+ ListContactsBranchInvalidResponse,
92
+ ListContactsBranchListed,
93
+ ListContactsBranchProviderRejected,
94
+ ListContactsDefinition,
95
+ ListContactsInputSchema,
96
+ ListContactsMetadata,
97
+ ListSendersBranch,
98
+ ListSendersBranchDefect,
99
+ ListSendersBranchInvalidResponse,
100
+ ListSendersBranchListed,
101
+ ListSendersBranchProviderRejected,
102
+ ListSendersDefinition,
103
+ ListSendersInputSchema,
104
+ ListSendersMetadata,
24
105
  ProviderID,
106
+ SendEmailBranch,
107
+ SendEmailBranchDefect,
108
+ SendEmailBranchProviderRejected,
109
+ SendEmailBranchSent,
110
+ SendEmailBranchUncertain,
111
+ SendEmailDefinition,
112
+ SendEmailInputSchema,
113
+ SendEmailMetadata,
114
+ SendTemplateEmailBranch,
115
+ SendTemplateEmailBranchDefect,
116
+ SendTemplateEmailBranchProviderRejected,
117
+ SendTemplateEmailBranchSent,
118
+ SendTemplateEmailBranchUncertain,
119
+ SendTemplateEmailDefinition,
120
+ SendTemplateEmailInputSchema,
121
+ SendTemplateEmailMetadata,
122
+ SenderChangeResultSchema,
123
+ SenderIdentitySchema,
124
+ SendersListSchema,
125
+ UpdateAttributeBranch,
126
+ UpdateAttributeBranchDefect,
127
+ UpdateAttributeBranchNotFound,
128
+ UpdateAttributeBranchProviderRejected,
129
+ UpdateAttributeBranchUpdated,
130
+ UpdateAttributeDefinition,
131
+ UpdateAttributeInputSchema,
132
+ UpdateAttributeMetadata,
133
+ UpdateContactBranch,
134
+ UpdateContactBranchDefect,
135
+ UpdateContactBranchNotFound,
136
+ UpdateContactBranchProviderRejected,
137
+ UpdateContactBranchUpdated,
138
+ UpdateContactDefinition,
139
+ UpdateContactInputSchema,
140
+ UpdateContactMetadata,
141
+ UpdateSenderBranch,
142
+ UpdateSenderBranchDefect,
143
+ UpdateSenderBranchNotFound,
144
+ UpdateSenderBranchProviderRejected,
145
+ UpdateSenderBranchUpdated,
146
+ UpdateSenderDefinition,
147
+ UpdateSenderInputSchema,
148
+ UpdateSenderMetadata,
149
+ decodeCredentials,
150
+ decodeSignedInteger,
151
+ exactIntegerJSONCodec,
152
+ isCredentialMaterialError,
25
153
  newConnection,
26
154
  newConnectionWithOperations,
27
- newProjectConnection
28
- } from "./chunk-NI2F5J36.js";
155
+ newProjectConnection,
156
+ parseExactIntegerJSON,
157
+ parseJSONNumberTokens
158
+ } from "./chunk-VBTEJFWF.js";
29
159
 
30
160
  // src/generated/steps.ts
31
161
  import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
162
+ function newCreateContactStep(configuration) {
163
+ const { connection, connectionName, created, providerRejected, defect: defect2, uncertain, ...stepConfiguration } = configuration;
164
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
165
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.createContact(), connection: connection.reference, branches: [
166
+ goToBranch("created", created),
167
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
168
+ ...defect2 ? [goToBranch("defect", defect2)] : [],
169
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : []
170
+ ] });
171
+ }
172
+ function newListContactsStep(configuration) {
173
+ const { connection, connectionName, listed, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
174
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
175
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listContacts(), connection: connection.reference, branches: [
176
+ goToBranch("listed", listed),
177
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
178
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
179
+ ...defect2 ? [goToBranch("defect", defect2)] : []
180
+ ] });
181
+ }
182
+ function newUpdateContactStep(configuration) {
183
+ const { connection, connectionName, updated, notFound, providerRejected, defect: defect2, maxSends, ...stepConfiguration } = configuration;
184
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
185
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.updateContact(), connection: connection.reference, branches: [
186
+ goToBranch("updated", updated),
187
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
188
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
189
+ ...defect2 ? [goToBranch("defect", defect2)] : []
190
+ ] });
191
+ }
192
+ function newDeleteContactStep(configuration) {
193
+ const { connection, connectionName, deleted, notFound, providerRejected, defect: defect2, maxSends, ...stepConfiguration } = configuration;
194
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
195
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.deleteContact(), connection: connection.reference, branches: [
196
+ goToBranch("deleted", deleted),
197
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
198
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
199
+ ...defect2 ? [goToBranch("defect", defect2)] : []
200
+ ] });
201
+ }
202
+ function newListAttributesStep(configuration) {
203
+ const { connection, connectionName, listed, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
204
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
205
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listAttributes(), connection: connection.reference, branches: [
206
+ goToBranch("listed", listed),
207
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
208
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
209
+ ...defect2 ? [goToBranch("defect", defect2)] : []
210
+ ] });
211
+ }
212
+ function newCreateAttributeStep(configuration) {
213
+ const { connection, connectionName, created, providerRejected, defect: defect2, uncertain, ...stepConfiguration } = configuration;
214
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
215
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.createAttribute(), connection: connection.reference, branches: [
216
+ goToBranch("created", created),
217
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
218
+ ...defect2 ? [goToBranch("defect", defect2)] : [],
219
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : []
220
+ ] });
221
+ }
222
+ function newUpdateAttributeStep(configuration) {
223
+ const { connection, connectionName, updated, notFound, providerRejected, defect: defect2, maxSends, ...stepConfiguration } = configuration;
224
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
225
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.updateAttribute(), connection: connection.reference, branches: [
226
+ goToBranch("updated", updated),
227
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
228
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
229
+ ...defect2 ? [goToBranch("defect", defect2)] : []
230
+ ] });
231
+ }
232
+ function newDeleteAttributeStep(configuration) {
233
+ const { connection, connectionName, deleted, notFound, providerRejected, defect: defect2, maxSends, ...stepConfiguration } = configuration;
234
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
235
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.deleteAttribute(), connection: connection.reference, branches: [
236
+ goToBranch("deleted", deleted),
237
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
238
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
239
+ ...defect2 ? [goToBranch("defect", defect2)] : []
240
+ ] });
241
+ }
242
+ function newListSendersStep(configuration) {
243
+ const { connection, connectionName, listed, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
244
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
245
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listSenders(), connection: connection.reference, branches: [
246
+ goToBranch("listed", listed),
247
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
248
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
249
+ ...defect2 ? [goToBranch("defect", defect2)] : []
250
+ ] });
251
+ }
252
+ function newCreateSenderStep(configuration) {
253
+ const { connection, connectionName, created, providerRejected, defect: defect2, uncertain, ...stepConfiguration } = configuration;
254
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
255
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.createSender(), connection: connection.reference, branches: [
256
+ goToBranch("created", created),
257
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
258
+ ...defect2 ? [goToBranch("defect", defect2)] : [],
259
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : []
260
+ ] });
261
+ }
262
+ function newUpdateSenderStep(configuration) {
263
+ const { connection, connectionName, updated, notFound, providerRejected, defect: defect2, maxSends, ...stepConfiguration } = configuration;
264
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
265
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.updateSender(), connection: connection.reference, branches: [
266
+ goToBranch("updated", updated),
267
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
268
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
269
+ ...defect2 ? [goToBranch("defect", defect2)] : []
270
+ ] });
271
+ }
272
+ function newDeleteSenderStep(configuration) {
273
+ const { connection, connectionName, deleted, notFound, providerRejected, defect: defect2, maxSends, ...stepConfiguration } = configuration;
274
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
275
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.deleteSender(), connection: connection.reference, branches: [
276
+ goToBranch("deleted", deleted),
277
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
278
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
279
+ ...defect2 ? [goToBranch("defect", defect2)] : []
280
+ ] });
281
+ }
282
+ function newSendEmailStep(configuration) {
283
+ const { connection, connectionName, sent, providerRejected, defect: defect2, uncertain, ...stepConfiguration } = configuration;
284
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
285
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.sendEmail(), connection: connection.reference, branches: [
286
+ goToBranch("sent", sent),
287
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
288
+ ...defect2 ? [goToBranch("defect", defect2)] : [],
289
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : []
290
+ ] });
291
+ }
292
+ function newSendTemplateEmailStep(configuration) {
293
+ const { connection, connectionName, sent, providerRejected, defect: defect2, uncertain, ...stepConfiguration } = configuration;
294
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
295
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.sendTemplateEmail(), connection: connection.reference, branches: [
296
+ goToBranch("sent", sent),
297
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
298
+ ...defect2 ? [goToBranch("defect", defect2)] : [],
299
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : []
300
+ ] });
301
+ }
32
302
  function newCreateOrUpdateContactStep(configuration) {
33
- const { connection, connectionName, saved, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
303
+ const { connection, connectionName, saved, providerRejected, invalidResponse, defect: defect2, maxSends, ...stepConfiguration } = configuration;
34
304
  if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
35
305
  return newMutationStep({ ...stepConfiguration, operation: connection.operations.createOrUpdateContact(), connection: connection.reference, branches: [
36
306
  goToBranch("saved", saved),
37
307
  ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
38
308
  ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
39
- ...defect ? [goToBranch("defect", defect)] : []
309
+ ...defect2 ? [goToBranch("defect", defect2)] : []
40
310
  ] });
41
311
  }
42
312
  function newGetContactStep(configuration) {
43
- const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
313
+ const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
44
314
  if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
45
315
  return newQueryStep({ ...stepConfiguration, operation: connection.operations.getContact(), connection: connection.reference, branches: [
46
316
  goToBranch("found", found),
47
317
  ...notFound ? [goToBranch("notFound", notFound)] : [],
48
318
  ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
49
319
  ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
50
- ...defect ? [goToBranch("defect", defect)] : []
320
+ ...defect2 ? [goToBranch("defect", defect2)] : []
51
321
  ] });
52
322
  }
53
323
 
54
324
  // src/project.ts
55
325
  import { SecretString as SecretString2 } from "@superdurable/connectors-sdk";
56
- import { z } from "zod";
326
+ import { z as z2 } from "zod";
57
327
 
58
328
  // src/client.ts
59
- import { BodyTooLargeError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
60
- import { SecretString } from "@superdurable/connectors-sdk";
329
+ import { BodyTooLargeError, ProviderTransportError, ProviderStalledError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
330
+ import { ReauthorizationRequiredError, SecretString } from "@superdurable/connectors-sdk";
331
+ import { ConnectionNotSelectedError, CredentialBrokerRejectedError, ObjectNotFoundError } from "@superdurable/connectors-sdk/projectconfig";
61
332
  import emailAddresses from "email-addresses";
333
+ import { z } from "zod";
334
+
335
+ // src/management.ts
336
+ import {
337
+ definitionMaxSends,
338
+ newMutationBranch as newMutationBranch2,
339
+ newMutationRetry as newMutationRetry2,
340
+ newMutationUncertain,
341
+ newQueryBranch as newQueryBranch2,
342
+ newQueryRetry as newQueryRetry2
343
+ } from "@superdurable/connectors-sdk";
344
+ import { CheckpointError, DispatchNotAllowedError, InsufficientTimeError, newFence } from "@superdurable/connectors-sdk/singledispatch";
62
345
 
63
346
  // src/operations.ts
64
347
  import { newMutationBranch, newMutationRetry, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
@@ -87,26 +370,28 @@ var CreateOrUpdateContactOperation = class {
87
370
  }
88
371
  let body;
89
372
  try {
90
- body = Buffer.from(JSON.stringify({ email: input.email, ...input.attributes && Object.keys(input.attributes).length ? { attributes: input.attributes } : {}, updateEnabled: true }));
373
+ body = encodeBrevoPayload({ email: input.email, ...input.attributes && Object.keys(input.attributes).length ? { attributes: input.attributes } : {}, updateEnabled: true });
91
374
  } catch {
92
375
  return newMutationBranch("defect", emptyWrite, {}, brevoFailure(operation, "VALIDATION", "contact payload is invalid or too large"));
93
376
  }
94
377
  if (body.byteLength > 1 << 20) return newMutationBranch("defect", emptyWrite, {}, brevoFailure(operation, "VALIDATION", "contact payload is invalid or too large"));
95
378
  const exchange = await this.client.exchange(call, operation, "POST", "/contacts", body);
96
379
  if ("failure" in exchange) {
97
- if (exchange.classification === "retry") return newMutationRetry(exchange.failure);
98
- return newMutationBranch(exchange.classification === "invalidResponse" ? "invalidResponse" : "defect", emptyWrite, {}, exchange.failure);
380
+ if (exchange.classification === "retry" || exchange.classification === "invalidResponse") return newMutationRetry(exchange.failure);
381
+ return newMutationBranch("defect", emptyWrite, {}, exchange.failure);
99
382
  }
100
383
  const { response } = exchange;
101
384
  if (isRetryableStatus(response.status)) return newMutationRetry(brevoFailure(operation, "AVAILABILITY", "Brevo contact request is temporarily unavailable"), this.client.retryAfter(response));
385
+ if (response.status !== 201 && response.status !== 204 && !isDefiniteBrevoRefusal(response))
386
+ return newMutationRetry(brevoFailure(operation, "AVAILABILITY", `Brevo answered the contact request with HTTP ${response.status}`));
102
387
  if (response.status !== 201 && response.status !== 204) return newMutationBranch("providerRejected", emptyWrite, {}, brevoFailure(operation, rejectionFailureKind(response.status), `Brevo rejected contact request with HTTP ${response.status}`));
103
388
  if (response.status === 204) return newMutationBranch("saved", { email: input.email, created: false });
104
389
  try {
105
- const decoded = JSON.parse(Buffer.from(response.body).toString("utf8"));
106
- if (!decoded || typeof decoded !== "object" || !("id" in decoded) || typeof decoded.id !== "number" || !Number.isSafeInteger(decoded.id) || decoded.id <= 0) throw new TypeError("invalid ID");
107
- return newMutationBranch("saved", { id: decoded.id, email: input.email, created: true });
390
+ const decoded = parseJSONNumberTokens(Buffer.from(response.body).toString("utf8"));
391
+ if (!decoded || typeof decoded !== "object" || !("id" in decoded)) throw new TypeError("invalid ID");
392
+ return newMutationBranch("saved", { id: readPositiveID(decoded.id), email: input.email, created: true });
108
393
  } catch {
109
- return newMutationBranch("invalidResponse", emptyWrite, {}, brevoFailure(operation, "PROTOCOL", "Brevo returned an invalid contact ID"));
394
+ return newMutationRetry(brevoFailure(operation, "PROTOCOL", "Brevo returned an invalid contact ID"));
110
395
  }
111
396
  }
112
397
  };
@@ -134,9 +419,9 @@ var GetContactOperation = class {
134
419
  if (response.status === 404) return newQueryBranch("notFound", emptyContact, {}, brevoFailure(operation, "NOT_FOUND", "Brevo contact was not found"));
135
420
  if (response.status !== 200) return newQueryBranch("providerRejected", emptyContact, {}, brevoFailure(operation, rejectionFailureKind(response.status), `Brevo rejected contact lookup with HTTP ${response.status}`));
136
421
  try {
137
- const decoded = JSON.parse(Buffer.from(response.body).toString("utf8"));
138
- if (!decoded || typeof decoded !== "object" || !("id" in decoded) || typeof decoded.id !== "number" || !Number.isSafeInteger(decoded.id) || decoded.id <= 0 || !("email" in decoded) || typeof decoded.email !== "string" || !isPlainEmail(decoded.email)) throw new TypeError("invalid contact");
139
- return newQueryBranch("found", { id: decoded.id, email: decoded.email });
422
+ const decoded = parseJSONNumberTokens(Buffer.from(response.body).toString("utf8"));
423
+ if (!decoded || typeof decoded !== "object" || !("id" in decoded) || !("email" in decoded) || typeof decoded.email !== "string" || !isPlainEmail(decoded.email)) throw new TypeError("invalid contact");
424
+ return newQueryBranch("found", { id: readPositiveID(decoded.id), email: decoded.email });
140
425
  } catch {
141
426
  return newQueryBranch("invalidResponse", emptyContact, {}, brevoFailure(operation, "PROTOCOL", "Brevo returned an invalid contact"));
142
427
  }
@@ -145,6 +430,474 @@ var GetContactOperation = class {
145
430
  function escapeContactEmailPath(email) {
146
431
  return encodeURIComponent(email).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(24|26|2B|3A|3D|40)/gi, (encoded) => String.fromCharCode(Number.parseInt(encoded.slice(1), 16)));
147
432
  }
433
+ function readPositiveID(value) {
434
+ const id = decodeSignedInteger(value);
435
+ if (BigInt(typeof id === "number" ? id : id.rawJSON) <= 0n) throw new TypeError("invalid contact ID");
436
+ return id;
437
+ }
438
+
439
+ // src/management.ts
440
+ var attributeCategories = ["normal", "transactional", "category", "calculated", "global"];
441
+ var emptyContactWrite = { email: "", created: false };
442
+ var emptyAttribute = { category: "", name: "" };
443
+ var emptySender = { id: 0 };
444
+ var emptyEmail = { messageId: "" };
445
+ var BrevoQuery = class {
446
+ /** Bind the authenticated Brevo client. */
447
+ constructor(client) {
448
+ this.client = client;
449
+ }
450
+ client;
451
+ /** Return the generated operation contract. */
452
+ definition() {
453
+ return this.contract;
454
+ }
455
+ };
456
+ var BrevoMutation = class {
457
+ /** Bind the authenticated Brevo client. */
458
+ constructor(client) {
459
+ this.client = client;
460
+ }
461
+ client;
462
+ /** Return the generated operation contract. */
463
+ definition() {
464
+ return this.contract;
465
+ }
466
+ /** Return the stable Call ID for one logical mutation. */
467
+ idempotencyKey(callID) {
468
+ return callID;
469
+ }
470
+ };
471
+ var CreateContactOperation = class extends BrevoMutation {
472
+ contract = CreateContactDefinition;
473
+ /** Run the operation through the authenticated client. */
474
+ async invoke(call, input) {
475
+ const attributes = input.attributes ?? {};
476
+ if (!isPlainEmail(input.email) || !uppercaseAttributes(attributes)) return defect(call, emptyContactWrite);
477
+ const document = {
478
+ email: input.email,
479
+ updateEnabled: false,
480
+ ...Object.keys(attributes).length ? { attributes } : {}
481
+ };
482
+ return limitedCreate(this.client, call, this.contract, "/contacts", document, emptyContactWrite, "created", (response) => ({
483
+ id: positiveID(createdObject(response).id),
484
+ email: input.email,
485
+ created: true
486
+ }));
487
+ }
488
+ };
489
+ var ListContactsOperation = class extends BrevoQuery {
490
+ contract = ListContactsDefinition;
491
+ /** Run the operation through the authenticated client. */
492
+ invoke(call, input) {
493
+ let path;
494
+ try {
495
+ const limit = integer(input.limit), offset = integer(input.offset);
496
+ if (typeof limit === "number" && limit >= 0 && limit <= 1e3 && signedBigInt(offset) >= 0n)
497
+ path = "/contacts?" + new URLSearchParams({ limit: String(limit || 50), offset: String(signedBigInt(offset)) });
498
+ } catch {
499
+ return read(this.client, call, void 0, { contacts: [], count: 0 }, contactList);
500
+ }
501
+ return read(this.client, call, path, { contacts: [], count: 0 }, contactList);
502
+ }
503
+ };
504
+ var UpdateContactOperation = class extends BrevoMutation {
505
+ contract = UpdateContactDefinition;
506
+ /** Run the operation through the authenticated client. */
507
+ async invoke(call, input) {
508
+ const empty = { email: "" };
509
+ if (!isPlainEmail(input.email) || !input.attributes || !Object.keys(input.attributes).length || !uppercaseAttributes(input.attributes)) return defect(call, empty);
510
+ return noContent(
511
+ this.client,
512
+ call,
513
+ "PUT",
514
+ "/contacts/" + escapeContactEmailPath(input.email),
515
+ { attributes: input.attributes },
516
+ { email: input.email },
517
+ empty,
518
+ "updated"
519
+ );
520
+ }
521
+ };
522
+ var DeleteContactOperation = class extends BrevoMutation {
523
+ contract = DeleteContactDefinition;
524
+ /** Run the operation through the authenticated client. */
525
+ async invoke(call, input) {
526
+ const empty = { email: "" };
527
+ if (!isPlainEmail(input.email)) return defect(call, empty);
528
+ return noContent(
529
+ this.client,
530
+ call,
531
+ "DELETE",
532
+ "/contacts/" + escapeContactEmailPath(input.email),
533
+ void 0,
534
+ { email: input.email },
535
+ empty,
536
+ "deleted"
537
+ );
538
+ }
539
+ };
540
+ var ListAttributesOperation = class extends BrevoQuery {
541
+ contract = ListAttributesDefinition;
542
+ invoke(call) {
543
+ return read(this.client, call, "/contacts/attributes", { attributes: [] }, attributeList);
544
+ }
545
+ };
546
+ var CreateAttributeOperation = class extends BrevoMutation {
547
+ contract = CreateAttributeDefinition;
548
+ /** Run the operation through the authenticated client. */
549
+ async invoke(call, input) {
550
+ const options = input.options ?? [], enumeration = input.enumeration ?? [], value = input.value ?? "", type = input.type ?? "";
551
+ if (!validAttributeName(input.name) || !validAttributeInput(input.category, options, enumeration, value, type))
552
+ return defect(call, emptyAttribute);
553
+ return limitedCreate(
554
+ this.client,
555
+ call,
556
+ this.contract,
557
+ `/contacts/attributes/${input.category}/${input.name}`,
558
+ attributeDocument(options, enumeration, value, type),
559
+ emptyAttribute,
560
+ "created",
561
+ () => ({ category: input.category, name: input.name })
562
+ );
563
+ }
564
+ };
565
+ var UpdateAttributeOperation = class extends BrevoMutation {
566
+ contract = UpdateAttributeDefinition;
567
+ /** Run the operation through the authenticated client. */
568
+ async invoke(call, input) {
569
+ const options = input.options ?? [], enumeration = input.enumeration ?? [], value = input.value ?? "";
570
+ if (!validAttributeName(input.name) || !validAttributeInput(input.category, options, enumeration, value))
571
+ return defect(call, emptyAttribute);
572
+ return noContent(
573
+ this.client,
574
+ call,
575
+ "PUT",
576
+ `/contacts/attributes/${input.category}/${input.name}`,
577
+ attributeDocument(options, enumeration, value),
578
+ { category: input.category, name: input.name },
579
+ emptyAttribute,
580
+ "updated"
581
+ );
582
+ }
583
+ };
584
+ var DeleteAttributeOperation = class extends BrevoMutation {
585
+ contract = DeleteAttributeDefinition;
586
+ /** Run the operation through the authenticated client. */
587
+ async invoke(call, input) {
588
+ if (!attributeCategories.includes(input.category) || !validAttributeName(input.name))
589
+ return defect(call, emptyAttribute);
590
+ return noContent(
591
+ this.client,
592
+ call,
593
+ "DELETE",
594
+ `/contacts/attributes/${input.category}/${input.name}`,
595
+ void 0,
596
+ { category: input.category, name: input.name },
597
+ emptyAttribute,
598
+ "deleted"
599
+ );
600
+ }
601
+ };
602
+ var ListSendersOperation = class extends BrevoQuery {
603
+ contract = ListSendersDefinition;
604
+ invoke(call) {
605
+ return read(this.client, call, "/senders", { senders: [] }, senderList);
606
+ }
607
+ };
608
+ var CreateSenderOperation = class extends BrevoMutation {
609
+ contract = CreateSenderDefinition;
610
+ /** Run the operation through the authenticated client. */
611
+ async invoke(call, input) {
612
+ if (!isPlainEmail(input.email) || !input.name.trim()) return defect(call, emptySender);
613
+ return limitedCreate(
614
+ this.client,
615
+ call,
616
+ this.contract,
617
+ "/senders",
618
+ { email: input.email, name: input.name },
619
+ emptySender,
620
+ "created",
621
+ (response) => ({ id: positiveID(createdObject(response).id) })
622
+ );
623
+ }
624
+ };
625
+ var UpdateSenderOperation = class extends BrevoMutation {
626
+ contract = UpdateSenderDefinition;
627
+ /** Run the operation through the authenticated client. */
628
+ async invoke(call, input) {
629
+ let id;
630
+ try {
631
+ id = positiveID(input.id);
632
+ } catch {
633
+ return defect(call, emptySender);
634
+ }
635
+ if (!input.name.trim()) return defect(call, emptySender);
636
+ return noContent(this.client, call, "PUT", `/senders/${signedBigInt(id)}`, { name: input.name }, { id }, emptySender, "updated");
637
+ }
638
+ };
639
+ var DeleteSenderOperation = class extends BrevoMutation {
640
+ contract = DeleteSenderDefinition;
641
+ /** Run the operation through the authenticated client. */
642
+ async invoke(call, input) {
643
+ let id;
644
+ try {
645
+ id = positiveID(input.id);
646
+ } catch {
647
+ return defect(call, emptySender);
648
+ }
649
+ return noContent(this.client, call, "DELETE", `/senders/${signedBigInt(id)}`, void 0, { id }, emptySender, "deleted");
650
+ }
651
+ };
652
+ var SendEmailOperation = class extends BrevoMutation {
653
+ contract = SendEmailDefinition;
654
+ /** Run the operation through the authenticated client. */
655
+ async invoke(call, input) {
656
+ if (!isPlainEmail(input.senderEmail) || !isPlainEmail(input.toEmail) || !input.senderName.trim() || !input.subject.trim() || !(input.textContent || input.htmlContent)) return defect(call, emptyEmail);
657
+ const document = {
658
+ sender: { email: input.senderEmail, name: input.senderName },
659
+ to: [{ email: input.toEmail }],
660
+ subject: input.subject,
661
+ ...input.textContent ? { textContent: input.textContent } : {},
662
+ ...input.htmlContent ? { htmlContent: input.htmlContent } : {}
663
+ };
664
+ return limitedCreate(this.client, call, this.contract, "/smtp/email", document, emptyEmail, "sent", sentEmail);
665
+ }
666
+ };
667
+ var SendTemplateEmailOperation = class extends BrevoMutation {
668
+ contract = SendTemplateEmailDefinition;
669
+ /** Run the operation through the authenticated client. */
670
+ async invoke(call, input) {
671
+ let templateId;
672
+ try {
673
+ templateId = positiveID(input.templateId);
674
+ } catch {
675
+ return defect(call, emptyEmail);
676
+ }
677
+ const params = input.params ?? {};
678
+ if (!isPlainEmail(input.toEmail) || Object.keys(params).some((name) => !name.trim())) return defect(call, emptyEmail);
679
+ const document = { templateId, to: [{ email: input.toEmail }], ...Object.keys(params).length ? { params } : {} };
680
+ return limitedCreate(this.client, call, this.contract, "/smtp/email", document, emptyEmail, "sent", sentEmail);
681
+ }
682
+ };
683
+ function object(value) {
684
+ const nativeJSON = JSON;
685
+ if (typeof value !== "object" || value === null || Array.isArray(value) || nativeJSON.isRawJSON(value))
686
+ throw new TypeError("Brevo did not return an object");
687
+ return value;
688
+ }
689
+ function items(value, field) {
690
+ const list = object(value)[field];
691
+ if (!Array.isArray(list)) throw new TypeError("Brevo did not return the expected list");
692
+ return list;
693
+ }
694
+ function text(value) {
695
+ if (value == null) return "";
696
+ if (typeof value !== "string") throw new TypeError("Brevo returned invalid text");
697
+ return value;
698
+ }
699
+ function requiredText(value) {
700
+ const result = text(value);
701
+ if (!result) throw new TypeError("Brevo returned missing text");
702
+ return result;
703
+ }
704
+ function integer(value) {
705
+ return decodeSignedInteger(value ?? 0);
706
+ }
707
+ function signedBigInt(value) {
708
+ return BigInt(typeof value === "number" ? value : value.rawJSON);
709
+ }
710
+ function positiveID(value) {
711
+ const result = integer(value);
712
+ if (signedBigInt(result) <= 0n) throw new TypeError("Brevo did not return a positive ID");
713
+ return result;
714
+ }
715
+ function contactList(value) {
716
+ const count = integer(object(value).count);
717
+ if (signedBigInt(count) < 0n) throw new TypeError("Brevo returned an invalid count");
718
+ const contacts = items(value, "contacts").map((item) => {
719
+ const record = object(item), email = text(record.email), id = positiveID(record.id);
720
+ if (email && !isPlainEmail(email)) throw new TypeError("Brevo returned an invalid contact email");
721
+ return email ? { id, email } : { id };
722
+ });
723
+ return { contacts, count };
724
+ }
725
+ function attributeList(value) {
726
+ return { attributes: items(value, "attributes").map((item) => {
727
+ const record = object(item);
728
+ return { name: requiredText(record.name), category: requiredText(record.category), type: requiredText(record.type) };
729
+ }) };
730
+ }
731
+ function senderList(value) {
732
+ return { senders: items(value, "senders").map((item) => {
733
+ const record = object(item), email = text(record.email);
734
+ if (!isPlainEmail(email) || record.active != null && typeof record.active !== "boolean")
735
+ throw new TypeError("Brevo returned invalid sender data");
736
+ return { id: positiveID(record.id), name: requiredText(record.name), email, active: record.active === true };
737
+ }) };
738
+ }
739
+ function createdObject(response) {
740
+ if (response.bodyError) throw new TypeError("Brevo response body could not be read");
741
+ return object(parseJSONNumberTokens(Buffer.from(response.body).toString("utf8")));
742
+ }
743
+ function sentEmail(response) {
744
+ return { messageId: requiredText(createdObject(response).messageId) };
745
+ }
746
+ function uppercaseAttributes(attributes) {
747
+ return Object.keys(attributes).every((name) => name && name.toUpperCase() === name);
748
+ }
749
+ function validAttributeName(name) {
750
+ return /^[A-Z0-9_]{1,100}(?![\s\S])/.test(name);
751
+ }
752
+ function nonblankOption(value) {
753
+ return Boolean(value.trim()) && new TextEncoder().encode(value).length <= 200;
754
+ }
755
+ function validAttributeInput(category, options, enumeration, value, type) {
756
+ if (category === "normal") {
757
+ if (enumeration.length || value || !options.every(nonblankOption)) return false;
758
+ return type === void 0 ? options.length > 0 : Boolean(type) && Boolean(options.length) === (type === "multiple-choice");
759
+ }
760
+ if (category === "category")
761
+ return (type === void 0 || type === "category") && !options.length && !value && enumeration.length > 0 && enumeration.every((item) => nonblankOption(item.label));
762
+ if (category === "calculated" || category === "global")
763
+ return !type && Boolean(value.trim()) && !options.length && !enumeration.length;
764
+ return category === "transactional" && Boolean(type) && !value && !options.length && !enumeration.length;
765
+ }
766
+ function attributeDocument(options, enumeration, value, type = "") {
767
+ return {
768
+ ...options.length ? { multiCategoryOptions: options } : {},
769
+ ...enumeration.length ? { enumeration } : {},
770
+ ...value ? { value } : {},
771
+ ...type ? { type } : {}
772
+ };
773
+ }
774
+ function encodeBrevoPayload(value) {
775
+ const text2 = JSON.stringify(value).replace(
776
+ /[<>&\u2028\u2029]/gu,
777
+ (character) => "\\u" + character.charCodeAt(0).toString(16).padStart(4, "0")
778
+ );
779
+ return Buffer.from(text2);
780
+ }
781
+ function isDefiniteBrevoRefusal(response) {
782
+ if (response.bodyError || ![400, 401, 403, 404, 411, 413, 414, 415, 422].includes(response.status)) return false;
783
+ const absent = (value) => value == null || typeof value === "object" && Object.keys(value).length === 0;
784
+ try {
785
+ const body = object(JSON.parse(Buffer.from(response.body).toString("utf8")));
786
+ return body.success !== true && ["data", "result", "results"].every((field) => absent(body[field])) && ["code", "message", "error", "errors"].some((field) => body[field] !== "" && !absent(body[field]));
787
+ } catch {
788
+ return false;
789
+ }
790
+ }
791
+ function mutationBranch(call, branch, output, kind, message) {
792
+ return newMutationBranch2(branch, output, {}, brevoFailure(call.operation.operationId, kind, message));
793
+ }
794
+ function defect(call, output) {
795
+ return mutationBranch(call, "defect", output, "VALIDATION", "Brevo input is invalid or too large");
796
+ }
797
+ function retryKind(status) {
798
+ return status === 429 ? "RATE_LIMIT" : "AVAILABILITY";
799
+ }
800
+ async function read(client, call, path, empty, parse) {
801
+ const operation = call.operation.operationId;
802
+ const terminal = (branch, kind, message) => newQueryBranch2(branch, empty, {}, brevoFailure(operation, kind, message));
803
+ if (path === void 0) return terminal("defect", "VALIDATION", "Brevo input is invalid");
804
+ const request = await client.prepare(call, operation, "GET", path);
805
+ if ("failure" in request) return newQueryBranch2("defect", empty, {}, request.failure);
806
+ let result;
807
+ try {
808
+ result = await client.sendPrepared(request);
809
+ } catch {
810
+ return newQueryRetry2(brevoFailure(operation, "TRANSPORT", "Brevo response is unavailable"), 0);
811
+ }
812
+ if (isRetryableStatus(result.status))
813
+ return newQueryRetry2(brevoFailure(operation, retryKind(result.status), "Brevo asked to retry the read"), client.retryAfter(result));
814
+ if (result.status !== 200) return terminal("providerRejected", rejectionFailureKind(result.status), "Brevo rejected the read");
815
+ if (result.bodyError === "tooLarge") return terminal("invalidResponse", "RESPONSE_TOO_LARGE", "Brevo response exceeded the limit");
816
+ if (result.bodyError) return newQueryRetry2(brevoFailure(operation, "TRANSPORT", "Brevo response was interrupted"), 0);
817
+ try {
818
+ return newQueryBranch2("listed", parse(parseJSONNumberTokens(Buffer.from(result.body).toString("utf8"))));
819
+ } catch {
820
+ return terminal("invalidResponse", "PROTOCOL", "Brevo returned invalid JSON");
821
+ }
822
+ }
823
+ async function noContent(client, call, method, path, document, resultValue, empty, branch) {
824
+ const operation = call.operation.operationId;
825
+ const retry = (kind, message, delay = 0) => newMutationRetry2(brevoFailure(operation, kind, message), delay);
826
+ const payload = document === void 0 ? void 0 : encodeBrevoPayload(document);
827
+ if (payload && payload.byteLength > 1 << 20) return defect(call, empty);
828
+ const request = await client.prepare(call, operation, method, path, payload);
829
+ const repeated = call.context.attempt > 1;
830
+ if ("failure" in request) {
831
+ if (repeated) return retry("TRANSPORT", "An earlier Brevo write remains unconfirmed");
832
+ return newMutationBranch2("defect", empty, {}, request.failure);
833
+ }
834
+ let result;
835
+ try {
836
+ result = await client.sendPrepared(request);
837
+ } catch {
838
+ return retry("TRANSPORT", "Brevo response is unavailable");
839
+ }
840
+ if (isRetryableStatus(result.status)) return retry(retryKind(result.status), "Brevo asked to retry the write", client.retryAfter(result));
841
+ if (result.status === 204) {
842
+ if (result.bodyError || result.body.byteLength) return retry("PROTOCOL", "Brevo acknowledgment is invalid");
843
+ return newMutationBranch2(branch, resultValue);
844
+ }
845
+ if (repeated || !isDefiniteBrevoRefusal(result)) return retry("TRANSPORT", "Brevo write outcome is unknown");
846
+ if (result.status === 404) return mutationBranch(call, "notFound", empty, "NOT_FOUND", "Brevo did not find the resource");
847
+ return mutationBranch(call, "providerRejected", empty, rejectionFailureKind(result.status), "Brevo rejected the write");
848
+ }
849
+ async function limitedCreate(client, call, definition, path, document, empty, branch, parse) {
850
+ const operation = call.operation.operationId;
851
+ const payload = encodeBrevoPayload(document);
852
+ if (payload.byteLength > 1 << 20) return defect(call, empty);
853
+ const retry = (kind, delay = 0) => newMutationRetry2(brevoFailure(operation, kind, "Brevo write may be retried"), delay);
854
+ const uncertain = (kind) => newMutationUncertain(empty, brevoFailure(operation, kind, "Brevo write could not be confirmed"));
855
+ const maxSends = call.maxSendsOverride ?? definitionMaxSends(definition);
856
+ let fence;
857
+ try {
858
+ fence = newFence(call, definition.stepDefaults.executeMethodTimeoutMs, { maxSends });
859
+ } catch {
860
+ return mutationBranch(call, "defect", empty, "LOCAL_DEFECT", "Brevo dispatch fence is invalid");
861
+ }
862
+ const decision = await fence.decide();
863
+ if (decision.kind === "failClosed") return retry("TRANSPORT");
864
+ if (decision.kind === "readBackRequired") return uncertain("TRANSPORT");
865
+ const request = await client.prepare(call, operation, "POST", path, payload);
866
+ if ("failure" in request) return newMutationBranch2("defect", empty, {}, request.failure);
867
+ const priorSends = decision.priorSendUpperBound ?? 0;
868
+ const atCap = priorSends + 1 >= maxSends;
869
+ let result;
870
+ try {
871
+ result = await fence.dispatch((signal) => client.sendPrepared(request, signal));
872
+ } catch (error) {
873
+ if (error instanceof CheckpointError || error instanceof DispatchNotAllowedError || error instanceof InsufficientTimeError)
874
+ return retry("AVAILABILITY");
875
+ return atCap ? uncertain("TRANSPORT") : retry("TRANSPORT");
876
+ }
877
+ if (result.status === 429 || result.status === 503) {
878
+ try {
879
+ await fence.recordCanResend();
880
+ } catch {
881
+ return retry("AVAILABILITY");
882
+ }
883
+ return retry("RATE_LIMIT", client.retryAfter(result));
884
+ }
885
+ if (isRetryableStatus(result.status)) return atCap ? uncertain("TRANSPORT") : retry("TRANSPORT");
886
+ if (result.status !== 201) {
887
+ if (priorSends || !isDefiniteBrevoRefusal(result)) return retry("TRANSPORT");
888
+ try {
889
+ await fence.recordCanResend();
890
+ } catch {
891
+ return retry("TRANSPORT");
892
+ }
893
+ return mutationBranch(call, "providerRejected", empty, rejectionFailureKind(result.status), "Brevo rejected the write");
894
+ }
895
+ try {
896
+ return newMutationBranch2(branch, parse(result));
897
+ } catch {
898
+ return atCap ? uncertain("PROTOCOL") : retry("PROTOCOL");
899
+ }
900
+ }
148
901
 
149
902
  // src/client.ts
150
903
  var publicEndpoint = "https://api.brevo.com/v3";
@@ -177,45 +930,125 @@ var BrevoClient = class {
177
930
  getContact() {
178
931
  return new GetContactOperation(this);
179
932
  }
933
+ /** Create a contact by email without updating an existing contact. */
934
+ createContact() {
935
+ return new CreateContactOperation(this);
936
+ }
937
+ /** List one page of contact IDs and emails. */
938
+ listContacts() {
939
+ return new ListContactsOperation(this);
940
+ }
941
+ /** Set absolute attributes on a contact identified by email. */
942
+ updateContact() {
943
+ return new UpdateContactOperation(this);
944
+ }
945
+ /** Delete a contact identified by email. */
946
+ deleteContact() {
947
+ return new DeleteContactOperation(this);
948
+ }
949
+ /** List contact attribute names, categories, and types. */
950
+ listAttributes() {
951
+ return new ListAttributesOperation(this);
952
+ }
953
+ /** Create a contact attribute with its type, options, or formula. */
954
+ createAttribute() {
955
+ return new CreateAttributeOperation(this);
956
+ }
957
+ /** Replace a contact attribute's choices or formula. */
958
+ updateAttribute() {
959
+ return new UpdateAttributeOperation(this);
960
+ }
961
+ /** Delete a contact attribute by category and name. */
962
+ deleteAttribute() {
963
+ return new DeleteAttributeOperation(this);
964
+ }
965
+ /** List email sender IDs, names, addresses, and active status. */
966
+ listSenders() {
967
+ return new ListSendersOperation(this);
968
+ }
969
+ /** Create an email sender. Brevo sends an address verification message. */
970
+ createSender() {
971
+ return new CreateSenderOperation(this);
972
+ }
973
+ /** Set an existing sender's display name. */
974
+ updateSender() {
975
+ return new UpdateSenderOperation(this);
976
+ }
977
+ /** Delete an email sender by numeric ID. */
978
+ deleteSender() {
979
+ return new DeleteSenderOperation(this);
980
+ }
981
+ /** Send one transactional email with inline text or HTML content. */
982
+ sendEmail() {
983
+ return new SendEmailOperation(this);
984
+ }
985
+ /** Send one transactional email from a configured Brevo template. */
986
+ sendTemplateEmail() {
987
+ return new SendTemplateEmailOperation(this);
988
+ }
180
989
  /** Send one authenticated request and classify transport failures. */
181
990
  async exchange(call, operation, method, path, body) {
182
- let apiKey;
991
+ const request = await this.prepare(call, operation, method, path, body);
992
+ if ("failure" in request) return request;
993
+ let response;
183
994
  try {
184
- const credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
185
- if (!(credentials.apiKey instanceof SecretString)) throw new TypeError("missing key");
186
- apiKey = credentials.apiKey.reveal();
187
- if (!isHeaderSafeCredential(apiKey)) throw new TypeError("invalid key");
995
+ response = await this.sendPrepared(request);
188
996
  } catch {
189
- return { failure: brevoFailure(operation, "AUTHENTICATION", "Brevo connection credentials are unavailable or invalid"), classification: "defect", retryAfterMs: 0 };
997
+ return { failure: brevoFailure(operation, "TRANSPORT", "Brevo contact response is unavailable"), classification: "retry", retryAfterMs: 0 };
190
998
  }
999
+ if ((response.status === 200 || response.status === 201) && response.bodyError === "tooLarge")
1000
+ return { failure: brevoFailure(operation, "RESPONSE_TOO_LARGE", "Brevo contact response exceeded the limit"), classification: "invalidResponse", retryAfterMs: 0 };
1001
+ if ((response.status === 200 || response.status === 201) && response.bodyError === "interrupted")
1002
+ return { failure: brevoFailure(operation, "AVAILABILITY", "Brevo contact response was interrupted"), classification: "retry", retryAfterMs: 0 };
1003
+ return { response };
1004
+ }
1005
+ /** Resolve credentials and build one request before dispatch. */
1006
+ async prepare(call, operation, method, path, body) {
1007
+ const unusable = { failure: brevoFailure(operation, "AUTHENTICATION", "Brevo connection credentials are unavailable or invalid"), classification: "defect", retryAfterMs: 0 };
1008
+ let credentials;
191
1009
  try {
192
- const response = await this.send({
193
- url: this.baseUrl + path,
194
- method,
195
- headers: { "api-key": apiKey, Accept: "application/json", "Content-Type": "application/json" },
196
- ...body ? { body } : {},
197
- maxResponseBytes: this.maxResponseBytes,
198
- timeoutMs: this.timeoutMs,
199
- addressPolicy: this.baseUrl === publicEndpoint ? "publicHTTPS" : "privateNetworkHTTP",
200
- signal: call.context.cancellationSignal
201
- });
202
- return { response };
1010
+ credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
203
1011
  } catch (error) {
204
- if (error instanceof BodyTooLargeError) {
205
- if (error.status !== void 0 && error.status !== 200 && error.status !== 201) {
206
- return { response: { status: error.status, headers: error.headers ?? {}, body: new Uint8Array() } };
207
- }
208
- return { failure: brevoFailure(operation, "RESPONSE_TOO_LARGE", "Brevo contact response exceeded the limit"), classification: "invalidResponse", retryAfterMs: 0 };
209
- }
210
- return { failure: brevoFailure(operation, "TRANSPORT", "Brevo contact response is unavailable"), classification: "retry", retryAfterMs: 0 };
1012
+ if (isTerminalCredentialError(error)) return unusable;
1013
+ return { failure: brevoFailure(operation, "AVAILABILITY", "Brevo connection credentials are temporarily unavailable"), classification: "retry", retryAfterMs: 0 };
1014
+ }
1015
+ if (!(credentials?.apiKey instanceof SecretString)) return unusable;
1016
+ const apiKey = credentials.apiKey.reveal();
1017
+ if (!isHeaderSafeCredential(apiKey)) return unusable;
1018
+ return {
1019
+ url: this.baseUrl + path,
1020
+ method,
1021
+ headers: { "api-key": apiKey, Accept: "application/json", "Content-Type": "application/json" },
1022
+ ...body ? { body } : {},
1023
+ maxResponseBytes: this.maxResponseBytes,
1024
+ timeoutMs: this.timeoutMs,
1025
+ addressPolicy: this.baseUrl === publicEndpoint ? "publicHTTPS" : "privateNetworkHTTP",
1026
+ signal: call.context.cancellationSignal
1027
+ };
1028
+ }
1029
+ /** Send one prepared request with the caller's deadline and preserve response status. */
1030
+ async sendPrepared(request, signal = request.signal) {
1031
+ try {
1032
+ const response = await this.send(signal === void 0 ? request : { ...request, signal });
1033
+ if (response.body.byteLength <= this.maxResponseBytes) return response;
1034
+ return { ...response, body: new Uint8Array(), bodyError: "tooLarge" };
1035
+ } catch (error) {
1036
+ if (error instanceof BodyTooLargeError && error.status !== void 0)
1037
+ return { status: error.status, headers: error.headers ?? {}, body: new Uint8Array(), bodyError: "tooLarge" };
1038
+ if ((error instanceof ProviderTransportError || error instanceof ProviderStalledError) && error.status !== void 0)
1039
+ return { status: error.status, headers: error.headers ?? {}, body: new Uint8Array(), bodyError: "interrupted" };
1040
+ throw error;
211
1041
  }
212
1042
  }
213
1043
  /** Parse a provider-directed retry delay. */
214
1044
  retryAfter(response) {
215
- const value = response.headers["retry-after"];
1045
+ const value = Object.entries(response.headers).find(([name]) => name.toLowerCase() === "retry-after")?.[1];
216
1046
  return parseRetryAfter(Array.isArray(value) ? value[0] ?? "" : value ?? "", this.now());
217
1047
  }
218
1048
  };
1049
+ function isTerminalCredentialError(error) {
1050
+ return isCredentialMaterialError(error) || error instanceof ReauthorizationRequiredError || error instanceof ObjectNotFoundError || error instanceof ConnectionNotSelectedError || error instanceof CredentialBrokerRejectedError || error instanceof z.ZodError;
1051
+ }
219
1052
  function brevoFailure(operation, kind, message) {
220
1053
  return { kind, provider: "brevo", operation, message };
221
1054
  }
@@ -237,7 +1070,7 @@ function newProjectConnection2(project, connectionName) {
237
1070
  return newProjectConnection(project, connectionName, (loadedProject, name) => {
238
1071
  const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "brevo" && entry.connectionName === name);
239
1072
  if (!selected) throw new TypeError("Brevo project connection is not configured");
240
- const fields = z.strictObject({ baseUrl: z.string().optional(), timeout: z.union([z.string(), z.number().int()]).optional(), maxResponseBytes: z.number().int().optional() }).parse(selected.configuration);
1073
+ const fields = z2.strictObject({ baseUrl: z2.string().optional(), timeout: z2.union([z2.string(), z2.number().int()]).optional(), maxResponseBytes: z2.number().int().optional() }).parse(selected.configuration);
241
1074
  const timeoutMs = typeof fields.timeout === "number" ? Math.ceil(fields.timeout / 1e6) : fields.timeout ? parseDurationMilliseconds(fields.timeout) : void 0;
242
1075
  const config = {
243
1076
  ...fields.baseUrl !== void 0 ? { baseUrl: fields.baseUrl } : {},
@@ -247,8 +1080,8 @@ function newProjectConnection2(project, connectionName) {
247
1080
  const credentials = {
248
1081
  async resolve(_call, signal) {
249
1082
  const privateFields = await loadedProject.resolveCredential("brevo", name, signal);
250
- if (typeof privateFields.api_key !== "string") throw new TypeError("Brevo API key is unavailable");
251
- return { apiKey: new SecretString2(privateFields.api_key) };
1083
+ const decoded = z2.object({ api_key: z2.string() }).parse(privateFields);
1084
+ return { apiKey: new SecretString2(decoded.api_key) };
252
1085
  }
253
1086
  };
254
1087
  return new BrevoClient(config, credentials);
@@ -268,12 +1101,37 @@ function parseDurationMilliseconds(value) {
268
1101
  return milliseconds;
269
1102
  }
270
1103
  export {
1104
+ AttributeChangeResultSchema,
1105
+ AttributeEnumerationValueSchema,
1106
+ AttributeIdentitySchema,
1107
+ AttributesListSchema,
271
1108
  BrevoClient,
272
1109
  ConfigSchema,
273
1110
  Connection,
274
1111
  ConnectorID,
1112
+ ContactChangeResultSchema,
1113
+ ContactIdentitySchema,
275
1114
  ContactSchema,
276
1115
  ContactWriteResultSchema,
1116
+ ContactsListSchema,
1117
+ CreateAttributeBranch,
1118
+ CreateAttributeBranchCreated,
1119
+ CreateAttributeBranchDefect,
1120
+ CreateAttributeBranchProviderRejected,
1121
+ CreateAttributeBranchUncertain,
1122
+ CreateAttributeDefinition,
1123
+ CreateAttributeInputSchema,
1124
+ CreateAttributeMetadata,
1125
+ CreateAttributeOperation,
1126
+ CreateContactBranch,
1127
+ CreateContactBranchCreated,
1128
+ CreateContactBranchDefect,
1129
+ CreateContactBranchProviderRejected,
1130
+ CreateContactBranchUncertain,
1131
+ CreateContactDefinition,
1132
+ CreateContactInputSchema,
1133
+ CreateContactMetadata,
1134
+ CreateContactOperation,
277
1135
  CreateOrUpdateContactBranch,
278
1136
  CreateOrUpdateContactBranchDefect,
279
1137
  CreateOrUpdateContactBranchInvalidResponse,
@@ -283,6 +1141,44 @@ export {
283
1141
  CreateOrUpdateContactInputSchema,
284
1142
  CreateOrUpdateContactMetadata,
285
1143
  CreateOrUpdateContactOperation,
1144
+ CreateSenderBranch,
1145
+ CreateSenderBranchCreated,
1146
+ CreateSenderBranchDefect,
1147
+ CreateSenderBranchProviderRejected,
1148
+ CreateSenderBranchUncertain,
1149
+ CreateSenderDefinition,
1150
+ CreateSenderInputSchema,
1151
+ CreateSenderMetadata,
1152
+ CreateSenderOperation,
1153
+ CredentialMaterialError,
1154
+ DeleteAttributeBranch,
1155
+ DeleteAttributeBranchDefect,
1156
+ DeleteAttributeBranchDeleted,
1157
+ DeleteAttributeBranchNotFound,
1158
+ DeleteAttributeBranchProviderRejected,
1159
+ DeleteAttributeDefinition,
1160
+ DeleteAttributeInputSchema,
1161
+ DeleteAttributeMetadata,
1162
+ DeleteAttributeOperation,
1163
+ DeleteContactBranch,
1164
+ DeleteContactBranchDefect,
1165
+ DeleteContactBranchDeleted,
1166
+ DeleteContactBranchNotFound,
1167
+ DeleteContactBranchProviderRejected,
1168
+ DeleteContactDefinition,
1169
+ DeleteContactInputSchema,
1170
+ DeleteContactMetadata,
1171
+ DeleteContactOperation,
1172
+ DeleteSenderBranch,
1173
+ DeleteSenderBranchDefect,
1174
+ DeleteSenderBranchDeleted,
1175
+ DeleteSenderBranchNotFound,
1176
+ DeleteSenderBranchProviderRejected,
1177
+ DeleteSenderDefinition,
1178
+ DeleteSenderInputSchema,
1179
+ DeleteSenderMetadata,
1180
+ DeleteSenderOperation,
1181
+ EmailSendResultSchema,
286
1182
  GetContactBranch,
287
1183
  GetContactBranchDefect,
288
1184
  GetContactBranchFound,
@@ -293,10 +1189,105 @@ export {
293
1189
  GetContactInputSchema,
294
1190
  GetContactMetadata,
295
1191
  GetContactOperation,
1192
+ ListAttributesBranch,
1193
+ ListAttributesBranchDefect,
1194
+ ListAttributesBranchInvalidResponse,
1195
+ ListAttributesBranchListed,
1196
+ ListAttributesBranchProviderRejected,
1197
+ ListAttributesDefinition,
1198
+ ListAttributesInputSchema,
1199
+ ListAttributesMetadata,
1200
+ ListAttributesOperation,
1201
+ ListContactsBranch,
1202
+ ListContactsBranchDefect,
1203
+ ListContactsBranchInvalidResponse,
1204
+ ListContactsBranchListed,
1205
+ ListContactsBranchProviderRejected,
1206
+ ListContactsDefinition,
1207
+ ListContactsInputSchema,
1208
+ ListContactsMetadata,
1209
+ ListContactsOperation,
1210
+ ListSendersBranch,
1211
+ ListSendersBranchDefect,
1212
+ ListSendersBranchInvalidResponse,
1213
+ ListSendersBranchListed,
1214
+ ListSendersBranchProviderRejected,
1215
+ ListSendersDefinition,
1216
+ ListSendersInputSchema,
1217
+ ListSendersMetadata,
1218
+ ListSendersOperation,
296
1219
  ProviderID,
1220
+ SendEmailBranch,
1221
+ SendEmailBranchDefect,
1222
+ SendEmailBranchProviderRejected,
1223
+ SendEmailBranchSent,
1224
+ SendEmailBranchUncertain,
1225
+ SendEmailDefinition,
1226
+ SendEmailInputSchema,
1227
+ SendEmailMetadata,
1228
+ SendEmailOperation,
1229
+ SendTemplateEmailBranch,
1230
+ SendTemplateEmailBranchDefect,
1231
+ SendTemplateEmailBranchProviderRejected,
1232
+ SendTemplateEmailBranchSent,
1233
+ SendTemplateEmailBranchUncertain,
1234
+ SendTemplateEmailDefinition,
1235
+ SendTemplateEmailInputSchema,
1236
+ SendTemplateEmailMetadata,
1237
+ SendTemplateEmailOperation,
1238
+ SenderChangeResultSchema,
1239
+ SenderIdentitySchema,
1240
+ SendersListSchema,
1241
+ UpdateAttributeBranch,
1242
+ UpdateAttributeBranchDefect,
1243
+ UpdateAttributeBranchNotFound,
1244
+ UpdateAttributeBranchProviderRejected,
1245
+ UpdateAttributeBranchUpdated,
1246
+ UpdateAttributeDefinition,
1247
+ UpdateAttributeInputSchema,
1248
+ UpdateAttributeMetadata,
1249
+ UpdateAttributeOperation,
1250
+ UpdateContactBranch,
1251
+ UpdateContactBranchDefect,
1252
+ UpdateContactBranchNotFound,
1253
+ UpdateContactBranchProviderRejected,
1254
+ UpdateContactBranchUpdated,
1255
+ UpdateContactDefinition,
1256
+ UpdateContactInputSchema,
1257
+ UpdateContactMetadata,
1258
+ UpdateContactOperation,
1259
+ UpdateSenderBranch,
1260
+ UpdateSenderBranchDefect,
1261
+ UpdateSenderBranchNotFound,
1262
+ UpdateSenderBranchProviderRejected,
1263
+ UpdateSenderBranchUpdated,
1264
+ UpdateSenderDefinition,
1265
+ UpdateSenderInputSchema,
1266
+ UpdateSenderMetadata,
1267
+ UpdateSenderOperation,
1268
+ decodeCredentials,
1269
+ decodeSignedInteger,
1270
+ exactIntegerJSONCodec,
1271
+ isCredentialMaterialError,
297
1272
  newConnection,
298
1273
  newConnectionWithOperations,
1274
+ newCreateAttributeStep,
1275
+ newCreateContactStep,
299
1276
  newCreateOrUpdateContactStep,
1277
+ newCreateSenderStep,
1278
+ newDeleteAttributeStep,
1279
+ newDeleteContactStep,
1280
+ newDeleteSenderStep,
300
1281
  newGetContactStep,
301
- newProjectConnection2 as newProjectConnection
1282
+ newListAttributesStep,
1283
+ newListContactsStep,
1284
+ newListSendersStep,
1285
+ newProjectConnection2 as newProjectConnection,
1286
+ newSendEmailStep,
1287
+ newSendTemplateEmailStep,
1288
+ newUpdateAttributeStep,
1289
+ newUpdateContactStep,
1290
+ newUpdateSenderStep,
1291
+ parseExactIntegerJSON,
1292
+ parseJSONNumberTokens
302
1293
  };