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