@drawbridge/drawbridge-utils 0.0.176 → 0.0.178

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 +3391 -271
  8. package/dist/connections/index.d.cts +13 -4
  9. package/dist/connections/index.d.ts +13 -4
  10. package/dist/connections/index.js +3388 -270
  11. package/dist/features.cjs +3080 -241
  12. package/dist/features.d.cts +13 -4
  13. package/dist/features.d.ts +13 -4
  14. package/dist/features.js +3120 -275
  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-qY18QITf.d.cts → index-C2rxasGZ.d.cts} +2670 -354
  20. package/dist/{index-B8JhYfvU.d.ts → index-DOYCXtd7.d.ts} +2670 -354
  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 +3079 -240
  28. package/dist/plans.d.cts +13 -4
  29. package/dist/plans.d.ts +13 -4
  30. package/dist/plans.js +3120 -275
  31. package/dist/pricing.cjs +3112 -273
  32. package/dist/pricing.d.cts +13 -4
  33. package/dist/pricing.d.ts +13 -4
  34. package/dist/pricing.js +3117 -272
  35. package/dist/providers.cjs +3082 -262
  36. package/dist/providers.d.cts +12 -3
  37. package/dist/providers.d.ts +12 -3
  38. package/dist/providers.js +3086 -260
  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
