@drawbridge/drawbridge-utils 0.0.176 → 0.0.177

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.
Files changed (69) hide show
  1. package/dist/admin-B9ZaLvan.d.cts +697 -0
  2. package/dist/admin-C3HtEM6h.d.ts +697 -0
  3. package/dist/billing-Bc4yo9XG.d.cts +175 -0
  4. package/dist/billing-mNsKflmQ.d.ts +175 -0
  5. package/dist/billing.d.cts +1 -1
  6. package/dist/billing.d.ts +1 -1
  7. package/dist/connections/index.cjs +3077 -228
  8. package/dist/connections/index.d.cts +13 -4
  9. package/dist/connections/index.d.ts +13 -4
  10. package/dist/connections/index.js +3107 -255
  11. package/dist/features.cjs +2940 -226
  12. package/dist/features.d.cts +13 -4
  13. package/dist/features.d.ts +13 -4
  14. package/dist/features.js +2980 -260
  15. package/dist/http.cjs +10 -1
  16. package/dist/http.d.cts +10 -1
  17. package/dist/http.d.ts +10 -1
  18. package/dist/http.js +10 -1
  19. package/dist/{index-B8JhYfvU.d.ts → index-B546oDNo.d.ts} +2837 -956
  20. package/dist/{index-qY18QITf.d.cts → index-C59xHago.d.cts} +2837 -956
  21. package/dist/oauth/index.d.cts +1 -1
  22. package/dist/oauth/index.d.ts +1 -1
  23. package/dist/oauth-BJDh0sdM.d.cts +527 -0
  24. package/dist/oauth-DveZMLHx.d.ts +527 -0
  25. package/dist/partner-BOZltuh2.d.ts +94 -0
  26. package/dist/partner-ed2OfW1J.d.cts +94 -0
  27. package/dist/plans.cjs +2939 -225
  28. package/dist/plans.d.cts +13 -4
  29. package/dist/plans.d.ts +13 -4
  30. package/dist/plans.js +2980 -260
  31. package/dist/pricing.cjs +2972 -258
  32. package/dist/pricing.d.cts +13 -4
  33. package/dist/pricing.d.ts +13 -4
  34. package/dist/pricing.js +2977 -257
  35. package/dist/providers.cjs +2942 -247
  36. package/dist/providers.d.cts +12 -3
  37. package/dist/providers.d.ts +12 -3
  38. package/dist/providers.js +2946 -245
  39. package/dist/sendgrid.cjs +10 -1
  40. package/dist/sendgrid.js +10 -1
  41. package/dist/shopify/admin.cjs +562 -0
  42. package/dist/shopify/admin.d.cts +3 -0
  43. package/dist/shopify/admin.d.ts +3 -0
  44. package/dist/shopify/admin.js +528 -0
  45. package/dist/shopify/billing.cjs +166 -0
  46. package/dist/shopify/billing.d.cts +3 -0
  47. package/dist/shopify/billing.d.ts +3 -0
  48. package/dist/shopify/billing.js +140 -0
  49. package/dist/shopify/constants.cjs +63 -0
  50. package/dist/shopify/constants.d.cts +58 -0
  51. package/dist/shopify/constants.d.ts +58 -0
  52. package/dist/shopify/constants.js +32 -0
  53. package/dist/shopify/oauth.cjs +509 -0
  54. package/dist/shopify/oauth.d.cts +7 -0
  55. package/dist/shopify/oauth.d.ts +7 -0
  56. package/dist/shopify/oauth.js +466 -0
  57. package/dist/shopify/partner.cjs +156 -0
  58. package/dist/shopify/partner.d.cts +3 -0
  59. package/dist/shopify/partner.d.ts +3 -0
  60. package/dist/shopify/partner.js +130 -0
  61. package/dist/shopify/storefront.cjs +611 -0
  62. package/dist/shopify/storefront.d.cts +3 -0
  63. package/dist/shopify/storefront.d.ts +3 -0
  64. package/dist/shopify/storefront.js +576 -0
  65. package/dist/storefront-C8FKOGeD.d.cts +659 -0
  66. package/dist/storefront-DJFGLqPl.d.ts +659 -0
  67. package/dist/twilio.cjs +10 -1
  68. package/dist/twilio.js +10 -1
  69. package/package.json +98 -68
package/dist/pricing.js CHANGED
@@ -1,3 +1,9 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all2) => {
3
+ for (var name in all2)
4
+ __defProp(target, name, { get: all2[name], enumerable: true });
5
+ };
6
+
1
7
  // lib/channels.js
