@drawbridge/drawbridge-utils 0.0.118 → 0.0.124

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.
@@ -176,6 +176,89 @@ var HOOKS = Object.freeze({
176
176
  "promotions"
177
177
  ])
178
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 effectsOf = (answer) => {
227
+ for (const key of HOOK_EFFECTS) {
228
+ if ((answer == null ? void 0 : answer[key]) !== void 0 && !Array.isArray(answer[key])) {
229
+ throw new Error("A hook returned " + key + " that is not an array");
230
+ }
231
+ }
232
+ const enqueues = (answer == null ? void 0 : answer.enqueues) || [];
233
+ const events = (answer == null ? void 0 : answer.events) || [];
234
+ const writes = (answer == null ? void 0 : answer.writes) || [];
235
+ for (const write of writes) {
236
+ if (!(write == null ? void 0 : write.collection)) throw new Error("A described write names no collection");
237
+ if (!WRITE_OPERATIONS.includes(write == null ? void 0 : write.operation)) {
238
+ throw new Error("A described write on " + write.collection + " needs an operation \u2014 one of " + WRITE_OPERATIONS.join(", "));
239
+ }
240
+ if (!(write == null ? void 0 : write.data)) throw new Error("A described write on " + write.collection + " carries no data");
241
+ if (write.operation === "update" && !write.query) {
242
+ throw new Error("A described update on " + write.collection + " has no query \u2014 that is every document in it");
243
+ }
244
+ if (write.operation === "create" && write.query) {
245
+ throw new Error("A described create on " + write.collection + " carries a query \u2014 create does not filter");
246
+ }
247
+ }
248
+ for (const enqueue of enqueues) {
249
+ if (!(enqueue == null ? void 0 : enqueue.queue)) throw new Error("A described enqueue names no queue");
250
+ if (!(enqueue == null ? void 0 : enqueue.name)) throw new Error("A described enqueue on the " + enqueue.queue + " queue names no job");
251
+ }
252
+ for (const event of events) {
253
+ if (!(event == null ? void 0 : event.event)) throw new Error("A described event has no name");
254
+ if (!(event == null ? void 0 : event.room)) throw new Error("A described " + event.event + " event has no room");
255
+ }
256
+ const transaction = Boolean(answer == null ? void 0 : answer.transaction);
257
+ if (transaction && !writes.length) {
258
+ throw new Error("A hook asked for a transaction and described no writes");
259
+ }
260
+ return { enqueues, events, transaction, writes };
261
+ };
179
262
  var STEPS = Object.freeze({
180
263
  "commerce.code.issue": "Issue discount code",
181
264
  "commerce.customer.insert": "Create customer",
@@ -385,13 +468,56 @@ var attentive_default = `<svg width="500" height="500" viewBox="0 0 500 500" fil
385
468
  <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"/>
386
469
  </svg>`;
387
470
 
388
- // lib/connections/attentive.js
471
+ // lib/phone.js
472
+ import { AsYouType, parsePhoneNumberFromString, isValidPhoneNumber } from "libphonenumber-js";
473
+ var toE164 = (value, country) => {
474
+ if (!value) return null;
475
+ try {
476
+ const parsed = parsePhoneNumberFromString(String(value), country);
477
+ return parsed ? parsed.number : null;
478
+ } catch {
479
+ return null;
480
+ }
481
+ };
482
+ var detectCountry = (value) => {
483
+ if (!value) return null;
484
+ try {
485
+ const parser = new AsYouType();
486
+ parser.input(String(value));
487
+ return parser.getCountry() || null;
488
+ } catch {
489
+ return null;
490
+ }
491
+ };
492
+
493
+ // lib/connections/providers/attentive.js
494
+ var api = async (path, { fetcher = fetch, method = "GET", payload, token }) => {
495
+ const response = await fetcher("https://api.attentivemobile.com" + path, {
496
+ ...payload && { body: JSON.stringify(payload) },
497
+ headers: {
498
+ authorization: "Bearer " + token,
499
+ ...payload && { "content-type": "application/json" }
500
+ },
501
+ method,
502
+ signal: AbortSignal.timeout(15e3)
503
+ });
504
+ if (!response.ok) {
505
+ throw Object.assign(
506
+ new Error("Attentive refused the request (" + response.status + ")"),
507
+ { status: response.status }
508
+ );
509
+ }
510
+ return response.json().catch(() => null);
511
+ };
389
512
  var attentive_default2 = {
390
513
  auth: {
391
514
  oauth: {
392
- // NAMES of the env vars holding OUR app's client — set at registration,
393
- // never before. No `headers` on the client: Attentive takes credentials
394
- // as form fields, which is the runner's default.
515
+ // NAMES of the credentials holding OUR app's client — keys into the map
516
+ // the provider collection answers, entered on the admin screen at
517
+ // registration, never before. (The names are the env vars they once
518
+ // were; the vocabulary stayed when the storage moved.) No `headers` on
519
+ // the client: Attentive takes credentials as form fields, which is the
520
+ // runner's default.
395
521
  client: {
396
522
  id: "ATTENTIVE_OAUTH_CLIENT_ID",
397
523
  secret: "ATTENTIVE_OAUTH_CLIENT_SECRET"
@@ -416,9 +542,10 @@ var attentive_default2 = {
416
542
  // has to say so rather than let them believe otherwise.
417
543
  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.",
418
544
  description: [
419
- "Attentive is where your SMS marketing lives, and this connection is becoming the way your Drawbridge contacts sync into an Attentive segment.",
545
+ "Attentive is where your SMS marketing lives, and this connection syncs the contacts your campaigns collect into an Attentive segment \u2014 subscribed for marketing and added to the segment you choose.",
420
546
  "You authorize Drawbridge from inside Attentive and can revoke that access there at any time. Drawbridge never sees or stores your Attentive password.",
421
- "Subscriber syncing is not live yet, so connecting today does nothing except choose the segment it will use when it ships."
547
+ "Anyone who has opted out in Drawbridge is sent to Attentive as an unsubscribe rather than omitted, so a person who asked not to be contacted stays suppressed in both systems instead of quietly reappearing.",
548
+ "Attentive accepts these updates and applies them in the background, so a contact appears in your segment shortly after the sync rather than the instant it runs."
422
549
  ],
423
550
  excerpt: "Sync your Drawbridge contacts into an Attentive segment.",
424
551
  guide: [
@@ -439,6 +566,10 @@ var attentive_default2 = {
439
566
  message: "Contacts your campaigns collect are synced into this segment.",
440
567
  hook: "resources.audiences",
441
568
  required: true
569
+ // CONSUMED BY THE MEMBERSHIP CALL, not by the subscribe. Attentive's
570
+ // /v1/subscriptions takes no segment id — subscription and segment
571
+ // membership are two operations here — so contacts.sync makes both calls
572
+ // and this value is the externalId the second one carries.
442
573
  // No `search : false` here, and that is a first: /v2/segments takes a
443
574
  // `name` filter (partial match, cited above), so this picker searches
444
575
  // the ACCOUNT — Klaviyo and Mailchimp can only match the fetched page.
@@ -451,17 +582,25 @@ var attentive_default2 = {
451
582
  // and contacts.sync are the first to flip.
452
583
  hooks: {
453
584
  auth: {
454
- // The exchange already yields the tokens, and Attentive documents no
455
- // account-identity endpoint to enrich them with — Klaviyo's connect
456
- // reads the account name back; this has nothing cited to read. The
457
- // callback stores the tokens and skips enrichment on `unimplemented`.
458
585
  // FALSE, NOT {}. `{}` means "supported, implemented in the repo with the
459
- // dependencies", and nothing anywhere implements either of these —
460
- // there is nothing for them to do. The exchange already yields the
461
- // tokens and Attentive documents no account-identity endpoint to
462
- // enrich them with, so connect has nothing to add; and they document
463
- // no revocation endpoint at all, so disconnect has nothing to call.
464
- // Recorded as a decision rather than left as an unkept promise.
586
+ // dependencies", and nothing anywhere implements either of these — there
587
+ // is nothing for them to do. They document no revocation endpoint at all,
588
+ // so disconnect has nothing to call. Recorded as a decision rather than
589
+ // left as an unkept promise.
590
+ //
591
+ // STILL FALSE AFTER LOOKING AGAIN, and this is the reason written down so
592
+ // nobody re-derives it. Klaviyo's connect reads the account name back so
593
+ // the card is not blank; Attentive's card stays blank. There IS an
594
+ // endpoint — GET https://api.attentivemobile.com/v1/me, Bearer, described
595
+ // on docs.attentive.com/pages/authentication/ as returning "information
596
+ // specific to your company" — but its RESPONSE SCHEMA is published
597
+ // nowhere we can read: the docs show the curl and no body. Reading
598
+ // `body.name` would be a guess, and a guess here fails at the worst
599
+ // moment, in the callback, after the merchant has already consented.
600
+ //
601
+ // A live token settles it in one call, alongside the three registration
602
+ // checks in the header. Until then the honest state is a blank field, not
603
+ // a hopeful one.
465
604
  connect: false,
466
605
  disconnect: false,
467
606
  probe: false,
@@ -483,7 +622,112 @@ var attentive_default2 = {
483
622
  }
484
623
  },
485
624
  commerce: false,
486
- contacts: { remove: false, sync: false },
625
+ // The verb the contacts.sync step points at.
626
+ contacts: {
627
+ // Not yet. Suppression syncs an opt-out as unsubscribed, which is a
628
+ // different thing from erasing the subscriber — Attentive's deletion sits
629
+ // behind their privacy-request API, which is a different grant.
630
+ remove: false,
631
+ // TWO CALLS, BECAUSE ATTENTIVE HAS TWO IDEAS.
632
+ //
633
+ // Subscribing and being in a segment are NOT the same operation here —
634
+ // unlike Klaviyo, where a subscription is created against the list itself.
635
+ // /v1/subscriptions takes no segment id at all, so the segment a merchant
636
+ // picked on this connection can only be honoured by the bulk segment
637
+ // membership API:
638
+ //
639
+ // subscribe POST /v1/subscriptions
640
+ // { user : { email, phone }, locale, subscriptionType } — the
641
+ // docs require EITHER signUpSourceId OR (locale +
642
+ // subscriptionType), and we hold no sign-up source. 202.
643
+ //
644
+ // membership POST /v2/bulk/segments/members
645
+ // { externalId, members : [ { email, phone } ] }, 1-10,000
646
+ // members, 202 with a batchJobId
647
+ // (docs.attentive.com/reference/postbulksegmentmembers).
648
+ //
649
+ // unsubscribe POST /v1/subscriptions/unsubscribe
650
+ // { user, subscriptions : [ { type, channel } ] }. 202.
651
+ //
652
+ // EVERY ONE OF THEM ANSWERS 202 ACCEPTED, which means Attentive took the
653
+ // job, not that it ran — the same distinction the Shopify usage charge
654
+ // makes between a 202 and a charge. The message below says accepted, and
655
+ // must keep saying accepted.
656
+ sync: async ({ lead, settings, suppressed, token }, { fetcher } = {}) => {
657
+ var _a, _b, _c, _d;
658
+ const segment = settings == null ? void 0 : settings.segment;
659
+ if (!segment) return { message: "No Attentive segment is chosen for this connection.", skipped: true };
660
+ 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);
661
+ const phone = toE164(((_d = (_c = lead == null ? void 0 : lead.canonical) == null ? void 0 : _c.phone) == null ? void 0 : _d.value) || (lead == null ? void 0 : lead.phone));
662
+ if (!email && !phone) return { message: "That lead has no email address or phone number to sync.", skipped: true };
663
+ const user = {
664
+ ...email && { email },
665
+ ...phone && { phone }
666
+ };
667
+ if (suppressed) {
668
+ await api("/v1/subscriptions/unsubscribe", {
669
+ fetcher,
670
+ method: "POST",
671
+ payload: {
672
+ // One entry per channel we can actually name them by. MARKETING
673
+ // is the only type Drawbridge ever subscribed them to.
674
+ subscriptions: [
675
+ ...phone ? [{ channel: "TEXT", type: "MARKETING" }] : [],
676
+ ...email ? [{ channel: "EMAIL", type: "MARKETING" }] : []
677
+ ],
678
+ user
679
+ },
680
+ token
681
+ });
682
+ return {
683
+ message: "Attentive accepted an unsubscribe for this contact \u2014 they have opted out.",
684
+ response: { accepted: true, unsubscribed: true }
685
+ };
686
+ }
687
+ await api("/v1/subscriptions", {
688
+ fetcher,
689
+ method: "POST",
690
+ payload: {
691
+ // LOCALE, because we hold no signUpSourceId and the docs require
692
+ // one or the other. The country is READ OFF the number when there
693
+ // is one — libphonenumber knows it from the calling code — rather
694
+ // than assumed; only the fallback pair below is a default, and it
695
+ // is the one value here that no vendor document dictates.
696
+ //
697
+ // ponytail: en/US default. A `signUpSourceId` field on the
698
+ // connection is the upgrade — Attentive's sign-up sources carry
699
+ // the consent language, which is a better answer than any locale
700
+ // we can infer — and it replaces this branch entirely.
701
+ locale: {
702
+ country: phone && detectCountry(phone) || "US",
703
+ language: "en"
704
+ },
705
+ subscriptionType: "MARKETING",
706
+ user
707
+ },
708
+ token
709
+ });
710
+ const membership = await api("/v2/bulk/segments/members", {
711
+ fetcher,
712
+ method: "POST",
713
+ payload: {
714
+ externalId: segment,
715
+ members: [user]
716
+ },
717
+ token
718
+ });
719
+ return {
720
+ // ACCEPTED, NOT LIVE. Both writes answered 202, which means Attentive
721
+ // queued them — a merchant who reads "synced" and looks for the person
722
+ // in Attentive a second later has been told the wrong thing.
723
+ message: "Attentive accepted this contact for the segment. Attentive processes these asynchronously, so it appears there shortly.",
724
+ response: {
725
+ accepted: true,
726
+ ...(membership == null ? void 0 : membership.batchJobId) && { batchJobId: membership.batchJobId }
727
+ }
728
+ };
729
+ }
730
+ },
487
731
  email: false,
488
732
  inbound: false,
489
733
  lifecycle: false,
@@ -496,26 +740,13 @@ var attentive_default2 = {
496
740
  // show a picker quietly missing most of a real account. The response's
497
741
  // only identifier is `externalId`, so an entry without one cannot be
498
742
  // stored and is dropped.
499
- audiences: async ({ cursor, fetcher = fetch, limit = 100, search, token }) => {
743
+ audiences: async ({ cursor, limit = 100, search, token }, { fetcher } = {}) => {
500
744
  const query = new URLSearchParams({
501
745
  limit: String(Math.min(limit, 1e3)),
502
746
  ...cursor && { cursor },
503
747
  ...(search == null ? void 0 : search.value) && { name: String(search.value).trim() }
504
748
  });
505
- const response = await fetcher(
506
- "https://api.attentivemobile.com/v2/segments?" + query,
507
- {
508
- headers: { authorization: "Bearer " + token },
509
- signal: AbortSignal.timeout(15e3)
510
- }
511
- );
512
- if (!response.ok) {
513
- throw Object.assign(
514
- new Error("Attentive refused the request (" + response.status + ")"),
515
- { status: response.status }
516
- );
517
- }
518
- const body = await response.json();
749
+ const body = await api("/v2/segments?" + query, { fetcher, token });
519
750
  return {
520
751
  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 })),
521
752
  pageInfo: {
@@ -533,33 +764,67 @@ var attentive_default2 = {
533
764
  webhook: false
534
765
  },
535
766
  icon: attentive_default,
767
+ // DRAWBRIDGE'S OWN CREDENTIALS for this vendor, as opposed to a merchant's —
768
+ // what an admin types on the provider screen, and the only declaration of it.
769
+ // It lives beside `requires`, which names the same variables: the manifest
770
+ // says what it needs and this says how someone supplies it, so a credential
771
+ // cannot be required by a vendor that offers nowhere to enter it.
772
+ //
773
+ // `redact` marks a secret — never returned by the api, and blank on save means
774
+ // keep the stored value. `required` drives the live check.
775
+ provider: {
776
+ fields: [
777
+ { input: "text", key: "clientId", credential: "ATTENTIVE_OAUTH_CLIENT_ID", label: "Client ID", required: true },
778
+ { input: "password", key: "clientSecret", credential: "ATTENTIVE_OAUTH_CLIENT_SECRET", label: "Client secret", redact: true, required: true }
779
+ ]
780
+ },
536
781
  requires: [
537
782
  "ATTENTIVE_OAUTH_CLIENT_ID",
538
783
  "ATTENTIVE_OAUTH_CLIENT_SECRET"
539
784
  ],
540
785
  slug: "attentive",
541
- // A consent with no segment chosen is authenticated and inert — the sync,
542
- // when it ships, needs somewhere to put people.
786
+ // A consent with no segment chosen is authenticated and inert — the sync needs
787
+ // somewhere to put people so the card says Pending rather than Active over
788
+ // nothing.
543
789
  status: (data2) => {
544
790
  var _a;
545
791
  return ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.segment) ? data2.status : "pending";
546
792
  },
547
- // No steps: subscriber sync has not shipped, so this vendor contributes
548
- // nothing to a workflow yet. An empty steps object is the honest declaration.
549
- steps: {},
793
+ steps: {
794
+ contacts: {
795
+ // A DECLARATION, not the work. The nesting IS the name: this is
796
+ // `step.contacts.sync`, the string a workflow document stores. Klaviyo and
797
+ // Mailchimp declare the same type — a step belongs to the capability, not
798
+ // to whoever implements it — and the connection on the step document is
799
+ // what says which vendor runs.
800
+ sync: ({ data: data2 }) => ({
801
+ hook: "contacts.sync",
802
+ // NO ACCOUNT NAME TO INTERPOLATE, unlike Klaviyo: auth.connect is false
803
+ // because Attentive publishes no account-identity response we can read
804
+ // (see its comment), and settings.segment is an opaque externalId no
805
+ // merchant would recognise in a builder label.
806
+ key: "Sync contact to Attentive",
807
+ queue: "connection",
808
+ // Nothing for a merchant to configure on the step itself — the segment
809
+ // is chosen once on the connection. Declared empty rather than omitted,
810
+ // so "this step takes no settings" and "nobody thought about settings"
811
+ // stay different statements.
812
+ settings: {},
813
+ // BOTH triggers, for the same reason as Klaviyo: lead.insert alone only
814
+ // ever fires for someone with no history yet, and crossing into a
815
+ // segment is the other moment a contact is worth pushing.
816
+ triggers: ["lead.insert", "segment.contact.add"],
817
+ usage: { actions: 1 }
818
+ })
819
+ }
820
+ },
821
+ // WHY, in the merchant's words, and what to do about it.
550
822
  tasks: (data2) => {
551
823
  var _a;
552
- return [
553
- ...((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.segment) ? [] : [
554
- {
555
- message: "Choose which Attentive segment your contacts should sync into. Until you do, nothing is being synced.",
556
- title: "Choose a segment"
557
- }
558
- ],
824
+ return ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.segment) ? [] : [
559
825
  {
560
- message: "Contact syncing to Attentive segments has not shipped yet. Nothing is being sent to Attentive right now.",
561
- title: "Subscriber sync not available yet",
562
- type: "warning"
826
+ message: "Choose which Attentive segment your contacts should sync into. Until you do, nothing is being synced.",
827
+ title: "Choose a segment"
563
828
  }
564
829
  ];
565
830
  },
@@ -612,10 +877,11 @@ var request = async ({
612
877
  // lib/hubspot.js
613
878
  var HUBSPOT_BASE = "https://api.hubapi.com";
614
879
  var hubspotRequest = ({ body, fetcher, method, path, query, token }) => {
880
+ if (!token) throw new Error("HubSpot access token missing \u2014 pass token (the drawbridge provider's hubspotToken)");
615
881
  return (fetcher || request)({
616
882
  body,
617
883
  headers: {
618
- "Authorization": "Bearer " + (token || process.env.HUBSPOT_ACCESS_TOKEN)
884
+ "Authorization": "Bearer " + token
619
885
  },
620
886
  method,
621
887
  query,
@@ -717,16 +983,15 @@ var contacts = {
717
983
  // FORGET A CONTACT, by id or by email. Account deletion — the caller had
718
984
  // to search then remove, which is one round trip it should not have to
719
985
  // know about.
720
- remove: async ({ email, fetcher, id, token }) => {
721
- const key = token || process.env.HUBSPOT_ACCESS_TOKEN;
722
- if (!key) return;
723
- const contact = id || await lookup({ email, fetcher, token: key });
986
+ remove: async ({ email, id, token }, { fetcher } = {}) => {
987
+ if (!token) return;
988
+ const contact = id || await lookup({ email, fetcher, token });
724
989
  if (!contact) return;
725
990
  return hubspotRequest({
726
991
  fetcher,
727
992
  method: "DELETE",
728
993
  path: "/crm/v3/objects/contacts/" + contact,
729
- token: key
994
+ token
730
995
  });
731
996
  },
732
997
  // Connect an account to its contact by email, creating it if absent, and
@@ -735,24 +1000,23 @@ var contacts = {
735
1000
  // no delete-old-then-create-new.
736
1001
  //
737
1002
  // Prefer the cached hubspotId; fall back to a search; create last.
738
- sync: async ({ doc, fetcher, token }) => {
1003
+ sync: async ({ doc, token }, { fetcher } = {}) => {
739
1004
  var _a, _b;
740
- const key = token || process.env.HUBSPOT_ACCESS_TOKEN;
741
- if (!key) return;
1005
+ if (!token) return;
742
1006
  if (doc == null ? void 0 : doc.hubspotId) {
743
1007
  try {
744
- return (_a = await send({ doc, fetcher, method: "PATCH", path: "/crm/v3/objects/contacts/" + doc.hubspotId, token: key })) == null ? void 0 : _a.id;
1008
+ return (_a = await send({ doc, fetcher, method: "PATCH", path: "/crm/v3/objects/contacts/" + doc.hubspotId, token })) == null ? void 0 : _a.id;
745
1009
  } catch (error) {
746
1010
  if ((error == null ? void 0 : error.status) !== 404) throw error;
747
1011
  }
748
1012
  }
749
- const existing = await lookup({ email: doc == null ? void 0 : doc.email, fetcher, token: key });
1013
+ const existing = await lookup({ email: doc == null ? void 0 : doc.email, fetcher, token });
750
1014
  return (_b = await send({
751
1015
  doc,
752
1016
  fetcher,
753
1017
  method: existing ? "PATCH" : "POST",
754
1018
  path: existing ? "/crm/v3/objects/contacts/" + existing : "/crm/v3/objects/contacts",
755
- token: key
1019
+ token
756
1020
  })) == null ? void 0 : _b.id;
757
1021
  }
758
1022
  };
@@ -762,7 +1026,7 @@ var drawbridge_default = `<svg width="500" height="500" viewBox="0 0 500 500" fi
762
1026
  <rect width="500" height="500" fill="#BAEC5F"/>
763
1027
  <g clip-path="url(#clip0_2115_2832)">
764
1028
  <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"/>
765
- <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"/>
1029
+ <path d="M360.002 127.523L323.694 108.282L284.949 178.498V321.596L322.924 391.749L359.394 372.79L326.225 311.52V188.73L360.002 127.523Z" fill="#0D1314"/>
766
1030
  </g>
767
1031
  <defs>
768
1032
  <clipPath id="clip0_2115_2832">
@@ -1208,6 +1472,36 @@ var plans = {
1208
1472
  conversion: 0.5
1209
1473
  }
1210
1474
  };
1475
+ var resolvePlan = (subscription) => {
1476
+ var _a, _b;
1477
+ const custom = subscription == null ? void 0 : subscription.custom;
1478
+ if (!custom) return plans[subscription == null ? void 0 : subscription.plan] ?? free;
1479
+ return {
1480
+ // Reusing all.features / all.limits is what keeps a custom plan the same
1481
+ // SHAPE as a catalog one: the base feature grants every plan carries, the
1482
+ // campaign limits that are always infinite, and members defaulting to
1483
+ // infinite when a deal does not name it.
1484
+ conversion: custom.conversion ?? free.conversion,
1485
+ custom: true,
1486
+ // A custom plan is a negotiated PAID deal, so it carries the paid-tier
1487
+ // baseline whether or not the deal thought to name it. Today that is the
1488
+ // sending domain: every catalog paid tier grants it, and a custom plan
1489
+ // silently lacking it would be a support ticket, not a pricing decision.
1490
+ features: all.features([organization.networking.key, ...((_a = custom.features) == null ? void 0 : _a.granted) || []]),
1491
+ limits: all.limits(((_b = custom.limits) == null ? void 0 : _b.organization) || {}),
1492
+ // A custom plan stores its overage BARE on `custom.overages` — a different
1493
+ // shape from the catalog's nested one. Number() so a deal stored as a string
1494
+ // still resolves to cents-per-action; an unnamed overage stays undefined
1495
+ // (it bills nothing) rather than becoming NaN.
1496
+ actionCents: custom.overages == null ? void 0 : Number(custom.overages),
1497
+ overages: { actions: custom.overages },
1498
+ title: custom.title || "Custom"
1499
+ };
1500
+ };
1501
+ var conversionRate = (subscription) => {
1502
+ var _a;
1503
+ return ((_a = resolvePlan(subscription)) == null ? void 0 : _a.conversion) ?? free.conversion;
1504
+ };
1211
1505
 
1212
1506
  // lib/transactions.js
1213
1507
  import { currentTraceId } from "@drawbridge/drawbridge-telemetry";
@@ -1362,7 +1656,36 @@ var channels = {
1362
1656
  }
1363
1657
  };
1364
1658
 
1365
- // lib/connections/drawbridge.js
1659
+ // lib/connections/providers/drawbridge.js
1660
+ var interpolate = (template, data2) => {
1661
+ if (!template) return template;
1662
+ return template.replace(/\{\{(\w+)\}\}/g, (_, key) => (data2 == null ? void 0 : data2[key]) != null ? String(data2[key]) : "{{" + key + "}}");
1663
+ };
1664
+ var teamRecipients = async ({ memberIds = [], organization: organization2, read }) => {
1665
+ const org = await read.get({ collection: "organization", query: { id: organization2 } });
1666
+ const owner = (org == null ? void 0 : org.owner) ? await read.get({ collection: "user", query: { id: org.owner } }) : null;
1667
+ const members = memberIds.length ? await read.aggregate({
1668
+ collection: "member",
1669
+ pipeline: [
1670
+ {
1671
+ $match: {
1672
+ id: { $in: memberIds },
1673
+ organization: organization2,
1674
+ status: "accepted"
1675
+ }
1676
+ }
1677
+ ]
1678
+ }) : [];
1679
+ const seen = /* @__PURE__ */ new Set();
1680
+ return [owner, ...members].filter((member) => {
1681
+ if (!(member == null ? void 0 : member.id) || !(member == null ? void 0 : member.email)) return false;
1682
+ const address = member.email.toLowerCase();
1683
+ if (seen.has(address)) return false;
1684
+ seen.add(address);
1685
+ return true;
1686
+ });
1687
+ };
1688
+ var queueNotification = (data2) => ({ collection: "notification", data: data2, operation: "create" });
1366
1689
  var drawbridge_default2 = {
1367
1690
  auth: {
1368
1691
  type: "none"
@@ -1380,10 +1703,15 @@ var drawbridge_default2 = {
1380
1703
  exclusive: false,
1381
1704
  fields: [],
1382
1705
  group: "developer",
1383
- // EVERY BODY LIVES IN drawbridge-sync. Sending needs the provider clients, the
1384
- // suppression collection and the queues; segment sync needs the streams. A
1385
- // published package carrying those makes every consumer carry them, which is
1386
- // the reason `{}` exists as an answer.
1706
+ // THE BODIES LIVE HERE, beside the declarations that name them. They used to
1707
+ // live in drawbridge-sync because they touch the database, the queues and the
1708
+ // sockets and a published package cannot carry a controller.
1709
+ //
1710
+ // It does not have to. A hook is a function, so everything it needs is PASSED
1711
+ // IN: `read` for the reads, `canSend` for the opt-out floor, `resolveContact`
1712
+ // for the one write whose RESULT the hook has to count. Everything else a hook
1713
+ // wants done it DESCRIBES — `writes`, `enqueues`, `events` — and the shell
1714
+ // performs it. See lib/connections/contract.js for that shape.
1387
1715
  hooks: {
1388
1716
  auth: {
1389
1717
  // Nothing to connect, revoke, probe or re-scope.
@@ -1404,13 +1732,157 @@ var drawbridge_default2 = {
1404
1732
  // accounts DRAWBRIDGE holds rather than ones a merchant connects.
1405
1733
  contacts,
1406
1734
  email: {
1407
- digest: {},
1408
- // To organization members. NEVER suppressed and never billed: an
1409
- // entrant's opt-out must not silence an alert to staff, and staff mail is
1410
- // not a metered send.
1411
- notify: {},
1412
- // To a lead. Suppression applies and the send is billed.
1413
- send: {}
1735
+ // A PERIODIC SUMMARY to the team, on a schedule trigger rather than per
1736
+ // lead.
1737
+ //
1738
+ // The count is the point: `email.notify` tells the owner one lead arrived
1739
+ // and dampens a spike to one message per bucket, which is deliberately not
1740
+ // a count. This is where "you got 43 entries this week" comes from.
1741
+ digest: async ({ context, step, workflow }, { read } = {}) => {
1742
+ var _a, _b, _c, _d;
1743
+ const days = { day: 1, month: 30, week: 7 }[(_a = workflow == null ? void 0 : workflow.trigger) == null ? void 0 : _a.event] || 7;
1744
+ const since = new Date(Date.now() - days * 24 * 60 * 60 * 1e3);
1745
+ const campaign = ((_c = (_b = workflow == null ? void 0 : workflow.trigger) == null ? void 0 : _b.filters) == null ? void 0 : _c.campaign) || null;
1746
+ const [counted] = await read.aggregate({
1747
+ collection: "lead",
1748
+ pipeline: [
1749
+ {
1750
+ $match: {
1751
+ createdAt: { $gte: since },
1752
+ organization: workflow.organization,
1753
+ ...campaign && { campaigns: { $in: [campaign] } }
1754
+ }
1755
+ },
1756
+ { $count: "count" }
1757
+ ]
1758
+ });
1759
+ const count = Number((counted == null ? void 0 : counted.count) || 0);
1760
+ const request2 = { campaign, count, days };
1761
+ if (!count) return { message: "No new leads in the period \u2014 digest skipped.", request: request2, response: { skipped: true }, skipped: true };
1762
+ const recipients = await teamRecipients({
1763
+ memberIds: ((_d = step.settings) == null ? void 0 : _d.members) || [],
1764
+ organization: workflow.organization,
1765
+ read
1766
+ });
1767
+ const values = { ...context, count };
1768
+ return {
1769
+ message: "Digest of " + count + " new lead(s) queued for " + recipients.length + " recipient(s).",
1770
+ request: request2,
1771
+ response: { count, notified: recipients.length },
1772
+ writes: recipients.map((member) => {
1773
+ var _a2, _b2;
1774
+ return queueNotification({
1775
+ audience: "member",
1776
+ message: interpolate((_a2 = step.settings) == null ? void 0 : _a2.message, values),
1777
+ organization: workflow.organization,
1778
+ send: { type: "email", email: member.email },
1779
+ title: interpolate((_b2 = step.settings) == null ? void 0 : _b2.subject, values),
1780
+ workflow: workflow.id
1781
+ });
1782
+ })
1783
+ };
1784
+ },
1785
+ // To the organization's OWN PEOPLE. Never suppressed, never
1786
+ // subscription-gated, no unsubscribe footer — telling an org's staff about
1787
+ // their own leads is not commercial mail to a stranger.
1788
+ //
1789
+ // FREE, permanently. The lead that triggered this run already consumed the
1790
+ // billable action, and `members` is a list — billing here would turn one
1791
+ // lead into five more charges and the org would be paying to read its own
1792
+ // mail. The declaration prices it at zero; the shell bills nothing for
1793
+ // zero.
1794
+ notify: async ({ context, step, workflow }, { read } = {}) => {
1795
+ var _a;
1796
+ const memberIds = ((_a = step.settings) == null ? void 0 : _a.members) || [];
1797
+ const request2 = { members: memberIds.length };
1798
+ const recipients = await teamRecipients({ memberIds, organization: workflow.organization, read });
1799
+ if (!recipients.length) {
1800
+ return {
1801
+ message: "No owner or accepted member with an email address \u2014 team notification skipped.",
1802
+ request: request2,
1803
+ response: { skipped: true },
1804
+ skipped: true
1805
+ };
1806
+ }
1807
+ const bucket = Math.floor(Date.now() / (15 * 60 * 1e3));
1808
+ return {
1809
+ message: "Team notification queued for " + recipients.length + " recipient(s).",
1810
+ request: request2,
1811
+ response: { notified: recipients.length },
1812
+ writes: recipients.map((member) => {
1813
+ var _a2, _b;
1814
+ return {
1815
+ ...queueNotification({
1816
+ audience: "member",
1817
+ // Per workflow, recipient AND bucket, so one recipient's damper
1818
+ // can never swallow another's mail and a later bucket is never
1819
+ // mistaken for a duplicate of an earlier one.
1820
+ key: "team.notify." + workflow.id + "." + member.id + "." + bucket,
1821
+ message: interpolate((_a2 = step.settings) == null ? void 0 : _a2.message, context),
1822
+ organization: workflow.organization,
1823
+ send: { type: "email", email: member.email },
1824
+ title: interpolate((_b = step.settings) == null ? void 0 : _b.subject, context),
1825
+ workflow: workflow.id
1826
+ }),
1827
+ // E11000 IS THE DAMPER WORKING: this recipient has already been
1828
+ // told within the bucket. Declared per write rather than assumed by
1829
+ // the shell, because on every other write here a duplicate key is a
1830
+ // real failure.
1831
+ ignoreDuplicate: true
1832
+ };
1833
+ })
1834
+ };
1835
+ },
1836
+ // Drawbridge sends lead-facing email itself — no merchant provider gates
1837
+ // it.
1838
+ //
1839
+ // This QUEUES rather than sends: queue/notification.js owns delivery, the
1840
+ // unsubscribe token and the CAN-SPAM footer. The step's job is to say who
1841
+ // and what, correctly, and to refuse early when it must not send at all.
1842
+ send: async ({ context, step, workflow }, { canSend, read } = {}) => {
1843
+ var _a, _b;
1844
+ const to = context == null ? void 0 : context.email;
1845
+ if (!to) throw new Error("No email address on context (context.email is required)");
1846
+ const request2 = { to };
1847
+ const { ok: sendable } = await canSend({ channel: "email", to });
1848
+ if (!sendable) return { message: "Recipient has opted out \u2014 skipped.", request: request2, response: { skipped: true }, skipped: true };
1849
+ const organization2 = await read.get({ collection: "organization", query: { id: workflow.organization } });
1850
+ const subscription = (organization2 == null ? void 0 : organization2.subscription) ? await read.get({ collection: "subscription", query: { id: organization2.subscription } }) : null;
1851
+ if ((subscription == null ? void 0 : subscription.status) !== "active") {
1852
+ return {
1853
+ message: "Organization has no active subscription \u2014 workflow-step email skipped.",
1854
+ request: request2,
1855
+ response: { skipped: true },
1856
+ skipped: true
1857
+ };
1858
+ }
1859
+ return {
1860
+ message: "Email queued for delivery to " + to + ".",
1861
+ request: request2,
1862
+ response: { queued: true },
1863
+ // NO `connection` FIELD, deliberately: the platform sends this.
1864
+ // `audience : 'lead'` states what the queue would otherwise infer from
1865
+ // shape.
1866
+ //
1867
+ // `campaign` is not decoration. queue/notification.js mints the
1868
+ // unsubscribe token with it, so it decides whether opting out is
1869
+ // scoped to this campaign or the whole organization, and it names the
1870
+ // campaign in the footer. Sending without it silently broadens every
1871
+ // opt-out to the entire organization.
1872
+ writes: [
1873
+ queueNotification({
1874
+ audience: "lead",
1875
+ campaign: (context == null ? void 0 : context.campaign) || null,
1876
+ lead: (context == null ? void 0 : context.lead) || null,
1877
+ message: interpolate((_a = step.settings) == null ? void 0 : _a.message, context),
1878
+ organization: workflow.organization,
1879
+ send: { type: "email", email: to },
1880
+ title: interpolate((_b = step.settings) == null ? void 0 : _b.subject, context),
1881
+ workflow: workflow.id
1882
+ })
1883
+ ]
1884
+ };
1885
+ }
1414
1886
  },
1415
1887
  inbound: false,
1416
1888
  lifecycle: false,
@@ -1420,13 +1892,207 @@ var drawbridge_default2 = {
1420
1892
  products: false,
1421
1893
  promotions: false
1422
1894
  },
1423
- segment: { sync: {} },
1424
- sms: { send: {} },
1895
+ segment: {
1896
+ // RECALCULATE SEGMENT MEMBERSHIP. The one FAN-OUT hook: it evaluates every
1897
+ // contact in an organization against every segment, which is too much for
1898
+ // one job, so it returns chunks and the shell defers completion.
1899
+ //
1900
+ // Returning `chunks` is the only thing that makes it different. The
1901
+ // declaration, the guards, the step document and the price are the shell's,
1902
+ // exactly as they are for a step that finishes in one go.
1903
+ sync: async ({ context, step }, { chunkSize, logger: logger2, read, resolveContact } = {}) => {
1904
+ var _a, _b, _c;
1905
+ if (!chunkSize) throw new Error("segment.sync needs chunkSize from the shell");
1906
+ const organization2 = context == null ? void 0 : context.organization;
1907
+ const configured = (_a = step == null ? void 0 : step.settings) == null ? void 0 : _a.segment;
1908
+ const request2 = { organization: organization2 || null, segmentId: configured || null };
1909
+ const release = (ids, status = "active") => {
1910
+ const released = (ids || []).filter(Boolean);
1911
+ return {
1912
+ events: organization2 ? released.map((id) => ({
1913
+ event: "organization.segments",
1914
+ payload: { id, status },
1915
+ room: "organization." + organization2
1916
+ })) : [],
1917
+ writes: released.map((id) => ({
1918
+ collection: "segment",
1919
+ data: { $set: { status } },
1920
+ operation: "update",
1921
+ query: { id }
1922
+ }))
1923
+ };
1924
+ };
1925
+ if (!organization2) {
1926
+ return {
1927
+ ...release([configured]),
1928
+ message: "Trigger data missing organization id \u2014 cannot sync segments.",
1929
+ request: request2,
1930
+ response: { skipped: true },
1931
+ skipped: true
1932
+ };
1933
+ }
1934
+ const segments = await read.aggregate({
1935
+ collection: "segment",
1936
+ pipeline: [{ $match: configured ? { id: configured, organization: organization2 } : { organization: organization2 } }]
1937
+ });
1938
+ if (!segments.length) {
1939
+ return {
1940
+ ...release([configured]),
1941
+ message: "No segments matched the request \u2014 nothing to sync.",
1942
+ request: request2,
1943
+ response: { skipped: true },
1944
+ skipped: true
1945
+ };
1946
+ }
1947
+ const segmentIds = segments.map((entry) => entry.id);
1948
+ try {
1949
+ let backfilled = 0;
1950
+ if (segments.some((entry) => entry.system)) {
1951
+ const contacted = await read.aggregate({
1952
+ collection: "contact",
1953
+ pipeline: [
1954
+ { $match: { organization: organization2 } },
1955
+ { $project: { _id: 0, leads: 1 } },
1956
+ { $unwind: "$leads" },
1957
+ { $group: { _id: null, ids: { $addToSet: "$leads" } } }
1958
+ ]
1959
+ });
1960
+ const uncontacted = await read.aggregate({
1961
+ collection: "lead",
1962
+ pipeline: [
1963
+ { $match: { id: { $nin: ((_b = contacted[0]) == null ? void 0 : _b.ids) || [] }, organization: organization2 } },
1964
+ { $project: { _id: 0, id: 1 } }
1965
+ ]
1966
+ });
1967
+ for (const lead of uncontacted) {
1968
+ try {
1969
+ await resolveContact({ leadId: lead.id });
1970
+ backfilled += 1;
1971
+ } catch (error) {
1972
+ if (error.code !== 11e3) throw error;
1973
+ }
1974
+ }
1975
+ (_c = logger2 == null ? void 0 : logger2.info) == null ? void 0 : _c.call(logger2, "segment.sync.backfill", { backfilled, organization: organization2, uncontacted: uncontacted.length });
1976
+ }
1977
+ const contacts2 = await read.aggregate({
1978
+ collection: "contact",
1979
+ pipeline: [
1980
+ { $match: { organization: organization2 } },
1981
+ { $project: { _id: 0, id: 1 } },
1982
+ { $sort: { id: 1 } }
1983
+ ]
1984
+ });
1985
+ if (!contacts2.length) {
1986
+ return {
1987
+ ...release(segmentIds),
1988
+ message: "Organization has no contacts to evaluate against segments.",
1989
+ request: request2,
1990
+ response: { skipped: true },
1991
+ skipped: true
1992
+ };
1993
+ }
1994
+ const contactIds = contacts2.map((contact) => contact.id);
1995
+ const org = await read.get({ collection: "organization", query: { id: organization2 } });
1996
+ const chunks = [];
1997
+ for (let index = 0; index < contactIds.length; index += chunkSize) {
1998
+ chunks.push({
1999
+ contactIds: contactIds.slice(index, index + chunkSize),
2000
+ organization: organization2,
2001
+ segments: segmentIds,
2002
+ // A BACKFILL IS NOT BILLABLE. It creates the contacts this run
2003
+ // then evaluates, so charging for it would bill an organization
2004
+ // for work its own history made necessary.
2005
+ usage: (context == null ? void 0 : context.billable) === true && backfilled === 0 ? (org == null ? void 0 : org.usage) || null : null
2006
+ });
2007
+ }
2008
+ return {
2009
+ chunks,
2010
+ ...configured && { extra: { segment: configured } },
2011
+ message: "Queued " + contactIds.length + " contacts across " + chunks.length + " chunks for segment evaluation.",
2012
+ queue: "segment",
2013
+ request: { ...request2, segments: segmentIds },
2014
+ response: { chunks: chunks.length, contacts: contactIds.length, segments: segments.length }
2015
+ };
2016
+ } catch (error) {
2017
+ throw Object.assign(error, release(segmentIds, "error"));
2018
+ }
2019
+ }
2020
+ },
2021
+ sms: {
2022
+ // SMS TO A LEAD, through the merchant's own Twilio connection.
2023
+ //
2024
+ // WITHDRAWN from the builder — twilio went, and a connection-gated step
2025
+ // with no connection to gate on could only ever render permanently
2026
+ // disabled. Stored workflows still carry it, so it still runs.
2027
+ //
2028
+ // It looks its own connection up rather than relying on the shell, because
2029
+ // the step is declared by the PRIVATE drawbridge connection (which has
2030
+ // none) while the credential belongs to twilio (which has no manifest).
2031
+ // Platform SMS will remove that split the way it did for email.
2032
+ send: async ({ context, step, workflow }, { canSend, read } = {}) => {
2033
+ var _a, _b, _c;
2034
+ const to = (_a = context == null ? void 0 : context.phone) == null ? void 0 : _a.number;
2035
+ if (!to) throw new Error("No phone number on context (context.phone.number is required)");
2036
+ const request2 = { to };
2037
+ const connection2 = await read.get({
2038
+ collection: "connection",
2039
+ query: { organization: workflow.organization, slug: "twilio", status: "active" }
2040
+ });
2041
+ if (!connection2) return { message: "No active Twilio SMS connection \u2014 workflow-step SMS skipped.", request: request2, response: { skipped: true }, skipped: true };
2042
+ const { ok: sendable } = await canSend({ channel: "sms", to: context.phone });
2043
+ if (!sendable) return { message: "Recipient has opted out \u2014 skipped.", request: request2, response: { skipped: true }, skipped: true };
2044
+ return {
2045
+ message: "SMS queued for delivery to " + to + " via twilio.",
2046
+ request: request2,
2047
+ response: { provider: "twilio", queued: true },
2048
+ // QUEUES rather than sends: queue/notification.js owns delivery, the
2049
+ // carrier opt-out line and the segment count this is billed on.
2050
+ writes: [
2051
+ queueNotification({
2052
+ connection: connection2.id,
2053
+ message: interpolate((_b = step.settings) == null ? void 0 : _b.message, context),
2054
+ organization: workflow.organization,
2055
+ send: { phone: { number: to }, type: "phone" },
2056
+ title: interpolate((_c = step.settings) == null ? void 0 : _c.subject, context),
2057
+ workflow: workflow.id
2058
+ })
2059
+ ]
2060
+ };
2061
+ }
2062
+ },
1425
2063
  webhook: false
1426
2064
  },
1427
2065
  icon: drawbridge_default,
1428
2066
  // PRIVATE: never in the catalog, always available to the builder.
1429
2067
  private: true,
2068
+ // THE PLATFORM'S OWN SENDING CREDENTIALS — SendGrid, Twilio, and the internal
2069
+ // HubSpot portal. No merchant ever sees these; they are what an admin types on
2070
+ // the provider screen so that Drawbridge itself can send.
2071
+ //
2072
+ // They belong on THIS manifest because this is the connection that sends: the
2073
+ // email, sms and segment hooks below are the only things that spend them, and
2074
+ // a private connection is still where a vendor fact lives.
2075
+ //
2076
+ // UNLIKE every public vendor, none of these appear in `requires` — see the
2077
+ // comment there. Availability and configuration are different questions, and a
2078
+ // missing CRM token must not take every base workflow step away.
2079
+ provider: {
2080
+ fields: [
2081
+ { input: "email", key: "accountSender", credential: "SENDGRID_FROM_ADDRESS", label: "Account sender", message: "Verification codes and security alerts send from here.", required: true },
2082
+ { input: "password", key: "apiKey", credential: "SENDGRID_API_KEY", label: "SendGrid API key", redact: true, required: true },
2083
+ // NOT required. The CRM sync is best-effort internal tooling and no-ops
2084
+ // without a token — requiring it would make the whole drawbridge provider
2085
+ // read not-live over something no merchant ever sees.
2086
+ { input: "password", key: "hubspotToken", credential: "HUBSPOT_ACCESS_TOKEN", label: "HubSpot access token", message: "Drawbridge's own CRM portal. Internal \u2014 no merchant sees this.", redact: true },
2087
+ // Optional: SENDGRID_SEND_FROM_ADDRESS is not boot-required in sync
2088
+ // either. Unset, it degrades to the account sender rather than
2089
+ // refusing to start.
2090
+ { input: "email", key: "leadSender", credential: "SENDGRID_SEND_FROM_ADDRESS", label: "Lead sender", message: "The default for lead-facing mail when a merchant has not verified their own domain." },
2091
+ { input: "text", key: "smsFrom", credential: "TWILIO_ACCOUNT_FROM", label: "SMS number", required: true },
2092
+ { input: "password", key: "smsSid", credential: "TWILIO_ACCOUNT_SID", label: "Twilio account SID", redact: true, required: true },
2093
+ { input: "password", key: "smsToken", credential: "TWILIO_AUTH_TOKEN", label: "Twilio auth token", redact: true, required: true }
2094
+ ]
2095
+ },
1430
2096
  // NOTHING, and HUBSPOT_ACCESS_TOKEN in particular must not be here.
1431
2097
  //
1432
2098
  // `requires` gates AVAILABILITY: a name in it that is unset removes the whole
@@ -1463,11 +2129,11 @@ var drawbridge_default2 = {
1463
2129
  key: "Email \u2014 Digest",
1464
2130
  queue: "notification",
1465
2131
  settings: {
1466
- // The organization OWNER is always a recipient, resolved in sync,
1467
- // so this is additional recipients rather than the list. It cannot
1468
- // be required: the members endpoint is owner-gated and the owner is
1469
- // not a member document, so a solo merchant has nothing to pick and
1470
- // could never save the step.
2132
+ // The organization OWNER is always a recipient, resolved by the
2133
+ // hook, so this is additional recipients rather than the list. It
2134
+ // cannot be required: the members endpoint is owner-gated and the
2135
+ // owner is not a member document, so a solo merchant has nothing to
2136
+ // pick and could never save the step.
1471
2137
  members: { of: "string", type: "array" },
1472
2138
  message: { required: true, type: "string" },
1473
2139
  subject: { required: true, type: "string" }
@@ -1563,12 +2229,12 @@ var drawbridge_default2 = {
1563
2229
 
1564
2230
  // lib/connections/icons/klaviyo.js
1565
2231
  var klaviyo_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
1566
- <rect width="500" height="500" fill="white"/>
2232
+ <rect width="500" height="500" fill="#FF4B32"/>
1567
2233
  <path d="M365.047 327.038H134.954V172.964H365.047L316.856 250.001L365.047 327.038Z" fill="#232121"/>
1568
2234
  </svg>`;
1569
2235
 
1570
- // lib/connections/klaviyo.js
1571
- var api = async (path, { fetcher = fetch, method = "GET", payload, token }) => {
2236
+ // lib/connections/providers/klaviyo.js
2237
+ var api2 = async (path, { fetcher = fetch, method = "GET", payload, token }) => {
1572
2238
  const response = await fetcher("https://a.klaviyo.com/api" + path, {
1573
2239
  ...payload && { body: JSON.stringify(payload) },
1574
2240
  headers: {
@@ -1604,7 +2270,8 @@ var klaviyo_default2 = {
1604
2270
  // differently, and it says so in hooks.auth.token rather than as a flag here.
1605
2271
  auth: {
1606
2272
  oauth: {
1607
- // NAMES the env vars holding OUR application's client. One identity,
2273
+ // NAMES the credentials holding OUR application's client keys into
2274
+ // the stored provider credentials, not env vars. One identity,
1608
2275
  // every merchant — the token is the merchant's and arrives from their
1609
2276
  // own consent, which is what stops one organization reading another's
1610
2277
  // data.
@@ -1744,9 +2411,9 @@ var klaviyo_default2 = {
1744
2411
  // renders an empty "Klaviyo account" field, because the merchant is
1745
2412
  // never asked which account they connected — the consent already
1746
2413
  // decided it, and asking again would be a question we can answer.
1747
- connect: async ({ fetcher, tokens }) => {
2414
+ connect: async ({ tokens }, { fetcher } = {}) => {
1748
2415
  var _a, _b, _c;
1749
- const body = await api("/accounts", { fetcher, token: tokens.accessToken });
2416
+ const body = await api2("/accounts", { fetcher, token: tokens.accessToken });
1750
2417
  const account = (_a = body == null ? void 0 : body.data) == null ? void 0 : _a[0];
1751
2418
  return {
1752
2419
  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,
@@ -1759,7 +2426,7 @@ var klaviyo_default2 = {
1759
2426
  //
1760
2427
  // Basic auth with our client, exactly like the token exchange — the
1761
2428
  // token being revoked is the subject, not the credential.
1762
- disconnect: async ({ clientId, clientSecret, fetcher = fetch, manifest, settings }) => {
2429
+ disconnect: async ({ clientId, clientSecret, manifest, settings }, { fetcher = fetch } = {}) => {
1763
2430
  const token = (settings == null ? void 0 : settings.refreshToken) || (settings == null ? void 0 : settings.accessToken);
1764
2431
  if (!token) return { revoked: false };
1765
2432
  const response = await fetcher(manifest.auth.oauth.urls.revoke, {
@@ -1782,7 +2449,7 @@ var klaviyo_default2 = {
1782
2449
  // the refresh token is the only thing that asks Klaviyo.
1783
2450
  //
1784
2451
  // It also keeps the grant warm against the 90-day idle window above.
1785
- probe: async ({ clientId, clientSecret, fetcher, manifest, settings }) => {
2452
+ probe: async ({ clientId, clientSecret, manifest, settings }, { fetcher } = {}) => {
1786
2453
  const token = await accessToken({
1787
2454
  clientId,
1788
2455
  clientSecret,
@@ -1812,19 +2479,18 @@ var klaviyo_default2 = {
1812
2479
  // the store's.
1813
2480
  commerce: false,
1814
2481
  // The verb the contacts.sync step points at. It does the work — including
1815
- // writing the profile id back onto the lead — and returns what happened.
1816
2482
  contacts: {
1817
2483
  // Not yet. Suppression syncs an opt-out as unsubscribed, which is a
1818
2484
  // different thing from deleting the profile.
1819
2485
  remove: false,
1820
- sync: async ({ contact, fetcher, lead, settings, suppressed, token }) => {
2486
+ sync: async ({ contact, lead, settings, suppressed, token }, { fetcher } = {}) => {
1821
2487
  var _a, _b, _c;
1822
2488
  const list = settings == null ? void 0 : settings.list;
1823
2489
  if (!list) return { message: "No Klaviyo list is chosen for this connection.", skipped: true };
1824
2490
  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);
1825
2491
  if (!email) return { message: "That lead has no email address to sync.", skipped: true };
1826
2492
  const totals = (contact == null ? void 0 : contact.totals) || {};
1827
- const profile = await api("/profiles/", {
2493
+ const profile = await api2("/profiles/", {
1828
2494
  fetcher,
1829
2495
  method: "POST",
1830
2496
  payload: {
@@ -1852,7 +2518,7 @@ var klaviyo_default2 = {
1852
2518
  });
1853
2519
  const profileId = (_c = profile == null ? void 0 : profile.data) == null ? void 0 : _c.id;
1854
2520
  if (!profileId) return { message: "Klaviyo returned no profile id.", skipped: true };
1855
- await api("/profile-subscription-bulk-create-jobs/", {
2521
+ await api2("/profile-subscription-bulk-create-jobs/", {
1856
2522
  fetcher,
1857
2523
  method: "POST",
1858
2524
  payload: {
@@ -1909,13 +2575,13 @@ var klaviyo_default2 = {
1909
2575
  // it, so one call quietly returns the first ten lists and an account
1910
2576
  // with more shows a picker missing the one they wanted, with nothing to
1911
2577
  // indicate anything was cut.
1912
- audiences: async ({ cursor, fetcher, limit = 100, search, token }) => {
2578
+ audiences: async ({ cursor, limit = 100, search, token }, { fetcher } = {}) => {
1913
2579
  var _a, _b;
1914
2580
  const audiences = [];
1915
2581
  let next = cursor ? "/lists?page%5Bsize%5D=10&page%5Bcursor%5D=" + encodeURIComponent(cursor) : "/lists?page%5Bsize%5D=10";
1916
2582
  let pages = 0;
1917
2583
  while (next && audiences.length < limit && pages < 20) {
1918
- const body = await api(next, { fetcher, token });
2584
+ const body = await api2(next, { fetcher, token });
1919
2585
  for (const list of (body == null ? void 0 : body.data) || []) {
1920
2586
  audiences.push({ id: list.id, title: ((_a = list == null ? void 0 : list.attributes) == null ? void 0 : _a.name) || list.id });
1921
2587
  }
@@ -1941,6 +2607,16 @@ var klaviyo_default2 = {
1941
2607
  webhook: false
1942
2608
  },
1943
2609
  icon: klaviyo_default,
2610
+ // DRAWBRIDGE'S OWN CREDENTIALS for this vendor, as opposed to a merchant's —
2611
+ // what an admin types on the provider screen. Declared here rather than in a
2612
+ // table in lib/providers.js, so a vendor's credentials sit beside the
2613
+ // `requires` that names the same variables.
2614
+ provider: {
2615
+ fields: [
2616
+ { input: "text", key: "clientId", credential: "KLAVIYO_OAUTH_CLIENT_ID", label: "Client ID", required: true },
2617
+ { input: "password", key: "clientSecret", credential: "KLAVIYO_OAUTH_CLIENT_SECRET", label: "Client secret", redact: true, required: true }
2618
+ ]
2619
+ },
1944
2620
  requires: [
1945
2621
  "KLAVIYO_OAUTH_CLIENT_ID",
1946
2622
  "KLAVIYO_OAUTH_CLIENT_SECRET"
@@ -2014,6 +2690,9 @@ var klaviyo_default2 = {
2014
2690
  title: "Klaviyo"
2015
2691
  };
2016
2692
 
2693
+ // lib/connections/providers/mailchimp.js
2694
+ import { createHash as createHash2 } from "crypto";
2695
+
2017
2696
  // lib/connections/icons/mailchimp.js
2018
2697
  var mailchimp_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
2019
2698
  <rect width="500" height="500" fill="#FFE01B"/>
@@ -2021,11 +2700,30 @@ var mailchimp_default = `<svg width="500" height="500" viewBox="0 0 500 500" fil
2021
2700
  <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"/>
2022
2701
  </svg>`;
2023
2702
 
2024
- // lib/connections/mailchimp.js
2703
+ // lib/connections/providers/mailchimp.js
2025
2704
  var base = (dc) => {
2026
2705
  if (!dc) throw new Error("This Mailchimp connection has no data centre stored, so there is no host to call");
2027
2706
  return "https://" + dc + ".api.mailchimp.com/3.0";
2028
2707
  };
2708
+ var api3 = async (path, { dc, fetcher = fetch, method = "GET", payload, token }) => {
2709
+ const response = await fetcher(base(dc) + path, {
2710
+ ...payload && { body: JSON.stringify(payload) },
2711
+ headers: {
2712
+ authorization: "Bearer " + token,
2713
+ ...payload && { "content-type": "application/json" }
2714
+ },
2715
+ method,
2716
+ signal: AbortSignal.timeout(15e3)
2717
+ });
2718
+ if (!response.ok) {
2719
+ throw Object.assign(
2720
+ new Error("Mailchimp refused the request (" + response.status + ")"),
2721
+ { status: response.status }
2722
+ );
2723
+ }
2724
+ return response.json();
2725
+ };
2726
+ var subscriberHash = (email) => createHash2("md5").update(String(email).trim().toLowerCase()).digest("hex");
2029
2727
  var mailchimp_default2 = {
2030
2728
  // OAUTH 2, authorization code. Every url below is quoted from
2031
2729
  // mailchimp.com/developer/marketing/guides/access-user-data-oauth-2/ rather
@@ -2068,7 +2766,9 @@ var mailchimp_default2 = {
2068
2766
  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.",
2069
2767
  description: [
2070
2768
  "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.",
2071
- "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."
2769
+ "Connecting Mailchimp lets Drawbridge sync the contacts your campaigns collect into a Mailchimp audience, so the people who enter a giveaway can be marketed to alongside the rest of your list.",
2770
+ "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.",
2771
+ "Someone who unsubscribed inside Mailchimp keeps that choice: a resync only sets the status of a subscriber Mailchimp has never seen before."
2072
2772
  ],
2073
2773
  excerpt: "Sync your Drawbridge contacts into a Mailchimp audience.",
2074
2774
  guide: [
@@ -2110,7 +2810,7 @@ var mailchimp_default2 = {
2110
2810
  // The header here is `OAuth <token>`, not Bearer — that is specific to
2111
2811
  // the metadata endpoint. Marketing API calls take Bearer; see the
2112
2812
  // audiences hook.
2113
- connect: async ({ fetcher = fetch, tokens }) => {
2813
+ connect: async ({ tokens }, { fetcher = fetch } = {}) => {
2114
2814
  const response = await fetcher("https://login.mailchimp.com/oauth2/metadata", {
2115
2815
  headers: {
2116
2816
  authorization: "OAuth " + (tokens == null ? void 0 : tokens.accessToken)
@@ -2143,7 +2843,51 @@ var mailchimp_default2 = {
2143
2843
  token: authToken
2144
2844
  },
2145
2845
  commerce: false,
2146
- contacts: { remove: false, sync: false },
2846
+ // The verb the contacts.sync step points at.
2847
+ contacts: {
2848
+ // Not yet. Suppression syncs an opt-out as unsubscribed, which is a
2849
+ // different thing from deleting the member — and Mailchimp's own delete is
2850
+ // permanent, so the address can never be re-added.
2851
+ remove: false,
2852
+ // PUT /lists/{list_id}/members/{subscriber_hash} — an UPSERT, which is
2853
+ // why there is no create-or-update branch here. Quoted from Mailchimp's
2854
+ // Marketing API reference for the list-members resource.
2855
+ sync: async ({ lead, settings, suppressed, token }, { fetcher } = {}) => {
2856
+ var _a, _b;
2857
+ const audience = settings == null ? void 0 : settings.audience;
2858
+ if (!audience) return { message: "No Mailchimp audience is chosen for this connection.", skipped: true };
2859
+ 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);
2860
+ if (!email) return { message: "That lead has no email address to sync.", skipped: true };
2861
+ const hash = subscriberHash(email);
2862
+ const member = await api3("/lists/" + audience + "/members/" + hash, {
2863
+ dc: settings == null ? void 0 : settings.dc,
2864
+ fetcher,
2865
+ method: "PUT",
2866
+ payload: {
2867
+ email_address: email,
2868
+ // FNAME ONLY. Unlike Klaviyo, Mailchimp's custom fields are not
2869
+ // schemaless — a merge tag that does not exist on the audience is
2870
+ // refused, taking the whole request with it — and FNAME is one of
2871
+ // the two tags every audience is created with. The Drawbridge
2872
+ // totals Klaviyo receives cannot travel until something registers
2873
+ // merge fields on the chosen audience, which is lifecycle.register's
2874
+ // job and is not built.
2875
+ ...(lead == null ? void 0 : lead.name) && { merge_fields: { FNAME: String(lead.name).trim().split(/\s+/)[0] } },
2876
+ ...suppressed && { status: "unsubscribed" },
2877
+ status_if_new: suppressed ? "unsubscribed" : "subscribed"
2878
+ },
2879
+ token
2880
+ });
2881
+ return {
2882
+ // Merged into `context` for later steps in this run.
2883
+ context: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash },
2884
+ message: suppressed ? "Synced to Mailchimp as unsubscribed \u2014 this contact has opted out." : "Synced to the Mailchimp audience.",
2885
+ // Recorded on the run for support to read back, not a write
2886
+ // instruction — the hook has already written what it needed to.
2887
+ response: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash }
2888
+ };
2889
+ }
2890
+ },
2147
2891
  // Drawbridge sends its own notification email and SMS, and owns its own
2148
2892
  // segments — see the private `drawbridge` manifest. A vendor answering
2149
2893
  // these would be a second sender, which is the arrangement the platform
@@ -2162,24 +2906,13 @@ var mailchimp_default2 = {
2162
2906
  // successful — the same silent truncation Klaviyo has, at a different
2163
2907
  // number. Paged against total_items so an account past a thousand still
2164
2908
  // resolves.
2165
- audiences: async ({ cursor, fetcher = fetch, limit = 100, search, settings, token }) => {
2166
- const dc = settings == null ? void 0 : settings.dc;
2909
+ audiences: async ({ cursor, limit = 100, search, settings, token }, { fetcher } = {}) => {
2167
2910
  const count = Math.min(limit, 1e3);
2168
2911
  const offset = Number(cursor || 0);
2169
- const response = await fetcher(
2170
- base(dc) + "/lists?count=" + count + "&offset=" + offset + "&fields=lists.id,lists.name,total_items",
2171
- {
2172
- headers: { authorization: "Bearer " + token },
2173
- signal: AbortSignal.timeout(15e3)
2174
- }
2912
+ const body = await api3(
2913
+ "/lists?count=" + count + "&offset=" + offset + "&fields=lists.id,lists.name,total_items",
2914
+ { dc: settings == null ? void 0 : settings.dc, fetcher, token }
2175
2915
  );
2176
- if (!response.ok) {
2177
- throw Object.assign(
2178
- new Error("Mailchimp refused the request (" + response.status + ")"),
2179
- { status: response.status }
2180
- );
2181
- }
2182
- const body = await response.json();
2183
2916
  const audiences = ((body == null ? void 0 : body.lists) || []).map((list) => ({ id: list.id, title: (list == null ? void 0 : list.name) || list.id }));
2184
2917
  const term = String((search == null ? void 0 : search.value) || "").trim().toLowerCase();
2185
2918
  const items = term ? audiences.filter((entry) => entry.title.toLowerCase().includes(term)) : audiences;
@@ -2201,6 +2934,15 @@ var mailchimp_default2 = {
2201
2934
  webhook: false
2202
2935
  },
2203
2936
  icon: mailchimp_default,
2937
+ // DRAWBRIDGE'S OWN CREDENTIALS for this vendor, as opposed to a merchant's —
2938
+ // what an admin types on the provider screen, beside the `requires` naming the
2939
+ // same variables.
2940
+ provider: {
2941
+ fields: [
2942
+ { input: "text", key: "clientId", credential: "MAILCHIMP_OAUTH_CLIENT_ID", label: "Client ID", required: true },
2943
+ { input: "password", key: "clientSecret", credential: "MAILCHIMP_OAUTH_CLIENT_SECRET", label: "Client secret", redact: true, required: true }
2944
+ ]
2945
+ },
2204
2946
  // The OAuth client this deployment registered. Without both, the vendor drops
2205
2947
  // out of availableConnections rather than offering a Connect button that
2206
2948
  // cannot complete.
@@ -2209,54 +2951,82 @@ var mailchimp_default2 = {
2209
2951
  "MAILCHIMP_OAUTH_CLIENT_SECRET"
2210
2952
  ],
2211
2953
  slug: "mailchimp",
2212
- // A key with no audience chosen is authenticated and inert. Mailchimp also
2213
- // needs its merge fields created on that audience before any Drawbridge total
2214
- // can be written to a member unlike Klaviyo, its custom fields are not
2215
- // schemaless so the audience must be picked before lifecycle.register has
2216
- // anything to register against.
2954
+ // A grant with no audience chosen is authenticated and useless the sync has
2955
+ // nowhere to put anyone so the card must say Pending rather than Active over
2956
+ // nothing. Mailchimp also needs its merge fields created on that audience
2957
+ // before any Drawbridge total can be written to a member — unlike Klaviyo, its
2958
+ // custom fields are not schemaless — so the audience must be picked before
2959
+ // lifecycle.register has anything to register against.
2217
2960
  status: (data2) => {
2218
2961
  var _a;
2219
2962
  return ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.audience) ? data2.status : "pending";
2220
2963
  },
2221
- // No steps: audience sync has not shipped, so this vendor contributes nothing
2222
- // to a workflow yet. An empty steps object is the honest declaration — the
2223
- // catalog renders the connection, and no builder offers a step it cannot run.
2224
- steps: {},
2964
+ steps: {
2965
+ contacts: {
2966
+ // A DECLARATION, not the work. It names the hook that does the work, and
2967
+ // the nesting IS the name: this is `step.contacts.sync`, the string a
2968
+ // workflow document stores. Klaviyo and Attentive declare the same type —
2969
+ // a step belongs to the capability, not to whoever implements it — and the
2970
+ // connection on the step document is what says which vendor runs.
2971
+ sync: ({ data: data2 }) => ({
2972
+ hook: "contacts.sync",
2973
+ // NO ACCOUNT NAME TO INTERPOLATE, unlike Klaviyo. Mailchimp's
2974
+ // auth.connect deliberately stores only the data centre (a test pins
2975
+ // that), and settings.audience is an opaque list id no merchant would
2976
+ // recognise in a builder label — so the label names the vendor rather
2977
+ // than showing a string like a1b2c3d4e5.
2978
+ key: "Sync contact to Mailchimp",
2979
+ queue: "connection",
2980
+ // Nothing for a merchant to configure on the step itself — the audience
2981
+ // is chosen once on the connection. Declared empty rather than omitted,
2982
+ // so "this step takes no settings" and "nobody thought about settings"
2983
+ // stay different statements.
2984
+ settings: {},
2985
+ // BOTH triggers, for the same reason as Klaviyo: lead.insert alone only
2986
+ // ever fires for someone with no history yet, and crossing into a
2987
+ // segment is the other moment a contact is worth pushing.
2988
+ triggers: ["lead.insert", "segment.contact.add"],
2989
+ // One source for cost: what the builder discloses before a merchant
2990
+ // adds this step, and what is charged when it runs.
2991
+ usage: { actions: 1 }
2992
+ })
2993
+ }
2994
+ },
2995
+ // WHY, in the merchant's words, and what to do about it.
2225
2996
  tasks: (data2) => {
2226
2997
  var _a;
2227
- return [
2228
- ...((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.audience) ? [] : [
2229
- {
2230
- message: "Choose which Mailchimp audience your contacts should sync into. Until you do, nothing is being synced.",
2231
- title: "Choose an audience"
2232
- }
2233
- ],
2998
+ return ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.audience) ? [] : [
2234
2999
  {
2235
- 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.",
2236
- title: "Audience sync not available yet",
2237
- type: "warning"
3000
+ message: "Choose which Mailchimp audience your contacts should sync into. Until you do, nothing is being synced.",
3001
+ title: "Choose an audience"
2238
3002
  }
2239
3003
  ];
2240
3004
  },
2241
3005
  title: "Mailchimp"
2242
3006
  };
2243
3007
 
3008
+ // lib/connections/providers/shopify.js
3009
+ import { randomUUID } from "crypto";
3010
+ import { customAlphabet as customAlphabet2 } from "nanoid";
3011
+
2244
3012
  // lib/connections/icons/shopify.js
2245
3013
  var shopify_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
2246
- <rect width="500" height="500" fill="white"/>
2247
- <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"/>
2248
- <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"/>
2249
- <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"/>
3014
+ <rect width="500" height="500" fill="#95C049"/>
3015
+ <path d="M292.997 147.633C292.997 147.633 289.98 148.495 285.023 150.004C284.161 147.202 282.868 143.969 281.144 140.521C275.54 129.744 267.134 123.925 257.22 123.925C256.574 123.925 255.927 123.925 255.065 124.141C254.849 123.71 254.418 123.494 254.203 123.063C249.892 118.322 244.289 116.166 237.607 116.382C224.676 116.813 211.744 126.081 201.399 142.676C194.071 154.314 188.468 168.97 186.959 180.393C172.088 184.919 161.743 188.152 161.527 188.367C153.984 190.738 153.768 190.954 152.906 198.066C151.613 203.454 132 355.4 132 355.4L294.937 383.633V147.202C294.075 147.418 293.429 147.418 292.997 147.633ZM255.281 159.271C246.66 161.858 237.176 164.875 227.909 167.677C230.495 157.547 235.668 147.418 241.702 140.736C244.073 138.365 247.306 135.564 250.97 133.839C254.634 141.598 255.496 152.159 255.281 159.271ZM237.823 125.003C240.84 125.003 243.427 125.649 245.582 126.943C242.133 128.667 238.685 131.469 235.452 134.702C227.262 143.538 221.012 157.332 218.426 170.479C210.667 172.85 202.908 175.22 195.796 177.376C200.322 156.901 217.779 125.649 237.823 125.003ZM212.607 243.542C213.469 257.335 249.892 260.353 252.048 292.897C253.556 318.545 238.47 336.002 216.701 337.295C190.407 339.02 175.967 323.502 175.967 323.502L181.571 299.794C181.571 299.794 196.011 310.786 207.649 309.924C215.193 309.493 217.995 303.242 217.779 298.932C216.701 280.828 186.959 281.905 185.019 252.163C183.295 227.377 199.675 202.161 235.883 199.79C249.892 198.928 257.005 202.377 257.005 202.377L248.815 233.412C248.815 233.412 239.547 229.102 228.555 229.964C212.607 231.041 212.391 241.171 212.607 243.542ZM263.902 156.685C263.902 150.219 263.039 140.952 260.022 133.193C269.936 135.133 274.678 146.124 276.833 152.806C272.954 153.883 268.643 155.176 263.902 156.685Z" fill="white"/>
3016
+ <path d="M300.325 382.771L368 365.96C368 365.96 338.904 169.185 338.689 167.892C338.473 166.599 337.396 165.737 336.318 165.737C335.24 165.737 316.274 165.306 316.274 165.306C316.274 165.306 304.636 154.099 300.325 149.788V382.771Z" fill="white"/>
2250
3017
  </svg>`;
2251
3018
 
2252
3019
  // lib/connections/inbound.js
2253
3020
  import { createHmac, timingSafeEqual } from "crypto";
2254
- var verifySignature = ({ body, descriptor, headers }) => {
3021
+ var verifySignature = ({ body, descriptor, headers, secret }) => {
3022
+ if (!secret) {
3023
+ throw Object.assign(new Error("Missing webhook secret: " + descriptor.signature.secret), { status: 500 });
3024
+ }
2255
3025
  const provided = headers[descriptor.headers.signature];
2256
3026
  if (!provided) {
2257
3027
  throw Object.assign(new Error("Missing webhook signature"), { status: 401 });
2258
3028
  }
2259
- const digest = createHmac(descriptor.signature.algorithm, process.env[descriptor.signature.secret]).update(body).digest(descriptor.signature.encoding);
3029
+ const digest = createHmac(descriptor.signature.algorithm, secret).update(body).digest(descriptor.signature.encoding);
2260
3030
  const digestBuffer = Buffer.from(digest, descriptor.signature.encoding);
2261
3031
  const providedBuffer = Buffer.from(provided, descriptor.signature.encoding);
2262
3032
  if (digestBuffer.length !== providedBuffer.length || !timingSafeEqual(digestBuffer, providedBuffer)) {
@@ -2266,7 +3036,60 @@ var verifySignature = ({ body, descriptor, headers }) => {
2266
3036
  };
2267
3037
  var readEventHeader = ({ descriptor, headers }) => headers[descriptor.headers.event];
2268
3038
 
2269
- // lib/connections/shopify.js
3039
+ // lib/email.js
3040
+ var GMAIL_DOMAINS = /* @__PURE__ */ new Set(["gmail.com", "googlemail.com"]);
3041
+ var toCanonicalEmail = (value) => {
3042
+ if (!value || typeof value !== "string") return null;
3043
+ const email = value.trim().toLowerCase();
3044
+ const at = email.lastIndexOf("@");
3045
+ if (at < 1 || at === email.length - 1) return null;
3046
+ let local = email.slice(0, at);
3047
+ const domain = email.slice(at + 1);
3048
+ const plus = local.indexOf("+");
3049
+ if (plus > 0) local = local.slice(0, plus);
3050
+ if (GMAIL_DOMAINS.has(domain)) local = local.replaceAll(".", "");
3051
+ if (!local) return null;
3052
+ return local + "@" + domain;
3053
+ };
3054
+
3055
+ // lib/connections/providers/shopify.js
3056
+ var toLine = ({
3057
+ price,
3058
+ product_id: productId,
3059
+ quantity,
3060
+ title,
3061
+ variant_id: variantId,
3062
+ variant_title: variantTitle
3063
+ }) => ({
3064
+ price: parseFloat(price) || 0,
3065
+ productId: productId ? "gid://shopify/Product/" + productId : null,
3066
+ quantity: quantity || 1,
3067
+ title: title || null,
3068
+ variantId: variantId ? "gid://shopify/ProductVariant/" + variantId : null,
3069
+ variantTitle: variantTitle || null
3070
+ });
3071
+ var attributeLineItems = (lineItems = []) => lineItems.reduce(
3072
+ (acc, item) => {
3073
+ const attrs = (item.properties || []).reduce(
3074
+ (map, { name, value }) => {
3075
+ map[name] = value;
3076
+ return map;
3077
+ },
3078
+ {}
3079
+ );
3080
+ if (!attrs["_drwbrdg_ca"]) return acc;
3081
+ if (!Object.keys(acc.attrMap).length) acc.attrMap = attrs;
3082
+ const line = toLine(item);
3083
+ acc.attributedGross += line.price * line.quantity;
3084
+ acc.attributedLines.push(line);
3085
+ return acc;
3086
+ },
3087
+ { attrMap: {}, attributedGross: 0, attributedLines: [] }
3088
+ );
3089
+ var generateDiscountCode = customAlphabet2("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8);
3090
+ var REFRESH_TOKEN_FRESHNESS_BUFFER_MS = 5 * 24 * 60 * 60 * 1e3;
3091
+ var OAUTH_ERROR_SOURCE = "oauth";
3092
+ var OAUTH_GRANT_REVOKED_CODES = ["application_cannot_be_found", "invalid_grant"];
2270
3093
  var inbound = {
2271
3094
  headers: {
2272
3095
  event: "x-shopify-topic",
@@ -2328,7 +3151,7 @@ var shopify_default2 = {
2328
3151
  // the App Store listing, and the dashboard must never imply a store can be
2329
3152
  // linked from inside it.
2330
3153
  redirect: {
2331
- env: "SHOPIFY_APP_LISTING_URL",
3154
+ credential: "SHOPIFY_APP_LISTING_URL",
2332
3155
  title: "View on the Shopify App Store"
2333
3156
  }
2334
3157
  },
@@ -2383,20 +3206,476 @@ var shopify_default2 = {
2383
3206
  //
2384
3207
  // `shopify` is injected for the same reason it is everywhere else — this
2385
3208
  // package cannot import @drawbridge/shopify, which depends on it.
2386
- scopes: ({ scope, shopify }) => scope ? shopify.oauth.missingScopes(scope) : null,
3209
+ scopes: ({ scope }, { shopify } = {}) => scope ? shopify.oauth.missingScopes(scope) : null,
2387
3210
  // Shopify's install grant is exchanged inside its own app flow, not
2388
3211
  // through the shared OAuth runner.
2389
3212
  token: false
2390
3213
  },
2391
- // Implemented in drawbridge-sync, which owns the attribution and the
2392
- // controllers it needs. Declared here so the steps below can point at them:
2393
- // a step naming a hook the vendor does not implement is a workflow that
2394
- // accepts the step and then silently does nothing.
3214
+ // THE VENDOR'S OWN WORK, here in full. Every body describes its writes,
3215
+ // enqueues and events for the shell to perform see contract.js and
3216
+ // everything it needs arrives as an argument: `read` (the controller's
3217
+ // read methods, nothing that writes), `shopify` (the SDK, injected because
3218
+ // this package cannot import what depends on it), `adminToken` (minted by
3219
+ // the shell, which persists rotations), `mintId` (so one described write
3220
+ // can reference another), `dispatch` (the caller's own coordinator table,
3221
+ // for the hooks that are dispatches).
2395
3222
  commerce: {
2396
- code: {},
2397
- customer: {},
2398
- order: {},
2399
- product: {}
3223
+ // MINT A DISCOUNT CODE against the merchant's chosen discount, mapped to
3224
+ // one lead — which is what lets an order that redeems it be attributed
3225
+ // back.
3226
+ code: async ({ connection: connection2, context, step }, { adminToken, shopify } = {}) => {
3227
+ var _a;
3228
+ const discount = (_a = step.settings) == null ? void 0 : _a.discount;
3229
+ const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection2.shop };
3230
+ if (!(context == null ? void 0 : context.email)) return { message: "Lead email is missing.", request: request2, response: { skipped: true }, skipped: true };
3231
+ if (!(context == null ? void 0 : context.lead)) return { message: "Lead id is missing.", request: request2, response: { skipped: true }, skipped: true };
3232
+ if (!(discount == null ? void 0 : discount.id)) return { message: "Discount is not configured on this step.", request: request2, response: { skipped: true }, skipped: true };
3233
+ const adminAccessToken = await adminToken();
3234
+ if (!context.shopifyCustomerId) {
3235
+ const customer = await shopify.admin.getOrCreateCustomer({ adminAccessToken, domain: connection2.shop, email: context.email });
3236
+ 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 };
3237
+ }
3238
+ const discountCode = await shopify.admin.createDiscountCode({
3239
+ adminAccessToken,
3240
+ code: "DB-" + generateDiscountCode(),
3241
+ discountId: discount.id,
3242
+ domain: connection2.shop
3243
+ });
3244
+ if (!discountCode) return { message: "Shopify did not return a discount code \u2014 create failed.", request: request2, response: { skipped: true }, skipped: true };
3245
+ return {
3246
+ context: {
3247
+ shopifyDiscountCode: discountCode.code,
3248
+ shopifyDiscountId: String(discountCode.id)
3249
+ },
3250
+ message: "Discount code created and linked to lead.",
3251
+ request: request2,
3252
+ response: { code: discountCode.code, id: String(discountCode.id) },
3253
+ // bypassDocumentValidation because these are vendor ids on a
3254
+ // Drawbridge document the schema does not declare — the
3255
+ // canonical-identity work resolves it properly.
3256
+ writes: [{
3257
+ collection: "lead",
3258
+ data: {
3259
+ $set: {
3260
+ shopifyDiscountCode: discountCode.code,
3261
+ shopifyDiscountId: String(discountCode.id)
3262
+ }
3263
+ },
3264
+ operation: "update",
3265
+ options: { bypassDocumentValidation: true },
3266
+ query: { id: context.lead }
3267
+ }]
3268
+ };
3269
+ },
3270
+ // CREATE THE BUYER AT THE STORE, so an order can be attributed to them.
3271
+ //
3272
+ // IDEMPOTENT THREE WAYS, because this runs on every entry and a duplicate
3273
+ // customer at the store is a support ticket: the context may already
3274
+ // carry the id from an earlier step, the lead may already be linked from
3275
+ // an earlier run, and Shopify's own get-or-create settles the rest.
3276
+ customer: async ({ connection: connection2, context }, { adminToken, read, shopify } = {}) => {
3277
+ const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection2.shop };
3278
+ 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 };
3279
+ 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 };
3280
+ if (context.shopifyCustomerId) {
3281
+ return {
3282
+ context: { shopifyCustomerId: context.shopifyCustomerId },
3283
+ message: "Trigger data already includes a Shopify customer id \u2014 reusing.",
3284
+ request: request2,
3285
+ response: { shopifyCustomerId: context.shopifyCustomerId },
3286
+ // Reusing an id is not a creation, so it does not bill.
3287
+ skipped: true
3288
+ };
3289
+ }
3290
+ const lead = await read.get({ collection: "lead", query: { id: context.lead } });
3291
+ if (lead == null ? void 0 : lead.shopifyCustomerId) {
3292
+ return {
3293
+ context: { shopifyCustomerId: lead.shopifyCustomerId },
3294
+ message: "Lead already has a Shopify customer id \u2014 reusing.",
3295
+ request: request2,
3296
+ response: { shopifyCustomerId: lead.shopifyCustomerId },
3297
+ skipped: true
3298
+ };
3299
+ }
3300
+ const adminAccessToken = await adminToken();
3301
+ const parts = ((lead == null ? void 0 : lead.name) || "").trim().split(/\s+/).filter(Boolean);
3302
+ const customer = await shopify.admin.getOrCreateCustomer({
3303
+ adminAccessToken,
3304
+ domain: connection2.shop,
3305
+ email: context.email,
3306
+ firstName: parts.length ? parts[0] : null,
3307
+ lastName: parts.length > 1 ? parts.slice(1).join(" ") : null,
3308
+ source: "drawbridge"
3309
+ });
3310
+ 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 };
3311
+ return {
3312
+ context: { shopifyCustomerId: customer.id },
3313
+ message: "Shopify customer created/linked to lead.",
3314
+ request: request2,
3315
+ response: { shopifyCustomerId: customer.id },
3316
+ // The hook's own result, described beside the call that produced it.
3317
+ writes: [{
3318
+ collection: "lead",
3319
+ data: { $set: { shopifyCustomerId: customer.id } },
3320
+ operation: "update",
3321
+ options: { bypassDocumentValidation: true },
3322
+ query: { id: context.lead }
3323
+ }]
3324
+ };
3325
+ },
3326
+ // AN ORDER ARRIVED AT THE STORE. The largest hook in the family, because
3327
+ // attribution genuinely is: an order can reach Drawbridge two ways and
3328
+ // they bill differently.
3329
+ //
3330
+ // CONVERSION — a `_drwbrdg_ca` line-item property, injected at
3331
+ // add-to-cart. Causal: the campaign produced the sale, so
3332
+ // it carries a fee.
3333
+ // REDEMPTION — a DB- discount code matched to a lead. Associative: we
3334
+ // cannot claim we caused the purchase, so it is fee-free.
3335
+ //
3336
+ // Both can be true, and an order already recorded as a conversion can
3337
+ // later have a redemption backfilled onto it — `backfill` below.
3338
+ //
3339
+ // IDEMPOTENT THROUGH THE RETRY, one layer up: two deliveries of the same
3340
+ // order race, the loser's transaction hits a duplicate key, the step
3341
+ // fails and BullMQ redelivers — and the re-run's read at the top finds
3342
+ // what the winner wrote and skips instead of double-billing a merchant
3343
+ // for one purchase. The hook used to loop for this itself; describing
3344
+ // the writes moved the retry to the queue, with the same guarantee.
3345
+ order: async ({ connection: connection2, context }, { logger: logger2, mintId, read } = {}) => {
3346
+ var _a, _b, _c, _d, _e, _f;
3347
+ const {
3348
+ advertisement,
3349
+ created_at: createdAt,
3350
+ currency,
3351
+ customer: orderCustomer,
3352
+ email,
3353
+ id: orderId,
3354
+ line_items: lineItems = [],
3355
+ organization: organization2,
3356
+ phone
3357
+ } = context || {};
3358
+ const request2 = { orderId: orderId ? String(orderId) : null, organization: organization2 };
3359
+ const [existingOrder, existingRedemption] = await Promise.all([
3360
+ read.get({ collection: "order", query: { "provider.id": String(orderId), "provider.slug": "shopify" } }),
3361
+ read.get({ collection: "redemption", query: { "provider.id": String(orderId), "provider.slug": "shopify" } })
3362
+ ]);
3363
+ if (existingRedemption) {
3364
+ return {
3365
+ message: "Order/redemption already recorded \u2014 skipping duplicate.",
3366
+ request: request2,
3367
+ response: {
3368
+ existingOrderId: (existingOrder == null ? void 0 : existingOrder.id) || null,
3369
+ existingRedemptionId: existingRedemption.id,
3370
+ skipped: true
3371
+ },
3372
+ skipped: true
3373
+ };
3374
+ }
3375
+ const backfill = !!existingOrder;
3376
+ const { attrMap, attributedGross, attributedLines } = attributeLineItems(lineItems);
3377
+ const campaign = attrMap["_drwbrdg_ca"] || null;
3378
+ const discountCodes = Array.isArray(context == null ? void 0 : context.discount_codes) ? context.discount_codes : [];
3379
+ const codes = [...new Set(discountCodes.map((dc) => dc == null ? void 0 : dc.code).filter(Boolean))];
3380
+ const matchedLeads = codes.length ? await read.aggregate({
3381
+ collection: "lead",
3382
+ pipeline: [{ $match: { organization: organization2, shopifyDiscountCode: { $in: codes } } }]
3383
+ }) : [];
3384
+ const codeToLead = {};
3385
+ for (const found of matchedLeads) {
3386
+ if (found.shopifyDiscountCode) codeToLead[found.shopifyDiscountCode] = found;
3387
+ }
3388
+ const matchedDiscounts = discountCodes.filter((dc) => (dc == null ? void 0 : dc.code) && codeToLead[dc.code]).map((dc) => ({
3389
+ amount: parseFloat(dc.amount) || 0,
3390
+ code: dc.code,
3391
+ id: codeToLead[dc.code].shopifyDiscountId || null
3392
+ }));
3393
+ const matchedLead = matchedDiscounts.length ? codeToLead[matchedDiscounts[0].code] : null;
3394
+ const discount = matchedDiscounts.length ? {
3395
+ amount: matchedDiscounts.reduce((sum, entry) => sum + entry.amount, 0),
3396
+ codes: matchedDiscounts
3397
+ } : null;
3398
+ const matchedCodes = new Set(matchedDiscounts.map((entry) => entry.code));
3399
+ const unmatched = codes.filter((code2) => code2.startsWith("DB-") && !matchedCodes.has(code2));
3400
+ if (unmatched.length) {
3401
+ (_a = logger2 == null ? void 0 : logger2.warn) == null ? void 0 : _a.call(logger2, "shopify.order.discount.unmatched", {
3402
+ campaign: campaign || null,
3403
+ codes: JSON.stringify(unmatched),
3404
+ isConversion: !!campaign,
3405
+ orderId: String(orderId),
3406
+ organization: organization2
3407
+ });
3408
+ }
3409
+ if (!campaign && !discount || backfill && !discount) {
3410
+ return {
3411
+ message: backfill ? "Order already recorded and no Drawbridge discount code matched \u2014 nothing to backfill." : "Order has no Drawbridge attribution \u2014 not recording.",
3412
+ request: request2,
3413
+ response: { skipped: true },
3414
+ skipped: true
3415
+ };
3416
+ }
3417
+ let advertisementId = null;
3418
+ let affiliateId = null;
3419
+ let campaignOrganization = organization2;
3420
+ let gross = 0;
3421
+ let leadId = null;
3422
+ let lines = [];
3423
+ let orderCampaign = null;
3424
+ let pageId = null;
3425
+ const isConversion = !!campaign;
3426
+ const customerPhone = toE164((orderCustomer == null ? void 0 : orderCustomer.phone) || phone) || null;
3427
+ const matchPhones = [...new Set([
3428
+ customerPhone,
3429
+ toE164((_b = context == null ? void 0 : context.billing_address) == null ? void 0 : _b.phone),
3430
+ toE164((_c = context == null ? void 0 : context.shipping_address) == null ? void 0 : _c.phone)
3431
+ ].filter(Boolean))];
3432
+ if (isConversion) {
3433
+ const campaignDoc = await read.get({ collection: "campaign", query: { id: campaign } });
3434
+ if (!campaignDoc || campaignDoc.organization !== organization2) {
3435
+ return {
3436
+ message: "Order carried a campaign attribution that does not belong to this store \u2014 not recording.",
3437
+ request: request2,
3438
+ response: { skipped: true },
3439
+ skipped: true
3440
+ };
3441
+ }
3442
+ advertisementId = attrMap["_drwbrdg_ad"] || advertisement || null;
3443
+ affiliateId = attrMap["_drwbrdg_af"] || null;
3444
+ campaignOrganization = campaignDoc.organization;
3445
+ gross = attributedGross;
3446
+ lines = attributedLines;
3447
+ orderCampaign = campaign;
3448
+ pageId = attrMap["_drwbrdg_pg"] || null;
3449
+ const identifiers = [];
3450
+ const canonicalEmail = toCanonicalEmail(email);
3451
+ if (email) identifiers.push({ email: email.toLowerCase() });
3452
+ if (canonicalEmail) identifiers.push({ "canonical.email.value": canonicalEmail });
3453
+ if (matchPhones.length) identifiers.push({ "phone.number": { $in: matchPhones } });
3454
+ if (matchPhones.length) identifiers.push({ "canonical.phone.value": { $in: matchPhones } });
3455
+ if (identifiers.length) {
3456
+ const lead = await read.get({
3457
+ collection: "lead",
3458
+ query: {
3459
+ campaigns: { $in: [campaign] },
3460
+ organization: campaignOrganization,
3461
+ $or: identifiers
3462
+ }
3463
+ });
3464
+ leadId = (lead == null ? void 0 : lead.id) || null;
3465
+ if (!leadId) {
3466
+ const orgLead = await read.get({
3467
+ collection: "lead",
3468
+ query: { organization: campaignOrganization, $or: identifiers }
3469
+ });
3470
+ leadId = (orgLead == null ? void 0 : orgLead.id) || null;
3471
+ }
3472
+ }
3473
+ } else {
3474
+ leadId = matchedLead.id;
3475
+ orderCampaign = (matchedLead.campaigns || []).length === 1 ? matchedLead.campaigns[0] : null;
3476
+ gross = lineItems.reduce((sum, item) => {
3477
+ const line = toLine(item);
3478
+ return sum + line.price * line.quantity;
3479
+ }, 0);
3480
+ lines = lineItems.map(toLine);
3481
+ }
3482
+ const org = await read.get({ collection: "organization", query: { id: campaignOrganization } });
3483
+ let rate = 0;
3484
+ if (isConversion) {
3485
+ const subscription = await read.get({ collection: "subscription", query: { id: org == null ? void 0 : org.subscription } });
3486
+ rate = conversionRate(subscription);
3487
+ }
3488
+ const fee = isConversion ? Math.round(gross * rate) / 100 : 0;
3489
+ const net2 = Math.round((gross - fee) * 100) / 100;
3490
+ const currencyCode = (currency || "usd").toLowerCase();
3491
+ const purchasedAt = new Date(createdAt || Date.now());
3492
+ const customer = orderCustomer || email || phone ? {
3493
+ 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,
3494
+ email: (orderCustomer == null ? void 0 : orderCustomer.email) || email || null,
3495
+ firstName: (orderCustomer == null ? void 0 : orderCustomer.first_name) || null,
3496
+ id: (orderCustomer == null ? void 0 : orderCustomer.id) ? String(orderCustomer.id) : null,
3497
+ lastName: (orderCustomer == null ? void 0 : orderCustomer.last_name) || null,
3498
+ phone: customerPhone
3499
+ } : null;
3500
+ const source = (connection2 == null ? void 0 : connection2.source) ? { domain: connection2.source.domain, id: connection2.source.id } : void 0;
3501
+ const orderDocId = (existingOrder == null ? void 0 : existingOrder.id) || (isConversion && !backfill ? mintId() : null);
3502
+ const writes = [];
3503
+ if (isConversion && !backfill) {
3504
+ writes.push({
3505
+ collection: "order",
3506
+ data: {
3507
+ advertisement: advertisementId,
3508
+ affiliate: affiliateId,
3509
+ campaign: orderCampaign,
3510
+ currency: currencyCode,
3511
+ customer,
3512
+ discount,
3513
+ fee,
3514
+ gross,
3515
+ id: orderDocId,
3516
+ lead: leadId,
3517
+ lines,
3518
+ net: net2,
3519
+ organization: campaignOrganization,
3520
+ page: pageId,
3521
+ provider: { id: String(orderId), slug: "shopify" },
3522
+ purchasedAt,
3523
+ rate,
3524
+ source,
3525
+ status: "completed"
3526
+ },
3527
+ operation: "create"
3528
+ });
3529
+ if (org == null ? void 0 : org.usage) {
3530
+ writes.push({
3531
+ collection: "usage",
3532
+ data: { $inc: { "totals.revenue": gross } },
3533
+ operation: "update",
3534
+ query: { id: org.usage }
3535
+ });
3536
+ }
3537
+ if (leadId) {
3538
+ writes.push({
3539
+ collection: "lead",
3540
+ data: { $inc: { "totals.orders": 1 } },
3541
+ operation: "update",
3542
+ options: { bypassDocumentValidation: true },
3543
+ query: { id: leadId }
3544
+ });
3545
+ }
3546
+ }
3547
+ if (discount) {
3548
+ writes.push({
3549
+ collection: "redemption",
3550
+ data: {
3551
+ advertisement: advertisementId,
3552
+ affiliate: affiliateId,
3553
+ campaign: orderCampaign,
3554
+ code: ((_e = matchedDiscounts[0]) == null ? void 0 : _e.code) || null,
3555
+ currency: currencyCode,
3556
+ customer,
3557
+ discount,
3558
+ gross,
3559
+ lead: leadId,
3560
+ order: orderDocId,
3561
+ organization: campaignOrganization,
3562
+ page: pageId,
3563
+ provider: { id: String(orderId), slug: "shopify" },
3564
+ purchasedAt,
3565
+ source,
3566
+ status: "completed"
3567
+ },
3568
+ operation: "create"
3569
+ });
3570
+ if (org == null ? void 0 : org.usage) {
3571
+ writes.push({
3572
+ collection: "usage",
3573
+ data: { $inc: { "totals.redemptions": 1 } },
3574
+ operation: "update",
3575
+ query: { id: org.usage }
3576
+ });
3577
+ }
3578
+ if (leadId) {
3579
+ writes.push({
3580
+ collection: "lead",
3581
+ data: { $inc: { "totals.redemptions": 1 } },
3582
+ operation: "update",
3583
+ options: { bypassDocumentValidation: true },
3584
+ query: { id: leadId }
3585
+ });
3586
+ }
3587
+ }
3588
+ const enqueues = (org == null ? void 0 : org.billingProvider) === "shopify" && fee > 0 && ((_f = connection2 == null ? void 0 : connection2.source) == null ? void 0 : _f.id) && !backfill ? [{
3589
+ data: {
3590
+ idempotencyKey: String(orderId),
3591
+ orderDocId,
3592
+ orderId: String(orderId),
3593
+ rate,
3594
+ shopId: connection2.source.id,
3595
+ // The App Events API returns no event id, so one is generated
3596
+ // here — the event handle plus the order id — and sent as the
3597
+ // event's `reference`. queue/usage.js stamps the same id onto
3598
+ // the order as billed.transaction.
3599
+ transaction: "drawbridge-orders." + orderId,
3600
+ value: Math.round(fee * 100)
3601
+ },
3602
+ name: "billing",
3603
+ options: { jobId: "shopify.usage." + orderId },
3604
+ queue: "usage"
3605
+ }] : [];
3606
+ return {
3607
+ enqueues,
3608
+ message: backfill ? "Redemption backfilled for an already-recorded order." : isConversion ? "Order recorded." : "Discount redemption recorded (fee-free).",
3609
+ request: request2,
3610
+ response: {
3611
+ campaign: orderCampaign,
3612
+ currency: currencyCode,
3613
+ discount,
3614
+ fee,
3615
+ gross,
3616
+ lead: leadId,
3617
+ lines: lines.length,
3618
+ net: net2,
3619
+ orderId: String(orderId)
3620
+ },
3621
+ // ONE TRANSACTION. The order, the redemption and both totals
3622
+ // counters land together or not at all — a half-written attribution
3623
+ // is revenue counted twice or not at all, and neither is
3624
+ // recoverable by hand.
3625
+ transaction: writes.length > 0,
3626
+ writes
3627
+ };
3628
+ },
3629
+ // A PRODUCT CHANGED AT THE STORE. Upserts the product row and hands it to
3630
+ // the product pipeline; the actual field sync happens there.
3631
+ //
3632
+ // The shell has already refused a missing or inactive Shopify connection,
3633
+ // so what is left is the two things only this hook can know are wrong.
3634
+ product: async ({ connection: connection2, context, workflow }, { mintId } = {}) => {
3635
+ const request2 = {
3636
+ numericId: (context == null ? void 0 : context.id) || null,
3637
+ organizationId: workflow.organization,
3638
+ title: (context == null ? void 0 : context.title) || null
3639
+ };
3640
+ if (!(context == null ? void 0 : context.id)) return { message: "Skipped \u2014 product webhook payload had no id.", request: request2, response: { skipped: true }, skipped: true };
3641
+ if (!connection2.shop) return { message: "Skipped \u2014 Shopify connection is missing shop domain.", request: request2, response: { skipped: true }, skipped: true };
3642
+ const providerId = "gid://shopify/Product/" + context.id;
3643
+ const productId = mintId();
3644
+ return {
3645
+ enqueues: [{
3646
+ data: { product: productId, providerId, shop: connection2.shop },
3647
+ name: "workflow",
3648
+ options: { jobId: "product.workflow.shopify." + providerId + "." + Date.now() },
3649
+ queue: "product.shopify"
3650
+ }],
3651
+ message: "Product sync queued from Shopify webhook.",
3652
+ request: request2,
3653
+ response: { productId, providerId, title: (context == null ? void 0 : context.title) || null },
3654
+ // KEYED ON PROVIDER + SHOP, so the same product in two stores stays
3655
+ // two rows. `connections` accumulates rather than replaces: one
3656
+ // store can be linked to several organizations, and each keeps its
3657
+ // own claim on the row.
3658
+ writes: [{
3659
+ collection: "product",
3660
+ data: {
3661
+ $addToSet: { connections: connection2.id },
3662
+ $setOnInsert: {
3663
+ id: productId,
3664
+ provider: { id: providerId, slug: "shopify" },
3665
+ "source.id": connection2.id,
3666
+ status: "active"
3667
+ }
3668
+ },
3669
+ operation: "update",
3670
+ options: { upsert: true },
3671
+ query: {
3672
+ "provider.id": providerId,
3673
+ "provider.slug": "shopify",
3674
+ "source.domain": connection2.shop
3675
+ }
3676
+ }]
3677
+ };
3678
+ }
2400
3679
  },
2401
3680
  contacts: { remove: false, sync: false },
2402
3681
  // verify and event lean entirely on the shared HMAC helper — Shopify's
@@ -2414,7 +3693,16 @@ var shopify_default2 = {
2414
3693
  sms: false,
2415
3694
  inbound: {
2416
3695
  event: (args) => readEventHeader({ ...args, descriptor: inbound }),
2417
- process: {},
3696
+ // One hook over the whole topic table, because that is what this
3697
+ // manifest declares: Shopify processes its own buffered events. The
3698
+ // topic rides in on the context rather than being a second hook name per
3699
+ // topic; the caller's handler table arrives as a prop.
3700
+ process: async ({ context }, { dispatch } = {}) => {
3701
+ const key = "shopify." + (context == null ? void 0 : context.topic);
3702
+ const handled = await dispatch({ data: context == null ? void 0 : context.data, handler: key });
3703
+ if (!handled) return { message: "No handler for " + key, skipped: true };
3704
+ return { message: "Processed " + key, request: { topic: context == null ? void 0 : context.topic } };
3705
+ },
2418
3706
  receive: ({ channel, event, headers, payload }) => {
2419
3707
  if (channel === "compliance" && !COMPLIANCE_TOPICS.has(event)) {
2420
3708
  throw Object.assign(new Error("Unrecognized compliance topic: " + event), { status: 401 });
@@ -2430,7 +3718,107 @@ var shopify_default2 = {
2430
3718
  },
2431
3719
  verify: (args) => verifySignature({ ...args, descriptor: inbound })
2432
3720
  },
2433
- lifecycle: { cleanup: {}, health: {}, register: {}, rehydrate: {} },
3721
+ lifecycle: {
3722
+ // DISPATCHES INTO THE CALLER'S OWN COORDINATORS. These three are
3723
+ // declarations made true: the work is queue orchestration over
3724
+ // Drawbridge's own collections, which is coordinator work and stays in
3725
+ // the repo that owns the queues. The hook receives the dispatch table as
3726
+ // a prop and picks the entry, so the manifest owns the SEAM — asking
3727
+ // Shopify whether it handles its own lifecycle now gets a real function
3728
+ // instead of `unimplemented` while the work happened anyway.
3729
+ cleanup: async ({ context }, { dispatch } = {}) => {
3730
+ await dispatch({ data: context, handler: "cleanup" });
3731
+ return { message: "Ran shopify lifecycle.cleanup", request: context || null };
3732
+ },
3733
+ // KEEP STORE ACCESS WORKING. Not a webhook monitor, despite the name the
3734
+ // step once carried — webhooks are declarative, declared in the app's
3735
+ // toml and applied by Shopify to every install, so nothing here registers
3736
+ // or checks them.
3737
+ //
3738
+ // It rotates the refresh token before its window closes, proves the
3739
+ // access token still works, reconciles the scopes the store granted
3740
+ // against the ones the app now needs, and queues a webhook
3741
+ // reconciliation.
3742
+ health: async ({ connection: connection2, workflow }, { adminToken, read, reconcileScopes, resolveSettings, rotateToken, shopify } = {}) => {
3743
+ const request2 = {
3744
+ connectionId: workflow.connection,
3745
+ organizationId: workflow.organization,
3746
+ shop: connection2.shop
3747
+ };
3748
+ const refreshTokenAtStart = (await resolveSettings()).refreshToken || null;
3749
+ try {
3750
+ const adminAccessToken = await adminToken();
3751
+ const settings = await resolveSettings();
3752
+ const refreshTokenExpiresAt = settings.refreshTokenExpiresAt;
3753
+ const needsRotation = refreshTokenExpiresAt && new Date(refreshTokenExpiresAt) < new Date(Date.now() + REFRESH_TOKEN_FRESHNESS_BUFFER_MS);
3754
+ let refreshTokenRotated = false;
3755
+ if (needsRotation) {
3756
+ await rotateToken();
3757
+ refreshTokenRotated = true;
3758
+ }
3759
+ await shopify.oauth.ping({ adminAccessToken, domain: connection2.shop });
3760
+ const scopesMissing = await reconcileScopes({ shop: connection2.shop });
3761
+ return {
3762
+ enqueues: [{
3763
+ data: {
3764
+ data: {
3765
+ connectionId: workflow.connection,
3766
+ organizationId: workflow.organization
3767
+ },
3768
+ event: "shopify.register.webhooks"
3769
+ },
3770
+ name: "register",
3771
+ options: { jobId: "connection.update.register." + workflow.connection + "." + randomUUID() },
3772
+ queue: "connection"
3773
+ }],
3774
+ 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.",
3775
+ request: request2,
3776
+ response: {
3777
+ pingedAt: /* @__PURE__ */ new Date(),
3778
+ refreshTokenExpiresAt: refreshTokenExpiresAt || null,
3779
+ refreshTokenRotated,
3780
+ scopesMissing,
3781
+ webhookReconciliationQueued: true
3782
+ }
3783
+ };
3784
+ } catch (error) {
3785
+ if (OAUTH_GRANT_REVOKED_CODES.includes(error.code)) {
3786
+ const current = await read.get({ collection: "connection", query: { id: connection2.id } });
3787
+ const refreshTokenStored = current ? (await resolveSettings(current)).refreshToken || null : null;
3788
+ const rotated = error.code === "invalid_grant" && refreshTokenStored !== refreshTokenAtStart;
3789
+ if (current && !rotated) {
3790
+ const others = (current.errors || []).filter((entry) => entry.source !== OAUTH_ERROR_SOURCE);
3791
+ error.writes = [{
3792
+ collection: "connection",
3793
+ data: {
3794
+ $set: {
3795
+ errors: [
3796
+ ...others,
3797
+ {
3798
+ message: "Shopify disconnected this store. Open the Drawbridge app in your Shopify admin to reconnect.",
3799
+ source: OAUTH_ERROR_SOURCE
3800
+ }
3801
+ ],
3802
+ status: "error"
3803
+ }
3804
+ },
3805
+ operation: "update",
3806
+ query: { id: connection2.id }
3807
+ }];
3808
+ }
3809
+ }
3810
+ throw error;
3811
+ }
3812
+ },
3813
+ register: async ({ context }, { dispatch } = {}) => {
3814
+ await dispatch({ data: context, handler: "register" });
3815
+ return { message: "Ran shopify lifecycle.register", request: context || null };
3816
+ },
3817
+ rehydrate: async ({ context }, { dispatch } = {}) => {
3818
+ await dispatch({ data: context, handler: "rehydrate" });
3819
+ return { message: "Ran shopify lifecycle.rehydrate", request: context || null };
3820
+ }
3821
+ },
2434
3822
  resources: {
2435
3823
  audiences: false,
2436
3824
  // Shopify has no separate price resource — a price belongs to a product
@@ -2450,7 +3838,7 @@ var shopify_default2 = {
2450
3838
  // credential is the caller's job because it is Drawbridge's job: the
2451
3839
  // admin token refreshes and writes itself back, which is service work,
2452
3840
  // not vendor work.
2453
- products: async ({ cursor, limit = 100, search, settings, shopify, sort }) => {
3841
+ products: async ({ cursor, limit = 100, search, settings, sort }, { shopify } = {}) => {
2454
3842
  var _a, _b, _c, _d;
2455
3843
  const products = await shopify.storefront.getProducts({
2456
3844
  cursor,
@@ -2470,7 +3858,7 @@ var shopify_default2 = {
2470
3858
  }
2471
3859
  };
2472
3860
  },
2473
- promotions: async ({ cursor, limit = 100, search, settings, shopify }) => {
3861
+ promotions: async ({ cursor, limit = 100, search, settings }, { shopify } = {}) => {
2474
3862
  var _a, _b;
2475
3863
  const discounts = await shopify.admin.getDiscounts({
2476
3864
  adminAccessToken: settings == null ? void 0 : settings.adminAccessToken,
@@ -2516,6 +3904,19 @@ var shopify_default2 = {
2516
3904
  const shop = (data2 == null ? void 0 : data2.shop) || ((_a = data2 == null ? void 0 : data2.settings) == null ? void 0 : _a.domain);
2517
3905
  return shop ? "https://admin.shopify.com/store/" + String(shop).replace(".myshopify.com", "") + "/apps/" + (env == null ? void 0 : env.SHOPIFY_APP_HANDLE) : void 0;
2518
3906
  },
3907
+ // DRAWBRIDGE'S OWN CREDENTIALS for this vendor, as opposed to a merchant's —
3908
+ // what an admin types on the provider screen. The four names below are exactly
3909
+ // what `requires` gates on, which is the point of declaring them together: a
3910
+ // name required by the manifest and enterable nowhere is a vendor that can
3911
+ // never go live from the admin screen.
3912
+ provider: {
3913
+ fields: [
3914
+ { input: "text", key: "apiKey", credential: "SHOPIFY_API_KEY", label: "API key", required: true },
3915
+ { input: "password", key: "apiSecret", credential: "SHOPIFY_API_SECRET", label: "API secret", redact: true, required: true },
3916
+ { input: "text", key: "appHandle", credential: "SHOPIFY_APP_HANDLE", label: "App handle", required: true },
3917
+ { input: "text", key: "listingUrl", credential: "SHOPIFY_APP_LISTING_URL", label: "App listing URL", required: true }
3918
+ ]
3919
+ },
2519
3920
  // A pre-launch integration: it only surfaces once the App Store listing
2520
3921
  // exists and the app is fully configured. Requiring all four means it can
2521
3922
  // never render half-configured — and absence of any one excludes the
@@ -2549,9 +3950,6 @@ var shopify_default2 = {
2549
3950
  // workflow document, and those strings cannot be renamed without a backfill.
2550
3951
  //
2551
3952
  // EVERY LEAF IS A FUNCTION so a step can read the merchant's own connection.
2552
- // The bodies these point at still live in drawbridge-sync; moving them is the
2553
- // next unit, and commerce.order.record is the one that decides whether the
2554
- // shape holds — 569 lines and 15 controller calls.
2555
3953
  steps: {
2556
3954
  commerce: {
2557
3955
  code: {
@@ -2656,7 +4054,7 @@ var shopify_default2 = {
2656
4054
  title: "Shopify"
2657
4055
  };
2658
4056
 
2659
- // lib/connections/webhook.js
4057
+ // lib/connections/providers/webhook.js
2660
4058
  import crypto from "crypto";
2661
4059
 
2662
4060
  // lib/safe-http.js
@@ -2794,7 +4192,7 @@ var safeRequest = async ({
2794
4192
  }
2795
4193
  };
2796
4194
 
2797
- // lib/connections/webhook.js
4195
+ // lib/connections/providers/webhook.js
2798
4196
  var webhook_default = {
2799
4197
  // Connecting GENERATES the secret rather than storing one the merchant typed,
2800
4198
  // so the buttons say what actually happens.
@@ -2881,11 +4279,10 @@ var webhook_default = {
2881
4279
  // That is the rule the whole split runs on: a hook lives in sync only if it
2882
4280
  // needs Drawbridge's own database, sockets or queues. This one does not.
2883
4281
  webhook: {
2884
- send: async ({ context, controller, request: send2 = safeRequest, settings, step }) => {
4282
+ send: async ({ context, lead, settings, step }, { request: send2 = safeRequest } = {}) => {
2885
4283
  const { headers = {}, method = "POST", url } = step.settings || {};
2886
4284
  const request2 = { method, url: url || null };
2887
4285
  if (!url) return { message: "Outgoing webhook URL is not configured for this step.", request: request2, response: { skipped: true }, skipped: true };
2888
- const lead = (context == null ? void 0 : context.lead) ? await controller.get({ collection: "lead", query: { id: context.lead } }) : null;
2889
4286
  const body = lead || context;
2890
4287
  request2.body = body;
2891
4288
  const outgoing = { ...headers };
@@ -2961,7 +4358,7 @@ var leaves = (node, path = []) => Object.entries(node || {}).flatMap(
2961
4358
  ([key, value]) => typeof value === "function" ? [[[...path, key].join("."), value]] : value && typeof value === "object" ? leaves(value, [...path, key]) : []
2962
4359
  );
2963
4360
  var build = (manifest) => {
2964
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
4361
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
2965
4362
  if (!(manifest == null ? void 0 : manifest.slug)) throw new Error("A connection needs a slug");
2966
4363
  if (!(manifest == null ? void 0 : manifest.title)) throw new Error(manifest.slug + " needs a title");
2967
4364
  if (!(manifest == null ? void 0 : manifest.private) && !(manifest == null ? void 0 : manifest.feature)) throw new Error(manifest.slug + " needs a plan feature key");
@@ -2991,6 +4388,17 @@ var build = (manifest) => {
2991
4388
  }
2992
4389
  }
2993
4390
  }
4391
+ for (const field2 of ((_c = manifest.provider) == null ? void 0 : _c.fields) || []) {
4392
+ if (!(field2 == null ? void 0 : field2.key) || !(field2 == null ? void 0 : field2.label)) {
4393
+ throw new Error(manifest.slug + " declares a provider field with no key or label");
4394
+ }
4395
+ if (!INPUTS.includes(field2.input)) {
4396
+ throw new Error(manifest.slug + ".provider." + field2.key + " needs an input the admin form can render \u2014 one of " + INPUTS.join(", "));
4397
+ }
4398
+ if (field2.input === "password" && !field2.redact) {
4399
+ throw new Error(manifest.slug + ".provider." + field2.key + " is a password and must declare redact : true \u2014 the api would hand the value back");
4400
+ }
4401
+ }
2994
4402
  if (typeof (manifest == null ? void 0 : manifest.icon) !== "string" || !manifest.icon.includes("<svg")) {
2995
4403
  throw new Error(manifest.slug + " needs an icon \u2014 the svg markup itself, not a path to one");
2996
4404
  }
@@ -3003,23 +4411,23 @@ var build = (manifest) => {
3003
4411
  if (!GROUPS.includes(manifest == null ? void 0 : manifest.group)) {
3004
4412
  throw new Error(manifest.slug + " needs a group \u2014 one of " + GROUPS.join(", "));
3005
4413
  }
3006
- if ((_c = manifest == null ? void 0 : manifest.connect) == null ? void 0 : _c.type) {
4414
+ if ((_d = manifest == null ? void 0 : manifest.connect) == null ? void 0 : _d.type) {
3007
4415
  throw new Error(manifest.slug + " declares connect.type \u2014 that is auth.type now");
3008
4416
  }
3009
- if (!AUTH_TYPES.includes((_d = manifest == null ? void 0 : manifest.auth) == null ? void 0 : _d.type)) {
4417
+ if (!AUTH_TYPES.includes((_e = manifest == null ? void 0 : manifest.auth) == null ? void 0 : _e.type)) {
3010
4418
  throw new Error(manifest.slug + " needs auth.type \u2014 one of " + AUTH_TYPES.join(", "));
3011
4419
  }
3012
4420
  if (manifest.auth.type === "oauth") {
3013
4421
  for (const field2 of OAUTH_FIELDS) {
3014
- if (!((_e = manifest.auth.oauth) == null ? void 0 : _e[field2])) {
4422
+ if (!((_f = manifest.auth.oauth) == null ? void 0 : _f[field2])) {
3015
4423
  throw new Error(manifest.slug + " is oauth and must declare auth.oauth." + field2);
3016
4424
  }
3017
4425
  }
3018
- if (typeof ((_g = (_f = manifest.hooks) == null ? void 0 : _f.auth) == null ? void 0 : _g.token) !== "function") {
4426
+ if (typeof ((_h = (_g = manifest.hooks) == null ? void 0 : _g.auth) == null ? void 0 : _h.token) !== "function") {
3019
4427
  throw new Error(manifest.slug + " is oauth and must implement hooks.auth.token \u2014 point it at authToken() or wrap it");
3020
4428
  }
3021
4429
  for (const url of OAUTH_URLS) {
3022
- if (!((_i = (_h = manifest.auth.oauth) == null ? void 0 : _h.urls) == null ? void 0 : _i[url])) {
4430
+ if (!((_j = (_i = manifest.auth.oauth) == null ? void 0 : _i.urls) == null ? void 0 : _j[url])) {
3023
4431
  throw new Error(manifest.slug + " is oauth and must declare auth.oauth.urls." + url);
3024
4432
  }
3025
4433
  }
@@ -3029,16 +4437,16 @@ var build = (manifest) => {
3029
4437
  );
3030
4438
  }
3031
4439
  }
3032
- if (implemented(manifest.hooks, "inbound.event") && !((_k = (_j = manifest.inbound) == null ? void 0 : _j.headers) == null ? void 0 : _k.event)) {
4440
+ if (implemented(manifest.hooks, "inbound.event") && !((_l = (_k = manifest.inbound) == null ? void 0 : _k.headers) == null ? void 0 : _l.event)) {
3033
4441
  throw new Error(manifest.slug + " implements inbound.event but declares no inbound.headers.event");
3034
4442
  }
3035
- if (implemented(manifest.hooks, "inbound.verify") && !((_m = (_l = manifest.inbound) == null ? void 0 : _l.headers) == null ? void 0 : _m.signature)) {
4443
+ if (implemented(manifest.hooks, "inbound.verify") && !((_n = (_m = manifest.inbound) == null ? void 0 : _m.headers) == null ? void 0 : _n.signature)) {
3036
4444
  throw new Error(manifest.slug + " implements inbound.verify but declares no inbound.headers.signature");
3037
4445
  }
3038
4446
  if (typeof (manifest == null ? void 0 : manifest.status) !== "function") {
3039
4447
  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");
3040
4448
  }
3041
- if (!Array.isArray((_n = manifest == null ? void 0 : manifest.content) == null ? void 0 : _n.guide) || !manifest.content.guide.length) {
4449
+ if (!Array.isArray((_o = manifest == null ? void 0 : manifest.content) == null ? void 0 : _o.guide) || !manifest.content.guide.length) {
3042
4450
  throw new Error(manifest.slug + " needs content.guide \u2014 an array of steps for its page");
3043
4451
  }
3044
4452
  if (typeof (manifest == null ? void 0 : manifest.status) !== "function") {
@@ -3050,8 +4458,8 @@ var build = (manifest) => {
3050
4458
  }
3051
4459
  for (const [domain, verbs] of Object.entries(HOOKS)) {
3052
4460
  for (const verb of verbs) {
3053
- const hook = (_p = (_o = manifest.hooks) == null ? void 0 : _o[domain]) == null ? void 0 : _p[verb];
3054
- if (((_q = manifest.hooks) == null ? void 0 : _q[domain]) === false) continue;
4461
+ const hook = (_q = (_p = manifest.hooks) == null ? void 0 : _p[domain]) == null ? void 0 : _q[verb];
4462
+ if (((_r = manifest.hooks) == null ? void 0 : _r[domain]) === false) continue;
3055
4463
  if (hook !== false && !implemented({ [domain]: { [verb]: hook } }, domain + "." + verb)) {
3056
4464
  throw new Error(manifest.slug + " must answer hooks." + domain + "." + verb + " \u2014 false, a function, or {} if another repo implements it");
3057
4465
  }
@@ -3102,14 +4510,18 @@ var connections = Object.freeze({
3102
4510
  webhook: build(webhook_default)
3103
4511
  });
3104
4512
  (() => {
3105
- const owners = {};
4513
+ var _a;
4514
+ const routes = {};
3106
4515
  for (const [slug, manifest] of Object.entries(connections)) {
3107
- for (const [name] of leaves(manifest.steps)) {
4516
+ for (const [name, step] of leaves(manifest.steps)) {
3108
4517
  const type = "step." + name;
3109
- if (owners[type]) {
3110
- throw new Error("Step " + type + " is declared by both " + owners[type] + " and " + slug);
4518
+ const queue = (_a = step({})) == null ? void 0 : _a.queue;
4519
+ if (routes[type] && routes[type].queue !== queue) {
4520
+ throw new Error(
4521
+ "Step " + type + " routes to " + routes[type].queue + " for " + routes[type].slug + " and " + queue + " for " + slug + " \u2014 one of them would be enqueued nowhere"
4522
+ );
3111
4523
  }
3112
- owners[type] = slug;
4524
+ routes[type] = { queue, slug };
3113
4525
  }
3114
4526
  }
3115
4527
  })();
@@ -3156,10 +4568,13 @@ var connectFields = (slug) => {
3156
4568
  secret: Boolean(redact)
3157
4569
  }));
3158
4570
  };
3159
- var runHook = async (slug, name, args = {}) => {
4571
+ var runHook = async (slug, name, props = {}, options = {}) => {
3160
4572
  const manifest = connections[slug];
3161
4573
  if (!manifest) return { outcome: OUTCOMES.unsupported, reason: "no such connection: " + slug };
3162
- const hook = name.split(".").reduce((node, key) => node == null ? void 0 : node[key], manifest.hooks);
4574
+ const hook = name.split(".").reduce(
4575
+ (node, key) => node && typeof node === "object" && Object.hasOwn(node, key) ? node[key] : void 0,
4576
+ manifest.hooks
4577
+ );
3163
4578
  if (hook === false || hook == null) {
3164
4579
  return { outcome: OUTCOMES.unsupported, reason: slug + " does not implement " + name };
3165
4580
  }
@@ -3167,7 +4582,9 @@ var runHook = async (slug, name, args = {}) => {
3167
4582
  return { outcome: OUTCOMES.unimplemented, reason: slug + " implements " + name + " outside this package" };
3168
4583
  }
3169
4584
  try {
3170
- return { outcome: OUTCOMES.answered, result: await hook({ ...args, manifest }) };
4585
+ const result = await hook({ ...props, manifest }, options);
4586
+ effectsOf(result);
4587
+ return { outcome: OUTCOMES.answered, result };
3171
4588
  } catch (error) {
3172
4589
  return { error: (error == null ? void 0 : error.message) || "failed", outcome: OUTCOMES.failed, status: (error == null ? void 0 : error.status) || null };
3173
4590
  }
@@ -3251,7 +4668,7 @@ var projectConnection = (record) => {
3251
4668
  var resolveConnection = (item, data2, env = {}) => {
3252
4669
  if (!item) return item;
3253
4670
  return Object.fromEntries(
3254
- Object.entries(item).filter(([key]) => !["auth", "enabled", "fields", "hooks", "inbound", "requires", "steps", "supports"].includes(key)).map(([key, value]) => [
4671
+ Object.entries(item).filter(([key]) => !["auth", "enabled", "fields", "hooks", "inbound", "provider", "requires", "steps", "supports"].includes(key)).map(([key, value]) => [
3255
4672
  key,
3256
4673
  typeof value === "function" ? value(data2, env) : value
3257
4674
  ])
@@ -3261,7 +4678,10 @@ export {
3261
4678
  AUTH_TYPES,
3262
4679
  GROUPS,
3263
4680
  HOOKS,
4681
+ HOOK_EFFECTS,
3264
4682
  HOOK_NAMES,
4683
+ HOOK_OPTIONS,
4684
+ HOOK_PROPS,
3265
4685
  INPUTS,
3266
4686
  OAUTH_FIELDS,
3267
4687
  OUTCOMES,
@@ -3269,6 +4689,7 @@ export {
3269
4689
  STATUSES,
3270
4690
  STEPS,
3271
4691
  STEP_TYPES,
4692
+ WRITE_OPERATIONS,
3272
4693
  accessToken,
3273
4694
  authToken,
3274
4695
  availableConnections,
@@ -3278,6 +4699,7 @@ export {
3278
4699
  connectionSteps,
3279
4700
  connections,
3280
4701
  consentUrl,
4702
+ effectsOf,
3281
4703
  hookSupport,
3282
4704
  isStale,
3283
4705
  mergeSettings,