@drawbridge/drawbridge-utils 0.0.117 → 0.0.121

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.
@@ -0,0 +1,4350 @@
1
+ // lib/connections/contract.js
2
+ var HOOKS = Object.freeze({
3
+ // Proving and holding the credential.
4
+ auth: Object.freeze([
5
+ // Accept what the merchant supplied — a form submission or an OAuth
6
+ // callback — and store what is needed to call the vendor later.
7
+ "connect",
8
+ // Is the stored credential still good? Answered by the cheapest real call
9
+ // the vendor offers, never by inspecting what we stored: a key that was
10
+ // revoked at the vendor still looks perfect in our database.
11
+ "probe",
12
+ // Which permissions we asked for and no longer hold. Distinct from probe:
13
+ // the credential can be valid and the grant still be too narrow.
14
+ "scopes",
15
+ // Revoke at the vendor and drop what we hold.
16
+ "disconnect",
17
+ // MINT A TOKEN — from a consent code, or from a stored refresh token. Both
18
+ // are the same POST, so they are one hook.
19
+ //
20
+ // The default body is authToken() in oauth.js and most vendors point
21
+ // straight at it. It is a hook rather than a declared flag because the
22
+ // vendors that differ, differ in ways config cannot express: Klaviyo needs
23
+ // HTTP Basic where others want body fields, and Mailchimp cannot use the
24
+ // token it receives until a second call tells it which data centre the
25
+ // account is behind.
26
+ "token"
27
+ ]),
28
+ // What happens around connecting and disconnecting, beyond the credential.
29
+ lifecycle: Object.freeze([
30
+ // KEEP ACCESS WORKING. Rotate a credential before its window closes, prove
31
+ // it still works, and reconcile whatever the vendor has changed underneath
32
+ // — scopes, webhooks. Distinct from auth.probe, which only answers "is this
33
+ // still good": this one FIXES what it can and reports what it cannot.
34
+ "health",
35
+ // Post-connect setup: register the vendor's webhooks, create the system
36
+ // workflows that describe them.
37
+ "register",
38
+ // Re-pull vendor state we mirror, after a reconnect or on a schedule.
39
+ "rehydrate",
40
+ // Undo `register` — deregister webhooks, release anything reserved.
41
+ "cleanup"
42
+ ]),
43
+ // Receiving from the vendor.
44
+ //
45
+ // Split across TWO SERVICES, and the split is the point. `verify` and `event`
46
+ // and `receive` run in drawbridge-webhooks against the vendor's open
47
+ // connection, where the budget is whatever that vendor's timeout is —
48
+ // Shopify's is about five seconds, and missing it means they retry and the
49
+ // delivery is buffered twice. `process` runs in drawbridge-sync off the
50
+ // buffer, where it can take as long as it needs and retry without the vendor
51
+ // ever knowing.
52
+ //
53
+ // One hook spanning that seam would hide it, and the thing it hides is the
54
+ // one most likely to bite: slow work written on the receiving side turns
55
+ // into duplicate deliveries.
56
+ inbound: Object.freeze([
57
+ // Prove the request came from the vendor, AND return the payload it
58
+ // carries. One hook rather than two because for some vendors they are
59
+ // genuinely one operation: a JWT-bodied webhook (Kinde) cannot be decoded
60
+ // into anything trustworthy without verifying it first, and a decode that
61
+ // runs before the signature check is exactly the bug this shape prevents.
62
+ //
63
+ // So the raw bytes stop here. Everything downstream receives the payload
64
+ // this returned, which means nothing downstream can act on unverified
65
+ // data even by mistake.
66
+ //
67
+ // It is also where a request gets refused for any other reason — an event
68
+ // outside the allowlist, a connection in the wrong state. Anything that
69
+ // can reject belongs here, so the route holds no rules of its own.
70
+ "verify",
71
+ // Name the event, from wherever this vendor puts it. A header for
72
+ // Shopify, the route itself for Twilio, a claim in the payload for a
73
+ // JWT-bodied vendor.
74
+ "event",
75
+ // What to buffer and what to answer RIGHT NOW, while the vendor waits.
76
+ // Thin by obligation. Most vendors only shape a buffer doc here; one that
77
+ // must reply with content (Twilio answers HELP inline with TwiML, which
78
+ // carriers require) returns that too.
79
+ "receive",
80
+ // Do the work the event implies. Runs in drawbridge-sync, off the buffer.
81
+ //
82
+ // DECLARED here, IMPLEMENTED there — the same split as the step handlers,
83
+ // and for the same reason: this half needs controllers, queues and vendor
84
+ // SDKs, and putting those behind a published package makes every consumer
85
+ // carry them. The declaration is what proves the implementation exists.
86
+ "process"
87
+ ]),
88
+ // WHAT A WORKFLOW STEP DOES, as a verb like any other. Step handlers used to
89
+ // live in drawbridge-sync keyed by step type, which meant a vendor's logic sat
90
+ // in a repo the vendor file could not see — the split this whole exercise
91
+ // exists to close.
92
+ //
93
+ // A `steps` entry points at one of these; the step says when it runs and what
94
+ // it costs, the hook does the work.
95
+ contacts: Object.freeze([
96
+ // Forget a contact at the vendor. Distinct from suppression, which keeps the
97
+ // record and marks it unsubscribed: this is deletion, for account closure.
98
+ "remove",
99
+ // Push one contact into the audience the merchant chose, honouring
100
+ // suppression rather than omitting an opted-out person — omission lets them
101
+ // quietly reappear on the next sync.
102
+ "sync"
103
+ ]),
104
+ commerce: Object.freeze([
105
+ // Mint a discount code against this merchant's store, mapped to one lead.
106
+ "code",
107
+ // Create the buyer at the vendor, so an order can be attributed to them.
108
+ "customer",
109
+ // An order arrived at the vendor: attribute it, record it, update totals.
110
+ "order",
111
+ // Pull product data across on a vendor update.
112
+ "product"
113
+ ]),
114
+ // WHAT DRAWBRIDGE ITSELF DOES. These are not a third party's verbs — nobody
115
+ // connects an account to send email through Drawbridge — but they are steps a
116
+ // workflow runs, and a step points at a hook. So they live on a PRIVATE
117
+ // connection: one that contributes steps and never appears in the catalog.
118
+ //
119
+ // Without it the base steps stay the exception the shell has to know about,
120
+ // and "every step is a declaration pointing at a hook" stops being true the
121
+ // moment somebody looks at the six most common ones.
122
+ email: Object.freeze([
123
+ // To a lead. Suppression applies, and the send is billed.
124
+ "send",
125
+ // To organization members. Never suppressed — an entrant's opt-out must not
126
+ // silence an alert to staff — and never billed.
127
+ "notify",
128
+ // A batched summary to members.
129
+ "digest"
130
+ ]),
131
+ sms: Object.freeze(["send"]),
132
+ segment: Object.freeze(["sync"]),
133
+ // OUTBOUND DELIVERY to an address the merchant owns, rather than to a vendor.
134
+ // The Webhooks connection is the only thing here with no third party behind
135
+ // it, and the destination is per STEP rather than per connection.
136
+ webhook: Object.freeze(["send"]),
137
+ // Vendor data we READ — the things a merchant picks from. Named `resources`
138
+ // rather than `catalog` because it also holds audiences, and a catalog is a
139
+ // commerce word for something that is not only commerce. It matches the
140
+ // pickers that render it, too: InputResource and ListResource.
141
+ //
142
+ // The verbs are named for what every vendor has, not for what one calls it:
143
+ // Shopify says discounts, Stripe says coupons and promotion codes,
144
+ // BigCommerce says coupons and promotions.
145
+ //
146
+ // ONE SHAPE FOR ALL OF THEM — searchable and cursor-paged:
147
+ //
148
+ // ({ connection, cursor, limit, search, settings, token })
149
+ // -> { items : [ { id, title, ... } ], pageInfo : { endCursor, hasNextPage } }
150
+ //
151
+ // Lifted from what the Shopify product picker already does, rather than
152
+ // invented: that endpoint takes cursor/limit/search and returns items plus a
153
+ // pageInfo, and ListResource consumes exactly that. It was a good contract
154
+ // written once for one vendor; this makes it the contract.
155
+ //
156
+ // `title` is not arbitrary — ListResource searches `[ 'title' ]` by default,
157
+ // so normalising to { id, title } is what lets a picker work with no
158
+ // per-vendor configuration.
159
+ //
160
+ // HOW a vendor searches is its own business, which is the point of a hook.
161
+ // Shopify pushes the term into its GraphQL query, Klaviyo has a filter
162
+ // parameter, and Mailchimp's /lists has no name filter at all so its hook
163
+ // matches against what it fetched. The caller never learns which.
164
+ resources: Object.freeze([
165
+ // The named groups a contact can be synced INTO. Klaviyo calls them lists,
166
+ // Mailchimp calls them audiences; `audiences` is the industry-generic term
167
+ // and belongs to neither vendor's API. Read at form time, so a merchant
168
+ // picks from what actually exists in their account rather than pasting an
169
+ // id from another tab.
170
+ "audiences",
171
+ "products",
172
+ // Shopify folds price into the product variant; Stripe makes Price a
173
+ // first-class object beside Product. Declared so a vendor that separates
174
+ // them has somewhere to answer.
175
+ "prices",
176
+ "promotions"
177
+ ])
178
+ });
179
+ var HOOK_EFFECTS = Object.freeze(["enqueues", "events", "writes"]);
180
+ var WRITE_OPERATIONS = Object.freeze(["create", "update"]);
181
+ var HOOK_PROPS = Object.freeze([
182
+ "channel",
183
+ "clientId",
184
+ "clientSecret",
185
+ "connection",
186
+ "contact",
187
+ "context",
188
+ "cursor",
189
+ "declaration",
190
+ "doc",
191
+ "email",
192
+ "event",
193
+ "headers",
194
+ "id",
195
+ "lead",
196
+ "limit",
197
+ "manifest",
198
+ "payload",
199
+ "scope",
200
+ "search",
201
+ "secret",
202
+ "settings",
203
+ "sort",
204
+ "step",
205
+ "suppressed",
206
+ "token",
207
+ "tokens",
208
+ "workflow"
209
+ ]);
210
+ var HOOK_OPTIONS = Object.freeze([
211
+ "adminToken",
212
+ "canSend",
213
+ "chunkSize",
214
+ "dispatch",
215
+ "fetcher",
216
+ "logger",
217
+ "mintId",
218
+ "read",
219
+ "reconcileScopes",
220
+ "request",
221
+ "resolveContact",
222
+ "resolveSettings",
223
+ "rotateToken",
224
+ "shopify"
225
+ ]);
226
+ var STEPS = Object.freeze({
227
+ "commerce.code.issue": "Issue discount code",
228
+ "commerce.customer.insert": "Create customer",
229
+ "commerce.order.record": "Record order",
230
+ "commerce.product.sync": "Sync product",
231
+ // Not commerce at all — connection lifecycle, and they generalise to any
232
+ // vendor holding a rotating credential.
233
+ "connection.health.check": "Connection health check",
234
+ "connection.token.exchange": "Exchange token",
235
+ "connection.token.refresh": "Refresh token",
236
+ "contacts.sync": "Sync contact",
237
+ "email.digest": "Digest",
238
+ "email.notify": "Notification",
239
+ "email.send": "Send email",
240
+ "segment.sync": "Sync segment",
241
+ "sms.send": "Send SMS",
242
+ "webhook.send": "Send webhook"
243
+ });
244
+ var RETIRED = Object.freeze({
245
+ "step.shopify.customer.insert": "step.commerce.customer.insert",
246
+ "step.shopify.discount.update": "step.commerce.code.issue",
247
+ "step.shopify.health.check": "step.connection.health.check",
248
+ "step.shopify.order.record": "step.commerce.order.record",
249
+ "step.shopify.product.sync": "step.commerce.product.sync",
250
+ "step.shopify.token.exchange": "step.connection.token.exchange",
251
+ "step.shopify.token.refresh": "step.connection.token.refresh"
252
+ });
253
+ var STEP_TYPES = Object.freeze(Object.keys(STEPS).map((name) => "step." + name));
254
+ var STEP_LABELS = Object.freeze(Object.fromEntries(
255
+ Object.entries(STEPS).map(([name, label]) => ["step." + name, label])
256
+ ));
257
+ var HOOK_NAMES = Object.freeze(
258
+ Object.entries(HOOKS).flatMap(([domain, verbs]) => verbs.map((verb) => domain + "." + verb))
259
+ );
260
+ var OUTCOMES = Object.freeze({
261
+ answered: "answered",
262
+ disconnected: "disconnected",
263
+ failed: "failed",
264
+ // Declared supported, implemented in a consumer rather than in this package —
265
+ // sync owns the step handlers and lifecycle jobs. Different from unsupported,
266
+ // which means the vendor cannot do it at all.
267
+ unimplemented: "unimplemented",
268
+ unsupported: "unsupported"
269
+ });
270
+ var STATUSES = Object.freeze(["active", "disconnected", "error", "pending"]);
271
+ var AUTH_TYPES = Object.freeze(["generated", "install", "keys", "none", "oauth"]);
272
+ var GROUPS = Object.freeze(["commerce", "contacts", "developer", "messaging"]);
273
+ var OAUTH_FIELDS = Object.freeze(["client"]);
274
+ var OAUTH_URLS = Object.freeze(["authorize", "redirect", "token"]);
275
+ var INPUTS = Object.freeze([
276
+ "checkbox",
277
+ "email",
278
+ "number",
279
+ "password",
280
+ "select",
281
+ "text",
282
+ "textarea",
283
+ "url"
284
+ ]);
285
+
286
+ // lib/connections/oauth.js
287
+ import { createHash, randomBytes } from "crypto";
288
+ var credentials = ({ basic, clientId, clientSecret }) => basic ? {
289
+ body: {},
290
+ headers: { authorization: "Basic " + Buffer.from(clientId + ":" + clientSecret).toString("base64") }
291
+ } : {
292
+ body: { client_id: clientId, client_secret: clientSecret },
293
+ headers: {}
294
+ };
295
+ var authToken = async ({
296
+ basic,
297
+ clientId,
298
+ clientSecret,
299
+ code: code2,
300
+ descriptor,
301
+ fetcher = fetch,
302
+ redirect,
303
+ refreshToken,
304
+ verifier
305
+ } = {}) => {
306
+ var _a;
307
+ if (!clientId || !clientSecret) throw new Error("This deployment has no OAuth client configured, so no token can be minted");
308
+ if (!((_a = descriptor == null ? void 0 : descriptor.urls) == null ? void 0 : _a.token)) throw new Error("This connection declares no token url");
309
+ const renewing = !code2;
310
+ if (renewing && !refreshToken) throw new Error("Nothing has been consented to yet, so there is no refresh token to spend");
311
+ if (!renewing && descriptor.pkce && !verifier) throw new Error("This connection requires PKCE, so the code verifier is not optional");
312
+ const client = credentials({ basic, clientId, clientSecret });
313
+ const response = await fetcher(descriptor.urls.token, {
314
+ body: new URLSearchParams({
315
+ ...client.body,
316
+ ...renewing ? { grant_type: "refresh_token", refresh_token: refreshToken } : {
317
+ code: decodeURIComponent(String(code2 || "").trim()),
318
+ grant_type: "authorization_code",
319
+ redirect_uri: redirect,
320
+ ...descriptor.pkce && { code_verifier: verifier }
321
+ }
322
+ }),
323
+ headers: { "content-type": "application/x-www-form-urlencoded", ...client.headers },
324
+ method: "POST",
325
+ signal: AbortSignal.timeout(15e3)
326
+ });
327
+ const body = await response.json().catch(() => ({}));
328
+ if (!response.ok) {
329
+ throw new Error(
330
+ renewing ? "The vendor refused the refresh token (" + response.status + ") \u2014 reconnect the connection" : "The vendor refused the exchange (" + response.status + ")" + ((body == null ? void 0 : body.error) ? ": " + body.error : "")
331
+ );
332
+ }
333
+ if (!renewing && !body.access_token) throw new Error("The vendor returned no access token");
334
+ return {
335
+ accessToken: body.access_token,
336
+ expiresIn: body.expires_in || null,
337
+ // A REFRESH TOKEN IS NOT UNIVERSAL. Google returns one only with
338
+ // access_type=offline; Mailchimp's tokens do not expire and it returns none
339
+ // at all, so its absence cannot be an error here.
340
+ //
341
+ // On a RENEWAL the same null matters for the opposite reason: a vendor that
342
+ // rotates returns a new one, and dropping it silently invalidates the stored
343
+ // grant on the NEXT refresh — a failure a day late and nowhere near its
344
+ // cause. tokenSettings() keeps the existing one when this is null.
345
+ refreshToken: body.refresh_token || null,
346
+ scope: body.scope || null
347
+ };
348
+ };
349
+
350
+ // lib/connections/token.js
351
+ var SKEW_SECONDS = 120;
352
+ var isStale = (settings, now = Date.now()) => {
353
+ if (!(settings == null ? void 0 : settings.expiresAt)) return false;
354
+ return new Date(settings.expiresAt).getTime() - SKEW_SECONDS * 1e3 <= now;
355
+ };
356
+ var tokenSettings = ({ existing = {}, now = Date.now(), tokens }) => ({
357
+ accessToken: tokens.accessToken,
358
+ // A vendor that does not rotate its refresh token returns none on a refresh
359
+ // (Klaviyo). Keeping the existing one is what makes the NEXT refresh work —
360
+ // dropping it invalidates the grant one call later, nowhere near the cause.
361
+ ...(tokens.refreshToken || existing.refreshToken) && {
362
+ refreshToken: tokens.refreshToken || existing.refreshToken
363
+ },
364
+ // Absent when the vendor issues non-expiring tokens, and absent is meaningful
365
+ // — isStale reads it as "nothing to refresh toward".
366
+ ...tokens.expiresIn && {
367
+ expiresAt: new Date(now + tokens.expiresIn * 1e3).toISOString()
368
+ },
369
+ ...tokens.scope && { scope: tokens.scope }
370
+ });
371
+ var accessToken = async ({
372
+ clientId,
373
+ clientSecret,
374
+ fetcher,
375
+ force = false,
376
+ manifest,
377
+ now = Date.now(),
378
+ save,
379
+ settings
380
+ } = {}) => {
381
+ if (!(settings == null ? void 0 : settings.accessToken) && !(settings == null ? void 0 : settings.refreshToken)) {
382
+ throw new Error("This connection holds no credential, so there is no token to use");
383
+ }
384
+ if (!force && !isStale(settings, now)) return settings.accessToken;
385
+ if (!settings.refreshToken) {
386
+ throw new Error("This connection has expired and cannot be renewed automatically. Reconnect it.");
387
+ }
388
+ const minted = await manifest.hooks.auth.token({
389
+ clientId,
390
+ clientSecret,
391
+ descriptor: manifest.auth.oauth,
392
+ ...fetcher && { fetcher },
393
+ refreshToken: settings.refreshToken
394
+ });
395
+ const next = tokenSettings({ existing: settings, now, tokens: minted });
396
+ if (save) await save(next);
397
+ return next.accessToken;
398
+ };
399
+
400
+ // lib/connections/icons/attentive.js
401
+ var attentive_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
402
+ <rect width="500" height="500" fill="#FFD967"/>
403
+ <path d="M239.369 127.404C260.863 122.013 284.964 132.569 295.576 152.039C321.796 201.286 347.928 250.567 374.131 299.825C380.149 311.989 381.244 326.564 376.733 339.41C371.446 355.097 358.039 367.69 342.107 372.089C326.274 376.67 308.351 372.871 295.741 362.255C288.865 356.892 284.161 349.359 280.354 341.629C261.869 306.95 243.478 272.217 225.071 237.501C214.409 218.614 187.221 212.656 169.622 225.315C168.104 227.309 164.159 226.857 164.72 223.796C176.911 202.569 189.361 181.497 201.662 160.331C205.183 154.428 208.214 148.129 212.967 143.091C219.844 135.272 229.263 129.782 239.374 127.404" fill="#1E1C1C"/>
404
+ <path d="M166.04 261.805C180.228 259.107 195.528 261.893 207.581 269.971C218.512 277.079 226.908 288.136 230.604 300.657C234.835 314.103 233.614 329.124 227.485 341.788C220.097 356.875 205.782 368.543 189.317 372.089C173.957 375.652 157.089 372.386 144.304 363.103C132.971 355.295 124.912 342.989 121.891 329.581C118.943 316.636 120.725 302.656 127.002 290.938C134.699 275.951 149.503 264.933 166.046 261.811" fill="#1E1C1C"/>
405
+ </svg>`;
406
+
407
+ // lib/connections/providers/attentive.js
408
+ var attentive_default2 = {
409
+ auth: {
410
+ oauth: {
411
+ // NAMES of the credentials holding OUR app's client — keys into the map
412
+ // the provider collection answers, entered on the admin screen at
413
+ // registration, never before. (The names are the env vars they once
414
+ // were; the vocabulary stayed when the storage moved.) No `headers` on
415
+ // the client: Attentive takes credentials as form fields, which is the
416
+ // runner's default.
417
+ client: {
418
+ id: "ATTENTIVE_OAUTH_CLIENT_ID",
419
+ secret: "ATTENTIVE_OAUTH_CLIENT_SECRET"
420
+ },
421
+ urls: {
422
+ authorize: "https://ui.attentivemobile.com/integrations/oauth-install",
423
+ redirect: "/api/connection/attentive/callback",
424
+ token: "https://api.attentivemobile.com/v1/authorization-codes/tokens"
425
+ }
426
+ },
427
+ type: "oauth"
428
+ },
429
+ // EVERYTHING A MERCHANT READS. `errors` would live in here too — the
430
+ // connection DOCUMENT carries its own `errors` array and is spread OVER the
431
+ // resolved manifest downstream, so a top-level one would never render.
432
+ content: {
433
+ // SAYS WHAT ACTUALLY HAPPENS. This used to promise that disconnecting
434
+ // revokes Drawbridge's access, and it cannot: Attentive documents no
435
+ // revocation endpoint, and their authentication page states an access
436
+ // token "does not expire". So the grant survives a disconnect forever
437
+ // unless the merchant removes the integration at Attentive, and the copy
438
+ // has to say so rather than let them believe otherwise.
439
+ confirm: "Disconnecting removes Drawbridge's stored Attentive token. Attentive does not offer a way for us to revoke it, so remove the Drawbridge integration in Attentive as well if you want its access fully withdrawn. Your subscribers stay in both Attentive and Drawbridge \u2014 neither list is deleted.",
440
+ description: [
441
+ "Attentive is where your SMS marketing lives, and this connection is becoming the way your Drawbridge contacts sync into an Attentive segment.",
442
+ "You authorize Drawbridge from inside Attentive and can revoke that access there at any time. Drawbridge never sees or stores your Attentive password.",
443
+ "Subscriber syncing is not live yet, so connecting today does nothing except choose the segment it will use when it ships."
444
+ ],
445
+ excerpt: "Sync your Drawbridge contacts into an Attentive segment.",
446
+ guide: [
447
+ "Press Connect. Drawbridge sends you to Attentive to approve access.",
448
+ "Sign in to Attentive if you are not already, and authorize the permissions listed.",
449
+ "You are returned here \u2014 choose which Attentive segment your contacts should sync into."
450
+ ]
451
+ },
452
+ // A contact destination, like Klaviyo and Mailchimp — a merchant could
453
+ // reasonably keep several up to date at once.
454
+ exclusive: false,
455
+ feature: "organization:connection:attentive",
456
+ fields: [
457
+ {
458
+ input: "select",
459
+ key: "segment",
460
+ label: "Attentive segment",
461
+ message: "Contacts your campaigns collect are synced into this segment.",
462
+ hook: "resources.audiences",
463
+ required: true
464
+ // No `search : false` here, and that is a first: /v2/segments takes a
465
+ // `name` filter (partial match, cited above), so this picker searches
466
+ // the ACCOUNT — Klaviyo and Mailchimp can only match the fetched page.
467
+ }
468
+ ],
469
+ group: "contacts",
470
+ // A HOOK'S VALUE IS ITS ANSWER. The consent is stored and can be revoked;
471
+ // nothing else is built yet, because subscriber sync has not shipped. Every
472
+ // false here is "not yet" rather than "never" — when the sync lands, probe
473
+ // and contacts.sync are the first to flip.
474
+ hooks: {
475
+ auth: {
476
+ // The exchange already yields the tokens, and Attentive documents no
477
+ // account-identity endpoint to enrich them with — Klaviyo's connect
478
+ // reads the account name back; this has nothing cited to read. The
479
+ // callback stores the tokens and skips enrichment on `unimplemented`.
480
+ // FALSE, NOT {}. `{}` means "supported, implemented in the repo with the
481
+ // dependencies", and nothing anywhere implements either of these —
482
+ // there is nothing for them to do. The exchange already yields the
483
+ // tokens and Attentive documents no account-identity endpoint to
484
+ // enrich them with, so connect has nothing to add; and they document
485
+ // no revocation endpoint at all, so disconnect has nothing to call.
486
+ // Recorded as a decision rather than left as an unkept promise.
487
+ connect: false,
488
+ disconnect: false,
489
+ probe: false,
490
+ scopes: false,
491
+ // THE ONE THING WRAPPED, and it is about the response rather than the
492
+ // request. Attentive's token reply carries expires_in : 900 while their
493
+ // auth overview says access tokens "do not expire" — and no refresh
494
+ // token exists to renew with. Storing that expiry would have
495
+ // accessToken() declaring the credential spent fifteen minutes after
496
+ // consent, with nothing to renew it: every connection would demand
497
+ // reconnecting four times an hour.
498
+ //
499
+ // The overview's answer is modelled — the expiry is dropped, so the
500
+ // token is treated as long-lived. Registration item 1 in the header is
501
+ // the live exchange that proves this right or wrong.
502
+ token: async (args) => {
503
+ const minted = await authToken(args);
504
+ return { ...minted, expiresIn: null };
505
+ }
506
+ },
507
+ commerce: false,
508
+ contacts: { remove: false, sync: false },
509
+ email: false,
510
+ inbound: false,
511
+ lifecycle: false,
512
+ resources: {
513
+ // The segments a merchant can sync into, for the picker on their
514
+ // connection.
515
+ //
516
+ // GET /v2/segments (cited in the header). `limit` caps at 1000 in their
517
+ // own spec, defaulting to 20 — low enough that leaving it unset would
518
+ // show a picker quietly missing most of a real account. The response's
519
+ // only identifier is `externalId`, so an entry without one cannot be
520
+ // stored and is dropped.
521
+ audiences: async ({ cursor, limit = 100, search, token }, { fetcher = fetch } = {}) => {
522
+ const query = new URLSearchParams({
523
+ limit: String(Math.min(limit, 1e3)),
524
+ ...cursor && { cursor },
525
+ ...(search == null ? void 0 : search.value) && { name: String(search.value).trim() }
526
+ });
527
+ const response = await fetcher(
528
+ "https://api.attentivemobile.com/v2/segments?" + query,
529
+ {
530
+ headers: { authorization: "Bearer " + token },
531
+ signal: AbortSignal.timeout(15e3)
532
+ }
533
+ );
534
+ if (!response.ok) {
535
+ throw Object.assign(
536
+ new Error("Attentive refused the request (" + response.status + ")"),
537
+ { status: response.status }
538
+ );
539
+ }
540
+ const body = await response.json();
541
+ return {
542
+ items: ((body == null ? void 0 : body.segments) || []).filter((segment) => segment == null ? void 0 : segment.externalId).map((segment) => ({ id: segment.externalId, title: (segment == null ? void 0 : segment.name) || segment.externalId })),
543
+ pageInfo: {
544
+ endCursor: (body == null ? void 0 : body.hasMore) ? (body == null ? void 0 : body.cursor) || null : null,
545
+ hasNextPage: Boolean(body == null ? void 0 : body.hasMore)
546
+ }
547
+ };
548
+ },
549
+ prices: false,
550
+ products: false,
551
+ promotions: false
552
+ },
553
+ segment: false,
554
+ sms: false,
555
+ webhook: false
556
+ },
557
+ icon: attentive_default,
558
+ requires: [
559
+ "ATTENTIVE_OAUTH_CLIENT_ID",
560
+ "ATTENTIVE_OAUTH_CLIENT_SECRET"
561
+ ],
562
+ slug: "attentive",
563
+ // A consent with no segment chosen is authenticated and inert — the sync,
564
+ // when it ships, needs somewhere to put people.
565
+ status: (data2) => {
566
+ var _a;
567
+ return ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.segment) ? data2.status : "pending";
568
+ },
569
+ // No steps: subscriber sync has not shipped, so this vendor contributes
570
+ // nothing to a workflow yet. An empty steps object is the honest declaration.
571
+ steps: {},
572
+ tasks: (data2) => {
573
+ var _a;
574
+ return [
575
+ ...((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.segment) ? [] : [
576
+ {
577
+ message: "Choose which Attentive segment your contacts should sync into. Until you do, nothing is being synced.",
578
+ title: "Choose a segment"
579
+ }
580
+ ],
581
+ {
582
+ message: "Contact syncing to Attentive segments has not shipped yet. Nothing is being sent to Attentive right now.",
583
+ title: "Subscriber sync not available yet",
584
+ type: "warning"
585
+ }
586
+ ];
587
+ },
588
+ title: "Attentive"
589
+ };
590
+
591
+ // lib/http.js
592
+ var DEFAULT_TIMEOUT_MS = 15e3;
593
+ var request = async ({
594
+ body,
595
+ headers = {},
596
+ method = "GET",
597
+ query,
598
+ timeout = DEFAULT_TIMEOUT_MS,
599
+ type = "json",
600
+ url
601
+ }) => {
602
+ const fullUrl = new URL(url);
603
+ if (query) {
604
+ Object.entries(query).forEach(([k, v]) => fullUrl.searchParams.set(k, v));
605
+ }
606
+ ;
607
+ const isForm = type === "form";
608
+ const response = await fetch(fullUrl.toString(), {
609
+ method,
610
+ headers: {
611
+ "Content-Type": isForm ? "application/x-www-form-urlencoded" : "application/json",
612
+ ...headers
613
+ },
614
+ signal: AbortSignal.timeout(timeout),
615
+ ...body !== void 0 && {
616
+ body: isForm ? new URLSearchParams(body).toString() : JSON.stringify(body)
617
+ }
618
+ });
619
+ if (!response.ok) {
620
+ const text2 = await response.text().catch(() => "");
621
+ const error = new Error(text2 || response.statusText);
622
+ error.status = response.status;
623
+ throw error;
624
+ }
625
+ ;
626
+ const text = await response.text();
627
+ try {
628
+ return text ? JSON.parse(text) : null;
629
+ } catch {
630
+ return null;
631
+ }
632
+ };
633
+
634
+ // lib/hubspot.js
635
+ var HUBSPOT_BASE = "https://api.hubapi.com";
636
+ var hubspotRequest = ({ body, fetcher, method, path, query, token }) => {
637
+ if (!token) throw new Error("HubSpot access token missing \u2014 pass token (the drawbridge provider's hubspotToken)");
638
+ return (fetcher || request)({
639
+ body,
640
+ headers: {
641
+ "Authorization": "Bearer " + token
642
+ },
643
+ method,
644
+ query,
645
+ url: HUBSPOT_BASE + path
646
+ });
647
+ };
648
+ var UTM_PROPERTIES = {
649
+ campaign: "utm_campaign",
650
+ content: "utm_content",
651
+ id: "utm_id",
652
+ medium: "utm_medium",
653
+ source: "utm_source",
654
+ term: "utm_term"
655
+ };
656
+ var CLICK_PROPERTIES = {
657
+ fbclid: "hs_facebook_click_id",
658
+ gclid: "hs_google_click_id",
659
+ liFatId: "hs_linkedin_click_id",
660
+ msclkid: "hs_bing_click_id",
661
+ ttclid: "hs_tiktok_click_id"
662
+ };
663
+ var DROPPABLE = new Set(Object.values(UTM_PROPERTIES));
664
+ var isUtmProperty = (key) => DROPPABLE.has(key);
665
+ var toProperties = ({ email, firstName, lastName, utm }) => {
666
+ var _a;
667
+ const properties = {};
668
+ if (email !== void 0) properties.email = email;
669
+ if (firstName !== void 0) properties.firstname = firstName;
670
+ if (lastName !== void 0) properties.lastname = lastName;
671
+ if (utm) {
672
+ for (const [key, property] of Object.entries(UTM_PROPERTIES)) {
673
+ if (utm[key]) properties[property] = utm[key];
674
+ }
675
+ ;
676
+ for (const [key, property] of Object.entries(CLICK_PROPERTIES)) {
677
+ if ((_a = utm.click) == null ? void 0 : _a[key]) properties[property] = utm.click[key];
678
+ }
679
+ ;
680
+ }
681
+ ;
682
+ return properties;
683
+ };
684
+ var send = async ({ doc, fetcher, method, path, token }) => {
685
+ const properties = toProperties(doc);
686
+ try {
687
+ return await hubspotRequest({
688
+ body: { properties },
689
+ fetcher,
690
+ method,
691
+ path,
692
+ token
693
+ });
694
+ } catch (error) {
695
+ const enriched = Object.keys(properties).some(isUtmProperty);
696
+ if ((error == null ? void 0 : error.status) !== 400 || !enriched) throw error;
697
+ return await hubspotRequest({
698
+ body: {
699
+ properties: Object.fromEntries(
700
+ Object.entries(properties).filter(([key]) => !isUtmProperty(key))
701
+ )
702
+ },
703
+ fetcher,
704
+ method,
705
+ path,
706
+ token
707
+ });
708
+ }
709
+ };
710
+ var lookup = async ({ email, fetcher, token }) => {
711
+ var _a, _b;
712
+ if (!token || !email) return;
713
+ try {
714
+ const body = await hubspotRequest({
715
+ body: {
716
+ filterGroups: [
717
+ {
718
+ filters: [
719
+ {
720
+ operator: "EQ",
721
+ propertyName: "email",
722
+ value: email
723
+ }
724
+ ]
725
+ }
726
+ ],
727
+ limit: 1,
728
+ properties: ["email"]
729
+ },
730
+ fetcher,
731
+ method: "POST",
732
+ path: "/crm/v3/objects/contacts/search",
733
+ token
734
+ });
735
+ return (_b = (_a = body == null ? void 0 : body.results) == null ? void 0 : _a[0]) == null ? void 0 : _b.id;
736
+ } catch (error) {
737
+ }
738
+ };
739
+ var contacts = {
740
+ // FORGET A CONTACT, by id or by email. Account deletion — the caller had
741
+ // to search then remove, which is one round trip it should not have to
742
+ // know about.
743
+ remove: async ({ email, id, token }, { fetcher } = {}) => {
744
+ if (!token) return;
745
+ const contact = id || await lookup({ email, fetcher, token });
746
+ if (!contact) return;
747
+ return hubspotRequest({
748
+ fetcher,
749
+ method: "DELETE",
750
+ path: "/crm/v3/objects/contacts/" + contact,
751
+ token
752
+ });
753
+ },
754
+ // Connect an account to its contact by email, creating it if absent, and
755
+ // return the contact id. Unlike SendGrid, HubSpot renames a contact's
756
+ // email in place, so an email change is a plain PATCH on the cached id —
757
+ // no delete-old-then-create-new.
758
+ //
759
+ // Prefer the cached hubspotId; fall back to a search; create last.
760
+ sync: async ({ doc, token }, { fetcher } = {}) => {
761
+ var _a, _b;
762
+ if (!token) return;
763
+ if (doc == null ? void 0 : doc.hubspotId) {
764
+ try {
765
+ return (_a = await send({ doc, fetcher, method: "PATCH", path: "/crm/v3/objects/contacts/" + doc.hubspotId, token })) == null ? void 0 : _a.id;
766
+ } catch (error) {
767
+ if ((error == null ? void 0 : error.status) !== 404) throw error;
768
+ }
769
+ }
770
+ const existing = await lookup({ email: doc == null ? void 0 : doc.email, fetcher, token });
771
+ return (_b = await send({
772
+ doc,
773
+ fetcher,
774
+ method: existing ? "PATCH" : "POST",
775
+ path: existing ? "/crm/v3/objects/contacts/" + existing : "/crm/v3/objects/contacts",
776
+ token
777
+ })) == null ? void 0 : _b.id;
778
+ }
779
+ };
780
+
781
+ // lib/connections/icons/drawbridge.js
782
+ var drawbridge_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
783
+ <rect width="500" height="500" fill="#BAEC5F"/>
784
+ <g clip-path="url(#clip0_2115_2832)">
785
+ <path d="M140.224 127.586L174.803 188.73V311.176L140 372.32L176.084 392.031L216.111 321.753V178.278L176.341 108L140.224 127.586Z" fill="#0D1314"/>
786
+ <path d="M360.001 127.523L323.693 108.282L284.948 178.498V321.596L322.923 391.749L359.393 372.79L326.224 311.52V188.73L360.001 127.523Z" fill="#0D1314"/>
787
+ </g>
788
+ <defs>
789
+ <clipPath id="clip0_2115_2832">
790
+ <rect width="220" height="284" fill="white" transform="translate(140 108)"/>
791
+ </clipPath>
792
+ </defs>
793
+ </svg>`;
794
+
795
+ // lib/features.js
796
+ var page = {
797
+ qrcode: {
798
+ key: "page:qrcode",
799
+ error: "Plan does not include qrcodes",
800
+ feature: "Page qrcode management"
801
+ },
802
+ shortcode: {
803
+ key: "page:shortcode",
804
+ error: "Plan does not include shortcodes",
805
+ feature: "Page shortcode management"
806
+ },
807
+ slug: {
808
+ key: "page:slug",
809
+ error: "Plan does not include url customization",
810
+ feature: "Page slug customization"
811
+ }
812
+ };
813
+ var fields = {
814
+ additional: {
815
+ key: "campaign:fields:additional",
816
+ error: "Plan does not include additional fields",
817
+ feature: "Campaign additional fields"
818
+ },
819
+ lead: {
820
+ key: "campaign:fields:lead",
821
+ error: "Plan does not include lead fields",
822
+ feature: "Campaign lead fields"
823
+ }
824
+ };
825
+ var field = {
826
+ email: {
827
+ key: "campaign:field:email",
828
+ error: "Plan does not include email field",
829
+ feature: "Campaign email field"
830
+ },
831
+ name: {
832
+ key: "campaign:field:name",
833
+ error: "Plan does not include name field",
834
+ feature: "Campaign name field"
835
+ },
836
+ number: {
837
+ key: "campaign:field:number",
838
+ error: "Plan does not include number field",
839
+ feature: "Campaign number field"
840
+ },
841
+ phone: {
842
+ key: "campaign:field:phone",
843
+ error: "Plan does not include phone field",
844
+ feature: "Campaign phone field"
845
+ },
846
+ select: {
847
+ key: "campaign:field:select",
848
+ error: "Plan does not include dropdown field",
849
+ feature: "Campaign dropdown field"
850
+ },
851
+ text: {
852
+ key: "campaign:field:text",
853
+ error: "Plan does not include short text field",
854
+ feature: "Campaign short text field"
855
+ },
856
+ textarea: {
857
+ key: "campaign:field:textarea",
858
+ error: "Plan does not include long text field",
859
+ feature: "Campaign long text field"
860
+ }
861
+ };
862
+ var connection = {
863
+ attentive: {
864
+ key: "organization:connection:attentive",
865
+ error: "Plan does not include Attentive connection",
866
+ feature: "Attentive connection"
867
+ },
868
+ // Klaviyo shipped without an entry here, which meant no plan GRANTED its
869
+ // key and the feature gate denied every non-admin request — a latent 403
870
+ // found while adding Attentive. getPlanFeature answers granted:false for a
871
+ // key absent from the plan's map, so a manifest feature key that appears in
872
+ // no plan list is a connection only admins can manage.
873
+ klaviyo: {
874
+ key: "organization:connection:klaviyo",
875
+ error: "Plan does not include Klaviyo connection",
876
+ feature: "Klaviyo connection"
877
+ },
878
+ mailchimp: {
879
+ key: "organization:connection:mailchimp",
880
+ error: "Plan does not include Mailchimp connection",
881
+ feature: "Mailchimp connection"
882
+ },
883
+ sendgrid: {
884
+ key: "organization:connection:sendgrid",
885
+ error: "Plan does not include SendGrid connection",
886
+ feature: "SendGrid connection"
887
+ },
888
+ shopify: {
889
+ key: "organization:connection:shopify",
890
+ error: "Plan does not include Shopify connection",
891
+ feature: "Shopify connection"
892
+ },
893
+ twilio: {
894
+ key: "organization:connection:twilio",
895
+ error: "Plan does not include Twilio connection",
896
+ feature: "Twilio connection"
897
+ },
898
+ webhook: {
899
+ key: "organization:connection:webhook",
900
+ error: "Plan does not include Webhook connection",
901
+ feature: "Webhook connection"
902
+ }
903
+ };
904
+ var organization = {
905
+ advertisements: {
906
+ key: "organization:advertisements",
907
+ error: "Your plan does not include advertisements",
908
+ feature: "Organization advertisement management"
909
+ },
910
+ affiliates: {
911
+ key: "organization:affiliates",
912
+ error: "Your plan does not include affiliates",
913
+ feature: "Organization affiliates management"
914
+ },
915
+ analytics: {
916
+ key: "organization:analytics",
917
+ error: "Your plan does not include analytics",
918
+ feature: "Organization analytics management"
919
+ },
920
+ brands: {
921
+ key: "organization:brands",
922
+ error: "Your plan does not include brands",
923
+ feature: "Organization brands management"
924
+ },
925
+ // Gates the Networking section as a whole — a verified sending domain today,
926
+ // the SMS number and a custom page domain as they land. One key rather than
927
+ // one per type: they are the same capability to a merchant, and splitting
928
+ // them would mean a plan could grant half a section.
929
+ //
930
+ // It replaces `connection.sender`, which named a connection this stopped
931
+ // being. Free organizations cannot send lead-facing email at all, so a
932
+ // sending identity there is one they could never send from.
933
+ networking: {
934
+ key: "organization:networking",
935
+ error: "Your plan does not include a custom sending identity",
936
+ feature: "Organization networking"
937
+ },
938
+ members: {
939
+ key: "organization:members",
940
+ error: "Your plan does not include team members",
941
+ feature: "Organization members management"
942
+ },
943
+ reports: {
944
+ key: "organization:report",
945
+ error: "Plan does not include report generation",
946
+ feature: "Organization report generation"
947
+ },
948
+ subdomain: {
949
+ key: "organization:subdomain",
950
+ error: "Plan does not include subdomain customization",
951
+ feature: "Organization subdomain customization"
952
+ }
953
+ };
954
+
955
+ // index.js
956
+ import { code, data } from "currency-codes";
957
+ import { customAlphabet } from "nanoid";
958
+
959
+ // lib/color.js
960
+ import tinycolor from "tinycolor2";
961
+ var colorFormatted = (value) => {
962
+ const color = tinycolor(value);
963
+ const attributes = {
964
+ brightness: color.getBrightness(),
965
+ dark: color.isDark(),
966
+ light: color.isLight(),
967
+ luminance: color.getLuminance()
968
+ };
969
+ return {
970
+ attributes,
971
+ hex: color.toHexString(),
972
+ hsl: color.toHsl(),
973
+ hsv: color.toHsv(),
974
+ rgb: color.toRgbString()
975
+ };
976
+ };
977
+ var colorAccessible = (background2) => {
978
+ const white = "#ffffff";
979
+ const black = "#000000";
980
+ return tinycolor.isReadable(
981
+ background2,
982
+ white,
983
+ {
984
+ level: "AA",
985
+ size: "normal"
986
+ }
987
+ ) ? white : black;
988
+ };
989
+
990
+ // lib/constants.js
991
+ var font = {
992
+ family: "Roboto Flex",
993
+ transform: "none",
994
+ weight: "regular"
995
+ };
996
+ var background = "#ffffff";
997
+ var style = {
998
+ background: {
999
+ color: colorFormatted(background)
1000
+ },
1001
+ body: font,
1002
+ button: {
1003
+ background: {
1004
+ color: colorFormatted(background)
1005
+ },
1006
+ radius: 0,
1007
+ text: {
1008
+ color: colorFormatted(colorAccessible(background))
1009
+ }
1010
+ },
1011
+ heading: font,
1012
+ input: {
1013
+ radius: 0
1014
+ },
1015
+ text: {
1016
+ color: colorFormatted(colorAccessible(background))
1017
+ }
1018
+ };
1019
+
1020
+ // index.js
1021
+ var nanoid = customAlphabet("0123456789abcdefghijklmnopqrstuvwxyz", 8);
1022
+ var infinite = 1e300;
1023
+ var megabyte = 1024 * 1024;
1024
+ var gigabyte = megabyte * 1024;
1025
+ var currencies = data.map((item) => ({
1026
+ ...item,
1027
+ key: item.currency,
1028
+ value: item.code
1029
+ }));
1030
+
1031
+ // lib/plans.js
1032
+ var featuresFor = (array = []) => Object.values({
1033
+ ...connection,
1034
+ ...organization,
1035
+ ...fields,
1036
+ ...field,
1037
+ ...page
1038
+ }).reduce(
1039
+ (accumulator, { key, error, feature }) => {
1040
+ if (array.includes(key)) {
1041
+ accumulator.granted[key] = feature;
1042
+ } else {
1043
+ accumulator.denied[key] = error;
1044
+ }
1045
+ return accumulator;
1046
+ },
1047
+ { denied: {}, granted: {} }
1048
+ );
1049
+ var overage = (actionCents) => ({
1050
+ actionCents,
1051
+ overages: { actions: String(actionCents) }
1052
+ });
1053
+ var all = {
1054
+ features: (array = []) => featuresFor([
1055
+ connection.attentive.key,
1056
+ connection.klaviyo.key,
1057
+ connection.mailchimp.key,
1058
+ connection.sendgrid.key,
1059
+ connection.shopify.key,
1060
+ connection.twilio.key,
1061
+ connection.webhook.key,
1062
+ organization.affiliates.key,
1063
+ organization.brands.key,
1064
+ fields.additional.key,
1065
+ fields.lead.key,
1066
+ field.email.key,
1067
+ field.name.key,
1068
+ field.number.key,
1069
+ field.phone.key,
1070
+ field.select.key,
1071
+ field.text.key,
1072
+ field.textarea.key,
1073
+ page.qrcode.key,
1074
+ page.shortcode.key,
1075
+ ...array
1076
+ ]),
1077
+ // `members` and `storage` default to infinite so an unnamed term on a custom
1078
+ // plan reads as UNLIMITED rather than absent. Storage used to have no
1079
+ // default, so a deal that did not name it resolved to undefined and the
1080
+ // organization's usage card simply omitted the row — the same blank field
1081
+ // that showed "Unlimited" for members showed nothing at all for storage.
1082
+ // Every catalog plan names both, so the defaults only ever apply to a
1083
+ // custom plan. `actions` has no default on purpose: an unnamed allowance
1084
+ // bills nothing, which is why the availability switch refuses to flip
1085
+ // without one.
1086
+ limits: ({ actions, members = infinite, storage = infinite }) => ({
1087
+ campaign: {
1088
+ advertisements: infinite,
1089
+ links: infinite,
1090
+ fields: infinite,
1091
+ pages: infinite
1092
+ },
1093
+ organization: {
1094
+ actions,
1095
+ affiliates: infinite,
1096
+ brands: infinite,
1097
+ campaigns: infinite,
1098
+ members,
1099
+ storage
1100
+ }
1101
+ })
1102
+ };
1103
+ var free = {
1104
+ conversion: 3,
1105
+ features: all.features(),
1106
+ limits: all.limits({
1107
+ actions: 200,
1108
+ members: 0,
1109
+ storage: gigabyte * 5
1110
+ }),
1111
+ title: "Free"
1112
+ };
1113
+ var plans = {
1114
+ DB00002: {
1115
+ // A verified sending domain is a PAID capability: free plans cannot send
1116
+ // lead-facing email at all (the send path gates on an active
1117
+ // subscription), so granting it there would offer a domain that can
1118
+ // never send from.
1119
+ features: all.features([organization.networking.key, organization.members.key]),
1120
+ limits: all.limits({ actions: 5e3, members: 3, storage: gigabyte * 10 }),
1121
+ marketing: {
1122
+ description: "Tools to fine-tune campaigns and improve lead quality.",
1123
+ features: [],
1124
+ limits: [
1125
+ ["Actions per month", "5,000"],
1126
+ ["Affiliates", "Unlimited"],
1127
+ ["Brands", "Unlimited"],
1128
+ ["Campaigns", "Unlimited"],
1129
+ ["Pages", "Unlimited"],
1130
+ ["Members", "3"],
1131
+ ["Storage", "10GB"]
1132
+ ]
1133
+ },
1134
+ ...overage(2.5),
1135
+ title: "Starter",
1136
+ conversion: 2
1137
+ },
1138
+ DB00003: {
1139
+ features: all.features([
1140
+ organization.networking.key,
1141
+ organization.advertisements.key,
1142
+ organization.analytics.key,
1143
+ organization.members.key,
1144
+ organization.subdomain.key,
1145
+ page.slug.key
1146
+ ]),
1147
+ limits: all.limits({ actions: 15e3, members: 5, storage: gigabyte * 20 }),
1148
+ marketing: {
1149
+ description: "Expand your reach and grow your lead pipeline.",
1150
+ features: [
1151
+ "Analytics",
1152
+ "Custom subdomain / URLs",
1153
+ "Confirmation page ads"
1154
+ ],
1155
+ limits: [
1156
+ ["Actions per month", "15,000"],
1157
+ ["Affiliates", "Unlimited"],
1158
+ ["Brands", "Unlimited"],
1159
+ ["Campaigns", "Unlimited"],
1160
+ ["Pages", "Unlimited"],
1161
+ ["Members", "5"],
1162
+ ["Storage", "20GB"]
1163
+ ]
1164
+ },
1165
+ ...overage(2),
1166
+ title: "Pro",
1167
+ conversion: 1.5
1168
+ },
1169
+ DB00004: {
1170
+ features: all.features([
1171
+ organization.networking.key,
1172
+ organization.advertisements.key,
1173
+ organization.analytics.key,
1174
+ organization.members.key,
1175
+ organization.subdomain.key,
1176
+ page.slug.key
1177
+ ]),
1178
+ limits: all.limits({ actions: 4e4, members: 10, storage: gigabyte * 50 }),
1179
+ marketing: {
1180
+ description: "Accelerate acquisition with more power and flexibility.",
1181
+ features: [
1182
+ "Analytics",
1183
+ "Custom subdomain / URLs",
1184
+ "Confirmation page ads"
1185
+ ],
1186
+ limits: [
1187
+ ["Actions per month", "40,000"],
1188
+ ["Affiliates", "Unlimited"],
1189
+ ["Brands", "Unlimited"],
1190
+ ["Campaigns", "Unlimited"],
1191
+ ["Pages", "Unlimited"],
1192
+ ["Members", "10"],
1193
+ ["Storage", "50GB"]
1194
+ ]
1195
+ },
1196
+ ...overage(1.85),
1197
+ title: "Premium",
1198
+ conversion: 1
1199
+ },
1200
+ DB00005: {
1201
+ features: all.features([
1202
+ organization.networking.key,
1203
+ organization.advertisements.key,
1204
+ organization.analytics.key,
1205
+ organization.members.key,
1206
+ organization.subdomain.key,
1207
+ page.slug.key
1208
+ ]),
1209
+ limits: all.limits({ actions: 1e5, members: infinite, storage: gigabyte * 100 }),
1210
+ marketing: {
1211
+ description: "Built for brands focused on results.",
1212
+ features: [
1213
+ "Analytics",
1214
+ "Custom subdomain / URLs",
1215
+ "Confirmation page ads"
1216
+ ],
1217
+ limits: [
1218
+ ["Actions per month", "100,000"],
1219
+ ["Affiliates", "Unlimited"],
1220
+ ["Brands", "Unlimited"],
1221
+ ["Campaigns", "Unlimited"],
1222
+ ["Pages", "Unlimited"],
1223
+ ["Members", "Unlimited"],
1224
+ ["Storage", "100GB"]
1225
+ ]
1226
+ },
1227
+ ...overage(1.5),
1228
+ title: "Elite",
1229
+ conversion: 0.5
1230
+ }
1231
+ };
1232
+ var resolvePlan = (subscription) => {
1233
+ var _a, _b;
1234
+ const custom = subscription == null ? void 0 : subscription.custom;
1235
+ if (!custom) return plans[subscription == null ? void 0 : subscription.plan] ?? free;
1236
+ return {
1237
+ // Reusing all.features / all.limits is what keeps a custom plan the same
1238
+ // SHAPE as a catalog one: the base feature grants every plan carries, the
1239
+ // campaign limits that are always infinite, and members defaulting to
1240
+ // infinite when a deal does not name it.
1241
+ conversion: custom.conversion ?? free.conversion,
1242
+ custom: true,
1243
+ // A custom plan is a negotiated PAID deal, so it carries the paid-tier
1244
+ // baseline whether or not the deal thought to name it. Today that is the
1245
+ // sending domain: every catalog paid tier grants it, and a custom plan
1246
+ // silently lacking it would be a support ticket, not a pricing decision.
1247
+ features: all.features([organization.networking.key, ...((_a = custom.features) == null ? void 0 : _a.granted) || []]),
1248
+ limits: all.limits(((_b = custom.limits) == null ? void 0 : _b.organization) || {}),
1249
+ // A custom plan stores its overage BARE on `custom.overages` — a different
1250
+ // shape from the catalog's nested one. Number() so a deal stored as a string
1251
+ // still resolves to cents-per-action; an unnamed overage stays undefined
1252
+ // (it bills nothing) rather than becoming NaN.
1253
+ actionCents: custom.overages == null ? void 0 : Number(custom.overages),
1254
+ overages: { actions: custom.overages },
1255
+ title: custom.title || "Custom"
1256
+ };
1257
+ };
1258
+ var conversionRate = (subscription) => {
1259
+ var _a;
1260
+ return ((_a = resolvePlan(subscription)) == null ? void 0 : _a.conversion) ?? free.conversion;
1261
+ };
1262
+
1263
+ // lib/transactions.js
1264
+ import { currentTraceId } from "@drawbridge/drawbridge-telemetry";
1265
+
1266
+ // lib/billing.js
1267
+ import { createLogger } from "@drawbridge/drawbridge-telemetry";
1268
+ var logger = createLogger();
1269
+ var MARKUP = 1.3;
1270
+ var cost = {
1271
+ // gemini-3.5-flash — verified against Google's pricing page 2026-07-09:
1272
+ // $0.15 cached / $1.50 input / $9.00 output per 1M tokens (thinking billed at
1273
+ // output). ~3.6x the retired 2.5-flash output rate.
1274
+ "gemini-3.5-flash": {
1275
+ cached: 15,
1276
+ input: 150,
1277
+ output: 900
1278
+ },
1279
+ // gemini-3.5-flash-lite — verified against Google's pricing page 2026-08-20:
1280
+ // $0.03 cached / $0.30 input / $2.50 output per 1M tokens (thinking billed at
1281
+ // output). A fifth of flash on input, ~a quarter on output. Growth's assistant
1282
+ // ranks the feed on this tier — one call per page — so its rows were the
1283
+ // unpriced ones until now.
1284
+ "gemini-3.5-flash-lite": {
1285
+ cached: 3,
1286
+ input: 30,
1287
+ output: 250
1288
+ },
1289
+ "gemini-2.5-flash": {
1290
+ cached: 3,
1291
+ input: 30,
1292
+ output: 250
1293
+ },
1294
+ "gemini-2.5-flash-image": {
1295
+ cached: 3,
1296
+ input: 30,
1297
+ output: 3e3
1298
+ },
1299
+ // gemini-3-pro-image-preview — verified against Google's pricing page
1300
+ // 2026-08-12: $2.00 input / $12.00 text output per 1M, and image output
1301
+ // tokens at ~$120/1M (a 1K-2K image is 1120 tokens = $0.134, a 4K image
1302
+ // 2000 tokens = $0.24). Encoded the flash-image way: one flat output rate
1303
+ // that reproduces the per-image price from the tokens usageMetadata
1304
+ // reports. Growth's hero generation runs this model today.
1305
+ "gemini-3-pro-image-preview": {
1306
+ cached: 20,
1307
+ input: 200,
1308
+ output: 12e3
1309
+ }
1310
+ };
1311
+ var toolCost = {
1312
+ search: 3.5
1313
+ };
1314
+ var toolPricing = Object.fromEntries(
1315
+ Object.entries(toolCost).map(([tool, value]) => [
1316
+ tool,
1317
+ Math.ceil(value * MARKUP)
1318
+ ])
1319
+ );
1320
+ var pricing = Object.fromEntries(
1321
+ Object.entries(cost).map(([model, rates]) => [
1322
+ model,
1323
+ {
1324
+ cached: Math.round(rates.cached * MARKUP),
1325
+ input: Math.round(rates.input * MARKUP),
1326
+ output: Math.round(rates.output * MARKUP)
1327
+ }
1328
+ ])
1329
+ );
1330
+
1331
+ // lib/pricing.js
1332
+ var emailPlans = {
1333
+ essentials50k: {
1334
+ included: 5e4,
1335
+ // The plan's own price is not shown in the console once you are on it —
1336
+ // it reads "Your Current Plan" where the price would be. Left null rather
1337
+ // than guessed; fill from an invoice. Nothing derives from it yet, and an
1338
+ // invented figure would quietly become the basis of an upgrade decision.
1339
+ monthly: null,
1340
+ overageCents: 0.133,
1341
+ title: "Essentials 50K"
1342
+ },
1343
+ essentials100k: {
1344
+ included: 1e5,
1345
+ monthly: 3495,
1346
+ overageCents: 0.09,
1347
+ title: "Essentials 100K"
1348
+ },
1349
+ pro100k: {
1350
+ included: 1e5,
1351
+ monthly: 8995,
1352
+ overageCents: 0.11,
1353
+ title: "Pro 100K"
1354
+ },
1355
+ pro300k: {
1356
+ included: 3e5,
1357
+ monthly: 24900,
1358
+ overageCents: 0.091,
1359
+ title: "Pro 300K"
1360
+ },
1361
+ pro700k: {
1362
+ included: 7e5,
1363
+ monthly: 49900,
1364
+ overageCents: 0.078,
1365
+ title: "Pro 700K"
1366
+ },
1367
+ pro1500k: {
1368
+ included: 15e5,
1369
+ monthly: 79900,
1370
+ overageCents: 0.059,
1371
+ title: "Pro 1.5 Million"
1372
+ },
1373
+ pro2500k: {
1374
+ included: 25e5,
1375
+ monthly: 109900,
1376
+ overageCents: 0.047,
1377
+ title: "Pro 2.5 Million"
1378
+ }
1379
+ };
1380
+ var emailPlan = "essentials50k";
1381
+ var sending = {
1382
+ email: {
1383
+ // Fraction of the included volume that raises the alarm. Far enough ahead
1384
+ // to act on, high enough not to fire on ordinary growth.
1385
+ //
1386
+ // Crossing it is NOT an outage. The provider bills overage rather than
1387
+ // stopping sends, so the alarm is a COST signal: past the included volume
1388
+ // every email is charged at overageCents, and at some run rate the next
1389
+ // plan up is cheaper than the overage. That is the decision it exists to
1390
+ // prompt, and it is why nobody should be woken by it.
1391
+ alertThreshold: 0.8,
1392
+ // Emails per calendar month included, PLATFORM-WIDE and across every send
1393
+ // path: lead-facing mail, workflow steps, and the sign-in codes and
1394
+ // account mail that no plan allowance meters.
1395
+ monthlyCeiling: emailPlans[emailPlan].included,
1396
+ overageCents: emailPlans[emailPlan].overageCents,
1397
+ plan: emailPlan,
1398
+ plans: emailPlans,
1399
+ title: emailPlans[emailPlan].title
1400
+ }
1401
+ };
1402
+ var channels = {
1403
+ email: {
1404
+ actionsPerSend: 1,
1405
+ includedInAllowance: true
1406
+ },
1407
+ sms: {
1408
+ // Two actions PER SEGMENT (a long message is several segments), billed from
1409
+ // the FIRST segment and never drawn from the plan's included allowance —
1410
+ // carrier cost is real from message one, so there is no free tier of it.
1411
+ actionsPerSegment: 2,
1412
+ includedInAllowance: false
1413
+ }
1414
+ };
1415
+
1416
+ // lib/connections/providers/drawbridge.js
1417
+ var interpolate = (template, data2) => {
1418
+ if (!template) return template;
1419
+ return template.replace(/\{\{(\w+)\}\}/g, (_, key) => (data2 == null ? void 0 : data2[key]) != null ? String(data2[key]) : "{{" + key + "}}");
1420
+ };
1421
+ var teamRecipients = async ({ memberIds = [], organization: organization2, read }) => {
1422
+ const org = await read.get({ collection: "organization", query: { id: organization2 } });
1423
+ const owner = (org == null ? void 0 : org.owner) ? await read.get({ collection: "user", query: { id: org.owner } }) : null;
1424
+ const members = memberIds.length ? await read.aggregate({
1425
+ collection: "member",
1426
+ pipeline: [
1427
+ {
1428
+ $match: {
1429
+ id: { $in: memberIds },
1430
+ organization: organization2,
1431
+ status: "accepted"
1432
+ }
1433
+ }
1434
+ ]
1435
+ }) : [];
1436
+ const seen = /* @__PURE__ */ new Set();
1437
+ return [owner, ...members].filter((member) => {
1438
+ if (!(member == null ? void 0 : member.id) || !(member == null ? void 0 : member.email)) return false;
1439
+ const address = member.email.toLowerCase();
1440
+ if (seen.has(address)) return false;
1441
+ seen.add(address);
1442
+ return true;
1443
+ });
1444
+ };
1445
+ var queueNotification = (data2) => ({ collection: "notification", data: data2, operation: "create" });
1446
+ var drawbridge_default2 = {
1447
+ auth: {
1448
+ type: "none"
1449
+ },
1450
+ content: {
1451
+ confirm: "This connection is part of Drawbridge and cannot be disconnected.",
1452
+ description: [
1453
+ "Drawbridge sends your notification email and SMS, keeps your segments in sync, and posts to your own endpoints. These are built in rather than connected, so there is nothing here to set up."
1454
+ ],
1455
+ excerpt: "The steps Drawbridge runs itself.",
1456
+ guide: [
1457
+ "Nothing to do. These steps are available in every workflow builder."
1458
+ ]
1459
+ },
1460
+ exclusive: false,
1461
+ fields: [],
1462
+ group: "developer",
1463
+ // THE BODIES LIVE HERE, beside the declarations that name them. They used to
1464
+ // live in drawbridge-sync because they touch the database, the queues and the
1465
+ // sockets — and a published package cannot carry a controller.
1466
+ //
1467
+ // It does not have to. A hook is a function, so everything it needs is PASSED
1468
+ // IN: `read` for the reads, `canSend` for the opt-out floor, `resolveContact`
1469
+ // for the one write whose RESULT the hook has to count. Everything else a hook
1470
+ // wants done it DESCRIBES — `writes`, `enqueues`, `events` — and the shell
1471
+ // performs it. See lib/connections/contract.js for that shape.
1472
+ hooks: {
1473
+ auth: {
1474
+ // Nothing to connect, revoke, probe or re-scope.
1475
+ connect: false,
1476
+ disconnect: false,
1477
+ probe: false,
1478
+ scopes: false,
1479
+ token: false
1480
+ },
1481
+ commerce: false,
1482
+ // DRAWBRIDGE'S OWN CRM. Not a merchant's — this keeps our HubSpot portal in
1483
+ // step with account signups, and drawbridge-sync's user stream calls it.
1484
+ //
1485
+ // A real implementation here rather than `{}` because the bodies are pure
1486
+ // HTTP against a token: no controller, no queue, nothing that would have to
1487
+ // live in the service. lib/hubspot.js holds them, beside lib/sendgrid.js
1488
+ // and lib/twilio.js, which are the same kind of thing — vendor clients for
1489
+ // accounts DRAWBRIDGE holds rather than ones a merchant connects.
1490
+ contacts,
1491
+ email: {
1492
+ // A PERIODIC SUMMARY to the team, on a schedule trigger rather than per
1493
+ // lead.
1494
+ //
1495
+ // The count is the point: `email.notify` tells the owner one lead arrived
1496
+ // and dampens a spike to one message per bucket, which is deliberately not
1497
+ // a count. This is where "you got 43 entries this week" comes from.
1498
+ digest: async ({ context, step, workflow }, { read } = {}) => {
1499
+ var _a, _b, _c, _d;
1500
+ const days = { day: 1, month: 30, week: 7 }[(_a = workflow == null ? void 0 : workflow.trigger) == null ? void 0 : _a.event] || 7;
1501
+ const since = new Date(Date.now() - days * 24 * 60 * 60 * 1e3);
1502
+ const campaign = ((_c = (_b = workflow == null ? void 0 : workflow.trigger) == null ? void 0 : _b.filters) == null ? void 0 : _c.campaign) || null;
1503
+ const [counted] = await read.aggregate({
1504
+ collection: "lead",
1505
+ pipeline: [
1506
+ {
1507
+ $match: {
1508
+ createdAt: { $gte: since },
1509
+ organization: workflow.organization,
1510
+ ...campaign && { campaigns: { $in: [campaign] } }
1511
+ }
1512
+ },
1513
+ { $count: "count" }
1514
+ ]
1515
+ });
1516
+ const count = Number((counted == null ? void 0 : counted.count) || 0);
1517
+ const request2 = { campaign, count, days };
1518
+ if (!count) return { message: "No new leads in the period \u2014 digest skipped.", request: request2, response: { skipped: true }, skipped: true };
1519
+ const recipients = await teamRecipients({
1520
+ memberIds: ((_d = step.settings) == null ? void 0 : _d.members) || [],
1521
+ organization: workflow.organization,
1522
+ read
1523
+ });
1524
+ const values = { ...context, count };
1525
+ return {
1526
+ message: "Digest of " + count + " new lead(s) queued for " + recipients.length + " recipient(s).",
1527
+ request: request2,
1528
+ response: { count, notified: recipients.length },
1529
+ writes: recipients.map((member) => {
1530
+ var _a2, _b2;
1531
+ return queueNotification({
1532
+ audience: "member",
1533
+ message: interpolate((_a2 = step.settings) == null ? void 0 : _a2.message, values),
1534
+ organization: workflow.organization,
1535
+ send: { type: "email", email: member.email },
1536
+ title: interpolate((_b2 = step.settings) == null ? void 0 : _b2.subject, values),
1537
+ workflow: workflow.id
1538
+ });
1539
+ })
1540
+ };
1541
+ },
1542
+ // To the organization's OWN PEOPLE. Never suppressed, never
1543
+ // subscription-gated, no unsubscribe footer — telling an org's staff about
1544
+ // their own leads is not commercial mail to a stranger.
1545
+ //
1546
+ // FREE, permanently. The lead that triggered this run already consumed the
1547
+ // billable action, and `members` is a list — billing here would turn one
1548
+ // lead into five more charges and the org would be paying to read its own
1549
+ // mail. The declaration prices it at zero; the shell bills nothing for
1550
+ // zero.
1551
+ notify: async ({ context, step, workflow }, { read } = {}) => {
1552
+ var _a;
1553
+ const memberIds = ((_a = step.settings) == null ? void 0 : _a.members) || [];
1554
+ const request2 = { members: memberIds.length };
1555
+ const recipients = await teamRecipients({ memberIds, organization: workflow.organization, read });
1556
+ if (!recipients.length) {
1557
+ return {
1558
+ message: "No owner or accepted member with an email address \u2014 team notification skipped.",
1559
+ request: request2,
1560
+ response: { skipped: true },
1561
+ skipped: true
1562
+ };
1563
+ }
1564
+ const bucket = Math.floor(Date.now() / (15 * 60 * 1e3));
1565
+ return {
1566
+ message: "Team notification queued for " + recipients.length + " recipient(s).",
1567
+ request: request2,
1568
+ response: { notified: recipients.length },
1569
+ writes: recipients.map((member) => {
1570
+ var _a2, _b;
1571
+ return {
1572
+ ...queueNotification({
1573
+ audience: "member",
1574
+ // Per workflow, recipient AND bucket, so one recipient's damper
1575
+ // can never swallow another's mail and a later bucket is never
1576
+ // mistaken for a duplicate of an earlier one.
1577
+ key: "team.notify." + workflow.id + "." + member.id + "." + bucket,
1578
+ message: interpolate((_a2 = step.settings) == null ? void 0 : _a2.message, context),
1579
+ organization: workflow.organization,
1580
+ send: { type: "email", email: member.email },
1581
+ title: interpolate((_b = step.settings) == null ? void 0 : _b.subject, context),
1582
+ workflow: workflow.id
1583
+ }),
1584
+ // E11000 IS THE DAMPER WORKING: this recipient has already been
1585
+ // told within the bucket. Declared per write rather than assumed by
1586
+ // the shell, because on every other write here a duplicate key is a
1587
+ // real failure.
1588
+ ignoreDuplicate: true
1589
+ };
1590
+ })
1591
+ };
1592
+ },
1593
+ // Drawbridge sends lead-facing email itself — no merchant provider gates
1594
+ // it.
1595
+ //
1596
+ // This QUEUES rather than sends: queue/notification.js owns delivery, the
1597
+ // unsubscribe token and the CAN-SPAM footer. The step's job is to say who
1598
+ // and what, correctly, and to refuse early when it must not send at all.
1599
+ send: async ({ context, step, workflow }, { canSend, read } = {}) => {
1600
+ var _a, _b;
1601
+ const to = context == null ? void 0 : context.email;
1602
+ if (!to) throw new Error("No email address on context (context.email is required)");
1603
+ const request2 = { to };
1604
+ const { ok: sendable } = await canSend({ channel: "email", to });
1605
+ if (!sendable) return { message: "Recipient has opted out \u2014 skipped.", request: request2, response: { skipped: true }, skipped: true };
1606
+ const organization2 = await read.get({ collection: "organization", query: { id: workflow.organization } });
1607
+ const subscription = (organization2 == null ? void 0 : organization2.subscription) ? await read.get({ collection: "subscription", query: { id: organization2.subscription } }) : null;
1608
+ if ((subscription == null ? void 0 : subscription.status) !== "active") {
1609
+ return {
1610
+ message: "Organization has no active subscription \u2014 workflow-step email skipped.",
1611
+ request: request2,
1612
+ response: { skipped: true },
1613
+ skipped: true
1614
+ };
1615
+ }
1616
+ return {
1617
+ message: "Email queued for delivery to " + to + ".",
1618
+ request: request2,
1619
+ response: { queued: true },
1620
+ // NO `connection` FIELD, deliberately: the platform sends this.
1621
+ // `audience : 'lead'` states what the queue would otherwise infer from
1622
+ // shape.
1623
+ //
1624
+ // `campaign` is not decoration. queue/notification.js mints the
1625
+ // unsubscribe token with it, so it decides whether opting out is
1626
+ // scoped to this campaign or the whole organization, and it names the
1627
+ // campaign in the footer. Sending without it silently broadens every
1628
+ // opt-out to the entire organization.
1629
+ writes: [
1630
+ queueNotification({
1631
+ audience: "lead",
1632
+ campaign: (context == null ? void 0 : context.campaign) || null,
1633
+ lead: (context == null ? void 0 : context.lead) || null,
1634
+ message: interpolate((_a = step.settings) == null ? void 0 : _a.message, context),
1635
+ organization: workflow.organization,
1636
+ send: { type: "email", email: to },
1637
+ title: interpolate((_b = step.settings) == null ? void 0 : _b.subject, context),
1638
+ workflow: workflow.id
1639
+ })
1640
+ ]
1641
+ };
1642
+ }
1643
+ },
1644
+ inbound: false,
1645
+ lifecycle: false,
1646
+ resources: {
1647
+ audiences: false,
1648
+ prices: false,
1649
+ products: false,
1650
+ promotions: false
1651
+ },
1652
+ segment: {
1653
+ // RECALCULATE SEGMENT MEMBERSHIP. The one FAN-OUT hook: it evaluates every
1654
+ // contact in an organization against every segment, which is too much for
1655
+ // one job, so it returns chunks and the shell defers completion.
1656
+ //
1657
+ // Returning `chunks` is the only thing that makes it different. The
1658
+ // declaration, the guards, the step document and the price are the shell's,
1659
+ // exactly as they are for a step that finishes in one go.
1660
+ sync: async ({ context, step }, { chunkSize, logger: logger2, read, resolveContact } = {}) => {
1661
+ var _a, _b, _c;
1662
+ if (!chunkSize) throw new Error("segment.sync needs chunkSize from the shell");
1663
+ const organization2 = context == null ? void 0 : context.organization;
1664
+ const configured = (_a = step == null ? void 0 : step.settings) == null ? void 0 : _a.segment;
1665
+ const request2 = { organization: organization2 || null, segmentId: configured || null };
1666
+ const release = (ids, status = "active") => {
1667
+ const released = (ids || []).filter(Boolean);
1668
+ return {
1669
+ events: organization2 ? released.map((id) => ({
1670
+ event: "organization.segments",
1671
+ payload: { id, status },
1672
+ room: "organization." + organization2
1673
+ })) : [],
1674
+ writes: released.map((id) => ({
1675
+ collection: "segment",
1676
+ data: { $set: { status } },
1677
+ operation: "update",
1678
+ query: { id }
1679
+ }))
1680
+ };
1681
+ };
1682
+ if (!organization2) {
1683
+ return {
1684
+ ...release([configured]),
1685
+ message: "Trigger data missing organization id \u2014 cannot sync segments.",
1686
+ request: request2,
1687
+ response: { skipped: true },
1688
+ skipped: true
1689
+ };
1690
+ }
1691
+ const segments = await read.aggregate({
1692
+ collection: "segment",
1693
+ pipeline: [{ $match: configured ? { id: configured, organization: organization2 } : { organization: organization2 } }]
1694
+ });
1695
+ if (!segments.length) {
1696
+ return {
1697
+ ...release([configured]),
1698
+ message: "No segments matched the request \u2014 nothing to sync.",
1699
+ request: request2,
1700
+ response: { skipped: true },
1701
+ skipped: true
1702
+ };
1703
+ }
1704
+ const segmentIds = segments.map((entry) => entry.id);
1705
+ try {
1706
+ let backfilled = 0;
1707
+ if (segments.some((entry) => entry.system)) {
1708
+ const contacted = await read.aggregate({
1709
+ collection: "contact",
1710
+ pipeline: [
1711
+ { $match: { organization: organization2 } },
1712
+ { $project: { _id: 0, leads: 1 } },
1713
+ { $unwind: "$leads" },
1714
+ { $group: { _id: null, ids: { $addToSet: "$leads" } } }
1715
+ ]
1716
+ });
1717
+ const uncontacted = await read.aggregate({
1718
+ collection: "lead",
1719
+ pipeline: [
1720
+ { $match: { id: { $nin: ((_b = contacted[0]) == null ? void 0 : _b.ids) || [] }, organization: organization2 } },
1721
+ { $project: { _id: 0, id: 1 } }
1722
+ ]
1723
+ });
1724
+ for (const lead of uncontacted) {
1725
+ try {
1726
+ await resolveContact({ leadId: lead.id });
1727
+ backfilled += 1;
1728
+ } catch (error) {
1729
+ if (error.code !== 11e3) throw error;
1730
+ }
1731
+ }
1732
+ (_c = logger2 == null ? void 0 : logger2.info) == null ? void 0 : _c.call(logger2, "segment.sync.backfill", { backfilled, organization: organization2, uncontacted: uncontacted.length });
1733
+ }
1734
+ const contacts2 = await read.aggregate({
1735
+ collection: "contact",
1736
+ pipeline: [
1737
+ { $match: { organization: organization2 } },
1738
+ { $project: { _id: 0, id: 1 } },
1739
+ { $sort: { id: 1 } }
1740
+ ]
1741
+ });
1742
+ if (!contacts2.length) {
1743
+ return {
1744
+ ...release(segmentIds),
1745
+ message: "Organization has no contacts to evaluate against segments.",
1746
+ request: request2,
1747
+ response: { skipped: true },
1748
+ skipped: true
1749
+ };
1750
+ }
1751
+ const contactIds = contacts2.map((contact) => contact.id);
1752
+ const org = await read.get({ collection: "organization", query: { id: organization2 } });
1753
+ const chunks = [];
1754
+ for (let index = 0; index < contactIds.length; index += chunkSize) {
1755
+ chunks.push({
1756
+ contactIds: contactIds.slice(index, index + chunkSize),
1757
+ organization: organization2,
1758
+ segments: segmentIds,
1759
+ // A BACKFILL IS NOT BILLABLE. It creates the contacts this run
1760
+ // then evaluates, so charging for it would bill an organization
1761
+ // for work its own history made necessary.
1762
+ usage: (context == null ? void 0 : context.billable) === true && backfilled === 0 ? (org == null ? void 0 : org.usage) || null : null
1763
+ });
1764
+ }
1765
+ return {
1766
+ chunks,
1767
+ ...configured && { extra: { segment: configured } },
1768
+ message: "Queued " + contactIds.length + " contacts across " + chunks.length + " chunks for segment evaluation.",
1769
+ queue: "segment",
1770
+ request: { ...request2, segments: segmentIds },
1771
+ response: { chunks: chunks.length, contacts: contactIds.length, segments: segments.length }
1772
+ };
1773
+ } catch (error) {
1774
+ throw Object.assign(error, release(segmentIds, "error"));
1775
+ }
1776
+ }
1777
+ },
1778
+ sms: {
1779
+ // SMS TO A LEAD, through the merchant's own Twilio connection.
1780
+ //
1781
+ // WITHDRAWN from the builder — twilio went, and a connection-gated step
1782
+ // with no connection to gate on could only ever render permanently
1783
+ // disabled. Stored workflows still carry it, so it still runs.
1784
+ //
1785
+ // It looks its own connection up rather than relying on the shell, because
1786
+ // the step is declared by the PRIVATE drawbridge connection (which has
1787
+ // none) while the credential belongs to twilio (which has no manifest).
1788
+ // Platform SMS will remove that split the way it did for email.
1789
+ send: async ({ context, step, workflow }, { canSend, read } = {}) => {
1790
+ var _a, _b, _c;
1791
+ const to = (_a = context == null ? void 0 : context.phone) == null ? void 0 : _a.number;
1792
+ if (!to) throw new Error("No phone number on context (context.phone.number is required)");
1793
+ const request2 = { to };
1794
+ const connection2 = await read.get({
1795
+ collection: "connection",
1796
+ query: { organization: workflow.organization, slug: "twilio", status: "active" }
1797
+ });
1798
+ if (!connection2) return { message: "No active Twilio SMS connection \u2014 workflow-step SMS skipped.", request: request2, response: { skipped: true }, skipped: true };
1799
+ const { ok: sendable } = await canSend({ channel: "sms", to: context.phone });
1800
+ if (!sendable) return { message: "Recipient has opted out \u2014 skipped.", request: request2, response: { skipped: true }, skipped: true };
1801
+ return {
1802
+ message: "SMS queued for delivery to " + to + " via twilio.",
1803
+ request: request2,
1804
+ response: { provider: "twilio", queued: true },
1805
+ // QUEUES rather than sends: queue/notification.js owns delivery, the
1806
+ // carrier opt-out line and the segment count this is billed on.
1807
+ writes: [
1808
+ queueNotification({
1809
+ connection: connection2.id,
1810
+ message: interpolate((_b = step.settings) == null ? void 0 : _b.message, context),
1811
+ organization: workflow.organization,
1812
+ send: { phone: { number: to }, type: "phone" },
1813
+ title: interpolate((_c = step.settings) == null ? void 0 : _c.subject, context),
1814
+ workflow: workflow.id
1815
+ })
1816
+ ]
1817
+ };
1818
+ }
1819
+ },
1820
+ webhook: false
1821
+ },
1822
+ icon: drawbridge_default,
1823
+ // PRIVATE: never in the catalog, always available to the builder.
1824
+ private: true,
1825
+ // NOTHING, and HUBSPOT_ACCESS_TOKEN in particular must not be here.
1826
+ //
1827
+ // `requires` gates AVAILABILITY: a name in it that is unset removes the whole
1828
+ // connection. This one is private and contributes every base workflow step —
1829
+ // email.send, sms.send, segment.sync — so gating it on a CRM token would take
1830
+ // all of them away from any deployment without a HubSpot portal, to protect a
1831
+ // sync that is best-effort and already no-ops without a token.
1832
+ //
1833
+ // The test 'a vendor is only available when its environment is configured'
1834
+ // caught exactly that: availableConnections({}) went from [ 'drawbridge' ] to
1835
+ // empty the moment this was added.
1836
+ requires: [],
1837
+ slug: "drawbridge",
1838
+ // Always on. There is no credential that could go bad and no configuration a
1839
+ // merchant could leave half-finished.
1840
+ status: () => "active",
1841
+ // DERIVED FROM drawbridge-api/lib/workflows.js, not invented. Every value
1842
+ // below — trigger, billable, settings — is what that catalog and the workflow
1843
+ // route already enforce today, because this replaces them rather than
1844
+ // competing with them.
1845
+ //
1846
+ // NOT HERE, deliberately:
1847
+ //
1848
+ // step.segment.sync a SYSTEM step, dispatched by drawbridge-sync rather
1849
+ // than offered in the builder. It fans out, so the shell
1850
+ // opens its step document and the chunks close it.
1851
+ steps: {
1852
+ email: {
1853
+ // SCHEDULE-TRIGGERED, not lead-triggered: it is offered under Daily,
1854
+ // Weekly and Monthly. Those triggers had offered no steps at all, so a
1855
+ // scheduled workflow was selectable and inert until this landed.
1856
+ digest: () => ({
1857
+ hook: "email.digest",
1858
+ key: "Email \u2014 Digest",
1859
+ queue: "notification",
1860
+ settings: {
1861
+ // The organization OWNER is always a recipient, resolved by the
1862
+ // hook, so this is additional recipients rather than the list. It
1863
+ // cannot be required: the members endpoint is owner-gated and the
1864
+ // owner is not a member document, so a solo merchant has nothing to
1865
+ // pick and could never save the step.
1866
+ members: { of: "string", type: "array" },
1867
+ message: { required: true, type: "string" },
1868
+ subject: { required: true, type: "string" }
1869
+ },
1870
+ triggers: ["schedule.day", "schedule.week", "schedule.month"],
1871
+ usage: { actions: 0 }
1872
+ }),
1873
+ // To organization MEMBERS. Never suppressed — an entrant's opt-out must
1874
+ // not silence an alert to staff — and not billed.
1875
+ notify: () => ({
1876
+ hook: "email.notify",
1877
+ key: "Email \u2014 Notification",
1878
+ queue: "notification",
1879
+ settings: {
1880
+ members: { of: "string", type: "array" },
1881
+ message: { required: true, type: "string" },
1882
+ subject: { required: true, type: "string" }
1883
+ },
1884
+ triggers: ["lead.insert"],
1885
+ // Zero is a PRICE, and a deliberate one. Declared rather than omitted
1886
+ // so "this is free" and "nobody decided" stay different statements;
1887
+ // completeStep bills only when actions > 0.
1888
+ usage: { actions: 0 }
1889
+ }),
1890
+ // To a LEAD. Suppression applies and the send is billed.
1891
+ send: () => ({
1892
+ hook: "email.send",
1893
+ key: "Email \u2014 Send email",
1894
+ queue: "notification",
1895
+ settings: {
1896
+ message: { required: true, type: "string" },
1897
+ subject: { required: true, type: "string" }
1898
+ },
1899
+ triggers: ["lead.insert"],
1900
+ // ONE SOURCE FOR THE PRICE. lib/pricing.js is the index of every
1901
+ // customer-facing number; the handler read it too, so the same fact
1902
+ // was stated in two places and only one of them was reviewed.
1903
+ usage: { actions: channels.email.actionsPerSend }
1904
+ })
1905
+ },
1906
+ // WITHDRAWN, which is a third thing from builder and system: declared,
1907
+ // routed and runnable, but never offered.
1908
+ //
1909
+ // It went when the twilio connection did — a connection-gated step with no
1910
+ // connection to gate on could only ever render permanently disabled. Stored
1911
+ // workflows still carry it, so it must keep running, and enums.step.type
1912
+ // keeps it for the same reason.
1913
+ //
1914
+ // NO TRIGGERS is what keeps it out of the builder: the catalog derives from
1915
+ // triggers, so a step with none is unreachable by a merchant without a
1916
+ // second list saying so.
1917
+ //
1918
+ // Platform SMS returns as a base step the way email did. That is this entry
1919
+ // gaining triggers, not a new one.
1920
+ sms: {
1921
+ send: () => ({
1922
+ hook: "sms.send",
1923
+ key: "Send an SMS",
1924
+ queue: "notification",
1925
+ settings: {
1926
+ message: { required: true, type: "string" },
1927
+ subject: { required: true, type: "string" }
1928
+ },
1929
+ // Priced per SEGMENT and billed from the first, which the send
1930
+ // resolves from the message length. This is the floor.
1931
+ usage: { actions: channels.sms.actionsPerSegment },
1932
+ withdrawn: true
1933
+ })
1934
+ },
1935
+ segment: {
1936
+ // FANS OUT. It evaluates every contact in the organization against every
1937
+ // segment, which is too much for one job — so the hook returns chunks and
1938
+ // the shell defers completion: openStep writes the document with a slot
1939
+ // per chunk, and whichever chunk lands last closes it and resumes the
1940
+ // chain.
1941
+ //
1942
+ // It carries a hook like every other step. An earlier version declared
1943
+ // none, on the theory that fan-out was a second protocol the shell could
1944
+ // not run; it is the same protocol with the ending deferred, and a step
1945
+ // declaring no hook is silently SKIPPED by the runner.
1946
+ sync: () => ({
1947
+ description: "Recalculates segment membership on a daily schedule.",
1948
+ hook: "segment.sync",
1949
+ key: "Segment Sync",
1950
+ queue: "segment",
1951
+ system: true
1952
+ })
1953
+ }
1954
+ },
1955
+ tasks: () => [],
1956
+ title: "Drawbridge"
1957
+ };
1958
+
1959
+ // lib/connections/icons/klaviyo.js
1960
+ var klaviyo_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
1961
+ <rect width="500" height="500" fill="white"/>
1962
+ <path d="M365.047 327.038H134.954V172.964H365.047L316.856 250.001L365.047 327.038Z" fill="#232121"/>
1963
+ </svg>`;
1964
+
1965
+ // lib/connections/providers/klaviyo.js
1966
+ var api = async (path, { fetcher = fetch, method = "GET", payload, token }) => {
1967
+ const response = await fetcher("https://a.klaviyo.com/api" + path, {
1968
+ ...payload && { body: JSON.stringify(payload) },
1969
+ headers: {
1970
+ // Bearer, not Klaviyo-API-Key — that header is for private keys, and
1971
+ // sending it with an OAuth token fails in a way that reads like a bad
1972
+ // token rather than a bad scheme.
1973
+ authorization: "Bearer " + token,
1974
+ ...payload && { "content-type": "application/json" },
1975
+ // Klaviyo pins its API by DATE. A request without this header is
1976
+ // refused, and one with an old date keeps the response shape that date
1977
+ // shipped with — which is the point: bumping it is a deliberate act
1978
+ // with a changelog to read, not something that drifts under us.
1979
+ revision: "2026-07-15"
1980
+ },
1981
+ method,
1982
+ signal: AbortSignal.timeout(15e3)
1983
+ });
1984
+ if (!response.ok) {
1985
+ throw Object.assign(
1986
+ new Error("Klaviyo refused the request (" + response.status + ")"),
1987
+ { status: response.status }
1988
+ );
1989
+ }
1990
+ return response.status === 204 ? null : response.json();
1991
+ };
1992
+ var klaviyo_default2 = {
1993
+ // OAuth 2.1, and PKCE is REQUIRED rather than recommended: Klaviyo refuses an
1994
+ // exchange without a code_verifier matching the challenge the consent
1995
+ // carried. Most vendors treat it as optional hardening; this one does not,
1996
+ // which is why it is a descriptor flag and not a global.
1997
+ //
1998
+ // HTTP Basic on the token endpoint is the other thing Klaviyo does
1999
+ // differently, and it says so in hooks.auth.token rather than as a flag here.
2000
+ auth: {
2001
+ oauth: {
2002
+ // NAMES the credentials holding OUR application's client — keys into
2003
+ // the stored provider credentials, not env vars. One identity,
2004
+ // every merchant — the token is the merchant's and arrives from their
2005
+ // own consent, which is what stops one organization reading another's
2006
+ // data.
2007
+ //
2008
+ client: {
2009
+ id: "KLAVIYO_OAUTH_CLIENT_ID",
2010
+ secret: "KLAVIYO_OAUTH_CLIENT_SECRET"
2011
+ },
2012
+ // Klaviyo drops a refresh token after 90 days of NON-USE. The vendor
2013
+ // never mentions this at runtime — you discover it when a refresh fails
2014
+ // on a connection nobody touched — so it is declared, and it is why
2015
+ // auth.probe has to run on a schedule rather than only before a call.
2016
+ //
2017
+ // Token lifetime is NOT declared: the vendor states it on every
2018
+ // exchange, and a copy here would be a second answer that goes stale.
2019
+ expiry: 90 * 24 * 60 * 60,
2020
+ pkce: true,
2021
+ // Space separated. accounts:read is required by Klaviyo on every app
2022
+ // and must stay in the list; the rest are what a contact sync needs.
2023
+ scopes: "accounts:read lists:read lists:write profiles:read profiles:write",
2024
+ // EVERY VENDOR URL, in one place. `revoke` used to be a literal inside
2025
+ // the disconnect hook — three vendor addresses, two of them declared,
2026
+ // which is exactly the kind of split that goes unnoticed.
2027
+ urls: {
2028
+ // TWO DIFFERENT HOSTS, and swapping them fails in opposite ways.
2029
+ //
2030
+ // authorize is a page a HUMAN loads, and it lives on www. Pointing it
2031
+ // at a.klaviyo.com — their API host — sends the merchant somewhere
2032
+ // that never renders a consent screen, so the journey stalls with no
2033
+ // error anybody can see.
2034
+ //
2035
+ // token and revoke are server calls and must stay on a.klaviyo.com:
2036
+ // Klaviyo began blocking OAuth token traffic through www on
2037
+ // 2025-03-31, so the mirror image of this mistake breaks the exchange
2038
+ // instead of the consent.
2039
+ authorize: "https://www.klaviyo.com/oauth/authorize",
2040
+ // WHERE THE MERCHANT LANDS — the dashboard, not drawbridge-api. The
2041
+ // `/api/` segment is Next's route-handler convention, which reads as
2042
+ // the api service to everyone who sees it; it is not, and the route
2043
+ // has never moved. build() pins it against the one callback route
2044
+ // that exists, because declared-but-wrong fails AFTER consent — a
2045
+ // 404 for someone who has already granted access.
2046
+ //
2047
+ // Registered in Klaviyo's own app settings, and they refuse anything
2048
+ // that does not byte-match, so it is a fact about someone else's
2049
+ // records rather than a string this code computes.
2050
+ redirect: "/api/connection/klaviyo/callback",
2051
+ revoke: "https://a.klaviyo.com/oauth/revoke",
2052
+ token: "https://a.klaviyo.com/oauth/token"
2053
+ }
2054
+ },
2055
+ type: "oauth"
2056
+ },
2057
+ // EVERYTHING A MERCHANT READS. Grouped by who it is for rather than by what
2058
+ // kind of sentence it is, so the question on the next vendor is "does a person
2059
+ // read this", which nobody gets wrong, instead of "is this marketing", which
2060
+ // someone will.
2061
+ //
2062
+ // `errors` is in here rather than at the top level, and that is not a
2063
+ // preference. The connection DOCUMENT carries its own `errors` array of
2064
+ // scope-drift entries, and the document is spread OVER the resolved manifest
2065
+ // downstream — so a top-level `errors` here would be silently replaced by that
2066
+ // array and this copy would never render. `fields`/`settings` already carry a
2067
+ // comment about the same collision.
2068
+ content: {
2069
+ // Shown at disconnect, so it says what is lost and what is not.
2070
+ confirm: "Disconnecting revokes Drawbridge's access to your Klaviyo account. Your profiles and lists stay in both Klaviyo and Drawbridge \u2014 neither is deleted.",
2071
+ description: [
2072
+ "Connecting Klaviyo lets Drawbridge sync the contacts your campaigns collect into a Klaviyo list, so the people who enter a giveaway can be marketed to alongside the rest of your audience.",
2073
+ "You authorize Drawbridge from inside Klaviyo and can revoke that access there at any time. Drawbridge never sees or stores your Klaviyo password, and only asks for the permissions listed on the consent screen.",
2074
+ "Anyone who has opted out in Drawbridge is synced as unsubscribed rather than omitted, so a person who asked not to be contacted stays suppressed in both systems instead of quietly reappearing."
2075
+ ],
2076
+ // KEYED BY WHAT FAILED, not nested inside it. Errors are the thing most
2077
+ // likely to grow — resources.* has already earned somewhere to put "we
2078
+ // could not load your lists" — so a new area adds a key here rather than a
2079
+ // second errors object somewhere else.
2080
+ //
2081
+ // `connect` no longer exists as a container above: its only other member
2082
+ // was `redirect`, which moved to auth.oauth.urls with the rest of the
2083
+ // vendor's addresses.
2084
+ errors: {
2085
+ connect: {
2086
+ denied: "The Klaviyo authorization was declined, so nothing was connected.",
2087
+ invalid: "We couldn't complete the Klaviyo connection. Try connecting again."
2088
+ }
2089
+ },
2090
+ excerpt: "Sync the contacts your campaigns collect into a Klaviyo list.",
2091
+ // HOW TO CONNECT, in the merchant's words. Was `setup`, which nothing
2092
+ // rendered — four useful instructions no component displayed.
2093
+ guide: [
2094
+ "Press Connect. Drawbridge sends you to Klaviyo to approve access.",
2095
+ "Sign in to Klaviyo if you are not already, and choose the account to connect.",
2096
+ "Approve the permissions Klaviyo lists. You are returned here and the connection shows Active.",
2097
+ "You can revoke access at any time from Klaviyo, under Integrations."
2098
+ ]
2099
+ },
2100
+ // CAN A MERCHANT KEEP TWO OF THESE AT ONCE?
2101
+ //
2102
+ // Required, and false is a decision rather than a default. Shopify is
2103
+ // exclusive because a store maps to exactly one organization. Contact syncs
2104
+ // are destinations — someone can reasonably keep Klaviyo and Mailchimp both
2105
+ // current — so the exclusivity that once applied when these were SENDERS is
2106
+ // deliberately gone. That was removed once already; declaring it out loud is
2107
+ // what stops it coming back by inference.
2108
+ exclusive: false,
2109
+ feature: "organization:connection:klaviyo",
2110
+ fields: [
2111
+ {
2112
+ key: "account",
2113
+ label: "Klaviyo account"
2114
+ },
2115
+ {
2116
+ // The choices come from the merchant's own account, so the field names
2117
+ // the capability and the client composes the url.
2118
+ hook: "resources.audiences",
2119
+ input: "select",
2120
+ key: "list",
2121
+ label: "Klaviyo list",
2122
+ message: "Contacts your campaigns collect are synced into this list.",
2123
+ required: true,
2124
+ // Klaviyo's list endpoint carries no name filter, so the hook can only
2125
+ // match what it already fetched. A search box that searches one page is
2126
+ // worse than none, so the picker does not offer one.
2127
+ search: false
2128
+ }
2129
+ ],
2130
+ // WHAT KIND OF THING THIS IS. One field, not two — `category` said the same
2131
+ // thing and was read by nothing, while `group` was quietly doing double duty
2132
+ // as the mutual-exclusion key. The exclusion moved to `exclusive` above, so
2133
+ // this is purely how a connection is grouped and labelled.
2134
+ group: "contacts",
2135
+ // Nothing typed at connect. The consent returns the grant, and the account it
2136
+ // belongs to is read back from Klaviyo rather than asked for.
2137
+ hooks: {
2138
+ auth: {
2139
+ // Turn a fresh grant into settings worth showing. Without this the card
2140
+ // renders an empty "Klaviyo account" field, because the merchant is
2141
+ // never asked which account they connected — the consent already
2142
+ // decided it, and asking again would be a question we can answer.
2143
+ connect: async ({ tokens }, { fetcher } = {}) => {
2144
+ var _a, _b, _c;
2145
+ const body = await api("/accounts", { fetcher, token: tokens.accessToken });
2146
+ const account = (_a = body == null ? void 0 : body.data) == null ? void 0 : _a[0];
2147
+ return {
2148
+ account: ((_c = (_b = account == null ? void 0 : account.attributes) == null ? void 0 : _b.contact_information) == null ? void 0 : _c.organization_name) || (account == null ? void 0 : account.id) || null,
2149
+ accountId: (account == null ? void 0 : account.id) || null
2150
+ };
2151
+ },
2152
+ // Revoke at KLAVIYO, not just locally. Forgetting our copy leaves the
2153
+ // grant live in the merchant's account, so a disconnect that looks
2154
+ // complete here still shows Drawbridge with access over there.
2155
+ //
2156
+ // Basic auth with our client, exactly like the token exchange — the
2157
+ // token being revoked is the subject, not the credential.
2158
+ disconnect: async ({ clientId, clientSecret, manifest, settings }, { fetcher = fetch } = {}) => {
2159
+ const token = (settings == null ? void 0 : settings.refreshToken) || (settings == null ? void 0 : settings.accessToken);
2160
+ if (!token) return { revoked: false };
2161
+ const response = await fetcher(manifest.auth.oauth.urls.revoke, {
2162
+ body: new URLSearchParams({
2163
+ token,
2164
+ token_type_hint: (settings == null ? void 0 : settings.refreshToken) ? "refresh_token" : "access_token"
2165
+ }),
2166
+ headers: {
2167
+ authorization: "Basic " + Buffer.from(clientId + ":" + clientSecret).toString("base64"),
2168
+ "content-type": "application/x-www-form-urlencoded"
2169
+ },
2170
+ method: "POST",
2171
+ signal: AbortSignal.timeout(15e3)
2172
+ });
2173
+ return { revoked: response.ok };
2174
+ },
2175
+ // THE MINT IS THE PROBE. Asking "is this token still good" by
2176
+ // inspecting what we stored answers the wrong question — a grant
2177
+ // revoked inside Klaviyo still looks perfect in our database. Spending
2178
+ // the refresh token is the only thing that asks Klaviyo.
2179
+ //
2180
+ // It also keeps the grant warm against the 90-day idle window above.
2181
+ probe: async ({ clientId, clientSecret, manifest, settings }, { fetcher } = {}) => {
2182
+ const token = await accessToken({
2183
+ clientId,
2184
+ clientSecret,
2185
+ fetcher,
2186
+ // Mint even if the stored token still looks good — a probe that
2187
+ // short-circuits never reaches Klaviyo and reports healthy on a
2188
+ // grant revoked an hour ago.
2189
+ force: true,
2190
+ manifest,
2191
+ settings
2192
+ });
2193
+ return { ok: Boolean(token) };
2194
+ },
2195
+ // Klaviyo scopes are fixed at app level and re-consented, not drifted.
2196
+ scopes: false,
2197
+ // KLAVIYO REQUIRES HTTP BASIC on the token endpoint and rejects the same
2198
+ // client_id/client_secret pair as body fields. Everything else about the
2199
+ // request is standard, so this is the shared implementation told the one
2200
+ // thing that differs — in Klaviyo's own file, beside the rest of what
2201
+ // makes Klaviyo unusual, rather than as a flag a caller has to know to
2202
+ // read.
2203
+ token: (args) => authToken({ ...args, basic: true })
2204
+ },
2205
+ // No commerce here. Klaviyo tracks orders, but Drawbridge's order data comes
2206
+ // from the store that took the money — a second source for the same event
2207
+ // is two answers to "did this person buy", and the one we can bill from is
2208
+ // the store's.
2209
+ commerce: false,
2210
+ // The verb the contacts.sync step points at. It does the work — including
2211
+ contacts: {
2212
+ // Not yet. Suppression syncs an opt-out as unsubscribed, which is a
2213
+ // different thing from deleting the profile.
2214
+ remove: false,
2215
+ sync: async ({ contact, lead, settings, suppressed, token }, { fetcher } = {}) => {
2216
+ var _a, _b, _c;
2217
+ const list = settings == null ? void 0 : settings.list;
2218
+ if (!list) return { message: "No Klaviyo list is chosen for this connection.", skipped: true };
2219
+ const email = ((_b = (_a = lead == null ? void 0 : lead.canonical) == null ? void 0 : _a.email) == null ? void 0 : _b.value) || (lead == null ? void 0 : lead.email);
2220
+ if (!email) return { message: "That lead has no email address to sync.", skipped: true };
2221
+ const totals = (contact == null ? void 0 : contact.totals) || {};
2222
+ const profile = await api("/profiles/", {
2223
+ fetcher,
2224
+ method: "POST",
2225
+ payload: {
2226
+ data: {
2227
+ attributes: {
2228
+ email,
2229
+ ...(lead == null ? void 0 : lead.name) && { first_name: String(lead.name).trim().split(/\s+/)[0] },
2230
+ properties: {
2231
+ drawbridge_campaigns: ((contact == null ? void 0 : contact.campaigns) || []).length,
2232
+ drawbridge_draws: totals.draws || 0,
2233
+ drawbridge_entries: totals.entries || 0,
2234
+ drawbridge_orders: totals.orders || 0,
2235
+ // Campaign-attributed, NOT lifetime. A merchant running
2236
+ // Shopify already has lifetime revenue in Klaviyo through
2237
+ // Klaviyo's own integration; what only we can say is how
2238
+ // much a campaign drove. Named so the two cannot be
2239
+ // mistaken for one another in a segment builder.
2240
+ drawbridge_revenue: totals.gross || 0
2241
+ }
2242
+ },
2243
+ type: "profile"
2244
+ }
2245
+ },
2246
+ token
2247
+ });
2248
+ const profileId = (_c = profile == null ? void 0 : profile.data) == null ? void 0 : _c.id;
2249
+ if (!profileId) return { message: "Klaviyo returned no profile id.", skipped: true };
2250
+ await api("/profile-subscription-bulk-create-jobs/", {
2251
+ fetcher,
2252
+ method: "POST",
2253
+ payload: {
2254
+ data: {
2255
+ attributes: {
2256
+ profiles: {
2257
+ data: [{
2258
+ attributes: {
2259
+ email,
2260
+ subscriptions: {
2261
+ email: { marketing: { consent: suppressed ? "UNSUBSCRIBED" : "SUBSCRIBED" } }
2262
+ }
2263
+ },
2264
+ type: "profile"
2265
+ }]
2266
+ }
2267
+ },
2268
+ relationships: { list: { data: { id: list, type: "list" } } },
2269
+ type: "profile-subscription-bulk-create-job"
2270
+ }
2271
+ },
2272
+ token
2273
+ });
2274
+ return {
2275
+ // Merged into `context` for later steps in this run.
2276
+ context: { klaviyoProfileId: profileId },
2277
+ message: suppressed ? "Synced to Klaviyo as unsubscribed \u2014 this contact has opted out." : "Synced to the Klaviyo list.",
2278
+ // Recorded on the run for support to read back, not a write
2279
+ // instruction — the hook has already written what it needed to.
2280
+ response: { klaviyoProfileId: profileId }
2281
+ };
2282
+ }
2283
+ },
2284
+ // A WHOLE DOMAIN CAN DECLINE AT ONCE. Klaviyo sends us nothing and we
2285
+ // register nothing with it, so listing four falses would be noise around a
2286
+ // single decision. Still explicit — absence would not say whether anybody
2287
+ // considered it.
2288
+ // Drawbridge sends its own notification email and SMS, and owns its own
2289
+ // segments — see the private `drawbridge` manifest. A vendor answering
2290
+ // these would be a second sender, which is the arrangement the platform
2291
+ // sender replaced.
2292
+ email: false,
2293
+ segment: false,
2294
+ sms: false,
2295
+ inbound: false,
2296
+ // Nothing to set up or tear down at the vendor: the grant is the whole
2297
+ // integration, and revoking it is auth.disconnect's job.
2298
+ lifecycle: false,
2299
+ resources: {
2300
+ // The lists a merchant can sync into, for the picker on their
2301
+ // connection.
2302
+ //
2303
+ // PAGINATED DELIBERATELY. Klaviyo caps page[size] at 10 and defaults to
2304
+ // it, so one call quietly returns the first ten lists and an account
2305
+ // with more shows a picker missing the one they wanted, with nothing to
2306
+ // indicate anything was cut.
2307
+ audiences: async ({ cursor, limit = 100, search, token }, { fetcher } = {}) => {
2308
+ var _a, _b;
2309
+ const audiences = [];
2310
+ let next = cursor ? "/lists?page%5Bsize%5D=10&page%5Bcursor%5D=" + encodeURIComponent(cursor) : "/lists?page%5Bsize%5D=10";
2311
+ let pages = 0;
2312
+ while (next && audiences.length < limit && pages < 20) {
2313
+ const body = await api(next, { fetcher, token });
2314
+ for (const list of (body == null ? void 0 : body.data) || []) {
2315
+ audiences.push({ id: list.id, title: ((_a = list == null ? void 0 : list.attributes) == null ? void 0 : _a.name) || list.id });
2316
+ }
2317
+ const link = (_b = body == null ? void 0 : body.links) == null ? void 0 : _b.next;
2318
+ next = link ? String(link).replace(/^https:\/\/a\.klaviyo\.com\/api/, "") : null;
2319
+ pages = pages + 1;
2320
+ }
2321
+ const term = String((search == null ? void 0 : search.value) || "").trim().toLowerCase();
2322
+ return {
2323
+ items: term ? audiences.filter((entry) => entry.title.toLowerCase().includes(term)) : audiences,
2324
+ pageInfo: {
2325
+ endCursor: next,
2326
+ hasNextPage: Boolean(next)
2327
+ }
2328
+ };
2329
+ },
2330
+ // Klaviyo sells no products and mints no discount codes.
2331
+ prices: false,
2332
+ products: false,
2333
+ promotions: false
2334
+ },
2335
+ // Drawbridge posts to a merchant's own endpoint, never through a vendor.
2336
+ webhook: false
2337
+ },
2338
+ icon: klaviyo_default,
2339
+ requires: [
2340
+ "KLAVIYO_OAUTH_CLIENT_ID",
2341
+ "KLAVIYO_OAUTH_CLIENT_SECRET"
2342
+ ],
2343
+ slug: "klaviyo",
2344
+ // ONE OF THE FOUR STATES AND NOTHING ELSE — the reason sits in `tasks`, which
2345
+ // is already the merchant-facing copy channel and is already rendered.
2346
+ //
2347
+ // A grant with no list chosen is authenticated and useless. The list cannot be
2348
+ // part of the consent flow — enumerating lists needs the token the consent
2349
+ // returns — so it is always a second step, and the card must say Pending
2350
+ // rather than Active over nothing.
2351
+ //
2352
+ // Otherwise the credential's own verdict stands. A manifest can only ever
2353
+ // DOWNGRADE: it can see the settings, and it cannot see whether the grant was
2354
+ // revoked at Klaviyo an hour ago.
2355
+ //
2356
+ // Computed at read time rather than written, for the same reason
2357
+ // shopifyMissingScopes is: it becomes true the moment a merchant clears the
2358
+ // list, without waiting for something to notice and write it down.
2359
+ status: (data2) => {
2360
+ var _a;
2361
+ return ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.list) ? data2.status : "pending";
2362
+ },
2363
+ steps: {
2364
+ contacts: {
2365
+ // A DECLARATION, not the work. It names the hook that does the work, and
2366
+ // says where that hook's values belong. Nested like the hooks, and the
2367
+ // nesting IS the name: this is `step.contacts.sync`, which is what a
2368
+ // workflow document stores.
2369
+ //
2370
+ // A function, so it can depend on what this deployment or this
2371
+ // merchant's connection knows — a static object would have to be true
2372
+ // for every deployment at publish time.
2373
+ sync: ({ data: data2 }) => {
2374
+ var _a;
2375
+ return {
2376
+ hook: "contacts.sync",
2377
+ // The account the merchant actually connected, read back by
2378
+ // auth.connect. The builder reads "Sync contact to Acme Co" rather
2379
+ // than a label that could be any of their Klaviyo accounts.
2380
+ key: "Sync contact to " + (((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.account) || "Klaviyo"),
2381
+ queue: "connection",
2382
+ // Nothing for a merchant to configure on the step itself — the list
2383
+ // is chosen once on the connection. Declared empty rather than
2384
+ // omitted, so "this step takes no settings" and "nobody thought about
2385
+ // settings" are different statements.
2386
+ settings: {},
2387
+ // BOTH triggers. lead.insert alone only ever fires for someone with
2388
+ // no history yet — a brand-new entrant has no orders and no revenue,
2389
+ // so a profile written then carries an email and nothing else.
2390
+ // Crossing into a segment is the moment the ranking data exists.
2391
+ triggers: ["lead.insert", "segment.contact.add"],
2392
+ // One source for cost: what the builder discloses before a merchant
2393
+ // adds this step, and what is charged when it runs.
2394
+ usage: { actions: 1 }
2395
+ };
2396
+ }
2397
+ }
2398
+ },
2399
+ // WHY, in the merchant's words, and what to do about it.
2400
+ tasks: (data2) => {
2401
+ var _a;
2402
+ return ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.list) ? [] : [
2403
+ {
2404
+ message: "Choose which Klaviyo list your contacts should sync into. Until you do, nothing is being synced.",
2405
+ title: "Choose a list"
2406
+ }
2407
+ ];
2408
+ },
2409
+ title: "Klaviyo"
2410
+ };
2411
+
2412
+ // lib/connections/icons/mailchimp.js
2413
+ var mailchimp_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
2414
+ <rect width="500" height="500" fill="#FFE01B"/>
2415
+ <path d="M310.633 243.561C312.49 243.336 314.249 243.308 315.882 243.561C316.81 241.394 316.979 237.665 316.149 233.598C314.882 227.561 313.18 223.917 309.662 224.508C306.13 225.071 305.989 229.433 307.269 235.47C307.973 238.847 309.24 241.746 310.633 243.561ZM280.392 248.332C282.925 249.429 284.473 250.147 285.05 249.542C285.458 249.148 285.345 248.36 284.74 247.375C283.112 245.042 280.844 243.229 278.211 242.154C275.397 240.982 272.328 240.556 269.301 240.916C266.274 241.275 263.391 242.41 260.93 244.209C259.256 245.447 257.666 247.15 257.863 248.191C257.961 248.515 258.186 248.782 258.777 248.895C260.17 249.049 265.025 246.587 270.64 246.249C274.608 245.968 277.859 247.206 280.392 248.332ZM275.312 251.216C272.047 251.737 270.232 252.807 269.078 253.848C268.079 254.72 267.488 255.649 267.488 256.339L267.741 256.93L268.262 257.127C269.008 257.127 270.668 256.479 270.668 256.479C275.228 254.861 278.253 255.044 281.25 255.382C282.897 255.579 283.671 255.663 284.037 255.1C284.135 254.931 284.29 254.608 283.938 254.059C283.15 252.778 279.843 250.682 275.312 251.216ZM300.416 261.855C302.654 262.953 305.102 262.502 305.904 260.884C306.735 259.266 305.567 257.056 303.329 255.973C301.106 254.861 298.643 255.283 297.841 256.902C297.039 258.52 298.207 260.757 300.416 261.855ZM314.742 249.317C312.94 249.289 311.449 251.259 311.393 253.764C311.35 256.254 312.8 258.281 314.615 258.295C316.43 258.323 317.922 256.339 317.964 253.862C318.006 251.385 316.571 249.359 314.742 249.317ZM193.103 294.108C192.653 293.545 191.907 293.7 191.189 293.897C190.683 293.995 190.12 294.136 189.515 294.122C188.909 294.134 188.308 293.998 187.767 293.726C187.225 293.454 186.757 293.054 186.405 292.56C185.575 291.294 185.617 289.394 186.546 287.241L186.968 286.27C188.431 283.019 190.838 277.559 188.122 272.367C187.234 270.534 185.908 268.948 184.261 267.75C182.614 266.553 180.697 265.78 178.679 265.5C176.772 265.256 174.835 265.469 173.026 266.123C171.218 266.776 169.591 267.85 168.28 269.257C164.284 273.661 163.679 279.684 164.439 281.823C164.734 282.611 165.184 282.822 165.494 282.864C166.169 282.963 167.169 282.456 167.802 280.754L167.999 280.219C168.28 279.318 168.801 277.63 169.659 276.307C170.717 274.689 172.375 273.558 174.267 273.162C176.159 272.766 178.131 273.138 179.749 274.196C182.563 276.039 183.619 279.473 182.423 282.752C181.803 284.455 180.804 287.691 181.015 290.351C181.466 295.74 184.815 297.907 187.77 298.175C190.669 298.273 192.695 296.655 193.216 295.459C193.511 294.713 193.258 294.277 193.103 294.108Z" fill="#231E15"/>
2416
+ <path d="M360.476 284.243C360.35 283.835 359.618 281.204 358.647 278.052L356.621 272.648C360.575 266.696 360.645 261.405 360.124 258.393C359.531 254.519 357.693 250.944 354.89 248.205C351.766 244.94 345.363 241.563 336.385 239.044L331.671 237.736C331.643 237.524 331.418 226.619 331.235 221.933C331.08 218.555 330.798 213.264 329.152 208.058C327.182 200.993 323.791 194.858 319.527 190.876C331.277 178.717 338.594 165.307 338.58 153.81C338.538 131.703 311.379 124.976 277.902 138.851L270.824 141.863C270.795 141.835 258.004 129.283 257.821 129.128C219.63 95.8334 100.327 228.476 138.49 260.687L146.835 267.737C144.581 273.775 143.781 280.259 144.499 286.664C145.414 295.543 149.973 304.029 157.375 310.6C164.411 316.82 173.684 320.788 182.648 320.774C197.494 354.998 231.408 375.965 271.175 377.161C313.842 378.427 349.641 358.403 364.67 322.435C365.641 319.916 369.806 308.546 369.806 298.513C369.792 288.409 364.093 284.229 360.476 284.243ZM185.913 311.149C184.613 311.381 183.293 311.48 181.973 311.445C169.083 311.079 155.166 299.483 153.787 285.735C152.253 270.537 160.02 258.829 173.783 256.071C175.415 255.72 177.414 255.537 179.552 255.635C187.264 256.085 198.606 261.996 201.209 278.784C203.517 293.63 199.858 308.785 185.913 311.149ZM171.545 246.953C163.179 248.499 155.744 253.244 150.817 260.18C148.045 257.873 142.909 253.426 142.008 251.681C134.635 237.693 150.043 210.478 160.823 195.111C187.405 157.145 229.086 128.424 248.393 133.603C251.517 134.503 261.902 146.563 261.902 146.563C261.902 146.563 242.623 157.244 224.724 172.16C200.646 190.735 182.423 217.697 171.545 246.953ZM306.792 305.464C306.937 305.403 307.057 305.295 307.134 305.157C307.211 305.019 307.239 304.86 307.214 304.704C307.205 304.61 307.178 304.519 307.133 304.436C307.088 304.353 307.027 304.28 306.954 304.221C306.88 304.162 306.796 304.118 306.705 304.092C306.614 304.066 306.519 304.059 306.426 304.071C306.426 304.071 286.246 307.054 267.179 300.089C269.247 293.348 274.792 295.754 283.137 296.444C296.108 297.209 309.116 295.802 321.623 292.279C330.25 289.788 341.592 284.905 350.401 277.953C353.384 284.497 354.425 291.674 354.425 291.674C354.425 291.674 356.719 291.265 358.647 292.447C360.476 293.573 361.799 295.895 360.898 301.89C359.027 313.119 354.271 322.224 346.235 330.611C341.236 336.036 335.277 340.492 328.659 343.754C324.983 345.691 321.151 347.32 317.205 348.623C286.964 358.487 256.006 347.638 246.029 324.321C245.224 322.535 244.556 320.691 244.03 318.804C239.781 303.438 243.383 285.032 254.655 273.408C255.372 272.676 256.09 271.804 256.09 270.706C256.09 269.806 255.499 268.835 255.007 268.131C251.066 262.418 237.374 252.666 240.132 233.795C242.088 220.23 253.951 210.689 265.012 211.252L267.826 211.421C272.611 211.702 276.79 212.307 280.73 212.49C287.344 212.758 293.268 211.801 300.304 205.947C302.683 203.949 304.582 202.246 307.791 201.711C308.128 201.627 308.973 201.359 310.647 201.416C312.365 201.485 314.032 202.015 315.474 202.949C321.103 206.693 321.905 215.783 322.214 222.439C322.383 226.225 322.848 235.414 322.988 238.031C323.354 244.054 324.944 244.912 328.125 245.954C329.94 246.573 331.615 246.995 334.077 247.713C341.521 249.781 345.968 251.934 348.754 254.65C350.198 256.049 351.13 257.893 351.4 259.885C352.315 266.316 346.432 274.252 330.925 281.457C313.954 289.324 293.367 291.322 279.154 289.732L274.173 289.169C262.774 287.649 256.315 302.34 263.14 312.402C267.545 318.889 279.52 323.11 291.523 323.11C319.006 323.139 340.142 311.402 348.023 301.242L348.642 300.356C349.008 299.765 348.712 299.469 348.22 299.779C341.817 304.169 313.279 321.619 282.771 316.384C282.771 316.384 279.056 315.765 275.678 314.442C273.005 313.429 267.362 310.811 266.686 305.042C291.27 312.683 306.792 305.478 306.792 305.464ZM220.671 194.971C230.127 184.051 241.765 174.538 252.206 169.219C252.558 169.022 252.938 169.43 252.741 169.754C251.46 172 250.476 174.403 249.814 176.902C249.73 177.282 250.138 177.592 250.461 177.353C256.963 172.934 268.248 168.192 278.155 167.601C278.251 167.584 278.351 167.601 278.436 167.65C278.521 167.698 278.586 167.775 278.621 167.866C278.656 167.957 278.658 168.058 278.627 168.151C278.596 168.244 278.533 168.323 278.451 168.375C276.809 169.634 275.342 171.105 274.088 172.751C273.891 173.032 274.074 173.44 274.426 173.44C281.378 173.483 291.186 175.903 297.56 179.491C297.982 179.745 297.673 180.575 297.209 180.462C287.527 178.253 271.724 176.564 255.288 180.575C240.597 184.149 229.396 189.666 221.248 195.618C220.826 195.899 220.333 195.351 220.671 194.971Z" fill="#231E15"/>
2417
+ </svg>`;
2418
+
2419
+ // lib/connections/providers/mailchimp.js
2420
+ var base = (dc) => {
2421
+ if (!dc) throw new Error("This Mailchimp connection has no data centre stored, so there is no host to call");
2422
+ return "https://" + dc + ".api.mailchimp.com/3.0";
2423
+ };
2424
+ var mailchimp_default2 = {
2425
+ // OAUTH 2, authorization code. Every url below is quoted from
2426
+ // mailchimp.com/developer/marketing/guides/access-user-data-oauth-2/ rather
2427
+ // than remembered.
2428
+ //
2429
+ // THE METADATA CALL IS MAILCHIMP'S QUIRK and cannot be skipped: an access
2430
+ // token alone cannot call the Marketing API, because every account lives
2431
+ // behind a data-centre prefix (us1, us19...) that only GET
2432
+ // login.mailchimp.com/oauth2/metadata returns — and every subsequent request
2433
+ // needs it in the HOST. That is why auth.connect below is a real function:
2434
+ // the standard exchange does not know where to send anything afterwards.
2435
+ //
2436
+ // No PKCE. No scopes — the docs describe none. And no refresh token: "Mailchimp
2437
+ // Marketing access tokens do not expire, so you don't need to use a
2438
+ // refresh_token", so tokenSettings stores no expiry and isStale reads that as
2439
+ // nothing to refresh toward.
2440
+ //
2441
+ // auth.token stays false: the exchange is POST form-encoded with grant_type,
2442
+ // client_id, client_secret, redirect_uri and code, which is exactly the
2443
+ // runner's default — nothing to wrap.
2444
+ auth: {
2445
+ oauth: {
2446
+ client: {
2447
+ id: "MAILCHIMP_OAUTH_CLIENT_ID",
2448
+ secret: "MAILCHIMP_OAUTH_CLIENT_SECRET"
2449
+ },
2450
+ urls: {
2451
+ authorize: "https://login.mailchimp.com/oauth2/authorize",
2452
+ redirect: "/api/connection/mailchimp/callback",
2453
+ token: "https://login.mailchimp.com/oauth2/token"
2454
+ }
2455
+ },
2456
+ type: "oauth"
2457
+ },
2458
+ // EVERYTHING A MERCHANT READS. `errors` belongs in here rather than at the
2459
+ // top level because the connection DOCUMENT carries its own `errors` array
2460
+ // and the document is spread OVER the resolved manifest downstream — a
2461
+ // top-level one would be replaced by that array and never render.
2462
+ content: {
2463
+ confirm: "Disconnecting removes Drawbridge's stored Mailchimp access. You can also remove Drawbridge from the Authorized Apps page in your Mailchimp account. Your contacts stay in both Drawbridge and Mailchimp \u2014 neither list is deleted.",
2464
+ description: [
2465
+ "Drawbridge no longer sends email through Mailchimp. Notification email now sends from Drawbridge itself, and verifying a domain under Networking in your organization settings puts your own brand in the from line.",
2466
+ "This connection is becoming the way your Drawbridge contacts sync into a Mailchimp audience. Audience syncing is not live yet, so connecting today does nothing except choose the audience it will use when it ships."
2467
+ ],
2468
+ excerpt: "Sync your Drawbridge contacts into a Mailchimp audience.",
2469
+ guide: [
2470
+ "Press Connect. Drawbridge sends you to Mailchimp to approve access.",
2471
+ "Sign in to Mailchimp if you are not already, and choose the account to connect.",
2472
+ "You come back here to pick the audience your contacts should sync into."
2473
+ ]
2474
+ },
2475
+ // Mailchimp and SendGrid shared a group while they were SENDERS, where an org
2476
+ // picking two providers to send the same mail was meaningless. As contact
2477
+ // syncs they are destinations, and a merchant could reasonably keep several
2478
+ // up to date, so the exclusivity is gone.
2479
+ exclusive: false,
2480
+ feature: "organization:connection:mailchimp",
2481
+ fields: [
2482
+ {
2483
+ input: "select",
2484
+ key: "audience",
2485
+ label: "Mailchimp audience",
2486
+ message: "Contacts your campaigns collect are synced into this audience.",
2487
+ hook: "resources.audiences",
2488
+ required: true,
2489
+ // Mailchimp's /lists takes no name filter either — same reason.
2490
+ search: false
2491
+ }
2492
+ ],
2493
+ group: "contacts",
2494
+ // A HOOK'S VALUE IS ITS ANSWER. A key is stored and can be removed; nothing
2495
+ // else is built yet, because audience sync has not shipped. Every false here
2496
+ // is "not yet" rather than "never" — when the sync lands, probe and
2497
+ // contacts.sync are the first to flip.
2498
+ hooks: {
2499
+ auth: {
2500
+ // WHERE THE ACCOUNT LIVES. Not enrichment — without this the connection
2501
+ // is unusable, because the Marketing API host is per-account and only
2502
+ // this call knows it. The callback merges what this returns into the
2503
+ // stored settings, which is how `dc` reaches every later request.
2504
+ //
2505
+ // The header here is `OAuth <token>`, not Bearer — that is specific to
2506
+ // the metadata endpoint. Marketing API calls take Bearer; see the
2507
+ // audiences hook.
2508
+ connect: async ({ tokens }, { fetcher = fetch } = {}) => {
2509
+ const response = await fetcher("https://login.mailchimp.com/oauth2/metadata", {
2510
+ headers: {
2511
+ authorization: "OAuth " + (tokens == null ? void 0 : tokens.accessToken)
2512
+ },
2513
+ signal: AbortSignal.timeout(15e3)
2514
+ });
2515
+ if (!response.ok) {
2516
+ throw Object.assign(
2517
+ new Error("Mailchimp would not say which data centre this account is on (" + response.status + ")"),
2518
+ { status: response.status }
2519
+ );
2520
+ }
2521
+ const body = await response.json();
2522
+ if (!(body == null ? void 0 : body.dc)) throw new Error("Mailchimp returned no data centre for this account");
2523
+ return { dc: body.dc };
2524
+ },
2525
+ // Nothing to call. A merchant revokes Drawbridge from Mailchimp's own
2526
+ // Authorized Apps page; the docs describe no revocation endpoint for us
2527
+ // to call on their behalf.
2528
+ disconnect: false,
2529
+ probe: false,
2530
+ scopes: false,
2531
+ // The plain exchange. Mailchimp takes the client as FORM FIELDS
2532
+ // (grant_type, client_id, client_secret, redirect_uri, code), which is
2533
+ // the runner's default — so no `basic : true` as Klaviyo needs.
2534
+ //
2535
+ // build() requires an oauth manifest to name this explicitly rather than
2536
+ // letting it default, which caught this file declaring `false` on the
2537
+ // first import after the conversion.
2538
+ token: authToken
2539
+ },
2540
+ commerce: false,
2541
+ contacts: { remove: false, sync: false },
2542
+ // Drawbridge sends its own notification email and SMS, and owns its own
2543
+ // segments — see the private `drawbridge` manifest. A vendor answering
2544
+ // these would be a second sender, which is the arrangement the platform
2545
+ // sender replaced.
2546
+ email: false,
2547
+ segment: false,
2548
+ sms: false,
2549
+ inbound: false,
2550
+ lifecycle: false,
2551
+ resources: {
2552
+ // The audiences a merchant can sync into, for the picker on their
2553
+ // connection.
2554
+ //
2555
+ // count DEFAULTS TO 10 and maxes at 1000 (Mailchimp's own OpenAPI spec),
2556
+ // so leaving it unset returns the first ten audiences and looks entirely
2557
+ // successful — the same silent truncation Klaviyo has, at a different
2558
+ // number. Paged against total_items so an account past a thousand still
2559
+ // resolves.
2560
+ audiences: async ({ cursor, limit = 100, search, settings, token }, { fetcher = fetch } = {}) => {
2561
+ const dc = settings == null ? void 0 : settings.dc;
2562
+ const count = Math.min(limit, 1e3);
2563
+ const offset = Number(cursor || 0);
2564
+ const response = await fetcher(
2565
+ base(dc) + "/lists?count=" + count + "&offset=" + offset + "&fields=lists.id,lists.name,total_items",
2566
+ {
2567
+ headers: { authorization: "Bearer " + token },
2568
+ signal: AbortSignal.timeout(15e3)
2569
+ }
2570
+ );
2571
+ if (!response.ok) {
2572
+ throw Object.assign(
2573
+ new Error("Mailchimp refused the request (" + response.status + ")"),
2574
+ { status: response.status }
2575
+ );
2576
+ }
2577
+ const body = await response.json();
2578
+ const audiences = ((body == null ? void 0 : body.lists) || []).map((list) => ({ id: list.id, title: (list == null ? void 0 : list.name) || list.id }));
2579
+ const term = String((search == null ? void 0 : search.value) || "").trim().toLowerCase();
2580
+ const items = term ? audiences.filter((entry) => entry.title.toLowerCase().includes(term)) : audiences;
2581
+ const nextOffset = offset + count;
2582
+ const more = nextOffset < Number((body == null ? void 0 : body.total_items) || 0);
2583
+ return {
2584
+ items,
2585
+ pageInfo: {
2586
+ endCursor: more ? String(nextOffset) : null,
2587
+ hasNextPage: more
2588
+ }
2589
+ };
2590
+ },
2591
+ prices: false,
2592
+ products: false,
2593
+ promotions: false
2594
+ },
2595
+ // Drawbridge posts to a merchant's own endpoint, never through a vendor.
2596
+ webhook: false
2597
+ },
2598
+ icon: mailchimp_default,
2599
+ // The OAuth client this deployment registered. Without both, the vendor drops
2600
+ // out of availableConnections rather than offering a Connect button that
2601
+ // cannot complete.
2602
+ requires: [
2603
+ "MAILCHIMP_OAUTH_CLIENT_ID",
2604
+ "MAILCHIMP_OAUTH_CLIENT_SECRET"
2605
+ ],
2606
+ slug: "mailchimp",
2607
+ // A key with no audience chosen is authenticated and inert. Mailchimp also
2608
+ // needs its merge fields created on that audience before any Drawbridge total
2609
+ // can be written to a member — unlike Klaviyo, its custom fields are not
2610
+ // schemaless — so the audience must be picked before lifecycle.register has
2611
+ // anything to register against.
2612
+ status: (data2) => {
2613
+ var _a;
2614
+ return ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.audience) ? data2.status : "pending";
2615
+ },
2616
+ // No steps: audience sync has not shipped, so this vendor contributes nothing
2617
+ // to a workflow yet. An empty steps object is the honest declaration — the
2618
+ // catalog renders the connection, and no builder offers a step it cannot run.
2619
+ steps: {},
2620
+ tasks: (data2) => {
2621
+ var _a;
2622
+ return [
2623
+ ...((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.audience) ? [] : [
2624
+ {
2625
+ message: "Choose which Mailchimp audience your contacts should sync into. Until you do, nothing is being synced.",
2626
+ title: "Choose an audience"
2627
+ }
2628
+ ],
2629
+ {
2630
+ message: "Contact syncing to Mailchimp audiences has not shipped yet, and this connection no longer sends your email. Nothing is being sent to Mailchimp right now.",
2631
+ title: "Audience sync not available yet",
2632
+ type: "warning"
2633
+ }
2634
+ ];
2635
+ },
2636
+ title: "Mailchimp"
2637
+ };
2638
+
2639
+ // lib/connections/providers/shopify.js
2640
+ import { randomUUID } from "crypto";
2641
+ import { customAlphabet as customAlphabet2 } from "nanoid";
2642
+
2643
+ // lib/connections/icons/shopify.js
2644
+ var shopify_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
2645
+ <rect width="500" height="500" fill="white"/>
2646
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M309.524 407.192L308.799 128.423C306.921 126.545 303.258 127.112 301.827 127.531L292.29 130.487C291.113 126.613 289.585 122.854 287.726 119.258C280.959 106.337 271.069 99.5052 259.096 99.4866H259.059C258.259 99.4866 257.469 99.5609 256.67 99.626L256.577 99.6353C256.231 99.2089 255.871 98.7935 255.499 98.3897C250.293 92.8125 243.601 90.0889 235.588 90.3213C220.139 90.7675 204.755 101.941 192.271 121.786C183.487 135.757 176.823 153.298 174.917 166.878L144.493 176.313C135.542 179.129 135.263 179.408 134.082 187.858C133.199 194.253 109.766 375.69 109.766 375.69L306.159 409.692L309.524 407.192ZM245.181 103.065C242.569 101.346 239.511 100.546 235.885 100.621C212.033 101.308 191.23 138.611 185.923 163.467L208.771 156.384L212.851 155.119C215.845 139.336 223.355 122.957 233.181 112.416C236.616 108.639 240.671 105.477 245.172 103.065H245.181ZM224.145 151.615L256.94 141.446C257.042 132.894 256.112 120.252 251.836 111.329C247.282 113.207 243.452 116.497 240.7 119.444C233.329 127.373 227.315 139.466 224.155 151.615H224.145ZM267.211 138.267L282.455 133.536C280.02 125.616 274.238 112.342 262.517 110.111C266.161 119.527 267.099 130.431 267.211 138.267Z" fill="#95BF47"/>
2647
+ <path d="M353.528 149.156C352.356 149.063 329.657 148.709 329.657 148.709C329.657 148.709 310.666 130.249 308.789 128.362C308.062 127.691 307.141 127.268 306.158 127.153V409.64L391.257 388.456C391.257 388.456 356.53 153.366 356.307 151.758C356.199 151.075 355.866 150.448 355.361 149.976C354.856 149.505 354.216 149.216 353.528 149.156Z" fill="#5E8E3E"/>
2648
+ <path d="M258.993 193.019L249.103 230.052C249.103 230.052 238.079 225.023 225 225.85C205.833 227.059 205.628 239.171 205.824 242.21C206.865 258.756 250.376 262.381 252.821 301.171C254.745 331.688 236.656 352.574 210.592 354.21C179.313 356.19 162.089 337.711 162.089 337.711L168.716 309.472C168.716 309.472 186.052 322.569 199.921 321.686C208.993 321.119 212.228 313.738 211.903 308.514C210.536 286.921 175.102 288.185 172.862 252.695C170.985 222.811 190.57 192.554 233.803 189.821C250.46 188.762 258.993 193.028 258.993 193.028" fill="white"/>
2649
+ </svg>`;
2650
+
2651
+ // lib/connections/inbound.js
2652
+ import { createHmac, timingSafeEqual } from "crypto";
2653
+ var verifySignature = ({ body, descriptor, headers, secret }) => {
2654
+ if (!secret) {
2655
+ throw Object.assign(new Error("Missing webhook secret: " + descriptor.signature.secret), { status: 500 });
2656
+ }
2657
+ const provided = headers[descriptor.headers.signature];
2658
+ if (!provided) {
2659
+ throw Object.assign(new Error("Missing webhook signature"), { status: 401 });
2660
+ }
2661
+ const digest = createHmac(descriptor.signature.algorithm, secret).update(body).digest(descriptor.signature.encoding);
2662
+ const digestBuffer = Buffer.from(digest, descriptor.signature.encoding);
2663
+ const providedBuffer = Buffer.from(provided, descriptor.signature.encoding);
2664
+ if (digestBuffer.length !== providedBuffer.length || !timingSafeEqual(digestBuffer, providedBuffer)) {
2665
+ throw Object.assign(new Error("Invalid webhook signature"), { status: 401 });
2666
+ }
2667
+ return JSON.parse(body.toString());
2668
+ };
2669
+ var readEventHeader = ({ descriptor, headers }) => headers[descriptor.headers.event];
2670
+
2671
+ // lib/email.js
2672
+ var GMAIL_DOMAINS = /* @__PURE__ */ new Set(["gmail.com", "googlemail.com"]);
2673
+ var toCanonicalEmail = (value) => {
2674
+ if (!value || typeof value !== "string") return null;
2675
+ const email = value.trim().toLowerCase();
2676
+ const at = email.lastIndexOf("@");
2677
+ if (at < 1 || at === email.length - 1) return null;
2678
+ let local = email.slice(0, at);
2679
+ const domain = email.slice(at + 1);
2680
+ const plus = local.indexOf("+");
2681
+ if (plus > 0) local = local.slice(0, plus);
2682
+ if (GMAIL_DOMAINS.has(domain)) local = local.replaceAll(".", "");
2683
+ if (!local) return null;
2684
+ return local + "@" + domain;
2685
+ };
2686
+
2687
+ // lib/phone.js
2688
+ import { AsYouType, parsePhoneNumberFromString, isValidPhoneNumber } from "libphonenumber-js";
2689
+ var toE164 = (value, country) => {
2690
+ if (!value) return null;
2691
+ try {
2692
+ const parsed = parsePhoneNumberFromString(String(value), country);
2693
+ return parsed ? parsed.number : null;
2694
+ } catch {
2695
+ return null;
2696
+ }
2697
+ };
2698
+
2699
+ // lib/connections/providers/shopify.js
2700
+ var toLine = ({
2701
+ price,
2702
+ product_id: productId,
2703
+ quantity,
2704
+ title,
2705
+ variant_id: variantId,
2706
+ variant_title: variantTitle
2707
+ }) => ({
2708
+ price: parseFloat(price) || 0,
2709
+ productId: productId ? "gid://shopify/Product/" + productId : null,
2710
+ quantity: quantity || 1,
2711
+ title: title || null,
2712
+ variantId: variantId ? "gid://shopify/ProductVariant/" + variantId : null,
2713
+ variantTitle: variantTitle || null
2714
+ });
2715
+ var attributeLineItems = (lineItems = []) => lineItems.reduce(
2716
+ (acc, item) => {
2717
+ const attrs = (item.properties || []).reduce(
2718
+ (map, { name, value }) => {
2719
+ map[name] = value;
2720
+ return map;
2721
+ },
2722
+ {}
2723
+ );
2724
+ if (!attrs["_drwbrdg_ca"]) return acc;
2725
+ if (!Object.keys(acc.attrMap).length) acc.attrMap = attrs;
2726
+ const line = toLine(item);
2727
+ acc.attributedGross += line.price * line.quantity;
2728
+ acc.attributedLines.push(line);
2729
+ return acc;
2730
+ },
2731
+ { attrMap: {}, attributedGross: 0, attributedLines: [] }
2732
+ );
2733
+ var generateDiscountCode = customAlphabet2("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8);
2734
+ var REFRESH_TOKEN_FRESHNESS_BUFFER_MS = 5 * 24 * 60 * 60 * 1e3;
2735
+ var OAUTH_ERROR_SOURCE = "oauth";
2736
+ var OAUTH_GRANT_REVOKED_CODES = ["application_cannot_be_found", "invalid_grant"];
2737
+ var inbound = {
2738
+ headers: {
2739
+ event: "x-shopify-topic",
2740
+ id: "x-shopify-webhook-id",
2741
+ shop: "x-shopify-shop-domain",
2742
+ signature: "x-shopify-hmac-sha256"
2743
+ },
2744
+ signature: {
2745
+ algorithm: "sha256",
2746
+ encoding: "base64",
2747
+ secret: "SHOPIFY_API_SECRET"
2748
+ }
2749
+ };
2750
+ var COMPLIANCE_TOPICS = /* @__PURE__ */ new Set([
2751
+ "customers/data_request",
2752
+ "customers/redact",
2753
+ "shop/redact"
2754
+ ]);
2755
+ var shopify_default2 = {
2756
+ // INSTALL, not oauth. The grant is an OAuth grant, but the merchant never
2757
+ // sees a consent screen we sent them to -- they start at the App Store, and
2758
+ // the install completes inside Shopify admin without redirecting back. A
2759
+ // Connect button here would be lying about where connecting happens.
2760
+ auth: {
2761
+ type: "install"
2762
+ },
2763
+ // EVERYTHING A MERCHANT READS.
2764
+ //
2765
+ // `errors` is in here rather than at the top level, and that is not a
2766
+ // preference: the connection DOCUMENT carries its own `errors` array of
2767
+ // scope-drift entries, and the document is spread OVER the resolved manifest
2768
+ // downstream — a top-level one would be replaced by that array and never
2769
+ // render.
2770
+ //
2771
+ // `connect` no longer exists as a container. Its other member was `redirect`,
2772
+ // which is a URL and now sits with the vendor's other addresses.
2773
+ content: {
2774
+ confirm: "Disconnecting deactivates all products from this store, drafts any advertisements that use them, disables Shopify steps in your workflows until you reconnect, and stops revenue tracking for this organization.",
2775
+ description: [
2776
+ "Installing the Drawbridge app from the Shopify App Store links your store to a single Drawbridge organization and makes your product catalog available inside Drawbridge, so you can feature products in your campaigns and advertisements.",
2777
+ "Drawbridge attributes orders that originate from your campaigns \u2014 matched through cart parameters and lead-mapped discount codes \u2014 so you can see the revenue each campaign drives.",
2778
+ "On connect, Drawbridge registers webhooks for product and order updates to keep your catalog and revenue in sync. Disconnecting removes those webhooks and unlinks the resources."
2779
+ ],
2780
+ errors: {
2781
+ connect: {
2782
+ conflict: "This store is already connected to another Drawbridge organization.",
2783
+ currency: "This store settles in a currency we can't bill yet. Connect a store with a supported settlement currency.",
2784
+ invalid: "We couldn't verify the install. Please try connecting again from the Shopify App Store."
2785
+ }
2786
+ },
2787
+ excerpt: "Connect your Shopify store to feature products in your campaigns and track conversions.",
2788
+ guide: [
2789
+ "Open the Drawbridge listing on the Shopify App Store.",
2790
+ "Install the app on the store you want to connect. It opens in Shopify admin and stays there.",
2791
+ "Choose a plan when Shopify asks. The connection shows Pending until you do, then Active.",
2792
+ "Come back here \u2014 the connections list updates on its own once the install lands."
2793
+ ],
2794
+ // Names where the link GOES rather than what it does: installing happens on
2795
+ // the App Store listing, and the dashboard must never imply a store can be
2796
+ // linked from inside it.
2797
+ redirect: {
2798
+ env: "SHOPIFY_APP_LISTING_URL",
2799
+ title: "View on the Shopify App Store"
2800
+ }
2801
+ },
2802
+ // ONE STORE PER ORGANIZATION. Two Shopify stores on one org would give every
2803
+ // attributed order two possible sources.
2804
+ exclusive: true,
2805
+ feature: "organization:connection:shopify",
2806
+ fields: [
2807
+ {
2808
+ // `shop` on the connection record wins when present — it is written by
2809
+ // the install, while settings.domain is the stored copy.
2810
+ from: "shop",
2811
+ key: "domain",
2812
+ label: "Store domain"
2813
+ }
2814
+ ],
2815
+ // Was `category : 'commerce'` AND `group : 'ecommerce'` — two words for one
2816
+ // fact, which left nobody able to say which one a page read.
2817
+ group: "commerce",
2818
+ // verify and event lean entirely on the shared HMAC helper — Shopify's scheme
2819
+ // is exactly the shape it covers, so there is nothing vendor-specific to
2820
+ // write for either. receive is the one hook that genuinely differs by
2821
+ // channel: /events buffers whatever arrives with the shop domain stamped on;
2822
+ // /compliance enforces the topic allowlist above, because answering one late
2823
+ // is a legal deadline rather than a retry.
2824
+ hooks: {
2825
+ auth: {
2826
+ // The install completes inside Shopify admin; the api's callback stores
2827
+ // what it hands back. auth.probe is false deliberately: the health check
2828
+ // re-registers rather than answering "is this token still good", and
2829
+ // scope drift is its own hook because a token can be perfectly valid
2830
+ // while the grant is too narrow.
2831
+ //
2832
+ // connect and disconnect are FALSE rather than `{}`: there is nothing to
2833
+ // call on either side. The install already hands the callback everything
2834
+ // it stores, and a Shopify grant is withdrawn by UNINSTALLING the app in
2835
+ // Shopify admin — which Drawbridge learns about from the app_uninstalled
2836
+ // webhook rather than by asking. `{}` claimed a body implemented
2837
+ // elsewhere; none exists, and none could.
2838
+ connect: false,
2839
+ disconnect: false,
2840
+ probe: false,
2841
+ // WHETHER THE GRANT IS STILL WIDE ENOUGH. A token can be perfectly valid
2842
+ // and still too narrow — a deploy that adds a scope leaves every existing
2843
+ // install short of it, and no webhook fires to say so.
2844
+ //
2845
+ // The comparison is the vendor's, so it belongs here. Reading WHICH
2846
+ // scopes a store granted is not: that lives in the `shop` collection and
2847
+ // needs a controller, which is precisely what a hook in a published
2848
+ // package must not be handed. The caller reads the grant and passes the
2849
+ // string; this answers what is missing from it.
2850
+ //
2851
+ // `shopify` is injected for the same reason it is everywhere else — this
2852
+ // package cannot import @drawbridge/shopify, which depends on it.
2853
+ scopes: ({ scope }, { shopify } = {}) => scope ? shopify.oauth.missingScopes(scope) : null,
2854
+ // Shopify's install grant is exchanged inside its own app flow, not
2855
+ // through the shared OAuth runner.
2856
+ token: false
2857
+ },
2858
+ // THE VENDOR'S OWN WORK, here in full. Every body describes its writes,
2859
+ // enqueues and events for the shell to perform — see contract.js — and
2860
+ // everything it needs arrives as an argument: `read` (the controller's
2861
+ // read methods, nothing that writes), `shopify` (the SDK, injected because
2862
+ // this package cannot import what depends on it), `adminToken` (minted by
2863
+ // the shell, which persists rotations), `mintId` (so one described write
2864
+ // can reference another), `dispatch` (the caller's own coordinator table,
2865
+ // for the hooks that are dispatches).
2866
+ commerce: {
2867
+ // MINT A DISCOUNT CODE against the merchant's chosen discount, mapped to
2868
+ // one lead — which is what lets an order that redeems it be attributed
2869
+ // back.
2870
+ code: async ({ connection: connection2, context, step }, { adminToken, shopify } = {}) => {
2871
+ var _a;
2872
+ const discount = (_a = step.settings) == null ? void 0 : _a.discount;
2873
+ const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection2.shop };
2874
+ if (!(context == null ? void 0 : context.email)) return { message: "Lead email is missing.", request: request2, response: { skipped: true }, skipped: true };
2875
+ if (!(context == null ? void 0 : context.lead)) return { message: "Lead id is missing.", request: request2, response: { skipped: true }, skipped: true };
2876
+ if (!(discount == null ? void 0 : discount.id)) return { message: "Discount is not configured on this step.", request: request2, response: { skipped: true }, skipped: true };
2877
+ const adminAccessToken = await adminToken();
2878
+ if (!context.shopifyCustomerId) {
2879
+ const customer = await shopify.admin.getOrCreateCustomer({ adminAccessToken, domain: connection2.shop, email: context.email });
2880
+ if (!(customer == null ? void 0 : customer.id)) return { message: "Shopify did not return a customer id \u2014 create/lookup failed.", request: request2, response: { skipped: true }, skipped: true };
2881
+ }
2882
+ const discountCode = await shopify.admin.createDiscountCode({
2883
+ adminAccessToken,
2884
+ code: "DB-" + generateDiscountCode(),
2885
+ discountId: discount.id,
2886
+ domain: connection2.shop
2887
+ });
2888
+ if (!discountCode) return { message: "Shopify did not return a discount code \u2014 create failed.", request: request2, response: { skipped: true }, skipped: true };
2889
+ return {
2890
+ context: {
2891
+ shopifyDiscountCode: discountCode.code,
2892
+ shopifyDiscountId: String(discountCode.id)
2893
+ },
2894
+ message: "Discount code created and linked to lead.",
2895
+ request: request2,
2896
+ response: { code: discountCode.code, id: String(discountCode.id) },
2897
+ // bypassDocumentValidation because these are vendor ids on a
2898
+ // Drawbridge document the schema does not declare — the
2899
+ // canonical-identity work resolves it properly.
2900
+ writes: [{
2901
+ collection: "lead",
2902
+ data: {
2903
+ $set: {
2904
+ shopifyDiscountCode: discountCode.code,
2905
+ shopifyDiscountId: String(discountCode.id)
2906
+ }
2907
+ },
2908
+ operation: "update",
2909
+ options: { bypassDocumentValidation: true },
2910
+ query: { id: context.lead }
2911
+ }]
2912
+ };
2913
+ },
2914
+ // CREATE THE BUYER AT THE STORE, so an order can be attributed to them.
2915
+ //
2916
+ // IDEMPOTENT THREE WAYS, because this runs on every entry and a duplicate
2917
+ // customer at the store is a support ticket: the context may already
2918
+ // carry the id from an earlier step, the lead may already be linked from
2919
+ // an earlier run, and Shopify's own get-or-create settles the rest.
2920
+ customer: async ({ connection: connection2, context }, { adminToken, read, shopify } = {}) => {
2921
+ const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection2.shop };
2922
+ if (!(context == null ? void 0 : context.email)) return { message: "Lead email is missing \u2014 cannot create Shopify customer.", request: request2, response: { skipped: true }, skipped: true };
2923
+ if (!(context == null ? void 0 : context.lead)) return { message: "Lead id is missing \u2014 cannot create Shopify customer.", request: request2, response: { skipped: true }, skipped: true };
2924
+ if (context.shopifyCustomerId) {
2925
+ return {
2926
+ context: { shopifyCustomerId: context.shopifyCustomerId },
2927
+ message: "Trigger data already includes a Shopify customer id \u2014 reusing.",
2928
+ request: request2,
2929
+ response: { shopifyCustomerId: context.shopifyCustomerId },
2930
+ // Reusing an id is not a creation, so it does not bill.
2931
+ skipped: true
2932
+ };
2933
+ }
2934
+ const lead = await read.get({ collection: "lead", query: { id: context.lead } });
2935
+ if (lead == null ? void 0 : lead.shopifyCustomerId) {
2936
+ return {
2937
+ context: { shopifyCustomerId: lead.shopifyCustomerId },
2938
+ message: "Lead already has a Shopify customer id \u2014 reusing.",
2939
+ request: request2,
2940
+ response: { shopifyCustomerId: lead.shopifyCustomerId },
2941
+ skipped: true
2942
+ };
2943
+ }
2944
+ const adminAccessToken = await adminToken();
2945
+ const parts = ((lead == null ? void 0 : lead.name) || "").trim().split(/\s+/).filter(Boolean);
2946
+ const customer = await shopify.admin.getOrCreateCustomer({
2947
+ adminAccessToken,
2948
+ domain: connection2.shop,
2949
+ email: context.email,
2950
+ firstName: parts.length ? parts[0] : null,
2951
+ lastName: parts.length > 1 ? parts.slice(1).join(" ") : null,
2952
+ source: "drawbridge"
2953
+ });
2954
+ if (!(customer == null ? void 0 : customer.id)) return { message: "Shopify did not return a customer id \u2014 create/lookup failed.", request: request2, response: { skipped: true }, skipped: true };
2955
+ return {
2956
+ context: { shopifyCustomerId: customer.id },
2957
+ message: "Shopify customer created/linked to lead.",
2958
+ request: request2,
2959
+ response: { shopifyCustomerId: customer.id },
2960
+ // The hook's own result, described beside the call that produced it.
2961
+ writes: [{
2962
+ collection: "lead",
2963
+ data: { $set: { shopifyCustomerId: customer.id } },
2964
+ operation: "update",
2965
+ options: { bypassDocumentValidation: true },
2966
+ query: { id: context.lead }
2967
+ }]
2968
+ };
2969
+ },
2970
+ // AN ORDER ARRIVED AT THE STORE. The largest hook in the family, because
2971
+ // attribution genuinely is: an order can reach Drawbridge two ways and
2972
+ // they bill differently.
2973
+ //
2974
+ // CONVERSION — a `_drwbrdg_ca` line-item property, injected at
2975
+ // add-to-cart. Causal: the campaign produced the sale, so
2976
+ // it carries a fee.
2977
+ // REDEMPTION — a DB- discount code matched to a lead. Associative: we
2978
+ // cannot claim we caused the purchase, so it is fee-free.
2979
+ //
2980
+ // Both can be true, and an order already recorded as a conversion can
2981
+ // later have a redemption backfilled onto it — `backfill` below.
2982
+ //
2983
+ // IDEMPOTENT THROUGH THE RETRY, one layer up: two deliveries of the same
2984
+ // order race, the loser's transaction hits a duplicate key, the step
2985
+ // fails and BullMQ redelivers — and the re-run's read at the top finds
2986
+ // what the winner wrote and skips instead of double-billing a merchant
2987
+ // for one purchase. The hook used to loop for this itself; describing
2988
+ // the writes moved the retry to the queue, with the same guarantee.
2989
+ order: async ({ connection: connection2, context }, { logger: logger2, mintId, read } = {}) => {
2990
+ var _a, _b, _c, _d, _e, _f;
2991
+ const {
2992
+ advertisement,
2993
+ created_at: createdAt,
2994
+ currency,
2995
+ customer: orderCustomer,
2996
+ email,
2997
+ id: orderId,
2998
+ line_items: lineItems = [],
2999
+ organization: organization2,
3000
+ phone
3001
+ } = context || {};
3002
+ const request2 = { orderId: orderId ? String(orderId) : null, organization: organization2 };
3003
+ const [existingOrder, existingRedemption] = await Promise.all([
3004
+ read.get({ collection: "order", query: { "provider.id": String(orderId), "provider.slug": "shopify" } }),
3005
+ read.get({ collection: "redemption", query: { "provider.id": String(orderId), "provider.slug": "shopify" } })
3006
+ ]);
3007
+ if (existingRedemption) {
3008
+ return {
3009
+ message: "Order/redemption already recorded \u2014 skipping duplicate.",
3010
+ request: request2,
3011
+ response: {
3012
+ existingOrderId: (existingOrder == null ? void 0 : existingOrder.id) || null,
3013
+ existingRedemptionId: existingRedemption.id,
3014
+ skipped: true
3015
+ },
3016
+ skipped: true
3017
+ };
3018
+ }
3019
+ const backfill = !!existingOrder;
3020
+ const { attrMap, attributedGross, attributedLines } = attributeLineItems(lineItems);
3021
+ const campaign = attrMap["_drwbrdg_ca"] || null;
3022
+ const discountCodes = Array.isArray(context == null ? void 0 : context.discount_codes) ? context.discount_codes : [];
3023
+ const codes = [...new Set(discountCodes.map((dc) => dc == null ? void 0 : dc.code).filter(Boolean))];
3024
+ const matchedLeads = codes.length ? await read.aggregate({
3025
+ collection: "lead",
3026
+ pipeline: [{ $match: { organization: organization2, shopifyDiscountCode: { $in: codes } } }]
3027
+ }) : [];
3028
+ const codeToLead = {};
3029
+ for (const found of matchedLeads) {
3030
+ if (found.shopifyDiscountCode) codeToLead[found.shopifyDiscountCode] = found;
3031
+ }
3032
+ const matchedDiscounts = discountCodes.filter((dc) => (dc == null ? void 0 : dc.code) && codeToLead[dc.code]).map((dc) => ({
3033
+ amount: parseFloat(dc.amount) || 0,
3034
+ code: dc.code,
3035
+ id: codeToLead[dc.code].shopifyDiscountId || null
3036
+ }));
3037
+ const matchedLead = matchedDiscounts.length ? codeToLead[matchedDiscounts[0].code] : null;
3038
+ const discount = matchedDiscounts.length ? {
3039
+ amount: matchedDiscounts.reduce((sum, entry) => sum + entry.amount, 0),
3040
+ codes: matchedDiscounts
3041
+ } : null;
3042
+ const matchedCodes = new Set(matchedDiscounts.map((entry) => entry.code));
3043
+ const unmatched = codes.filter((code2) => code2.startsWith("DB-") && !matchedCodes.has(code2));
3044
+ if (unmatched.length) {
3045
+ (_a = logger2 == null ? void 0 : logger2.warn) == null ? void 0 : _a.call(logger2, "shopify.order.discount.unmatched", {
3046
+ campaign: campaign || null,
3047
+ codes: JSON.stringify(unmatched),
3048
+ isConversion: !!campaign,
3049
+ orderId: String(orderId),
3050
+ organization: organization2
3051
+ });
3052
+ }
3053
+ if (!campaign && !discount || backfill && !discount) {
3054
+ return {
3055
+ message: backfill ? "Order already recorded and no Drawbridge discount code matched \u2014 nothing to backfill." : "Order has no Drawbridge attribution \u2014 not recording.",
3056
+ request: request2,
3057
+ response: { skipped: true },
3058
+ skipped: true
3059
+ };
3060
+ }
3061
+ let advertisementId = null;
3062
+ let affiliateId = null;
3063
+ let campaignOrganization = organization2;
3064
+ let gross = 0;
3065
+ let leadId = null;
3066
+ let lines = [];
3067
+ let orderCampaign = null;
3068
+ let pageId = null;
3069
+ const isConversion = !!campaign;
3070
+ const customerPhone = toE164((orderCustomer == null ? void 0 : orderCustomer.phone) || phone) || null;
3071
+ const matchPhones = [...new Set([
3072
+ customerPhone,
3073
+ toE164((_b = context == null ? void 0 : context.billing_address) == null ? void 0 : _b.phone),
3074
+ toE164((_c = context == null ? void 0 : context.shipping_address) == null ? void 0 : _c.phone)
3075
+ ].filter(Boolean))];
3076
+ if (isConversion) {
3077
+ const campaignDoc = await read.get({ collection: "campaign", query: { id: campaign } });
3078
+ if (!campaignDoc || campaignDoc.organization !== organization2) {
3079
+ return {
3080
+ message: "Order carried a campaign attribution that does not belong to this store \u2014 not recording.",
3081
+ request: request2,
3082
+ response: { skipped: true },
3083
+ skipped: true
3084
+ };
3085
+ }
3086
+ advertisementId = attrMap["_drwbrdg_ad"] || advertisement || null;
3087
+ affiliateId = attrMap["_drwbrdg_af"] || null;
3088
+ campaignOrganization = campaignDoc.organization;
3089
+ gross = attributedGross;
3090
+ lines = attributedLines;
3091
+ orderCampaign = campaign;
3092
+ pageId = attrMap["_drwbrdg_pg"] || null;
3093
+ const identifiers = [];
3094
+ const canonicalEmail = toCanonicalEmail(email);
3095
+ if (email) identifiers.push({ email: email.toLowerCase() });
3096
+ if (canonicalEmail) identifiers.push({ "canonical.email.value": canonicalEmail });
3097
+ if (matchPhones.length) identifiers.push({ "phone.number": { $in: matchPhones } });
3098
+ if (matchPhones.length) identifiers.push({ "canonical.phone.value": { $in: matchPhones } });
3099
+ if (identifiers.length) {
3100
+ const lead = await read.get({
3101
+ collection: "lead",
3102
+ query: {
3103
+ campaigns: { $in: [campaign] },
3104
+ organization: campaignOrganization,
3105
+ $or: identifiers
3106
+ }
3107
+ });
3108
+ leadId = (lead == null ? void 0 : lead.id) || null;
3109
+ if (!leadId) {
3110
+ const orgLead = await read.get({
3111
+ collection: "lead",
3112
+ query: { organization: campaignOrganization, $or: identifiers }
3113
+ });
3114
+ leadId = (orgLead == null ? void 0 : orgLead.id) || null;
3115
+ }
3116
+ }
3117
+ } else {
3118
+ leadId = matchedLead.id;
3119
+ orderCampaign = (matchedLead.campaigns || []).length === 1 ? matchedLead.campaigns[0] : null;
3120
+ gross = lineItems.reduce((sum, item) => {
3121
+ const line = toLine(item);
3122
+ return sum + line.price * line.quantity;
3123
+ }, 0);
3124
+ lines = lineItems.map(toLine);
3125
+ }
3126
+ const org = await read.get({ collection: "organization", query: { id: campaignOrganization } });
3127
+ let rate = 0;
3128
+ if (isConversion) {
3129
+ const subscription = await read.get({ collection: "subscription", query: { id: org == null ? void 0 : org.subscription } });
3130
+ rate = conversionRate(subscription);
3131
+ }
3132
+ const fee = isConversion ? Math.round(gross * rate) / 100 : 0;
3133
+ const net2 = Math.round((gross - fee) * 100) / 100;
3134
+ const currencyCode = (currency || "usd").toLowerCase();
3135
+ const purchasedAt = new Date(createdAt || Date.now());
3136
+ const customer = orderCustomer || email || phone ? {
3137
+ acceptsMarketing: ((_d = orderCustomer == null ? void 0 : orderCustomer.email_marketing_consent) == null ? void 0 : _d.state) ? orderCustomer.email_marketing_consent.state === "subscribed" : typeof (orderCustomer == null ? void 0 : orderCustomer.accepts_marketing) === "boolean" ? orderCustomer.accepts_marketing : null,
3138
+ email: (orderCustomer == null ? void 0 : orderCustomer.email) || email || null,
3139
+ firstName: (orderCustomer == null ? void 0 : orderCustomer.first_name) || null,
3140
+ id: (orderCustomer == null ? void 0 : orderCustomer.id) ? String(orderCustomer.id) : null,
3141
+ lastName: (orderCustomer == null ? void 0 : orderCustomer.last_name) || null,
3142
+ phone: customerPhone
3143
+ } : null;
3144
+ const source = (connection2 == null ? void 0 : connection2.source) ? { domain: connection2.source.domain, id: connection2.source.id } : void 0;
3145
+ const orderDocId = (existingOrder == null ? void 0 : existingOrder.id) || (isConversion && !backfill ? mintId() : null);
3146
+ const writes = [];
3147
+ if (isConversion && !backfill) {
3148
+ writes.push({
3149
+ collection: "order",
3150
+ data: {
3151
+ advertisement: advertisementId,
3152
+ affiliate: affiliateId,
3153
+ campaign: orderCampaign,
3154
+ currency: currencyCode,
3155
+ customer,
3156
+ discount,
3157
+ fee,
3158
+ gross,
3159
+ id: orderDocId,
3160
+ lead: leadId,
3161
+ lines,
3162
+ net: net2,
3163
+ organization: campaignOrganization,
3164
+ page: pageId,
3165
+ provider: { id: String(orderId), slug: "shopify" },
3166
+ purchasedAt,
3167
+ rate,
3168
+ source,
3169
+ status: "completed"
3170
+ },
3171
+ operation: "create"
3172
+ });
3173
+ if (org == null ? void 0 : org.usage) {
3174
+ writes.push({
3175
+ collection: "usage",
3176
+ data: { $inc: { "totals.revenue": gross } },
3177
+ operation: "update",
3178
+ query: { id: org.usage }
3179
+ });
3180
+ }
3181
+ if (leadId) {
3182
+ writes.push({
3183
+ collection: "lead",
3184
+ data: { $inc: { "totals.orders": 1 } },
3185
+ operation: "update",
3186
+ options: { bypassDocumentValidation: true },
3187
+ query: { id: leadId }
3188
+ });
3189
+ }
3190
+ }
3191
+ if (discount) {
3192
+ writes.push({
3193
+ collection: "redemption",
3194
+ data: {
3195
+ advertisement: advertisementId,
3196
+ affiliate: affiliateId,
3197
+ campaign: orderCampaign,
3198
+ code: ((_e = matchedDiscounts[0]) == null ? void 0 : _e.code) || null,
3199
+ currency: currencyCode,
3200
+ customer,
3201
+ discount,
3202
+ gross,
3203
+ lead: leadId,
3204
+ order: orderDocId,
3205
+ organization: campaignOrganization,
3206
+ page: pageId,
3207
+ provider: { id: String(orderId), slug: "shopify" },
3208
+ purchasedAt,
3209
+ source,
3210
+ status: "completed"
3211
+ },
3212
+ operation: "create"
3213
+ });
3214
+ if (org == null ? void 0 : org.usage) {
3215
+ writes.push({
3216
+ collection: "usage",
3217
+ data: { $inc: { "totals.redemptions": 1 } },
3218
+ operation: "update",
3219
+ query: { id: org.usage }
3220
+ });
3221
+ }
3222
+ if (leadId) {
3223
+ writes.push({
3224
+ collection: "lead",
3225
+ data: { $inc: { "totals.redemptions": 1 } },
3226
+ operation: "update",
3227
+ options: { bypassDocumentValidation: true },
3228
+ query: { id: leadId }
3229
+ });
3230
+ }
3231
+ }
3232
+ const enqueues = (org == null ? void 0 : org.billingProvider) === "shopify" && fee > 0 && ((_f = connection2 == null ? void 0 : connection2.source) == null ? void 0 : _f.id) && !backfill ? [{
3233
+ data: {
3234
+ idempotencyKey: String(orderId),
3235
+ orderDocId,
3236
+ orderId: String(orderId),
3237
+ rate,
3238
+ shopId: connection2.source.id,
3239
+ // The App Events API returns no event id, so one is generated
3240
+ // here — the event handle plus the order id — and sent as the
3241
+ // event's `reference`. queue/usage.js stamps the same id onto
3242
+ // the order as billed.transaction.
3243
+ transaction: "drawbridge-orders." + orderId,
3244
+ value: Math.round(fee * 100)
3245
+ },
3246
+ name: "billing",
3247
+ options: { jobId: "shopify.usage." + orderId },
3248
+ queue: "usage"
3249
+ }] : [];
3250
+ return {
3251
+ enqueues,
3252
+ message: backfill ? "Redemption backfilled for an already-recorded order." : isConversion ? "Order recorded." : "Discount redemption recorded (fee-free).",
3253
+ request: request2,
3254
+ response: {
3255
+ campaign: orderCampaign,
3256
+ currency: currencyCode,
3257
+ discount,
3258
+ fee,
3259
+ gross,
3260
+ lead: leadId,
3261
+ lines: lines.length,
3262
+ net: net2,
3263
+ orderId: String(orderId)
3264
+ },
3265
+ // ONE TRANSACTION. The order, the redemption and both totals
3266
+ // counters land together or not at all — a half-written attribution
3267
+ // is revenue counted twice or not at all, and neither is
3268
+ // recoverable by hand.
3269
+ transaction: writes.length > 0,
3270
+ writes
3271
+ };
3272
+ },
3273
+ // A PRODUCT CHANGED AT THE STORE. Upserts the product row and hands it to
3274
+ // the product pipeline; the actual field sync happens there.
3275
+ //
3276
+ // The shell has already refused a missing or inactive Shopify connection,
3277
+ // so what is left is the two things only this hook can know are wrong.
3278
+ product: async ({ connection: connection2, context, workflow }, { mintId } = {}) => {
3279
+ const request2 = {
3280
+ numericId: (context == null ? void 0 : context.id) || null,
3281
+ organizationId: workflow.organization,
3282
+ title: (context == null ? void 0 : context.title) || null
3283
+ };
3284
+ if (!(context == null ? void 0 : context.id)) return { message: "Skipped \u2014 product webhook payload had no id.", request: request2, response: { skipped: true }, skipped: true };
3285
+ if (!connection2.shop) return { message: "Skipped \u2014 Shopify connection is missing shop domain.", request: request2, response: { skipped: true }, skipped: true };
3286
+ const providerId = "gid://shopify/Product/" + context.id;
3287
+ const productId = mintId();
3288
+ return {
3289
+ enqueues: [{
3290
+ data: { product: productId, providerId, shop: connection2.shop },
3291
+ name: "workflow",
3292
+ options: { jobId: "product.workflow.shopify." + providerId + "." + Date.now() },
3293
+ queue: "product.shopify"
3294
+ }],
3295
+ message: "Product sync queued from Shopify webhook.",
3296
+ request: request2,
3297
+ response: { productId, providerId, title: (context == null ? void 0 : context.title) || null },
3298
+ // KEYED ON PROVIDER + SHOP, so the same product in two stores stays
3299
+ // two rows. `connections` accumulates rather than replaces: one
3300
+ // store can be linked to several organizations, and each keeps its
3301
+ // own claim on the row.
3302
+ writes: [{
3303
+ collection: "product",
3304
+ data: {
3305
+ $addToSet: { connections: connection2.id },
3306
+ $setOnInsert: {
3307
+ id: productId,
3308
+ provider: { id: providerId, slug: "shopify" },
3309
+ "source.id": connection2.id,
3310
+ status: "active"
3311
+ }
3312
+ },
3313
+ operation: "update",
3314
+ options: { upsert: true },
3315
+ query: {
3316
+ "provider.id": providerId,
3317
+ "provider.slug": "shopify",
3318
+ "source.domain": connection2.shop
3319
+ }
3320
+ }]
3321
+ };
3322
+ }
3323
+ },
3324
+ contacts: { remove: false, sync: false },
3325
+ // verify and event lean entirely on the shared HMAC helper — Shopify's
3326
+ // scheme is exactly the shape it covers, so there is nothing vendor-specific
3327
+ // to write for either. receive is the one hook that genuinely differs by
3328
+ // channel: /events buffers whatever arrives with the shop domain stamped on;
3329
+ // /compliance enforces the topic allowlist above, because answering one late
3330
+ // is a legal deadline rather than a retry.
3331
+ // Drawbridge sends its own notification email and SMS, and owns its own
3332
+ // segments — see the private `drawbridge` manifest. A vendor answering
3333
+ // these would be a second sender, which is the arrangement the platform
3334
+ // sender replaced.
3335
+ email: false,
3336
+ segment: false,
3337
+ sms: false,
3338
+ inbound: {
3339
+ event: (args) => readEventHeader({ ...args, descriptor: inbound }),
3340
+ // One hook over the whole topic table, because that is what this
3341
+ // manifest declares: Shopify processes its own buffered events. The
3342
+ // topic rides in on the context rather than being a second hook name per
3343
+ // topic; the caller's handler table arrives as a prop.
3344
+ process: async ({ context }, { dispatch } = {}) => {
3345
+ const key = "shopify." + (context == null ? void 0 : context.topic);
3346
+ const handled = await dispatch({ data: context == null ? void 0 : context.data, handler: key });
3347
+ if (!handled) return { message: "No handler for " + key, skipped: true };
3348
+ return { message: "Processed " + key, request: { topic: context == null ? void 0 : context.topic } };
3349
+ },
3350
+ receive: ({ channel, event, headers, payload }) => {
3351
+ if (channel === "compliance" && !COMPLIANCE_TOPICS.has(event)) {
3352
+ throw Object.assign(new Error("Unrecognized compliance topic: " + event), { status: 401 });
3353
+ }
3354
+ return {
3355
+ // Compliance payloads already carry shop_domain in the body — Shopify's
3356
+ // own GDPR shape. The app-level event stream does not; that domain
3357
+ // lives only in the header, so it is stamped on here rather than left
3358
+ // for drawbridge-sync to reach into headers nobody hands it.
3359
+ data: channel === "compliance" ? payload : { ...payload, shop_domain: headers[inbound.headers.shop] || null },
3360
+ provider: { id: headers[inbound.headers.id] || null }
3361
+ };
3362
+ },
3363
+ verify: (args) => verifySignature({ ...args, descriptor: inbound })
3364
+ },
3365
+ lifecycle: {
3366
+ // DISPATCHES INTO THE CALLER'S OWN COORDINATORS. These three are
3367
+ // declarations made true: the work is queue orchestration over
3368
+ // Drawbridge's own collections, which is coordinator work and stays in
3369
+ // the repo that owns the queues. The hook receives the dispatch table as
3370
+ // a prop and picks the entry, so the manifest owns the SEAM — asking
3371
+ // Shopify whether it handles its own lifecycle now gets a real function
3372
+ // instead of `unimplemented` while the work happened anyway.
3373
+ cleanup: async ({ context }, { dispatch } = {}) => {
3374
+ await dispatch({ data: context, handler: "cleanup" });
3375
+ return { message: "Ran shopify lifecycle.cleanup", request: context || null };
3376
+ },
3377
+ // KEEP STORE ACCESS WORKING. Not a webhook monitor, despite the name the
3378
+ // step once carried — webhooks are declarative, declared in the app's
3379
+ // toml and applied by Shopify to every install, so nothing here registers
3380
+ // or checks them.
3381
+ //
3382
+ // It rotates the refresh token before its window closes, proves the
3383
+ // access token still works, reconciles the scopes the store granted
3384
+ // against the ones the app now needs, and queues a webhook
3385
+ // reconciliation.
3386
+ health: async ({ connection: connection2, workflow }, { adminToken, read, reconcileScopes, resolveSettings, rotateToken, shopify } = {}) => {
3387
+ const request2 = {
3388
+ connectionId: workflow.connection,
3389
+ organizationId: workflow.organization,
3390
+ shop: connection2.shop
3391
+ };
3392
+ const refreshTokenAtStart = (await resolveSettings()).refreshToken || null;
3393
+ try {
3394
+ const adminAccessToken = await adminToken();
3395
+ const settings = await resolveSettings();
3396
+ const refreshTokenExpiresAt = settings.refreshTokenExpiresAt;
3397
+ const needsRotation = refreshTokenExpiresAt && new Date(refreshTokenExpiresAt) < new Date(Date.now() + REFRESH_TOKEN_FRESHNESS_BUFFER_MS);
3398
+ let refreshTokenRotated = false;
3399
+ if (needsRotation) {
3400
+ await rotateToken();
3401
+ refreshTokenRotated = true;
3402
+ }
3403
+ await shopify.oauth.ping({ adminAccessToken, domain: connection2.shop });
3404
+ const scopesMissing = await reconcileScopes({ shop: connection2.shop });
3405
+ return {
3406
+ enqueues: [{
3407
+ data: {
3408
+ data: {
3409
+ connectionId: workflow.connection,
3410
+ organizationId: workflow.organization
3411
+ },
3412
+ event: "shopify.register.webhooks"
3413
+ },
3414
+ name: "register",
3415
+ options: { jobId: "connection.update.register." + workflow.connection + "." + randomUUID() },
3416
+ queue: "connection"
3417
+ }],
3418
+ message: (scopesMissing == null ? void 0 : scopesMissing.length) ? "Health check: ping ok, webhooks reconciled \u2014 connection errored, granted scopes are missing: " + scopesMissing.join(", ") + "." : refreshTokenRotated ? "Health check passed \u2014 refresh token rotated, ping ok, webhooks reconciled." : "Health check passed \u2014 ping ok, webhooks reconciled.",
3419
+ request: request2,
3420
+ response: {
3421
+ pingedAt: /* @__PURE__ */ new Date(),
3422
+ refreshTokenExpiresAt: refreshTokenExpiresAt || null,
3423
+ refreshTokenRotated,
3424
+ scopesMissing,
3425
+ webhookReconciliationQueued: true
3426
+ }
3427
+ };
3428
+ } catch (error) {
3429
+ if (OAUTH_GRANT_REVOKED_CODES.includes(error.code)) {
3430
+ const current = await read.get({ collection: "connection", query: { id: connection2.id } });
3431
+ const refreshTokenStored = current ? (await resolveSettings(current)).refreshToken || null : null;
3432
+ const rotated = error.code === "invalid_grant" && refreshTokenStored !== refreshTokenAtStart;
3433
+ if (current && !rotated) {
3434
+ const others = (current.errors || []).filter((entry) => entry.source !== OAUTH_ERROR_SOURCE);
3435
+ error.writes = [{
3436
+ collection: "connection",
3437
+ data: {
3438
+ $set: {
3439
+ errors: [
3440
+ ...others,
3441
+ {
3442
+ message: "Shopify disconnected this store. Open the Drawbridge app in your Shopify admin to reconnect.",
3443
+ source: OAUTH_ERROR_SOURCE
3444
+ }
3445
+ ],
3446
+ status: "error"
3447
+ }
3448
+ },
3449
+ operation: "update",
3450
+ query: { id: connection2.id }
3451
+ }];
3452
+ }
3453
+ }
3454
+ throw error;
3455
+ }
3456
+ },
3457
+ register: async ({ context }, { dispatch } = {}) => {
3458
+ await dispatch({ data: context, handler: "register" });
3459
+ return { message: "Ran shopify lifecycle.register", request: context || null };
3460
+ },
3461
+ rehydrate: async ({ context }, { dispatch } = {}) => {
3462
+ await dispatch({ data: context, handler: "rehydrate" });
3463
+ return { message: "Ran shopify lifecycle.rehydrate", request: context || null };
3464
+ }
3465
+ },
3466
+ resources: {
3467
+ audiences: false,
3468
+ // Shopify has no separate price resource — a price belongs to a product
3469
+ // variant and arrives with it, so there is nothing for prices to answer
3470
+ // that products does not already.
3471
+ prices: false,
3472
+ // WHAT THE VENDOR ANSWERS, shaped for a picker. Both of these were api
3473
+ // ROUTES — /organization/:organization/shopify/products and
3474
+ // .../connection/:id/shopify/discounts — vendor-named urls in a service
3475
+ // that is supposed to have none, reachable only by knowing the path.
3476
+ // They are the same two questions every other vendor answers through
3477
+ // resources.*, so they answer them the same way now.
3478
+ //
3479
+ // `shopify` is INJECTED: this package cannot import @drawbridge/shopify,
3480
+ // which depends on it. What arrives is the SDK's pure HTTP namespaces
3481
+ // and nothing else — no controller, no collection access. Resolving the
3482
+ // credential is the caller's job because it is Drawbridge's job: the
3483
+ // admin token refreshes and writes itself back, which is service work,
3484
+ // not vendor work.
3485
+ products: async ({ cursor, limit = 100, search, settings, sort }, { shopify } = {}) => {
3486
+ var _a, _b, _c, _d;
3487
+ const products = await shopify.storefront.getProducts({
3488
+ cursor,
3489
+ domain: settings == null ? void 0 : settings.domain,
3490
+ limit: Number(limit),
3491
+ search: (search == null ? void 0 : search.value) || null,
3492
+ sort,
3493
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken
3494
+ });
3495
+ return {
3496
+ items: ((products == null ? void 0 : products.edges) || []).map((edge) => edge.node),
3497
+ pageInfo: {
3498
+ endCursor: ((_a = products == null ? void 0 : products.pageInfo) == null ? void 0 : _a.endCursor) || null,
3499
+ hasNextPage: Boolean((_b = products == null ? void 0 : products.pageInfo) == null ? void 0 : _b.hasNextPage),
3500
+ hasPreviousPage: Boolean((_c = products == null ? void 0 : products.pageInfo) == null ? void 0 : _c.hasPreviousPage),
3501
+ startCursor: ((_d = products == null ? void 0 : products.pageInfo) == null ? void 0 : _d.startCursor) || null
3502
+ }
3503
+ };
3504
+ },
3505
+ promotions: async ({ cursor, limit = 100, search, settings }, { shopify } = {}) => {
3506
+ var _a, _b;
3507
+ const discounts = await shopify.admin.getDiscounts({
3508
+ adminAccessToken: settings == null ? void 0 : settings.adminAccessToken,
3509
+ cursor,
3510
+ domain: settings == null ? void 0 : settings.domain,
3511
+ limit: Number(limit),
3512
+ search: (search == null ? void 0 : search.value) || null
3513
+ });
3514
+ return {
3515
+ // The GLOBAL id is what Shopify returns and the bare id is what a
3516
+ // picker stores, which is why the tail is taken here rather than by
3517
+ // each caller that happened to remember.
3518
+ items: ((discounts == null ? void 0 : discounts.edges) || []).map((edge) => {
3519
+ var _a2, _b2, _c;
3520
+ return {
3521
+ id: String(((_a2 = edge == null ? void 0 : edge.node) == null ? void 0 : _a2.id) || "").split("/").pop(),
3522
+ title: (_c = (_b2 = edge == null ? void 0 : edge.node) == null ? void 0 : _b2.codeDiscount) == null ? void 0 : _c.title
3523
+ };
3524
+ }),
3525
+ pageInfo: {
3526
+ endCursor: ((_a = discounts == null ? void 0 : discounts.pageInfo) == null ? void 0 : _a.endCursor) || null,
3527
+ hasNextPage: Boolean((_b = discounts == null ? void 0 : discounts.pageInfo) == null ? void 0 : _b.hasNextPage)
3528
+ }
3529
+ };
3530
+ }
3531
+ },
3532
+ // Drawbridge posts to a merchant's own endpoint, never through a vendor.
3533
+ webhook: false
3534
+ },
3535
+ icon: shopify_default,
3536
+ inbound,
3537
+ // THE DEEP LINK into this store's Drawbridge app inside Shopify admin.
3538
+ //
3539
+ // Here rather than in drawbridge-api, which had `slug === 'shopify' && {...}`
3540
+ // in the shared resolver — a hardcoded vendor branch in code every vendor runs
3541
+ // through, which is the arrangement these manifests exist to remove.
3542
+ //
3543
+ // Undefined until a shop is linked, so the Manage button only appears on a
3544
+ // connected connection. The app handle is NAMED by `requires` and read from
3545
+ // the env the resolver passes, never from process.env here.
3546
+ manage: (data2, env) => {
3547
+ var _a;
3548
+ const shop = (data2 == null ? void 0 : data2.shop) || ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.domain);
3549
+ return shop ? "https://admin.shopify.com/store/" + String(shop).replace(".myshopify.com", "") + "/apps/" + (env == null ? void 0 : env.SHOPIFY_APP_HANDLE) : void 0;
3550
+ },
3551
+ // A pre-launch integration: it only surfaces once the App Store listing
3552
+ // exists and the app is fully configured. Requiring all four means it can
3553
+ // never render half-configured — and absence of any one excludes the
3554
+ // connection AND every step below it.
3555
+ requires: [
3556
+ "SHOPIFY_API_KEY",
3557
+ "SHOPIFY_API_SECRET",
3558
+ "SHOPIFY_APP_LISTING_URL",
3559
+ "SHOPIFY_APP_HANDLE"
3560
+ ],
3561
+ slug: "shopify",
3562
+ // The install is the whole configuration — Shopify hands back the shop and
3563
+ // there is nothing further to choose. `shop` absent means the install did not
3564
+ // finish, which is a credential problem rather than a setup one, so the
3565
+ // stored status already says so.
3566
+ // Nothing to add — no setting can make this connection unusable, so the
3567
+ // credential's own verdict stands.
3568
+ status: (data2) => data2 == null ? void 0 : data2.status,
3569
+ // Step types name the CAPABILITY, not this vendor. A second store platform
3570
+ // implements the same four commerce steps, and the connection on the step
3571
+ // says which store it runs against — so a merchant sees one "Create
3572
+ // customer", not one per platform. The three connection.* steps are not
3573
+ // commerce at all: any vendor holding a rotating credential needs them.
3574
+ // Step types name the CAPABILITY, not this vendor. A second store platform
3575
+ // implements the same commerce steps, and the connection on the step says
3576
+ // which store it runs against — so a merchant sees one "Create customer", not
3577
+ // one per platform.
3578
+ //
3579
+ // Nested for readability and flattened to the stored name, at whatever depth:
3580
+ // steps.commerce.customer.insert is `step.commerce.customer.insert` on a
3581
+ // workflow document, and those strings cannot be renamed without a backfill.
3582
+ //
3583
+ // EVERY LEAF IS A FUNCTION so a step can read the merchant's own connection.
3584
+ steps: {
3585
+ commerce: {
3586
+ code: {
3587
+ issue: () => ({
3588
+ hook: "commerce.code",
3589
+ key: "Issue a discount code",
3590
+ queue: "connection",
3591
+ settings: {
3592
+ discount: {
3593
+ required: true,
3594
+ shape: {
3595
+ id: { required: true, type: "string" }
3596
+ },
3597
+ type: "object"
3598
+ }
3599
+ },
3600
+ triggers: ["lead.insert"],
3601
+ usage: { actions: 1 }
3602
+ })
3603
+ },
3604
+ customer: {
3605
+ insert: () => ({
3606
+ hook: "commerce.customer",
3607
+ key: "Create customer",
3608
+ queue: "connection",
3609
+ settings: {},
3610
+ triggers: ["lead.insert"],
3611
+ usage: { actions: 1 }
3612
+ })
3613
+ },
3614
+ // SYSTEM STEPS: dispatched by drawbridge-sync itself rather than offered
3615
+ // in the builder, so they carry no trigger and no usage. Declared because
3616
+ // the routing table and the system-workflow descriptions both read here.
3617
+ order: {
3618
+ record: () => ({
3619
+ description: "Records an order and billing charge when a purchase is made via a Drawbridge campaign link.",
3620
+ hook: "commerce.order",
3621
+ key: "Shopify Order Tracking",
3622
+ queue: "connection",
3623
+ system: true
3624
+ })
3625
+ },
3626
+ product: {
3627
+ sync: () => ({
3628
+ description: "Syncs Shopify product data on webhook updates.",
3629
+ hook: "commerce.product",
3630
+ key: "Shopify Product Sync",
3631
+ queue: "connection",
3632
+ system: true
3633
+ })
3634
+ }
3635
+ },
3636
+ connection: {
3637
+ // Not a webhook monitor, despite the name it once carried. Webhooks are
3638
+ // declarative — declared in the app's toml, applied by Shopify to every
3639
+ // install — so nothing registers or checks them here. This rotates the
3640
+ // access token before Shopify's idle window closes, and reconciles the
3641
+ // scopes the store granted against the ones the app now needs.
3642
+ health: {
3643
+ check: () => ({
3644
+ description: "Keeps store access working \u2014 refreshes the access token before it goes stale and reports when the store's approved permissions fall behind.",
3645
+ hook: "lifecycle.health",
3646
+ key: "Shopify Connection Health",
3647
+ queue: "connection",
3648
+ system: true
3649
+ })
3650
+ },
3651
+ // Audit-only. The "Shopify Token Activity" system workflow lists these
3652
+ // for descriptive grouping, but its audit step docs are written manually
3653
+ // at OAuth time — the workflow is never dispatched. Routing is declared
3654
+ // defensively so that if it ever IS dispatched, the job lands on a real
3655
+ // queue and the handler lookup misses cleanly instead of throwing
3656
+ // "Unknown step type".
3657
+ token: {
3658
+ exchange: () => ({
3659
+ description: "Records the token exchange that completed an install. Audit only \u2014 never dispatched.",
3660
+ key: "Shopify Token Exchange",
3661
+ queue: "connection",
3662
+ system: true
3663
+ }),
3664
+ refresh: () => ({
3665
+ description: "Records a token rotation. Audit only \u2014 never dispatched.",
3666
+ key: "Shopify Token Refresh",
3667
+ queue: "connection",
3668
+ system: true
3669
+ })
3670
+ }
3671
+ }
3672
+ },
3673
+ // Shopify sits pending between the install landing and the merchant choosing a
3674
+ // plan, and nothing on our side can move it — so the card says what they need
3675
+ // to go and do rather than showing Pending with no next step.
3676
+ //
3677
+ // Scope drift is NOT here: drawbridge-sync writes it onto the connection
3678
+ // document, and the document's own warnings render beside these.
3679
+ tasks: (data2) => (data2 == null ? void 0 : data2.status) === "pending" ? [
3680
+ {
3681
+ message: "Open the Drawbridge app in your Shopify admin and choose a plan. The connection activates once Shopify confirms it.",
3682
+ title: "Choose a plan in Shopify"
3683
+ }
3684
+ ] : [],
3685
+ title: "Shopify"
3686
+ };
3687
+
3688
+ // lib/connections/providers/webhook.js
3689
+ import crypto from "crypto";
3690
+
3691
+ // lib/safe-http.js
3692
+ import dns2 from "dns";
3693
+ import * as http2 from "http";
3694
+ import * as https2 from "https";
3695
+
3696
+ // lib/axios.js
3697
+ import axiosLib from "axios";
3698
+ import dns from "dns";
3699
+ import * as http from "http";
3700
+ import * as https from "https";
3701
+ import net from "net";
3702
+ var dnsLookup = dns.promises.lookup;
3703
+ var isBlockedIPv4 = (ip) => {
3704
+ const parts = ip.split(".").map(Number);
3705
+ if (parts.length !== 4 || parts.some((n) => Number.isNaN(n) || n < 0 || n > 255)) return true;
3706
+ const [a, b] = parts;
3707
+ if (a === 0) return true;
3708
+ if (a === 10) return true;
3709
+ if (a === 127) return true;
3710
+ if (a === 169 && b === 254) return true;
3711
+ if (a === 172 && b >= 16 && b <= 31) return true;
3712
+ if (a === 192 && b === 168) return true;
3713
+ if (a === 100 && b >= 64 && b <= 127) return true;
3714
+ if (a === 192 && b === 0) return true;
3715
+ if (a === 198 && (b === 18 || b === 19)) return true;
3716
+ if (a === 198 && b === 51) return true;
3717
+ if (a === 203 && b === 0) return true;
3718
+ if (a >= 224) return true;
3719
+ return false;
3720
+ };
3721
+ var isBlockedIPv6 = (ip) => {
3722
+ const lower = ip.toLowerCase();
3723
+ if (lower === "::1" || lower === "::") return true;
3724
+ if (lower.startsWith("fc") || lower.startsWith("fd")) return true;
3725
+ if (/^fe[89ab]/.test(lower)) return true;
3726
+ if (lower.startsWith("ff")) return true;
3727
+ if (lower.startsWith("::ffff:")) {
3728
+ const v4 = lower.slice(7);
3729
+ return isBlockedIPv4(v4);
3730
+ }
3731
+ ;
3732
+ return false;
3733
+ };
3734
+ var isBlockedIP = (ip) => {
3735
+ const version = net.isIP(ip);
3736
+ if (version === 4) return isBlockedIPv4(ip);
3737
+ if (version === 6) return isBlockedIPv6(ip);
3738
+ return true;
3739
+ };
3740
+ var axios = axiosLib.create({
3741
+ timeout: 3e4,
3742
+ httpAgent: new http.Agent({ keepAlive: true, maxSockets: 128 }),
3743
+ httpsAgent: new https.Agent({ keepAlive: true, maxSockets: 128 })
3744
+ });
3745
+
3746
+ // lib/safe-http.js
3747
+ var DEFAULT_TIMEOUT_MS2 = 15e3;
3748
+ var resolveSafeHost = async (url) => {
3749
+ const parsed = new URL(url);
3750
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
3751
+ throw new Error("Only http(s) URLs are allowed");
3752
+ }
3753
+ const records = await dns2.promises.lookup(parsed.hostname, { all: true });
3754
+ if (!(records == null ? void 0 : records.length)) {
3755
+ throw new Error("Host could not be resolved");
3756
+ }
3757
+ for (const record of records) {
3758
+ if (isBlockedIP(record.address)) {
3759
+ throw new Error("Host resolves to a blocked IP range");
3760
+ }
3761
+ }
3762
+ return { parsed, records };
3763
+ };
3764
+ var pinnedAgent = async (url) => {
3765
+ const { parsed, records } = await resolveSafeHost(url);
3766
+ const pinned = records[0];
3767
+ const lookup2 = (hostname, options, callback) => {
3768
+ if (options == null ? void 0 : options.all) {
3769
+ callback(null, [{ address: pinned.address, family: pinned.family }]);
3770
+ } else {
3771
+ callback(null, pinned.address, pinned.family);
3772
+ }
3773
+ };
3774
+ return {
3775
+ protocol: parsed.protocol,
3776
+ agent: parsed.protocol === "https:" ? new https2.Agent({ lookup: lookup2 }) : new http2.Agent({ lookup: lookup2 })
3777
+ };
3778
+ };
3779
+ var safeRequest = async ({
3780
+ body,
3781
+ headers = {},
3782
+ method = "GET",
3783
+ query,
3784
+ timeout = DEFAULT_TIMEOUT_MS2,
3785
+ type = "json",
3786
+ url
3787
+ }) => {
3788
+ const full = new URL(url);
3789
+ if (query) {
3790
+ Object.entries(query).forEach(([key, value]) => full.searchParams.set(key, value));
3791
+ }
3792
+ const { protocol, agent } = await pinnedAgent(full.toString());
3793
+ const isForm = type === "form";
3794
+ try {
3795
+ const response = await axios({
3796
+ method,
3797
+ url: full.toString(),
3798
+ headers: {
3799
+ "Content-Type": isForm ? "application/x-www-form-urlencoded" : "application/json",
3800
+ ...headers
3801
+ },
3802
+ ...body !== void 0 && {
3803
+ data: isForm ? new URLSearchParams(body).toString() : body
3804
+ },
3805
+ timeout,
3806
+ maxRedirects: 0,
3807
+ httpAgent: protocol === "http:" ? agent : void 0,
3808
+ httpsAgent: protocol === "https:" ? agent : void 0,
3809
+ responseType: "json",
3810
+ validateStatus: (status) => status >= 200 && status < 300
3811
+ });
3812
+ return response.data || null;
3813
+ } catch (error) {
3814
+ if (error == null ? void 0 : error.response) {
3815
+ const normalized = new Error(
3816
+ typeof error.response.data === "string" ? error.response.data : error.message || "Request failed"
3817
+ );
3818
+ normalized.status = error.response.status;
3819
+ normalized.response = error.response.data;
3820
+ throw normalized;
3821
+ }
3822
+ throw error;
3823
+ }
3824
+ };
3825
+
3826
+ // lib/connections/providers/webhook.js
3827
+ var webhook_default = {
3828
+ // Connecting GENERATES the secret rather than storing one the merchant typed,
3829
+ // so the buttons say what actually happens.
3830
+ actions: {
3831
+ create: "Connect",
3832
+ update: "Regenerate secret"
3833
+ },
3834
+ // GENERATED. There is no third party and nothing to authenticate against --
3835
+ // connecting mints a secret rather than proving a credential.
3836
+ auth: {
3837
+ type: "generated"
3838
+ },
3839
+ // EVERYTHING A MERCHANT READS. `errors` would belong here too — the
3840
+ // connection DOCUMENT carries its own `errors` array and is spread OVER the
3841
+ // resolved manifest downstream, so a top-level one is replaced by that array.
3842
+ content: {
3843
+ confirm: "Disconnecting stops Drawbridge from sending signed webhook payloads to your endpoint.",
3844
+ description: [
3845
+ "Drawbridge can POST event payloads to your endpoint as activity happens in your account, so your own systems can react in real time.",
3846
+ "Generate a signing secret and Drawbridge signs every request with it. Your endpoint recomputes the signature to confirm each payload genuinely came from Drawbridge before acting on it."
3847
+ ],
3848
+ excerpt: "Sign outgoing webhook payloads with an HMAC secret to verify authenticity.",
3849
+ guide: [
3850
+ "Press Connect. Drawbridge generates a signing secret and shows it here.",
3851
+ "Copy the secret into your own endpoint.",
3852
+ "On each request, compute HMAC-SHA256 of the raw body using the secret and compare it against the X-Drawbridge-Signature header before acting on the payload."
3853
+ ]
3854
+ },
3855
+ // Nothing to be exclusive with — there is no second webhook vendor, and a
3856
+ // merchant with two endpoints is a step-level choice rather than a second
3857
+ // connection.
3858
+ exclusive: false,
3859
+ feature: "organization:connection:webhook",
3860
+ fields: [
3861
+ {
3862
+ // No `input`: Drawbridge generates this, the merchant never types it.
3863
+ // No `redact` either — it is shared with the merchant's own endpoint
3864
+ // rather than being a third-party credential, so it round-trips for
3865
+ // them to copy and configure.
3866
+ copy: true,
3867
+ key: "secret",
3868
+ label: "Signing secret"
3869
+ }
3870
+ ],
3871
+ group: "developer",
3872
+ // OUTBOUND ONLY. inbound.* is false because the direction is the point: we
3873
+ // sign and POST to the merchant's endpoint, they never call us. Every other
3874
+ // false follows from there being no third party to authenticate against —
3875
+ // connect generates a secret rather than proving a credential.
3876
+ hooks: {
3877
+ auth: {
3878
+ // FALSE, NOT {}. There is no vendor here at all — connecting mints a
3879
+ // secret and disconnecting clears it, both done by the api's own
3880
+ // handler. `{}` would promise a body implemented elsewhere, and none
3881
+ // exists or could.
3882
+ connect: false,
3883
+ disconnect: false,
3884
+ probe: false,
3885
+ scopes: false,
3886
+ // Nothing to mint. Connecting generates a secret; there is no vendor.
3887
+ token: false
3888
+ },
3889
+ commerce: false,
3890
+ contacts: { remove: false, sync: false },
3891
+ // Drawbridge sends its own notification email and SMS, and owns its own
3892
+ // segments — see the private `drawbridge` manifest. A vendor answering
3893
+ // these would be a second sender, which is the arrangement the platform
3894
+ // sender replaced.
3895
+ email: false,
3896
+ segment: false,
3897
+ sms: false,
3898
+ inbound: false,
3899
+ lifecycle: false,
3900
+ resources: {
3901
+ audiences: false,
3902
+ prices: false,
3903
+ products: false,
3904
+ promotions: false
3905
+ },
3906
+ // THE BODY IS HERE, not in drawbridge-sync. It needs `crypto` and an HTTP
3907
+ // client and nothing else — no controller, no queue, no database — so
3908
+ // there was never a reason for it to live in another repo.
3909
+ //
3910
+ // That is the rule the whole split runs on: a hook lives in sync only if it
3911
+ // needs Drawbridge's own database, sockets or queues. This one does not.
3912
+ webhook: {
3913
+ send: async ({ context, lead, settings, step }, { request: send2 = safeRequest } = {}) => {
3914
+ const { headers = {}, method = "POST", url } = step.settings || {};
3915
+ const request2 = { method, url: url || null };
3916
+ if (!url) return { message: "Outgoing webhook URL is not configured for this step.", request: request2, response: { skipped: true }, skipped: true };
3917
+ const body = lead || context;
3918
+ request2.body = body;
3919
+ const outgoing = { ...headers };
3920
+ if (settings == null ? void 0 : settings.secret) {
3921
+ outgoing["X-Drawbridge-Signature"] = "sha256=" + crypto.createHmac("sha256", settings.secret).update(JSON.stringify(body)).digest("hex");
3922
+ }
3923
+ const response = await send2({ body, headers: outgoing, method, url });
3924
+ return { message: "Webhook POSTed to " + url + ".", request: request2, response: response || { delivered: true } };
3925
+ }
3926
+ }
3927
+ },
3928
+ // Borrowed: this is the Drawbridge mark, because Webhooks has none of its own.
3929
+ // It is the one card that reads wrong — our logo among vendor logos — and it
3930
+ // wants a mark of its own when there is one.
3931
+ icon: drawbridge_default,
3932
+ // Gated on the encryption secret: without it the signing secret could not be
3933
+ // stored safely, so the connection must not be offered at all.
3934
+ requires: ["ENCRYPT_CONNECTION_SECRET"],
3935
+ // Outbound only. inbound.* is false because the direction is the point: we
3936
+ // sign and POST to the merchant's endpoint, they never call us. Every other
3937
+ // false follows from there being no third party to authenticate against —
3938
+ // connect generates a secret rather than proving a credential.
3939
+ slug: "webhook",
3940
+ // The destination url is supplied per step, not per connection, so there is
3941
+ // nothing to finish here — generating the secret IS connecting, and no
3942
+ // setting can make this connection unusable. The credential's own verdict
3943
+ // stands.
3944
+ status: (data2) => data2 == null ? void 0 : data2.status,
3945
+ steps: {
3946
+ webhook: {
3947
+ send: () => ({
3948
+ hook: "webhook.send",
3949
+ key: "Send webhook",
3950
+ queue: "webhook",
3951
+ settings: {
3952
+ url: { format: "url", required: true, type: "string" }
3953
+ },
3954
+ triggers: ["lead.insert", "lead.delete"],
3955
+ // Replaces `billable : true`, which fed BILLABLE_STEP_TYPES, which set
3956
+ // workflow.billable at save, which sync then checked against a usage
3957
+ // the handler returned — three hops for one fact, two of which could
3958
+ // disagree silently.
3959
+ usage: { actions: 1 }
3960
+ })
3961
+ }
3962
+ },
3963
+ // The card the connection page raises. Before connecting it explains what
3964
+ // pressing Connect will do; afterwards it states the verification the
3965
+ // merchant's own endpoint has to perform, because a signed payload nobody
3966
+ // checks is an unsigned payload.
3967
+ tasks: ({ settings }) => (settings == null ? void 0 : settings.secret) ? [
3968
+ {
3969
+ message: "Compute HMAC-SHA256( secret, body ) and compare against the X-Drawbridge-Signature header to confirm each payload.",
3970
+ title: "Requests must be verified",
3971
+ type: "warning"
3972
+ }
3973
+ ] : [
3974
+ {
3975
+ message: "Connect to generate a signing secret. Drawbridge signs every webhook it sends with it.",
3976
+ title: "Webhook signing"
3977
+ }
3978
+ ],
3979
+ title: "Webhooks"
3980
+ };
3981
+
3982
+ // lib/connections/index.js
3983
+ var QUEUES = ["connection", "notification", "segment", "webhook"];
3984
+ var implemented = (hooks, path) => {
3985
+ const hook = path.split(".").reduce((node, key) => node == null ? void 0 : node[key], hooks);
3986
+ return typeof hook === "function" || !!hook && typeof hook === "object";
3987
+ };
3988
+ var leaves = (node, path = []) => Object.entries(node || {}).flatMap(
3989
+ ([key, value]) => typeof value === "function" ? [[[...path, key].join("."), value]] : value && typeof value === "object" ? leaves(value, [...path, key]) : []
3990
+ );
3991
+ var build = (manifest) => {
3992
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
3993
+ if (!(manifest == null ? void 0 : manifest.slug)) throw new Error("A connection needs a slug");
3994
+ if (!(manifest == null ? void 0 : manifest.title)) throw new Error(manifest.slug + " needs a title");
3995
+ if (!(manifest == null ? void 0 : manifest.private) && !(manifest == null ? void 0 : manifest.feature)) throw new Error(manifest.slug + " needs a plan feature key");
3996
+ if (!((_a = manifest == null ? void 0 : manifest.content) == null ? void 0 : _a.excerpt)) throw new Error(manifest.slug + " needs content.excerpt for its card");
3997
+ if (!Array.isArray((_b = manifest == null ? void 0 : manifest.content) == null ? void 0 : _b.description) || !manifest.content.description.length) {
3998
+ throw new Error(manifest.slug + " needs content.description \u2014 an array of paragraphs for its page");
3999
+ }
4000
+ for (const field2 of manifest.fields || []) {
4001
+ if (!(field2 == null ? void 0 : field2.key) || !(field2 == null ? void 0 : field2.label)) {
4002
+ throw new Error(manifest.slug + " declares a field with no key or label");
4003
+ }
4004
+ if (field2.input && !INPUTS.includes(field2.input)) {
4005
+ throw new Error(manifest.slug + "." + field2.key + " declares an unknown input: " + field2.input + " \u2014 one of " + INPUTS.join(", "));
4006
+ }
4007
+ if (field2.input === "select" && !(field2.options || []).length && !field2.hook) {
4008
+ throw new Error(manifest.slug + "." + field2.key + " is a select and must declare options or a hook");
4009
+ }
4010
+ if (field2.hook) {
4011
+ if (!HOOK_NAMES.includes(field2.hook)) {
4012
+ throw new Error(manifest.slug + "." + field2.key + " names an unknown hook: " + field2.hook);
4013
+ }
4014
+ if (!field2.hook.startsWith("resources.")) {
4015
+ throw new Error(manifest.slug + "." + field2.key + " reads from " + field2.hook + " \u2014 a picker may only read resources.*");
4016
+ }
4017
+ if (!implemented(manifest.hooks, field2.hook)) {
4018
+ throw new Error(manifest.slug + "." + field2.key + " reads " + field2.hook + ", which this vendor does not implement");
4019
+ }
4020
+ }
4021
+ }
4022
+ if (typeof (manifest == null ? void 0 : manifest.icon) !== "string" || !manifest.icon.includes("<svg")) {
4023
+ throw new Error(manifest.slug + " needs an icon \u2014 the svg markup itself, not a path to one");
4024
+ }
4025
+ if (!manifest.icon.includes("viewBox")) {
4026
+ throw new Error(manifest.slug + " icon has no viewBox, so it cannot scale");
4027
+ }
4028
+ if (manifest.icon.includes("<image")) {
4029
+ throw new Error(manifest.slug + " icon wraps a raster \u2014 re-export it as vector shapes");
4030
+ }
4031
+ if (!GROUPS.includes(manifest == null ? void 0 : manifest.group)) {
4032
+ throw new Error(manifest.slug + " needs a group \u2014 one of " + GROUPS.join(", "));
4033
+ }
4034
+ if ((_c = manifest == null ? void 0 : manifest.connect) == null ? void 0 : _c.type) {
4035
+ throw new Error(manifest.slug + " declares connect.type \u2014 that is auth.type now");
4036
+ }
4037
+ if (!AUTH_TYPES.includes((_d = manifest == null ? void 0 : manifest.auth) == null ? void 0 : _d.type)) {
4038
+ throw new Error(manifest.slug + " needs auth.type \u2014 one of " + AUTH_TYPES.join(", "));
4039
+ }
4040
+ if (manifest.auth.type === "oauth") {
4041
+ for (const field2 of OAUTH_FIELDS) {
4042
+ if (!((_e = manifest.auth.oauth) == null ? void 0 : _e[field2])) {
4043
+ throw new Error(manifest.slug + " is oauth and must declare auth.oauth." + field2);
4044
+ }
4045
+ }
4046
+ if (typeof ((_g = (_f = manifest.hooks) == null ? void 0 : _f.auth) == null ? void 0 : _g.token) !== "function") {
4047
+ throw new Error(manifest.slug + " is oauth and must implement hooks.auth.token \u2014 point it at authToken() or wrap it");
4048
+ }
4049
+ for (const url of OAUTH_URLS) {
4050
+ if (!((_i = (_h = manifest.auth.oauth) == null ? void 0 : _h.urls) == null ? void 0 : _i[url])) {
4051
+ throw new Error(manifest.slug + " is oauth and must declare auth.oauth.urls." + url);
4052
+ }
4053
+ }
4054
+ if (manifest.auth.oauth.urls.redirect !== "/api/connection/" + manifest.slug + "/callback") {
4055
+ throw new Error(
4056
+ manifest.slug + " declares auth.oauth.urls.redirect " + manifest.auth.oauth.urls.redirect + " but the only callback route is /api/connection/" + manifest.slug + "/callback"
4057
+ );
4058
+ }
4059
+ }
4060
+ if (implemented(manifest.hooks, "inbound.event") && !((_k = (_j = manifest.inbound) == null ? void 0 : _j.headers) == null ? void 0 : _k.event)) {
4061
+ throw new Error(manifest.slug + " implements inbound.event but declares no inbound.headers.event");
4062
+ }
4063
+ if (implemented(manifest.hooks, "inbound.verify") && !((_m = (_l = manifest.inbound) == null ? void 0 : _l.headers) == null ? void 0 : _m.signature)) {
4064
+ throw new Error(manifest.slug + " implements inbound.verify but declares no inbound.headers.signature");
4065
+ }
4066
+ if (typeof (manifest == null ? void 0 : manifest.status) !== "function") {
4067
+ throw new Error(manifest.slug + " must declare status( data ) \u2014 return null to accept the connection's own status, or { message, status } to override it");
4068
+ }
4069
+ if (!Array.isArray((_n = manifest == null ? void 0 : manifest.content) == null ? void 0 : _n.guide) || !manifest.content.guide.length) {
4070
+ throw new Error(manifest.slug + " needs content.guide \u2014 an array of steps for its page");
4071
+ }
4072
+ if (typeof (manifest == null ? void 0 : manifest.status) !== "function") {
4073
+ throw new Error(manifest.slug + " must declare status( data ) \u2014 one of " + STATUSES.join(", "));
4074
+ }
4075
+ const status = manifest.status({});
4076
+ if (status != null && !STATUSES.includes(status)) {
4077
+ throw new Error(manifest.slug + " status() returned " + status + " \u2014 must be one of " + STATUSES.join(", "));
4078
+ }
4079
+ for (const [domain, verbs] of Object.entries(HOOKS)) {
4080
+ for (const verb of verbs) {
4081
+ const hook = (_p = (_o = manifest.hooks) == null ? void 0 : _o[domain]) == null ? void 0 : _p[verb];
4082
+ if (((_q = manifest.hooks) == null ? void 0 : _q[domain]) === false) continue;
4083
+ if (hook !== false && !implemented({ [domain]: { [verb]: hook } }, domain + "." + verb)) {
4084
+ throw new Error(manifest.slug + " must answer hooks." + domain + "." + verb + " \u2014 false, a function, or {} if another repo implements it");
4085
+ }
4086
+ }
4087
+ }
4088
+ for (const [domain, verbs] of Object.entries(manifest.hooks || {})) {
4089
+ if (!HOOKS[domain]) throw new Error(manifest.slug + " implements an unknown hook domain: " + domain);
4090
+ for (const verb of Object.keys(verbs === false ? {} : verbs)) {
4091
+ if (!HOOKS[domain].includes(verb)) {
4092
+ throw new Error(manifest.slug + " implements an unknown hook: " + domain + "." + verb);
4093
+ }
4094
+ }
4095
+ }
4096
+ for (const [name, step] of leaves(manifest.steps)) {
4097
+ const type = "step." + name;
4098
+ if (!STEPS[name]) {
4099
+ throw new Error(manifest.slug + " declares an unknown step: " + type + " \u2014 add it to STEPS in contract.js");
4100
+ }
4101
+ const declared = step({});
4102
+ if (!(declared == null ? void 0 : declared.key)) throw new Error(manifest.slug + " step " + type + " needs a key \u2014 the label the builder shows");
4103
+ if (!QUEUES.includes(declared == null ? void 0 : declared.queue)) {
4104
+ throw new Error(manifest.slug + " step " + type + " needs a queue \u2014 one of " + QUEUES.join(", "));
4105
+ }
4106
+ if (declared.hook && !implemented(manifest.hooks, declared.hook)) {
4107
+ throw new Error(manifest.slug + " step " + type + " points at hook " + declared.hook + ", which this vendor does not implement");
4108
+ }
4109
+ }
4110
+ return Object.freeze({
4111
+ ...manifest,
4112
+ fields: Object.freeze(manifest.fields || []),
4113
+ hooks: Object.freeze(manifest.hooks || {}),
4114
+ inbound: Object.freeze(manifest.inbound || {}),
4115
+ requires: Object.freeze(manifest.requires || []),
4116
+ steps: Object.freeze(manifest.steps || {})
4117
+ });
4118
+ };
4119
+ var connections = Object.freeze({
4120
+ attentive: build(attentive_default2),
4121
+ drawbridge: build(drawbridge_default2),
4122
+ klaviyo: build(klaviyo_default2),
4123
+ mailchimp: build(mailchimp_default2),
4124
+ shopify: build(shopify_default2),
4125
+ webhook: build(webhook_default)
4126
+ });
4127
+ (() => {
4128
+ const owners = {};
4129
+ for (const [slug, manifest] of Object.entries(connections)) {
4130
+ for (const [name] of leaves(manifest.steps)) {
4131
+ const type = "step." + name;
4132
+ if (owners[type]) {
4133
+ throw new Error("Step " + type + " is declared by both " + owners[type] + " and " + slug);
4134
+ }
4135
+ owners[type] = slug;
4136
+ }
4137
+ }
4138
+ })();
4139
+ var publicSettingsBySlug = Object.fromEntries(
4140
+ Object.entries(connections).map(([slug, manifest]) => [
4141
+ slug,
4142
+ manifest.fields.filter((field2) => !field2.redact).map((field2) => field2.key)
4143
+ ])
4144
+ );
4145
+ var mergeSettings = ({ existing, incoming }) => {
4146
+ if (!existing || typeof existing !== "object") return incoming;
4147
+ const merged = { ...existing };
4148
+ for (const [key, value] of Object.entries(incoming || {})) {
4149
+ if (value !== void 0 && value !== null && value !== "") {
4150
+ merged[key] = value;
4151
+ }
4152
+ ;
4153
+ }
4154
+ ;
4155
+ return merged;
4156
+ };
4157
+ var publicConnectionKeys = Object.freeze([
4158
+ "actions",
4159
+ // API-COMPOSED, not manifest-declared: the api's resolve() builds it from
4160
+ // auth.type, content.redirect and the manifest's manage() — the client reads
4161
+ // connect.type to choose entered-vs-installed, connect.redirect for the App
4162
+ // Store link, connect.manage for the admin deep link. It was dropped from
4163
+ // this list when the manifests stopped declaring it, which stripped the
4164
+ // composed object from every response and broke all three.
4165
+ "connect",
4166
+ // EVERYTHING A MERCHANT READS, in one key: confirm, description, errors,
4167
+ // excerpt, guide, and any vendor redirect copy.
4168
+ "content",
4169
+ "createdAt",
4170
+ // The connection DOCUMENT's own errors array — scope-drift entries written by
4171
+ // drawbridge-sync. NOT the manifest's error copy, which is content.errors:
4172
+ // the document is spread OVER the resolved manifest downstream, so the two
4173
+ // sharing this key means the array silently wins.
4174
+ "errors",
4175
+ "fields",
4176
+ "group",
4177
+ "id",
4178
+ "image",
4179
+ "settings",
4180
+ "shop",
4181
+ "slug",
4182
+ "status",
4183
+ "tasks",
4184
+ "title",
4185
+ "updatedAt",
4186
+ "warnings"
4187
+ ]);
4188
+
4189
+ // lib/encrypt.js
4190
+ import crypto3 from "crypto";
4191
+
4192
+ // lib/token.js
4193
+ import crypto2 from "crypto";
4194
+ var generate = (bytes = 32, encoding = "base64url") => {
4195
+ const buf = crypto2.randomBytes(bytes);
4196
+ return encoding ? buf.toString(encoding) : buf;
4197
+ };
4198
+
4199
+ // lib/encrypt.js
4200
+ var ALGORITHM = "aes-256-gcm";
4201
+ var getKey = () => Buffer.from(process.env.ENCRYPT_CONNECTION_SECRET, "hex");
4202
+ var encrypt = (value) => {
4203
+ const iv = generate(12, null);
4204
+ const cipher = crypto3.createCipheriv(ALGORITHM, getKey(), iv);
4205
+ const data2 = Buffer.concat([
4206
+ cipher.update(JSON.stringify(value), "utf8"),
4207
+ cipher.final()
4208
+ ]);
4209
+ const tag = cipher.getAuthTag();
4210
+ return [iv, tag, data2].map((b) => b.toString("hex")).join(":");
4211
+ };
4212
+ var decrypt = (value) => {
4213
+ if (typeof value !== "string") return value;
4214
+ const [ivHex, tagHex, dataHex] = value.split(":");
4215
+ const decipher = crypto3.createDecipheriv(
4216
+ ALGORITHM,
4217
+ getKey(),
4218
+ Buffer.from(ivHex, "hex")
4219
+ );
4220
+ decipher.setAuthTag(Buffer.from(tagHex, "hex"));
4221
+ const result = Buffer.concat([
4222
+ decipher.update(Buffer.from(dataHex, "hex")),
4223
+ decipher.final()
4224
+ ]);
4225
+ return JSON.parse(result.toString("utf8"));
4226
+ };
4227
+
4228
+ // lib/providers.js
4229
+ var FIELDS = {
4230
+ attentive: [
4231
+ { input: "text", key: "clientId", env: "ATTENTIVE_OAUTH_CLIENT_ID", label: "Client ID", required: true },
4232
+ { input: "password", key: "clientSecret", env: "ATTENTIVE_OAUTH_CLIENT_SECRET", label: "Client secret", redact: true, required: true }
4233
+ ],
4234
+ drawbridge: [
4235
+ { input: "email", key: "accountSender", env: "SENDGRID_FROM_ADDRESS", label: "Account sender", message: "Verification codes and security alerts send from here.", required: true },
4236
+ { input: "password", key: "apiKey", env: "SENDGRID_API_KEY", label: "SendGrid API key", redact: true, required: true },
4237
+ // NOT required. The CRM sync is best-effort internal tooling and no-ops
4238
+ // without a token — requiring it would make the whole drawbridge provider
4239
+ // read not-live over something no merchant ever sees.
4240
+ { input: "password", key: "hubspotToken", env: "HUBSPOT_ACCESS_TOKEN", label: "HubSpot access token", message: "Drawbridge's own CRM portal. Internal \u2014 no merchant sees this.", redact: true },
4241
+ // Optional: SENDGRID_SEND_FROM_ADDRESS is not boot-required in sync
4242
+ // either. Unset, it degrades to the account sender rather than
4243
+ // refusing to start.
4244
+ { input: "email", key: "leadSender", env: "SENDGRID_SEND_FROM_ADDRESS", label: "Lead sender", message: "The default for lead-facing mail when a merchant has not verified their own domain." },
4245
+ { input: "text", key: "smsFrom", env: "TWILIO_ACCOUNT_FROM", label: "SMS number", required: true },
4246
+ { input: "password", key: "smsSid", env: "TWILIO_ACCOUNT_SID", label: "Twilio account SID", redact: true, required: true },
4247
+ { input: "password", key: "smsToken", env: "TWILIO_AUTH_TOKEN", label: "Twilio auth token", redact: true, required: true }
4248
+ ],
4249
+ klaviyo: [
4250
+ { input: "text", key: "clientId", env: "KLAVIYO_OAUTH_CLIENT_ID", label: "Client ID", required: true },
4251
+ { input: "password", key: "clientSecret", env: "KLAVIYO_OAUTH_CLIENT_SECRET", label: "Client secret", redact: true, required: true }
4252
+ ],
4253
+ mailchimp: [
4254
+ { input: "text", key: "clientId", env: "MAILCHIMP_OAUTH_CLIENT_ID", label: "Client ID", required: true },
4255
+ { input: "password", key: "clientSecret", env: "MAILCHIMP_OAUTH_CLIENT_SECRET", label: "Client secret", redact: true, required: true }
4256
+ ],
4257
+ shopify: [
4258
+ { input: "text", key: "apiKey", env: "SHOPIFY_API_KEY", label: "API key", required: true },
4259
+ { input: "password", key: "apiSecret", env: "SHOPIFY_API_SECRET", label: "API secret", redact: true, required: true },
4260
+ { input: "text", key: "appHandle", env: "SHOPIFY_APP_HANDLE", label: "App handle", required: true },
4261
+ { input: "text", key: "listingUrl", env: "SHOPIFY_APP_LISTING_URL", label: "App listing URL", required: true }
4262
+ ]
4263
+ };
4264
+ var providerFields = (slug) => Object.hasOwn(FIELDS, slug) ? FIELDS[slug] : [];
4265
+ var providerSlugs = () => Object.keys(FIELDS).sort();
4266
+ var isLive = (slug, settings) => {
4267
+ const fields2 = providerFields(slug);
4268
+ if (!fields2.length) return false;
4269
+ return fields2.filter((field2) => field2.required).every((field2) => Boolean(settings == null ? void 0 : settings[field2.key]));
4270
+ };
4271
+ var mask = (value) => {
4272
+ if (!value) return null;
4273
+ if (String(value).length < 16) return "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022";
4274
+ return String(value).slice(0, 3) + "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022" + String(value).slice(-4);
4275
+ };
4276
+ var providerMemo = /* @__PURE__ */ new Map();
4277
+ var MEMO_TTL_MS = 60 * 1e3;
4278
+ var clearProviderMemo = () => providerMemo.clear();
4279
+ var providerSettings = async ({ controller, slug }) => {
4280
+ const memoized = providerMemo.get(slug);
4281
+ if (memoized && Date.now() - memoized.at < MEMO_TTL_MS) return memoized.value;
4282
+ const row = await controller.get({
4283
+ collection: "provider",
4284
+ query: { slug }
4285
+ });
4286
+ const value = (row == null ? void 0 : row.settings) ? decrypt(row.settings) : {};
4287
+ providerMemo.set(slug, { at: Date.now(), value });
4288
+ return value;
4289
+ };
4290
+ var saveProviderSettings = async ({ authenticated, clear, controller, settings, slug }) => {
4291
+ const fields2 = providerFields(slug);
4292
+ if (!fields2.length) return null;
4293
+ const existing = await controller.get({
4294
+ collection: "provider",
4295
+ query: { slug }
4296
+ });
4297
+ const stored = (existing == null ? void 0 : existing.settings) ? decrypt(existing.settings) : {};
4298
+ const merged = mergeSettings({
4299
+ existing: stored,
4300
+ incoming: Object.fromEntries(fields2.map((field2) => [field2.key, settings == null ? void 0 : settings[field2.key]]))
4301
+ });
4302
+ for (const key of Array.isArray(clear) ? clear : []) {
4303
+ if (fields2.some((field2) => field2.key === key)) delete merged[key];
4304
+ }
4305
+ const result = await controller.update({
4306
+ authenticated,
4307
+ collection: "provider",
4308
+ data: {
4309
+ $set: {
4310
+ settings: encrypt(merged)
4311
+ }
4312
+ },
4313
+ options: {
4314
+ upsert: true
4315
+ },
4316
+ query: { slug }
4317
+ });
4318
+ providerMemo.delete(slug);
4319
+ return result;
4320
+ };
4321
+ var providerEnvNames = () => new Set(
4322
+ providerSlugs().flatMap((slug) => providerFields(slug)).map((field2) => field2.env).filter(Boolean)
4323
+ );
4324
+ var providerCredentials = async ({ controller }) => {
4325
+ const credentials2 = {};
4326
+ for (const slug of providerSlugs()) {
4327
+ try {
4328
+ const settings = await providerSettings({ controller, slug });
4329
+ for (const field2 of providerFields(slug)) {
4330
+ const value = settings == null ? void 0 : settings[field2.key];
4331
+ if (field2.env && value) credentials2[field2.env] = value;
4332
+ }
4333
+ } catch {
4334
+ continue;
4335
+ }
4336
+ }
4337
+ return credentials2;
4338
+ };
4339
+ export {
4340
+ clearProviderMemo,
4341
+ isLive,
4342
+ mask,
4343
+ providerCredentials,
4344
+ providerEnvNames,
4345
+ providerFields,
4346
+ providerMemo,
4347
+ providerSettings,
4348
+ providerSlugs,
4349
+ saveProviderSettings
4350
+ };