2
8
  var channels = {
3
9
  email: {
@@ -417,6 +423,10 @@ var HOOKS = Object.freeze({
417
423
  "code",
418
424
  // Create the buyer at the vendor, so an order can be attributed to them.
419
425
  "customer",
426
+ // HOW MANY OF THIS PRODUCT ARE LEFT, at the vendor. Read at the moment a
427
+ // campaign's product list is rendered rather than stored, because stock is
428
+ // the one product fact that is stale the instant it is written down.
429
+ "inventory",
420
430
  // An order arrived at the vendor: attribute it, record it, update totals.
421
431
  "order",
422
432
  // Pull product data across on a vendor update.
@@ -484,7 +494,19 @@ var HOOKS = Object.freeze({
484
494
  organizations: Object.freeze(["add", "list", "remove"]),
485
495
  // What the merchant pays the VENDOR. Pairs with auth.install.billing, which
486
496
  // declares the plan they are being charged on.
487
- plan: Object.freeze(["cancel", "reselect"]),
497
+ //
498
+ // `verify` is the odd one of the three: not something a merchant does, but
499
+ // the question "is this store's billing actually metered right now". It is
500
+ // here because it is the same subject — and because the answer was being
501
+ // derived in TWO places, the vendor's health check and drawbridge-sync's
502
+ // approval webhook, whose copy said in its own comment that it matched the
503
+ // other and did not.
504
+ // `charge` and `verify` are the two that are not merchant actions: one
505
+ // sends a usage charge to the vendor's meter, the other asks whether that
506
+ // meter is actually working. Both are here because both are the same
507
+ // subject — what the merchant pays the vendor — and both were being done
508
+ // from drawbridge-sync with a direct import of the vendor's client.
509
+ plan: Object.freeze(["cancel", "charge", "reselect", "verify"]),
488
510
  // The embedded app's own session, stored by us on the vendor's behalf.
489
511
  session: Object.freeze(["clear", "read", "save"]),
490
512
  // The one-time code that hands a merchant from the embedded app into
@@ -569,7 +591,7 @@ var ANSWER_KEYS = Object.freeze([
569
591
  "usage"
570
592
  ].sort());
571
593
  var WRITE_OPERATIONS = Object.freeze(["create", "delete", "update"]);
572
- var INSTALL_SIGNATURE = Object.freeze({ options: ["read", "request"], props: ["context"] });
594
+ var INSTALL_SIGNATURE = Object.freeze({ options: ["read"], props: ["context"] });
573
595
  var LIFECYCLE_SIGNATURE = Object.freeze({ options: ["dispatch"], props: ["context"] });
574
596
  var RESOURCE_SIGNATURE = Object.freeze({
575
597
  options: ["fetcher", "shopify"],
@@ -586,15 +608,30 @@ var HOOK_SLOT_PROPS = Object.freeze({
586
608
  // the second bag would be silently discarded, which is exactly the
587
609
  // stubbed-fetcher-reaches-production failure the split exists to prevent.
588
610
  "auth.token": false,
589
- // COMMERCE. `cart` is declared and unimplemented the Checkout Kit path in
590
- // api/route/subdomain.js writes nothing, which is why it never became a hook
591
- // so its signature mirrors `code`, its nearest sibling, and moving the
592
- // route here is a deliberate widening of this line rather than a silent one.
593
- "commerce.cart": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context", "step"] }),
611
+ // COMMERCE. `cart` is the odd one: it runs for a SHOPPER on a public page,
612
+ // not for an organization inside a workflow, so it takes no `connection` and
613
+ // no `step`. It reads the storefront with the store's own storefront token
614
+ // and mints a checkout token from DRAWBRIDGE'S app credentials, which is why
615
+ // `clientId`/`clientSecret` are here as props, the way auth.disconnect
616
+ // already carries them, because a credential is a fact of the run rather
617
+ // than a service.
618
+ "commerce.cart": Object.freeze({
619
+ options: ["fetcher", "shopify"],
620
+ props: ["clientId", "clientSecret", "context", "settings"]
621
+ }),
594
622
  "commerce.code": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context", "step"] }),
595
623
  "commerce.customer": Object.freeze({ options: ["adminToken", "read", "shopify"], props: ["connection", "context"] }),
624
+ "commerce.inventory": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context"] }),
596
625
  "commerce.order": Object.freeze({ options: ["conversionRate", "logger", "mintId", "read"], props: ["connection", "context"] }),
597
- "commerce.product": Object.freeze({ options: ["mintId", "read"], props: ["connection", "context", "workflow"] }),
626
+ // THREE OPERATIONS, one slot — record, sync, variants. `settings` and
627
+ // `adminToken` arrived with the pull half: the storefront read needs the
628
+ // store's storefront token and the product-feedback send needs its admin one,
629
+ // and both are resolved by the caller because minting either needs a
630
+ // controller.
631
+ "commerce.product": Object.freeze({
632
+ options: ["adminToken", "mintId", "read", "shopify"],
633
+ props: ["connection", "context", "settings", "workflow"]
634
+ }),
598
635
  // THE ADDRESS IS `contact` IN BOTH, and the shell already says why: it is the
599
636
  // person, not the lead document. `remove` called it `email` and `sync` called
600
637
  // it `doc` on one vendor and `lead` on three — three names for two facts.
@@ -607,19 +644,58 @@ var HOOK_SLOT_PROPS = Object.freeze({
607
644
  "inbound.process": Object.freeze({ options: ["dispatch"], props: ["context"] }),
608
645
  "inbound.receive": Object.freeze({ options: [], props: ["channel", "event", "headers", "payload"] }),
609
646
  "inbound.verify": Object.freeze({ options: [], props: ["body", "channel", "headers", "secret", "url"] }),
610
- // INSTALL — thirteen slots, none implemented yet. They are what the thirteen
611
- // routes in api/route/shopify-embedded.js become, and the signature is
612
- // deliberately narrow: `context` is the request's own body, `read` and
613
- // `request` are the only services an install surface has been shown to need.
614
- // A route that cannot be expressed inside this line is a finding to bring
615
- // back here, not a name to add at the call site.
647
+ // INSTALL — thirteen slots, and they are the thirteen routes that used to be
648
+ // api/route/shopify-embedded.js. `context` is the request's own body in all
649
+ // of them; the options are where they differ, and every difference below was
650
+ // forced by a line in those routes rather than chosen.
651
+ //
652
+ // SEVEN NEED NOTHING BUT `read`. The two session slots that write, the two
653
+ // token slots that write, the two clears, and both account slots answer from
654
+ // the shared install record alone.
655
+ //
656
+ // SIX TAKE MORE, and the widenings are worth naming because each is a fact
657
+ // Drawbridge owns that the manifest must not:
658
+ //
659
+ // conversionRate, planTitle what Drawbridge charges this organization.
660
+ // The org list renders both, and importing the
661
+ // plan catalogue here is the cycle
662
+ // features -> connections -> shopify -> plans
663
+ // -> features that was just broken.
664
+ // currencies which settlement currencies Drawbridge can
665
+ // bill. A store outside them fails the
666
+ // connection validator INSIDE the transaction,
667
+ // which surfaces as an opaque 500, so `add`
668
+ // checks first and says so.
669
+ // mintId the connection's id, known before the write
670
+ // that creates it, because the organization's
671
+ // own refs have to name it in the same
672
+ // transaction.
673
+ // shopify the vendor. Four slots call the store: two
674
+ // read the live plan, two release it.
675
+ // mark THE ONE WRITE A DESCRIPTION CANNOT CARRY, and
676
+ // `reselect` is the only slot with one. See its
677
+ // implementation for why the order is the point.
616
678
  "install.account.link": INSTALL_SIGNATURE,
617
679
  "install.account.unlink": INSTALL_SIGNATURE,
618
- "install.organizations.add": INSTALL_SIGNATURE,
619
- "install.organizations.list": INSTALL_SIGNATURE,
680
+ "install.organizations.add": Object.freeze({
681
+ options: ["currencies", "mintId", "read", "shopify"],
682
+ props: ["context"]
683
+ }),
684
+ "install.organizations.list": Object.freeze({
685
+ options: ["conversionRate", "planTitle", "read", "shopify"],
686
+ props: ["context"]
687
+ }),
620
688
  "install.organizations.remove": INSTALL_SIGNATURE,
621
- "install.plan.cancel": INSTALL_SIGNATURE,
622
- "install.plan.reselect": INSTALL_SIGNATURE,
689
+ "install.plan.cancel": Object.freeze({ options: ["read", "shopify"], props: ["context"] }),
690
+ // `manifest` because the handle this charge bills under is the vendor's own
691
+ // declaration (auth.install.billing.handle), and checking the job against the
692
+ // declaration is what the enqueuer-checks-itself version could not do.
693
+ "install.plan.charge": Object.freeze({
694
+ options: ["shopify"],
695
+ props: ["clientId", "clientSecret", "context", "manifest"]
696
+ }),
697
+ "install.plan.reselect": Object.freeze({ options: ["mark", "read", "shopify"], props: ["context"] }),
698
+ "install.plan.verify": Object.freeze({ options: ["adminToken", "read", "shopify"], props: ["context"] }),
623
699
  "install.session.clear": INSTALL_SIGNATURE,
624
700
  "install.session.read": INSTALL_SIGNATURE,
625
701
  "install.session.save": INSTALL_SIGNATURE,
@@ -778,6 +854,52 @@ var ERROR_SOURCES = Object.freeze({
778
854
  "shopify.register.webhooks": true
779
855
  });
780
856
 
857
+ // lib/encrypt.js
858
+ import crypto2 from "crypto";
859
+
860
+ // lib/token.js
861
+ import crypto from "crypto";
862
+ var generate = (bytes = 32, encoding = "base64url") => {
863
+ const buf = crypto.randomBytes(bytes);
864
+ return encoding ? buf.toString(encoding) : buf;
865
+ };
866
+ var hash = (value, key) => {
867
+ if (!value) return null;
868
+ if (key) {
869
+ return crypto.createHmac("sha256", key).update(String(value)).digest("base64url");
870
+ }
871
+ return crypto.createHash("sha256").update(String(value)).digest("base64url");
872
+ };
873
+
874
+ // lib/encrypt.js
875
+ var ALGORITHM = "aes-256-gcm";
876
+ var getKey = () => Buffer.from(process.env.ENCRYPT_CONNECTION_SECRET, "hex");
877
+ var encrypt = (value) => {
878
+ const iv = generate(12, null);
879
+ const cipher = crypto2.createCipheriv(ALGORITHM, getKey(), iv);
880
+ const data2 = Buffer.concat([
881
+ cipher.update(JSON.stringify(value), "utf8"),
882
+ cipher.final()
883
+ ]);
884
+ const tag = cipher.getAuthTag();
885
+ return [iv, tag, data2].map((b) => b.toString("hex")).join(":");
886
+ };
887
+ var decrypt = (value) => {
888
+ if (typeof value !== "string") return value;
889
+ const [ivHex, tagHex, dataHex] = value.split(":");
890
+ const decipher = crypto2.createDecipheriv(
891
+ ALGORITHM,
892
+ getKey(),
893
+ Buffer.from(ivHex, "hex")
894
+ );
895
+ decipher.setAuthTag(Buffer.from(tagHex, "hex"));
896
+ const result = Buffer.concat([
897
+ decipher.update(Buffer.from(dataHex, "hex")),
898
+ decipher.final()
899
+ ]);
900
+ return JSON.parse(result.toString("utf8"));
901
+ };
902
+
781
903
  // lib/connections/oauth.js
782
904
  import { createHash, randomBytes } from "crypto";
783
905
  var credentials = ({ basic, clientId, clientSecret }) => basic ? {
@@ -804,10 +926,10 @@ var authToken = async ({
804
926
  const renewing = !code2;
805
927
  if (renewing && !refreshToken) throw new Error("Nothing has been consented to yet, so there is no refresh token to spend");
806
928
  if (!renewing && descriptor.pkce && !verifier) throw new Error("This connection requires PKCE, so the code verifier is not optional");
807
- const client = credentials({ basic, clientId, clientSecret });
929
+ const client2 = credentials({ basic, clientId, clientSecret });
808
930
  const response = await fetcher(descriptor.endpoints.token, {
809
931
  body: new URLSearchParams({
810
- ...client.body,
932
+ ...client2.body,
811
933
  ...renewing ? { grant_type: "refresh_token", refresh_token: refreshToken } : {
812
934
  code: decodeURIComponent(String(code2 || "").trim()),
813
935
  grant_type: "authorization_code",
@@ -815,7 +937,7 @@ var authToken = async ({
815
937
  ...descriptor.pkce && { code_verifier: verifier }
816
938
  }
817
939
  }),
818
- headers: { "content-type": "application/x-www-form-urlencoded", ...client.headers },
940
+ headers: { "content-type": "application/x-www-form-urlencoded", ...client2.headers },
819
941
  method: "POST",
820
942
  signal: AbortSignal.timeout(15e3)
821
943
  });
@@ -1210,9 +1332,18 @@ var scaffold_default = {
1210
1332
  commerce: {
1211
1333
  // NEW in phase 1 — the Checkout Kit cart path, which writes nothing and is
1212
1334
  // the last api surface Shopify owns outside a hook.
1213
- cart: async ({ connection: connection2, context }, { read } = {}) => ANSWER,
1335
+ // NO `connection` AND NO `step`: this one runs for a SHOPPER on a public
1336
+ // page, not for an organization inside a workflow. It reads the storefront
1337
+ // with the store's storefront token and mints a checkout token from
1338
+ // DRAWBRIDGE'S app credentials, which is why the credential pair rides in
1339
+ // as props — the way auth.disconnect already carries it.
1340
+ cart: async ({ clientId, clientSecret, context, settings }, { fetcher, shopify } = {}) => ANSWER,
1214
1341
  code: async ({ connection: connection2, context, step }, { adminToken, shopify } = {}) => ANSWER,
1215
1342
  customer: async ({ connection: connection2, context }, { adminToken, read, shopify } = {}) => ANSWER,
1343
+ // STOCK, READ AT RENDER TIME rather than stored. It is the one product
1344
+ // fact that is stale the instant it is written down, so the campaign
1345
+ // product list asks the vendor and caches the answer for a minute.
1346
+ inventory: async ({ connection: connection2, context }, { adminToken, shopify } = {}) => ANSWER,
1216
1347
  order: async ({ connection: connection2, context }, { logger: logger2, mintId, read } = {}) => ANSWER,
1217
1348
  // THIS IS WHERE `product.insert` LANDS.
1218
1349
  //
@@ -1234,7 +1365,7 @@ var scaffold_default = {
1234
1365
  // nothing and shows up only as `workflow.dispatch.candidates matched : 0` in
1235
1366
  // a log. Phase 1 closes it and build() checks every trigger against it.
1236
1367
  product: {
1237
- hook: async ({ connection: connection2, context, workflow }, { mintId, read } = {}) => ANSWER,
1368
+ hook: async ({ connection: connection2, context, settings, workflow }, { adminToken, mintId, read, shopify } = {}) => ANSWER,
1238
1369
  step: () => ({
1239
1370
  description: "Syncs product data from the vendor when a product changes.",
1240
1371
  key: "Vendor Product Sync",
@@ -1382,8 +1513,19 @@ var scaffold_default = {
1382
1513
  // Vendor billing, the only group that is not generic. Pairs with
1383
1514
  // auth.install.billing, which declares what the merchant is being charged.
1384
1515
  plan: {
1385
- cancel: async ({ context }, { dispatch, read } = {}) => ANSWER,
1386
- reselect: async ({ context }, { dispatch, read } = {}) => ANSWER
1516
+ cancel: async ({ context }, { read, shopify } = {}) => ANSWER,
1517
+ // NOT A MERCHANT ACTION EITHER one attributed order's usage charge,
1518
+ // sent to the vendor's meter. The credential pair rides in as props
1519
+ // because the charge authenticates as the APP, not as the store.
1520
+ charge: async ({ clientId, clientSecret, context, manifest }, { shopify } = {}) => ANSWER,
1521
+ // `mark` is the one write a description cannot carry: the marker must
1522
+ // be persisted BEFORE the approval is released, and a described write
1523
+ // lands after the hook returns.
1524
+ reselect: async ({ context }, { mark, read, shopify } = {}) => ANSWER,
1525
+ // NOT A MERCHANT ACTION — the question "is this store's billing
1526
+ // actually metered right now", asked by the daily health check and by
1527
+ // the vendor's own approval webhook, which used to hand-copy it.
1528
+ verify: async ({ context }, { adminToken, read, shopify } = {}) => ANSWER
1387
1529
  },
1388
1530
  // The embedded app's own session, stored by us on the vendor's behalf.
1389
1531
  session: {
@@ -1869,16 +2011,19 @@ var attentive_default2 = {
1869
2011
  "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.",
1870
2012
  "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."
1871
2013
  ],
1872
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
1873
- // The dashboard already carries generic reasons for every way an
1874
- // authorization can fail — declined, expired state, a vendor we are not set
1875
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
1876
- // failures need saying differently. This one's do not.
2014
+ // WHAT THE MERCHANT READS WHEN A CONNECT FAILS. Two states, because the
2015
+ // consent screen has two ways to end: they said no, or something between
2016
+ // here and the vendor went wrong.
1877
2017
  //
1878
- // Answered rather than omitted, because `errors` existed on two of six
1879
- // manifests and there was no way to tell "nothing to add" from "nobody
1880
- // wrote it".
1881
- errors: false,
2018
+ // THE VENDOR IS NAMED IN BOTH. The dashboard's generic copy says "the
2019
+ // authorization"; a merchant connecting two accounts in one sitting needs
2020
+ // to know which one this was.
2021
+ errors: {
2022
+ connect: {
2023
+ denied: "The Attentive authorization was declined, so nothing was connected.",
2024
+ invalid: "We couldn't complete the Attentive connection. Try connecting again."
2025
+ }
2026
+ },
1882
2027
  excerpt: "Sync your Drawbridge contacts into an Attentive segment.",
1883
2028
  // NAMES THE SEGMENT STEP, because `status` below gates on it: a grant with
1884
2029
  // no segment chosen sits at Pending, and a guide that stops at the consent
@@ -2406,6 +2551,15 @@ var readEventHeader = ({ descriptor, headers }) => ({ result: { event: headers[d
2406
2551
  var DEFAULT_TIMEOUT_MS = 15e3;
2407
2552
  var request = async ({
2408
2553
  body,
2554
+ // THE TRANSPORT, injectable and defaulted to the real one.
2555
+ //
2556
+ // Every other vendor client in this package takes a `fetcher` — it is how
2557
+ // klaviyo, mailchimp and attentive are tested without a network, and it is a
2558
+ // declared HOOK_OPTION. The Shopify client had no seam at all, so the only way
2559
+ // to test a hook that used it was to inject the whole SDK namespace; that
2560
+ // injection existed to work around an import cycle, and when the cycle went
2561
+ // the tests lost their only hold. This is the seam they should have had.
2562
+ fetcher = fetch,
2409
2563
  headers = {},
2410
2564
  method = "GET",
2411
2565
  query,
@@ -2419,7 +2573,7 @@ var request = async ({
2419
2573
  }
2420
2574
  ;
2421
2575
  const isForm = type === "form";
2422
- const response = await fetch(fullUrl.toString(), {
2576
+ const response = await fetcher(fullUrl.toString(), {
2423
2577
  method,
2424
2578
  headers: {
2425
2579
  "Content-Type": isForm ? "application/x-www-form-urlencoded" : "application/json",
@@ -2861,15 +3015,12 @@ var drawbridge_default2 = {
2861
3015
  description: [
2862
3016
  "Drawbridge sends your notification emails and your entrants' emails, and recalculates segment membership on a schedule. It is always on and needs nothing connected."
2863
3017
  ],
2864
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
2865
- // The dashboard already carries generic reasons for every way an
2866
- // authorization can fail declined, expired state, a vendor we are not set
2867
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
2868
- // failures need saying differently. This one's do not.
3018
+ // NOTHING IS EVER CONNECTED, so no connect can fail. This is the platform's
3019
+ // own manifest always on, private, never in the catalogue — and it exists
3020
+ // to give Drawbridge's own steps a hook to point at. `denied` and `invalid`
3021
+ // describe a consent screen this connection does not have.
2869
3022
  //
2870
- // Answered rather than omitted, because `errors` existed on two of six
2871
- // manifests and there was no way to tell "nothing to add" from "nobody
2872
- // wrote it".
3023
+ // `false` is the recorded decision, not silence.
2873
3024
  errors: false,
2874
3025
  excerpt: "The steps Drawbridge runs itself.",
2875
3026
  guide: [
@@ -3629,10 +3780,10 @@ var klaviyo_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill=
3629
3780
 
3630
3781
  // lib/connections/scopes.js
3631
3782
  var list = (value) => (Array.isArray(value) ? value.flatMap((entry) => String(entry).split(/\s+/)) : String(value ?? "").split(/\s+/)).map((entry) => entry.trim()).filter(Boolean);
3632
- var missingScopes = ({ granted, required }) => {
3783
+ var missingScopes = ({ granted, required: required2 }) => {
3633
3784
  if (granted === null || granted === void 0 || granted === "") return null;
3634
3785
  const held = new Set(list(granted));
3635
- return list(required).filter((scope) => !held.has(scope));
3786
+ return list(required2).filter((scope) => !held.has(scope));
3636
3787
  };
3637
3788
 
3638
3789
  // lib/connections/manifests/klaviyo.js
@@ -4531,16 +4682,19 @@ var mailchimp_default2 = {
4531
4682
  "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.",
4532
4683
  "Someone who unsubscribed inside Mailchimp keeps that choice: a resync only sets the status of a subscriber Mailchimp has never seen before."
4533
4684
  ],
4534
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
4535
- // The dashboard already carries generic reasons for every way an
4536
- // authorization can fail — declined, expired state, a vendor we are not set
4537
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
4538
- // failures need saying differently. This one's do not.
4685
+ // WHAT THE MERCHANT READS WHEN A CONNECT FAILS. Two states, because the
4686
+ // consent screen has two ways to end: they said no, or something between
4687
+ // here and the vendor went wrong.
4539
4688
  //
4540
- // Answered rather than omitted, because `errors` existed on two of six
4541
- // manifests and there was no way to tell "nothing to add" from "nobody
4542
- // wrote it".
4543
- errors: false,
4689
+ // THE VENDOR IS NAMED IN BOTH. The dashboard's generic copy says "the
4690
+ // authorization"; a merchant connecting two accounts in one sitting needs
4691
+ // to know which one this was.
4692
+ errors: {
4693
+ connect: {
4694
+ denied: "The Mailchimp authorization was declined, so nothing was connected.",
4695
+ invalid: "We couldn't complete the Mailchimp connection. Try connecting again."
4696
+ }
4697
+ },
4544
4698
  excerpt: "Sync your Drawbridge contacts into a Mailchimp audience.",
4545
4699
  // NAMES THE AUDIENCE STEP, because `status` below gates on it: a grant with
4546
4700
  // no audience chosen sits at Pending, and a guide that stops at the consent
@@ -4639,7 +4793,7 @@ var mailchimp_default2 = {
4639
4793
  if (!audience) return { message: "No Mailchimp audience is chosen for this connection.", request: request2, skipped: true };
4640
4794
  const email = ((_d = (_c = lead == null ? void 0 : lead.canonical) == null ? void 0 : _c.email) == null ? void 0 : _d.value) || (lead == null ? void 0 : lead.email);
4641
4795
  if (!email) return { message: "That lead has no email address to sync.", request: request2, skipped: true };
4642
- const hash = subscriberHash(email);
4796
+ const hash2 = subscriberHash(email);
4643
4797
  const [firstName, ...restOfName] = String((lead == null ? void 0 : lead.name) || "").trim().split(/\s+/).filter(Boolean);
4644
4798
  const lastName = restOfName.join(" ");
4645
4799
  const phone = ((_e = lead == null ? void 0 : lead.phone) == null ? void 0 : _e.number) || null;
@@ -4648,7 +4802,7 @@ var mailchimp_default2 = {
4648
4802
  ...lastName && { LNAME: lastName },
4649
4803
  ...phone && { PHONE: phone }
4650
4804
  };
4651
- const member = await api3("/lists/" + audience + "/members/" + hash, {
4805
+ const member = await api3("/lists/" + audience + "/members/" + hash2, {
4652
4806
  dc: settings == null ? void 0 : settings.dc,
4653
4807
  fetcher,
4654
4808
  method: "PUT",
@@ -4689,7 +4843,7 @@ var mailchimp_default2 = {
4689
4843
  status: joined.has(entry.id) ? "active" : "inactive"
4690
4844
  }));
4691
4845
  if (tags.length > 0) {
4692
- await api3("/lists/" + audience + "/members/" + hash + "/tags", {
4846
+ await api3("/lists/" + audience + "/members/" + hash2 + "/tags", {
4693
4847
  dc: settings == null ? void 0 : settings.dc,
4694
4848
  fetcher,
4695
4849
  method: "POST",
@@ -4700,12 +4854,12 @@ var mailchimp_default2 = {
4700
4854
  }
4701
4855
  return {
4702
4856
  // Merged into `context` for later steps in this run.
4703
- context: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash },
4857
+ context: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash2 },
4704
4858
  message: suppressed ? "Synced to Mailchimp as unsubscribed \u2014 this contact has opted out." : "Synced to the Mailchimp audience.",
4705
4859
  request: request2,
4706
4860
  // Recorded on the run for support to read back, not a write
4707
4861
  // instruction — the hook has already written what it needed to.
4708
- response: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash }
4862
+ response: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash2 }
4709
4863
  };
4710
4864
  }
4711
4865
  },
@@ -5075,164 +5229,2055 @@ var shopify_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill=
5075
5229
  <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"/>
5076
5230
  </svg>`;
5077
5231
 
5078
- // lib/email.js
5079
- var GMAIL_DOMAINS = /* @__PURE__ */ new Set(["gmail.com", "googlemail.com"]);
5080
- var toCanonicalEmail = (value) => {
5081
- if (!value || typeof value !== "string") return null;
5082
- const email = value.trim().toLowerCase();
5083
- const at = email.lastIndexOf("@");
5084
- if (at < 1 || at === email.length - 1) return null;
5085
- let local = email.slice(0, at);
5086
- const domain = email.slice(at + 1);
5087
- const plus = local.indexOf("+");
5088
- if (plus > 0) local = local.slice(0, plus);
5089
- if (GMAIL_DOMAINS.has(domain)) local = local.replaceAll(".", "");
5090
- if (!local) return null;
5091
- return local + "@" + domain;
5092
- };
5232
+ // lib/shopify/admin.js
5233
+ var admin_exports = {};
5234
+ __export(admin_exports, {
5235
+ adminFetch: () => adminFetch,
5236
+ createDiscountCode: () => createDiscountCode,
5237
+ createUsageRecord: () => createUsageRecord,
5238
+ createUsageSubscription: () => createUsageSubscription,
5239
+ getActiveAppSubscriptions: () => getActiveAppSubscriptions,
5240
+ getDiscounts: () => getDiscounts,
5241
+ getOrCreateCustomer: () => getOrCreateCustomer,
5242
+ getProductInventory: () => getProductInventory,
5243
+ sendProductResourceFeedback: () => sendProductResourceFeedback
5244
+ });
5093
5245
 
5094
- // lib/encrypt.js
5095
- import crypto from "crypto";
5096
- var ALGORITHM = "aes-256-gcm";
5097
- var getKey = () => Buffer.from(process.env.ENCRYPT_CONNECTION_SECRET, "hex");
5098
- var decrypt = (value) => {
5099
- if (typeof value !== "string") return value;
5100
- const [ivHex, tagHex, dataHex] = value.split(":");
5101
- const decipher = crypto.createDecipheriv(
5102
- ALGORITHM,
5103
- getKey(),
5104
- Buffer.from(ivHex, "hex")
5105
- );
5106
- decipher.setAuthTag(Buffer.from(tagHex, "hex"));
5107
- const result = Buffer.concat([
5108
- decipher.update(Buffer.from(dataHex, "hex")),
5109
- decipher.final()
5110
- ]);
5111
- return JSON.parse(result.toString("utf8"));
5112
- };
5246
+ // lib/shopify/constants.js
5247
+ var SHOPIFY_STOREFRONT_API_VERSION = "2025-01";
5248
+ var SHOPIFY_ADMIN_API_VERSION = "2026-04";
5249
+ var SHOPIFY_APP_API_VERSION = "unstable";
5250
+ var SHOPIFY_REQUIRED_SCOPES = [
5251
+ "read_customers",
5252
+ "write_customers",
5253
+ "read_discounts",
5254
+ "write_discounts",
5255
+ "read_orders",
5256
+ "read_products",
5257
+ "read_publications",
5258
+ "write_resource_feedbacks",
5259
+ "unauthenticated_read_checkouts",
5260
+ "unauthenticated_read_product_inventory",
5261
+ "unauthenticated_read_product_listings",
5262
+ "unauthenticated_write_checkouts"
5263
+ ];
5264
+ var REFRESH_TOKEN_LIFETIME_MS = 90 * 24 * 60 * 60 * 1e3;
5265
+ var ACCESS_TOKEN_REFRESH_BUFFER_MS = 5 * 60 * 1e3;
5266
+ var PARTNER_API_VERSION = process.env.SHOPIFY_PARTNER_API_VERSION || "2026-07";
5113
5267
 
5114
- // lib/slugify.js
5115
- import slug from "slugify";
5116
- var slugify = (value, nochars = false) => {
5117
- const remove = nochars ? /[-?*+~.()'"!:@#^_{}\[\];,/\\]/g : /[?*+~.()'"!:@#^_{}\[\];,/\\]/g;
5118
- const replacement = nochars ? "" : "-";
5119
- return slug(
5120
- value,
5121
- {
5122
- remove,
5123
- replacement,
5124
- lower: true,
5125
- trim: true
5268
+ // lib/shopify/admin.js
5269
+ var adminUrl = (domain) => `https://${domain}/admin/api/${SHOPIFY_ADMIN_API_VERSION}`;
5270
+ var adminFetch = async ({ adminAccessToken, domain, fetcher, query, variables }) => {
5271
+ var _a;
5272
+ const { data: data2, errors } = await request({
5273
+ fetcher,
5274
+ method: "POST",
5275
+ url: adminUrl(domain) + "/graphql.json",
5276
+ headers: {
5277
+ "X-Shopify-Access-Token": adminAccessToken
5278
+ },
5279
+ body: {
5280
+ query,
5281
+ ...variables && { variables }
5126
5282
  }
5127
- );
5283
+ });
5284
+ if (errors) {
5285
+ throw new Error("Shopify GraphQL error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
5286
+ }
5287
+ ;
5288
+ return data2;
5128
5289
  };
5129
-
5130
- // lib/connections/manifests/shopify.js
5131
- var toLine = ({
5132
- price,
5133
- product_id: productId,
5134
- quantity,
5135
- title,
5136
- variant_id: variantId,
5137
- variant_title: variantTitle
5138
- }) => ({
5139
- price: parseFloat(price) || 0,
5140
- productId: productId ? "gid://shopify/Product/" + productId : null,
5141
- quantity: quantity || 1,
5142
- title: title || null,
5143
- variantId: variantId ? "gid://shopify/ProductVariant/" + variantId : null,
5144
- variantTitle: variantTitle || null
5145
- });
5146
- var attributeLineItems = (lineItems = []) => lineItems.reduce(
5147
- (acc, item) => {
5148
- const attrs = (item.properties || []).reduce(
5149
- (map, { name, value }) => {
5150
- map[name] = value;
5151
- return map;
5152
- },
5153
- {}
5154
- );
5155
- if (!attrs["_drwbrdg_ca"]) return acc;
5156
- if (!Object.keys(acc.attrMap).length) acc.attrMap = attrs;
5157
- const line = toLine(item);
5158
- acc.attributedGross += line.price * line.quantity;
5159
- acc.attributedLines.push(line);
5160
- return acc;
5161
- },
5162
- { attrMap: {}, attributedGross: 0, attributedLines: [] }
5163
- );
5164
- var generateDiscountCode = customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8);
5165
- var blockedReason = (discount) => {
5166
- var _a;
5167
- if ((discount == null ? void 0 : discount.status) === "EXPIRED") return "This discount has expired.";
5168
- const buyers = (_a = discount == null ? void 0 : discount.context) == null ? void 0 : _a.__typename;
5169
- if (buyers && buyers !== "DiscountBuyerSelectionAll") {
5170
- return "This discount is limited to specific buyers in Shopify, so a code issued to an entrant won't work. Set it to all customers to use it here.";
5290
+ var DISCOUNT_FIELDS = `
5291
+ title
5292
+ status
5293
+ startsAt
5294
+ endsAt
5295
+ usageLimit
5296
+ asyncUsageCount
5297
+ appliesOncePerCustomer
5298
+ context { __typename }
5299
+ `;
5300
+ var discountsQuery = (search, cursor, limit) => `{
5301
+ codeDiscountNodes(first: ${limit}${search ? `, query: "title:*${search}*"` : ""}${cursor ? `, after: "${cursor}"` : ""}) {
5302
+ edges {
5303
+ node {
5304
+ id
5305
+ codeDiscount {
5306
+ ... on DiscountCodeBasic { ${DISCOUNT_FIELDS} }
5307
+ ... on DiscountCodeBxgy { ${DISCOUNT_FIELDS} }
5308
+ ... on DiscountCodeFreeShipping { ${DISCOUNT_FIELDS} }
5309
+ ... on DiscountCodeApp { ${DISCOUNT_FIELDS} }
5310
+ }
5311
+ }
5312
+ }
5313
+ pageInfo {
5314
+ endCursor
5315
+ hasNextPage
5316
+ hasPreviousPage
5317
+ startCursor
5318
+ }
5319
+ }
5320
+ }`;
5321
+ var getDiscounts = async ({ fetcher, adminAccessToken, domain, search, cursor, limit }) => {
5322
+ const data2 = await adminFetch({
5323
+ fetcher,
5324
+ adminAccessToken,
5325
+ domain,
5326
+ query: discountsQuery(search, cursor, limit)
5327
+ });
5328
+ return data2 == null ? void 0 : data2.codeDiscountNodes;
5329
+ };
5330
+ var discountGid = (id) => String(id).startsWith("gid://") ? String(id) : "gid://shopify/DiscountCodeNode/" + id;
5331
+ var createDiscountCode = async ({ fetcher, adminAccessToken, domain, discountId, code: code2 }) => {
5332
+ var _a, _b, _c, _d, _e, _f, _g, _h;
5333
+ const added = await adminFetch({
5334
+ fetcher,
5335
+ adminAccessToken,
5336
+ domain,
5337
+ query: `
5338
+ mutation DiscountRedeemCodeBulkAdd($discountId: ID!, $codes: [DiscountRedeemCodeInput!]!) {
5339
+ discountRedeemCodeBulkAdd(discountId: $discountId, codes: $codes) {
5340
+ bulkCreation {
5341
+ id
5342
+ }
5343
+ userErrors {
5344
+ field
5345
+ message
5346
+ }
5347
+ }
5348
+ }
5349
+ `,
5350
+ variables: {
5351
+ codes: [{ code: code2 }],
5352
+ discountId: discountGid(discountId)
5353
+ }
5354
+ });
5355
+ const addErrors = (_a = added == null ? void 0 : added.discountRedeemCodeBulkAdd) == null ? void 0 : _a.userErrors;
5356
+ if (addErrors == null ? void 0 : addErrors.length) {
5357
+ throw new Error("Shopify discount code create failed: " + addErrors[0].message);
5171
5358
  }
5172
5359
  ;
5173
- if (typeof (discount == null ? void 0 : discount.usageLimit) === "number" && discount.usageLimit > 0 && ((discount == null ? void 0 : discount.asyncUsageCount) || 0) >= discount.usageLimit) {
5174
- return "This discount has reached its total usage limit.";
5360
+ const bulkCreationId = (_c = (_b = added == null ? void 0 : added.discountRedeemCodeBulkAdd) == null ? void 0 : _b.bulkCreation) == null ? void 0 : _c.id;
5361
+ if (!bulkCreationId) {
5362
+ throw new Error("Shopify discount code create failed: no bulk creation id returned");
5175
5363
  }
5176
5364
  ;
5177
- return null;
5365
+ for (let attempt = 0; attempt < 15; attempt++) {
5366
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
5367
+ const polled = await adminFetch({
5368
+ fetcher,
5369
+ adminAccessToken,
5370
+ domain,
5371
+ query: `
5372
+ query DiscountRedeemCodeBulkCreationPoll($id: ID!) {
5373
+ discountRedeemCodeBulkCreation(id: $id) {
5374
+ done
5375
+ codes(first: 1) {
5376
+ nodes {
5377
+ code
5378
+ discountRedeemCode {
5379
+ id
5380
+ }
5381
+ errors {
5382
+ message
5383
+ }
5384
+ }
5385
+ }
5386
+ }
5387
+ }
5388
+ `,
5389
+ variables: {
5390
+ id: bulkCreationId
5391
+ }
5392
+ });
5393
+ const creation = polled == null ? void 0 : polled.discountRedeemCodeBulkCreation;
5394
+ if (!(creation == null ? void 0 : creation.done)) continue;
5395
+ const node = (_e = (_d = creation.codes) == null ? void 0 : _d.nodes) == null ? void 0 : _e[0];
5396
+ if (!((_f = node == null ? void 0 : node.discountRedeemCode) == null ? void 0 : _f.id)) {
5397
+ throw new Error("Shopify discount code create failed: " + (((_h = (_g = node == null ? void 0 : node.errors) == null ? void 0 : _g[0]) == null ? void 0 : _h.message) || "code was not created"));
5398
+ }
5399
+ ;
5400
+ return {
5401
+ code: node.code,
5402
+ // Numeric tail keeps the stored shopifyDiscountId in the shape the
5403
+ // legacy REST endpoint returned — it feeds a merchant-visible
5404
+ // workflow template variable, so no gid:// leakage.
5405
+ id: node.discountRedeemCode.id.split("/").pop()
5406
+ };
5407
+ }
5408
+ ;
5409
+ throw new Error("Shopify discount code create timed out waiting for bulk creation " + bulkCreationId);
5178
5410
  };
5179
- var discountWarning = (discount) => {
5180
- if ((discount == null ? void 0 : discount.status) === "SCHEDULED") {
5181
- return "This discount hasn't started yet, so codes issued before it does won't work until then.";
5411
+ var getOrCreateCustomer = async ({ fetcher, adminAccessToken, domain, email, firstName, lastName, source }) => {
5412
+ var _a, _b, _c, _d, _e, _f, _g, _h;
5413
+ const lookupQuery = `
5414
+ query customerByEmail( $query : String! ) {
5415
+ customers( first : 1, query : $query ) {
5416
+ edges {
5417
+ node {
5418
+ id
5419
+ }
5420
+ }
5421
+ }
5422
+ }
5423
+ `;
5424
+ const data2 = await adminFetch({
5425
+ fetcher,
5426
+ adminAccessToken,
5427
+ domain,
5428
+ query: lookupQuery,
5429
+ variables: { query: "email:" + email }
5430
+ });
5431
+ const existing = (_c = (_b = (_a = data2 == null ? void 0 : data2.customers) == null ? void 0 : _a.edges) == null ? void 0 : _b[0]) == null ? void 0 : _c.node;
5432
+ if (existing) return existing;
5433
+ const input = { email };
5434
+ if (firstName) input.firstName = firstName;
5435
+ if (lastName) input.lastName = lastName;
5436
+ if (source) {
5437
+ input.metafields = [{
5438
+ namespace: "drwbrdg",
5439
+ key: "source",
5440
+ type: "single_line_text_field",
5441
+ value: source
5442
+ }];
5182
5443
  }
5183
5444
  ;
5184
- if (discount == null ? void 0 : discount.appliesOncePerCustomer) return "Each customer can use this discount only once.";
5185
- return null;
5445
+ const result = await adminFetch({
5446
+ fetcher,
5447
+ adminAccessToken,
5448
+ domain,
5449
+ query: `
5450
+ mutation customerCreate( $input : CustomerInput! ) {
5451
+ customerCreate( input : $input ) {
5452
+ customer {
5453
+ id
5454
+ }
5455
+ userErrors {
5456
+ field
5457
+ message
5458
+ }
5459
+ }
5460
+ }
5461
+ `,
5462
+ variables: { input }
5463
+ });
5464
+ const userErrors = (_d = result == null ? void 0 : result.customerCreate) == null ? void 0 : _d.userErrors;
5465
+ if (userErrors == null ? void 0 : userErrors.length) {
5466
+ const emailTaken = userErrors.some((e) => {
5467
+ var _a2;
5468
+ return (_a2 = e.message) == null ? void 0 : _a2.includes("Email has already been taken");
5469
+ });
5470
+ if (emailTaken) {
5471
+ const retry = await adminFetch({
5472
+ fetcher,
5473
+ adminAccessToken,
5474
+ domain,
5475
+ query: lookupQuery,
5476
+ variables: { query: "email:" + email }
5477
+ });
5478
+ const found = (_g = (_f = (_e = retry == null ? void 0 : retry.customers) == null ? void 0 : _e.edges) == null ? void 0 : _f[0]) == null ? void 0 : _g.node;
5479
+ if (found) return found;
5480
+ }
5481
+ ;
5482
+ throw new Error("Shopify customer create failed: " + userErrors[0].message);
5483
+ }
5484
+ ;
5485
+ return (_h = result == null ? void 0 : result.customerCreate) == null ? void 0 : _h.customer;
5186
5486
  };
5187
- var ORDER_EVENT_HANDLE = slugify("drawbridge-orders");
5188
- var REFRESH_TOKEN_FRESHNESS_BUFFER_MS = 5 * 24 * 60 * 60 * 1e3;
5189
- var OAUTH_ERROR_SOURCE = "oauth";
5190
- var BILLING_ERROR_SOURCE = "billing";
5191
- var BILLING_ERROR_MESSAGE = "Order billing isn't set up for this store \u2014 reselect and approve the plan from the Shopify connection page.";
5192
- var OAUTH_GRANT_REVOKED_CODES = ["application_cannot_be_found", "invalid_grant"];
5193
- var inbound = {
5194
- headers: {
5195
- event: "x-shopify-topic",
5196
- id: "x-shopify-webhook-id",
5197
- shop: "x-shopify-shop-domain",
5198
- signature: "x-shopify-hmac-sha256"
5199
- },
5200
- signature: {
5201
- algorithm: "sha256",
5202
- encoding: "base64",
5203
- secret: "SHOPIFY_API_SECRET"
5487
+ var getActiveAppSubscriptions = async ({ fetcher, adminAccessToken, domain }) => {
5488
+ var _a, _b;
5489
+ const data2 = await adminFetch({
5490
+ fetcher,
5491
+ adminAccessToken,
5492
+ domain,
5493
+ query: `{
5494
+ currentAppInstallation {
5495
+ activeSubscriptions {
5496
+ id
5497
+ name
5498
+ status
5499
+ test
5500
+ lineItems {
5501
+ id
5502
+ plan {
5503
+ pricingDetails {
5504
+ __typename
5505
+ }
5506
+ }
5507
+ }
5508
+ }
5509
+ }
5510
+ shop {
5511
+ myshopifyDomain
5512
+ }
5513
+ }`
5514
+ });
5515
+ return {
5516
+ shopDomain: ((_a = data2 == null ? void 0 : data2.shop) == null ? void 0 : _a.myshopifyDomain) || null,
5517
+ subscriptions: (((_b = data2 == null ? void 0 : data2.currentAppInstallation) == null ? void 0 : _b.activeSubscriptions) || []).map((subscription) => {
5518
+ var _a2;
5519
+ return {
5520
+ ...subscription,
5521
+ metered: ((subscription == null ? void 0 : subscription.lineItems) || []).some(
5522
+ (item) => {
5523
+ var _a3, _b2;
5524
+ return ((_b2 = (_a3 = item == null ? void 0 : item.plan) == null ? void 0 : _a3.pricingDetails) == null ? void 0 : _b2.__typename) === "AppUsagePricing";
5525
+ }
5526
+ ),
5527
+ // The usage line's own id — the address appUsageRecordCreate charges
5528
+ // against. Null when the approval carries no usage component.
5529
+ usageLineItemId: ((_a2 = ((subscription == null ? void 0 : subscription.lineItems) || []).find(
5530
+ (item) => {
5531
+ var _a3, _b2;
5532
+ return ((_b2 = (_a3 = item == null ? void 0 : item.plan) == null ? void 0 : _a3.pricingDetails) == null ? void 0 : _b2.__typename) === "AppUsagePricing";
5533
+ }
5534
+ )) == null ? void 0 : _a2.id) || null
5535
+ };
5536
+ })
5537
+ };
5538
+ };
5539
+ var createUsageSubscription = async ({ fetcher, adminAccessToken, cappedAmount, currencyCode = "USD", domain, name, recurringPrice = 0, returnUrl, terms, test = false }) => {
5540
+ if (!name || !returnUrl || !terms || !(Number(cappedAmount) > 0)) {
5541
+ throw new Error("createUsageSubscription requires name, returnUrl, terms, and a positive cappedAmount");
5204
5542
  }
5543
+ ;
5544
+ const data2 = await adminFetch({
5545
+ fetcher,
5546
+ adminAccessToken,
5547
+ domain,
5548
+ query: `mutation createUsageSubscription( $lineItems : [AppSubscriptionLineItemInput!]!, $name : String!, $returnUrl : URL!, $test : Boolean ) {
5549
+ appSubscriptionCreate( lineItems : $lineItems, name : $name, returnUrl : $returnUrl, test : $test ) {
5550
+ appSubscription { id name status test lineItems { id plan { pricingDetails { __typename } } } }
5551
+ confirmationUrl
5552
+ userErrors { field message }
5553
+ }
5554
+ }`,
5555
+ variables: {
5556
+ lineItems: [
5557
+ {
5558
+ plan: {
5559
+ appRecurringPricingDetails: {
5560
+ interval: "EVERY_30_DAYS",
5561
+ price: { amount: Number(recurringPrice), currencyCode }
5562
+ }
5563
+ }
5564
+ },
5565
+ {
5566
+ plan: {
5567
+ appUsagePricingDetails: {
5568
+ cappedAmount: { amount: Number(cappedAmount), currencyCode },
5569
+ terms
5570
+ }
5571
+ }
5572
+ }
5573
+ ],
5574
+ name,
5575
+ returnUrl,
5576
+ test
5577
+ }
5578
+ });
5579
+ const payload = data2 == null ? void 0 : data2.appSubscriptionCreate;
5580
+ const userErrors = (payload == null ? void 0 : payload.userErrors) || [];
5581
+ if (userErrors.length) {
5582
+ throw new Error("Shopify subscription create failed: " + userErrors.map((entry) => entry.message).join("; "));
5583
+ }
5584
+ ;
5585
+ if (!(payload == null ? void 0 : payload.confirmationUrl)) {
5586
+ throw new Error("Shopify subscription create failed: no confirmation url returned");
5587
+ }
5588
+ ;
5589
+ return {
5590
+ confirmationUrl: payload.confirmationUrl,
5591
+ subscription: payload.appSubscription
5592
+ };
5205
5593
  };
5206
- var COMPLIANCE_TOPICS = /* @__PURE__ */ new Set([
5207
- "customers/data_request",
5208
- "customers/redact",
5209
- "shop/redact"
5210
- ]);
5211
- var shopify_default2 = {
5212
- // THE WORDS ON THE BUTTONS. `listing` was `content.redirect.title`, which put
5213
- // a BUTTON LABEL inside the copy object next to a url — the title and the
5214
- // address it belongs to sat at different levels and could drift apart.
5215
- //
5216
- // It names where the link GOES rather than what it does: installing happens on
5217
- // the App Store listing, and the dashboard must never imply a store can be
5218
- // linked from inside it.
5219
- actions: {
5220
- create: null,
5221
- listing: "View on the Shopify App Store",
5222
- manage: null,
5223
- update: null
5224
- },
5225
- // INSTALL, not oauth. The grant is an OAuth grant, but the merchant never
5226
- // sees a consent screen we sent them to -- they start at the App Store, and
5227
- // the install completes inside Shopify admin without redirecting back. A
5228
- // Connect button here would be lying about where connecting happens.
5229
- auth: {
5230
- // ONE STORE PER ORGANIZATION. A Shopify install IS a store, and a second
5231
- // one would give an organization two catalogues, two order streams and two
5232
- // usage meters with nothing to say which is authoritative.
5233
- //
5234
- // DECLARED AND ENFORCED BY NOTHING, measured 2026-09-13: no repo reads this
5235
- // key, and the connection collection's { organization, slug } index is not
5594
+ var createUsageRecord = async ({ fetcher, adminAccessToken, amount, currencyCode = "USD", description, domain, idempotencyKey, subscriptionLineItemId }) => {
5595
+ var _a;
5596
+ if (!subscriptionLineItemId || !description || !(Number(amount) > 0)) {
5597
+ throw new Error("createUsageRecord requires subscriptionLineItemId, description, and a positive amount");
5598
+ }
5599
+ ;
5600
+ const data2 = await adminFetch({
5601
+ fetcher,
5602
+ adminAccessToken,
5603
+ domain,
5604
+ query: `mutation createUsageRecord( $description : String!, $idempotencyKey : String, $price : MoneyInput!, $subscriptionLineItemId : ID! ) {
5605
+ appUsageRecordCreate( description : $description, idempotencyKey : $idempotencyKey, price : $price, subscriptionLineItemId : $subscriptionLineItemId ) {
5606
+ appUsageRecord { id }
5607
+ userErrors { field message }
5608
+ }
5609
+ }`,
5610
+ variables: {
5611
+ description,
5612
+ idempotencyKey: idempotencyKey ? String(idempotencyKey) : null,
5613
+ price: { amount: Number(amount), currencyCode },
5614
+ subscriptionLineItemId
5615
+ }
5616
+ });
5617
+ const payload = data2 == null ? void 0 : data2.appUsageRecordCreate;
5618
+ const userErrors = (payload == null ? void 0 : payload.userErrors) || [];
5619
+ if (userErrors.length || !((_a = payload == null ? void 0 : payload.appUsageRecord) == null ? void 0 : _a.id)) {
5620
+ throw new Error("Shopify usage record failed: " + (userErrors.map((entry) => entry.message).join("; ") || "no record returned"));
5621
+ }
5622
+ ;
5623
+ return { id: payload.appUsageRecord.id };
5624
+ };
5625
+ var getProductInventory = async ({ fetcher, adminAccessToken, domain, productId }) => {
5626
+ var _a, _b;
5627
+ const data2 = await adminFetch({
5628
+ fetcher,
5629
+ adminAccessToken,
5630
+ domain,
5631
+ query: `{
5632
+ product( id : "${productId}" ) {
5633
+ variants( first : 100 ) {
5634
+ edges {
5635
+ node {
5636
+ id
5637
+ inventoryQuantity
5638
+ }
5639
+ }
5640
+ }
5641
+ }
5642
+ }`
5643
+ });
5644
+ const edges = ((_b = (_a = data2 == null ? void 0 : data2.product) == null ? void 0 : _a.variants) == null ? void 0 : _b.edges) || [];
5645
+ return edges.reduce((accumulator, edge) => {
5646
+ var _a2, _b2;
5647
+ const id = (_a2 = edge == null ? void 0 : edge.node) == null ? void 0 : _a2.id;
5648
+ const quantity = (_b2 = edge == null ? void 0 : edge.node) == null ? void 0 : _b2.inventoryQuantity;
5649
+ if (id) {
5650
+ accumulator[id] = Number.isFinite(quantity) ? quantity : 0;
5651
+ }
5652
+ ;
5653
+ return accumulator;
5654
+ }, {});
5655
+ };
5656
+ var getProductUpdatedAt = async ({ adminAccessToken, domain, fetcher, productId }) => {
5657
+ var _a;
5658
+ const data2 = await adminFetch({
5659
+ fetcher,
5660
+ adminAccessToken,
5661
+ domain,
5662
+ query: `
5663
+ query ProductUpdatedAt($id: ID!) {
5664
+ product(id: $id) {
5665
+ updatedAt
5666
+ }
5667
+ }
5668
+ `,
5669
+ variables: { id: productId }
5670
+ });
5671
+ return ((_a = data2 == null ? void 0 : data2.product) == null ? void 0 : _a.updatedAt) || null;
5672
+ };
5673
+ var NOT_ON_CHANNEL = "not available to the channel";
5674
+ var OUTDATED_FEEDBACK = "later version";
5675
+ var sendProductResourceFeedback = async ({ fetcher, adminAccessToken, domain, productId, state, messages = [] }) => {
5676
+ var _a, _b, _c;
5677
+ const productUpdatedAt = await getProductUpdatedAt({ adminAccessToken, domain, fetcher, productId });
5678
+ if (!productUpdatedAt) return null;
5679
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5680
+ const submit = async (version) => {
5681
+ const data2 = await adminFetch({
5682
+ fetcher,
5683
+ adminAccessToken,
5684
+ domain,
5685
+ query: `
5686
+ mutation ProductFeedback($feedbackInput: [ProductResourceFeedbackInput!]!) {
5687
+ bulkProductResourceFeedbackCreate(feedbackInput: $feedbackInput) {
5688
+ feedback {
5689
+ productId
5690
+ state
5691
+ }
5692
+ userErrors {
5693
+ field
5694
+ message
5695
+ }
5696
+ }
5697
+ }
5698
+ `,
5699
+ variables: {
5700
+ feedbackInput: [
5701
+ {
5702
+ productId,
5703
+ state,
5704
+ feedbackGeneratedAt: now,
5705
+ productUpdatedAt: version,
5706
+ messages
5707
+ }
5708
+ ]
5709
+ }
5710
+ });
5711
+ return data2 == null ? void 0 : data2.bulkProductResourceFeedbackCreate;
5712
+ };
5713
+ let result = await submit(productUpdatedAt);
5714
+ if ((((_b = (_a = result == null ? void 0 : result.userErrors) == null ? void 0 : _a[0]) == null ? void 0 : _b.message) || "").toLowerCase().includes(OUTDATED_FEEDBACK)) {
5715
+ result = await submit(now);
5716
+ }
5717
+ ;
5718
+ const feedbackErrors = result == null ? void 0 : result.userErrors;
5719
+ if (feedbackErrors == null ? void 0 : feedbackErrors.length) {
5720
+ const message = feedbackErrors[0].message || "";
5721
+ if (message.toLowerCase().includes(NOT_ON_CHANNEL)) return null;
5722
+ throw new Error("Shopify product feedback failed: " + message);
5723
+ }
5724
+ ;
5725
+ return ((_c = result == null ? void 0 : result.feedback) == null ? void 0 : _c[0]) || null;
5726
+ };
5727
+
5728
+ // lib/shopify/billing.js
5729
+ var billing_exports = {};
5730
+ __export(billing_exports, {
5731
+ sendAppEvent: () => sendAppEvent
5732
+ });
5733
+ var APP_API = "https://api.shopify.com";
5734
+ var APP_API_VERSION = process.env.SHOPIFY_APP_API_VERSION || SHOPIFY_APP_API_VERSION;
5735
+ var cachedTokens = {};
5736
+ var fetchAppToken = async ({ clientId, clientSecret, fetcher }) => {
5737
+ const data2 = await request({
5738
+ fetcher,
5739
+ method: "POST",
5740
+ url: APP_API + "/auth/access_token",
5741
+ body: {
5742
+ client_id: clientId,
5743
+ client_secret: clientSecret,
5744
+ grant_type: "client_credentials"
5745
+ }
5746
+ });
5747
+ if (!(data2 == null ? void 0 : data2.access_token)) {
5748
+ throw new Error("Shopify app token request failed: no access token returned");
5749
+ }
5750
+ ;
5751
+ const ttl = data2.expires_in ? data2.expires_in * 1e3 : 60 * 60 * 1e3;
5752
+ cachedTokens[clientId] = {
5753
+ expiresAt: Date.now() + ttl - 60 * 1e3,
5754
+ token: data2.access_token
5755
+ };
5756
+ return data2.access_token;
5757
+ };
5758
+ var getAppToken = async ({ clientId, clientSecret, fetcher }) => {
5759
+ const cached = cachedTokens[clientId];
5760
+ if (cached && cached.expiresAt > Date.now()) {
5761
+ return cached.token;
5762
+ }
5763
+ ;
5764
+ return fetchAppToken({ clientId, clientSecret, fetcher });
5765
+ };
5766
+ var toShopGid = (shopId) => String(shopId).startsWith("gid://") ? String(shopId) : "gid://shopify/Shop/" + shopId;
5767
+ var sendAppEvent = async ({ fetcher, clientId, clientSecret, eventHandle, idempotencyKey, reference, revision, shopId, timestamp, value }) => {
5768
+ if (!shopId || !eventHandle || !(Number(value) > 0)) {
5769
+ throw new Error("sendAppEvent requires shopId, eventHandle, and a positive value");
5770
+ }
5771
+ ;
5772
+ if (!clientId || !clientSecret) {
5773
+ throw new Error("sendAppEvent requires clientId and clientSecret");
5774
+ }
5775
+ ;
5776
+ const suffix = revision ? ".r" + revision : "";
5777
+ const key = idempotencyKey && String(idempotencyKey).slice(0, Math.max(0, 64 - suffix.length)) + suffix;
5778
+ const body = {
5779
+ attributes: {
5780
+ value: Number(value),
5781
+ ...reference && {
5782
+ reference: String(reference).slice(0, 128)
5783
+ }
5784
+ },
5785
+ event_handle: eventHandle,
5786
+ shop_id: toShopGid(shopId),
5787
+ timestamp: timestamp || (/* @__PURE__ */ new Date()).toISOString(),
5788
+ ...key && {
5789
+ idempotency_key: key
5790
+ }
5791
+ };
5792
+ const send2 = async (token) => request({
5793
+ method: "POST",
5794
+ url: APP_API + "/app/" + APP_API_VERSION + "/events",
5795
+ headers: {
5796
+ "Authorization": "Bearer " + token
5797
+ },
5798
+ body
5799
+ });
5800
+ try {
5801
+ return await send2(await getAppToken({ clientId, clientSecret, fetcher }));
5802
+ } catch (error) {
5803
+ if ((error == null ? void 0 : error.status) === 401) {
5804
+ delete cachedTokens[clientId];
5805
+ return send2(await fetchAppToken({ clientId, clientSecret, fetcher }));
5806
+ }
5807
+ ;
5808
+ throw error;
5809
+ }
5810
+ };
5811
+
5812
+ // lib/shopify/oauth.js
5813
+ var oauth_exports = {};
5814
+ __export(oauth_exports, {
5815
+ SHOPIFY_REQUIRED_SCOPES: () => SHOPIFY_REQUIRED_SCOPES,
5816
+ createStorefrontToken: () => createStorefrontToken,
5817
+ getAdminToken: () => getAdminToken,
5818
+ getShop: () => getShop,
5819
+ missingScopes: () => missingScopes2,
5820
+ ping: () => ping,
5821
+ refreshAdminToken: () => refreshAdminToken,
5822
+ resolveConnectionSettings: () => resolveConnectionSettings
5823
+ });
5824
+ var required = (name, value) => {
5825
+ if (!value) {
5826
+ throw new Error("Shopify " + name + " is required");
5827
+ }
5828
+ ;
5829
+ return value;
5830
+ };
5831
+ var missingScopes2 = (granted) => {
5832
+ const grantedSet = new Set(
5833
+ (Array.isArray(granted) ? granted : String(granted || "").split(",")).map((scope) => scope.trim()).filter(Boolean)
5834
+ );
5835
+ const satisfied = (scope) => grantedSet.has(scope) || grantedSet.has(scope.replace(/(^|_)read_/, "$1write_"));
5836
+ return SHOPIFY_REQUIRED_SCOPES.filter((scope) => !satisfied(scope));
5837
+ };
5838
+ var ping = async ({ fetcher, adminAccessToken, domain }) => {
5839
+ var _a;
5840
+ const response = await fetch(
5841
+ `https://${domain}/admin/api/${SHOPIFY_ADMIN_API_VERSION}/graphql.json`,
5842
+ {
5843
+ body: JSON.stringify({ query: "{ shop { name } }" }),
5844
+ headers: {
5845
+ "Content-Type": "application/json",
5846
+ "X-Shopify-Access-Token": adminAccessToken
5847
+ },
5848
+ method: "POST"
5849
+ }
5850
+ );
5851
+ if (!response.ok) {
5852
+ const text = await response.text().catch(() => "");
5853
+ const error = new Error(response.status + ": " + text);
5854
+ error.status = response.status;
5855
+ throw error;
5856
+ }
5857
+ ;
5858
+ const { errors } = await response.json().catch(() => ({}));
5859
+ if (errors == null ? void 0 : errors.length) {
5860
+ throw new Error("GraphQL: " + (((_a = errors[0]) == null ? void 0 : _a.message) || "unknown error"));
5861
+ }
5862
+ ;
5863
+ };
5864
+ var OAUTH_ERROR_TITLE_PATTERN = /Oauth error (\w+)/i;
5865
+ var parseOAuthErrorCode = (text) => {
5866
+ var _a;
5867
+ try {
5868
+ const parsed = JSON.parse(text);
5869
+ if (parsed == null ? void 0 : parsed.error) return parsed.error;
5870
+ } catch {
5871
+ }
5872
+ ;
5873
+ return ((_a = text.match(OAUTH_ERROR_TITLE_PATTERN)) == null ? void 0 : _a[1]) || null;
5874
+ };
5875
+ var shopifyOAuthFetch = async (url, body) => {
5876
+ const response = await fetch(url, {
5877
+ method: "POST",
5878
+ headers: {
5879
+ "Content-Type": "application/json"
5880
+ },
5881
+ body: JSON.stringify(body)
5882
+ });
5883
+ if (!response.ok) {
5884
+ const text = await response.text().catch(() => "");
5885
+ const error = new Error(response.status + ": " + text);
5886
+ error.status = response.status;
5887
+ error.code = parseOAuthErrorCode(text);
5888
+ throw error;
5889
+ }
5890
+ ;
5891
+ return response.json();
5892
+ };
5893
+ var getShop = async ({ fetcher, adminAccessToken, shop }) => {
5894
+ const data2 = await adminFetch({
5895
+ fetcher,
5896
+ adminAccessToken,
5897
+ domain: shop,
5898
+ query: `{
5899
+ shop {
5900
+ currencyCode
5901
+ id
5902
+ myshopifyDomain
5903
+ name
5904
+ }
5905
+ }`
5906
+ });
5907
+ const shopData = data2 == null ? void 0 : data2.shop;
5908
+ if (!(shopData == null ? void 0 : shopData.id)) {
5909
+ throw new Error("Shopify shop lookup failed: no shop returned");
5910
+ }
5911
+ ;
5912
+ return {
5913
+ currency: shopData.currencyCode || null,
5914
+ id: shopData.id.split("/").pop(),
5915
+ myshopifyDomain: shopData.myshopifyDomain,
5916
+ name: shopData.name
5917
+ };
5918
+ };
5919
+ var createStorefrontToken = async ({ fetcher, adminAccessToken, shop }) => {
5920
+ var _a, _b, _c, _d, _e;
5921
+ try {
5922
+ const listed = await adminFetch({
5923
+ fetcher,
5924
+ adminAccessToken,
5925
+ domain: shop,
5926
+ query: `{
5927
+ shop {
5928
+ storefrontAccessTokens(first: 100) {
5929
+ edges {
5930
+ node {
5931
+ id
5932
+ title
5933
+ }
5934
+ }
5935
+ }
5936
+ }
5937
+ }`
5938
+ });
5939
+ const existing = (((_b = (_a = listed == null ? void 0 : listed.shop) == null ? void 0 : _a.storefrontAccessTokens) == null ? void 0 : _b.edges) || []).map((edge) => edge == null ? void 0 : edge.node);
5940
+ const orphaned = existing.filter((token) => (token == null ? void 0 : token.title) === "Drawbridge");
5941
+ await Promise.allSettled(
5942
+ orphaned.map((token) => adminFetch({
5943
+ adminAccessToken,
5944
+ domain: shop,
5945
+ query: `
5946
+ mutation StorefrontAccessTokenDelete($input: StorefrontAccessTokenDeleteInput!) {
5947
+ storefrontAccessTokenDelete(input: $input) {
5948
+ deletedStorefrontAccessTokenId
5949
+ userErrors {
5950
+ field
5951
+ message
5952
+ }
5953
+ }
5954
+ }
5955
+ `,
5956
+ variables: {
5957
+ input: {
5958
+ id: token.id
5959
+ }
5960
+ }
5961
+ }))
5962
+ );
5963
+ } catch {
5964
+ }
5965
+ const created = await adminFetch({
5966
+ fetcher,
5967
+ adminAccessToken,
5968
+ domain: shop,
5969
+ query: `
5970
+ mutation StorefrontAccessTokenCreate($input: StorefrontAccessTokenInput!) {
5971
+ storefrontAccessTokenCreate(input: $input) {
5972
+ storefrontAccessToken {
5973
+ accessToken
5974
+ }
5975
+ userErrors {
5976
+ field
5977
+ message
5978
+ }
5979
+ }
5980
+ }
5981
+ `,
5982
+ variables: {
5983
+ input: {
5984
+ title: "Drawbridge"
5985
+ }
5986
+ }
5987
+ });
5988
+ const createErrors = (_c = created == null ? void 0 : created.storefrontAccessTokenCreate) == null ? void 0 : _c.userErrors;
5989
+ if (createErrors == null ? void 0 : createErrors.length) {
5990
+ throw new Error("Shopify storefront token create failed: " + createErrors[0].message);
5991
+ }
5992
+ ;
5993
+ return ((_e = (_d = created == null ? void 0 : created.storefrontAccessTokenCreate) == null ? void 0 : _d.storefrontAccessToken) == null ? void 0 : _e.accessToken) || null;
5994
+ };
5995
+ var resolveTokenContext = async ({ connection: connection2, controller }) => {
5996
+ const decrypted = (connection2 == null ? void 0 : connection2.settings) ? decrypt(connection2.settings) : {};
5997
+ if ((decrypted == null ? void 0 : decrypted.ref) !== "shop") {
5998
+ return {
5999
+ raw: (connection2 == null ? void 0 : connection2.settings) || null,
6000
+ session: null,
6001
+ settings: decrypted,
6002
+ shop: null,
6003
+ target: "connection"
6004
+ };
6005
+ }
6006
+ ;
6007
+ const shop = decrypted.shop;
6008
+ if (!controller || !shop) {
6009
+ return { raw: null, session: {}, settings: {}, shop, target: "shop" };
6010
+ }
6011
+ ;
6012
+ const record = await controller.get({ collection: "shop", query: { shop } });
6013
+ const session = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : {};
6014
+ const storefront = (record == null ? void 0 : record.storefront) ? decrypt(record.storefront) : null;
6015
+ return {
6016
+ raw: (record == null ? void 0 : record.settings) || null,
6017
+ session,
6018
+ settings: {
6019
+ adminAccessToken: session.accessToken || null,
6020
+ refreshToken: session.refreshToken || null,
6021
+ refreshTokenExpiresAt: session.refreshTokenExpires || null,
6022
+ storefrontAccessToken: (storefront == null ? void 0 : storefront.token) || null,
6023
+ tokenExpiresAt: session.expires || null
6024
+ },
6025
+ shop,
6026
+ target: "shop"
6027
+ };
6028
+ };
6029
+ var resolveConnectionSettings = async ({ fetcher, connection: connection2, controller }) => {
6030
+ const { settings } = await resolveTokenContext({ connection: connection2, controller });
6031
+ return settings;
6032
+ };
6033
+ var refreshAdminToken = async ({ fetcher, clientId, clientSecret, connection: connection2, controller }) => {
6034
+ var _a;
6035
+ const { raw, session, settings, shop, target } = await resolveTokenContext({ connection: connection2, controller });
6036
+ const domain = (connection2 == null ? void 0 : connection2.shop) || ((_a = settings.source) == null ? void 0 : _a.domain) || settings.domain || shop;
6037
+ const { refreshToken } = settings;
6038
+ const data2 = await shopifyOAuthFetch(
6039
+ `https://${domain}/admin/oauth/access_token`,
6040
+ {
6041
+ grant_type: "refresh_token",
6042
+ // Throw before the grant: rotation RETIRES the old pair the moment it
6043
+ // returns, so a credential-less call that Shopify rejects opaquely is
6044
+ // the one failure mode worth being loud about.
6045
+ client_id: required("clientId", clientId),
6046
+ client_secret: required("clientSecret", clientSecret),
6047
+ refresh_token: refreshToken
6048
+ }
6049
+ );
6050
+ const adminAccessToken = data2.access_token;
6051
+ const newRefreshToken = data2.refresh_token;
6052
+ const expiresIn = data2.expires_in;
6053
+ const tokenExpiresAt = expiresIn ? new Date(Date.now() + expiresIn * 1e3) : null;
6054
+ const refreshTokenExpiresAt = new Date(Date.now() + REFRESH_TOKEN_LIFETIME_MS);
6055
+ let liveToken = adminAccessToken;
6056
+ if (target === "shop") {
6057
+ const written = await controller.update({
6058
+ collection: "shop",
6059
+ data: {
6060
+ $set: {
6061
+ settings: encrypt({
6062
+ ...session,
6063
+ accessToken: adminAccessToken,
6064
+ expires: tokenExpiresAt,
6065
+ refreshToken: newRefreshToken,
6066
+ refreshTokenExpires: refreshTokenExpiresAt
6067
+ })
6068
+ }
6069
+ },
6070
+ query: {
6071
+ shop,
6072
+ ...raw && { settings: raw }
6073
+ }
6074
+ });
6075
+ if (!written) {
6076
+ const current = await controller.get({ collection: "shop", query: { shop } });
6077
+ if (!(current == null ? void 0 : current.settings)) {
6078
+ throw new Error("Shopify token refresh write-back failed: shop record missing for " + shop);
6079
+ }
6080
+ ;
6081
+ const currentSession = decrypt(current.settings);
6082
+ if ((currentSession == null ? void 0 : currentSession.accessToken) && currentSession.accessToken !== settings.adminAccessToken) {
6083
+ liveToken = currentSession.accessToken;
6084
+ } else {
6085
+ throw new Error("Shopify token refresh write-back failed for " + shop);
6086
+ }
6087
+ ;
6088
+ }
6089
+ ;
6090
+ } else {
6091
+ const written = await controller.update({
6092
+ collection: "connection",
6093
+ data: {
6094
+ $set: {
6095
+ settings: encrypt({
6096
+ ...settings,
6097
+ adminAccessToken,
6098
+ refreshToken: newRefreshToken,
6099
+ refreshTokenExpiresAt,
6100
+ tokenExpiresAt
6101
+ })
6102
+ }
6103
+ },
6104
+ query: {
6105
+ id: connection2.id,
6106
+ ...raw && { settings: raw }
6107
+ }
6108
+ });
6109
+ if (!written) {
6110
+ const current = await controller.get({ collection: "connection", query: { id: connection2.id } });
6111
+ const currentSettings = (current == null ? void 0 : current.settings) ? decrypt(current.settings) : null;
6112
+ if ((currentSettings == null ? void 0 : currentSettings.adminAccessToken) && currentSettings.adminAccessToken !== settings.adminAccessToken) {
6113
+ liveToken = currentSettings.adminAccessToken;
6114
+ } else {
6115
+ throw new Error("Shopify token refresh write-back failed for connection " + (connection2 == null ? void 0 : connection2.id));
6116
+ }
6117
+ ;
6118
+ }
6119
+ ;
6120
+ }
6121
+ ;
6122
+ await ping({ adminAccessToken: liveToken, domain });
6123
+ return liveToken;
6124
+ };
6125
+ var getAdminToken = async ({ fetcher, clientId, clientSecret, connection: connection2, controller }) => {
6126
+ required("clientId", clientId);
6127
+ required("clientSecret", clientSecret);
6128
+ const settings = await resolveConnectionSettings({ connection: connection2, controller });
6129
+ const { adminAccessToken, refreshToken, tokenExpiresAt } = settings;
6130
+ if (!adminAccessToken) {
6131
+ return null;
6132
+ }
6133
+ ;
6134
+ if (!refreshToken) {
6135
+ return adminAccessToken;
6136
+ }
6137
+ ;
6138
+ const needsRefresh = !tokenExpiresAt || new Date(tokenExpiresAt) < new Date(Date.now() + ACCESS_TOKEN_REFRESH_BUFFER_MS);
6139
+ if (needsRefresh) {
6140
+ return refreshAdminToken({ clientId, clientSecret, connection: connection2, controller });
6141
+ }
6142
+ ;
6143
+ return adminAccessToken;
6144
+ };
6145
+
6146
+ // lib/shopify/partner.js
6147
+ var partner_exports = {};
6148
+ __export(partner_exports, {
6149
+ getUsageChargeEvents: () => getUsageChargeEvents
6150
+ });
6151
+ var PARTNER_API = "https://partners.shopify.com";
6152
+ var getUsageChargeEvents = async ({ fetcher, appId, first = 10, occurredAtMin, organizationId, partnerToken, shopId }) => {
6153
+ var _a, _b, _c;
6154
+ if (!partnerToken || !organizationId || !appId) {
6155
+ throw new Error("getUsageChargeEvents requires partnerToken, organizationId, and appId");
6156
+ }
6157
+ ;
6158
+ const data2 = await request({
6159
+ fetcher,
6160
+ method: "POST",
6161
+ url: PARTNER_API + "/" + organizationId + "/api/" + PARTNER_API_VERSION + "/graphql.json",
6162
+ headers: {
6163
+ "X-Shopify-Access-Token": partnerToken
6164
+ },
6165
+ body: {
6166
+ query: `query usageCharges( $filter : EventFilterInput!, $first : Int! ) {
6167
+ events( filter : $filter, orderBy : OCCURRED_AT_DESC, first : $first ) {
6168
+ edges {
6169
+ node {
6170
+ id
6171
+ occurredAt
6172
+ eventType
6173
+ shop { id myshopifyDomain }
6174
+ ... on Charge {
6175
+ chargeId
6176
+ chargeType
6177
+ amount { amount currencyCode }
6178
+ usageQuantity
6179
+ planHandle
6180
+ description
6181
+ }
6182
+ }
6183
+ }
6184
+ pageInfo { hasNextPage endCursor }
6185
+ }
6186
+ }`,
6187
+ variables: {
6188
+ filter: {
6189
+ eventTypes: ["CHARGE_USAGE"],
6190
+ subjectId: String(appId),
6191
+ ...occurredAtMin && { occurredAtMin },
6192
+ ...shopId && { shopId: String(shopId) }
6193
+ },
6194
+ first
6195
+ }
6196
+ }
6197
+ });
6198
+ if ((_a = data2 == null ? void 0 : data2.errors) == null ? void 0 : _a.length) {
6199
+ throw new Error("Shopify partner events query failed: " + data2.errors.map((entry) => entry.message).join("; "));
6200
+ }
6201
+ ;
6202
+ return (((_c = (_b = data2 == null ? void 0 : data2.data) == null ? void 0 : _b.events) == null ? void 0 : _c.edges) || []).map((edge) => {
6203
+ var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j;
6204
+ return {
6205
+ amount: ((_a2 = edge.node) == null ? void 0 : _a2.amount) || null,
6206
+ chargeId: ((_b2 = edge.node) == null ? void 0 : _b2.chargeId) || null,
6207
+ // USAGE vs the recurring plan charge an approval emits — the
6208
+ // disambiguator callers filter on.
6209
+ chargeType: ((_c2 = edge.node) == null ? void 0 : _c2.chargeType) || null,
6210
+ description: ((_d = edge.node) == null ? void 0 : _d.description) || null,
6211
+ eventType: ((_e = edge.node) == null ? void 0 : _e.eventType) || null,
6212
+ id: ((_f = edge.node) == null ? void 0 : _f.id) || null,
6213
+ occurredAt: ((_g = edge.node) == null ? void 0 : _g.occurredAt) || null,
6214
+ planHandle: ((_h = edge.node) == null ? void 0 : _h.planHandle) || null,
6215
+ shop: ((_i = edge.node) == null ? void 0 : _i.shop) || null,
6216
+ usageQuantity: ((_j = edge.node) == null ? void 0 : _j.usageQuantity) ?? null
6217
+ };
6218
+ });
6219
+ };
6220
+
6221
+ // lib/shopify/storefront.js
6222
+ var storefront_exports = {};
6223
+ __export(storefront_exports, {
6224
+ cartCreate: () => cartCreate,
6225
+ cartGet: () => cartGet,
6226
+ cartLinesAdd: () => cartLinesAdd,
6227
+ cartLinesRemove: () => cartLinesRemove,
6228
+ cartLinesUpdate: () => cartLinesUpdate,
6229
+ createCheckoutToken: () => createCheckoutToken,
6230
+ getProduct: () => getProduct,
6231
+ getProductVariantsPage: () => getProductVariantsPage,
6232
+ getProducts: () => getProducts,
6233
+ probeVariantsOutOfStock: () => probeVariantsOutOfStock
6234
+ });
6235
+ var SORT_KEY_MAP = {
6236
+ bestSelling: "BEST_SELLING",
6237
+ createdAt: "CREATED_AT",
6238
+ id: "ID",
6239
+ price: "PRICE",
6240
+ productType: "PRODUCT_TYPE",
6241
+ title: "TITLE",
6242
+ updatedAt: "UPDATED_AT",
6243
+ vendor: "VENDOR"
6244
+ };
6245
+ var resolveProductSort = (sort) => {
6246
+ const entry = sort && Object.entries(sort)[0];
6247
+ if (!entry) return null;
6248
+ const [field2, direction] = entry;
6249
+ const sortKey = SORT_KEY_MAP[field2];
6250
+ if (!sortKey) return null;
6251
+ return {
6252
+ sortKey,
6253
+ reverse: Number(direction) < 0
6254
+ };
6255
+ };
6256
+ var storefrontUrl = (domain) => `https://${domain}/api/${SHOPIFY_STOREFRONT_API_VERSION}/graphql.json`;
6257
+ var storefrontFetch = async ({ fetcher, domain, storefrontAccessToken, query, variables }) => {
6258
+ return request({
6259
+ method: "POST",
6260
+ url: storefrontUrl(domain),
6261
+ headers: {
6262
+ "X-Shopify-Storefront-Access-Token": storefrontAccessToken
6263
+ },
6264
+ body: {
6265
+ query,
6266
+ ...variables && { variables }
6267
+ }
6268
+ });
6269
+ };
6270
+ var shopCountryCache = {};
6271
+ var getShopCountry = async ({ domain, fetcher, storefrontAccessToken }) => {
6272
+ var _a, _b;
6273
+ if (shopCountryCache[domain]) return shopCountryCache[domain];
6274
+ const { data: data2 } = await storefrontFetch({
6275
+ fetcher,
6276
+ domain,
6277
+ storefrontAccessToken,
6278
+ query: `{
6279
+ shop {
6280
+ paymentSettings {
6281
+ countryCode
6282
+ }
6283
+ }
6284
+ }`
6285
+ });
6286
+ const countryCode = ((_b = (_a = data2 == null ? void 0 : data2.shop) == null ? void 0 : _a.paymentSettings) == null ? void 0 : _b.countryCode) || null;
6287
+ if (countryCode) shopCountryCache[domain] = countryCode;
6288
+ return countryCode;
6289
+ };
6290
+ var OUT_OF_STOCK_WARNING_CODES = [
6291
+ "MERCHANDISE_OUT_OF_STOCK",
6292
+ "MERCHANDISE_NOT_ENOUGH_STOCK"
6293
+ ];
6294
+ var probeVariantsOutOfStock = async ({ fetcher, domain, storefrontAccessToken, variantIds, countryCode }) => {
6295
+ var _a, _b;
6296
+ if (!(variantIds == null ? void 0 : variantIds.length)) return [];
6297
+ const resolvedCountry = countryCode || await getShopCountry({ domain, fetcher, storefrontAccessToken });
6298
+ const { data: data2, errors } = await storefrontFetch({
6299
+ fetcher,
6300
+ domain,
6301
+ storefrontAccessToken,
6302
+ query: `
6303
+ mutation probe( $input : CartInput! ){
6304
+ cartCreate( input : $input ){
6305
+ cart {
6306
+ lines( first : 250 ){
6307
+ edges {
6308
+ node {
6309
+ id
6310
+ merchandise {
6311
+ ... on ProductVariant {
6312
+ id
6313
+ }
6314
+ }
6315
+ }
6316
+ }
6317
+ }
6318
+ }
6319
+ warnings {
6320
+ code
6321
+ message
6322
+ target
6323
+ }
6324
+ }
6325
+ }
6326
+ `,
6327
+ variables: {
6328
+ input: {
6329
+ lines: variantIds.map((merchandiseId) => ({
6330
+ merchandiseId,
6331
+ quantity: 1
6332
+ })),
6333
+ ...resolvedCountry && {
6334
+ buyerIdentity: {
6335
+ countryCode: resolvedCountry
6336
+ }
6337
+ }
6338
+ }
6339
+ }
6340
+ });
6341
+ if (errors) return [];
6342
+ const payload = data2 == null ? void 0 : data2.cartCreate;
6343
+ const soldOut = new Set(
6344
+ ((payload == null ? void 0 : payload.warnings) || []).filter((warning) => OUT_OF_STOCK_WARNING_CODES.includes(warning == null ? void 0 : warning.code) && (warning == null ? void 0 : warning.target)).map((warning) => warning.target)
6345
+ );
6346
+ return (((_b = (_a = payload == null ? void 0 : payload.cart) == null ? void 0 : _a.lines) == null ? void 0 : _b.edges) || []).filter(({ node }) => soldOut.has(node.id)).map(({ node }) => {
6347
+ var _a2;
6348
+ return (_a2 = node == null ? void 0 : node.merchandise) == null ? void 0 : _a2.id;
6349
+ }).filter(Boolean);
6350
+ };
6351
+ var productsQuery = (search, cursor, limit, sort) => {
6352
+ const resolved = resolveProductSort(sort);
6353
+ const sortArgs = resolved ? `, sortKey: ${resolved.sortKey}, reverse: ${resolved.reverse}` : "";
6354
+ return `{
6355
+ products(first: ${limit}${search ? `, query: "title:*${search}*"` : ""}${cursor ? `, after: "${cursor}"` : ""}${sortArgs}) {
6356
+ edges {
6357
+ node {
6358
+ id
6359
+ title
6360
+ description
6361
+ handle
6362
+ productType
6363
+ featuredImage {
6364
+ url
6365
+ }
6366
+ variants(first: 10) {
6367
+ edges {
6368
+ node {
6369
+ id
6370
+ title
6371
+ image {
6372
+ url
6373
+ }
6374
+ price {
6375
+ amount
6376
+ currencyCode
6377
+ }
6378
+ compareAtPrice {
6379
+ amount
6380
+ currencyCode
6381
+ }
6382
+ availableForSale
6383
+ requiresShipping
6384
+ }
6385
+ }
6386
+ }
6387
+ }
6388
+ }
6389
+ pageInfo {
6390
+ endCursor
6391
+ hasNextPage
6392
+ hasPreviousPage
6393
+ startCursor
6394
+ }
6395
+ }
6396
+ }`;
6397
+ };
6398
+ var productQuery = (productId) => `{
6399
+ product(id: "${productId}") {
6400
+ id
6401
+ title
6402
+ description
6403
+ handle
6404
+ productType
6405
+ featuredImage {
6406
+ url
6407
+ }
6408
+ variants(first: 10) {
6409
+ edges {
6410
+ node {
6411
+ id
6412
+ title
6413
+ image {
6414
+ url
6415
+ }
6416
+ price {
6417
+ amount
6418
+ currencyCode
6419
+ }
6420
+ compareAtPrice {
6421
+ amount
6422
+ currencyCode
6423
+ }
6424
+ availableForSale
6425
+ requiresShipping
6426
+ }
6427
+ }
6428
+ }
6429
+ }
6430
+ }`;
6431
+ var variantsQuery = (productId, cursor) => `{
6432
+ product(id: "${productId}") {
6433
+ variants(first: 250${cursor ? `, after: "${cursor}"` : ""}) {
6434
+ edges {
6435
+ node {
6436
+ id
6437
+ title
6438
+ image {
6439
+ url
6440
+ }
6441
+ price {
6442
+ amount
6443
+ currencyCode
6444
+ }
6445
+ compareAtPrice {
6446
+ amount
6447
+ currencyCode
6448
+ }
6449
+ availableForSale
6450
+ requiresShipping
6451
+ }
6452
+ }
6453
+ pageInfo {
6454
+ hasNextPage
6455
+ endCursor
6456
+ }
6457
+ }
6458
+ }
6459
+ }`;
6460
+ var getProducts = async ({ fetcher, domain, storefrontAccessToken, search, cursor, limit, sort }) => {
6461
+ const { data: data2, errors } = await storefrontFetch({
6462
+ fetcher,
6463
+ domain,
6464
+ storefrontAccessToken,
6465
+ query: productsQuery(search, cursor, limit, sort)
6466
+ });
6467
+ if (errors) {
6468
+ throw new Error("Failed to fetch Shopify products");
6469
+ }
6470
+ ;
6471
+ return data2 == null ? void 0 : data2.products;
6472
+ };
6473
+ var getProduct = async ({ fetcher, domain, storefrontAccessToken, productId }) => {
6474
+ var _a;
6475
+ const { data: data2, errors } = await storefrontFetch({
6476
+ fetcher,
6477
+ domain,
6478
+ storefrontAccessToken,
6479
+ query: productQuery(productId)
6480
+ });
6481
+ if (errors) {
6482
+ throw new Error("Shopify storefront error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
6483
+ }
6484
+ ;
6485
+ if (!(data2 == null ? void 0 : data2.product)) {
6486
+ throw new Error("Shopify product not found");
6487
+ }
6488
+ ;
6489
+ return data2.product;
6490
+ };
6491
+ var getProductVariantsPage = async ({ fetcher, domain, storefrontAccessToken, productId, cursor }) => {
6492
+ var _a;
6493
+ const { data: data2, errors } = await storefrontFetch({
6494
+ fetcher,
6495
+ domain,
6496
+ storefrontAccessToken,
6497
+ query: variantsQuery(productId, cursor)
6498
+ });
6499
+ if (errors) {
6500
+ throw new Error("Shopify storefront error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
6501
+ }
6502
+ ;
6503
+ if (!(data2 == null ? void 0 : data2.product)) {
6504
+ throw new Error("Shopify product not found");
6505
+ }
6506
+ ;
6507
+ return data2.product.variants;
6508
+ };
6509
+ var CART_FIELDS = `
6510
+ id
6511
+ checkoutUrl
6512
+ lines(first: 100) {
6513
+ edges {
6514
+ node {
6515
+ id
6516
+ quantity
6517
+ merchandise {
6518
+ ... on ProductVariant {
6519
+ id
6520
+ title
6521
+ availableForSale
6522
+ image {
6523
+ url
6524
+ }
6525
+ price {
6526
+ amount
6527
+ currencyCode
6528
+ }
6529
+ product {
6530
+ title
6531
+ }
6532
+ }
6533
+ }
6534
+ }
6535
+ }
6536
+ }
6537
+ `;
6538
+ var mapCart = (cart) => {
6539
+ var _a;
6540
+ if (!cart) return null;
6541
+ return {
6542
+ checkoutUrl: cart.checkoutUrl,
6543
+ id: cart.id,
6544
+ lines: (((_a = cart.lines) == null ? void 0 : _a.edges) || []).map(({ node }) => {
6545
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
6546
+ return {
6547
+ availableForSale: ((_a2 = node == null ? void 0 : node.merchandise) == null ? void 0 : _a2.availableForSale) ?? true,
6548
+ currency: ((_c = (_b = node == null ? void 0 : node.merchandise) == null ? void 0 : _b.price) == null ? void 0 : _c.currencyCode) || null,
6549
+ id: node.id,
6550
+ image: ((_e = (_d = node == null ? void 0 : node.merchandise) == null ? void 0 : _d.image) == null ? void 0 : _e.url) || null,
6551
+ price: ((_g = (_f = node == null ? void 0 : node.merchandise) == null ? void 0 : _f.price) == null ? void 0 : _g.amount) || null,
6552
+ productTitle: ((_i = (_h = node == null ? void 0 : node.merchandise) == null ? void 0 : _h.product) == null ? void 0 : _i.title) || null,
6553
+ quantity: node.quantity,
6554
+ variantId: (_j = node == null ? void 0 : node.merchandise) == null ? void 0 : _j.id,
6555
+ variantTitle: ((_k = node == null ? void 0 : node.merchandise) == null ? void 0 : _k.title) || null
6556
+ };
6557
+ })
6558
+ };
6559
+ };
6560
+ var firstUserError = (userErrors) => {
6561
+ const error = userErrors == null ? void 0 : userErrors[0];
6562
+ if (!error) return null;
6563
+ const message = new Error(error.message || "Shopify cart error");
6564
+ message.userError = true;
6565
+ return message;
6566
+ };
6567
+ var createCheckoutToken = async ({ fetcher, clientId, clientSecret } = {}) => {
6568
+ if (!clientId || !clientSecret) {
6569
+ throw new Error("createCheckoutToken requires clientId and clientSecret");
6570
+ }
6571
+ ;
6572
+ const response = await request({
6573
+ fetcher,
6574
+ method: "POST",
6575
+ url: "https://api.shopify.com/auth/access_token",
6576
+ body: {
6577
+ client_id: clientId,
6578
+ client_secret: clientSecret,
6579
+ grant_type: "client_credentials"
6580
+ }
6581
+ });
6582
+ const token = response == null ? void 0 : response.access_token;
6583
+ if (!token) {
6584
+ throw new Error("Failed to create Shopify checkout token");
6585
+ }
6586
+ ;
6587
+ return token;
6588
+ };
6589
+ var cartCreate = async ({ fetcher, domain, storefrontAccessToken, lines }) => {
6590
+ var _a, _b;
6591
+ const { data: data2, errors } = await storefrontFetch({
6592
+ fetcher,
6593
+ domain,
6594
+ storefrontAccessToken,
6595
+ query: `
6596
+ mutation cartCreate($input: CartInput!) {
6597
+ cartCreate(input: $input) {
6598
+ cart {
6599
+ ${CART_FIELDS}
6600
+ }
6601
+ userErrors {
6602
+ field
6603
+ message
6604
+ }
6605
+ }
6606
+ }
6607
+ `,
6608
+ variables: {
6609
+ input: {
6610
+ lines
6611
+ }
6612
+ }
6613
+ });
6614
+ if (errors) {
6615
+ throw new Error("Failed to create Shopify cart");
6616
+ }
6617
+ ;
6618
+ const userError = firstUserError((_a = data2 == null ? void 0 : data2.cartCreate) == null ? void 0 : _a.userErrors);
6619
+ if (userError) throw userError;
6620
+ return mapCart((_b = data2 == null ? void 0 : data2.cartCreate) == null ? void 0 : _b.cart);
6621
+ };
6622
+ var cartGet = async ({ fetcher, domain, storefrontAccessToken, cartId }) => {
6623
+ const { data: data2, errors } = await storefrontFetch({
6624
+ fetcher,
6625
+ domain,
6626
+ storefrontAccessToken,
6627
+ query: `
6628
+ query cart($id: ID!) {
6629
+ cart(id: $id) {
6630
+ ${CART_FIELDS}
6631
+ }
6632
+ }
6633
+ `,
6634
+ variables: {
6635
+ id: cartId
6636
+ }
6637
+ });
6638
+ if (errors) {
6639
+ throw new Error("Failed to fetch Shopify cart");
6640
+ }
6641
+ ;
6642
+ return mapCart(data2 == null ? void 0 : data2.cart);
6643
+ };
6644
+ var cartLinesAdd = async ({ fetcher, domain, storefrontAccessToken, cartId, lines }) => {
6645
+ var _a, _b;
6646
+ const { data: data2, errors } = await storefrontFetch({
6647
+ fetcher,
6648
+ domain,
6649
+ storefrontAccessToken,
6650
+ query: `
6651
+ mutation cartLinesAdd($cartId: ID!, $lines: [CartLineInput!]!) {
6652
+ cartLinesAdd(cartId: $cartId, lines: $lines) {
6653
+ cart {
6654
+ ${CART_FIELDS}
6655
+ }
6656
+ userErrors {
6657
+ field
6658
+ message
6659
+ }
6660
+ }
6661
+ }
6662
+ `,
6663
+ variables: {
6664
+ cartId,
6665
+ lines
6666
+ }
6667
+ });
6668
+ if (errors) {
6669
+ throw new Error("Failed to add Shopify cart lines");
6670
+ }
6671
+ ;
6672
+ const userError = firstUserError((_a = data2 == null ? void 0 : data2.cartLinesAdd) == null ? void 0 : _a.userErrors);
6673
+ if (userError) throw userError;
6674
+ return mapCart((_b = data2 == null ? void 0 : data2.cartLinesAdd) == null ? void 0 : _b.cart);
6675
+ };
6676
+ var cartLinesRemove = async ({ fetcher, domain, storefrontAccessToken, cartId, lineIds }) => {
6677
+ var _a, _b;
6678
+ const { data: data2, errors } = await storefrontFetch({
6679
+ fetcher,
6680
+ domain,
6681
+ storefrontAccessToken,
6682
+ query: `
6683
+ mutation cartLinesRemove($cartId: ID!, $lineIds: [ID!]!) {
6684
+ cartLinesRemove(cartId: $cartId, lineIds: $lineIds) {
6685
+ cart {
6686
+ ${CART_FIELDS}
6687
+ }
6688
+ userErrors {
6689
+ field
6690
+ message
6691
+ }
6692
+ }
6693
+ }
6694
+ `,
6695
+ variables: {
6696
+ cartId,
6697
+ lineIds
6698
+ }
6699
+ });
6700
+ if (errors) {
6701
+ throw new Error("Failed to remove Shopify cart lines");
6702
+ }
6703
+ ;
6704
+ const userError = firstUserError((_a = data2 == null ? void 0 : data2.cartLinesRemove) == null ? void 0 : _a.userErrors);
6705
+ if (userError) throw userError;
6706
+ return mapCart((_b = data2 == null ? void 0 : data2.cartLinesRemove) == null ? void 0 : _b.cart);
6707
+ };
6708
+ var cartLinesUpdate = async ({ fetcher, domain, storefrontAccessToken, cartId, lines }) => {
6709
+ var _a, _b;
6710
+ const { data: data2, errors } = await storefrontFetch({
6711
+ fetcher,
6712
+ domain,
6713
+ storefrontAccessToken,
6714
+ query: `
6715
+ mutation cartLinesUpdate($cartId: ID!, $lines: [CartLineUpdateInput!]!) {
6716
+ cartLinesUpdate(cartId: $cartId, lines: $lines) {
6717
+ cart {
6718
+ ${CART_FIELDS}
6719
+ }
6720
+ userErrors {
6721
+ field
6722
+ message
6723
+ }
6724
+ }
6725
+ }
6726
+ `,
6727
+ variables: {
6728
+ cartId,
6729
+ lines
6730
+ }
6731
+ });
6732
+ if (errors) {
6733
+ throw new Error("Failed to update Shopify cart lines");
6734
+ }
6735
+ ;
6736
+ const userError = firstUserError((_a = data2 == null ? void 0 : data2.cartLinesUpdate) == null ? void 0 : _a.userErrors);
6737
+ if (userError) throw userError;
6738
+ return mapCart((_b = data2 == null ? void 0 : data2.cartLinesUpdate) == null ? void 0 : _b.cart);
6739
+ };
6740
+
6741
+ // lib/email.js
6742
+ var GMAIL_DOMAINS = /* @__PURE__ */ new Set(["gmail.com", "googlemail.com"]);
6743
+ var toCanonicalEmail = (value) => {
6744
+ if (!value || typeof value !== "string") return null;
6745
+ const email = value.trim().toLowerCase();
6746
+ const at = email.lastIndexOf("@");
6747
+ if (at < 1 || at === email.length - 1) return null;
6748
+ let local = email.slice(0, at);
6749
+ const domain = email.slice(at + 1);
6750
+ const plus = local.indexOf("+");
6751
+ if (plus > 0) local = local.slice(0, plus);
6752
+ if (GMAIL_DOMAINS.has(domain)) local = local.replaceAll(".", "");
6753
+ if (!local) return null;
6754
+ return local + "@" + domain;
6755
+ };
6756
+
6757
+ // lib/oauth/index.js
6758
+ var lifetimes = {
6759
+ access: 60 * 60 * 8,
6760
+ // 8 hours
6761
+ authorizationCode: 10 * 60,
6762
+ // 10 minutes
6763
+ code: 15 * 60,
6764
+ // 15 minutes (email OTC)
6765
+ refresh: 30 * 24 * 60 * 60
6766
+ // 30 days
6767
+ };
6768
+ var tokenTypes = {
6769
+ access: "access",
6770
+ oauthState: "oauth.state",
6771
+ pat: "pat",
6772
+ refresh: "refresh"
6773
+ };
6774
+ var scopes = [
6775
+ "profile:read",
6776
+ "profile:write",
6777
+ "organization:read",
6778
+ "organization:write",
6779
+ "campaigns:read",
6780
+ "campaigns:write",
6781
+ "contacts:read",
6782
+ "contacts:write",
6783
+ "workflows:read",
6784
+ "workflows:write",
6785
+ "connections:read",
6786
+ "connections:write",
6787
+ "billing:read",
6788
+ "billing:write",
6789
+ "admin"
6790
+ ];
6791
+ var developer = [
6792
+ "profile:read",
6793
+ "organization:read",
6794
+ "campaigns:read",
6795
+ "campaigns:write",
6796
+ "contacts:read",
6797
+ "contacts:write",
6798
+ "workflows:read",
6799
+ "workflows:write",
6800
+ "connections:read",
6801
+ "connections:write"
6802
+ ];
6803
+ var scopeLabels = {
6804
+ "profile:read": "Read own profile",
6805
+ "profile:write": "Update own profile",
6806
+ "organization:read": "Read organization info",
6807
+ "organization:write": "Manage organization",
6808
+ "campaigns:read": "Read campaigns",
6809
+ "campaigns:write": "Manage campaigns",
6810
+ "contacts:read": "Read contacts",
6811
+ "contacts:write": "Manage contacts",
6812
+ "workflows:read": "Read workflows",
6813
+ "workflows:write": "Manage workflows",
6814
+ "connections:read": "Read integrations",
6815
+ "connections:write": "Manage integrations",
6816
+ "billing:read": "Read billing",
6817
+ "billing:write": "Manage billing",
6818
+ admin: "Admin access"
6819
+ };
6820
+ var toOption = (scope) => ({
6821
+ key: scopeLabels[scope] || scope,
6822
+ value: scope
6823
+ });
6824
+ var developerOptions = developer.map(toOption);
6825
+ var scopeOptions = scopes.map(toOption);
6826
+ var hashToken = (raw) => hash(raw, process.env.HMAC_OAUTH_TOKEN_KEY);
6827
+
6828
+ // lib/sanitize.js
6829
+ import disposableDomains from "disposable-email-domains/index.js";
6830
+ var disposableBlacklist = new Set(disposableDomains.map((d) => d.toLowerCase()));
6831
+ var sanitizeDomain = (value, pattern) => {
6832
+ if (!value) return value;
6833
+ const cleaned = value.trim().toLowerCase().replace(/^https?:\/\//i, "").replace(/\/+$/, "");
6834
+ if (pattern) {
6835
+ const match = cleaned.match(pattern);
6836
+ return match ? match[0] : cleaned;
6837
+ }
6838
+ return cleaned;
6839
+ };
6840
+
6841
+ // lib/slugify.js
6842
+ import slug from "slugify";
6843
+ var slugify = (value, nochars = false) => {
6844
+ const remove = nochars ? /[-?*+~.()'"!:@#^_{}\[\];,/\\]/g : /[?*+~.()'"!:@#^_{}\[\];,/\\]/g;
6845
+ const replacement = nochars ? "" : "-";
6846
+ return slug(
6847
+ value,
6848
+ {
6849
+ remove,
6850
+ replacement,
6851
+ lower: true,
6852
+ trim: true
6853
+ }
6854
+ );
6855
+ };
6856
+
6857
+ // lib/connections/manifests/shopify.js
6858
+ var client = Object.freeze({
6859
+ admin: admin_exports,
6860
+ billing: billing_exports,
6861
+ oauth: oauth_exports,
6862
+ partner: partner_exports,
6863
+ storefront: storefront_exports
6864
+ });
6865
+ var toLine = ({
6866
+ price,
6867
+ product_id: productId,
6868
+ quantity,
6869
+ title,
6870
+ variant_id: variantId,
6871
+ variant_title: variantTitle
6872
+ }) => ({
6873
+ price: parseFloat(price) || 0,
6874
+ productId: productId ? "gid://shopify/Product/" + productId : null,
6875
+ quantity: quantity || 1,
6876
+ title: title || null,
6877
+ variantId: variantId ? "gid://shopify/ProductVariant/" + variantId : null,
6878
+ variantTitle: variantTitle || null
6879
+ });
6880
+ var attributeLineItems = (lineItems = []) => lineItems.reduce(
6881
+ (acc, item) => {
6882
+ const attrs = (item.properties || []).reduce(
6883
+ (map, { name, value }) => {
6884
+ map[name] = value;
6885
+ return map;
6886
+ },
6887
+ {}
6888
+ );
6889
+ if (!attrs["_drwbrdg_ca"]) return acc;
6890
+ if (!Object.keys(acc.attrMap).length) acc.attrMap = attrs;
6891
+ const line = toLine(item);
6892
+ acc.attributedGross += line.price * line.quantity;
6893
+ acc.attributedLines.push(line);
6894
+ return acc;
6895
+ },
6896
+ { attrMap: {}, attributedGross: 0, attributedLines: [] }
6897
+ );
6898
+ var generateDiscountCode = customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8);
6899
+ var blockedReason = (discount) => {
6900
+ var _a;
6901
+ if ((discount == null ? void 0 : discount.status) === "EXPIRED") return "This discount has expired.";
6902
+ const buyers = (_a = discount == null ? void 0 : discount.context) == null ? void 0 : _a.__typename;
6903
+ if (buyers && buyers !== "DiscountBuyerSelectionAll") {
6904
+ return "This discount is limited to specific buyers in Shopify, so a code issued to an entrant won't work. Set it to all customers to use it here.";
6905
+ }
6906
+ ;
6907
+ if (typeof (discount == null ? void 0 : discount.usageLimit) === "number" && discount.usageLimit > 0 && ((discount == null ? void 0 : discount.asyncUsageCount) || 0) >= discount.usageLimit) {
6908
+ return "This discount has reached its total usage limit.";
6909
+ }
6910
+ ;
6911
+ return null;
6912
+ };
6913
+ var discountWarning = (discount) => {
6914
+ if ((discount == null ? void 0 : discount.status) === "SCHEDULED") {
6915
+ return "This discount hasn't started yet, so codes issued before it does won't work until then.";
6916
+ }
6917
+ ;
6918
+ if (discount == null ? void 0 : discount.appliesOncePerCustomer) return "Each customer can use this discount only once.";
6919
+ return null;
6920
+ };
6921
+ var ORDER_EVENT_HANDLE = slugify("drawbridge-orders");
6922
+ var REFRESH_TOKEN_FRESHNESS_BUFFER_MS = 5 * 24 * 60 * 60 * 1e3;
6923
+ var OAUTH_ERROR_SOURCE = "oauth";
6924
+ var BILLING_ERROR_SOURCE = "billing";
6925
+ var BILLING_ERROR_MESSAGE = "Order billing isn't set up for this store \u2014 reselect and approve the plan from the Shopify connection page.";
6926
+ var OAUTH_GRANT_REVOKED_CODES = ["application_cannot_be_found", "invalid_grant"];
6927
+ var inbound = {
6928
+ headers: {
6929
+ event: "x-shopify-topic",
6930
+ id: "x-shopify-webhook-id",
6931
+ shop: "x-shopify-shop-domain",
6932
+ signature: "x-shopify-hmac-sha256"
6933
+ },
6934
+ signature: {
6935
+ algorithm: "sha256",
6936
+ encoding: "base64",
6937
+ secret: "SHOPIFY_API_SECRET"
6938
+ }
6939
+ };
6940
+ var COMPLIANCE_TOPICS = /* @__PURE__ */ new Set([
6941
+ "customers/data_request",
6942
+ "customers/redact",
6943
+ "shop/redact"
6944
+ ]);
6945
+ var refusal = (message, status) => Object.assign(new Error(message), { status });
6946
+ var LINK_TOKEN_TTL_MS = 30 * 60 * 1e3;
6947
+ var CONNECTABLE_STATUSES = ["active", "unsubscribed"];
6948
+ var merchantOrganizations = ({ read, user }) => read.aggregate({
6949
+ collection: "organization",
6950
+ pipeline: [
6951
+ // A member qualifies only at `manage`; an owner always qualifies.
6952
+ {
6953
+ $lookup: {
6954
+ as: "membership",
6955
+ from: "member",
6956
+ let: { organization: "$id" },
6957
+ pipeline: [
6958
+ {
6959
+ $match: {
6960
+ $expr: { $eq: ["$organization", "$$organization"] },
6961
+ "capabilities.connections": "manage",
6962
+ status: "accepted",
6963
+ user
6964
+ }
6965
+ },
6966
+ { $limit: 1 },
6967
+ { $project: { _id: 0, organization: 1 } }
6968
+ ]
6969
+ }
6970
+ },
6971
+ {
6972
+ $match: {
6973
+ status: { $ne: "canceled" },
6974
+ $or: [{ owner: user }, { "membership.0": { $exists: true } }]
6975
+ }
6976
+ },
6977
+ // `organization.subscription` is a subscription RECORD ID — resolved here so
6978
+ // the list can read the real plan and conversion rate. Without it every org
6979
+ // rendered as free tier.
6980
+ { $lookup: { as: "subscription", foreignField: "id", from: "subscription", localField: "subscription" } },
6981
+ { $unwind: { path: "$subscription", preserveNullAndEmptyArrays: true } },
6982
+ {
6983
+ $lookup: {
6984
+ as: "connection",
6985
+ foreignField: "organization",
6986
+ from: "connection",
6987
+ localField: "id",
6988
+ pipeline: [
6989
+ { $match: { slug: "shopify" } },
6990
+ { $limit: 1 },
6991
+ { $project: { _id: 0, id: 1, shop: 1, status: 1 } }
6992
+ ]
6993
+ }
6994
+ },
6995
+ { $unwind: { path: "$connection", preserveNullAndEmptyArrays: true } },
6996
+ { $project: { _id: 0, billingStatus: "$status", connection: 1, id: 1, name: "$title", subscription: 1 } },
6997
+ { $sort: { name: 1 } }
6998
+ ]
6999
+ });
7000
+ var storePlan = async ({ record, shopify }) => {
7001
+ var _a;
7002
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
7003
+ if (!(settings == null ? void 0 : settings.accessToken)) return { active: false, name: null };
7004
+ try {
7005
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
7006
+ adminAccessToken: settings.accessToken,
7007
+ domain: record.shop
7008
+ });
7009
+ const active = (subscriptions || []).length > 0;
7010
+ const metered = active && subscriptions.some((subscription) => subscription.metered === true) ? true : null;
7011
+ return { active, metered, name: active ? ((_a = subscriptions[0]) == null ? void 0 : _a.name) || null : null };
7012
+ } catch (_) {
7013
+ return { active: false, name: null, unavailable: true };
7014
+ }
7015
+ };
7016
+ var releaseApprovals = async ({ context, read, shopify }) => {
7017
+ var _a;
7018
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
7019
+ if (!shop) throw refusal("shop is required", 400);
7020
+ const record = await read.get({ collection: "shop", query: { shop } });
7021
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
7022
+ if (!(settings == null ? void 0 : settings.accessToken)) throw refusal("Store is not installed", 409);
7023
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
7024
+ adminAccessToken: settings.accessToken,
7025
+ domain: shop
7026
+ });
7027
+ for (const subscription of subscriptions || []) {
7028
+ const data2 = await shopify.admin.adminFetch({
7029
+ adminAccessToken: settings.accessToken,
7030
+ domain: shop,
7031
+ query: "mutation appSubscriptionCancel( $id : ID! ) { appSubscriptionCancel( id : $id ) { appSubscription { id status } userErrors { field message } } }",
7032
+ variables: { id: subscription.id }
7033
+ });
7034
+ const [userError] = ((_a = data2 == null ? void 0 : data2.appSubscriptionCancel) == null ? void 0 : _a.userErrors) || [];
7035
+ if (userError) throw refusal(userError.message, 422);
7036
+ }
7037
+ return {
7038
+ message: "Released " + (subscriptions || []).length + " approval(s).",
7039
+ request: { shop },
7040
+ result: { ok: true }
7041
+ };
7042
+ };
7043
+ var LEDGER_WINDOW_MS = 30 * 24 * 60 * 60 * 1e3;
7044
+ var meterVerdict = async ({ adminAccessToken, ledgerFloor, partner, shop, shopId, shopify }) => {
7045
+ var _a;
7046
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({ adminAccessToken, domain: shop });
7047
+ let metered = (_a = subscriptions.find((subscription) => subscription.usageLineItemId)) == null ? void 0 : _a.usageLineItemId;
7048
+ if (!((partner == null ? void 0 : partner.partnerToken) && (partner == null ? void 0 : partner.partnerOrgId) && (partner == null ? void 0 : partner.partnerAppId) && shopId)) {
7049
+ return { boundaries: [], ledger: false, metered };
7050
+ }
7051
+ const accruals = await shopify.partner.getUsageChargeEvents({
7052
+ appId: "gid://shopify/App/" + partner.partnerAppId,
7053
+ first: 10,
7054
+ occurredAtMin: ledgerFloor.toISOString(),
7055
+ organizationId: partner.partnerOrgId,
7056
+ partnerToken: partner.partnerToken,
7057
+ shopId: "gid://shopify/Shop/" + shopId
7058
+ });
7059
+ const boundaries = (accruals || []).filter((event) => event.occurredAt).sort((a, b) => new Date(a.occurredAt) - new Date(b.occurredAt));
7060
+ const accrued = [...boundaries].reverse().find((event) => Number(event.usageQuantity) > 0);
7061
+ if (accrued) metered = String(accrued.chargeId || accrued.id);
7062
+ return { boundaries, ledger: true, metered };
7063
+ };
7064
+ var toVariant = (edge) => {
7065
+ var _a, _b, _c, _d;
7066
+ return {
7067
+ availableForSale: edge.node.availableForSale || false,
7068
+ currency: ((_a = edge.node.price) == null ? void 0 : _a.currencyCode) || null,
7069
+ id: edge.node.id,
7070
+ image: ((_b = edge.node.image) == null ? void 0 : _b.url) || null,
7071
+ price: parseFloat((_c = edge.node.price) == null ? void 0 : _c.amount) || null,
7072
+ requiresShipping: edge.node.requiresShipping || false,
7073
+ sale: parseFloat((_d = edge.node.compareAtPrice) == null ? void 0 : _d.amount) || null,
7074
+ title: edge.node.title !== "Default Title" ? edge.node.title : null
7075
+ };
7076
+ };
7077
+ var applyOutOfStock = async ({ domain, shopify, storefrontAccessToken, variants }) => {
7078
+ try {
7079
+ const outOfStock = new Set(await shopify.storefront.probeVariantsOutOfStock({
7080
+ domain,
7081
+ storefrontAccessToken,
7082
+ variantIds: variants.map((variant) => variant.id)
7083
+ }));
7084
+ return variants.map((variant) => ({
7085
+ ...variant,
7086
+ availableForSale: variant.availableForSale && !outOfStock.has(variant.id)
7087
+ }));
7088
+ } catch (_) {
7089
+ return variants;
7090
+ }
7091
+ };
7092
+ var sendFeedback = async ({ adminToken, connection: connection2, messages, productId, shopify, state }) => {
7093
+ try {
7094
+ await shopify.admin.sendProductResourceFeedback({
7095
+ adminAccessToken: await adminToken(),
7096
+ domain: connection2.shop,
7097
+ messages,
7098
+ productId,
7099
+ state
7100
+ });
7101
+ return null;
7102
+ } catch (error) {
7103
+ return error;
7104
+ }
7105
+ };
7106
+ var resolveProduct = async ({ connection: connection2, context, read }) => {
7107
+ const byId = (context == null ? void 0 : context.product) ? await read.get({ collection: "product", query: { id: context.product } }) : null;
7108
+ const row2 = byId || ((context == null ? void 0 : context.providerId) && ((context == null ? void 0 : context.shop) || (connection2 == null ? void 0 : connection2.shop)) ? await read.get({
7109
+ collection: "product",
7110
+ query: {
7111
+ "provider.id": context.providerId,
7112
+ "provider.slug": "shopify",
7113
+ "source.domain": context.shop || connection2.shop
7114
+ }
7115
+ }) : null);
7116
+ return row2;
7117
+ };
7118
+ var UNAVAILABLE_FEEDBACK = "Drawbridge can't display this product. Check it is active and available in the United States.";
7119
+ var NOT_FOUND = "Shopify product not found";
7120
+ var syncProduct = async ({ adminToken, connection: connection2, context, read, settings, shopify }) => {
7121
+ var _a, _b, _c;
7122
+ const row2 = await resolveProduct({ connection: connection2, context, read });
7123
+ if (!row2) return { message: "No product row to sync.", request: { product: (context == null ? void 0 : context.product) || null }, skipped: true };
7124
+ const domain = connection2.shop;
7125
+ const providerId = (_a = row2.provider) == null ? void 0 : _a.id;
7126
+ const request2 = { product: row2.id, providerId: providerId || null, shop: domain };
7127
+ let product;
7128
+ try {
7129
+ product = await shopify.storefront.getProduct({
7130
+ domain,
7131
+ productId: providerId,
7132
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken
7133
+ });
7134
+ } catch (error) {
7135
+ if (error.message !== NOT_FOUND) throw error;
7136
+ const failed2 = await sendFeedback({
7137
+ adminToken,
7138
+ connection: connection2,
7139
+ messages: [UNAVAILABLE_FEEDBACK],
7140
+ productId: providerId,
7141
+ shopify,
7142
+ state: "REQUIRES_ACTION"
7143
+ });
7144
+ return {
7145
+ failed: failed2 ? [failed2.message] : void 0,
7146
+ message: "Storefront cannot see this product \u2014 deactivated.",
7147
+ request: request2,
7148
+ result: { status: "inactive" },
7149
+ writes: [
7150
+ {
7151
+ collection: "product",
7152
+ data: { $set: { status: "inactive" } },
7153
+ operation: "update",
7154
+ query: { id: row2.id }
7155
+ },
7156
+ {
7157
+ collection: "advertisement",
7158
+ data: { $set: { status: "drafted" } },
7159
+ multiple: true,
7160
+ operation: "update",
7161
+ query: { product: row2.id }
7162
+ }
7163
+ ]
7164
+ };
7165
+ }
7166
+ const variants = await applyOutOfStock({
7167
+ domain,
7168
+ shopify,
7169
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken,
7170
+ variants: (((_b = product == null ? void 0 : product.variants) == null ? void 0 : _b.edges) || []).map(toVariant)
7171
+ });
7172
+ const failed = await sendFeedback({
7173
+ adminToken,
7174
+ connection: connection2,
7175
+ messages: [],
7176
+ productId: providerId,
7177
+ shopify,
7178
+ state: "ACCEPTED"
7179
+ });
7180
+ return {
7181
+ // EVERYTHING PAST THE FIRST PAGE, filled in silently. The first page is
7182
+ // written above; a product with thousands of variants becomes N short
7183
+ // sequential jobs rather than one long loop that risks a BullMQ stall.
7184
+ enqueues: [{
7185
+ data: { operation: "variants", product: row2.id },
7186
+ name: "sync",
7187
+ options: { jobId: "product.shopify.variants." + row2.id + "." + Date.now() },
7188
+ queue: "product.shopify.variants"
7189
+ }],
7190
+ failed: failed ? [failed.message] : void 0,
7191
+ message: "Synced " + (product.title || "product") + ".",
7192
+ request: request2,
7193
+ result: { status: "active", variants: variants.length },
7194
+ writes: [{
7195
+ collection: "product",
7196
+ data: {
7197
+ $set: {
7198
+ description: product.description || null,
7199
+ image: ((_c = product.featuredImage) == null ? void 0 : _c.url) || null,
7200
+ // A successful sync PROVES channel visibility, which reverses the
7201
+ // deactivation above. Ads stay drafted.
7202
+ status: "active",
7203
+ title: product.title || null,
7204
+ type: product.productType || null,
7205
+ url: domain && product.handle ? "https://" + domain + "/products/" + product.handle : null,
7206
+ variants
7207
+ }
7208
+ },
7209
+ operation: "update",
7210
+ query: { id: row2.id }
7211
+ }]
7212
+ };
7213
+ };
7214
+ var syncVariants = async ({ connection: connection2, context, read, settings, shopify }) => {
7215
+ var _a, _b, _c;
7216
+ const row2 = await resolveProduct({ connection: connection2, context, read });
7217
+ if (!row2) return { message: "No product row to paginate.", request: { product: (context == null ? void 0 : context.product) || null }, skipped: true };
7218
+ const cursor = (context == null ? void 0 : context.cursor) || null;
7219
+ const request2 = { cursor, product: row2.id };
7220
+ let page2;
7221
+ try {
7222
+ page2 = await shopify.storefront.getProductVariantsPage({
7223
+ cursor,
7224
+ domain: connection2.shop,
7225
+ productId: (_a = row2.provider) == null ? void 0 : _a.id,
7226
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken
7227
+ });
7228
+ } catch (error) {
7229
+ if (error.message !== NOT_FOUND) throw error;
7230
+ return { message: "Storefront lost this product mid-pagination \u2014 stopping.", request: request2, skipped: true };
7231
+ }
7232
+ const variants = await applyOutOfStock({
7233
+ domain: connection2.shop,
7234
+ shopify,
7235
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken,
7236
+ variants: (page2.edges || []).map(toVariant)
7237
+ });
7238
+ return {
7239
+ ...((_b = page2.pageInfo) == null ? void 0 : _b.hasNextPage) && { enqueues: [{
7240
+ data: { cursor: page2.pageInfo.endCursor, operation: "variants", product: row2.id },
7241
+ name: "page",
7242
+ options: { jobId: "product.shopify.variants." + row2.id + "." + Date.now() },
7243
+ queue: "product.shopify.variants"
7244
+ }] },
7245
+ message: variants.length + " variant(s) on this page.",
7246
+ request: request2,
7247
+ result: { hasNextPage: Boolean((_c = page2.pageInfo) == null ? void 0 : _c.hasNextPage), variants: variants.length },
7248
+ writes: [{
7249
+ collection: "product",
7250
+ data: cursor ? { $push: { variants: { $each: variants } } } : { $set: { variants } },
7251
+ operation: "update",
7252
+ query: { id: row2.id }
7253
+ }]
7254
+ };
7255
+ };
7256
+ var shopify_default2 = {
7257
+ // THE WORDS ON THE BUTTONS. `listing` was `content.redirect.title`, which put
7258
+ // a BUTTON LABEL inside the copy object next to a url — the title and the
7259
+ // address it belongs to sat at different levels and could drift apart.
7260
+ //
7261
+ // It names where the link GOES rather than what it does: installing happens on
7262
+ // the App Store listing, and the dashboard must never imply a store can be
7263
+ // linked from inside it.
7264
+ actions: {
7265
+ create: null,
7266
+ listing: "View on the Shopify App Store",
7267
+ manage: null,
7268
+ update: null
7269
+ },
7270
+ // INSTALL, not oauth. The grant is an OAuth grant, but the merchant never
7271
+ // sees a consent screen we sent them to -- they start at the App Store, and
7272
+ // the install completes inside Shopify admin without redirecting back. A
7273
+ // Connect button here would be lying about where connecting happens.
7274
+ auth: {
7275
+ // ONE STORE PER ORGANIZATION. A Shopify install IS a store, and a second
7276
+ // one would give an organization two catalogues, two order streams and two
7277
+ // usage meters with nothing to say which is authoritative.
7278
+ //
7279
+ // DECLARED AND ENFORCED BY NOTHING, measured 2026-09-13: no repo reads this
7280
+ // key, and the connection collection's { organization, slug } index is not
5236
7281
  // unique. So a second Shopify connection would be accepted today. The gate
5237
7282
  // belongs at the connect route with a unique partial index behind it, and
5238
7283
  // that is api work — this is the declaration it will read.
@@ -5394,8 +7439,8 @@ var shopify_default2 = {
5394
7439
  // string; this answers what is missing from it.
5395
7440
  //
5396
7441
  // `shopify` is injected for the same reason it is everywhere else — this
5397
- // package cannot import @drawbridge/shopify, which depends on it.
5398
- scopes: ({ scope }, { shopify } = {}) => ({ result: { missing: scope ? shopify.oauth.missingScopes(scope) : null } }),
7442
+ // client is imported here and defaulted, never wired in by a caller.
7443
+ scopes: ({ scope }, { shopify = client } = {}) => ({ result: { missing: scope ? shopify.oauth.missingScopes(scope) : null } }),
5399
7444
  // Shopify's install grant is exchanged inside its own app flow, not
5400
7445
  // through the shared OAuth runner.
5401
7446
  token: false
@@ -5409,17 +7454,53 @@ var shopify_default2 = {
5409
7454
  // can reference another), `dispatch` (the caller's own coordinator table,
5410
7455
  // for the hooks that are dispatches).
5411
7456
  commerce: {
5412
- // NOT YET. The Checkout Kit cart path is `api/route/subdomain.js`, six direct
5413
- // calls into `@drawbridge/shopify/storefront` that write nothing — which is
5414
- // exactly why it never became a hook: a hook is reached to have its effects
5415
- // performed, and this one has none to perform. It moves here when the vendor
5416
- // client moves into the manifest and `subdomain.js` stops importing the
5417
- // package directly.
5418
- cart: false,
7457
+ // THE CHECKOUT KIT CART. Six operations that were six direct calls into
7458
+ // the storefront client from api/route/subdomain.js.
7459
+ //
7460
+ // IT WRITES NOTHING, which is exactly why it was the last surface to
7461
+ // become a hook a hook is usually reached to have its effects performed
7462
+ // and this one has none. That reasoning was wrong: a hook is also the one
7463
+ // place a vendor's client is allowed to be called from, and leaving the
7464
+ // cart out meant a public route importing a vendor SDK directly.
7465
+ //
7466
+ // ONE HOOK, OPERATION IN THE CONTEXT, the same shape `inbound.process`
7467
+ // uses for its topic table. Six slots would be six names in the closed
7468
+ // vocabulary for one question — what does this shopper's cart look like
7469
+ // now — asked six ways.
7470
+ //
7471
+ // A USER ERROR IS A 400 AND THE SHOPPER'S OWN WORDS. Shopify's cart
7472
+ // mutations answer "that variant is sold out" as a userError rather than a
7473
+ // transport failure, and the route it replaced already told the two apart.
7474
+ // runHook carries `status` off a thrown error, so it survives to the
7475
+ // caller; the rest of a thrown error's shape does not.
7476
+ cart: async ({ clientId, clientSecret, context, settings }, { fetcher, shopify = client } = {}) => {
7477
+ const { cartId, lineIds, lines, operation } = context || {};
7478
+ const { domain, storefrontAccessToken } = settings || {};
7479
+ if (operation === "checkout") {
7480
+ const token = await shopify.storefront.createCheckoutToken({ clientId, clientSecret, fetcher });
7481
+ return { message: "Checkout token minted.", result: { token } };
7482
+ }
7483
+ const storefront = { domain, fetcher, storefrontAccessToken };
7484
+ try {
7485
+ const cart = await ({
7486
+ create: () => shopify.storefront.cartCreate({ ...storefront, lines }),
7487
+ get: () => shopify.storefront.cartGet({ ...storefront, cartId }),
7488
+ linesAdd: () => shopify.storefront.cartLinesAdd({ ...storefront, cartId, lines }),
7489
+ linesRemove: () => shopify.storefront.cartLinesRemove({ ...storefront, cartId, lineIds }),
7490
+ linesUpdate: () => shopify.storefront.cartLinesUpdate({ ...storefront, cartId, lines })
7491
+ }[operation] || (() => {
7492
+ throw Object.assign(new Error("Unknown cart operation: " + operation), { status: 400 });
7493
+ }))();
7494
+ return { message: "Cart " + operation + ".", request: { cartId: cartId || null, operation }, result: cart };
7495
+ } catch (error) {
7496
+ if (error == null ? void 0 : error.userError) throw Object.assign(error, { status: 400 });
7497
+ throw error;
7498
+ }
7499
+ },
5419
7500
  // MINT A DISCOUNT CODE against the merchant's chosen discount, mapped to
5420
7501
  // one lead — which is what lets an order that redeems it be attributed
5421
7502
  // back.
5422
- code: async ({ connection: connection2, context, step }, { adminToken, shopify } = {}) => {
7503
+ code: async ({ connection: connection2, context, step }, { adminToken, shopify = client } = {}) => {
5423
7504
  var _a;
5424
7505
  const discount = (_a = step.settings) == null ? void 0 : _a.discount;
5425
7506
  const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection2.shop };
@@ -5465,7 +7546,7 @@ var shopify_default2 = {
5465
7546
  // customer at the store is a support ticket: the context may already
5466
7547
  // carry the id from an earlier step, the lead may already be linked from
5467
7548
  // an earlier run, and Shopify's own get-or-create settles the rest.
5468
- customer: async ({ connection: connection2, context }, { adminToken, read, shopify } = {}) => {
7549
+ customer: async ({ connection: connection2, context }, { adminToken, read, shopify = client } = {}) => {
5469
7550
  const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection2.shop };
5470
7551
  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 };
5471
7552
  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 };
@@ -5515,6 +7596,30 @@ var shopify_default2 = {
5515
7596
  }]
5516
7597
  };
5517
7598
  },
7599
+ // HOW MANY ARE LEFT. Read at the moment a campaign's product list is
7600
+ // rendered rather than stored on the product, because stock is the one
7601
+ // product fact that is stale the instant it is written down.
7602
+ //
7603
+ // SUMMED HERE, not by the caller. Shopify answers per variant and every
7604
+ // caller wanted the total; the one that existed summed it inline, and
7605
+ // summing `Object.values()` over the raw map is how a cache wrapper's own
7606
+ // bookkeeping key got counted as a quantity.
7607
+ inventory: async ({ connection: connection2, context }, { adminToken, shopify = client } = {}) => {
7608
+ const productId = context == null ? void 0 : context.product;
7609
+ const request2 = { product: productId || null, shop: connection2.shop };
7610
+ if (!productId) return { message: "No product id \u2014 nothing to count.", request: request2, result: { total: null }, skipped: true };
7611
+ const adminAccessToken = await adminToken();
7612
+ const byVariant = await shopify.admin.getProductInventory({
7613
+ adminAccessToken,
7614
+ domain: connection2.shop,
7615
+ productId
7616
+ });
7617
+ return {
7618
+ message: "Inventory read.",
7619
+ request: request2,
7620
+ result: { total: Object.values(byVariant || {}).reduce((sum, quantity) => sum + quantity, 0) }
7621
+ };
7622
+ },
5518
7623
  // AN ORDER ARRIVED AT THE STORE. The largest hook in the family, because
5519
7624
  // attribution genuinely is: an order can reach Drawbridge two ways and
5520
7625
  // they bill differently.
@@ -5874,10 +7979,28 @@ var shopify_default2 = {
5874
7979
  //
5875
7980
  // The shell has already refused a missing or inactive Shopify connection,
5876
7981
  // so what is left is the two things only this hook can know are wrong.
5877
- product: async ({ connection: connection2, context, workflow }, { mintId, read } = {}) => {
7982
+ // A PRODUCT, IN THREE MOVES. Nested by operation rather than by three
7983
+ // slots in the closed vocabulary, the same shape inbound.process uses
7984
+ // for its topic table — they are one subject, and a vendor that syncs
7985
+ // products has to answer all three or none.
7986
+ //
7987
+ // record a webhook said a product changed: upsert the row and
7988
+ // queue the pull
7989
+ // sync pull the product from the storefront and write what it
7990
+ // says, including what it says by NOT answering
7991
+ // variants one page of variants, self-chaining
7992
+ //
7993
+ // `sync` and `variants` were 443 lines of drawbridge-sync's
7994
+ // queue/product.js — a shadow implementation of the step this manifest
7995
+ // already declared, importing three of the vendor's client modules from
7996
+ // a worker file.
7997
+ product: async ({ connection: connection2, context, settings, workflow }, { adminToken, mintId, read, shopify = client } = {}) => {
7998
+ const operation = (context == null ? void 0 : context.operation) || "record";
7999
+ if (operation === "sync") return syncProduct({ adminToken, connection: connection2, context, read, settings, shopify });
8000
+ if (operation === "variants") return syncVariants({ connection: connection2, context, read, settings, shopify });
5878
8001
  const request2 = {
5879
8002
  numericId: (context == null ? void 0 : context.id) || null,
5880
- organizationId: workflow.organization,
8003
+ organizationId: (workflow == null ? void 0 : workflow.organization) || null,
5881
8004
  title: (context == null ? void 0 : context.title) || null
5882
8005
  };
5883
8006
  if (!(context == null ? void 0 : context.id)) return { message: "Skipped \u2014 product webhook payload had no id.", request: request2, response: { skipped: true }, skipped: true };
@@ -5927,9 +8050,612 @@ var shopify_default2 = {
5927
8050
  }
5928
8051
  },
5929
8052
  contacts: { remove: false, sync: false },
5930
- // The embedded-app surface. Only a vendor whose merchants arrive from its
5931
- // own app store has one.
5932
- install: false,
8053
+ // THE EMBEDDED-APP SURFACE. Only a vendor whose merchants arrive from its
8054
+ // own app store has one, and these thirteen slots are the thirteen routes
8055
+ // that used to live in api/route/shopify-embedded.js.
8056
+ //
8057
+ // A HOOK DESCRIBES ITS WRITES and the shell performs them, so none of these
8058
+ // holds a controller — `read` is the controller's read methods and nothing
8059
+ // else. Where one REFUSES it throws with a status, and the route answers
8060
+ // what it said. The helpers they share are above the manifest.
8061
+ install: {
8062
+ account: {
8063
+ // ESTABLISH THE DURABLE MERCHANT-TO-STORE LINK. The breakout
8064
+ // authenticates the merchant once, top-level, and stashes their user
8065
+ // token in `install.token.save`; App Bridge has already proven shop
8066
+ // control by the time this runs.
8067
+ //
8068
+ // THE STASHED TOKEN IS THE TRUST ANCHOR, not merely any valid user
8069
+ // token: the presented one must BE this shop's one-shot handoff token,
8070
+ // unexpired, and an access or pat record — a refresh or oauth-state
8071
+ // token that happens to resolve to a user must not qualify, which is
8072
+ // the rule a session is held to in drawbridge-api's middleware.
8073
+ link: async ({ context }, { read } = {}) => {
8074
+ var _a;
8075
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8076
+ const token = context == null ? void 0 : context.token;
8077
+ if (!shop || !token) throw refusal("shop and token are required", 400);
8078
+ const now = /* @__PURE__ */ new Date();
8079
+ const record = await read.get({ collection: "shop", query: { shop } });
8080
+ const stashed = (record == null ? void 0 : record.linkToken) ? (_a = decrypt(record.linkToken)) == null ? void 0 : _a.token : null;
8081
+ const expired = !(record == null ? void 0 : record.linkTokenExpiresAt) || new Date(record.linkTokenExpiresAt) <= now;
8082
+ if (!stashed || expired || stashed !== token) throw refusal("Invalid or expired link token", 401);
8083
+ const granted = await read.get({
8084
+ collection: "token",
8085
+ query: {
8086
+ revoked: false,
8087
+ tokenHash: hashToken(token),
8088
+ type: { $in: [tokenTypes.access, tokenTypes.pat] }
8089
+ }
8090
+ });
8091
+ if (!(granted == null ? void 0 : granted.user) || granted.expiresAt && new Date(granted.expiresAt) <= now) {
8092
+ throw refusal("Invalid or expired link token", 401);
8093
+ }
8094
+ const switching = Boolean(record == null ? void 0 : record.user) && record.user !== granted.user;
8095
+ const connections2 = switching ? await read.aggregate({
8096
+ collection: "connection",
8097
+ pipeline: [
8098
+ { $match: { shop, slug: "shopify" } },
8099
+ { $project: { _id: 0, id: 1 } }
8100
+ ]
8101
+ }) : [];
8102
+ return {
8103
+ message: switching ? "Linked to a different Drawbridge account." : "Linked.",
8104
+ request: { shop },
8105
+ result: { connected: true, switched: switching },
8106
+ // ALL OR NONE. A half-done switch is a store linked to the new
8107
+ // account while the old account's connections still serve from it.
8108
+ transaction: true,
8109
+ writes: [
8110
+ ...(connections2 || []).map((connection2) => ({
8111
+ collection: "connection",
8112
+ operation: "delete",
8113
+ query: { id: connection2.id }
8114
+ })),
8115
+ {
8116
+ collection: "shop",
8117
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null, user: granted.user } },
8118
+ operation: "update",
8119
+ query: { shop }
8120
+ }
8121
+ ]
8122
+ };
8123
+ },
8124
+ // DISCONNECT THE ACCOUNT FROM THE STORE. Every org connection goes and
8125
+ // the durable link clears; the offline token and the shop record stay,
8126
+ // because the app is still installed and the merchant may link a
8127
+ // different account next.
8128
+ unlink: async ({ context }, { read } = {}) => {
8129
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8130
+ if (!shop) throw refusal("shop is required", 400);
8131
+ const connections2 = await read.aggregate({
8132
+ collection: "connection",
8133
+ pipeline: [
8134
+ { $match: { shop, slug: "shopify" } },
8135
+ { $project: { _id: 0, id: 1 } }
8136
+ ]
8137
+ });
8138
+ return {
8139
+ message: "Unlinked " + (connections2 || []).length + " connection(s).",
8140
+ request: { shop },
8141
+ result: { ok: true },
8142
+ transaction: true,
8143
+ writes: [
8144
+ ...(connections2 || []).map((connection2) => ({
8145
+ collection: "connection",
8146
+ operation: "delete",
8147
+ query: { id: connection2.id }
8148
+ })),
8149
+ {
8150
+ collection: "shop",
8151
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null, user: null } },
8152
+ operation: "update",
8153
+ query: { shop }
8154
+ }
8155
+ ]
8156
+ };
8157
+ }
8158
+ },
8159
+ organizations: {
8160
+ // BIND ONE ORGANIZATION TO THIS STORE. The longest slot here, and every
8161
+ // gate in it came from a line in the route it replaces.
8162
+ add: async ({ context }, { currencies: currencies2, mintId, read, shopify = client } = {}) => {
8163
+ var _a, _b;
8164
+ const organization2 = context == null ? void 0 : context.organization;
8165
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8166
+ if (!shop) throw refusal("shop is required", 400);
8167
+ if (!organization2) throw refusal("organization is required", 400);
8168
+ const record = await read.get({ collection: "shop", query: { shop } });
8169
+ if (!(record == null ? void 0 : record.user)) throw refusal("Account is not connected for this store", 409);
8170
+ const owned = await merchantOrganizations({ read, user: record.user });
8171
+ const org = (owned || []).find((entry) => entry.id === organization2);
8172
+ if (!org) throw refusal("No access to this organization", 403);
8173
+ if (!CONNECTABLE_STATUSES.includes(org.billingStatus)) {
8174
+ throw refusal("This organization can't accept connections right now \u2014 check its billing status in the dashboard", 403);
8175
+ }
8176
+ if (org.connection && org.connection.shop !== shop) {
8177
+ throw refusal("This organization is already connected to another Shopify store", 409);
8178
+ }
8179
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
8180
+ if (!(settings == null ? void 0 : settings.accessToken)) {
8181
+ throw refusal("Store is not installed \u2014 open the app in the Shopify admin first", 409);
8182
+ }
8183
+ const plan = await storePlan({ record, shopify });
8184
+ if (plan.unavailable) throw refusal("Couldn't verify the store's plan \u2014 try again shortly", 502);
8185
+ if (!plan.active) throw refusal("Approve a plan before connecting organizations", 402);
8186
+ let storefront = null;
8187
+ if (!record.storefront) {
8188
+ try {
8189
+ const minted2 = await shopify.oauth.createStorefrontToken({
8190
+ adminAccessToken: settings.accessToken,
8191
+ shop
8192
+ });
8193
+ if (minted2) storefront = encrypt({ token: minted2 });
8194
+ } catch (_) {
8195
+ }
8196
+ }
8197
+ let currency = (record == null ? void 0 : record.currency) || null;
8198
+ let source = (record == null ? void 0 : record.source) || null;
8199
+ try {
8200
+ const shopData = await shopify.oauth.getShop({ adminAccessToken: settings.accessToken, shop });
8201
+ if (shopData) {
8202
+ currency = String(shopData.currency || "").toLowerCase() || null;
8203
+ source = { domain: shopData.myshopifyDomain, id: String(shopData.id), label: shopData.name };
8204
+ }
8205
+ } catch (_) {
8206
+ }
8207
+ if (currency && currencies2 && !currencies2.includes(currency)) {
8208
+ throw refusal("This store settles in a currency we can't bill yet. Connect a store with a supported settlement currency.", 422);
8209
+ }
8210
+ const minted = ((_a = org.connection) == null ? void 0 : _a.id) ? null : mintId();
8211
+ const connectionId = ((_b = org.connection) == null ? void 0 : _b.id) || minted.id;
8212
+ return {
8213
+ message: "Connected " + org.name + " to " + shop + ".",
8214
+ request: { organization: organization2, shop },
8215
+ result: { ok: true },
8216
+ transaction: true,
8217
+ writes: [
8218
+ ...storefront ? [{
8219
+ collection: "shop",
8220
+ data: { $set: { storefront } },
8221
+ operation: "update",
8222
+ query: { shop }
8223
+ }] : [],
8224
+ {
8225
+ collection: "connection",
8226
+ data: {
8227
+ $set: {
8228
+ currency,
8229
+ errors: [],
8230
+ // The token of record lives on the shared `shop` row; this
8231
+ // is the pointer that satisfies the required `settings`
8232
+ // string, and `auth.install.shared` declares how to read it.
8233
+ settings: encrypt({ ref: "shop", shop }),
8234
+ shop,
8235
+ status: "pending",
8236
+ ...source && { source }
8237
+ },
8238
+ $setOnInsert: {
8239
+ ...minted && { _id: minted._id, id: minted.id },
8240
+ feature: "organization:connection:shopify",
8241
+ organization: organization2,
8242
+ slug: "shopify"
8243
+ }
8244
+ },
8245
+ operation: "update",
8246
+ options: { upsert: true },
8247
+ query: { organization: organization2, slug: "shopify" }
8248
+ },
8249
+ {
8250
+ collection: "organization",
8251
+ data: {
8252
+ // $addToSet UNCONDITIONALLY. The route this replaces only
8253
+ // registered the refs when the upsert INSERTED, which meant an
8254
+ // org whose refs had drifted stayed drifted through every
8255
+ // re-link. Adding a member that is already there is a no-op,
8256
+ // so doing it every time costs nothing and repairs the drift.
8257
+ $addToSet: {
8258
+ "connections.groups": "ecommerce",
8259
+ "connections.ids": connectionId,
8260
+ "connections.keys": "shopify"
8261
+ },
8262
+ $set: { billingProvider: "shopify" }
8263
+ },
8264
+ operation: "update",
8265
+ query: { id: organization2 }
8266
+ }
8267
+ ]
8268
+ };
8269
+ },
8270
+ // WHAT THIS STORE CAN SEE: the linked merchant's organizations, the
8271
+ // store's live plan, and the products the merchant has to act on.
8272
+ //
8273
+ // AN ORG CONNECTED TO A DIFFERENT STORE IS OMITTED ENTIRELY, because
8274
+ // `add` would refuse it — a list that offers what the next call rejects
8275
+ // is worse than a shorter one.
8276
+ list: async ({ context }, { conversionRate: conversionRate2, planTitle, read, shopify = client } = {}) => {
8277
+ var _a;
8278
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8279
+ if (!shop) throw refusal("shop is required", 400);
8280
+ const record = await read.get({ collection: "shop", query: { shop } });
8281
+ if (!(record == null ? void 0 : record.user)) {
8282
+ return {
8283
+ message: "No account linked to this store.",
8284
+ request: { shop },
8285
+ result: {
8286
+ account: null,
8287
+ connected: false,
8288
+ organizations: [],
8289
+ plan: { active: false, name: null },
8290
+ unavailableProducts: [],
8291
+ unavailableProductsTotal: 0
8292
+ }
8293
+ };
8294
+ }
8295
+ const owned = await merchantOrganizations({ read, user: record.user });
8296
+ const organizations = (owned || []).filter((org) => !org.connection || org.connection.shop === shop).map((org) => {
8297
+ var _a2;
8298
+ return {
8299
+ // The org's OWN billing status decides whether `add` accepts it.
8300
+ // Sent up so the app can disable Connect and name the reason
8301
+ // rather than letting the merchant click into a 403 —
8302
+ // listed-but-blocked beats hidden, because an org vanishing from
8303
+ // the list is indistinguishable from a bug.
8304
+ billingStatus: org.billingStatus || null,
8305
+ connectable: CONNECTABLE_STATUSES.includes(org.billingStatus),
8306
+ connected: Boolean(org.connection),
8307
+ conversion: conversionRate2(org.subscription),
8308
+ id: org.id,
8309
+ name: org.name,
8310
+ plan: planTitle(org.subscription),
8311
+ status: ((_a2 = org.connection) == null ? void 0 : _a2.status) || null
8312
+ };
8313
+ });
8314
+ const connections2 = (owned || []).filter((org) => {
8315
+ var _a2;
8316
+ return ((_a2 = org.connection) == null ? void 0 : _a2.shop) === shop && org.connection.id;
8317
+ }).map((org) => org.connection.id);
8318
+ const [account, plan, unavailable] = await Promise.all([
8319
+ read.get({ collection: "user", query: { id: record.user } }),
8320
+ storePlan({ record, shopify }),
8321
+ connections2.length ? read.aggregate({
8322
+ collection: "product",
8323
+ pipeline: [
8324
+ { $match: { connections: { $in: connections2 }, "source.domain": shop, status: "inactive" } },
8325
+ // $facet so the app can name the first 25 AND report a
8326
+ // truthful total: listing 25 of 40 under "25 products need
8327
+ // attention" would understate the problem.
8328
+ {
8329
+ $facet: {
8330
+ items: [{ $sort: { title: 1 } }, { $limit: 25 }, { $project: { _id: 0, id: 1, title: 1 } }],
8331
+ total: [{ $count: "count" }]
8332
+ }
8333
+ }
8334
+ ]
8335
+ }) : []
8336
+ ]);
8337
+ const facet = (unavailable || [])[0] || {};
8338
+ if (plan.active && plan.metered !== true) {
8339
+ const stamped = await read.aggregate({
8340
+ collection: "connection",
8341
+ pipeline: [
8342
+ { $match: { shop, slug: "shopify" } },
8343
+ { $project: { _id: 0, "source.metered": 1 } }
8344
+ ]
8345
+ });
8346
+ const verdicts = (stamped || []).map((row2) => {
8347
+ var _a2;
8348
+ return (_a2 = row2 == null ? void 0 : row2.source) == null ? void 0 : _a2.metered;
8349
+ });
8350
+ if (verdicts.some((verdict) => typeof verdict === "string")) plan.metered = true;
8351
+ else if (verdicts.some((verdict) => verdict === null)) plan.metered = false;
8352
+ }
8353
+ return {
8354
+ message: organizations.length + " organization(s) for this store.",
8355
+ request: { shop },
8356
+ result: {
8357
+ account: { email: (account == null ? void 0 : account.email) || null },
8358
+ connected: true,
8359
+ organizations,
8360
+ plan,
8361
+ unavailableProducts: (facet.items || []).map((product) => ({
8362
+ id: product.id,
8363
+ title: product.title || "Untitled product"
8364
+ })),
8365
+ // The total can exceed the 25 listed above, and has to.
8366
+ unavailableProductsTotal: ((_a = (facet.total || [])[0]) == null ? void 0 : _a.count) || 0
8367
+ }
8368
+ };
8369
+ },
8370
+ // DISCONNECT ONE ORGANIZATION. The connection is deleted and nothing
8371
+ // else: every dependent — products, ads, steps, workflows, and the org's
8372
+ // own connection refs — is torn down by drawbridge-sync's connection
8373
+ // change stream. The shared token and the other orgs are untouched.
8374
+ remove: async ({ context }, { read } = {}) => {
8375
+ const organization2 = context == null ? void 0 : context.organization;
8376
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8377
+ if (!shop) throw refusal("shop is required", 400);
8378
+ if (!organization2) throw refusal("organization is required", 400);
8379
+ const record = await read.get({ collection: "shop", query: { shop } });
8380
+ if (!(record == null ? void 0 : record.user)) throw refusal("Account is not connected for this store", 409);
8381
+ const owned = await merchantOrganizations({ read, user: record.user });
8382
+ if (!(owned || []).some((entry) => entry.id === organization2)) {
8383
+ throw refusal("No access to this organization", 403);
8384
+ }
8385
+ const connection2 = await read.get({
8386
+ collection: "connection",
8387
+ query: { organization: organization2, shop, slug: "shopify" }
8388
+ });
8389
+ if (!connection2) throw refusal("No connection to remove", 404);
8390
+ return {
8391
+ message: "Disconnected.",
8392
+ request: { organization: organization2, shop },
8393
+ result: { ok: true },
8394
+ writes: [{ collection: "connection", operation: "delete", query: { id: connection2.id } }]
8395
+ };
8396
+ }
8397
+ },
8398
+ plan: {
8399
+ // RELEASE EVERY ACTIVE APPROVAL. The App Home then re-checks the plan
8400
+ // and falls back to "Choose a plan".
8401
+ cancel: ({ context }, { read, shopify = client } = {}) => releaseApprovals({ context, read, shopify }),
8402
+ // ONE ATTRIBUTED ORDER'S USAGE CHARGE. Enqueued per conversion by the
8403
+ // order step and run on a retrying queue, so this may be called
8404
+ // several times for one order — which is safe because the idempotency
8405
+ // key is PERMANENT for billing events and Shopify settles the repeat.
8406
+ //
8407
+ // THE HANDLE IS CHECKED AGAINST THE MANIFEST'S OWN DECLARATION, which
8408
+ // is a real strengthening of what it replaced: drawbridge-sync compared
8409
+ // the job's `handle` against the job's `transaction` — two fields from
8410
+ // the same enqueuer, so a drifted enqueuer agreed with itself. The
8411
+ // handle is the one string that decides whether the event bills at all,
8412
+ // and this is the file that publishes it.
8413
+ //
8414
+ // REFUSE BEFORE SENDING, because sending burns the order's PERMANENT
8415
+ // idempotency key on an event that misclassifies or mistraces. The
8416
+ // throw rides the queue's normal retry path and the abandoned-job alert
8417
+ // pages on exhaustion.
8418
+ //
8419
+ // DELIBERATELY NO TIMESTAMP. sendAppEvent defaults to the SEND time,
8420
+ // which is always inside the merchant's current billing cycle at the
8421
+ // moment of sending and so can never hit PERIOD_CLOSED. Pinning the
8422
+ // purchase time reads more correct and is strictly worse: a retry
8423
+ // backoff crossing a cycle boundary would carry a closed-cycle
8424
+ // timestamp, Shopify would 202-accept, silently drop it, and the
8425
+ // commission would be lost. Send-time's worst case is benign — the
8426
+ // charge lands in the next cycle, but it lands.
8427
+ charge: async ({ clientId, clientSecret, context, manifest }, { shopify = client } = {}) => {
8428
+ const { idempotencyKey, order, orderId, rate, revision, shopId, timestamp, transaction, value } = context || {};
8429
+ const handle = (context == null ? void 0 : context.handle) || manifest.auth.install.billing.handle;
8430
+ if (!transaction || !String(transaction).startsWith(handle + ".")) {
8431
+ throw new Error("shopify.usage.billing.handle.mismatch on order " + orderId + ": transaction " + (transaction || "null") + " does not carry handle " + handle + " \u2014 refusing to send");
8432
+ }
8433
+ await shopify.billing.sendAppEvent({
8434
+ clientId,
8435
+ clientSecret,
8436
+ eventHandle: handle,
8437
+ idempotencyKey,
8438
+ // The Shopify-side event record names the order that produced it.
8439
+ reference: transaction,
8440
+ // OPERATOR-ONLY, BOTH OF THEM, and absent on every automatic
8441
+ // send. `revision` suffixes the idempotency key, which is what
8442
+ // makes a second attempt possible once a key has been consumed;
8443
+ // the encoding is owned by sendAppEvent so no caller builds keys
8444
+ // itself. `timestamp` pins the PURCHASE time, which the automatic
8445
+ // path must never do — see the note above — and the recovery
8446
+ // migration must, because it is resending orders from a closed
8447
+ // window and bounds its own run to the merchant's current cycle.
8448
+ ...revision && { revision },
8449
+ ...timestamp && { timestamp },
8450
+ shopId,
8451
+ value
8452
+ });
8453
+ return {
8454
+ message: "Usage charge sent for order " + orderId + ".",
8455
+ request: { order: order || null, orderId: orderId || null, shopId: shopId || null, value },
8456
+ result: { transaction: String(transaction) },
8457
+ // TRACEABILITY. The App Events API returns no event id, so the
8458
+ // trace key into Shopify's event logs is the transaction id the
8459
+ // commerce.order hook minted and this sent as `reference`.
8460
+ // `amount` is the per-order usage value in cents, mirroring the
8461
+ // Stripe path's marker.
8462
+ ...order && { writes: [{
8463
+ collection: "order",
8464
+ data: {
8465
+ $set: {
8466
+ billed: {
8467
+ amount: value,
8468
+ date: /* @__PURE__ */ new Date(),
8469
+ rate: rate || 0,
8470
+ transaction: String(transaction)
8471
+ }
8472
+ }
8473
+ },
8474
+ operation: "update",
8475
+ query: { id: order }
8476
+ }] }
8477
+ };
8478
+ },
8479
+ // RESELECT, NOT CANCEL. The same mechanics — the current approval has to
8480
+ // be released before the pricing page will offer the plan again — but
8481
+ // the intent is a thirty-second round trip rather than a departure.
8482
+ //
8483
+ // `mark` IS A DECLARED CAPABILITY, and this is the only slot here that
8484
+ // needs one. The marker has to be persisted BEFORE the approval is
8485
+ // released: it is what tells sync's CANCELLED handler to hold the pause
8486
+ // — no connection error, no owner email — and start a timed recheck that
8487
+ // pauses honestly if the merchant abandons. A described write lands
8488
+ // after the hook returns, which is after the cancel, and a marker
8489
+ // written then can race the very webhook it exists to soften. Same
8490
+ // precedent as `resolveContact`: the one write a description cannot
8491
+ // carry.
8492
+ reselect: async ({ context }, { mark, read, shopify = client } = {}) => {
8493
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8494
+ if (!shop) throw refusal("shop is required", 400);
8495
+ await mark({ shop });
8496
+ return releaseApprovals({ context, read, shopify });
8497
+ },
8498
+ // IS THIS STORE'S ORDER BILLING ACTUALLY METERED? Not a merchant
8499
+ // action — the other two slots here are — but the same subject, and
8500
+ // the reason it is a declared hook rather than a helper is that the
8501
+ // answer was being derived in two places: `lifecycle.health` below,
8502
+ // and drawbridge-sync's app_subscriptions/update handler, whose copy
8503
+ // stated in its own comment that it matched this one and did not.
8504
+ //
8505
+ // THREE ANSWERS, and the caller must keep them apart:
8506
+ //
8507
+ // a string PROVEN. The charge id or usage line id, stamped on
8508
+ // the connection as the evidence.
8509
+ // null PROBED, and nothing is accruing.
8510
+ // undefined NO VERDICT — the probe could not run. `probed` says
8511
+ // which, because undefined does not survive JSON.
8512
+ verify: async ({ context }, { adminToken, read, shopify = client } = {}) => {
8513
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8514
+ if (!shop) throw refusal("shop is required", 400);
8515
+ const adminAccessToken = await adminToken();
8516
+ if (!adminAccessToken) {
8517
+ return { message: "No admin token for this store \u2014 no verdict.", request: { shop }, result: { metered: null, probed: false }, skipped: true };
8518
+ }
8519
+ const partnerRow = (read == null ? void 0 : read.get) ? await read.get({ collection: "provider", query: { slug: "shopify" } }) : null;
8520
+ const partner = (partnerRow == null ? void 0 : partnerRow.settings) ? decrypt(partnerRow.settings) : {};
8521
+ const { ledger, metered } = await meterVerdict({
8522
+ adminAccessToken,
8523
+ ledgerFloor: new Date(Date.now() - LEDGER_WINDOW_MS),
8524
+ partner,
8525
+ shop,
8526
+ shopId: (context == null ? void 0 : context.shopId) || null,
8527
+ shopify
8528
+ });
8529
+ return {
8530
+ message: typeof metered === "string" ? "Billing is metered." : "No meter evidence for this store.",
8531
+ request: { shop },
8532
+ // `probed` is the LEDGER, not the call: a store whose Partner
8533
+ // credentials are absent was not asked, and reporting that as
8534
+ // "probed, nothing accruing" would stamp an unmetered verdict on
8535
+ // a store nobody looked at.
8536
+ result: { metered: metered ?? null, probed: ledger || typeof metered === "string" }
8537
+ };
8538
+ }
8539
+ },
8540
+ // THE EMBEDDED APP'S SESSION STORE. The @shopify/shopify-app library
8541
+ // persists the offline session on token exchange and refresh; it lives
8542
+ // encrypted on the shared `shop` record, which is the same row every
8543
+ // organization's connection to this store points at.
8544
+ session: {
8545
+ // SOFT-CLEAR, NEVER A DELETE. The library calls this on session
8546
+ // invalidation and not only on uninstall, so hard-deleting the record
8547
+ // would orphan every org connection pointing at it — token resolution
8548
+ // silently nulls — and destroy the durable account link and the
8549
+ // storefront token with it. The next embedded load re-runs token
8550
+ // exchange. The full record delete belongs to the uninstall webhook.
8551
+ clear: async ({ context }) => {
8552
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8553
+ if (!shop) throw refusal("shop is required", 400);
8554
+ return {
8555
+ message: "Session cleared.",
8556
+ request: { shop },
8557
+ result: { ok: true },
8558
+ writes: [{
8559
+ collection: "shop",
8560
+ data: { $set: { settings: null } },
8561
+ operation: "update",
8562
+ query: { shop }
8563
+ }]
8564
+ };
8565
+ },
8566
+ read: async ({ context }, { read } = {}) => {
8567
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8568
+ if (!shop) throw refusal("shop is required", 400);
8569
+ const record = await read.get({ collection: "shop", query: { shop } });
8570
+ if (!(record == null ? void 0 : record.settings)) throw refusal("No session for this store", 404);
8571
+ return {
8572
+ message: "Session read.",
8573
+ request: { shop },
8574
+ result: { session: decrypt(record.settings) }
8575
+ };
8576
+ },
8577
+ save: async ({ context }) => {
8578
+ const session = context == null ? void 0 : context.session;
8579
+ const shop = sanitizeDomain(session == null ? void 0 : session.shop);
8580
+ if (!shop || !(session == null ? void 0 : session.accessToken)) throw refusal("session.shop and session.accessToken are required", 400);
8581
+ return {
8582
+ message: "Session saved.",
8583
+ request: { shop },
8584
+ result: { ok: true },
8585
+ writes: [{
8586
+ collection: "shop",
8587
+ data: {
8588
+ $set: { settings: encrypt(session), shop },
8589
+ $setOnInsert: { status: "pending" }
8590
+ },
8591
+ operation: "update",
8592
+ options: { upsert: true },
8593
+ query: { shop }
8594
+ }]
8595
+ };
8596
+ }
8597
+ },
8598
+ // THE LINK-TOKEN HANDOFF. The breakout callback runs top-level and can set
8599
+ // a first-party cookie; the embedded App Home cannot read that cookie from
8600
+ // inside the Shopify admin iframe. So the callback stashes the merchant's
8601
+ // user token here keyed by shop, and App Home reads it once and clears it.
8602
+ //
8603
+ // DURABLE RATHER THAN IN REDIS: a restart must not strand a merchant
8604
+ // mid-handoff. Short-lived and encrypted.
8605
+ token: {
8606
+ clear: async ({ context }) => {
8607
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8608
+ if (!shop) throw refusal("shop is required", 400);
8609
+ return {
8610
+ message: "Link token cleared.",
8611
+ request: { shop },
8612
+ result: { ok: true },
8613
+ writes: [{
8614
+ collection: "shop",
8615
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null } },
8616
+ operation: "update",
8617
+ query: { shop }
8618
+ }]
8619
+ };
8620
+ },
8621
+ read: async ({ context }, { read } = {}) => {
8622
+ var _a;
8623
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8624
+ if (!shop) throw refusal("shop is required", 400);
8625
+ const record = await read.get({ collection: "shop", query: { shop } });
8626
+ const expiresAt = (record == null ? void 0 : record.linkTokenExpiresAt) ? new Date(record.linkTokenExpiresAt) : null;
8627
+ if (!(record == null ? void 0 : record.linkToken) || !expiresAt || expiresAt <= /* @__PURE__ */ new Date()) {
8628
+ throw refusal("No link token for this store", 404);
8629
+ }
8630
+ return {
8631
+ message: "Link token read.",
8632
+ request: { shop },
8633
+ result: { token: ((_a = decrypt(record.linkToken)) == null ? void 0 : _a.token) ?? null }
8634
+ };
8635
+ },
8636
+ save: async ({ context }) => {
8637
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8638
+ const token = context == null ? void 0 : context.token;
8639
+ if (!shop || !token) throw refusal("shop and token are required", 400);
8640
+ return {
8641
+ message: "Link token saved.",
8642
+ request: { shop },
8643
+ result: { ok: true },
8644
+ writes: [{
8645
+ collection: "shop",
8646
+ data: {
8647
+ $set: {
8648
+ linkToken: encrypt({ token }),
8649
+ linkTokenExpiresAt: new Date(Date.now() + LINK_TOKEN_TTL_MS)
8650
+ }
8651
+ },
8652
+ operation: "update",
8653
+ query: { shop }
8654
+ }]
8655
+ };
8656
+ }
8657
+ }
8658
+ },
5933
8659
  // Drawbridge sends its own notification email and SMS — see the private
5934
8660
  // `drawbridge` manifest. A vendor answering these would be a second sender,
5935
8661
  // which is the arrangement the platform sender replaced.
@@ -5991,8 +8717,8 @@ var shopify_default2 = {
5991
8717
  // access token still works, reconciles the scopes the store granted
5992
8718
  // against the ones the app now needs, and queues a webhook
5993
8719
  // reconciliation.
5994
- health: async ({ connection: connection2, workflow }, { adminToken, logger: logger2, read, reconcileScopes, resolveSettings, rotateToken, shopify } = {}) => {
5995
- var _a, _b, _c, _d, _e, _f;
8720
+ health: async ({ connection: connection2, workflow }, { adminToken, logger: logger2, read, reconcileScopes, resolveSettings, rotateToken, shopify = client } = {}) => {
8721
+ var _a, _b, _c, _d;
5996
8722
  const request2 = {
5997
8723
  connectionId: workflow.connection,
5998
8724
  organizationId: workflow.organization,
@@ -6029,33 +8755,26 @@ var shopify_default2 = {
6029
8755
  shopCurrency = String(shopData.currency || "").toLowerCase() || null;
6030
8756
  sourceRepaired = true;
6031
8757
  }
6032
- const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
6033
- adminAccessToken,
6034
- domain: connection2.shop
6035
- });
6036
- const usageLine = (_a = subscriptions.find((subscription) => subscription.usageLineItemId)) == null ? void 0 : _a.usageLineItemId;
6037
- if (usageLine) metered = usageLine;
6038
8758
  const partnerRow = (read == null ? void 0 : read.get) ? await read.get({ collection: "provider", query: { slug: "shopify" } }) : null;
6039
8759
  const partner = (partnerRow == null ? void 0 : partnerRow.settings) ? decrypt(partnerRow.settings) : {};
6040
- if (partner.partnerToken && partner.partnerOrgId && partner.partnerAppId && (source == null ? void 0 : source.id) && ((_b = shopify.partner) == null ? void 0 : _b.getUsageChargeEvents)) {
6041
- const ledgerFloor = new Date(Date.now() - 30 * 24 * 60 * 60 * 1e3);
6042
- const accruals = await shopify.partner.getUsageChargeEvents({
6043
- appId: "gid://shopify/App/" + partner.partnerAppId,
6044
- first: 10,
6045
- occurredAtMin: ledgerFloor.toISOString(),
6046
- organizationId: partner.partnerOrgId,
6047
- partnerToken: partner.partnerToken,
6048
- shopId: "gid://shopify/Shop/" + source.id
6049
- });
6050
- const boundaries = accruals.filter((event) => event.occurredAt).sort((a, b) => new Date(a.occurredAt) - new Date(b.occurredAt));
6051
- const accrued = [...boundaries].reverse().find((event) => Number(event.usageQuantity) > 0);
6052
- if (accrued) metered = String(accrued.chargeId || accrued.id);
6053
- const stampedAt = (_c = boundaries.find(
8760
+ const ledgerFloor = new Date(Date.now() - LEDGER_WINDOW_MS);
8761
+ const verdict = await meterVerdict({
8762
+ adminAccessToken,
8763
+ ledgerFloor,
8764
+ partner,
8765
+ shop: connection2.shop,
8766
+ shopId: source == null ? void 0 : source.id,
8767
+ shopify
8768
+ });
8769
+ if (verdict.metered !== void 0) metered = verdict.metered;
8770
+ const { boundaries } = verdict;
8771
+ if (boundaries.length) {
8772
+ const stampedAt = (_a = boundaries.find(
6054
8773
  (event) => {
6055
8774
  var _a2;
6056
8775
  return String(event.chargeId || event.id) === String(((_a2 = connection2.source) == null ? void 0 : _a2.metered) || "");
6057
8776
  }
6058
- )) == null ? void 0 : _c.occurredAt;
8777
+ )) == null ? void 0 : _a.occurredAt;
6059
8778
  reconciliation = [];
6060
8779
  let windowStart = ledgerFloor;
6061
8780
  for (const boundary of boundaries) {
@@ -6105,7 +8824,7 @@ var shopify_default2 = {
6105
8824
  }
6106
8825
  });
6107
8826
  } else {
6108
- (_d = logger2 == null ? void 0 : logger2.error) == null ? void 0 : _d.call(logger2, new Error(
8827
+ (_b = logger2 == null ? void 0 : logger2.error) == null ? void 0 : _b.call(logger2, new Error(
6109
8828
  "shopify.usage.reconciliation.mismatch on shop " + connection2.shop + ": charge " + charge + " charged " + charged + " cents but its window holds " + billed + " cents across " + orders.length + " billed orders \u2014 each cent of difference is commission that never charged"
6110
8829
  ), {
6111
8830
  extra: {
@@ -6124,13 +8843,13 @@ var shopify_default2 = {
6124
8843
  }
6125
8844
  } catch (probeError) {
6126
8845
  billingProbeFailed = true;
6127
- (_e = logger2 == null ? void 0 : logger2.warn) == null ? void 0 : _e.call(logger2, "shopify.health.billing.probe.failed", {
8846
+ (_c = logger2 == null ? void 0 : logger2.warn) == null ? void 0 : _c.call(logger2, "shopify.health.billing.probe.failed", {
6128
8847
  connectionId: connection2.id,
6129
8848
  message: probeError == null ? void 0 : probeError.message,
6130
8849
  shop: connection2.shop
6131
8850
  });
6132
8851
  }
6133
- if (sourceRepaired || metered !== void 0 && metered !== (((_f = connection2.source) == null ? void 0 : _f.metered) ?? void 0)) {
8852
+ if (sourceRepaired || metered !== void 0 && metered !== (((_d = connection2.source) == null ? void 0 : _d.metered) ?? void 0)) {
6134
8853
  writes.push({
6135
8854
  collection: "connection",
6136
8855
  data: {
@@ -6265,13 +8984,13 @@ var shopify_default2 = {
6265
8984
  // They are the same two questions every other vendor answers through
6266
8985
  // resources.*, so they answer them the same way now.
6267
8986
  //
6268
- // `shopify` is INJECTED: this package cannot import @drawbridge/shopify,
8987
+ // `shopify` DEFAULTS to the client this file imports; nothing injects it,
6269
8988
  // which depends on it. What arrives is the SDK's pure HTTP namespaces
6270
8989
  // and nothing else — no controller, no collection access. Resolving the
6271
8990
  // credential is the caller's job because it is Drawbridge's job: the
6272
8991
  // admin token refreshes and writes itself back, which is service work,
6273
8992
  // not vendor work.
6274
- products: async ({ cursor, limit = 100, search, settings, sort }, { shopify } = {}) => {
8993
+ products: async ({ cursor, limit = 100, search, settings, sort }, { shopify = client } = {}) => {
6275
8994
  var _a, _b, _c, _d;
6276
8995
  const products = await shopify.storefront.getProducts({
6277
8996
  cursor,
@@ -6293,7 +9012,7 @@ var shopify_default2 = {
6293
9012
  }
6294
9013
  };
6295
9014
  },
6296
- promotions: async ({ cursor, limit = 100, search, settings }, { shopify } = {}) => {
9015
+ promotions: async ({ cursor, limit = 100, search, settings }, { shopify = client } = {}) => {
6297
9016
  var _a, _b;
6298
9017
  const discounts = await shopify.admin.getDiscounts({
6299
9018
  adminAccessToken: settings == null ? void 0 : settings.adminAccessToken,
@@ -6580,7 +9299,7 @@ var shopify_default2 = {
6580
9299
  };
6581
9300
 
6582
9301
  // lib/connections/manifests/webhook.js
6583
- import crypto2 from "crypto";
9302
+ import crypto3 from "crypto";
6584
9303
 
6585
9304
  // lib/safe-http.js
6586
9305
  import dns2 from "dns";
@@ -6753,7 +9472,7 @@ var signature = ({ body, settings }) => {
6753
9472
  return [
6754
9473
  "t=" + timestamp,
6755
9474
  ...[settings.secret, ...previous].map(
6756
- (secret) => "v1=" + crypto2.createHmac(generated.algorithm, secret).update(payload).digest(generated.encoding)
9475
+ (secret) => "v1=" + crypto3.createHmac(generated.algorithm, secret).update(payload).digest(generated.encoding)
6757
9476
  )
6758
9477
  ].join(",");
6759
9478
  };
@@ -6798,14 +9517,15 @@ var webhook_default = {
6798
9517
  "Drawbridge can POST event payloads to your endpoint as activity happens in your account, so your own systems can react to it.",
6799
9518
  "Generate a signing secret and Drawbridge signs every request with it. Your endpoint recomputes the signature to confirm each payload genuinely came from Drawbridge before acting on it."
6800
9519
  ],
6801
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
6802
- // The dashboard already carries generic reasons for every way an
6803
- // authorization can fail declined, expired state, a vendor we are not set
6804
- // up for and a sentence here is an ADDITION to those, for a vendor whose
6805
- // failures need saying differently. This one's do not.
9520
+ // THERE IS NO CONSENT SCREEN TO FAIL. Connecting mints a signing secret;
9521
+ // nothing is authorized against a third party, so neither `denied` nor
9522
+ // `invalid` has a state it could describe. The failures this connection
9523
+ // really has are at DELIVERY a merchant's endpoint refusing a POST and
9524
+ // those reach them through the connection's own errors rather than through
9525
+ // connect copy.
6806
9526
  //
6807
- // Answered rather than omitted, because `errors` existed on two of six
6808
- // manifests and there was no way to tell "nothing to add" from "nobody
9527
+ // `false` is the recorded decision, not silence: `errors` existed on two of
9528
+ // six manifests and there was no way to tell "nothing to add" from "nobody
6809
9529
  // wrote it".
6810
9530
  errors: false,
6811
9531
  excerpt: "Sign outgoing webhook payloads with an HMAC secret to verify authenticity.",