@@ -173,6 +173,10 @@ var HOOKS = Object.freeze({
173
173
  "code",
174
174
  // Create the buyer at the vendor, so an order can be attributed to them.
175
175
  "customer",
176
+ // HOW MANY OF THIS PRODUCT ARE LEFT, at the vendor. Read at the moment a
177
+ // campaign's product list is rendered rather than stored, because stock is
178
+ // the one product fact that is stale the instant it is written down.
179
+ "inventory",
176
180
  // An order arrived at the vendor: attribute it, record it, update totals.
177
181
  "order",
178
182
  // Pull product data across on a vendor update.
@@ -240,7 +244,19 @@ var HOOKS = Object.freeze({
240
244
  organizations: Object.freeze(["add", "list", "remove"]),
241
245
  // What the merchant pays the VENDOR. Pairs with auth.install.billing, which
242
246
  // declares the plan they are being charged on.
243
- plan: Object.freeze(["cancel", "reselect"]),
247
+ //
248
+ // `verify` is the odd one of the three: not something a merchant does, but
249
+ // the question "is this store's billing actually metered right now". It is
250
+ // here because it is the same subject — and because the answer was being
251
+ // derived in TWO places, the vendor's health check and drawbridge-sync's
252
+ // approval webhook, whose copy said in its own comment that it matched the
253
+ // other and did not.
254
+ // `charge` and `verify` are the two that are not merchant actions: one
255
+ // sends a usage charge to the vendor's meter, the other asks whether that
256
+ // meter is actually working. Both are here because both are the same
257
+ // subject — what the merchant pays the vendor — and both were being done
258
+ // from drawbridge-sync with a direct import of the vendor's client.
259
+ plan: Object.freeze(["cancel", "charge", "reselect", "verify"]),
244
260
  // The embedded app's own session, stored by us on the vendor's behalf.
245
261
  session: Object.freeze(["clear", "read", "save"]),
246
262
  // The one-time code that hands a merchant from the embedded app into
@@ -325,7 +341,7 @@ var ANSWER_KEYS = Object.freeze([
325
341
  "usage"
326
342
  ].sort());
327
343
  var WRITE_OPERATIONS = Object.freeze(["create", "delete", "update"]);
328
- var INSTALL_SIGNATURE = Object.freeze({ options: ["read", "request"], props: ["context"] });
344
+ var INSTALL_SIGNATURE = Object.freeze({ options: ["read"], props: ["context"] });
329
345
  var LIFECYCLE_SIGNATURE = Object.freeze({ options: ["dispatch"], props: ["context"] });
330
346
  var RESOURCE_SIGNATURE = Object.freeze({
331
347
  options: ["fetcher", "shopify"],
@@ -342,15 +358,30 @@ var HOOK_SLOT_PROPS = Object.freeze({
342
358
  // the second bag would be silently discarded, which is exactly the
343
359
  // stubbed-fetcher-reaches-production failure the split exists to prevent.
344
360
  "auth.token": false,
345
- // COMMERCE. `cart` is declared and unimplemented the Checkout Kit path in
346
- // api/route/subdomain.js writes nothing, which is why it never became a hook
347
- // so its signature mirrors `code`, its nearest sibling, and moving the
348
- // route here is a deliberate widening of this line rather than a silent one.
349
- "commerce.cart": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context", "step"] }),
361
+ // COMMERCE. `cart` is the odd one: it runs for a SHOPPER on a public page,
362
+ // not for an organization inside a workflow, so it takes no `connection` and
363
+ // no `step`. It reads the storefront with the store's own storefront token
364
+ // and mints a checkout token from DRAWBRIDGE'S app credentials, which is why
365
+ // `clientId`/`clientSecret` are here as props, the way auth.disconnect
366
+ // already carries them, because a credential is a fact of the run rather
367
+ // than a service.
368
+ "commerce.cart": Object.freeze({
369
+ options: ["fetcher", "shopify"],
370
+ props: ["clientId", "clientSecret", "context", "settings"]
371
+ }),
350
372
  "commerce.code": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context", "step"] }),
351
373
  "commerce.customer": Object.freeze({ options: ["adminToken", "read", "shopify"], props: ["connection", "context"] }),
374
+ "commerce.inventory": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context"] }),
352
375
  "commerce.order": Object.freeze({ options: ["conversionRate", "logger", "mintId", "read"], props: ["connection", "context"] }),
353
- "commerce.product": Object.freeze({ options: ["mintId", "read"], props: ["connection", "context", "workflow"] }),
376
+ // THREE OPERATIONS, one slot — record, sync, variants. `settings` and
377
+ // `adminToken` arrived with the pull half: the storefront read needs the
378
+ // store's storefront token and the product-feedback send needs its admin one,
379
+ // and both are resolved by the caller because minting either needs a
380
+ // controller.
381
+ "commerce.product": Object.freeze({
382
+ options: ["adminToken", "mintId", "read", "shopify"],
383
+ props: ["connection", "context", "settings", "workflow"]
384
+ }),
354
385
  // THE ADDRESS IS `contact` IN BOTH, and the shell already says why: it is the
355
386
  // person, not the lead document. `remove` called it `email` and `sync` called
356
387
  // it `doc` on one vendor and `lead` on three — three names for two facts.
@@ -363,19 +394,58 @@ var HOOK_SLOT_PROPS = Object.freeze({
363
394
  "inbound.process": Object.freeze({ options: ["dispatch"], props: ["context"] }),
364
395
  "inbound.receive": Object.freeze({ options: [], props: ["channel", "event", "headers", "payload"] }),
365
396
  "inbound.verify": Object.freeze({ options: [], props: ["body", "channel", "headers", "secret", "url"] }),
366
- // INSTALL — thirteen slots, none implemented yet. They are what the thirteen
367
- // routes in api/route/shopify-embedded.js become, and the signature is
368
- // deliberately narrow: `context` is the request's own body, `read` and
369
- // `request` are the only services an install surface has been shown to need.
370
- // A route that cannot be expressed inside this line is a finding to bring
371
- // back here, not a name to add at the call site.
397
+ // INSTALL — thirteen slots, and they are the thirteen routes that used to be
398
+ // api/route/shopify-embedded.js. `context` is the request's own body in all
399
+ // of them; the options are where they differ, and every difference below was
400
+ // forced by a line in those routes rather than chosen.
401
+ //
402
+ // SEVEN NEED NOTHING BUT `read`. The two session slots that write, the two
403
+ // token slots that write, the two clears, and both account slots answer from
404
+ // the shared install record alone.
405
+ //
406
+ // SIX TAKE MORE, and the widenings are worth naming because each is a fact
407
+ // Drawbridge owns that the manifest must not:
408
+ //
409
+ // conversionRate, planTitle what Drawbridge charges this organization.
410
+ // The org list renders both, and importing the
411
+ // plan catalogue here is the cycle
412
+ // features -> connections -> shopify -> plans
413
+ // -> features that was just broken.
414
+ // currencies which settlement currencies Drawbridge can
415
+ // bill. A store outside them fails the
416
+ // connection validator INSIDE the transaction,
417
+ // which surfaces as an opaque 500, so `add`
418
+ // checks first and says so.
419
+ // mintId the connection's id, known before the write
420
+ // that creates it, because the organization's
421
+ // own refs have to name it in the same
422
+ // transaction.
423
+ // shopify the vendor. Four slots call the store: two
424
+ // read the live plan, two release it.
425
+ // mark THE ONE WRITE A DESCRIPTION CANNOT CARRY, and
426
+ // `reselect` is the only slot with one. See its
427
+ // implementation for why the order is the point.
372
428
  "install.account.link": INSTALL_SIGNATURE,
373
429
  "install.account.unlink": INSTALL_SIGNATURE,
374
- "install.organizations.add": INSTALL_SIGNATURE,
375
- "install.organizations.list": INSTALL_SIGNATURE,
430
+ "install.organizations.add": Object.freeze({
431
+ options: ["currencies", "mintId", "read", "shopify"],
432
+ props: ["context"]
433
+ }),
434
+ "install.organizations.list": Object.freeze({
435
+ options: ["conversionRate", "planTitle", "read", "shopify"],
436
+ props: ["context"]
437
+ }),
376
438
  "install.organizations.remove": INSTALL_SIGNATURE,
377
- "install.plan.cancel": INSTALL_SIGNATURE,
378
- "install.plan.reselect": INSTALL_SIGNATURE,
439
+ "install.plan.cancel": Object.freeze({ options: ["read", "shopify"], props: ["context"] }),
440
+ // `manifest` because the handle this charge bills under is the vendor's own
441
+ // declaration (auth.install.billing.handle), and checking the job against the
442
+ // declaration is what the enqueuer-checks-itself version could not do.
443
+ "install.plan.charge": Object.freeze({
444
+ options: ["shopify"],
445
+ props: ["clientId", "clientSecret", "context", "manifest"]
446
+ }),
447
+ "install.plan.reselect": Object.freeze({ options: ["mark", "read", "shopify"], props: ["context"] }),
448
+ "install.plan.verify": Object.freeze({ options: ["adminToken", "read", "shopify"], props: ["context"] }),
379
449
  "install.session.clear": INSTALL_SIGNATURE,
380
450
  "install.session.read": INSTALL_SIGNATURE,
381
451
  "install.session.save": INSTALL_SIGNATURE,
@@ -426,6 +496,16 @@ var TRIGGERS = Object.freeze({
426
496
  "range.ended": Object.freeze({ event: "range.ended", type: "range" }),
427
497
  "range.started": Object.freeze({ event: "range.started", type: "range" }),
428
498
  "schedule.day": Object.freeze({ event: "day", type: "schedule" }),
499
+ // THE THREE SHOPIFY TRIGGERS, which were never in this vocabulary because the
500
+ // four workflows they fire were hand-written in drawbridge-sync's register job
501
+ // rather than provisioned from the manifest. `webhook` is a fourth trigger
502
+ // TYPE, and it is the honest name: these fire when the vendor calls us, which
503
+ // is neither an event Drawbridge raised nor a schedule it keeps.
504
+ "shopify.order.create": Object.freeze({ event: "shopify.order.create", type: "webhook" }),
505
+ "shopify.product.update": Object.freeze({ event: "shopify.product.update", type: "webhook" }),
506
+ // The token audit, dispatched programmatically by the register job when a
507
+ // store's grant is exchanged or rotated.
508
+ "shopify.token": Object.freeze({ event: "shopify.token", type: "event" }),
429
509
  "schedule.month": Object.freeze({ event: "month", type: "schedule" }),
430
510
  "schedule.week": Object.freeze({ event: "week", type: "schedule" }),
431
511
  "segment.contact.add": Object.freeze({ event: "segment.contact.add", type: "event" }),
@@ -478,7 +558,7 @@ var OUTCOMES = Object.freeze({
478
558
  unimplemented: "unimplemented",
479
559
  unsupported: "unsupported"
480
560
  });
481
- var STATUSES = Object.freeze(["active", "disconnected", "error", "pending"]);
561
+ var STATUSES = Object.freeze(["active", "error", "pending"]);
482
562
  var PLATFORM_CREDENTIALS = Object.freeze([
483
563
  // Seals a merchant's stored connection settings. The webhook connection is
484
564
  // gated on it because its whole credential is a secret WE mint and store, so
@@ -534,6 +614,52 @@ var ERROR_SOURCES = Object.freeze({
534
614
  "shopify.register.webhooks": true
535
615
  });
536
616
 
617
+ // lib/encrypt.js
618
+ var import_crypto2 = __toESM(require("crypto"), 1);
619
+
620
+ // lib/token.js
621
+ var import_crypto = __toESM(require("crypto"), 1);
622
+ var generate = (bytes = 32, encoding = "base64url") => {
623
+ const buf = import_crypto.default.randomBytes(bytes);
624
+ return encoding ? buf.toString(encoding) : buf;
625
+ };
626
+ var hash = (value, key) => {
627
+ if (!value) return null;
628
+ if (key) {
629
+ return import_crypto.default.createHmac("sha256", key).update(String(value)).digest("base64url");
630
+ }
631
+ return import_crypto.default.createHash("sha256").update(String(value)).digest("base64url");
632
+ };
633
+
634
+ // lib/encrypt.js
635
+ var ALGORITHM = "aes-256-gcm";
636
+ var getKey = () => Buffer.from(process.env.ENCRYPT_CONNECTION_SECRET, "hex");
637
+ var encrypt = (value) => {
638
+ const iv = generate(12, null);
639
+ const cipher = import_crypto2.default.createCipheriv(ALGORITHM, getKey(), iv);
640
+ const data = Buffer.concat([
641
+ cipher.update(JSON.stringify(value), "utf8"),
642
+ cipher.final()
643
+ ]);
644
+ const tag = cipher.getAuthTag();
645
+ return [iv, tag, data].map((b) => b.toString("hex")).join(":");
646
+ };
647
+ var decrypt = (value) => {
648
+ if (typeof value !== "string") return value;
649
+ const [ivHex, tagHex, dataHex] = value.split(":");
650
+ const decipher = import_crypto2.default.createDecipheriv(
651
+ ALGORITHM,
652
+ getKey(),
653
+ Buffer.from(ivHex, "hex")
654
+ );
655
+ decipher.setAuthTag(Buffer.from(tagHex, "hex"));
656
+ const result = Buffer.concat([
657
+ decipher.update(Buffer.from(dataHex, "hex")),
658
+ decipher.final()
659
+ ]);
660
+ return JSON.parse(result.toString("utf8"));
661
+ };
662
+
537
663
  // lib/connections/oauth.js
538
664
  var import_node_crypto = require("crypto");
539
665
  var credentials = ({ basic, clientId, clientSecret }) => basic ? {
@@ -560,10 +686,10 @@ var authToken = async ({
560
686
  const renewing = !code;
561
687
  if (renewing && !refreshToken) throw new Error("Nothing has been consented to yet, so there is no refresh token to spend");
562
688
  if (!renewing && descriptor.pkce && !verifier) throw new Error("This connection requires PKCE, so the code verifier is not optional");
563
- const client = credentials({ basic, clientId, clientSecret });
689
+ const client2 = credentials({ basic, clientId, clientSecret });
564
690
  const response = await fetcher(descriptor.endpoints.token, {
565
691
  body: new URLSearchParams({
566
- ...client.body,
692
+ ...client2.body,
567
693
  ...renewing ? { grant_type: "refresh_token", refresh_token: refreshToken } : {
568
694
  code: decodeURIComponent(String(code || "").trim()),
569
695
  grant_type: "authorization_code",
@@ -571,7 +697,7 @@ var authToken = async ({
571
697
  ...descriptor.pkce && { code_verifier: verifier }
572
698
  }
573
699
  }),
574
- headers: { "content-type": "application/x-www-form-urlencoded", ...client.headers },
700
+ headers: { "content-type": "application/x-www-form-urlencoded", ...client2.headers },
575
701
  method: "POST",
576
702
  signal: AbortSignal.timeout(15e3)
577
703
  });
@@ -966,9 +1092,18 @@ var scaffold_default = {
966
1092
  commerce: {
967
1093
  // NEW in phase 1 — the Checkout Kit cart path, which writes nothing and is
968
1094
  // the last api surface Shopify owns outside a hook.
969
- cart: async ({ connection, context }, { read } = {}) => ANSWER,
1095
+ // NO `connection` AND NO `step`: this one runs for a SHOPPER on a public
1096
+ // page, not for an organization inside a workflow. It reads the storefront
1097
+ // with the store's storefront token and mints a checkout token from
1098
+ // DRAWBRIDGE'S app credentials, which is why the credential pair rides in
1099
+ // as props — the way auth.disconnect already carries it.
1100
+ cart: async ({ clientId, clientSecret, context, settings }, { fetcher, shopify } = {}) => ANSWER,
970
1101
  code: async ({ connection, context, step }, { adminToken, shopify } = {}) => ANSWER,
971
1102
  customer: async ({ connection, context }, { adminToken, read, shopify } = {}) => ANSWER,
1103
+ // STOCK, READ AT RENDER TIME rather than stored. It is the one product
1104
+ // fact that is stale the instant it is written down, so the campaign
1105
+ // product list asks the vendor and caches the answer for a minute.
1106
+ inventory: async ({ connection, context }, { adminToken, shopify } = {}) => ANSWER,
972
1107
  order: async ({ connection, context }, { logger, mintId, read } = {}) => ANSWER,
973
1108
  // THIS IS WHERE `product.insert` LANDS.
974
1109
  //
@@ -990,7 +1125,7 @@ var scaffold_default = {
990
1125
  // nothing and shows up only as `workflow.dispatch.candidates matched : 0` in
991
1126
  // a log. Phase 1 closes it and build() checks every trigger against it.
992
1127
  product: {
993
- hook: async ({ connection, context, workflow }, { mintId, read } = {}) => ANSWER,
1128
+ hook: async ({ connection, context, settings, workflow }, { adminToken, mintId, read, shopify } = {}) => ANSWER,
994
1129
  step: () => ({
995
1130
  description: "Syncs product data from the vendor when a product changes.",
996
1131
  key: "Vendor Product Sync",
@@ -1138,8 +1273,19 @@ var scaffold_default = {
1138
1273
  // Vendor billing, the only group that is not generic. Pairs with
1139
1274
  // auth.install.billing, which declares what the merchant is being charged.
1140
1275
  plan: {
1141
- cancel: async ({ context }, { dispatch, read } = {}) => ANSWER,
1142
- reselect: async ({ context }, { dispatch, read } = {}) => ANSWER
1276
+ cancel: async ({ context }, { read, shopify } = {}) => ANSWER,
1277
+ // NOT A MERCHANT ACTION EITHER one attributed order's usage charge,
1278
+ // sent to the vendor's meter. The credential pair rides in as props
1279
+ // because the charge authenticates as the APP, not as the store.
1280
+ charge: async ({ clientId, clientSecret, context, manifest }, { shopify } = {}) => ANSWER,
1281
+ // `mark` is the one write a description cannot carry: the marker must
1282
+ // be persisted BEFORE the approval is released, and a described write
1283
+ // lands after the hook returns.
1284
+ reselect: async ({ context }, { mark, read, shopify } = {}) => ANSWER,
1285
+ // NOT A MERCHANT ACTION — the question "is this store's billing
1286
+ // actually metered right now", asked by the daily health check and by
1287
+ // the vendor's own approval webhook, which used to hand-copy it.
1288
+ verify: async ({ context }, { adminToken, read, shopify } = {}) => ANSWER
1143
1289
  },
1144
1290
  // The embedded app's own session, stored by us on the vendor's behalf.
1145
1291
  session: {
@@ -1625,16 +1771,19 @@ var attentive_default2 = {
1625
1771
  "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.",
1626
1772
  "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."
1627
1773
  ],
1628
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
1629
- // The dashboard already carries generic reasons for every way an
1630
- // authorization can fail — declined, expired state, a vendor we are not set
1631
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
1632
- // failures need saying differently. This one's do not.
1774
+ // WHAT THE MERCHANT READS WHEN A CONNECT FAILS. Two states, because the
1775
+ // consent screen has two ways to end: they said no, or something between
1776
+ // here and the vendor went wrong.
1633
1777
  //
1634
- // Answered rather than omitted, because `errors` existed on two of six
1635
- // manifests and there was no way to tell "nothing to add" from "nobody
1636
- // wrote it".
1637
- errors: false,
1778
+ // THE VENDOR IS NAMED IN BOTH. The dashboard's generic copy says "the
1779
+ // authorization"; a merchant connecting two accounts in one sitting needs
1780
+ // to know which one this was.
1781
+ errors: {
1782
+ connect: {
1783
+ denied: "The Attentive authorization was declined, so nothing was connected.",
1784
+ invalid: "We couldn't complete the Attentive connection. Try connecting again."
1785
+ }
1786
+ },
1638
1787
  excerpt: "Sync your Drawbridge contacts into an Attentive segment.",
1639
1788
  // NAMES THE SEGMENT STEP, because `status` below gates on it: a grant with
1640
1789
  // no segment chosen sits at Pending, and a guide that stops at the consent
@@ -2162,6 +2311,15 @@ var readEventHeader = ({ descriptor, headers }) => ({ result: { event: headers[d
2162
2311
  var DEFAULT_TIMEOUT_MS = 15e3;
2163
2312
  var request = async ({
2164
2313
  body,
2314
+ // THE TRANSPORT, injectable and defaulted to the real one.
2315
+ //
2316
+ // Every other vendor client in this package takes a `fetcher` — it is how
2317
+ // klaviyo, mailchimp and attentive are tested without a network, and it is a
2318
+ // declared HOOK_OPTION. The Shopify client had no seam at all, so the only way
2319
+ // to test a hook that used it was to inject the whole SDK namespace; that
2320
+ // injection existed to work around an import cycle, and when the cycle went
2321
+ // the tests lost their only hold. This is the seam they should have had.
2322
+ fetcher = fetch,
2165
2323
  headers = {},
2166
2324
  method = "GET",
2167
2325
  query,
@@ -2175,7 +2333,7 @@ var request = async ({
2175
2333
  }
2176
2334
  ;
2177
2335
  const isForm = type === "form";
2178
- const response = await fetch(fullUrl.toString(), {
2336
+ const response = await fetcher(fullUrl.toString(), {
2179
2337
  method,
2180
2338
  headers: {
2181
2339
  "Content-Type": isForm ? "application/x-www-form-urlencoded" : "application/json",
@@ -2632,15 +2790,12 @@ var drawbridge_default2 = {
2632
2790
  description: [
2633
2791
  "Drawbridge sends your notification emails and your entrants' emails, and recalculates segment membership on a schedule. It is always on and needs nothing connected."
2634
2792
  ],
2635
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
2636
- // The dashboard already carries generic reasons for every way an
2637
- // authorization can fail declined, expired state, a vendor we are not set
2638
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
2639
- // failures need saying differently. This one's do not.
2793
+ // NOTHING IS EVER CONNECTED, so no connect can fail. This is the platform's
2794
+ // own manifest always on, private, never in the catalogue — and it exists
2795
+ // to give Drawbridge's own steps a hook to point at. `denied` and `invalid`
2796
+ // describe a consent screen this connection does not have.
2640
2797
  //
2641
- // Answered rather than omitted, because `errors` existed on two of six
2642
- // manifests and there was no way to tell "nothing to add" from "nobody
2643
- // wrote it".
2798
+ // `false` is the recorded decision, not silence.
2644
2799
  errors: false,
2645
2800
  excerpt: "The steps Drawbridge runs itself.",
2646
2801
  guide: [
@@ -3400,10 +3555,10 @@ var klaviyo_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill=
3400
3555
 
3401
3556
  // lib/connections/scopes.js
3402
3557
  var list = (value) => (Array.isArray(value) ? value.flatMap((entry) => String(entry).split(/\s+/)) : String(value ?? "").split(/\s+/)).map((entry) => entry.trim()).filter(Boolean);
3403
- var missingScopes = ({ granted, required }) => {
3558
+ var missingScopes = ({ granted, required: required2 }) => {
3404
3559
  if (granted === null || granted === void 0 || granted === "") return null;
3405
3560
  const held = new Set(list(granted));
3406
- return list(required).filter((scope) => !held.has(scope));
3561
+ return list(required2).filter((scope) => !held.has(scope));
3407
3562
  };
3408
3563
 
3409
3564
  // lib/connections/manifests/klaviyo.js
@@ -4302,16 +4457,19 @@ var mailchimp_default2 = {
4302
4457
  "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.",
4303
4458
  "Someone who unsubscribed inside Mailchimp keeps that choice: a resync only sets the status of a subscriber Mailchimp has never seen before."
4304
4459
  ],
4305
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
4306
- // The dashboard already carries generic reasons for every way an
4307
- // authorization can fail — declined, expired state, a vendor we are not set
4308
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
4309
- // failures need saying differently. This one's do not.
4460
+ // WHAT THE MERCHANT READS WHEN A CONNECT FAILS. Two states, because the
4461
+ // consent screen has two ways to end: they said no, or something between
4462
+ // here and the vendor went wrong.
4310
4463
  //
4311
- // Answered rather than omitted, because `errors` existed on two of six
4312
- // manifests and there was no way to tell "nothing to add" from "nobody
4313
- // wrote it".
4314
- errors: false,
4464
+ // THE VENDOR IS NAMED IN BOTH. The dashboard's generic copy says "the
4465
+ // authorization"; a merchant connecting two accounts in one sitting needs
4466
+ // to know which one this was.
4467
+ errors: {
4468
+ connect: {
4469
+ denied: "The Mailchimp authorization was declined, so nothing was connected.",
4470
+ invalid: "We couldn't complete the Mailchimp connection. Try connecting again."
4471
+ }
4472
+ },
4315
4473
  excerpt: "Sync your Drawbridge contacts into a Mailchimp audience.",
4316
4474
  // NAMES THE AUDIENCE STEP, because `status` below gates on it: a grant with
4317
4475
  // no audience chosen sits at Pending, and a guide that stops at the consent
@@ -4410,7 +4568,7 @@ var mailchimp_default2 = {
4410
4568
  if (!audience) return { message: "No Mailchimp audience is chosen for this connection.", request: request2, skipped: true };
4411
4569
  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);
4412
4570
  if (!email) return { message: "That lead has no email address to sync.", request: request2, skipped: true };
4413
- const hash = subscriberHash(email);
4571
+ const hash2 = subscriberHash(email);
4414
4572
  const [firstName, ...restOfName] = String((lead == null ? void 0 : lead.name) || "").trim().split(/\s+/).filter(Boolean);
4415
4573
  const lastName = restOfName.join(" ");
4416
4574
  const phone = ((_e = lead == null ? void 0 : lead.phone) == null ? void 0 : _e.number) || null;
@@ -4419,7 +4577,7 @@ var mailchimp_default2 = {
4419
4577
  ...lastName && { LNAME: lastName },
4420
4578
  ...phone && { PHONE: phone }
4421
4579
  };
4422
- const member = await api3("/lists/" + audience + "/members/" + hash, {
4580
+ const member = await api3("/lists/" + audience + "/members/" + hash2, {
4423
4581
  dc: settings == null ? void 0 : settings.dc,
4424
4582
  fetcher,
4425
4583
  method: "PUT",
@@ -4460,7 +4618,7 @@ var mailchimp_default2 = {
4460
4618
  status: joined.has(entry.id) ? "active" : "inactive"
4461
4619
  }));
4462
4620
  if (tags.length > 0) {
4463
- await api3("/lists/" + audience + "/members/" + hash + "/tags", {
4621
+ await api3("/lists/" + audience + "/members/" + hash2 + "/tags", {
4464
4622
  dc: settings == null ? void 0 : settings.dc,
4465
4623
  fetcher,
4466
4624
  method: "POST",
@@ -4471,12 +4629,12 @@ var mailchimp_default2 = {
4471
4629
  }
4472
4630
  return {
4473
4631
  // Merged into `context` for later steps in this run.
4474
- context: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash },
4632
+ context: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash2 },
4475
4633
  message: suppressed ? "Synced to Mailchimp as unsubscribed \u2014 this contact has opted out." : "Synced to the Mailchimp audience.",
4476
4634
  request: request2,
4477
4635
  // Recorded on the run for support to read back, not a write
4478
4636
  // instruction — the hook has already written what it needed to.
4479
- response: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash }
4637
+ response: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash2 }
4480
4638
  };
4481
4639
  }
4482
4640
  },
@@ -4846,158 +5004,2030 @@ var shopify_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill=
4846
5004
  <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"/>
4847
5005
  </svg>`;
4848
5006
 
4849
- // lib/email.js
4850
- var GMAIL_DOMAINS = /* @__PURE__ */ new Set(["gmail.com", "googlemail.com"]);
4851
- var toCanonicalEmail = (value) => {
4852
- if (!value || typeof value !== "string") return null;
4853
- const email = value.trim().toLowerCase();
4854
- const at = email.lastIndexOf("@");
4855
- if (at < 1 || at === email.length - 1) return null;
4856
- let local = email.slice(0, at);
4857
- const domain = email.slice(at + 1);
4858
- const plus = local.indexOf("+");
4859
- if (plus > 0) local = local.slice(0, plus);
4860
- if (GMAIL_DOMAINS.has(domain)) local = local.replaceAll(".", "");
4861
- if (!local) return null;
4862
- return local + "@" + domain;
4863
- };
4864
-
4865
- // lib/encrypt.js
4866
- var import_crypto2 = __toESM(require("crypto"), 1);
5007
+ // lib/shopify/admin.js
5008
+ var admin_exports = {};
5009
+ __export(admin_exports, {
5010
+ adminFetch: () => adminFetch,
5011
+ createDiscountCode: () => createDiscountCode,
5012
+ createUsageRecord: () => createUsageRecord,
5013
+ createUsageSubscription: () => createUsageSubscription,
5014
+ getActiveAppSubscriptions: () => getActiveAppSubscriptions,
5015
+ getDiscounts: () => getDiscounts,
5016
+ getOrCreateCustomer: () => getOrCreateCustomer,
5017
+ getProductInventory: () => getProductInventory,
5018
+ sendProductResourceFeedback: () => sendProductResourceFeedback
5019
+ });
4867
5020
 
4868
- // lib/token.js
4869
- var import_crypto = __toESM(require("crypto"), 1);
4870
- var generate = (bytes = 32, encoding = "base64url") => {
4871
- const buf = import_crypto.default.randomBytes(bytes);
4872
- return encoding ? buf.toString(encoding) : buf;
4873
- };
5021
+ // lib/shopify/constants.js
5022
+ var SHOPIFY_STOREFRONT_API_VERSION = "2025-01";
5023
+ var SHOPIFY_ADMIN_API_VERSION = "2026-04";
5024
+ var SHOPIFY_APP_API_VERSION = "unstable";
5025
+ var SHOPIFY_REQUIRED_SCOPES = [
5026
+ "read_customers",
5027
+ "write_customers",
5028
+ "read_discounts",
5029
+ "write_discounts",
5030
+ "read_orders",
5031
+ "read_products",
5032
+ "read_publications",
5033
+ "write_resource_feedbacks",
5034
+ "unauthenticated_read_checkouts",
5035
+ "unauthenticated_read_product_inventory",
5036
+ "unauthenticated_read_product_listings",
5037
+ "unauthenticated_write_checkouts"
5038
+ ];
5039
+ var REFRESH_TOKEN_LIFETIME_MS = 90 * 24 * 60 * 60 * 1e3;
5040
+ var ACCESS_TOKEN_REFRESH_BUFFER_MS = 5 * 60 * 1e3;
5041
+ var PARTNER_API_VERSION = process.env.SHOPIFY_PARTNER_API_VERSION || "2026-07";
4874
5042
 
4875
- // lib/encrypt.js
4876
- var ALGORITHM = "aes-256-gcm";
4877
- var getKey = () => Buffer.from(process.env.ENCRYPT_CONNECTION_SECRET, "hex");
4878
- var encrypt = (value) => {
4879
- const iv = generate(12, null);
4880
- const cipher = import_crypto2.default.createCipheriv(ALGORITHM, getKey(), iv);
4881
- const data = Buffer.concat([
4882
- cipher.update(JSON.stringify(value), "utf8"),
4883
- cipher.final()
4884
- ]);
4885
- const tag = cipher.getAuthTag();
4886
- return [iv, tag, data].map((b) => b.toString("hex")).join(":");
5043
+ // lib/shopify/admin.js
5044
+ var adminUrl = (domain) => `https://${domain}/admin/api/${SHOPIFY_ADMIN_API_VERSION}`;
5045
+ var adminFetch = async ({ adminAccessToken, domain, fetcher, query, variables }) => {
5046
+ var _a;
5047
+ const { data, errors } = await request({
5048
+ fetcher,
5049
+ method: "POST",
5050
+ url: adminUrl(domain) + "/graphql.json",
5051
+ headers: {
5052
+ "X-Shopify-Access-Token": adminAccessToken
5053
+ },
5054
+ body: {
5055
+ query,
5056
+ ...variables && { variables }
5057
+ }
5058
+ });
5059
+ if (errors) {
5060
+ throw new Error("Shopify GraphQL error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
5061
+ }
5062
+ ;
5063
+ return data;
4887
5064
  };
4888
- var decrypt = (value) => {
4889
- if (typeof value !== "string") return value;
4890
- const [ivHex, tagHex, dataHex] = value.split(":");
4891
- const decipher = import_crypto2.default.createDecipheriv(
4892
- ALGORITHM,
4893
- getKey(),
4894
- Buffer.from(ivHex, "hex")
4895
- );
4896
- decipher.setAuthTag(Buffer.from(tagHex, "hex"));
4897
- const result = Buffer.concat([
4898
- decipher.update(Buffer.from(dataHex, "hex")),
4899
- decipher.final()
4900
- ]);
4901
- return JSON.parse(result.toString("utf8"));
5065
+ var DISCOUNT_FIELDS = `
5066
+ title
5067
+ status
5068
+ startsAt
5069
+ endsAt
5070
+ usageLimit
5071
+ asyncUsageCount
5072
+ appliesOncePerCustomer
5073
+ context { __typename }
5074
+ `;
5075
+ var discountsQuery = (search, cursor, limit) => `{
5076
+ codeDiscountNodes(first: ${limit}${search ? `, query: "title:*${search}*"` : ""}${cursor ? `, after: "${cursor}"` : ""}) {
5077
+ edges {
5078
+ node {
5079
+ id
5080
+ codeDiscount {
5081
+ ... on DiscountCodeBasic { ${DISCOUNT_FIELDS} }
5082
+ ... on DiscountCodeBxgy { ${DISCOUNT_FIELDS} }
5083
+ ... on DiscountCodeFreeShipping { ${DISCOUNT_FIELDS} }
5084
+ ... on DiscountCodeApp { ${DISCOUNT_FIELDS} }
5085
+ }
5086
+ }
5087
+ }
5088
+ pageInfo {
5089
+ endCursor
5090
+ hasNextPage
5091
+ hasPreviousPage
5092
+ startCursor
5093
+ }
5094
+ }
5095
+ }`;
5096
+ var getDiscounts = async ({ fetcher, adminAccessToken, domain, search, cursor, limit }) => {
5097
+ const data = await adminFetch({
5098
+ fetcher,
5099
+ adminAccessToken,
5100
+ domain,
5101
+ query: discountsQuery(search, cursor, limit)
5102
+ });
5103
+ return data == null ? void 0 : data.codeDiscountNodes;
4902
5104
  };
4903
-
4904
- // lib/slugify.js
4905
- var import_slugify = __toESM(require("slugify"), 1);
4906
- var slugify = (value, nochars = false) => {
4907
- const remove = nochars ? /[-?*+~.()'"!:@#^_{}\[\];,/\\]/g : /[?*+~.()'"!:@#^_{}\[\];,/\\]/g;
4908
- const replacement = nochars ? "" : "-";
4909
- return (0, import_slugify.default)(
4910
- value,
4911
- {
4912
- remove,
4913
- replacement,
4914
- lower: true,
4915
- trim: true
5105
+ var discountGid = (id) => String(id).startsWith("gid://") ? String(id) : "gid://shopify/DiscountCodeNode/" + id;
5106
+ var createDiscountCode = async ({ fetcher, adminAccessToken, domain, discountId, code }) => {
5107
+ var _a, _b, _c, _d, _e, _f, _g, _h;
5108
+ const added = await adminFetch({
5109
+ fetcher,
5110
+ adminAccessToken,
5111
+ domain,
5112
+ query: `
5113
+ mutation DiscountRedeemCodeBulkAdd($discountId: ID!, $codes: [DiscountRedeemCodeInput!]!) {
5114
+ discountRedeemCodeBulkAdd(discountId: $discountId, codes: $codes) {
5115
+ bulkCreation {
5116
+ id
5117
+ }
5118
+ userErrors {
5119
+ field
5120
+ message
5121
+ }
5122
+ }
5123
+ }
5124
+ `,
5125
+ variables: {
5126
+ codes: [{ code }],
5127
+ discountId: discountGid(discountId)
4916
5128
  }
4917
- );
4918
- };
4919
-
4920
- // lib/connections/manifests/shopify.js
4921
- var toLine = ({
4922
- price,
4923
- product_id: productId,
4924
- quantity,
4925
- title,
4926
- variant_id: variantId,
4927
- variant_title: variantTitle
4928
- }) => ({
4929
- price: parseFloat(price) || 0,
4930
- productId: productId ? "gid://shopify/Product/" + productId : null,
4931
- quantity: quantity || 1,
4932
- title: title || null,
4933
- variantId: variantId ? "gid://shopify/ProductVariant/" + variantId : null,
4934
- variantTitle: variantTitle || null
4935
- });
4936
- var attributeLineItems = (lineItems = []) => lineItems.reduce(
4937
- (acc, item) => {
4938
- const attrs = (item.properties || []).reduce(
4939
- (map, { name, value }) => {
4940
- map[name] = value;
4941
- return map;
4942
- },
4943
- {}
4944
- );
4945
- if (!attrs["_drwbrdg_ca"]) return acc;
4946
- if (!Object.keys(acc.attrMap).length) acc.attrMap = attrs;
4947
- const line = toLine(item);
4948
- acc.attributedGross += line.price * line.quantity;
4949
- acc.attributedLines.push(line);
4950
- return acc;
4951
- },
4952
- { attrMap: {}, attributedGross: 0, attributedLines: [] }
4953
- );
4954
- var generateDiscountCode = (0, import_nanoid.customAlphabet)("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8);
4955
- var blockedReason = (discount) => {
4956
- var _a;
4957
- if ((discount == null ? void 0 : discount.status) === "EXPIRED") return "This discount has expired.";
4958
- const buyers = (_a = discount == null ? void 0 : discount.context) == null ? void 0 : _a.__typename;
4959
- if (buyers && buyers !== "DiscountBuyerSelectionAll") {
4960
- 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.";
5129
+ });
5130
+ const addErrors = (_a = added == null ? void 0 : added.discountRedeemCodeBulkAdd) == null ? void 0 : _a.userErrors;
5131
+ if (addErrors == null ? void 0 : addErrors.length) {
5132
+ throw new Error("Shopify discount code create failed: " + addErrors[0].message);
4961
5133
  }
4962
5134
  ;
4963
- if (typeof (discount == null ? void 0 : discount.usageLimit) === "number" && discount.usageLimit > 0 && ((discount == null ? void 0 : discount.asyncUsageCount) || 0) >= discount.usageLimit) {
4964
- return "This discount has reached its total usage limit.";
5135
+ const bulkCreationId = (_c = (_b = added == null ? void 0 : added.discountRedeemCodeBulkAdd) == null ? void 0 : _b.bulkCreation) == null ? void 0 : _c.id;
5136
+ if (!bulkCreationId) {
5137
+ throw new Error("Shopify discount code create failed: no bulk creation id returned");
4965
5138
  }
4966
5139
  ;
4967
- return null;
5140
+ for (let attempt = 0; attempt < 15; attempt++) {
5141
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
5142
+ const polled = await adminFetch({
5143
+ fetcher,
5144
+ adminAccessToken,
5145
+ domain,
5146
+ query: `
5147
+ query DiscountRedeemCodeBulkCreationPoll($id: ID!) {
5148
+ discountRedeemCodeBulkCreation(id: $id) {
5149
+ done
5150
+ codes(first: 1) {
5151
+ nodes {
5152
+ code
5153
+ discountRedeemCode {
5154
+ id
5155
+ }
5156
+ errors {
5157
+ message
5158
+ }
5159
+ }
5160
+ }
5161
+ }
5162
+ }
5163
+ `,
5164
+ variables: {
5165
+ id: bulkCreationId
5166
+ }
5167
+ });
5168
+ const creation = polled == null ? void 0 : polled.discountRedeemCodeBulkCreation;
5169
+ if (!(creation == null ? void 0 : creation.done)) continue;
5170
+ const node = (_e = (_d = creation.codes) == null ? void 0 : _d.nodes) == null ? void 0 : _e[0];
5171
+ if (!((_f = node == null ? void 0 : node.discountRedeemCode) == null ? void 0 : _f.id)) {
5172
+ 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"));
5173
+ }
5174
+ ;
5175
+ return {
5176
+ code: node.code,
5177
+ // Numeric tail keeps the stored shopifyDiscountId in the shape the
5178
+ // legacy REST endpoint returned — it feeds a merchant-visible
5179
+ // workflow template variable, so no gid:// leakage.
5180
+ id: node.discountRedeemCode.id.split("/").pop()
5181
+ };
5182
+ }
5183
+ ;
5184
+ throw new Error("Shopify discount code create timed out waiting for bulk creation " + bulkCreationId);
4968
5185
  };
4969
- var discountWarning = (discount) => {
4970
- if ((discount == null ? void 0 : discount.status) === "SCHEDULED") {
4971
- return "This discount hasn't started yet, so codes issued before it does won't work until then.";
5186
+ var getOrCreateCustomer = async ({ fetcher, adminAccessToken, domain, email, firstName, lastName, source }) => {
5187
+ var _a, _b, _c, _d, _e, _f, _g, _h;
5188
+ const lookupQuery = `
5189
+ query customerByEmail( $query : String! ) {
5190
+ customers( first : 1, query : $query ) {
5191
+ edges {
5192
+ node {
5193
+ id
5194
+ }
5195
+ }
5196
+ }
5197
+ }
5198
+ `;
5199
+ const data = await adminFetch({
5200
+ fetcher,
5201
+ adminAccessToken,
5202
+ domain,
5203
+ query: lookupQuery,
5204
+ variables: { query: "email:" + email }
5205
+ });
5206
+ const existing = (_c = (_b = (_a = data == null ? void 0 : data.customers) == null ? void 0 : _a.edges) == null ? void 0 : _b[0]) == null ? void 0 : _c.node;
5207
+ if (existing) return existing;
5208
+ const input = { email };
5209
+ if (firstName) input.firstName = firstName;
5210
+ if (lastName) input.lastName = lastName;
5211
+ if (source) {
5212
+ input.metafields = [{
5213
+ namespace: "drwbrdg",
5214
+ key: "source",
5215
+ type: "single_line_text_field",
5216
+ value: source
5217
+ }];
4972
5218
  }
4973
5219
  ;
4974
- if (discount == null ? void 0 : discount.appliesOncePerCustomer) return "Each customer can use this discount only once.";
4975
- return null;
5220
+ const result = await adminFetch({
5221
+ fetcher,
5222
+ adminAccessToken,
5223
+ domain,
5224
+ query: `
5225
+ mutation customerCreate( $input : CustomerInput! ) {
5226
+ customerCreate( input : $input ) {
5227
+ customer {
5228
+ id
5229
+ }
5230
+ userErrors {
5231
+ field
5232
+ message
5233
+ }
5234
+ }
5235
+ }
5236
+ `,
5237
+ variables: { input }
5238
+ });
5239
+ const userErrors = (_d = result == null ? void 0 : result.customerCreate) == null ? void 0 : _d.userErrors;
5240
+ if (userErrors == null ? void 0 : userErrors.length) {
5241
+ const emailTaken = userErrors.some((e) => {
5242
+ var _a2;
5243
+ return (_a2 = e.message) == null ? void 0 : _a2.includes("Email has already been taken");
5244
+ });
5245
+ if (emailTaken) {
5246
+ const retry = await adminFetch({
5247
+ fetcher,
5248
+ adminAccessToken,
5249
+ domain,
5250
+ query: lookupQuery,
5251
+ variables: { query: "email:" + email }
5252
+ });
5253
+ 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;
5254
+ if (found) return found;
5255
+ }
5256
+ ;
5257
+ throw new Error("Shopify customer create failed: " + userErrors[0].message);
5258
+ }
5259
+ ;
5260
+ return (_h = result == null ? void 0 : result.customerCreate) == null ? void 0 : _h.customer;
4976
5261
  };
4977
- var ORDER_EVENT_HANDLE = slugify("drawbridge-orders");
4978
- var REFRESH_TOKEN_FRESHNESS_BUFFER_MS = 5 * 24 * 60 * 60 * 1e3;
4979
- var OAUTH_ERROR_SOURCE = "oauth";
4980
- var BILLING_ERROR_SOURCE = "billing";
4981
- var BILLING_ERROR_MESSAGE = "Order billing isn't set up for this store \u2014 reselect and approve the plan from the Shopify connection page.";
4982
- var OAUTH_GRANT_REVOKED_CODES = ["application_cannot_be_found", "invalid_grant"];
4983
- var inbound = {
4984
- headers: {
4985
- event: "x-shopify-topic",
4986
- id: "x-shopify-webhook-id",
4987
- shop: "x-shopify-shop-domain",
4988
- signature: "x-shopify-hmac-sha256"
4989
- },
4990
- signature: {
4991
- algorithm: "sha256",
4992
- encoding: "base64",
4993
- secret: "SHOPIFY_API_SECRET"
5262
+ var getActiveAppSubscriptions = async ({ fetcher, adminAccessToken, domain }) => {
5263
+ var _a, _b;
5264
+ const data = await adminFetch({
5265
+ fetcher,
5266
+ adminAccessToken,
5267
+ domain,
5268
+ query: `{
5269
+ currentAppInstallation {
5270
+ activeSubscriptions {
5271
+ id
5272
+ name
5273
+ status
5274
+ test
5275
+ lineItems {
5276
+ id
5277
+ plan {
5278
+ pricingDetails {
5279
+ __typename
5280
+ }
5281
+ }
5282
+ }
5283
+ }
5284
+ }
5285
+ shop {
5286
+ myshopifyDomain
5287
+ }
5288
+ }`
5289
+ });
5290
+ return {
5291
+ shopDomain: ((_a = data == null ? void 0 : data.shop) == null ? void 0 : _a.myshopifyDomain) || null,
5292
+ subscriptions: (((_b = data == null ? void 0 : data.currentAppInstallation) == null ? void 0 : _b.activeSubscriptions) || []).map((subscription) => {
5293
+ var _a2;
5294
+ return {
5295
+ ...subscription,
5296
+ metered: ((subscription == null ? void 0 : subscription.lineItems) || []).some(
5297
+ (item) => {
5298
+ var _a3, _b2;
5299
+ return ((_b2 = (_a3 = item == null ? void 0 : item.plan) == null ? void 0 : _a3.pricingDetails) == null ? void 0 : _b2.__typename) === "AppUsagePricing";
5300
+ }
5301
+ ),
5302
+ // The usage line's own id — the address appUsageRecordCreate charges
5303
+ // against. Null when the approval carries no usage component.
5304
+ usageLineItemId: ((_a2 = ((subscription == null ? void 0 : subscription.lineItems) || []).find(
5305
+ (item) => {
5306
+ var _a3, _b2;
5307
+ return ((_b2 = (_a3 = item == null ? void 0 : item.plan) == null ? void 0 : _a3.pricingDetails) == null ? void 0 : _b2.__typename) === "AppUsagePricing";
5308
+ }
5309
+ )) == null ? void 0 : _a2.id) || null
5310
+ };
5311
+ })
5312
+ };
5313
+ };
5314
+ var createUsageSubscription = async ({ fetcher, adminAccessToken, cappedAmount, currencyCode = "USD", domain, name, recurringPrice = 0, returnUrl, terms, test = false }) => {
5315
+ if (!name || !returnUrl || !terms || !(Number(cappedAmount) > 0)) {
5316
+ throw new Error("createUsageSubscription requires name, returnUrl, terms, and a positive cappedAmount");
5317
+ }
5318
+ ;
5319
+ const data = await adminFetch({
5320
+ fetcher,
5321
+ adminAccessToken,
5322
+ domain,
5323
+ query: `mutation createUsageSubscription( $lineItems : [AppSubscriptionLineItemInput!]!, $name : String!, $returnUrl : URL!, $test : Boolean ) {
5324
+ appSubscriptionCreate( lineItems : $lineItems, name : $name, returnUrl : $returnUrl, test : $test ) {
5325
+ appSubscription { id name status test lineItems { id plan { pricingDetails { __typename } } } }
5326
+ confirmationUrl
5327
+ userErrors { field message }
5328
+ }
5329
+ }`,
5330
+ variables: {
5331
+ lineItems: [
5332
+ {
5333
+ plan: {
5334
+ appRecurringPricingDetails: {
5335
+ interval: "EVERY_30_DAYS",
5336
+ price: { amount: Number(recurringPrice), currencyCode }
5337
+ }
5338
+ }
5339
+ },
5340
+ {
5341
+ plan: {
5342
+ appUsagePricingDetails: {
5343
+ cappedAmount: { amount: Number(cappedAmount), currencyCode },
5344
+ terms
5345
+ }
5346
+ }
5347
+ }
5348
+ ],
5349
+ name,
5350
+ returnUrl,
5351
+ test
5352
+ }
5353
+ });
5354
+ const payload = data == null ? void 0 : data.appSubscriptionCreate;
5355
+ const userErrors = (payload == null ? void 0 : payload.userErrors) || [];
5356
+ if (userErrors.length) {
5357
+ throw new Error("Shopify subscription create failed: " + userErrors.map((entry) => entry.message).join("; "));
5358
+ }
5359
+ ;
5360
+ if (!(payload == null ? void 0 : payload.confirmationUrl)) {
5361
+ throw new Error("Shopify subscription create failed: no confirmation url returned");
4994
5362
  }
5363
+ ;
5364
+ return {
5365
+ confirmationUrl: payload.confirmationUrl,
5366
+ subscription: payload.appSubscription
5367
+ };
4995
5368
  };
4996
- var COMPLIANCE_TOPICS = /* @__PURE__ */ new Set([
4997
- "customers/data_request",
4998
- "customers/redact",
4999
- "shop/redact"
5369
+ var createUsageRecord = async ({ fetcher, adminAccessToken, amount, currencyCode = "USD", description, domain, idempotencyKey, subscriptionLineItemId }) => {
5370
+ var _a;
5371
+ if (!subscriptionLineItemId || !description || !(Number(amount) > 0)) {
5372
+ throw new Error("createUsageRecord requires subscriptionLineItemId, description, and a positive amount");
5373
+ }
5374
+ ;
5375
+ const data = await adminFetch({
5376
+ fetcher,
5377
+ adminAccessToken,
5378
+ domain,
5379
+ query: `mutation createUsageRecord( $description : String!, $idempotencyKey : String, $price : MoneyInput!, $subscriptionLineItemId : ID! ) {
5380
+ appUsageRecordCreate( description : $description, idempotencyKey : $idempotencyKey, price : $price, subscriptionLineItemId : $subscriptionLineItemId ) {
5381
+ appUsageRecord { id }
5382
+ userErrors { field message }
5383
+ }
5384
+ }`,
5385
+ variables: {
5386
+ description,
5387
+ idempotencyKey: idempotencyKey ? String(idempotencyKey) : null,
5388
+ price: { amount: Number(amount), currencyCode },
5389
+ subscriptionLineItemId
5390
+ }
5391
+ });
5392
+ const payload = data == null ? void 0 : data.appUsageRecordCreate;
5393
+ const userErrors = (payload == null ? void 0 : payload.userErrors) || [];
5394
+ if (userErrors.length || !((_a = payload == null ? void 0 : payload.appUsageRecord) == null ? void 0 : _a.id)) {
5395
+ throw new Error("Shopify usage record failed: " + (userErrors.map((entry) => entry.message).join("; ") || "no record returned"));
5396
+ }
5397
+ ;
5398
+ return { id: payload.appUsageRecord.id };
5399
+ };
5400
+ var getProductInventory = async ({ fetcher, adminAccessToken, domain, productId }) => {
5401
+ var _a, _b;
5402
+ const data = await adminFetch({
5403
+ fetcher,
5404
+ adminAccessToken,
5405
+ domain,
5406
+ query: `{
5407
+ product( id : "${productId}" ) {
5408
+ variants( first : 100 ) {
5409
+ edges {
5410
+ node {
5411
+ id
5412
+ inventoryQuantity
5413
+ }
5414
+ }
5415
+ }
5416
+ }
5417
+ }`
5418
+ });
5419
+ const edges = ((_b = (_a = data == null ? void 0 : data.product) == null ? void 0 : _a.variants) == null ? void 0 : _b.edges) || [];
5420
+ return edges.reduce((accumulator, edge) => {
5421
+ var _a2, _b2;
5422
+ const id = (_a2 = edge == null ? void 0 : edge.node) == null ? void 0 : _a2.id;
5423
+ const quantity = (_b2 = edge == null ? void 0 : edge.node) == null ? void 0 : _b2.inventoryQuantity;
5424
+ if (id) {
5425
+ accumulator[id] = Number.isFinite(quantity) ? quantity : 0;
5426
+ }
5427
+ ;
5428
+ return accumulator;
5429
+ }, {});
5430
+ };
5431
+ var getProductUpdatedAt = async ({ adminAccessToken, domain, fetcher, productId }) => {
5432
+ var _a;
5433
+ const data = await adminFetch({
5434
+ fetcher,
5435
+ adminAccessToken,
5436
+ domain,
5437
+ query: `
5438
+ query ProductUpdatedAt($id: ID!) {
5439
+ product(id: $id) {
5440
+ updatedAt
5441
+ }
5442
+ }
5443
+ `,
5444
+ variables: { id: productId }
5445
+ });
5446
+ return ((_a = data == null ? void 0 : data.product) == null ? void 0 : _a.updatedAt) || null;
5447
+ };
5448
+ var NOT_ON_CHANNEL = "not available to the channel";
5449
+ var OUTDATED_FEEDBACK = "later version";
5450
+ var sendProductResourceFeedback = async ({ fetcher, adminAccessToken, domain, productId, state, messages = [] }) => {
5451
+ var _a, _b, _c;
5452
+ const productUpdatedAt = await getProductUpdatedAt({ adminAccessToken, domain, fetcher, productId });
5453
+ if (!productUpdatedAt) return null;
5454
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5455
+ const submit = async (version) => {
5456
+ const data = await adminFetch({
5457
+ fetcher,
5458
+ adminAccessToken,
5459
+ domain,
5460
+ query: `
5461
+ mutation ProductFeedback($feedbackInput: [ProductResourceFeedbackInput!]!) {
5462
+ bulkProductResourceFeedbackCreate(feedbackInput: $feedbackInput) {
5463
+ feedback {
5464
+ productId
5465
+ state
5466
+ }
5467
+ userErrors {
5468
+ field
5469
+ message
5470
+ }
5471
+ }
5472
+ }
5473
+ `,
5474
+ variables: {
5475
+ feedbackInput: [
5476
+ {
5477
+ productId,
5478
+ state,
5479
+ feedbackGeneratedAt: now,
5480
+ productUpdatedAt: version,
5481
+ messages
5482
+ }
5483
+ ]
5484
+ }
5485
+ });
5486
+ return data == null ? void 0 : data.bulkProductResourceFeedbackCreate;
5487
+ };
5488
+ let result = await submit(productUpdatedAt);
5489
+ if ((((_b = (_a = result == null ? void 0 : result.userErrors) == null ? void 0 : _a[0]) == null ? void 0 : _b.message) || "").toLowerCase().includes(OUTDATED_FEEDBACK)) {
5490
+ result = await submit(now);
5491
+ }
5492
+ ;
5493
+ const feedbackErrors = result == null ? void 0 : result.userErrors;
5494
+ if (feedbackErrors == null ? void 0 : feedbackErrors.length) {
5495
+ const message = feedbackErrors[0].message || "";
5496
+ if (message.toLowerCase().includes(NOT_ON_CHANNEL)) return null;
5497
+ throw new Error("Shopify product feedback failed: " + message);
5498
+ }
5499
+ ;
5500
+ return ((_c = result == null ? void 0 : result.feedback) == null ? void 0 : _c[0]) || null;
5501
+ };
5502
+
5503
+ // lib/shopify/billing.js
5504
+ var billing_exports = {};
5505
+ __export(billing_exports, {
5506
+ sendAppEvent: () => sendAppEvent
5507
+ });
5508
+ var APP_API = "https://api.shopify.com";
5509
+ var APP_API_VERSION = process.env.SHOPIFY_APP_API_VERSION || SHOPIFY_APP_API_VERSION;
5510
+ var cachedTokens = {};
5511
+ var fetchAppToken = async ({ clientId, clientSecret, fetcher }) => {
5512
+ const data = await request({
5513
+ fetcher,
5514
+ method: "POST",
5515
+ url: APP_API + "/auth/access_token",
5516
+ body: {
5517
+ client_id: clientId,
5518
+ client_secret: clientSecret,
5519
+ grant_type: "client_credentials"
5520
+ }
5521
+ });
5522
+ if (!(data == null ? void 0 : data.access_token)) {
5523
+ throw new Error("Shopify app token request failed: no access token returned");
5524
+ }
5525
+ ;
5526
+ const ttl = data.expires_in ? data.expires_in * 1e3 : 60 * 60 * 1e3;
5527
+ cachedTokens[clientId] = {
5528
+ expiresAt: Date.now() + ttl - 60 * 1e3,
5529
+ token: data.access_token
5530
+ };
5531
+ return data.access_token;
5532
+ };
5533
+ var getAppToken = async ({ clientId, clientSecret, fetcher }) => {
5534
+ const cached = cachedTokens[clientId];
5535
+ if (cached && cached.expiresAt > Date.now()) {
5536
+ return cached.token;
5537
+ }
5538
+ ;
5539
+ return fetchAppToken({ clientId, clientSecret, fetcher });
5540
+ };
5541
+ var toShopGid = (shopId) => String(shopId).startsWith("gid://") ? String(shopId) : "gid://shopify/Shop/" + shopId;
5542
+ var sendAppEvent = async ({ fetcher, clientId, clientSecret, eventHandle, idempotencyKey, reference: reference2, revision, shopId, timestamp, value }) => {
5543
+ if (!shopId || !eventHandle || !(Number(value) > 0)) {
5544
+ throw new Error("sendAppEvent requires shopId, eventHandle, and a positive value");
5545
+ }
5546
+ ;
5547
+ if (!clientId || !clientSecret) {
5548
+ throw new Error("sendAppEvent requires clientId and clientSecret");
5549
+ }
5550
+ ;
5551
+ const suffix = revision ? ".r" + revision : "";
5552
+ const key = idempotencyKey && String(idempotencyKey).slice(0, Math.max(0, 64 - suffix.length)) + suffix;
5553
+ const body = {
5554
+ attributes: {
5555
+ value: Number(value),
5556
+ ...reference2 && {
5557
+ reference: String(reference2).slice(0, 128)
5558
+ }
5559
+ },
5560
+ event_handle: eventHandle,
5561
+ shop_id: toShopGid(shopId),
5562
+ timestamp: timestamp || (/* @__PURE__ */ new Date()).toISOString(),
5563
+ ...key && {
5564
+ idempotency_key: key
5565
+ }
5566
+ };
5567
+ const send2 = async (token) => request({
5568
+ method: "POST",
5569
+ url: APP_API + "/app/" + APP_API_VERSION + "/events",
5570
+ headers: {
5571
+ "Authorization": "Bearer " + token
5572
+ },
5573
+ body
5574
+ });
5575
+ try {
5576
+ return await send2(await getAppToken({ clientId, clientSecret, fetcher }));
5577
+ } catch (error) {
5578
+ if ((error == null ? void 0 : error.status) === 401) {
5579
+ delete cachedTokens[clientId];
5580
+ return send2(await fetchAppToken({ clientId, clientSecret, fetcher }));
5581
+ }
5582
+ ;
5583
+ throw error;
5584
+ }
5585
+ };
5586
+
5587
+ // lib/shopify/oauth.js
5588
+ var oauth_exports = {};
5589
+ __export(oauth_exports, {
5590
+ SHOPIFY_REQUIRED_SCOPES: () => SHOPIFY_REQUIRED_SCOPES,
5591
+ createStorefrontToken: () => createStorefrontToken,
5592
+ getAdminToken: () => getAdminToken,
5593
+ getShop: () => getShop,
5594
+ missingScopes: () => missingScopes2,
5595
+ ping: () => ping,
5596
+ refreshAdminToken: () => refreshAdminToken,
5597
+ resolveConnectionSettings: () => resolveConnectionSettings
5598
+ });
5599
+ var required = (name, value) => {
5600
+ if (!value) {
5601
+ throw new Error("Shopify " + name + " is required");
5602
+ }
5603
+ ;
5604
+ return value;
5605
+ };
5606
+ var missingScopes2 = (granted) => {
5607
+ const grantedSet = new Set(
5608
+ (Array.isArray(granted) ? granted : String(granted || "").split(",")).map((scope) => scope.trim()).filter(Boolean)
5609
+ );
5610
+ const satisfied = (scope) => grantedSet.has(scope) || grantedSet.has(scope.replace(/(^|_)read_/, "$1write_"));
5611
+ return SHOPIFY_REQUIRED_SCOPES.filter((scope) => !satisfied(scope));
5612
+ };
5613
+ var ping = async ({ fetcher, adminAccessToken, domain }) => {
5614
+ var _a;
5615
+ const response = await fetch(
5616
+ `https://${domain}/admin/api/${SHOPIFY_ADMIN_API_VERSION}/graphql.json`,
5617
+ {
5618
+ body: JSON.stringify({ query: "{ shop { name } }" }),
5619
+ headers: {
5620
+ "Content-Type": "application/json",
5621
+ "X-Shopify-Access-Token": adminAccessToken
5622
+ },
5623
+ method: "POST"
5624
+ }
5625
+ );
5626
+ if (!response.ok) {
5627
+ const text = await response.text().catch(() => "");
5628
+ const error = new Error(response.status + ": " + text);
5629
+ error.status = response.status;
5630
+ throw error;
5631
+ }
5632
+ ;
5633
+ const { errors } = await response.json().catch(() => ({}));
5634
+ if (errors == null ? void 0 : errors.length) {
5635
+ throw new Error("GraphQL: " + (((_a = errors[0]) == null ? void 0 : _a.message) || "unknown error"));
5636
+ }
5637
+ ;
5638
+ };
5639
+ var OAUTH_ERROR_TITLE_PATTERN = /Oauth error (\w+)/i;
5640
+ var parseOAuthErrorCode = (text) => {
5641
+ var _a;
5642
+ try {
5643
+ const parsed = JSON.parse(text);
5644
+ if (parsed == null ? void 0 : parsed.error) return parsed.error;
5645
+ } catch {
5646
+ }
5647
+ ;
5648
+ return ((_a = text.match(OAUTH_ERROR_TITLE_PATTERN)) == null ? void 0 : _a[1]) || null;
5649
+ };
5650
+ var shopifyOAuthFetch = async (url, body) => {
5651
+ const response = await fetch(url, {
5652
+ method: "POST",
5653
+ headers: {
5654
+ "Content-Type": "application/json"
5655
+ },
5656
+ body: JSON.stringify(body)
5657
+ });
5658
+ if (!response.ok) {
5659
+ const text = await response.text().catch(() => "");
5660
+ const error = new Error(response.status + ": " + text);
5661
+ error.status = response.status;
5662
+ error.code = parseOAuthErrorCode(text);
5663
+ throw error;
5664
+ }
5665
+ ;
5666
+ return response.json();
5667
+ };
5668
+ var getShop = async ({ fetcher, adminAccessToken, shop }) => {
5669
+ const data = await adminFetch({
5670
+ fetcher,
5671
+ adminAccessToken,
5672
+ domain: shop,
5673
+ query: `{
5674
+ shop {
5675
+ currencyCode
5676
+ id
5677
+ myshopifyDomain
5678
+ name
5679
+ }
5680
+ }`
5681
+ });
5682
+ const shopData = data == null ? void 0 : data.shop;
5683
+ if (!(shopData == null ? void 0 : shopData.id)) {
5684
+ throw new Error("Shopify shop lookup failed: no shop returned");
5685
+ }
5686
+ ;
5687
+ return {
5688
+ currency: shopData.currencyCode || null,
5689
+ id: shopData.id.split("/").pop(),
5690
+ myshopifyDomain: shopData.myshopifyDomain,
5691
+ name: shopData.name
5692
+ };
5693
+ };
5694
+ var createStorefrontToken = async ({ fetcher, adminAccessToken, shop }) => {
5695
+ var _a, _b, _c, _d, _e;
5696
+ try {
5697
+ const listed = await adminFetch({
5698
+ fetcher,
5699
+ adminAccessToken,
5700
+ domain: shop,
5701
+ query: `{
5702
+ shop {
5703
+ storefrontAccessTokens(first: 100) {
5704
+ edges {
5705
+ node {
5706
+ id
5707
+ title
5708
+ }
5709
+ }
5710
+ }
5711
+ }
5712
+ }`
5713
+ });
5714
+ 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);
5715
+ const orphaned = existing.filter((token) => (token == null ? void 0 : token.title) === "Drawbridge");
5716
+ await Promise.allSettled(
5717
+ orphaned.map((token) => adminFetch({
5718
+ adminAccessToken,
5719
+ domain: shop,
5720
+ query: `
5721
+ mutation StorefrontAccessTokenDelete($input: StorefrontAccessTokenDeleteInput!) {
5722
+ storefrontAccessTokenDelete(input: $input) {
5723
+ deletedStorefrontAccessTokenId
5724
+ userErrors {
5725
+ field
5726
+ message
5727
+ }
5728
+ }
5729
+ }
5730
+ `,
5731
+ variables: {
5732
+ input: {
5733
+ id: token.id
5734
+ }
5735
+ }
5736
+ }))
5737
+ );
5738
+ } catch {
5739
+ }
5740
+ const created = await adminFetch({
5741
+ fetcher,
5742
+ adminAccessToken,
5743
+ domain: shop,
5744
+ query: `
5745
+ mutation StorefrontAccessTokenCreate($input: StorefrontAccessTokenInput!) {
5746
+ storefrontAccessTokenCreate(input: $input) {
5747
+ storefrontAccessToken {
5748
+ accessToken
5749
+ }
5750
+ userErrors {
5751
+ field
5752
+ message
5753
+ }
5754
+ }
5755
+ }
5756
+ `,
5757
+ variables: {
5758
+ input: {
5759
+ title: "Drawbridge"
5760
+ }
5761
+ }
5762
+ });
5763
+ const createErrors = (_c = created == null ? void 0 : created.storefrontAccessTokenCreate) == null ? void 0 : _c.userErrors;
5764
+ if (createErrors == null ? void 0 : createErrors.length) {
5765
+ throw new Error("Shopify storefront token create failed: " + createErrors[0].message);
5766
+ }
5767
+ ;
5768
+ return ((_e = (_d = created == null ? void 0 : created.storefrontAccessTokenCreate) == null ? void 0 : _d.storefrontAccessToken) == null ? void 0 : _e.accessToken) || null;
5769
+ };
5770
+ var resolveTokenContext = async ({ connection, controller }) => {
5771
+ const decrypted = (connection == null ? void 0 : connection.settings) ? decrypt(connection.settings) : {};
5772
+ if ((decrypted == null ? void 0 : decrypted.ref) !== "shop") {
5773
+ return {
5774
+ raw: (connection == null ? void 0 : connection.settings) || null,
5775
+ session: null,
5776
+ settings: decrypted,
5777
+ shop: null,
5778
+ target: "connection"
5779
+ };
5780
+ }
5781
+ ;
5782
+ const shop = decrypted.shop;
5783
+ if (!controller || !shop) {
5784
+ return { raw: null, session: {}, settings: {}, shop, target: "shop" };
5785
+ }
5786
+ ;
5787
+ const record = await controller.get({ collection: "shop", query: { shop } });
5788
+ const session = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : {};
5789
+ const storefront = (record == null ? void 0 : record.storefront) ? decrypt(record.storefront) : null;
5790
+ return {
5791
+ raw: (record == null ? void 0 : record.settings) || null,
5792
+ session,
5793
+ settings: {
5794
+ adminAccessToken: session.accessToken || null,
5795
+ refreshToken: session.refreshToken || null,
5796
+ refreshTokenExpiresAt: session.refreshTokenExpires || null,
5797
+ storefrontAccessToken: (storefront == null ? void 0 : storefront.token) || null,
5798
+ tokenExpiresAt: session.expires || null
5799
+ },
5800
+ shop,
5801
+ target: "shop"
5802
+ };
5803
+ };
5804
+ var resolveConnectionSettings = async ({ fetcher, connection, controller }) => {
5805
+ const { settings } = await resolveTokenContext({ connection, controller });
5806
+ return settings;
5807
+ };
5808
+ var refreshAdminToken = async ({ fetcher, clientId, clientSecret, connection, controller }) => {
5809
+ var _a;
5810
+ const { raw, session, settings, shop, target } = await resolveTokenContext({ connection, controller });
5811
+ const domain = (connection == null ? void 0 : connection.shop) || ((_a = settings.source) == null ? void 0 : _a.domain) || settings.domain || shop;
5812
+ const { refreshToken } = settings;
5813
+ const data = await shopifyOAuthFetch(
5814
+ `https://${domain}/admin/oauth/access_token`,
5815
+ {
5816
+ grant_type: "refresh_token",
5817
+ // Throw before the grant: rotation RETIRES the old pair the moment it
5818
+ // returns, so a credential-less call that Shopify rejects opaquely is
5819
+ // the one failure mode worth being loud about.
5820
+ client_id: required("clientId", clientId),
5821
+ client_secret: required("clientSecret", clientSecret),
5822
+ refresh_token: refreshToken
5823
+ }
5824
+ );
5825
+ const adminAccessToken = data.access_token;
5826
+ const newRefreshToken = data.refresh_token;
5827
+ const expiresIn = data.expires_in;
5828
+ const tokenExpiresAt = expiresIn ? new Date(Date.now() + expiresIn * 1e3) : null;
5829
+ const refreshTokenExpiresAt = new Date(Date.now() + REFRESH_TOKEN_LIFETIME_MS);
5830
+ let liveToken = adminAccessToken;
5831
+ if (target === "shop") {
5832
+ const written = await controller.update({
5833
+ collection: "shop",
5834
+ data: {
5835
+ $set: {
5836
+ settings: encrypt({
5837
+ ...session,
5838
+ accessToken: adminAccessToken,
5839
+ expires: tokenExpiresAt,
5840
+ refreshToken: newRefreshToken,
5841
+ refreshTokenExpires: refreshTokenExpiresAt
5842
+ })
5843
+ }
5844
+ },
5845
+ query: {
5846
+ shop,
5847
+ ...raw && { settings: raw }
5848
+ }
5849
+ });
5850
+ if (!written) {
5851
+ const current = await controller.get({ collection: "shop", query: { shop } });
5852
+ if (!(current == null ? void 0 : current.settings)) {
5853
+ throw new Error("Shopify token refresh write-back failed: shop record missing for " + shop);
5854
+ }
5855
+ ;
5856
+ const currentSession = decrypt(current.settings);
5857
+ if ((currentSession == null ? void 0 : currentSession.accessToken) && currentSession.accessToken !== settings.adminAccessToken) {
5858
+ liveToken = currentSession.accessToken;
5859
+ } else {
5860
+ throw new Error("Shopify token refresh write-back failed for " + shop);
5861
+ }
5862
+ ;
5863
+ }
5864
+ ;
5865
+ } else {
5866
+ const written = await controller.update({
5867
+ collection: "connection",
5868
+ data: {
5869
+ $set: {
5870
+ settings: encrypt({
5871
+ ...settings,
5872
+ adminAccessToken,
5873
+ refreshToken: newRefreshToken,
5874
+ refreshTokenExpiresAt,
5875
+ tokenExpiresAt
5876
+ })
5877
+ }
5878
+ },
5879
+ query: {
5880
+ id: connection.id,
5881
+ ...raw && { settings: raw }
5882
+ }
5883
+ });
5884
+ if (!written) {
5885
+ const current = await controller.get({ collection: "connection", query: { id: connection.id } });
5886
+ const currentSettings = (current == null ? void 0 : current.settings) ? decrypt(current.settings) : null;
5887
+ if ((currentSettings == null ? void 0 : currentSettings.adminAccessToken) && currentSettings.adminAccessToken !== settings.adminAccessToken) {
5888
+ liveToken = currentSettings.adminAccessToken;
5889
+ } else {
5890
+ throw new Error("Shopify token refresh write-back failed for connection " + (connection == null ? void 0 : connection.id));
5891
+ }
5892
+ ;
5893
+ }
5894
+ ;
5895
+ }
5896
+ ;
5897
+ await ping({ adminAccessToken: liveToken, domain });
5898
+ return liveToken;
5899
+ };
5900
+ var getAdminToken = async ({ fetcher, clientId, clientSecret, connection, controller }) => {
5901
+ required("clientId", clientId);
5902
+ required("clientSecret", clientSecret);
5903
+ const settings = await resolveConnectionSettings({ connection, controller });
5904
+ const { adminAccessToken, refreshToken, tokenExpiresAt } = settings;
5905
+ if (!adminAccessToken) {
5906
+ return null;
5907
+ }
5908
+ ;
5909
+ if (!refreshToken) {
5910
+ return adminAccessToken;
5911
+ }
5912
+ ;
5913
+ const needsRefresh = !tokenExpiresAt || new Date(tokenExpiresAt) < new Date(Date.now() + ACCESS_TOKEN_REFRESH_BUFFER_MS);
5914
+ if (needsRefresh) {
5915
+ return refreshAdminToken({ clientId, clientSecret, connection, controller });
5916
+ }
5917
+ ;
5918
+ return adminAccessToken;
5919
+ };
5920
+
5921
+ // lib/shopify/partner.js
5922
+ var partner_exports = {};
5923
+ __export(partner_exports, {
5924
+ getUsageChargeEvents: () => getUsageChargeEvents
5925
+ });
5926
+ var PARTNER_API = "https://partners.shopify.com";
5927
+ var getUsageChargeEvents = async ({ fetcher, appId, first = 10, occurredAtMin, organizationId, partnerToken, shopId }) => {
5928
+ var _a, _b, _c;
5929
+ if (!partnerToken || !organizationId || !appId) {
5930
+ throw new Error("getUsageChargeEvents requires partnerToken, organizationId, and appId");
5931
+ }
5932
+ ;
5933
+ const data = await request({
5934
+ fetcher,
5935
+ method: "POST",
5936
+ url: PARTNER_API + "/" + organizationId + "/api/" + PARTNER_API_VERSION + "/graphql.json",
5937
+ headers: {
5938
+ "X-Shopify-Access-Token": partnerToken
5939
+ },
5940
+ body: {
5941
+ query: `query usageCharges( $filter : EventFilterInput!, $first : Int! ) {
5942
+ events( filter : $filter, orderBy : OCCURRED_AT_DESC, first : $first ) {
5943
+ edges {
5944
+ node {
5945
+ id
5946
+ occurredAt
5947
+ eventType
5948
+ shop { id myshopifyDomain }
5949
+ ... on Charge {
5950
+ chargeId
5951
+ chargeType
5952
+ amount { amount currencyCode }
5953
+ usageQuantity
5954
+ planHandle
5955
+ description
5956
+ }
5957
+ }
5958
+ }
5959
+ pageInfo { hasNextPage endCursor }
5960
+ }
5961
+ }`,
5962
+ variables: {
5963
+ filter: {
5964
+ eventTypes: ["CHARGE_USAGE"],
5965
+ subjectId: String(appId),
5966
+ ...occurredAtMin && { occurredAtMin },
5967
+ ...shopId && { shopId: String(shopId) }
5968
+ },
5969
+ first
5970
+ }
5971
+ }
5972
+ });
5973
+ if ((_a = data == null ? void 0 : data.errors) == null ? void 0 : _a.length) {
5974
+ throw new Error("Shopify partner events query failed: " + data.errors.map((entry) => entry.message).join("; "));
5975
+ }
5976
+ ;
5977
+ return (((_c = (_b = data == null ? void 0 : data.data) == null ? void 0 : _b.events) == null ? void 0 : _c.edges) || []).map((edge) => {
5978
+ var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j;
5979
+ return {
5980
+ amount: ((_a2 = edge.node) == null ? void 0 : _a2.amount) || null,
5981
+ chargeId: ((_b2 = edge.node) == null ? void 0 : _b2.chargeId) || null,
5982
+ // USAGE vs the recurring plan charge an approval emits — the
5983
+ // disambiguator callers filter on.
5984
+ chargeType: ((_c2 = edge.node) == null ? void 0 : _c2.chargeType) || null,
5985
+ description: ((_d = edge.node) == null ? void 0 : _d.description) || null,
5986
+ eventType: ((_e = edge.node) == null ? void 0 : _e.eventType) || null,
5987
+ id: ((_f = edge.node) == null ? void 0 : _f.id) || null,
5988
+ occurredAt: ((_g = edge.node) == null ? void 0 : _g.occurredAt) || null,
5989
+ planHandle: ((_h = edge.node) == null ? void 0 : _h.planHandle) || null,
5990
+ shop: ((_i = edge.node) == null ? void 0 : _i.shop) || null,
5991
+ usageQuantity: ((_j = edge.node) == null ? void 0 : _j.usageQuantity) ?? null
5992
+ };
5993
+ });
5994
+ };
5995
+
5996
+ // lib/shopify/storefront.js
5997
+ var storefront_exports = {};
5998
+ __export(storefront_exports, {
5999
+ cartCreate: () => cartCreate,
6000
+ cartGet: () => cartGet,
6001
+ cartLinesAdd: () => cartLinesAdd,
6002
+ cartLinesRemove: () => cartLinesRemove,
6003
+ cartLinesUpdate: () => cartLinesUpdate,
6004
+ createCheckoutToken: () => createCheckoutToken,
6005
+ getProduct: () => getProduct,
6006
+ getProductVariantsPage: () => getProductVariantsPage,
6007
+ getProducts: () => getProducts,
6008
+ probeVariantsOutOfStock: () => probeVariantsOutOfStock
6009
+ });
6010
+ var SORT_KEY_MAP = {
6011
+ bestSelling: "BEST_SELLING",
6012
+ createdAt: "CREATED_AT",
6013
+ id: "ID",
6014
+ price: "PRICE",
6015
+ productType: "PRODUCT_TYPE",
6016
+ title: "TITLE",
6017
+ updatedAt: "UPDATED_AT",
6018
+ vendor: "VENDOR"
6019
+ };
6020
+ var resolveProductSort = (sort) => {
6021
+ const entry = sort && Object.entries(sort)[0];
6022
+ if (!entry) return null;
6023
+ const [field, direction] = entry;
6024
+ const sortKey = SORT_KEY_MAP[field];
6025
+ if (!sortKey) return null;
6026
+ return {
6027
+ sortKey,
6028
+ reverse: Number(direction) < 0
6029
+ };
6030
+ };
6031
+ var storefrontUrl = (domain) => `https://${domain}/api/${SHOPIFY_STOREFRONT_API_VERSION}/graphql.json`;
6032
+ var storefrontFetch = async ({ fetcher, domain, storefrontAccessToken, query, variables }) => {
6033
+ return request({
6034
+ method: "POST",
6035
+ url: storefrontUrl(domain),
6036
+ headers: {
6037
+ "X-Shopify-Storefront-Access-Token": storefrontAccessToken
6038
+ },
6039
+ body: {
6040
+ query,
6041
+ ...variables && { variables }
6042
+ }
6043
+ });
6044
+ };
6045
+ var shopCountryCache = {};
6046
+ var getShopCountry = async ({ domain, fetcher, storefrontAccessToken }) => {
6047
+ var _a, _b;
6048
+ if (shopCountryCache[domain]) return shopCountryCache[domain];
6049
+ const { data } = await storefrontFetch({
6050
+ fetcher,
6051
+ domain,
6052
+ storefrontAccessToken,
6053
+ query: `{
6054
+ shop {
6055
+ paymentSettings {
6056
+ countryCode
6057
+ }
6058
+ }
6059
+ }`
6060
+ });
6061
+ const countryCode = ((_b = (_a = data == null ? void 0 : data.shop) == null ? void 0 : _a.paymentSettings) == null ? void 0 : _b.countryCode) || null;
6062
+ if (countryCode) shopCountryCache[domain] = countryCode;
6063
+ return countryCode;
6064
+ };
6065
+ var OUT_OF_STOCK_WARNING_CODES = [
6066
+ "MERCHANDISE_OUT_OF_STOCK",
6067
+ "MERCHANDISE_NOT_ENOUGH_STOCK"
6068
+ ];
6069
+ var probeVariantsOutOfStock = async ({ fetcher, domain, storefrontAccessToken, variantIds, countryCode }) => {
6070
+ var _a, _b;
6071
+ if (!(variantIds == null ? void 0 : variantIds.length)) return [];
6072
+ const resolvedCountry = countryCode || await getShopCountry({ domain, fetcher, storefrontAccessToken });
6073
+ const { data, errors } = await storefrontFetch({
6074
+ fetcher,
6075
+ domain,
6076
+ storefrontAccessToken,
6077
+ query: `
6078
+ mutation probe( $input : CartInput! ){
6079
+ cartCreate( input : $input ){
6080
+ cart {
6081
+ lines( first : 250 ){
6082
+ edges {
6083
+ node {
6084
+ id
6085
+ merchandise {
6086
+ ... on ProductVariant {
6087
+ id
6088
+ }
6089
+ }
6090
+ }
6091
+ }
6092
+ }
6093
+ }
6094
+ warnings {
6095
+ code
6096
+ message
6097
+ target
6098
+ }
6099
+ }
6100
+ }
6101
+ `,
6102
+ variables: {
6103
+ input: {
6104
+ lines: variantIds.map((merchandiseId) => ({
6105
+ merchandiseId,
6106
+ quantity: 1
6107
+ })),
6108
+ ...resolvedCountry && {
6109
+ buyerIdentity: {
6110
+ countryCode: resolvedCountry
6111
+ }
6112
+ }
6113
+ }
6114
+ }
6115
+ });
6116
+ if (errors) return [];
6117
+ const payload = data == null ? void 0 : data.cartCreate;
6118
+ const soldOut = new Set(
6119
+ ((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)
6120
+ );
6121
+ 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 }) => {
6122
+ var _a2;
6123
+ return (_a2 = node == null ? void 0 : node.merchandise) == null ? void 0 : _a2.id;
6124
+ }).filter(Boolean);
6125
+ };
6126
+ var productsQuery = (search, cursor, limit, sort) => {
6127
+ const resolved = resolveProductSort(sort);
6128
+ const sortArgs = resolved ? `, sortKey: ${resolved.sortKey}, reverse: ${resolved.reverse}` : "";
6129
+ return `{
6130
+ products(first: ${limit}${search ? `, query: "title:*${search}*"` : ""}${cursor ? `, after: "${cursor}"` : ""}${sortArgs}) {
6131
+ edges {
6132
+ node {
6133
+ id
6134
+ title
6135
+ description
6136
+ handle
6137
+ productType
6138
+ featuredImage {
6139
+ url
6140
+ }
6141
+ variants(first: 10) {
6142
+ edges {
6143
+ node {
6144
+ id
6145
+ title
6146
+ image {
6147
+ url
6148
+ }
6149
+ price {
6150
+ amount
6151
+ currencyCode
6152
+ }
6153
+ compareAtPrice {
6154
+ amount
6155
+ currencyCode
6156
+ }
6157
+ availableForSale
6158
+ requiresShipping
6159
+ }
6160
+ }
6161
+ }
6162
+ }
6163
+ }
6164
+ pageInfo {
6165
+ endCursor
6166
+ hasNextPage
6167
+ hasPreviousPage
6168
+ startCursor
6169
+ }
6170
+ }
6171
+ }`;
6172
+ };
6173
+ var productQuery = (productId) => `{
6174
+ product(id: "${productId}") {
6175
+ id
6176
+ title
6177
+ description
6178
+ handle
6179
+ productType
6180
+ featuredImage {
6181
+ url
6182
+ }
6183
+ variants(first: 10) {
6184
+ edges {
6185
+ node {
6186
+ id
6187
+ title
6188
+ image {
6189
+ url
6190
+ }
6191
+ price {
6192
+ amount
6193
+ currencyCode
6194
+ }
6195
+ compareAtPrice {
6196
+ amount
6197
+ currencyCode
6198
+ }
6199
+ availableForSale
6200
+ requiresShipping
6201
+ }
6202
+ }
6203
+ }
6204
+ }
6205
+ }`;
6206
+ var variantsQuery = (productId, cursor) => `{
6207
+ product(id: "${productId}") {
6208
+ variants(first: 250${cursor ? `, after: "${cursor}"` : ""}) {
6209
+ edges {
6210
+ node {
6211
+ id
6212
+ title
6213
+ image {
6214
+ url
6215
+ }
6216
+ price {
6217
+ amount
6218
+ currencyCode
6219
+ }
6220
+ compareAtPrice {
6221
+ amount
6222
+ currencyCode
6223
+ }
6224
+ availableForSale
6225
+ requiresShipping
6226
+ }
6227
+ }
6228
+ pageInfo {
6229
+ hasNextPage
6230
+ endCursor
6231
+ }
6232
+ }
6233
+ }
6234
+ }`;
6235
+ var getProducts = async ({ fetcher, domain, storefrontAccessToken, search, cursor, limit, sort }) => {
6236
+ const { data, errors } = await storefrontFetch({
6237
+ fetcher,
6238
+ domain,
6239
+ storefrontAccessToken,
6240
+ query: productsQuery(search, cursor, limit, sort)
6241
+ });
6242
+ if (errors) {
6243
+ throw new Error("Failed to fetch Shopify products");
6244
+ }
6245
+ ;
6246
+ return data == null ? void 0 : data.products;
6247
+ };
6248
+ var getProduct = async ({ fetcher, domain, storefrontAccessToken, productId }) => {
6249
+ var _a;
6250
+ const { data, errors } = await storefrontFetch({
6251
+ fetcher,
6252
+ domain,
6253
+ storefrontAccessToken,
6254
+ query: productQuery(productId)
6255
+ });
6256
+ if (errors) {
6257
+ throw new Error("Shopify storefront error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
6258
+ }
6259
+ ;
6260
+ if (!(data == null ? void 0 : data.product)) {
6261
+ throw new Error("Shopify product not found");
6262
+ }
6263
+ ;
6264
+ return data.product;
6265
+ };
6266
+ var getProductVariantsPage = async ({ fetcher, domain, storefrontAccessToken, productId, cursor }) => {
6267
+ var _a;
6268
+ const { data, errors } = await storefrontFetch({
6269
+ fetcher,
6270
+ domain,
6271
+ storefrontAccessToken,
6272
+ query: variantsQuery(productId, cursor)
6273
+ });
6274
+ if (errors) {
6275
+ throw new Error("Shopify storefront error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
6276
+ }
6277
+ ;
6278
+ if (!(data == null ? void 0 : data.product)) {
6279
+ throw new Error("Shopify product not found");
6280
+ }
6281
+ ;
6282
+ return data.product.variants;
6283
+ };
6284
+ var CART_FIELDS = `
6285
+ id
6286
+ checkoutUrl
6287
+ lines(first: 100) {
6288
+ edges {
6289
+ node {
6290
+ id
6291
+ quantity
6292
+ merchandise {
6293
+ ... on ProductVariant {
6294
+ id
6295
+ title
6296
+ availableForSale
6297
+ image {
6298
+ url
6299
+ }
6300
+ price {
6301
+ amount
6302
+ currencyCode
6303
+ }
6304
+ product {
6305
+ title
6306
+ }
6307
+ }
6308
+ }
6309
+ }
6310
+ }
6311
+ }
6312
+ `;
6313
+ var mapCart = (cart) => {
6314
+ var _a;
6315
+ if (!cart) return null;
6316
+ return {
6317
+ checkoutUrl: cart.checkoutUrl,
6318
+ id: cart.id,
6319
+ lines: (((_a = cart.lines) == null ? void 0 : _a.edges) || []).map(({ node }) => {
6320
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
6321
+ return {
6322
+ availableForSale: ((_a2 = node == null ? void 0 : node.merchandise) == null ? void 0 : _a2.availableForSale) ?? true,
6323
+ currency: ((_c = (_b = node == null ? void 0 : node.merchandise) == null ? void 0 : _b.price) == null ? void 0 : _c.currencyCode) || null,
6324
+ id: node.id,
6325
+ image: ((_e = (_d = node == null ? void 0 : node.merchandise) == null ? void 0 : _d.image) == null ? void 0 : _e.url) || null,
6326
+ price: ((_g = (_f = node == null ? void 0 : node.merchandise) == null ? void 0 : _f.price) == null ? void 0 : _g.amount) || null,
6327
+ productTitle: ((_i = (_h = node == null ? void 0 : node.merchandise) == null ? void 0 : _h.product) == null ? void 0 : _i.title) || null,
6328
+ quantity: node.quantity,
6329
+ variantId: (_j = node == null ? void 0 : node.merchandise) == null ? void 0 : _j.id,
6330
+ variantTitle: ((_k = node == null ? void 0 : node.merchandise) == null ? void 0 : _k.title) || null
6331
+ };
6332
+ })
6333
+ };
6334
+ };
6335
+ var firstUserError = (userErrors) => {
6336
+ const error = userErrors == null ? void 0 : userErrors[0];
6337
+ if (!error) return null;
6338
+ const message = new Error(error.message || "Shopify cart error");
6339
+ message.userError = true;
6340
+ return message;
6341
+ };
6342
+ var createCheckoutToken = async ({ fetcher, clientId, clientSecret } = {}) => {
6343
+ if (!clientId || !clientSecret) {
6344
+ throw new Error("createCheckoutToken requires clientId and clientSecret");
6345
+ }
6346
+ ;
6347
+ const response = await request({
6348
+ fetcher,
6349
+ method: "POST",
6350
+ url: "https://api.shopify.com/auth/access_token",
6351
+ body: {
6352
+ client_id: clientId,
6353
+ client_secret: clientSecret,
6354
+ grant_type: "client_credentials"
6355
+ }
6356
+ });
6357
+ const token = response == null ? void 0 : response.access_token;
6358
+ if (!token) {
6359
+ throw new Error("Failed to create Shopify checkout token");
6360
+ }
6361
+ ;
6362
+ return token;
6363
+ };
6364
+ var cartCreate = async ({ fetcher, domain, storefrontAccessToken, lines }) => {
6365
+ var _a, _b;
6366
+ const { data, errors } = await storefrontFetch({
6367
+ fetcher,
6368
+ domain,
6369
+ storefrontAccessToken,
6370
+ query: `
6371
+ mutation cartCreate($input: CartInput!) {
6372
+ cartCreate(input: $input) {
6373
+ cart {
6374
+ ${CART_FIELDS}
6375
+ }
6376
+ userErrors {
6377
+ field
6378
+ message
6379
+ }
6380
+ }
6381
+ }
6382
+ `,
6383
+ variables: {
6384
+ input: {
6385
+ lines
6386
+ }
6387
+ }
6388
+ });
6389
+ if (errors) {
6390
+ throw new Error("Failed to create Shopify cart");
6391
+ }
6392
+ ;
6393
+ const userError = firstUserError((_a = data == null ? void 0 : data.cartCreate) == null ? void 0 : _a.userErrors);
6394
+ if (userError) throw userError;
6395
+ return mapCart((_b = data == null ? void 0 : data.cartCreate) == null ? void 0 : _b.cart);
6396
+ };
6397
+ var cartGet = async ({ fetcher, domain, storefrontAccessToken, cartId }) => {
6398
+ const { data, errors } = await storefrontFetch({
6399
+ fetcher,
6400
+ domain,
6401
+ storefrontAccessToken,
6402
+ query: `
6403
+ query cart($id: ID!) {
6404
+ cart(id: $id) {
6405
+ ${CART_FIELDS}
6406
+ }
6407
+ }
6408
+ `,
6409
+ variables: {
6410
+ id: cartId
6411
+ }
6412
+ });
6413
+ if (errors) {
6414
+ throw new Error("Failed to fetch Shopify cart");
6415
+ }
6416
+ ;
6417
+ return mapCart(data == null ? void 0 : data.cart);
6418
+ };
6419
+ var cartLinesAdd = async ({ fetcher, domain, storefrontAccessToken, cartId, lines }) => {
6420
+ var _a, _b;
6421
+ const { data, errors } = await storefrontFetch({
6422
+ fetcher,
6423
+ domain,
6424
+ storefrontAccessToken,
6425
+ query: `
6426
+ mutation cartLinesAdd($cartId: ID!, $lines: [CartLineInput!]!) {
6427
+ cartLinesAdd(cartId: $cartId, lines: $lines) {
6428
+ cart {
6429
+ ${CART_FIELDS}
6430
+ }
6431
+ userErrors {
6432
+ field
6433
+ message
6434
+ }
6435
+ }
6436
+ }
6437
+ `,
6438
+ variables: {
6439
+ cartId,
6440
+ lines
6441
+ }
6442
+ });
6443
+ if (errors) {
6444
+ throw new Error("Failed to add Shopify cart lines");
6445
+ }
6446
+ ;
6447
+ const userError = firstUserError((_a = data == null ? void 0 : data.cartLinesAdd) == null ? void 0 : _a.userErrors);
6448
+ if (userError) throw userError;
6449
+ return mapCart((_b = data == null ? void 0 : data.cartLinesAdd) == null ? void 0 : _b.cart);
6450
+ };
6451
+ var cartLinesRemove = async ({ fetcher, domain, storefrontAccessToken, cartId, lineIds }) => {
6452
+ var _a, _b;
6453
+ const { data, errors } = await storefrontFetch({
6454
+ fetcher,
6455
+ domain,
6456
+ storefrontAccessToken,
6457
+ query: `
6458
+ mutation cartLinesRemove($cartId: ID!, $lineIds: [ID!]!) {
6459
+ cartLinesRemove(cartId: $cartId, lineIds: $lineIds) {
6460
+ cart {
6461
+ ${CART_FIELDS}
6462
+ }
6463
+ userErrors {
6464
+ field
6465
+ message
6466
+ }
6467
+ }
6468
+ }
6469
+ `,
6470
+ variables: {
6471
+ cartId,
6472
+ lineIds
6473
+ }
6474
+ });
6475
+ if (errors) {
6476
+ throw new Error("Failed to remove Shopify cart lines");
6477
+ }
6478
+ ;
6479
+ const userError = firstUserError((_a = data == null ? void 0 : data.cartLinesRemove) == null ? void 0 : _a.userErrors);
6480
+ if (userError) throw userError;
6481
+ return mapCart((_b = data == null ? void 0 : data.cartLinesRemove) == null ? void 0 : _b.cart);
6482
+ };
6483
+ var cartLinesUpdate = async ({ fetcher, domain, storefrontAccessToken, cartId, lines }) => {
6484
+ var _a, _b;
6485
+ const { data, errors } = await storefrontFetch({
6486
+ fetcher,
6487
+ domain,
6488
+ storefrontAccessToken,
6489
+ query: `
6490
+ mutation cartLinesUpdate($cartId: ID!, $lines: [CartLineUpdateInput!]!) {
6491
+ cartLinesUpdate(cartId: $cartId, lines: $lines) {
6492
+ cart {
6493
+ ${CART_FIELDS}
6494
+ }
6495
+ userErrors {
6496
+ field
6497
+ message
6498
+ }
6499
+ }
6500
+ }
6501
+ `,
6502
+ variables: {
6503
+ cartId,
6504
+ lines
6505
+ }
6506
+ });
6507
+ if (errors) {
6508
+ throw new Error("Failed to update Shopify cart lines");
6509
+ }
6510
+ ;
6511
+ const userError = firstUserError((_a = data == null ? void 0 : data.cartLinesUpdate) == null ? void 0 : _a.userErrors);
6512
+ if (userError) throw userError;
6513
+ return mapCart((_b = data == null ? void 0 : data.cartLinesUpdate) == null ? void 0 : _b.cart);
6514
+ };
6515
+
6516
+ // lib/email.js
6517
+ var GMAIL_DOMAINS = /* @__PURE__ */ new Set(["gmail.com", "googlemail.com"]);
6518
+ var toCanonicalEmail = (value) => {
6519
+ if (!value || typeof value !== "string") return null;
6520
+ const email = value.trim().toLowerCase();
6521
+ const at = email.lastIndexOf("@");
6522
+ if (at < 1 || at === email.length - 1) return null;
6523
+ let local = email.slice(0, at);
6524
+ const domain = email.slice(at + 1);
6525
+ const plus = local.indexOf("+");
6526
+ if (plus > 0) local = local.slice(0, plus);
6527
+ if (GMAIL_DOMAINS.has(domain)) local = local.replaceAll(".", "");
6528
+ if (!local) return null;
6529
+ return local + "@" + domain;
6530
+ };
6531
+
6532
+ // lib/oauth/index.js
6533
+ var lifetimes = {
6534
+ access: 60 * 60 * 8,
6535
+ // 8 hours
6536
+ authorizationCode: 10 * 60,
6537
+ // 10 minutes
6538
+ code: 15 * 60,
6539
+ // 15 minutes (email OTC)
6540
+ refresh: 30 * 24 * 60 * 60
6541
+ // 30 days
6542
+ };
6543
+ var tokenTypes = {
6544
+ access: "access",
6545
+ oauthState: "oauth.state",
6546
+ pat: "pat",
6547
+ refresh: "refresh"
6548
+ };
6549
+ var scopes = [
6550
+ "profile:read",
6551
+ "profile:write",
6552
+ "organization:read",
6553
+ "organization:write",
6554
+ "campaigns:read",
6555
+ "campaigns:write",
6556
+ "contacts:read",
6557
+ "contacts:write",
6558
+ "workflows:read",
6559
+ "workflows:write",
6560
+ "connections:read",
6561
+ "connections:write",
6562
+ "billing:read",
6563
+ "billing:write",
6564
+ "admin"
6565
+ ];
6566
+ var developer = [
6567
+ "profile:read",
6568
+ "organization:read",
6569
+ "campaigns:read",
6570
+ "campaigns:write",
6571
+ "contacts:read",
6572
+ "contacts:write",
6573
+ "workflows:read",
6574
+ "workflows:write",
6575
+ "connections:read",
6576
+ "connections:write"
6577
+ ];
6578
+ var scopeLabels = {
6579
+ "profile:read": "Read own profile",
6580
+ "profile:write": "Update own profile",
6581
+ "organization:read": "Read organization info",
6582
+ "organization:write": "Manage organization",
6583
+ "campaigns:read": "Read campaigns",
6584
+ "campaigns:write": "Manage campaigns",
6585
+ "contacts:read": "Read contacts",
6586
+ "contacts:write": "Manage contacts",
6587
+ "workflows:read": "Read workflows",
6588
+ "workflows:write": "Manage workflows",
6589
+ "connections:read": "Read integrations",
6590
+ "connections:write": "Manage integrations",
6591
+ "billing:read": "Read billing",
6592
+ "billing:write": "Manage billing",
6593
+ admin: "Admin access"
6594
+ };
6595
+ var toOption = (scope) => ({
6596
+ key: scopeLabels[scope] || scope,
6597
+ value: scope
6598
+ });
6599
+ var developerOptions = developer.map(toOption);
6600
+ var scopeOptions = scopes.map(toOption);
6601
+ var hashToken = (raw) => hash(raw, process.env.HMAC_OAUTH_TOKEN_KEY);
6602
+
6603
+ // lib/sanitize.js
6604
+ var import_disposable_email_domains = __toESM(require("disposable-email-domains/index.js"), 1);
6605
+ var disposableBlacklist = new Set(import_disposable_email_domains.default.map((d) => d.toLowerCase()));
6606
+ var sanitizeDomain = (value, pattern) => {
6607
+ if (!value) return value;
6608
+ const cleaned = value.trim().toLowerCase().replace(/^https?:\/\//i, "").replace(/\/+$/, "");
6609
+ if (pattern) {
6610
+ const match = cleaned.match(pattern);
6611
+ return match ? match[0] : cleaned;
6612
+ }
6613
+ return cleaned;
6614
+ };
6615
+
6616
+ // lib/slugify.js
6617
+ var import_slugify = __toESM(require("slugify"), 1);
6618
+ var slugify = (value, nochars = false) => {
6619
+ const remove = nochars ? /[-?*+~.()'"!:@#^_{}\[\];,/\\]/g : /[?*+~.()'"!:@#^_{}\[\];,/\\]/g;
6620
+ const replacement = nochars ? "" : "-";
6621
+ return (0, import_slugify.default)(
6622
+ value,
6623
+ {
6624
+ remove,
6625
+ replacement,
6626
+ lower: true,
6627
+ trim: true
6628
+ }
6629
+ );
6630
+ };
6631
+
6632
+ // lib/connections/manifests/shopify.js
6633
+ var client = Object.freeze({
6634
+ admin: admin_exports,
6635
+ billing: billing_exports,
6636
+ oauth: oauth_exports,
6637
+ partner: partner_exports,
6638
+ storefront: storefront_exports
6639
+ });
6640
+ var toLine = ({
6641
+ price,
6642
+ product_id: productId,
6643
+ quantity,
6644
+ title,
6645
+ variant_id: variantId,
6646
+ variant_title: variantTitle
6647
+ }) => ({
6648
+ price: parseFloat(price) || 0,
6649
+ productId: productId ? "gid://shopify/Product/" + productId : null,
6650
+ quantity: quantity || 1,
6651
+ title: title || null,
6652
+ variantId: variantId ? "gid://shopify/ProductVariant/" + variantId : null,
6653
+ variantTitle: variantTitle || null
6654
+ });
6655
+ var attributeLineItems = (lineItems = []) => lineItems.reduce(
6656
+ (acc, item) => {
6657
+ const attrs = (item.properties || []).reduce(
6658
+ (map, { name, value }) => {
6659
+ map[name] = value;
6660
+ return map;
6661
+ },
6662
+ {}
6663
+ );
6664
+ if (!attrs["_drwbrdg_ca"]) return acc;
6665
+ if (!Object.keys(acc.attrMap).length) acc.attrMap = attrs;
6666
+ const line = toLine(item);
6667
+ acc.attributedGross += line.price * line.quantity;
6668
+ acc.attributedLines.push(line);
6669
+ return acc;
6670
+ },
6671
+ { attrMap: {}, attributedGross: 0, attributedLines: [] }
6672
+ );
6673
+ var generateDiscountCode = (0, import_nanoid.customAlphabet)("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8);
6674
+ var blockedReason = (discount) => {
6675
+ var _a;
6676
+ if ((discount == null ? void 0 : discount.status) === "EXPIRED") return "This discount has expired.";
6677
+ const buyers = (_a = discount == null ? void 0 : discount.context) == null ? void 0 : _a.__typename;
6678
+ if (buyers && buyers !== "DiscountBuyerSelectionAll") {
6679
+ 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.";
6680
+ }
6681
+ ;
6682
+ if (typeof (discount == null ? void 0 : discount.usageLimit) === "number" && discount.usageLimit > 0 && ((discount == null ? void 0 : discount.asyncUsageCount) || 0) >= discount.usageLimit) {
6683
+ return "This discount has reached its total usage limit.";
6684
+ }
6685
+ ;
6686
+ return null;
6687
+ };
6688
+ var discountWarning = (discount) => {
6689
+ if ((discount == null ? void 0 : discount.status) === "SCHEDULED") {
6690
+ return "This discount hasn't started yet, so codes issued before it does won't work until then.";
6691
+ }
6692
+ ;
6693
+ if (discount == null ? void 0 : discount.appliesOncePerCustomer) return "Each customer can use this discount only once.";
6694
+ return null;
6695
+ };
6696
+ var ORDER_EVENT_HANDLE = slugify("drawbridge-orders");
6697
+ var REFRESH_TOKEN_FRESHNESS_BUFFER_MS = 5 * 24 * 60 * 60 * 1e3;
6698
+ var OAUTH_ERROR_SOURCE = "oauth";
6699
+ var BILLING_ERROR_SOURCE = "billing";
6700
+ var BILLING_ERROR_MESSAGE = "Order billing isn't set up for this store \u2014 reselect and approve the plan from the Shopify connection page.";
6701
+ var OAUTH_GRANT_REVOKED_CODES = ["application_cannot_be_found", "invalid_grant"];
6702
+ var inbound = {
6703
+ headers: {
6704
+ event: "x-shopify-topic",
6705
+ id: "x-shopify-webhook-id",
6706
+ shop: "x-shopify-shop-domain",
6707
+ signature: "x-shopify-hmac-sha256"
6708
+ },
6709
+ signature: {
6710
+ algorithm: "sha256",
6711
+ encoding: "base64",
6712
+ secret: "SHOPIFY_API_SECRET"
6713
+ }
6714
+ };
6715
+ var COMPLIANCE_TOPICS = /* @__PURE__ */ new Set([
6716
+ "customers/data_request",
6717
+ "customers/redact",
6718
+ "shop/redact"
5000
6719
  ]);
6720
+ var refusal = (message, status) => Object.assign(new Error(message), { status });
6721
+ var LINK_TOKEN_TTL_MS = 30 * 60 * 1e3;
6722
+ var CONNECTABLE_STATUSES = ["active", "unsubscribed"];
6723
+ var merchantOrganizations = ({ read, user }) => read.aggregate({
6724
+ collection: "organization",
6725
+ pipeline: [
6726
+ // A member qualifies only at `manage`; an owner always qualifies.
6727
+ {
6728
+ $lookup: {
6729
+ as: "membership",
6730
+ from: "member",
6731
+ let: { organization: "$id" },
6732
+ pipeline: [
6733
+ {
6734
+ $match: {
6735
+ $expr: { $eq: ["$organization", "$$organization"] },
6736
+ "capabilities.connections": "manage",
6737
+ status: "accepted",
6738
+ user
6739
+ }
6740
+ },
6741
+ { $limit: 1 },
6742
+ { $project: { _id: 0, organization: 1 } }
6743
+ ]
6744
+ }
6745
+ },
6746
+ {
6747
+ $match: {
6748
+ status: { $ne: "canceled" },
6749
+ $or: [{ owner: user }, { "membership.0": { $exists: true } }]
6750
+ }
6751
+ },
6752
+ // `organization.subscription` is a subscription RECORD ID — resolved here so
6753
+ // the list can read the real plan and conversion rate. Without it every org
6754
+ // rendered as free tier.
6755
+ { $lookup: { as: "subscription", foreignField: "id", from: "subscription", localField: "subscription" } },
6756
+ { $unwind: { path: "$subscription", preserveNullAndEmptyArrays: true } },
6757
+ {
6758
+ $lookup: {
6759
+ as: "connection",
6760
+ foreignField: "organization",
6761
+ from: "connection",
6762
+ localField: "id",
6763
+ pipeline: [
6764
+ { $match: { slug: "shopify" } },
6765
+ { $limit: 1 },
6766
+ { $project: { _id: 0, id: 1, shop: 1, status: 1 } }
6767
+ ]
6768
+ }
6769
+ },
6770
+ { $unwind: { path: "$connection", preserveNullAndEmptyArrays: true } },
6771
+ { $project: { _id: 0, billingStatus: "$status", connection: 1, id: 1, name: "$title", subscription: 1 } },
6772
+ { $sort: { name: 1 } }
6773
+ ]
6774
+ });
6775
+ var storePlan = async ({ record, shopify }) => {
6776
+ var _a;
6777
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
6778
+ if (!(settings == null ? void 0 : settings.accessToken)) return { active: false, name: null };
6779
+ try {
6780
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
6781
+ adminAccessToken: settings.accessToken,
6782
+ domain: record.shop
6783
+ });
6784
+ const active = (subscriptions || []).length > 0;
6785
+ const metered = active && subscriptions.some((subscription) => subscription.metered === true) ? true : null;
6786
+ return { active, metered, name: active ? ((_a = subscriptions[0]) == null ? void 0 : _a.name) || null : null };
6787
+ } catch (_) {
6788
+ return { active: false, name: null, unavailable: true };
6789
+ }
6790
+ };
6791
+ var releaseApprovals = async ({ context, read, shopify }) => {
6792
+ var _a;
6793
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
6794
+ if (!shop) throw refusal("shop is required", 400);
6795
+ const record = await read.get({ collection: "shop", query: { shop } });
6796
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
6797
+ if (!(settings == null ? void 0 : settings.accessToken)) throw refusal("Store is not installed", 409);
6798
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
6799
+ adminAccessToken: settings.accessToken,
6800
+ domain: shop
6801
+ });
6802
+ for (const subscription of subscriptions || []) {
6803
+ const data = await shopify.admin.adminFetch({
6804
+ adminAccessToken: settings.accessToken,
6805
+ domain: shop,
6806
+ query: "mutation appSubscriptionCancel( $id : ID! ) { appSubscriptionCancel( id : $id ) { appSubscription { id status } userErrors { field message } } }",
6807
+ variables: { id: subscription.id }
6808
+ });
6809
+ const [userError] = ((_a = data == null ? void 0 : data.appSubscriptionCancel) == null ? void 0 : _a.userErrors) || [];
6810
+ if (userError) throw refusal(userError.message, 422);
6811
+ }
6812
+ return {
6813
+ message: "Released " + (subscriptions || []).length + " approval(s).",
6814
+ request: { shop },
6815
+ result: { ok: true }
6816
+ };
6817
+ };
6818
+ var LEDGER_WINDOW_MS = 30 * 24 * 60 * 60 * 1e3;
6819
+ var meterVerdict = async ({ adminAccessToken, ledgerFloor, partner, shop, shopId, shopify }) => {
6820
+ var _a;
6821
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({ adminAccessToken, domain: shop });
6822
+ let metered = (_a = subscriptions.find((subscription) => subscription.usageLineItemId)) == null ? void 0 : _a.usageLineItemId;
6823
+ if (!((partner == null ? void 0 : partner.partnerToken) && (partner == null ? void 0 : partner.partnerOrgId) && (partner == null ? void 0 : partner.partnerAppId) && shopId)) {
6824
+ return { boundaries: [], ledger: false, metered };
6825
+ }
6826
+ const accruals = await shopify.partner.getUsageChargeEvents({
6827
+ appId: "gid://shopify/App/" + partner.partnerAppId,
6828
+ first: 10,
6829
+ occurredAtMin: ledgerFloor.toISOString(),
6830
+ organizationId: partner.partnerOrgId,
6831
+ partnerToken: partner.partnerToken,
6832
+ shopId: "gid://shopify/Shop/" + shopId
6833
+ });
6834
+ const boundaries = (accruals || []).filter((event) => event.occurredAt).sort((a, b) => new Date(a.occurredAt) - new Date(b.occurredAt));
6835
+ const accrued = [...boundaries].reverse().find((event) => Number(event.usageQuantity) > 0);
6836
+ if (accrued) metered = String(accrued.chargeId || accrued.id);
6837
+ return { boundaries, ledger: true, metered };
6838
+ };
6839
+ var toVariant = (edge) => {
6840
+ var _a, _b, _c, _d;
6841
+ return {
6842
+ availableForSale: edge.node.availableForSale || false,
6843
+ currency: ((_a = edge.node.price) == null ? void 0 : _a.currencyCode) || null,
6844
+ id: edge.node.id,
6845
+ image: ((_b = edge.node.image) == null ? void 0 : _b.url) || null,
6846
+ price: parseFloat((_c = edge.node.price) == null ? void 0 : _c.amount) || null,
6847
+ requiresShipping: edge.node.requiresShipping || false,
6848
+ sale: parseFloat((_d = edge.node.compareAtPrice) == null ? void 0 : _d.amount) || null,
6849
+ title: edge.node.title !== "Default Title" ? edge.node.title : null
6850
+ };
6851
+ };
6852
+ var applyOutOfStock = async ({ domain, shopify, storefrontAccessToken, variants }) => {
6853
+ try {
6854
+ const outOfStock = new Set(await shopify.storefront.probeVariantsOutOfStock({
6855
+ domain,
6856
+ storefrontAccessToken,
6857
+ variantIds: variants.map((variant) => variant.id)
6858
+ }));
6859
+ return variants.map((variant) => ({
6860
+ ...variant,
6861
+ availableForSale: variant.availableForSale && !outOfStock.has(variant.id)
6862
+ }));
6863
+ } catch (_) {
6864
+ return variants;
6865
+ }
6866
+ };
6867
+ var sendFeedback = async ({ adminToken, connection, messages, productId, shopify, state }) => {
6868
+ try {
6869
+ await shopify.admin.sendProductResourceFeedback({
6870
+ adminAccessToken: await adminToken(),
6871
+ domain: connection.shop,
6872
+ messages,
6873
+ productId,
6874
+ state
6875
+ });
6876
+ return null;
6877
+ } catch (error) {
6878
+ return error;
6879
+ }
6880
+ };
6881
+ var resolveProduct = async ({ connection, context, read }) => {
6882
+ const byId = (context == null ? void 0 : context.product) ? await read.get({ collection: "product", query: { id: context.product } }) : null;
6883
+ const row2 = byId || ((context == null ? void 0 : context.providerId) && ((context == null ? void 0 : context.shop) || (connection == null ? void 0 : connection.shop)) ? await read.get({
6884
+ collection: "product",
6885
+ query: {
6886
+ "provider.id": context.providerId,
6887
+ "provider.slug": "shopify",
6888
+ "source.domain": context.shop || connection.shop
6889
+ }
6890
+ }) : null);
6891
+ return row2;
6892
+ };
6893
+ var UNAVAILABLE_FEEDBACK = "Drawbridge can't display this product. Check it is active and available in the United States.";
6894
+ var NOT_FOUND = "Shopify product not found";
6895
+ var syncProduct = async ({ adminToken, connection, context, read, settings, shopify }) => {
6896
+ var _a, _b, _c;
6897
+ const row2 = await resolveProduct({ connection, context, read });
6898
+ if (!row2) return { message: "No product row to sync.", request: { product: (context == null ? void 0 : context.product) || null }, skipped: true };
6899
+ const domain = connection.shop;
6900
+ const providerId = (_a = row2.provider) == null ? void 0 : _a.id;
6901
+ const request2 = { product: row2.id, providerId: providerId || null, shop: domain };
6902
+ let product;
6903
+ try {
6904
+ product = await shopify.storefront.getProduct({
6905
+ domain,
6906
+ productId: providerId,
6907
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken
6908
+ });
6909
+ } catch (error) {
6910
+ if (error.message !== NOT_FOUND) throw error;
6911
+ const failed2 = await sendFeedback({
6912
+ adminToken,
6913
+ connection,
6914
+ messages: [UNAVAILABLE_FEEDBACK],
6915
+ productId: providerId,
6916
+ shopify,
6917
+ state: "REQUIRES_ACTION"
6918
+ });
6919
+ return {
6920
+ failed: failed2 ? [failed2.message] : void 0,
6921
+ message: "Storefront cannot see this product \u2014 deactivated.",
6922
+ request: request2,
6923
+ result: { status: "inactive" },
6924
+ writes: [
6925
+ {
6926
+ collection: "product",
6927
+ data: { $set: { status: "inactive" } },
6928
+ operation: "update",
6929
+ query: { id: row2.id }
6930
+ },
6931
+ {
6932
+ collection: "advertisement",
6933
+ data: { $set: { status: "drafted" } },
6934
+ multiple: true,
6935
+ operation: "update",
6936
+ query: { product: row2.id }
6937
+ }
6938
+ ]
6939
+ };
6940
+ }
6941
+ const variants = await applyOutOfStock({
6942
+ domain,
6943
+ shopify,
6944
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken,
6945
+ variants: (((_b = product == null ? void 0 : product.variants) == null ? void 0 : _b.edges) || []).map(toVariant)
6946
+ });
6947
+ const failed = await sendFeedback({
6948
+ adminToken,
6949
+ connection,
6950
+ messages: [],
6951
+ productId: providerId,
6952
+ shopify,
6953
+ state: "ACCEPTED"
6954
+ });
6955
+ return {
6956
+ // EVERYTHING PAST THE FIRST PAGE, filled in silently. The first page is
6957
+ // written above; a product with thousands of variants becomes N short
6958
+ // sequential jobs rather than one long loop that risks a BullMQ stall.
6959
+ enqueues: [{
6960
+ data: { operation: "variants", product: row2.id },
6961
+ name: "sync",
6962
+ options: { jobId: "product.shopify.variants." + row2.id + "." + Date.now() },
6963
+ queue: "product.shopify.variants"
6964
+ }],
6965
+ failed: failed ? [failed.message] : void 0,
6966
+ message: "Synced " + (product.title || "product") + ".",
6967
+ request: request2,
6968
+ result: { status: "active", variants: variants.length },
6969
+ writes: [{
6970
+ collection: "product",
6971
+ data: {
6972
+ $set: {
6973
+ description: product.description || null,
6974
+ image: ((_c = product.featuredImage) == null ? void 0 : _c.url) || null,
6975
+ // A successful sync PROVES channel visibility, which reverses the
6976
+ // deactivation above. Ads stay drafted.
6977
+ status: "active",
6978
+ title: product.title || null,
6979
+ type: product.productType || null,
6980
+ url: domain && product.handle ? "https://" + domain + "/products/" + product.handle : null,
6981
+ variants
6982
+ }
6983
+ },
6984
+ operation: "update",
6985
+ query: { id: row2.id }
6986
+ }]
6987
+ };
6988
+ };
6989
+ var syncVariants = async ({ connection, context, read, settings, shopify }) => {
6990
+ var _a, _b, _c;
6991
+ const row2 = await resolveProduct({ connection, context, read });
6992
+ if (!row2) return { message: "No product row to paginate.", request: { product: (context == null ? void 0 : context.product) || null }, skipped: true };
6993
+ const cursor = (context == null ? void 0 : context.cursor) || null;
6994
+ const request2 = { cursor, product: row2.id };
6995
+ let page;
6996
+ try {
6997
+ page = await shopify.storefront.getProductVariantsPage({
6998
+ cursor,
6999
+ domain: connection.shop,
7000
+ productId: (_a = row2.provider) == null ? void 0 : _a.id,
7001
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken
7002
+ });
7003
+ } catch (error) {
7004
+ if (error.message !== NOT_FOUND) throw error;
7005
+ return { message: "Storefront lost this product mid-pagination \u2014 stopping.", request: request2, skipped: true };
7006
+ }
7007
+ const variants = await applyOutOfStock({
7008
+ domain: connection.shop,
7009
+ shopify,
7010
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken,
7011
+ variants: (page.edges || []).map(toVariant)
7012
+ });
7013
+ return {
7014
+ ...((_b = page.pageInfo) == null ? void 0 : _b.hasNextPage) && { enqueues: [{
7015
+ data: { cursor: page.pageInfo.endCursor, operation: "variants", product: row2.id },
7016
+ name: "page",
7017
+ options: { jobId: "product.shopify.variants." + row2.id + "." + Date.now() },
7018
+ queue: "product.shopify.variants"
7019
+ }] },
7020
+ message: variants.length + " variant(s) on this page.",
7021
+ request: request2,
7022
+ result: { hasNextPage: Boolean((_c = page.pageInfo) == null ? void 0 : _c.hasNextPage), variants: variants.length },
7023
+ writes: [{
7024
+ collection: "product",
7025
+ data: cursor ? { $push: { variants: { $each: variants } } } : { $set: { variants } },
7026
+ operation: "update",
7027
+ query: { id: row2.id }
7028
+ }]
7029
+ };
7030
+ };
5001
7031
  var shopify_default2 = {
5002
7032
  // THE WORDS ON THE BUTTONS. `listing` was `content.redirect.title`, which put
5003
7033
  // a BUTTON LABEL inside the copy object next to a url — the title and the
@@ -5184,8 +7214,8 @@ var shopify_default2 = {
5184
7214
  // string; this answers what is missing from it.
5185
7215
  //
5186
7216
  // `shopify` is injected for the same reason it is everywhere else — this
5187
- // package cannot import @drawbridge/shopify, which depends on it.
5188
- scopes: ({ scope }, { shopify } = {}) => ({ result: { missing: scope ? shopify.oauth.missingScopes(scope) : null } }),
7217
+ // client is imported here and defaulted, never wired in by a caller.
7218
+ scopes: ({ scope }, { shopify = client } = {}) => ({ result: { missing: scope ? shopify.oauth.missingScopes(scope) : null } }),
5189
7219
  // Shopify's install grant is exchanged inside its own app flow, not
5190
7220
  // through the shared OAuth runner.
5191
7221
  token: false
@@ -5199,17 +7229,53 @@ var shopify_default2 = {
5199
7229
  // can reference another), `dispatch` (the caller's own coordinator table,
5200
7230
  // for the hooks that are dispatches).
5201
7231
  commerce: {
5202
- // NOT YET. The Checkout Kit cart path is `api/route/subdomain.js`, six direct
5203
- // calls into `@drawbridge/shopify/storefront` that write nothing — which is
5204
- // exactly why it never became a hook: a hook is reached to have its effects
5205
- // performed, and this one has none to perform. It moves here when the vendor
5206
- // client moves into the manifest and `subdomain.js` stops importing the
5207
- // package directly.
5208
- cart: false,
7232
+ // THE CHECKOUT KIT CART. Six operations that were six direct calls into
7233
+ // the storefront client from api/route/subdomain.js.
7234
+ //
7235
+ // IT WRITES NOTHING, which is exactly why it was the last surface to
7236
+ // become a hook a hook is usually reached to have its effects performed
7237
+ // and this one has none. That reasoning was wrong: a hook is also the one
7238
+ // place a vendor's client is allowed to be called from, and leaving the
7239
+ // cart out meant a public route importing a vendor SDK directly.
7240
+ //
7241
+ // ONE HOOK, OPERATION IN THE CONTEXT, the same shape `inbound.process`
7242
+ // uses for its topic table. Six slots would be six names in the closed
7243
+ // vocabulary for one question — what does this shopper's cart look like
7244
+ // now — asked six ways.
7245
+ //
7246
+ // A USER ERROR IS A 400 AND THE SHOPPER'S OWN WORDS. Shopify's cart
7247
+ // mutations answer "that variant is sold out" as a userError rather than a
7248
+ // transport failure, and the route it replaced already told the two apart.
7249
+ // runHook carries `status` off a thrown error, so it survives to the
7250
+ // caller; the rest of a thrown error's shape does not.
7251
+ cart: async ({ clientId, clientSecret, context, settings }, { fetcher, shopify = client } = {}) => {
7252
+ const { cartId, lineIds, lines, operation } = context || {};
7253
+ const { domain, storefrontAccessToken } = settings || {};
7254
+ if (operation === "checkout") {
7255
+ const token = await shopify.storefront.createCheckoutToken({ clientId, clientSecret, fetcher });
7256
+ return { message: "Checkout token minted.", result: { token } };
7257
+ }
7258
+ const storefront = { domain, fetcher, storefrontAccessToken };
7259
+ try {
7260
+ const cart = await ({
7261
+ create: () => shopify.storefront.cartCreate({ ...storefront, lines }),
7262
+ get: () => shopify.storefront.cartGet({ ...storefront, cartId }),
7263
+ linesAdd: () => shopify.storefront.cartLinesAdd({ ...storefront, cartId, lines }),
7264
+ linesRemove: () => shopify.storefront.cartLinesRemove({ ...storefront, cartId, lineIds }),
7265
+ linesUpdate: () => shopify.storefront.cartLinesUpdate({ ...storefront, cartId, lines })
7266
+ }[operation] || (() => {
7267
+ throw Object.assign(new Error("Unknown cart operation: " + operation), { status: 400 });
7268
+ }))();
7269
+ return { message: "Cart " + operation + ".", request: { cartId: cartId || null, operation }, result: cart };
7270
+ } catch (error) {
7271
+ if (error == null ? void 0 : error.userError) throw Object.assign(error, { status: 400 });
7272
+ throw error;
7273
+ }
7274
+ },
5209
7275
  // MINT A DISCOUNT CODE against the merchant's chosen discount, mapped to
5210
7276
  // one lead — which is what lets an order that redeems it be attributed
5211
7277
  // back.
5212
- code: async ({ connection, context, step }, { adminToken, shopify } = {}) => {
7278
+ code: async ({ connection, context, step }, { adminToken, shopify = client } = {}) => {
5213
7279
  var _a;
5214
7280
  const discount = (_a = step.settings) == null ? void 0 : _a.discount;
5215
7281
  const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection.shop };
@@ -5255,7 +7321,7 @@ var shopify_default2 = {
5255
7321
  // customer at the store is a support ticket: the context may already
5256
7322
  // carry the id from an earlier step, the lead may already be linked from
5257
7323
  // an earlier run, and Shopify's own get-or-create settles the rest.
5258
- customer: async ({ connection, context }, { adminToken, read, shopify } = {}) => {
7324
+ customer: async ({ connection, context }, { adminToken, read, shopify = client } = {}) => {
5259
7325
  const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection.shop };
5260
7326
  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 };
5261
7327
  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 };
@@ -5305,6 +7371,30 @@ var shopify_default2 = {
5305
7371
  }]
5306
7372
  };
5307
7373
  },
7374
+ // HOW MANY ARE LEFT. Read at the moment a campaign's product list is
7375
+ // rendered rather than stored on the product, because stock is the one
7376
+ // product fact that is stale the instant it is written down.
7377
+ //
7378
+ // SUMMED HERE, not by the caller. Shopify answers per variant and every
7379
+ // caller wanted the total; the one that existed summed it inline, and
7380
+ // summing `Object.values()` over the raw map is how a cache wrapper's own
7381
+ // bookkeeping key got counted as a quantity.
7382
+ inventory: async ({ connection, context }, { adminToken, shopify = client } = {}) => {
7383
+ const productId = context == null ? void 0 : context.product;
7384
+ const request2 = { product: productId || null, shop: connection.shop };
7385
+ if (!productId) return { message: "No product id \u2014 nothing to count.", request: request2, result: { total: null }, skipped: true };
7386
+ const adminAccessToken = await adminToken();
7387
+ const byVariant = await shopify.admin.getProductInventory({
7388
+ adminAccessToken,
7389
+ domain: connection.shop,
7390
+ productId
7391
+ });
7392
+ return {
7393
+ message: "Inventory read.",
7394
+ request: request2,
7395
+ result: { total: Object.values(byVariant || {}).reduce((sum, quantity) => sum + quantity, 0) }
7396
+ };
7397
+ },
5308
7398
  // AN ORDER ARRIVED AT THE STORE. The largest hook in the family, because
5309
7399
  // attribution genuinely is: an order can reach Drawbridge two ways and
5310
7400
  // they bill differently.
@@ -5625,6 +7715,12 @@ var shopify_default2 = {
5625
7715
  orderId: String(orderId),
5626
7716
  rate,
5627
7717
  shopId: connection.source.id,
7718
+ // WHICH VENDOR IS BEING CHARGED, so the sender does not have
7719
+ // to assume. queue/usage.js named the slug itself and
7720
+ // defaults to it for anything already queued when this
7721
+ // shipped — an app-store vendor billing through its own meter
7722
+ // enqueues the same job with its own slug.
7723
+ slug: connection.slug,
5628
7724
  // The App Events API returns no event id, so one is generated
5629
7725
  // here — the event handle plus the order id — and sent as the
5630
7726
  // event's `reference`. queue/usage.js stamps the same id onto
@@ -5664,10 +7760,28 @@ var shopify_default2 = {
5664
7760
  //
5665
7761
  // The shell has already refused a missing or inactive Shopify connection,
5666
7762
  // so what is left is the two things only this hook can know are wrong.
5667
- product: async ({ connection, context, workflow }, { mintId, read } = {}) => {
7763
+ // A PRODUCT, IN THREE MOVES. Nested by operation rather than by three
7764
+ // slots in the closed vocabulary, the same shape inbound.process uses
7765
+ // for its topic table — they are one subject, and a vendor that syncs
7766
+ // products has to answer all three or none.
7767
+ //
7768
+ // record a webhook said a product changed: upsert the row and
7769
+ // queue the pull
7770
+ // sync pull the product from the storefront and write what it
7771
+ // says, including what it says by NOT answering
7772
+ // variants one page of variants, self-chaining
7773
+ //
7774
+ // `sync` and `variants` were 443 lines of drawbridge-sync's
7775
+ // queue/product.js — a shadow implementation of the step this manifest
7776
+ // already declared, importing three of the vendor's client modules from
7777
+ // a worker file.
7778
+ product: async ({ connection, context, settings, workflow }, { adminToken, mintId, read, shopify = client } = {}) => {
7779
+ const operation = (context == null ? void 0 : context.operation) || "record";
7780
+ if (operation === "sync") return syncProduct({ adminToken, connection, context, read, settings, shopify });
7781
+ if (operation === "variants") return syncVariants({ connection, context, read, settings, shopify });
5668
7782
  const request2 = {
5669
7783
  numericId: (context == null ? void 0 : context.id) || null,
5670
- organizationId: workflow.organization,
7784
+ organizationId: (workflow == null ? void 0 : workflow.organization) || null,
5671
7785
  title: (context == null ? void 0 : context.title) || null
5672
7786
  };
5673
7787
  if (!(context == null ? void 0 : context.id)) return { message: "Skipped \u2014 product webhook payload had no id.", request: request2, response: { skipped: true }, skipped: true };
@@ -5717,9 +7831,612 @@ var shopify_default2 = {
5717
7831
  }
5718
7832
  },
5719
7833
  contacts: { remove: false, sync: false },
5720
- // The embedded-app surface. Only a vendor whose merchants arrive from its
5721
- // own app store has one.
5722
- install: false,
7834
+ // THE EMBEDDED-APP SURFACE. Only a vendor whose merchants arrive from its
7835
+ // own app store has one, and these thirteen slots are the thirteen routes
7836
+ // that used to live in api/route/shopify-embedded.js.
7837
+ //
7838
+ // A HOOK DESCRIBES ITS WRITES and the shell performs them, so none of these
7839
+ // holds a controller — `read` is the controller's read methods and nothing
7840
+ // else. Where one REFUSES it throws with a status, and the route answers
7841
+ // what it said. The helpers they share are above the manifest.
7842
+ install: {
7843
+ account: {
7844
+ // ESTABLISH THE DURABLE MERCHANT-TO-STORE LINK. The breakout
7845
+ // authenticates the merchant once, top-level, and stashes their user
7846
+ // token in `install.token.save`; App Bridge has already proven shop
7847
+ // control by the time this runs.
7848
+ //
7849
+ // THE STASHED TOKEN IS THE TRUST ANCHOR, not merely any valid user
7850
+ // token: the presented one must BE this shop's one-shot handoff token,
7851
+ // unexpired, and an access or pat record — a refresh or oauth-state
7852
+ // token that happens to resolve to a user must not qualify, which is
7853
+ // the rule a session is held to in drawbridge-api's middleware.
7854
+ link: async ({ context }, { read } = {}) => {
7855
+ var _a;
7856
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
7857
+ const token = context == null ? void 0 : context.token;
7858
+ if (!shop || !token) throw refusal("shop and token are required", 400);
7859
+ const now = /* @__PURE__ */ new Date();
7860
+ const record = await read.get({ collection: "shop", query: { shop } });
7861
+ const stashed = (record == null ? void 0 : record.linkToken) ? (_a = decrypt(record.linkToken)) == null ? void 0 : _a.token : null;
7862
+ const expired = !(record == null ? void 0 : record.linkTokenExpiresAt) || new Date(record.linkTokenExpiresAt) <= now;
7863
+ if (!stashed || expired || stashed !== token) throw refusal("Invalid or expired link token", 401);
7864
+ const granted = await read.get({
7865
+ collection: "token",
7866
+ query: {
7867
+ revoked: false,
7868
+ tokenHash: hashToken(token),
7869
+ type: { $in: [tokenTypes.access, tokenTypes.pat] }
7870
+ }
7871
+ });
7872
+ if (!(granted == null ? void 0 : granted.user) || granted.expiresAt && new Date(granted.expiresAt) <= now) {
7873
+ throw refusal("Invalid or expired link token", 401);
7874
+ }
7875
+ const switching = Boolean(record == null ? void 0 : record.user) && record.user !== granted.user;
7876
+ const connections2 = switching ? await read.aggregate({
7877
+ collection: "connection",
7878
+ pipeline: [
7879
+ { $match: { shop, slug: "shopify" } },
7880
+ { $project: { _id: 0, id: 1 } }
7881
+ ]
7882
+ }) : [];
7883
+ return {
7884
+ message: switching ? "Linked to a different Drawbridge account." : "Linked.",
7885
+ request: { shop },
7886
+ result: { connected: true, switched: switching },
7887
+ // ALL OR NONE. A half-done switch is a store linked to the new
7888
+ // account while the old account's connections still serve from it.
7889
+ transaction: true,
7890
+ writes: [
7891
+ ...(connections2 || []).map((connection) => ({
7892
+ collection: "connection",
7893
+ operation: "delete",
7894
+ query: { id: connection.id }
7895
+ })),
7896
+ {
7897
+ collection: "shop",
7898
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null, user: granted.user } },
7899
+ operation: "update",
7900
+ query: { shop }
7901
+ }
7902
+ ]
7903
+ };
7904
+ },
7905
+ // DISCONNECT THE ACCOUNT FROM THE STORE. Every org connection goes and
7906
+ // the durable link clears; the offline token and the shop record stay,
7907
+ // because the app is still installed and the merchant may link a
7908
+ // different account next.
7909
+ unlink: async ({ context }, { read } = {}) => {
7910
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
7911
+ if (!shop) throw refusal("shop is required", 400);
7912
+ const connections2 = await read.aggregate({
7913
+ collection: "connection",
7914
+ pipeline: [
7915
+ { $match: { shop, slug: "shopify" } },
7916
+ { $project: { _id: 0, id: 1 } }
7917
+ ]
7918
+ });
7919
+ return {
7920
+ message: "Unlinked " + (connections2 || []).length + " connection(s).",
7921
+ request: { shop },
7922
+ result: { ok: true },
7923
+ transaction: true,
7924
+ writes: [
7925
+ ...(connections2 || []).map((connection) => ({
7926
+ collection: "connection",
7927
+ operation: "delete",
7928
+ query: { id: connection.id }
7929
+ })),
7930
+ {
7931
+ collection: "shop",
7932
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null, user: null } },
7933
+ operation: "update",
7934
+ query: { shop }
7935
+ }
7936
+ ]
7937
+ };
7938
+ }
7939
+ },
7940
+ organizations: {
7941
+ // BIND ONE ORGANIZATION TO THIS STORE. The longest slot here, and every
7942
+ // gate in it came from a line in the route it replaces.
7943
+ add: async ({ context }, { currencies, mintId, read, shopify = client } = {}) => {
7944
+ var _a, _b;
7945
+ const organization = context == null ? void 0 : context.organization;
7946
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
7947
+ if (!shop) throw refusal("shop is required", 400);
7948
+ if (!organization) throw refusal("organization is required", 400);
7949
+ const record = await read.get({ collection: "shop", query: { shop } });
7950
+ if (!(record == null ? void 0 : record.user)) throw refusal("Account is not connected for this store", 409);
7951
+ const owned = await merchantOrganizations({ read, user: record.user });
7952
+ const org = (owned || []).find((entry) => entry.id === organization);
7953
+ if (!org) throw refusal("No access to this organization", 403);
7954
+ if (!CONNECTABLE_STATUSES.includes(org.billingStatus)) {
7955
+ throw refusal("This organization can't accept connections right now \u2014 check its billing status in the dashboard", 403);
7956
+ }
7957
+ if (org.connection && org.connection.shop !== shop) {
7958
+ throw refusal("This organization is already connected to another Shopify store", 409);
7959
+ }
7960
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
7961
+ if (!(settings == null ? void 0 : settings.accessToken)) {
7962
+ throw refusal("Store is not installed \u2014 open the app in the Shopify admin first", 409);
7963
+ }
7964
+ const plan = await storePlan({ record, shopify });
7965
+ if (plan.unavailable) throw refusal("Couldn't verify the store's plan \u2014 try again shortly", 502);
7966
+ if (!plan.active) throw refusal("Approve a plan before connecting organizations", 402);
7967
+ let storefront = null;
7968
+ if (!record.storefront) {
7969
+ try {
7970
+ const minted2 = await shopify.oauth.createStorefrontToken({
7971
+ adminAccessToken: settings.accessToken,
7972
+ shop
7973
+ });
7974
+ if (minted2) storefront = encrypt({ token: minted2 });
7975
+ } catch (_) {
7976
+ }
7977
+ }
7978
+ let currency = (record == null ? void 0 : record.currency) || null;
7979
+ let source = (record == null ? void 0 : record.source) || null;
7980
+ try {
7981
+ const shopData = await shopify.oauth.getShop({ adminAccessToken: settings.accessToken, shop });
7982
+ if (shopData) {
7983
+ currency = String(shopData.currency || "").toLowerCase() || null;
7984
+ source = { domain: shopData.myshopifyDomain, id: String(shopData.id), label: shopData.name };
7985
+ }
7986
+ } catch (_) {
7987
+ }
7988
+ if (currency && currencies && !currencies.includes(currency)) {
7989
+ throw refusal("This store settles in a currency we can't bill yet. Connect a store with a supported settlement currency.", 422);
7990
+ }
7991
+ const minted = ((_a = org.connection) == null ? void 0 : _a.id) ? null : mintId();
7992
+ const connectionId = ((_b = org.connection) == null ? void 0 : _b.id) || minted.id;
7993
+ return {
7994
+ message: "Connected " + org.name + " to " + shop + ".",
7995
+ request: { organization, shop },
7996
+ result: { ok: true },
7997
+ transaction: true,
7998
+ writes: [
7999
+ ...storefront ? [{
8000
+ collection: "shop",
8001
+ data: { $set: { storefront } },
8002
+ operation: "update",
8003
+ query: { shop }
8004
+ }] : [],
8005
+ {
8006
+ collection: "connection",
8007
+ data: {
8008
+ $set: {
8009
+ currency,
8010
+ errors: [],
8011
+ // The token of record lives on the shared `shop` row; this
8012
+ // is the pointer that satisfies the required `settings`
8013
+ // string, and `auth.install.shared` declares how to read it.
8014
+ settings: encrypt({ ref: "shop", shop }),
8015
+ shop,
8016
+ status: "pending",
8017
+ ...source && { source }
8018
+ },
8019
+ $setOnInsert: {
8020
+ ...minted && { _id: minted._id, id: minted.id },
8021
+ feature: "organization:connection:shopify",
8022
+ organization,
8023
+ slug: "shopify"
8024
+ }
8025
+ },
8026
+ operation: "update",
8027
+ options: { upsert: true },
8028
+ query: { organization, slug: "shopify" }
8029
+ },
8030
+ {
8031
+ collection: "organization",
8032
+ data: {
8033
+ // $addToSet UNCONDITIONALLY. The route this replaces only
8034
+ // registered the refs when the upsert INSERTED, which meant an
8035
+ // org whose refs had drifted stayed drifted through every
8036
+ // re-link. Adding a member that is already there is a no-op,
8037
+ // so doing it every time costs nothing and repairs the drift.
8038
+ $addToSet: {
8039
+ "connections.groups": "ecommerce",
8040
+ "connections.ids": connectionId,
8041
+ "connections.keys": "shopify"
8042
+ },
8043
+ $set: { billingProvider: "shopify" }
8044
+ },
8045
+ operation: "update",
8046
+ query: { id: organization }
8047
+ }
8048
+ ]
8049
+ };
8050
+ },
8051
+ // WHAT THIS STORE CAN SEE: the linked merchant's organizations, the
8052
+ // store's live plan, and the products the merchant has to act on.
8053
+ //
8054
+ // AN ORG CONNECTED TO A DIFFERENT STORE IS OMITTED ENTIRELY, because
8055
+ // `add` would refuse it — a list that offers what the next call rejects
8056
+ // is worse than a shorter one.
8057
+ list: async ({ context }, { conversionRate, planTitle, read, shopify = client } = {}) => {
8058
+ var _a;
8059
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8060
+ if (!shop) throw refusal("shop is required", 400);
8061
+ const record = await read.get({ collection: "shop", query: { shop } });
8062
+ if (!(record == null ? void 0 : record.user)) {
8063
+ return {
8064
+ message: "No account linked to this store.",
8065
+ request: { shop },
8066
+ result: {
8067
+ account: null,
8068
+ connected: false,
8069
+ organizations: [],
8070
+ plan: { active: false, name: null },
8071
+ unavailableProducts: [],
8072
+ unavailableProductsTotal: 0
8073
+ }
8074
+ };
8075
+ }
8076
+ const owned = await merchantOrganizations({ read, user: record.user });
8077
+ const organizations = (owned || []).filter((org) => !org.connection || org.connection.shop === shop).map((org) => {
8078
+ var _a2;
8079
+ return {
8080
+ // The org's OWN billing status decides whether `add` accepts it.
8081
+ // Sent up so the app can disable Connect and name the reason
8082
+ // rather than letting the merchant click into a 403 —
8083
+ // listed-but-blocked beats hidden, because an org vanishing from
8084
+ // the list is indistinguishable from a bug.
8085
+ billingStatus: org.billingStatus || null,
8086
+ connectable: CONNECTABLE_STATUSES.includes(org.billingStatus),
8087
+ connected: Boolean(org.connection),
8088
+ conversion: conversionRate(org.subscription),
8089
+ id: org.id,
8090
+ name: org.name,
8091
+ plan: planTitle(org.subscription),
8092
+ status: ((_a2 = org.connection) == null ? void 0 : _a2.status) || null
8093
+ };
8094
+ });
8095
+ const connections2 = (owned || []).filter((org) => {
8096
+ var _a2;
8097
+ return ((_a2 = org.connection) == null ? void 0 : _a2.shop) === shop && org.connection.id;
8098
+ }).map((org) => org.connection.id);
8099
+ const [account, plan, unavailable] = await Promise.all([
8100
+ read.get({ collection: "user", query: { id: record.user } }),
8101
+ storePlan({ record, shopify }),
8102
+ connections2.length ? read.aggregate({
8103
+ collection: "product",
8104
+ pipeline: [
8105
+ { $match: { connections: { $in: connections2 }, "source.domain": shop, status: "inactive" } },
8106
+ // $facet so the app can name the first 25 AND report a
8107
+ // truthful total: listing 25 of 40 under "25 products need
8108
+ // attention" would understate the problem.
8109
+ {
8110
+ $facet: {
8111
+ items: [{ $sort: { title: 1 } }, { $limit: 25 }, { $project: { _id: 0, id: 1, title: 1 } }],
8112
+ total: [{ $count: "count" }]
8113
+ }
8114
+ }
8115
+ ]
8116
+ }) : []
8117
+ ]);
8118
+ const facet = (unavailable || [])[0] || {};
8119
+ if (plan.active && plan.metered !== true) {
8120
+ const stamped = await read.aggregate({
8121
+ collection: "connection",
8122
+ pipeline: [
8123
+ { $match: { shop, slug: "shopify" } },
8124
+ { $project: { _id: 0, "source.metered": 1 } }
8125
+ ]
8126
+ });
8127
+ const verdicts = (stamped || []).map((row2) => {
8128
+ var _a2;
8129
+ return (_a2 = row2 == null ? void 0 : row2.source) == null ? void 0 : _a2.metered;
8130
+ });
8131
+ if (verdicts.some((verdict) => typeof verdict === "string")) plan.metered = true;
8132
+ else if (verdicts.some((verdict) => verdict === null)) plan.metered = false;
8133
+ }
8134
+ return {
8135
+ message: organizations.length + " organization(s) for this store.",
8136
+ request: { shop },
8137
+ result: {
8138
+ account: { email: (account == null ? void 0 : account.email) || null },
8139
+ connected: true,
8140
+ organizations,
8141
+ plan,
8142
+ unavailableProducts: (facet.items || []).map((product) => ({
8143
+ id: product.id,
8144
+ title: product.title || "Untitled product"
8145
+ })),
8146
+ // The total can exceed the 25 listed above, and has to.
8147
+ unavailableProductsTotal: ((_a = (facet.total || [])[0]) == null ? void 0 : _a.count) || 0
8148
+ }
8149
+ };
8150
+ },
8151
+ // DISCONNECT ONE ORGANIZATION. The connection is deleted and nothing
8152
+ // else: every dependent — products, ads, steps, workflows, and the org's
8153
+ // own connection refs — is torn down by drawbridge-sync's connection
8154
+ // change stream. The shared token and the other orgs are untouched.
8155
+ remove: async ({ context }, { read } = {}) => {
8156
+ const organization = context == null ? void 0 : context.organization;
8157
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8158
+ if (!shop) throw refusal("shop is required", 400);
8159
+ if (!organization) throw refusal("organization is required", 400);
8160
+ const record = await read.get({ collection: "shop", query: { shop } });
8161
+ if (!(record == null ? void 0 : record.user)) throw refusal("Account is not connected for this store", 409);
8162
+ const owned = await merchantOrganizations({ read, user: record.user });
8163
+ if (!(owned || []).some((entry) => entry.id === organization)) {
8164
+ throw refusal("No access to this organization", 403);
8165
+ }
8166
+ const connection = await read.get({
8167
+ collection: "connection",
8168
+ query: { organization, shop, slug: "shopify" }
8169
+ });
8170
+ if (!connection) throw refusal("No connection to remove", 404);
8171
+ return {
8172
+ message: "Disconnected.",
8173
+ request: { organization, shop },
8174
+ result: { ok: true },
8175
+ writes: [{ collection: "connection", operation: "delete", query: { id: connection.id } }]
8176
+ };
8177
+ }
8178
+ },
8179
+ plan: {
8180
+ // RELEASE EVERY ACTIVE APPROVAL. The App Home then re-checks the plan
8181
+ // and falls back to "Choose a plan".
8182
+ cancel: ({ context }, { read, shopify = client } = {}) => releaseApprovals({ context, read, shopify }),
8183
+ // ONE ATTRIBUTED ORDER'S USAGE CHARGE. Enqueued per conversion by the
8184
+ // order step and run on a retrying queue, so this may be called
8185
+ // several times for one order — which is safe because the idempotency
8186
+ // key is PERMANENT for billing events and Shopify settles the repeat.
8187
+ //
8188
+ // THE HANDLE IS CHECKED AGAINST THE MANIFEST'S OWN DECLARATION, which
8189
+ // is a real strengthening of what it replaced: drawbridge-sync compared
8190
+ // the job's `handle` against the job's `transaction` — two fields from
8191
+ // the same enqueuer, so a drifted enqueuer agreed with itself. The
8192
+ // handle is the one string that decides whether the event bills at all,
8193
+ // and this is the file that publishes it.
8194
+ //
8195
+ // REFUSE BEFORE SENDING, because sending burns the order's PERMANENT
8196
+ // idempotency key on an event that misclassifies or mistraces. The
8197
+ // throw rides the queue's normal retry path and the abandoned-job alert
8198
+ // pages on exhaustion.
8199
+ //
8200
+ // DELIBERATELY NO TIMESTAMP. sendAppEvent defaults to the SEND time,
8201
+ // which is always inside the merchant's current billing cycle at the
8202
+ // moment of sending and so can never hit PERIOD_CLOSED. Pinning the
8203
+ // purchase time reads more correct and is strictly worse: a retry
8204
+ // backoff crossing a cycle boundary would carry a closed-cycle
8205
+ // timestamp, Shopify would 202-accept, silently drop it, and the
8206
+ // commission would be lost. Send-time's worst case is benign — the
8207
+ // charge lands in the next cycle, but it lands.
8208
+ charge: async ({ clientId, clientSecret, context, manifest }, { shopify = client } = {}) => {
8209
+ const { idempotencyKey, order, orderId, rate, revision, shopId, timestamp, transaction, value } = context || {};
8210
+ const handle = (context == null ? void 0 : context.handle) || manifest.auth.install.billing.handle;
8211
+ if (!transaction || !String(transaction).startsWith(handle + ".")) {
8212
+ throw new Error("shopify.usage.billing.handle.mismatch on order " + orderId + ": transaction " + (transaction || "null") + " does not carry handle " + handle + " \u2014 refusing to send");
8213
+ }
8214
+ await shopify.billing.sendAppEvent({
8215
+ clientId,
8216
+ clientSecret,
8217
+ eventHandle: handle,
8218
+ idempotencyKey,
8219
+ // The Shopify-side event record names the order that produced it.
8220
+ reference: transaction,
8221
+ // OPERATOR-ONLY, BOTH OF THEM, and absent on every automatic
8222
+ // send. `revision` suffixes the idempotency key, which is what
8223
+ // makes a second attempt possible once a key has been consumed;
8224
+ // the encoding is owned by sendAppEvent so no caller builds keys
8225
+ // itself. `timestamp` pins the PURCHASE time, which the automatic
8226
+ // path must never do — see the note above — and the recovery
8227
+ // migration must, because it is resending orders from a closed
8228
+ // window and bounds its own run to the merchant's current cycle.
8229
+ ...revision && { revision },
8230
+ ...timestamp && { timestamp },
8231
+ shopId,
8232
+ value
8233
+ });
8234
+ return {
8235
+ message: "Usage charge sent for order " + orderId + ".",
8236
+ request: { order: order || null, orderId: orderId || null, shopId: shopId || null, value },
8237
+ result: { transaction: String(transaction) },
8238
+ // TRACEABILITY. The App Events API returns no event id, so the
8239
+ // trace key into Shopify's event logs is the transaction id the
8240
+ // commerce.order hook minted and this sent as `reference`.
8241
+ // `amount` is the per-order usage value in cents, mirroring the
8242
+ // Stripe path's marker.
8243
+ ...order && { writes: [{
8244
+ collection: "order",
8245
+ data: {
8246
+ $set: {
8247
+ billed: {
8248
+ amount: value,
8249
+ date: /* @__PURE__ */ new Date(),
8250
+ rate: rate || 0,
8251
+ transaction: String(transaction)
8252
+ }
8253
+ }
8254
+ },
8255
+ operation: "update",
8256
+ query: { id: order }
8257
+ }] }
8258
+ };
8259
+ },
8260
+ // RESELECT, NOT CANCEL. The same mechanics — the current approval has to
8261
+ // be released before the pricing page will offer the plan again — but
8262
+ // the intent is a thirty-second round trip rather than a departure.
8263
+ //
8264
+ // `mark` IS A DECLARED CAPABILITY, and this is the only slot here that
8265
+ // needs one. The marker has to be persisted BEFORE the approval is
8266
+ // released: it is what tells sync's CANCELLED handler to hold the pause
8267
+ // — no connection error, no owner email — and start a timed recheck that
8268
+ // pauses honestly if the merchant abandons. A described write lands
8269
+ // after the hook returns, which is after the cancel, and a marker
8270
+ // written then can race the very webhook it exists to soften. Same
8271
+ // precedent as `resolveContact`: the one write a description cannot
8272
+ // carry.
8273
+ reselect: async ({ context }, { mark, read, shopify = client } = {}) => {
8274
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8275
+ if (!shop) throw refusal("shop is required", 400);
8276
+ await mark({ shop });
8277
+ return releaseApprovals({ context, read, shopify });
8278
+ },
8279
+ // IS THIS STORE'S ORDER BILLING ACTUALLY METERED? Not a merchant
8280
+ // action — the other two slots here are — but the same subject, and
8281
+ // the reason it is a declared hook rather than a helper is that the
8282
+ // answer was being derived in two places: `lifecycle.health` below,
8283
+ // and drawbridge-sync's app_subscriptions/update handler, whose copy
8284
+ // stated in its own comment that it matched this one and did not.
8285
+ //
8286
+ // THREE ANSWERS, and the caller must keep them apart:
8287
+ //
8288
+ // a string PROVEN. The charge id or usage line id, stamped on
8289
+ // the connection as the evidence.
8290
+ // null PROBED, and nothing is accruing.
8291
+ // undefined NO VERDICT — the probe could not run. `probed` says
8292
+ // which, because undefined does not survive JSON.
8293
+ verify: async ({ context }, { adminToken, read, shopify = client } = {}) => {
8294
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8295
+ if (!shop) throw refusal("shop is required", 400);
8296
+ const adminAccessToken = await adminToken();
8297
+ if (!adminAccessToken) {
8298
+ return { message: "No admin token for this store \u2014 no verdict.", request: { shop }, result: { metered: null, probed: false }, skipped: true };
8299
+ }
8300
+ const partnerRow = (read == null ? void 0 : read.get) ? await read.get({ collection: "provider", query: { slug: "shopify" } }) : null;
8301
+ const partner = (partnerRow == null ? void 0 : partnerRow.settings) ? decrypt(partnerRow.settings) : {};
8302
+ const { ledger, metered } = await meterVerdict({
8303
+ adminAccessToken,
8304
+ ledgerFloor: new Date(Date.now() - LEDGER_WINDOW_MS),
8305
+ partner,
8306
+ shop,
8307
+ shopId: (context == null ? void 0 : context.shopId) || null,
8308
+ shopify
8309
+ });
8310
+ return {
8311
+ message: typeof metered === "string" ? "Billing is metered." : "No meter evidence for this store.",
8312
+ request: { shop },
8313
+ // `probed` is the LEDGER, not the call: a store whose Partner
8314
+ // credentials are absent was not asked, and reporting that as
8315
+ // "probed, nothing accruing" would stamp an unmetered verdict on
8316
+ // a store nobody looked at.
8317
+ result: { metered: metered ?? null, probed: ledger || typeof metered === "string" }
8318
+ };
8319
+ }
8320
+ },
8321
+ // THE EMBEDDED APP'S SESSION STORE. The @shopify/shopify-app library
8322
+ // persists the offline session on token exchange and refresh; it lives
8323
+ // encrypted on the shared `shop` record, which is the same row every
8324
+ // organization's connection to this store points at.
8325
+ session: {
8326
+ // SOFT-CLEAR, NEVER A DELETE. The library calls this on session
8327
+ // invalidation and not only on uninstall, so hard-deleting the record
8328
+ // would orphan every org connection pointing at it — token resolution
8329
+ // silently nulls — and destroy the durable account link and the
8330
+ // storefront token with it. The next embedded load re-runs token
8331
+ // exchange. The full record delete belongs to the uninstall webhook.
8332
+ clear: async ({ context }) => {
8333
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8334
+ if (!shop) throw refusal("shop is required", 400);
8335
+ return {
8336
+ message: "Session cleared.",
8337
+ request: { shop },
8338
+ result: { ok: true },
8339
+ writes: [{
8340
+ collection: "shop",
8341
+ data: { $set: { settings: null } },
8342
+ operation: "update",
8343
+ query: { shop }
8344
+ }]
8345
+ };
8346
+ },
8347
+ read: async ({ context }, { read } = {}) => {
8348
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8349
+ if (!shop) throw refusal("shop is required", 400);
8350
+ const record = await read.get({ collection: "shop", query: { shop } });
8351
+ if (!(record == null ? void 0 : record.settings)) throw refusal("No session for this store", 404);
8352
+ return {
8353
+ message: "Session read.",
8354
+ request: { shop },
8355
+ result: { session: decrypt(record.settings) }
8356
+ };
8357
+ },
8358
+ save: async ({ context }) => {
8359
+ const session = context == null ? void 0 : context.session;
8360
+ const shop = sanitizeDomain(session == null ? void 0 : session.shop);
8361
+ if (!shop || !(session == null ? void 0 : session.accessToken)) throw refusal("session.shop and session.accessToken are required", 400);
8362
+ return {
8363
+ message: "Session saved.",
8364
+ request: { shop },
8365
+ result: { ok: true },
8366
+ writes: [{
8367
+ collection: "shop",
8368
+ data: {
8369
+ $set: { settings: encrypt(session), shop },
8370
+ $setOnInsert: { status: "pending" }
8371
+ },
8372
+ operation: "update",
8373
+ options: { upsert: true },
8374
+ query: { shop }
8375
+ }]
8376
+ };
8377
+ }
8378
+ },
8379
+ // THE LINK-TOKEN HANDOFF. The breakout callback runs top-level and can set
8380
+ // a first-party cookie; the embedded App Home cannot read that cookie from
8381
+ // inside the Shopify admin iframe. So the callback stashes the merchant's
8382
+ // user token here keyed by shop, and App Home reads it once and clears it.
8383
+ //
8384
+ // DURABLE RATHER THAN IN REDIS: a restart must not strand a merchant
8385
+ // mid-handoff. Short-lived and encrypted.
8386
+ token: {
8387
+ clear: async ({ context }) => {
8388
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8389
+ if (!shop) throw refusal("shop is required", 400);
8390
+ return {
8391
+ message: "Link token cleared.",
8392
+ request: { shop },
8393
+ result: { ok: true },
8394
+ writes: [{
8395
+ collection: "shop",
8396
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null } },
8397
+ operation: "update",
8398
+ query: { shop }
8399
+ }]
8400
+ };
8401
+ },
8402
+ read: async ({ context }, { read } = {}) => {
8403
+ var _a;
8404
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8405
+ if (!shop) throw refusal("shop is required", 400);
8406
+ const record = await read.get({ collection: "shop", query: { shop } });
8407
+ const expiresAt = (record == null ? void 0 : record.linkTokenExpiresAt) ? new Date(record.linkTokenExpiresAt) : null;
8408
+ if (!(record == null ? void 0 : record.linkToken) || !expiresAt || expiresAt <= /* @__PURE__ */ new Date()) {
8409
+ throw refusal("No link token for this store", 404);
8410
+ }
8411
+ return {
8412
+ message: "Link token read.",
8413
+ request: { shop },
8414
+ result: { token: ((_a = decrypt(record.linkToken)) == null ? void 0 : _a.token) ?? null }
8415
+ };
8416
+ },
8417
+ save: async ({ context }) => {
8418
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8419
+ const token = context == null ? void 0 : context.token;
8420
+ if (!shop || !token) throw refusal("shop and token are required", 400);
8421
+ return {
8422
+ message: "Link token saved.",
8423
+ request: { shop },
8424
+ result: { ok: true },
8425
+ writes: [{
8426
+ collection: "shop",
8427
+ data: {
8428
+ $set: {
8429
+ linkToken: encrypt({ token }),
8430
+ linkTokenExpiresAt: new Date(Date.now() + LINK_TOKEN_TTL_MS)
8431
+ }
8432
+ },
8433
+ operation: "update",
8434
+ query: { shop }
8435
+ }]
8436
+ };
8437
+ }
8438
+ }
8439
+ },
5723
8440
  // Drawbridge sends its own notification email and SMS — see the private
5724
8441
  // `drawbridge` manifest. A vendor answering these would be a second sender,
5725
8442
  // which is the arrangement the platform sender replaced.
@@ -5781,8 +8498,8 @@ var shopify_default2 = {
5781
8498
  // access token still works, reconciles the scopes the store granted
5782
8499
  // against the ones the app now needs, and queues a webhook
5783
8500
  // reconciliation.
5784
- health: async ({ connection, workflow }, { adminToken, logger, read, reconcileScopes, resolveSettings, rotateToken, shopify } = {}) => {
5785
- var _a, _b, _c, _d, _e, _f;
8501
+ health: async ({ connection, workflow }, { adminToken, logger, read, reconcileScopes, resolveSettings, rotateToken, shopify = client } = {}) => {
8502
+ var _a, _b, _c, _d;
5786
8503
  const request2 = {
5787
8504
  connectionId: workflow.connection,
5788
8505
  organizationId: workflow.organization,
@@ -5819,33 +8536,26 @@ var shopify_default2 = {
5819
8536
  shopCurrency = String(shopData.currency || "").toLowerCase() || null;
5820
8537
  sourceRepaired = true;
5821
8538
  }
5822
- const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
5823
- adminAccessToken,
5824
- domain: connection.shop
5825
- });
5826
- const usageLine = (_a = subscriptions.find((subscription) => subscription.usageLineItemId)) == null ? void 0 : _a.usageLineItemId;
5827
- if (usageLine) metered = usageLine;
5828
8539
  const partnerRow = (read == null ? void 0 : read.get) ? await read.get({ collection: "provider", query: { slug: "shopify" } }) : null;
5829
8540
  const partner = (partnerRow == null ? void 0 : partnerRow.settings) ? decrypt(partnerRow.settings) : {};
5830
- if (partner.partnerToken && partner.partnerOrgId && partner.partnerAppId && (source == null ? void 0 : source.id) && ((_b = shopify.partner) == null ? void 0 : _b.getUsageChargeEvents)) {
5831
- const ledgerFloor = new Date(Date.now() - 30 * 24 * 60 * 60 * 1e3);
5832
- const accruals = await shopify.partner.getUsageChargeEvents({
5833
- appId: "gid://shopify/App/" + partner.partnerAppId,
5834
- first: 10,
5835
- occurredAtMin: ledgerFloor.toISOString(),
5836
- organizationId: partner.partnerOrgId,
5837
- partnerToken: partner.partnerToken,
5838
- shopId: "gid://shopify/Shop/" + source.id
5839
- });
5840
- const boundaries = accruals.filter((event) => event.occurredAt).sort((a, b) => new Date(a.occurredAt) - new Date(b.occurredAt));
5841
- const accrued = [...boundaries].reverse().find((event) => Number(event.usageQuantity) > 0);
5842
- if (accrued) metered = String(accrued.chargeId || accrued.id);
5843
- const stampedAt = (_c = boundaries.find(
8541
+ const ledgerFloor = new Date(Date.now() - LEDGER_WINDOW_MS);
8542
+ const verdict = await meterVerdict({
8543
+ adminAccessToken,
8544
+ ledgerFloor,
8545
+ partner,
8546
+ shop: connection.shop,
8547
+ shopId: source == null ? void 0 : source.id,
8548
+ shopify
8549
+ });
8550
+ if (verdict.metered !== void 0) metered = verdict.metered;
8551
+ const { boundaries } = verdict;
8552
+ if (boundaries.length) {
8553
+ const stampedAt = (_a = boundaries.find(
5844
8554
  (event) => {
5845
8555
  var _a2;
5846
8556
  return String(event.chargeId || event.id) === String(((_a2 = connection.source) == null ? void 0 : _a2.metered) || "");
5847
8557
  }
5848
- )) == null ? void 0 : _c.occurredAt;
8558
+ )) == null ? void 0 : _a.occurredAt;
5849
8559
  reconciliation = [];
5850
8560
  let windowStart = ledgerFloor;
5851
8561
  for (const boundary of boundaries) {
@@ -5895,7 +8605,7 @@ var shopify_default2 = {
5895
8605
  }
5896
8606
  });
5897
8607
  } else {
5898
- (_d = logger == null ? void 0 : logger.error) == null ? void 0 : _d.call(logger, new Error(
8608
+ (_b = logger == null ? void 0 : logger.error) == null ? void 0 : _b.call(logger, new Error(
5899
8609
  "shopify.usage.reconciliation.mismatch on shop " + connection.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"
5900
8610
  ), {
5901
8611
  extra: {
@@ -5914,13 +8624,13 @@ var shopify_default2 = {
5914
8624
  }
5915
8625
  } catch (probeError) {
5916
8626
  billingProbeFailed = true;
5917
- (_e = logger == null ? void 0 : logger.warn) == null ? void 0 : _e.call(logger, "shopify.health.billing.probe.failed", {
8627
+ (_c = logger == null ? void 0 : logger.warn) == null ? void 0 : _c.call(logger, "shopify.health.billing.probe.failed", {
5918
8628
  connectionId: connection.id,
5919
8629
  message: probeError == null ? void 0 : probeError.message,
5920
8630
  shop: connection.shop
5921
8631
  });
5922
8632
  }
5923
- if (sourceRepaired || metered !== void 0 && metered !== (((_f = connection.source) == null ? void 0 : _f.metered) ?? void 0)) {
8633
+ if (sourceRepaired || metered !== void 0 && metered !== (((_d = connection.source) == null ? void 0 : _d.metered) ?? void 0)) {
5924
8634
  writes.push({
5925
8635
  collection: "connection",
5926
8636
  data: {
@@ -6055,13 +8765,13 @@ var shopify_default2 = {
6055
8765
  // They are the same two questions every other vendor answers through
6056
8766
  // resources.*, so they answer them the same way now.
6057
8767
  //
6058
- // `shopify` is INJECTED: this package cannot import @drawbridge/shopify,
8768
+ // `shopify` DEFAULTS to the client this file imports; nothing injects it,
6059
8769
  // which depends on it. What arrives is the SDK's pure HTTP namespaces
6060
8770
  // and nothing else — no controller, no collection access. Resolving the
6061
8771
  // credential is the caller's job because it is Drawbridge's job: the
6062
8772
  // admin token refreshes and writes itself back, which is service work,
6063
8773
  // not vendor work.
6064
- products: async ({ cursor, limit = 100, search, settings, sort }, { shopify } = {}) => {
8774
+ products: async ({ cursor, limit = 100, search, settings, sort }, { shopify = client } = {}) => {
6065
8775
  var _a, _b, _c, _d;
6066
8776
  const products = await shopify.storefront.getProducts({
6067
8777
  cursor,
@@ -6083,7 +8793,7 @@ var shopify_default2 = {
6083
8793
  }
6084
8794
  };
6085
8795
  },
6086
- promotions: async ({ cursor, limit = 100, search, settings }, { shopify } = {}) => {
8796
+ promotions: async ({ cursor, limit = 100, search, settings }, { shopify = client } = {}) => {
6087
8797
  var _a, _b;
6088
8798
  const discounts = await shopify.admin.getDiscounts({
6089
8799
  adminAccessToken: settings == null ? void 0 : settings.adminAccessToken,
@@ -6234,6 +8944,13 @@ var shopify_default2 = {
6234
8944
  key: "Shopify Order Tracking",
6235
8945
  queue: "connection",
6236
8946
  system: true,
8947
+ // THE TRIGGER THE REGISTER JOB HAND-WROTE. It is byte-identical to
8948
+ // the one on every stored workflow, because these documents exist on
8949
+ // prod with thousands of runs behind them and provisioning is
8950
+ // idempotent on (connection, system, title) — a different trigger
8951
+ // here would not be picked up by the existing rows anyway, and a
8952
+ // different TITLE would provision a second workflow for every store.
8953
+ trigger: { event: "shopify.order.create", type: "webhook" },
6237
8954
  type: "step.commerce.order.record"
6238
8955
  })
6239
8956
  },
@@ -6244,6 +8961,15 @@ var shopify_default2 = {
6244
8961
  key: "Shopify Product Sync",
6245
8962
  queue: "connection",
6246
8963
  system: true,
8964
+ // `shopify.product.update`, NOT `product.insert`. The plan named the
8965
+ // latter, and it is the right long-term answer — a Drawbridge product
8966
+ // row appearing should pull the vendor's copy, rather than
8967
+ // stream/product.js branching on the slug and enqueueing a
8968
+ // vendor-named queue. But a workflow carries ONE trigger, this one is
8969
+ // stored on prod against the webhook, and changing a live workflow's
8970
+ // trigger is a data migration. So the declaration matches what exists
8971
+ // and `product.insert` stays a separate, migration-gated change.
8972
+ trigger: { event: "shopify.product.update", type: "webhook" },
6247
8973
  type: "step.commerce.product.sync"
6248
8974
  })
6249
8975
  }
@@ -6265,26 +8991,37 @@ var shopify_default2 = {
6265
8991
  type: "step.connection.health.check"
6266
8992
  })
6267
8993
  },
6268
- // Audit-only. The "Shopify Token Activity" system workflow lists these
6269
- // for descriptive grouping, but its audit step docs are written manually
6270
- // at OAuth time — the workflow is never dispatched. Routing is declared
6271
- // defensively so that if it ever IS dispatched, the job lands on a real
6272
- // queue and the handler lookup misses cleanly instead of throwing
6273
- // "Unknown step type".
8994
+ // THE ONE WORKFLOW THAT CARRIES TWO STEPS, and the shape the plan called
8995
+ // the single genuinely new thing in it.
8996
+ //
8997
+ // Every other system step is its own workflow, titled by its own `key`.
8998
+ // These two are "Shopify Token Activity", one row in the merchant's list
8999
+ // with both steps in it — so they declare `workflow`, which names the
9000
+ // title, the trigger and the ORDER, and the provisioner groups on it.
9001
+ // Without that key the pair could only be provisioned by the hand-written
9002
+ // spec in drawbridge-sync's register job, which is exactly why that spec
9003
+ // outlived every other one.
9004
+ //
9005
+ // AUDIT-ONLY. The step documents are written manually at OAuth time and
9006
+ // the workflow is never dispatched; `queue` is declared defensively so
9007
+ // that if it ever IS, the job lands on a real queue and the handler lookup
9008
+ // misses cleanly rather than throwing "Unknown step type".
6274
9009
  token: {
6275
9010
  exchange: () => ({
6276
9011
  description: "Records the token exchange that completed an install. Audit only \u2014 never dispatched.",
6277
9012
  key: "Shopify Token Exchange",
6278
9013
  queue: "connection",
6279
9014
  system: true,
6280
- type: "step.connection.token.exchange"
9015
+ type: "step.connection.token.exchange",
9016
+ workflow: { key: "Shopify Token Activity", order: 0, trigger: { event: "shopify.token", type: "event" } }
6281
9017
  }),
6282
9018
  refresh: () => ({
6283
9019
  description: "Records a token rotation. Audit only \u2014 never dispatched.",
6284
9020
  key: "Shopify Token Refresh",
6285
9021
  queue: "connection",
6286
9022
  system: true,
6287
- type: "step.connection.token.refresh"
9023
+ type: "step.connection.token.refresh",
9024
+ workflow: { key: "Shopify Token Activity", order: 1, trigger: { event: "shopify.token", type: "event" } }
6288
9025
  })
6289
9026
  }
6290
9027
  }
@@ -6588,14 +9325,15 @@ var webhook_default = {
6588
9325
  "Drawbridge can POST event payloads to your endpoint as activity happens in your account, so your own systems can react to it.",
6589
9326
  "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."
6590
9327
  ],
6591
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
6592
- // The dashboard already carries generic reasons for every way an
6593
- // authorization can fail declined, expired state, a vendor we are not set
6594
- // up for and a sentence here is an ADDITION to those, for a vendor whose
6595
- // failures need saying differently. This one's do not.
9328
+ // THERE IS NO CONSENT SCREEN TO FAIL. Connecting mints a signing secret;
9329
+ // nothing is authorized against a third party, so neither `denied` nor
9330
+ // `invalid` has a state it could describe. The failures this connection
9331
+ // really has are at DELIVERY a merchant's endpoint refusing a POST and
9332
+ // those reach them through the connection's own errors rather than through
9333
+ // connect copy.
6596
9334
  //
6597
- // Answered rather than omitted, because `errors` existed on two of six
6598
- // manifests and there was no way to tell "nothing to add" from "nobody
9335
+ // `false` is the recorded decision, not silence: `errors` existed on two of
9336
+ // six manifests and there was no way to tell "nothing to add" from "nobody
6599
9337
  // wrote it".
6600
9338
  errors: false,
6601
9339
  excerpt: "Sign outgoing webhook payloads with an HMAC secret to verify authenticity.",
@@ -6739,7 +9477,7 @@ var webhook_default = {
6739
9477
  // The connect prompt only where connecting is not already the card's whole
6740
9478
  // story: a disconnected or errored document renders a Connect action itself,
6741
9479
  // and a task repeating it talks over the button.
6742
- tasks: ({ settings, status } = {}) => ["disconnected", "error"].includes(status) ? [] : (settings == null ? void 0 : settings.secret) ? [
9480
+ tasks: ({ settings, status } = {}) => status === "error" ? [] : (settings == null ? void 0 : settings.secret) ? [
6743
9481
  {
6744
9482
  message: 'Compute HMAC-SHA256( secret, t + "." + raw body ) and constant-time compare it against a v1 in the X-Drawbridge-Signature header; reject timestamps older than five minutes.',
6745
9483
  title: "Requests must be verified",
@@ -6826,6 +9564,77 @@ var attentive_default3 = {
6826
9564
  }
6827
9565
  };
6828
9566
 
9567
+ // lib/connections/icons/brightdata.js
9568
+ var brightdata_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
9569
+ <rect width="500" height="500" fill="#0F58FF"/>
9570
+ <circle cx="250" cy="250" r="52" fill="white"/>
9571
+ <rect x="234" y="70" width="32" height="96" rx="16" fill="white"/>
9572
+ <rect x="234" y="334" width="32" height="96" rx="16" fill="white"/>
9573
+ <rect x="70" y="234" width="96" height="32" rx="16" fill="white"/>
9574
+ <rect x="334" y="234" width="96" height="32" rx="16" fill="white"/>
9575
+ <rect x="117" y="140" width="32" height="96" rx="16" transform="rotate(-45 117 140)" fill="white"/>
9576
+ <rect x="304" y="327" width="32" height="96" rx="16" transform="rotate(-45 304 327)" fill="white"/>
9577
+ <rect x="360" y="117" width="32" height="96" rx="16" transform="rotate(45 360 117)" fill="white"/>
9578
+ <rect x="173" y="304" width="32" height="96" rx="16" transform="rotate(45 173 304)" fill="white"/>
9579
+ </svg>`;
9580
+
9581
+ // lib/connections/vendors/brightdata.js
9582
+ var brightdata_default2 = {
9583
+ fields: [
9584
+ {
9585
+ credential: "BRIGHTDATA_BROWSER_URI",
9586
+ input: "password",
9587
+ key: "browserUri",
9588
+ // A wss:// endpoint with the account's user and password in its
9589
+ // authority, which is why it is a password field rather than a url one:
9590
+ // the whole string is the credential.
9591
+ label: "Scraping Browser endpoint",
9592
+ message: "The wss:// Scraping Browser endpoint, carrying its own credentials. Used to render pages that need a real browser.",
9593
+ redact: true,
9594
+ required: true
9595
+ },
9596
+ {
9597
+ credential: "BRIGHTDATA_UNLOCKER_API_KEY",
9598
+ input: "password",
9599
+ key: "unlockerApiKey",
9600
+ label: "Web Unlocker API key",
9601
+ // NO EXPIRY FIELD, and that is a decision rather than an omission. Bright
9602
+ // Data offers an `Unlimited` expiry and recommends against it; Drawbridge
9603
+ // takes the unlimited key deliberately, because there is no way to rotate
9604
+ // this programmatically and a date nothing can act on is a date that only
9605
+ // surfaces after it has already broken scraping. If a fixed expiry is ever
9606
+ // taken instead, the field to add is a stored date and a warning ahead of
9607
+ // it — not a rotation, which the vendor cannot support.
9608
+ message: "Bright Data account settings \u2192 API keys. Taken with an unlimited expiry: their API offers no way to rotate a key, so a dated one can only ever break scraping silently.",
9609
+ redact: true,
9610
+ required: true
9611
+ },
9612
+ {
9613
+ credential: "BRIGHTDATA_UNLOCKER_ZONE",
9614
+ input: "text",
9615
+ key: "unlockerZone",
9616
+ label: "Web Unlocker zone",
9617
+ // Not secret — a zone is a label on the account, and it is shown rather
9618
+ // than redacted so an operator can confirm which one is in use without
9619
+ // clearing the field to read it.
9620
+ message: "The zone name the Unlocker requests run against.",
9621
+ required: true
9622
+ }
9623
+ ],
9624
+ icon: brightdata_default,
9625
+ name: "Bright Data",
9626
+ slug: "brightdata",
9627
+ // WHERE THE FACTS CAME FROM, read 2026-09-16.
9628
+ urls: {
9629
+ api: "https://docs.brightdata.com/api-reference/authentication",
9630
+ dashboard: "https://brightdata.com/cp/setting/users",
9631
+ // Bright Data has no scope model — a key carries the account's own access —
9632
+ // so there is nothing to link. `false` is the recorded answer rather than a
9633
+ // missing key.
9634
+ scopes: false
9635
+ }
9636
+ };
9637
+
6829
9638
  // lib/connections/vendors/hubspot.js
6830
9639
  var hubspot_default2 = {
6831
9640
  // WHAT AN ADMIN TYPES on the provider screen. `credential` names the env var a
@@ -7201,7 +10010,7 @@ var checkIcon = (owner, icon) => {
7201
10010
  }
7202
10011
  };
7203
10012
  var vendors = Object.freeze(Object.fromEntries(
7204
- [attentive_default3, hubspot_default2, klaviyo_default3, mailchimp_default3, sendgrid_default2, shopify_default3, twilio_default2].map((vendor) => [vendor.slug, vendor])
10013
+ [attentive_default3, brightdata_default2, hubspot_default2, klaviyo_default3, mailchimp_default3, sendgrid_default2, shopify_default3, twilio_default2].map((vendor) => [vendor.slug, vendor])
7205
10014
  ));
7206
10015
  var buildVendor = (vendor) => {
7207
10016
  if (!(vendor == null ? void 0 : vendor.slug)) throw new Error("A vendor needs a slug");
@@ -7228,7 +10037,7 @@ for (const [slug2, vendor] of Object.entries(vendors)) {
7228
10037
  buildVendor(vendor);
7229
10038
  }
7230
10039
  var build = (manifest) => {
7231
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
10040
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y;
7232
10041
  if (!(manifest == null ? void 0 : manifest.slug)) throw new Error("A connection needs a slug");
7233
10042
  if (!(manifest == null ? void 0 : manifest.title)) throw new Error(manifest.slug + " needs a title");
7234
10043
  if (manifest == null ? void 0 : manifest.private) throw new Error(manifest.slug + " declares private \u2014 that is feature : false now");
@@ -7494,11 +10303,22 @@ var build = (manifest) => {
7494
10303
  manifest.slug + " step " + type2 + " may be triggered by " + trigger + ", which is not a trigger \u2014 one of " + Object.keys(TRIGGERS).join(", ")
7495
10304
  );
7496
10305
  }
7497
- if (declared2.trigger) {
7498
- const known2 = TRIGGERS[Object.keys(TRIGGERS).find((key) => TRIGGERS[key].event === declared2.trigger.event && TRIGGERS[key].type === declared2.trigger.type)];
10306
+ if (declared2.workflow) {
10307
+ if (!declared2.workflow.key) {
10308
+ throw new Error(manifest.slug + " step " + type2 + " declares a workflow with no key \u2014 the title several steps share");
10309
+ }
10310
+ if (typeof declared2.workflow.order !== "number") {
10311
+ throw new Error(manifest.slug + " step " + type2 + " declares a workflow with no order \u2014 two steps in one row need a sequence");
10312
+ }
10313
+ if (declared2.trigger) {
10314
+ throw new Error(manifest.slug + " step " + type2 + " declares BOTH a trigger and a workflow \u2014 the workflow carries the trigger for every step in it");
10315
+ }
10316
+ }
10317
+ for (const candidate of [declared2.trigger, (_y = declared2.workflow) == null ? void 0 : _y.trigger].filter(Boolean)) {
10318
+ const known2 = TRIGGERS[Object.keys(TRIGGERS).find((key) => TRIGGERS[key].event === candidate.event && TRIGGERS[key].type === candidate.type)];
7499
10319
  if (!known2) {
7500
10320
  throw new Error(
7501
- manifest.slug + " step " + type2 + " declares trigger { event : " + declared2.trigger.event + ", type : " + declared2.trigger.type + " }, which nothing dispatches"
10321
+ manifest.slug + " step " + type2 + " declares trigger { event : " + candidate.event + ", type : " + candidate.type + " }, which nothing dispatches"
7502
10322
  );
7503
10323
  }
7504
10324
  }