@drawbridge/drawbridge-utils 0.0.176 → 0.0.177

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/admin-B9ZaLvan.d.cts +697 -0
  2. package/dist/admin-C3HtEM6h.d.ts +697 -0
  3. package/dist/billing-Bc4yo9XG.d.cts +175 -0
  4. package/dist/billing-mNsKflmQ.d.ts +175 -0
  5. package/dist/billing.d.cts +1 -1
  6. package/dist/billing.d.ts +1 -1
  7. package/dist/connections/index.cjs +3077 -228
  8. package/dist/connections/index.d.cts +13 -4
  9. package/dist/connections/index.d.ts +13 -4
  10. package/dist/connections/index.js +3107 -255
  11. package/dist/features.cjs +2940 -226
  12. package/dist/features.d.cts +13 -4
  13. package/dist/features.d.ts +13 -4
  14. package/dist/features.js +2980 -260
  15. package/dist/http.cjs +10 -1
  16. package/dist/http.d.cts +10 -1
  17. package/dist/http.d.ts +10 -1
  18. package/dist/http.js +10 -1
  19. package/dist/{index-B8JhYfvU.d.ts → index-B546oDNo.d.ts} +2837 -956
  20. package/dist/{index-qY18QITf.d.cts → index-C59xHago.d.cts} +2837 -956
  21. package/dist/oauth/index.d.cts +1 -1
  22. package/dist/oauth/index.d.ts +1 -1
  23. package/dist/oauth-BJDh0sdM.d.cts +527 -0
  24. package/dist/oauth-DveZMLHx.d.ts +527 -0
  25. package/dist/partner-BOZltuh2.d.ts +94 -0
  26. package/dist/partner-ed2OfW1J.d.cts +94 -0
  27. package/dist/plans.cjs +2939 -225
  28. package/dist/plans.d.cts +13 -4
  29. package/dist/plans.d.ts +13 -4
  30. package/dist/plans.js +2980 -260
  31. package/dist/pricing.cjs +2972 -258
  32. package/dist/pricing.d.cts +13 -4
  33. package/dist/pricing.d.ts +13 -4
  34. package/dist/pricing.js +2977 -257
  35. package/dist/providers.cjs +2942 -247
  36. package/dist/providers.d.cts +12 -3
  37. package/dist/providers.d.ts +12 -3
  38. package/dist/providers.js +2946 -245
  39. package/dist/sendgrid.cjs +10 -1
  40. package/dist/sendgrid.js +10 -1
  41. package/dist/shopify/admin.cjs +562 -0
  42. package/dist/shopify/admin.d.cts +3 -0
  43. package/dist/shopify/admin.d.ts +3 -0
  44. package/dist/shopify/admin.js +528 -0
  45. package/dist/shopify/billing.cjs +166 -0
  46. package/dist/shopify/billing.d.cts +3 -0
  47. package/dist/shopify/billing.d.ts +3 -0
  48. package/dist/shopify/billing.js +140 -0
  49. package/dist/shopify/constants.cjs +63 -0
  50. package/dist/shopify/constants.d.cts +58 -0
  51. package/dist/shopify/constants.d.ts +58 -0
  52. package/dist/shopify/constants.js +32 -0
  53. package/dist/shopify/oauth.cjs +509 -0
  54. package/dist/shopify/oauth.d.cts +7 -0
  55. package/dist/shopify/oauth.d.ts +7 -0
  56. package/dist/shopify/oauth.js +466 -0
  57. package/dist/shopify/partner.cjs +156 -0
  58. package/dist/shopify/partner.d.cts +3 -0
  59. package/dist/shopify/partner.d.ts +3 -0
  60. package/dist/shopify/partner.js +130 -0
  61. package/dist/shopify/storefront.cjs +611 -0
  62. package/dist/shopify/storefront.d.cts +3 -0
  63. package/dist/shopify/storefront.d.ts +3 -0
  64. package/dist/shopify/storefront.js +576 -0
  65. package/dist/storefront-C8FKOGeD.d.cts +659 -0
  66. package/dist/storefront-DJFGLqPl.d.ts +659 -0
  67. package/dist/twilio.cjs +10 -1
  68. package/dist/twilio.js +10 -1
  69. package/package.json +98 -68
@@ -1,3 +1,9 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
1
7
  // lib/connections/contract.js
2
8
  var HOOKS = Object.freeze({
3
9
  // Proving and holding the credential.
@@ -124,6 +130,10 @@ var HOOKS = Object.freeze({
124
130
  "code",
125
131
  // Create the buyer at the vendor, so an order can be attributed to them.
126
132
  "customer",
133
+ // HOW MANY OF THIS PRODUCT ARE LEFT, at the vendor. Read at the moment a
134
+ // campaign's product list is rendered rather than stored, because stock is
135
+ // the one product fact that is stale the instant it is written down.
136
+ "inventory",
127
137
  // An order arrived at the vendor: attribute it, record it, update totals.
128
138
  "order",
129
139
  // Pull product data across on a vendor update.
@@ -191,7 +201,19 @@ var HOOKS = Object.freeze({
191
201
  organizations: Object.freeze(["add", "list", "remove"]),
192
202
  // What the merchant pays the VENDOR. Pairs with auth.install.billing, which
193
203
  // declares the plan they are being charged on.
194
- plan: Object.freeze(["cancel", "reselect"]),
204
+ //
205
+ // `verify` is the odd one of the three: not something a merchant does, but
206
+ // the question "is this store's billing actually metered right now". It is
207
+ // here because it is the same subject — and because the answer was being
208
+ // derived in TWO places, the vendor's health check and drawbridge-sync's
209
+ // approval webhook, whose copy said in its own comment that it matched the
210
+ // other and did not.
211
+ // `charge` and `verify` are the two that are not merchant actions: one
212
+ // sends a usage charge to the vendor's meter, the other asks whether that
213
+ // meter is actually working. Both are here because both are the same
214
+ // subject — what the merchant pays the vendor — and both were being done
215
+ // from drawbridge-sync with a direct import of the vendor's client.
216
+ plan: Object.freeze(["cancel", "charge", "reselect", "verify"]),
195
217
  // The embedded app's own session, stored by us on the vendor's behalf.
196
218
  session: Object.freeze(["clear", "read", "save"]),
197
219
  // The one-time code that hands a merchant from the embedded app into
@@ -288,7 +310,7 @@ var answerOf = (answer) => {
288
310
  return effectsOf(answer);
289
311
  };
290
312
  var WRITE_OPERATIONS = Object.freeze(["create", "delete", "update"]);
291
- var INSTALL_SIGNATURE = Object.freeze({ options: ["read", "request"], props: ["context"] });
313
+ var INSTALL_SIGNATURE = Object.freeze({ options: ["read"], props: ["context"] });
292
314
  var LIFECYCLE_SIGNATURE = Object.freeze({ options: ["dispatch"], props: ["context"] });
293
315
  var RESOURCE_SIGNATURE = Object.freeze({
294
316
  options: ["fetcher", "shopify"],
@@ -305,15 +327,30 @@ var HOOK_SLOT_PROPS = Object.freeze({
305
327
  // the second bag would be silently discarded, which is exactly the
306
328
  // stubbed-fetcher-reaches-production failure the split exists to prevent.
307
329
  "auth.token": false,
308
- // COMMERCE. `cart` is declared and unimplemented the Checkout Kit path in
309
- // api/route/subdomain.js writes nothing, which is why it never became a hook
310
- // so its signature mirrors `code`, its nearest sibling, and moving the
311
- // route here is a deliberate widening of this line rather than a silent one.
312
- "commerce.cart": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context", "step"] }),
330
+ // COMMERCE. `cart` is the odd one: it runs for a SHOPPER on a public page,
331
+ // not for an organization inside a workflow, so it takes no `connection` and
332
+ // no `step`. It reads the storefront with the store's own storefront token
333
+ // and mints a checkout token from DRAWBRIDGE'S app credentials, which is why
334
+ // `clientId`/`clientSecret` are here as props, the way auth.disconnect
335
+ // already carries them, because a credential is a fact of the run rather
336
+ // than a service.
337
+ "commerce.cart": Object.freeze({
338
+ options: ["fetcher", "shopify"],
339
+ props: ["clientId", "clientSecret", "context", "settings"]
340
+ }),
313
341
  "commerce.code": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context", "step"] }),
314
342
  "commerce.customer": Object.freeze({ options: ["adminToken", "read", "shopify"], props: ["connection", "context"] }),
343
+ "commerce.inventory": Object.freeze({ options: ["adminToken", "shopify"], props: ["connection", "context"] }),
315
344
  "commerce.order": Object.freeze({ options: ["conversionRate", "logger", "mintId", "read"], props: ["connection", "context"] }),
316
- "commerce.product": Object.freeze({ options: ["mintId", "read"], props: ["connection", "context", "workflow"] }),
345
+ // THREE OPERATIONS, one slot — record, sync, variants. `settings` and
346
+ // `adminToken` arrived with the pull half: the storefront read needs the
347
+ // store's storefront token and the product-feedback send needs its admin one,
348
+ // and both are resolved by the caller because minting either needs a
349
+ // controller.
350
+ "commerce.product": Object.freeze({
351
+ options: ["adminToken", "mintId", "read", "shopify"],
352
+ props: ["connection", "context", "settings", "workflow"]
353
+ }),
317
354
  // THE ADDRESS IS `contact` IN BOTH, and the shell already says why: it is the
318
355
  // person, not the lead document. `remove` called it `email` and `sync` called
319
356
  // it `doc` on one vendor and `lead` on three — three names for two facts.
@@ -326,19 +363,58 @@ var HOOK_SLOT_PROPS = Object.freeze({
326
363
  "inbound.process": Object.freeze({ options: ["dispatch"], props: ["context"] }),
327
364
  "inbound.receive": Object.freeze({ options: [], props: ["channel", "event", "headers", "payload"] }),
328
365
  "inbound.verify": Object.freeze({ options: [], props: ["body", "channel", "headers", "secret", "url"] }),
329
- // INSTALL — thirteen slots, none implemented yet. They are what the thirteen
330
- // routes in api/route/shopify-embedded.js become, and the signature is
331
- // deliberately narrow: `context` is the request's own body, `read` and
332
- // `request` are the only services an install surface has been shown to need.
333
- // A route that cannot be expressed inside this line is a finding to bring
334
- // back here, not a name to add at the call site.
366
+ // INSTALL — thirteen slots, and they are the thirteen routes that used to be
367
+ // api/route/shopify-embedded.js. `context` is the request's own body in all
368
+ // of them; the options are where they differ, and every difference below was
369
+ // forced by a line in those routes rather than chosen.
370
+ //
371
+ // SEVEN NEED NOTHING BUT `read`. The two session slots that write, the two
372
+ // token slots that write, the two clears, and both account slots answer from
373
+ // the shared install record alone.
374
+ //
375
+ // SIX TAKE MORE, and the widenings are worth naming because each is a fact
376
+ // Drawbridge owns that the manifest must not:
377
+ //
378
+ // conversionRate, planTitle what Drawbridge charges this organization.
379
+ // The org list renders both, and importing the
380
+ // plan catalogue here is the cycle
381
+ // features -> connections -> shopify -> plans
382
+ // -> features that was just broken.
383
+ // currencies which settlement currencies Drawbridge can
384
+ // bill. A store outside them fails the
385
+ // connection validator INSIDE the transaction,
386
+ // which surfaces as an opaque 500, so `add`
387
+ // checks first and says so.
388
+ // mintId the connection's id, known before the write
389
+ // that creates it, because the organization's
390
+ // own refs have to name it in the same
391
+ // transaction.
392
+ // shopify the vendor. Four slots call the store: two
393
+ // read the live plan, two release it.
394
+ // mark THE ONE WRITE A DESCRIPTION CANNOT CARRY, and
395
+ // `reselect` is the only slot with one. See its
396
+ // implementation for why the order is the point.
335
397
  "install.account.link": INSTALL_SIGNATURE,
336
398
  "install.account.unlink": INSTALL_SIGNATURE,
337
- "install.organizations.add": INSTALL_SIGNATURE,
338
- "install.organizations.list": INSTALL_SIGNATURE,
399
+ "install.organizations.add": Object.freeze({
400
+ options: ["currencies", "mintId", "read", "shopify"],
401
+ props: ["context"]
402
+ }),
403
+ "install.organizations.list": Object.freeze({
404
+ options: ["conversionRate", "planTitle", "read", "shopify"],
405
+ props: ["context"]
406
+ }),
339
407
  "install.organizations.remove": INSTALL_SIGNATURE,
340
- "install.plan.cancel": INSTALL_SIGNATURE,
341
- "install.plan.reselect": INSTALL_SIGNATURE,
408
+ "install.plan.cancel": Object.freeze({ options: ["read", "shopify"], props: ["context"] }),
409
+ // `manifest` because the handle this charge bills under is the vendor's own
410
+ // declaration (auth.install.billing.handle), and checking the job against the
411
+ // declaration is what the enqueuer-checks-itself version could not do.
412
+ "install.plan.charge": Object.freeze({
413
+ options: ["shopify"],
414
+ props: ["clientId", "clientSecret", "context", "manifest"]
415
+ }),
416
+ "install.plan.reselect": Object.freeze({ options: ["mark", "read", "shopify"], props: ["context"] }),
417
+ "install.plan.verify": Object.freeze({ options: ["adminToken", "read", "shopify"], props: ["context"] }),
342
418
  "install.session.clear": INSTALL_SIGNATURE,
343
419
  "install.session.read": INSTALL_SIGNATURE,
344
420
  "install.session.save": INSTALL_SIGNATURE,
@@ -544,6 +620,181 @@ var isStatus = (status) => STATUSES.includes(status);
544
620
  // lib/usage.js
545
621
  var isDuplicateKey = (error) => (error == null ? void 0 : error.code) === 11e3 || (error == null ? void 0 : error.code) === "11000" || /E11000|duplicate key/i.test((error == null ? void 0 : error.message) || "");
546
622
 
623
+ // lib/connections/perform.js
624
+ var perform = async ({ answer, controller, emit, enqueue }) => {
625
+ const { enqueues, events, transaction, writes } = answerOf(answer) || {};
626
+ const write = async ({ collection, data, ignoreDuplicate, multiple, operation, options, query }, session) => {
627
+ try {
628
+ await controller[operation]({
629
+ collection,
630
+ data,
631
+ // The controller takes `multiple` beside options — an update that
632
+ // means every matching document must say so explicitly.
633
+ ...multiple && { multiple: true },
634
+ ...(options || session) && { options: { ...options, ...session && { session } } },
635
+ ...query && { query }
636
+ });
637
+ } catch (error) {
638
+ if (!(ignoreDuplicate && isDuplicateKey(error))) throw error;
639
+ }
640
+ };
641
+ if (transaction) {
642
+ await controller.transaction(async (session) => {
643
+ for (const descriptor of writes) await write(descriptor, session);
644
+ });
645
+ } else {
646
+ for (const descriptor of writes) await write(descriptor);
647
+ }
648
+ for (const { data, name, options, queue: target } of enqueues) {
649
+ if (!enqueue) throw new Error("A hook described an enqueue and this caller supplied no enqueuer");
650
+ await enqueue({ data, name, options, queue: target });
651
+ }
652
+ for (const descriptor of events) {
653
+ if (!emit) throw new Error("A hook described a socket event and this caller supplied no emitter");
654
+ emit(descriptor);
655
+ }
656
+ };
657
+
658
+ // lib/encrypt.js
659
+ import crypto2 from "crypto";
660
+
661
+ // lib/token.js
662
+ import crypto from "crypto";
663
+ var generate = (bytes = 32, encoding = "base64url") => {
664
+ const buf = crypto.randomBytes(bytes);
665
+ return encoding ? buf.toString(encoding) : buf;
666
+ };
667
+ var hash = (value, key) => {
668
+ if (!value) return null;
669
+ if (key) {
670
+ return crypto.createHmac("sha256", key).update(String(value)).digest("base64url");
671
+ }
672
+ return crypto.createHash("sha256").update(String(value)).digest("base64url");
673
+ };
674
+
675
+ // lib/encrypt.js
676
+ var ALGORITHM = "aes-256-gcm";
677
+ var getKey = () => Buffer.from(process.env.ENCRYPT_CONNECTION_SECRET, "hex");
678
+ var encrypt = (value) => {
679
+ const iv = generate(12, null);
680
+ const cipher = crypto2.createCipheriv(ALGORITHM, getKey(), iv);
681
+ const data = Buffer.concat([
682
+ cipher.update(JSON.stringify(value), "utf8"),
683
+ cipher.final()
684
+ ]);
685
+ const tag = cipher.getAuthTag();
686
+ return [iv, tag, data].map((b) => b.toString("hex")).join(":");
687
+ };
688
+ var decrypt = (value) => {
689
+ if (typeof value !== "string") return value;
690
+ const [ivHex, tagHex, dataHex] = value.split(":");
691
+ const decipher = crypto2.createDecipheriv(
692
+ ALGORITHM,
693
+ getKey(),
694
+ Buffer.from(ivHex, "hex")
695
+ );
696
+ decipher.setAuthTag(Buffer.from(tagHex, "hex"));
697
+ const result = Buffer.concat([
698
+ decipher.update(Buffer.from(dataHex, "hex")),
699
+ decipher.final()
700
+ ]);
701
+ return JSON.parse(result.toString("utf8"));
702
+ };
703
+
704
+ // lib/connections/reconcile.js
705
+ var connectionSettings = async ({ controller, query }) => {
706
+ const connection = await controller.get({ collection: "connection", query });
707
+ if (!connection) return { connection: null, settings: null };
708
+ return { connection, settings: decrypt(connection.settings) };
709
+ };
710
+ var SCOPES_ERROR_SOURCE = "scopes";
711
+ var SCOPES_ERROR_MESSAGE = "Shopify permissions are out of date. Open the Drawbridge app in your Shopify admin to approve the updated permissions.";
712
+ var reconcileConnectionScopes = async ({
713
+ controller,
714
+ enqueue,
715
+ granted = null,
716
+ logger,
717
+ shop,
718
+ slug: slug2 = "shopify"
719
+ }) => {
720
+ var _a, _b, _c;
721
+ if (granted === null) {
722
+ const record = await controller.get({ collection: "shop", query: { shop } });
723
+ const session = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
724
+ granted = (session == null ? void 0 : session.scope) || null;
725
+ }
726
+ if (!granted) return null;
727
+ const answered = await runHook(slug2, "auth.scopes", { scope: granted });
728
+ const missing2 = answered.outcome === "answered" ? (_a = answered.answer.result) == null ? void 0 : _a.missing : null;
729
+ if (!Array.isArray(missing2)) {
730
+ (_b = logger == null ? void 0 : logger.warn) == null ? void 0 : _b.call(logger, "connection.scopes.unreadable", { shop, slug: slug2 });
731
+ return null;
732
+ }
733
+ const connections2 = await controller.aggregate({
734
+ collection: "connection",
735
+ pipeline: [{ $match: { shop, slug: slug2 } }]
736
+ });
737
+ let hadScopesError = false;
738
+ for (const connection of connections2) {
739
+ const others = (connection.errors || []).filter((entry) => entry.source !== SCOPES_ERROR_SOURCE);
740
+ const hasScopesError = others.length !== (connection.errors || []).length;
741
+ hadScopesError = hadScopesError || hasScopesError;
742
+ if (missing2.length) {
743
+ await controller.update({
744
+ collection: "connection",
745
+ data: {
746
+ $set: {
747
+ errors: [...others, { message: SCOPES_ERROR_MESSAGE, source: SCOPES_ERROR_SOURCE }],
748
+ status: "error"
749
+ }
750
+ },
751
+ query: { id: connection.id }
752
+ });
753
+ } else if (hasScopesError) {
754
+ await controller.update({
755
+ collection: "connection",
756
+ data: {
757
+ $set: {
758
+ errors: others,
759
+ ...connection.status === "error" && !others.length && { status: "active" }
760
+ }
761
+ },
762
+ query: { id: connection.id }
763
+ });
764
+ }
765
+ }
766
+ const products = connections2.length ? await controller.aggregate({
767
+ collection: "product",
768
+ pipeline: [{ $match: { "provider.slug": slug2, "source.domain": shop } }]
769
+ }) : [];
770
+ if (missing2.length && products.length) {
771
+ const productIds = products.map((product) => product.id);
772
+ await controller.update({
773
+ collection: "product",
774
+ data: { $set: { status: "inactive" } },
775
+ multiple: true,
776
+ query: { id: { $in: productIds } }
777
+ });
778
+ await controller.update({
779
+ collection: "advertisement",
780
+ data: { $set: { status: "drafted" } },
781
+ multiple: true,
782
+ query: { product: { $in: productIds } }
783
+ });
784
+ } else if (!missing2.length && hadScopesError && enqueue) {
785
+ for (const product of products) {
786
+ await enqueue({
787
+ data: { product: product.id },
788
+ name: "sync",
789
+ options: { jobId: "product." + slug2 + "." + product.id + "." + Date.now() },
790
+ queue: "product." + slug2
791
+ });
792
+ }
793
+ }
794
+ (_c = logger == null ? void 0 : logger.info) == null ? void 0 : _c.call(logger, "connection.scopes.reconciled", { connections: connections2.length, missing: missing2, shop });
795
+ return missing2;
796
+ };
797
+
547
798
  // lib/connections/workflows.js
548
799
  var systemSteps = (node, path = []) => Object.entries(node || {}).flatMap(
549
800
  ([key, value]) => {
@@ -657,10 +908,10 @@ var authToken = async ({
657
908
  const renewing = !code;
658
909
  if (renewing && !refreshToken) throw new Error("Nothing has been consented to yet, so there is no refresh token to spend");
659
910
  if (!renewing && descriptor.pkce && !verifier) throw new Error("This connection requires PKCE, so the code verifier is not optional");
660
- const client = credentials({ basic, clientId, clientSecret });
911
+ const client2 = credentials({ basic, clientId, clientSecret });
661
912
  const response = await fetcher(descriptor.endpoints.token, {
662
913
  body: new URLSearchParams({
663
- ...client.body,
914
+ ...client2.body,
664
915
  ...renewing ? { grant_type: "refresh_token", refresh_token: refreshToken } : {
665
916
  code: decodeURIComponent(String(code || "").trim()),
666
917
  grant_type: "authorization_code",
@@ -668,7 +919,7 @@ var authToken = async ({
668
919
  ...descriptor.pkce && { code_verifier: verifier }
669
920
  }
670
921
  }),
671
- headers: { "content-type": "application/x-www-form-urlencoded", ...client.headers },
922
+ headers: { "content-type": "application/x-www-form-urlencoded", ...client2.headers },
672
923
  method: "POST",
673
924
  signal: AbortSignal.timeout(15e3)
674
925
  });
@@ -1124,9 +1375,18 @@ var scaffold_default = {
1124
1375
  commerce: {
1125
1376
  // NEW in phase 1 — the Checkout Kit cart path, which writes nothing and is
1126
1377
  // the last api surface Shopify owns outside a hook.
1127
- cart: async ({ connection, context }, { read } = {}) => ANSWER,
1378
+ // NO `connection` AND NO `step`: this one runs for a SHOPPER on a public
1379
+ // page, not for an organization inside a workflow. It reads the storefront
1380
+ // with the store's storefront token and mints a checkout token from
1381
+ // DRAWBRIDGE'S app credentials, which is why the credential pair rides in
1382
+ // as props — the way auth.disconnect already carries it.
1383
+ cart: async ({ clientId, clientSecret, context, settings }, { fetcher, shopify } = {}) => ANSWER,
1128
1384
  code: async ({ connection, context, step }, { adminToken, shopify } = {}) => ANSWER,
1129
1385
  customer: async ({ connection, context }, { adminToken, read, shopify } = {}) => ANSWER,
1386
+ // STOCK, READ AT RENDER TIME rather than stored. It is the one product
1387
+ // fact that is stale the instant it is written down, so the campaign
1388
+ // product list asks the vendor and caches the answer for a minute.
1389
+ inventory: async ({ connection, context }, { adminToken, shopify } = {}) => ANSWER,
1130
1390
  order: async ({ connection, context }, { logger, mintId, read } = {}) => ANSWER,
1131
1391
  // THIS IS WHERE `product.insert` LANDS.
1132
1392
  //
@@ -1148,7 +1408,7 @@ var scaffold_default = {
1148
1408
  // nothing and shows up only as `workflow.dispatch.candidates matched : 0` in
1149
1409
  // a log. Phase 1 closes it and build() checks every trigger against it.
1150
1410
  product: {
1151
- hook: async ({ connection, context, workflow }, { mintId, read } = {}) => ANSWER,
1411
+ hook: async ({ connection, context, settings, workflow }, { adminToken, mintId, read, shopify } = {}) => ANSWER,
1152
1412
  step: () => ({
1153
1413
  description: "Syncs product data from the vendor when a product changes.",
1154
1414
  key: "Vendor Product Sync",
@@ -1296,8 +1556,19 @@ var scaffold_default = {
1296
1556
  // Vendor billing, the only group that is not generic. Pairs with
1297
1557
  // auth.install.billing, which declares what the merchant is being charged.
1298
1558
  plan: {
1299
- cancel: async ({ context }, { dispatch, read } = {}) => ANSWER,
1300
- reselect: async ({ context }, { dispatch, read } = {}) => ANSWER
1559
+ cancel: async ({ context }, { read, shopify } = {}) => ANSWER,
1560
+ // NOT A MERCHANT ACTION EITHER one attributed order's usage charge,
1561
+ // sent to the vendor's meter. The credential pair rides in as props
1562
+ // because the charge authenticates as the APP, not as the store.
1563
+ charge: async ({ clientId, clientSecret, context, manifest }, { shopify } = {}) => ANSWER,
1564
+ // `mark` is the one write a description cannot carry: the marker must
1565
+ // be persisted BEFORE the approval is released, and a described write
1566
+ // lands after the hook returns.
1567
+ reselect: async ({ context }, { mark, read, shopify } = {}) => ANSWER,
1568
+ // NOT A MERCHANT ACTION — the question "is this store's billing
1569
+ // actually metered right now", asked by the daily health check and by
1570
+ // the vendor's own approval webhook, which used to hand-copy it.
1571
+ verify: async ({ context }, { adminToken, read, shopify } = {}) => ANSWER
1301
1572
  },
1302
1573
  // The embedded app's own session, stored by us on the vendor's behalf.
1303
1574
  session: {
@@ -1783,16 +2054,19 @@ var attentive_default2 = {
1783
2054
  "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.",
1784
2055
  "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."
1785
2056
  ],
1786
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
1787
- // The dashboard already carries generic reasons for every way an
1788
- // authorization can fail — declined, expired state, a vendor we are not set
1789
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
1790
- // failures need saying differently. This one's do not.
2057
+ // WHAT THE MERCHANT READS WHEN A CONNECT FAILS. Two states, because the
2058
+ // consent screen has two ways to end: they said no, or something between
2059
+ // here and the vendor went wrong.
1791
2060
  //
1792
- // Answered rather than omitted, because `errors` existed on two of six
1793
- // manifests and there was no way to tell "nothing to add" from "nobody
1794
- // wrote it".
1795
- errors: false,
2061
+ // THE VENDOR IS NAMED IN BOTH. The dashboard's generic copy says "the
2062
+ // authorization"; a merchant connecting two accounts in one sitting needs
2063
+ // to know which one this was.
2064
+ errors: {
2065
+ connect: {
2066
+ denied: "The Attentive authorization was declined, so nothing was connected.",
2067
+ invalid: "We couldn't complete the Attentive connection. Try connecting again."
2068
+ }
2069
+ },
1796
2070
  excerpt: "Sync your Drawbridge contacts into an Attentive segment.",
1797
2071
  // NAMES THE SEGMENT STEP, because `status` below gates on it: a grant with
1798
2072
  // no segment chosen sits at Pending, and a guide that stops at the consent
@@ -2320,6 +2594,15 @@ var readEventHeader = ({ descriptor, headers }) => ({ result: { event: headers[d
2320
2594
  var DEFAULT_TIMEOUT_MS = 15e3;
2321
2595
  var request = async ({
2322
2596
  body,
2597
+ // THE TRANSPORT, injectable and defaulted to the real one.
2598
+ //
2599
+ // Every other vendor client in this package takes a `fetcher` — it is how
2600
+ // klaviyo, mailchimp and attentive are tested without a network, and it is a
2601
+ // declared HOOK_OPTION. The Shopify client had no seam at all, so the only way
2602
+ // to test a hook that used it was to inject the whole SDK namespace; that
2603
+ // injection existed to work around an import cycle, and when the cycle went
2604
+ // the tests lost their only hold. This is the seam they should have had.
2605
+ fetcher = fetch,
2323
2606
  headers = {},
2324
2607
  method = "GET",
2325
2608
  query,
@@ -2333,7 +2616,7 @@ var request = async ({
2333
2616
  }
2334
2617
  ;
2335
2618
  const isForm = type === "form";
2336
- const response = await fetch(fullUrl.toString(), {
2619
+ const response = await fetcher(fullUrl.toString(), {
2337
2620
  method,
2338
2621
  headers: {
2339
2622
  "Content-Type": isForm ? "application/x-www-form-urlencoded" : "application/json",
@@ -2790,15 +3073,12 @@ var drawbridge_default2 = {
2790
3073
  description: [
2791
3074
  "Drawbridge sends your notification emails and your entrants' emails, and recalculates segment membership on a schedule. It is always on and needs nothing connected."
2792
3075
  ],
2793
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
2794
- // The dashboard already carries generic reasons for every way an
2795
- // authorization can fail declined, expired state, a vendor we are not set
2796
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
2797
- // failures need saying differently. This one's do not.
3076
+ // NOTHING IS EVER CONNECTED, so no connect can fail. This is the platform's
3077
+ // own manifest always on, private, never in the catalogue — and it exists
3078
+ // to give Drawbridge's own steps a hook to point at. `denied` and `invalid`
3079
+ // describe a consent screen this connection does not have.
2798
3080
  //
2799
- // Answered rather than omitted, because `errors` existed on two of six
2800
- // manifests and there was no way to tell "nothing to add" from "nobody
2801
- // wrote it".
3081
+ // `false` is the recorded decision, not silence.
2802
3082
  errors: false,
2803
3083
  excerpt: "The steps Drawbridge runs itself.",
2804
3084
  guide: [
@@ -3558,10 +3838,10 @@ var klaviyo_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill=
3558
3838
 
3559
3839
  // lib/connections/scopes.js
3560
3840
  var list = (value) => (Array.isArray(value) ? value.flatMap((entry) => String(entry).split(/\s+/)) : String(value ?? "").split(/\s+/)).map((entry) => entry.trim()).filter(Boolean);
3561
- var missingScopes = ({ granted, required }) => {
3841
+ var missingScopes = ({ granted, required: required2 }) => {
3562
3842
  if (granted === null || granted === void 0 || granted === "") return null;
3563
3843
  const held = new Set(list(granted));
3564
- return list(required).filter((scope) => !held.has(scope));
3844
+ return list(required2).filter((scope) => !held.has(scope));
3565
3845
  };
3566
3846
 
3567
3847
  // lib/connections/manifests/klaviyo.js
@@ -4460,16 +4740,19 @@ var mailchimp_default2 = {
4460
4740
  "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.",
4461
4741
  "Someone who unsubscribed inside Mailchimp keeps that choice: a resync only sets the status of a subscriber Mailchimp has never seen before."
4462
4742
  ],
4463
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
4464
- // The dashboard already carries generic reasons for every way an
4465
- // authorization can fail — declined, expired state, a vendor we are not set
4466
- // up for — and a sentence here is an ADDITION to those, for a vendor whose
4467
- // failures need saying differently. This one's do not.
4743
+ // WHAT THE MERCHANT READS WHEN A CONNECT FAILS. Two states, because the
4744
+ // consent screen has two ways to end: they said no, or something between
4745
+ // here and the vendor went wrong.
4468
4746
  //
4469
- // Answered rather than omitted, because `errors` existed on two of six
4470
- // manifests and there was no way to tell "nothing to add" from "nobody
4471
- // wrote it".
4472
- errors: false,
4747
+ // THE VENDOR IS NAMED IN BOTH. The dashboard's generic copy says "the
4748
+ // authorization"; a merchant connecting two accounts in one sitting needs
4749
+ // to know which one this was.
4750
+ errors: {
4751
+ connect: {
4752
+ denied: "The Mailchimp authorization was declined, so nothing was connected.",
4753
+ invalid: "We couldn't complete the Mailchimp connection. Try connecting again."
4754
+ }
4755
+ },
4473
4756
  excerpt: "Sync your Drawbridge contacts into a Mailchimp audience.",
4474
4757
  // NAMES THE AUDIENCE STEP, because `status` below gates on it: a grant with
4475
4758
  // no audience chosen sits at Pending, and a guide that stops at the consent
@@ -4568,7 +4851,7 @@ var mailchimp_default2 = {
4568
4851
  if (!audience) return { message: "No Mailchimp audience is chosen for this connection.", request: request2, skipped: true };
4569
4852
  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);
4570
4853
  if (!email) return { message: "That lead has no email address to sync.", request: request2, skipped: true };
4571
- const hash = subscriberHash(email);
4854
+ const hash2 = subscriberHash(email);
4572
4855
  const [firstName, ...restOfName] = String((lead == null ? void 0 : lead.name) || "").trim().split(/\s+/).filter(Boolean);
4573
4856
  const lastName = restOfName.join(" ");
4574
4857
  const phone = ((_e = lead == null ? void 0 : lead.phone) == null ? void 0 : _e.number) || null;
@@ -4577,7 +4860,7 @@ var mailchimp_default2 = {
4577
4860
  ...lastName && { LNAME: lastName },
4578
4861
  ...phone && { PHONE: phone }
4579
4862
  };
4580
- const member = await api3("/lists/" + audience + "/members/" + hash, {
4863
+ const member = await api3("/lists/" + audience + "/members/" + hash2, {
4581
4864
  dc: settings == null ? void 0 : settings.dc,
4582
4865
  fetcher,
4583
4866
  method: "PUT",
@@ -4618,7 +4901,7 @@ var mailchimp_default2 = {
4618
4901
  status: joined.has(entry.id) ? "active" : "inactive"
4619
4902
  }));
4620
4903
  if (tags.length > 0) {
4621
- await api3("/lists/" + audience + "/members/" + hash + "/tags", {
4904
+ await api3("/lists/" + audience + "/members/" + hash2 + "/tags", {
4622
4905
  dc: settings == null ? void 0 : settings.dc,
4623
4906
  fetcher,
4624
4907
  method: "POST",
@@ -4629,12 +4912,12 @@ var mailchimp_default2 = {
4629
4912
  }
4630
4913
  return {
4631
4914
  // Merged into `context` for later steps in this run.
4632
- context: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash },
4915
+ context: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash2 },
4633
4916
  message: suppressed ? "Synced to Mailchimp as unsubscribed \u2014 this contact has opted out." : "Synced to the Mailchimp audience.",
4634
4917
  request: request2,
4635
4918
  // Recorded on the run for support to read back, not a write
4636
4919
  // instruction — the hook has already written what it needed to.
4637
- response: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash }
4920
+ response: { mailchimpMemberId: (member == null ? void 0 : member.id) || hash2 }
4638
4921
  };
4639
4922
  }
4640
4923
  },
@@ -5004,159 +5287,2050 @@ var shopify_default = `<svg width="500" height="500" viewBox="0 0 500 500" fill=
5004
5287
  <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"/>
5005
5288
  </svg>`;
5006
5289
 
5007
- // lib/email.js
5008
- var GMAIL_DOMAINS = /* @__PURE__ */ new Set(["gmail.com", "googlemail.com"]);
5009
- var toCanonicalEmail = (value) => {
5010
- if (!value || typeof value !== "string") return null;
5011
- const email = value.trim().toLowerCase();
5012
- const at = email.lastIndexOf("@");
5013
- if (at < 1 || at === email.length - 1) return null;
5014
- let local = email.slice(0, at);
5015
- const domain = email.slice(at + 1);
5016
- const plus = local.indexOf("+");
5017
- if (plus > 0) local = local.slice(0, plus);
5018
- if (GMAIL_DOMAINS.has(domain)) local = local.replaceAll(".", "");
5019
- if (!local) return null;
5020
- return local + "@" + domain;
5021
- };
5290
+ // lib/shopify/admin.js
5291
+ var admin_exports = {};
5292
+ __export(admin_exports, {
5293
+ adminFetch: () => adminFetch,
5294
+ createDiscountCode: () => createDiscountCode,
5295
+ createUsageRecord: () => createUsageRecord,
5296
+ createUsageSubscription: () => createUsageSubscription,
5297
+ getActiveAppSubscriptions: () => getActiveAppSubscriptions,
5298
+ getDiscounts: () => getDiscounts,
5299
+ getOrCreateCustomer: () => getOrCreateCustomer,
5300
+ getProductInventory: () => getProductInventory,
5301
+ sendProductResourceFeedback: () => sendProductResourceFeedback
5302
+ });
5022
5303
 
5023
- // lib/encrypt.js
5024
- import crypto from "crypto";
5025
- var ALGORITHM = "aes-256-gcm";
5026
- var getKey = () => Buffer.from(process.env.ENCRYPT_CONNECTION_SECRET, "hex");
5027
- var decrypt = (value) => {
5028
- if (typeof value !== "string") return value;
5029
- const [ivHex, tagHex, dataHex] = value.split(":");
5030
- const decipher = crypto.createDecipheriv(
5031
- ALGORITHM,
5032
- getKey(),
5033
- Buffer.from(ivHex, "hex")
5034
- );
5035
- decipher.setAuthTag(Buffer.from(tagHex, "hex"));
5036
- const result = Buffer.concat([
5037
- decipher.update(Buffer.from(dataHex, "hex")),
5038
- decipher.final()
5039
- ]);
5040
- return JSON.parse(result.toString("utf8"));
5041
- };
5304
+ // lib/shopify/constants.js
5305
+ var SHOPIFY_STOREFRONT_API_VERSION = "2025-01";
5306
+ var SHOPIFY_ADMIN_API_VERSION = "2026-04";
5307
+ var SHOPIFY_APP_API_VERSION = "unstable";
5308
+ var SHOPIFY_REQUIRED_SCOPES = [
5309
+ "read_customers",
5310
+ "write_customers",
5311
+ "read_discounts",
5312
+ "write_discounts",
5313
+ "read_orders",
5314
+ "read_products",
5315
+ "read_publications",
5316
+ "write_resource_feedbacks",
5317
+ "unauthenticated_read_checkouts",
5318
+ "unauthenticated_read_product_inventory",
5319
+ "unauthenticated_read_product_listings",
5320
+ "unauthenticated_write_checkouts"
5321
+ ];
5322
+ var REFRESH_TOKEN_LIFETIME_MS = 90 * 24 * 60 * 60 * 1e3;
5323
+ var ACCESS_TOKEN_REFRESH_BUFFER_MS = 5 * 60 * 1e3;
5324
+ var PARTNER_API_VERSION = process.env.SHOPIFY_PARTNER_API_VERSION || "2026-07";
5042
5325
 
5043
- // lib/slugify.js
5044
- import slug from "slugify";
5045
- var slugify = (value, nochars = false) => {
5046
- const remove = nochars ? /[-?*+~.()'"!:@#^_{}\[\];,/\\]/g : /[?*+~.()'"!:@#^_{}\[\];,/\\]/g;
5047
- const replacement = nochars ? "" : "-";
5048
- return slug(
5049
- value,
5050
- {
5051
- remove,
5052
- replacement,
5053
- lower: true,
5054
- trim: true
5326
+ // lib/shopify/admin.js
5327
+ var adminUrl = (domain) => `https://${domain}/admin/api/${SHOPIFY_ADMIN_API_VERSION}`;
5328
+ var adminFetch = async ({ adminAccessToken, domain, fetcher, query, variables }) => {
5329
+ var _a;
5330
+ const { data, errors } = await request({
5331
+ fetcher,
5332
+ method: "POST",
5333
+ url: adminUrl(domain) + "/graphql.json",
5334
+ headers: {
5335
+ "X-Shopify-Access-Token": adminAccessToken
5336
+ },
5337
+ body: {
5338
+ query,
5339
+ ...variables && { variables }
5055
5340
  }
5056
- );
5341
+ });
5342
+ if (errors) {
5343
+ throw new Error("Shopify GraphQL error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
5344
+ }
5345
+ ;
5346
+ return data;
5057
5347
  };
5058
-
5059
- // lib/connections/manifests/shopify.js
5060
- var toLine = ({
5061
- price,
5062
- product_id: productId,
5063
- quantity,
5064
- title,
5065
- variant_id: variantId,
5066
- variant_title: variantTitle
5067
- }) => ({
5068
- price: parseFloat(price) || 0,
5069
- productId: productId ? "gid://shopify/Product/" + productId : null,
5070
- quantity: quantity || 1,
5071
- title: title || null,
5072
- variantId: variantId ? "gid://shopify/ProductVariant/" + variantId : null,
5073
- variantTitle: variantTitle || null
5074
- });
5075
- var attributeLineItems = (lineItems = []) => lineItems.reduce(
5076
- (acc, item) => {
5077
- const attrs = (item.properties || []).reduce(
5078
- (map, { name, value }) => {
5079
- map[name] = value;
5080
- return map;
5081
- },
5082
- {}
5083
- );
5084
- if (!attrs["_drwbrdg_ca"]) return acc;
5085
- if (!Object.keys(acc.attrMap).length) acc.attrMap = attrs;
5086
- const line = toLine(item);
5087
- acc.attributedGross += line.price * line.quantity;
5088
- acc.attributedLines.push(line);
5089
- return acc;
5090
- },
5091
- { attrMap: {}, attributedGross: 0, attributedLines: [] }
5092
- );
5093
- var generateDiscountCode = customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8);
5094
- var blockedReason = (discount) => {
5095
- var _a;
5096
- if ((discount == null ? void 0 : discount.status) === "EXPIRED") return "This discount has expired.";
5097
- const buyers = (_a = discount == null ? void 0 : discount.context) == null ? void 0 : _a.__typename;
5098
- if (buyers && buyers !== "DiscountBuyerSelectionAll") {
5099
- 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.";
5348
+ var DISCOUNT_FIELDS = `
5349
+ title
5350
+ status
5351
+ startsAt
5352
+ endsAt
5353
+ usageLimit
5354
+ asyncUsageCount
5355
+ appliesOncePerCustomer
5356
+ context { __typename }
5357
+ `;
5358
+ var discountsQuery = (search, cursor, limit) => `{
5359
+ codeDiscountNodes(first: ${limit}${search ? `, query: "title:*${search}*"` : ""}${cursor ? `, after: "${cursor}"` : ""}) {
5360
+ edges {
5361
+ node {
5362
+ id
5363
+ codeDiscount {
5364
+ ... on DiscountCodeBasic { ${DISCOUNT_FIELDS} }
5365
+ ... on DiscountCodeBxgy { ${DISCOUNT_FIELDS} }
5366
+ ... on DiscountCodeFreeShipping { ${DISCOUNT_FIELDS} }
5367
+ ... on DiscountCodeApp { ${DISCOUNT_FIELDS} }
5368
+ }
5369
+ }
5370
+ }
5371
+ pageInfo {
5372
+ endCursor
5373
+ hasNextPage
5374
+ hasPreviousPage
5375
+ startCursor
5376
+ }
5377
+ }
5378
+ }`;
5379
+ var getDiscounts = async ({ fetcher, adminAccessToken, domain, search, cursor, limit }) => {
5380
+ const data = await adminFetch({
5381
+ fetcher,
5382
+ adminAccessToken,
5383
+ domain,
5384
+ query: discountsQuery(search, cursor, limit)
5385
+ });
5386
+ return data == null ? void 0 : data.codeDiscountNodes;
5387
+ };
5388
+ var discountGid = (id) => String(id).startsWith("gid://") ? String(id) : "gid://shopify/DiscountCodeNode/" + id;
5389
+ var createDiscountCode = async ({ fetcher, adminAccessToken, domain, discountId, code }) => {
5390
+ var _a, _b, _c, _d, _e, _f, _g, _h;
5391
+ const added = await adminFetch({
5392
+ fetcher,
5393
+ adminAccessToken,
5394
+ domain,
5395
+ query: `
5396
+ mutation DiscountRedeemCodeBulkAdd($discountId: ID!, $codes: [DiscountRedeemCodeInput!]!) {
5397
+ discountRedeemCodeBulkAdd(discountId: $discountId, codes: $codes) {
5398
+ bulkCreation {
5399
+ id
5400
+ }
5401
+ userErrors {
5402
+ field
5403
+ message
5404
+ }
5405
+ }
5406
+ }
5407
+ `,
5408
+ variables: {
5409
+ codes: [{ code }],
5410
+ discountId: discountGid(discountId)
5411
+ }
5412
+ });
5413
+ const addErrors = (_a = added == null ? void 0 : added.discountRedeemCodeBulkAdd) == null ? void 0 : _a.userErrors;
5414
+ if (addErrors == null ? void 0 : addErrors.length) {
5415
+ throw new Error("Shopify discount code create failed: " + addErrors[0].message);
5100
5416
  }
5101
5417
  ;
5102
- if (typeof (discount == null ? void 0 : discount.usageLimit) === "number" && discount.usageLimit > 0 && ((discount == null ? void 0 : discount.asyncUsageCount) || 0) >= discount.usageLimit) {
5103
- return "This discount has reached its total usage limit.";
5418
+ const bulkCreationId = (_c = (_b = added == null ? void 0 : added.discountRedeemCodeBulkAdd) == null ? void 0 : _b.bulkCreation) == null ? void 0 : _c.id;
5419
+ if (!bulkCreationId) {
5420
+ throw new Error("Shopify discount code create failed: no bulk creation id returned");
5104
5421
  }
5105
5422
  ;
5106
- return null;
5107
- };
5108
- var discountWarning = (discount) => {
5109
- if ((discount == null ? void 0 : discount.status) === "SCHEDULED") {
5110
- return "This discount hasn't started yet, so codes issued before it does won't work until then.";
5423
+ for (let attempt = 0; attempt < 15; attempt++) {
5424
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
5425
+ const polled = await adminFetch({
5426
+ fetcher,
5427
+ adminAccessToken,
5428
+ domain,
5429
+ query: `
5430
+ query DiscountRedeemCodeBulkCreationPoll($id: ID!) {
5431
+ discountRedeemCodeBulkCreation(id: $id) {
5432
+ done
5433
+ codes(first: 1) {
5434
+ nodes {
5435
+ code
5436
+ discountRedeemCode {
5437
+ id
5438
+ }
5439
+ errors {
5440
+ message
5441
+ }
5442
+ }
5443
+ }
5444
+ }
5445
+ }
5446
+ `,
5447
+ variables: {
5448
+ id: bulkCreationId
5449
+ }
5450
+ });
5451
+ const creation = polled == null ? void 0 : polled.discountRedeemCodeBulkCreation;
5452
+ if (!(creation == null ? void 0 : creation.done)) continue;
5453
+ const node = (_e = (_d = creation.codes) == null ? void 0 : _d.nodes) == null ? void 0 : _e[0];
5454
+ if (!((_f = node == null ? void 0 : node.discountRedeemCode) == null ? void 0 : _f.id)) {
5455
+ 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"));
5456
+ }
5457
+ ;
5458
+ return {
5459
+ code: node.code,
5460
+ // Numeric tail keeps the stored shopifyDiscountId in the shape the
5461
+ // legacy REST endpoint returned — it feeds a merchant-visible
5462
+ // workflow template variable, so no gid:// leakage.
5463
+ id: node.discountRedeemCode.id.split("/").pop()
5464
+ };
5111
5465
  }
5112
5466
  ;
5113
- if (discount == null ? void 0 : discount.appliesOncePerCustomer) return "Each customer can use this discount only once.";
5114
- return null;
5467
+ throw new Error("Shopify discount code create timed out waiting for bulk creation " + bulkCreationId);
5115
5468
  };
5116
- var ORDER_EVENT_HANDLE = slugify("drawbridge-orders");
5117
- var REFRESH_TOKEN_FRESHNESS_BUFFER_MS = 5 * 24 * 60 * 60 * 1e3;
5118
- var OAUTH_ERROR_SOURCE = "oauth";
5119
- var BILLING_ERROR_SOURCE = "billing";
5120
- var BILLING_ERROR_MESSAGE = "Order billing isn't set up for this store \u2014 reselect and approve the plan from the Shopify connection page.";
5121
- var OAUTH_GRANT_REVOKED_CODES = ["application_cannot_be_found", "invalid_grant"];
5122
- var inbound = {
5123
- headers: {
5124
- event: "x-shopify-topic",
5125
- id: "x-shopify-webhook-id",
5126
- shop: "x-shopify-shop-domain",
5127
- signature: "x-shopify-hmac-sha256"
5128
- },
5129
- signature: {
5130
- algorithm: "sha256",
5131
- encoding: "base64",
5132
- secret: "SHOPIFY_API_SECRET"
5469
+ var getOrCreateCustomer = async ({ fetcher, adminAccessToken, domain, email, firstName, lastName, source }) => {
5470
+ var _a, _b, _c, _d, _e, _f, _g, _h;
5471
+ const lookupQuery = `
5472
+ query customerByEmail( $query : String! ) {
5473
+ customers( first : 1, query : $query ) {
5474
+ edges {
5475
+ node {
5476
+ id
5477
+ }
5478
+ }
5479
+ }
5480
+ }
5481
+ `;
5482
+ const data = await adminFetch({
5483
+ fetcher,
5484
+ adminAccessToken,
5485
+ domain,
5486
+ query: lookupQuery,
5487
+ variables: { query: "email:" + email }
5488
+ });
5489
+ 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;
5490
+ if (existing) return existing;
5491
+ const input = { email };
5492
+ if (firstName) input.firstName = firstName;
5493
+ if (lastName) input.lastName = lastName;
5494
+ if (source) {
5495
+ input.metafields = [{
5496
+ namespace: "drwbrdg",
5497
+ key: "source",
5498
+ type: "single_line_text_field",
5499
+ value: source
5500
+ }];
5501
+ }
5502
+ ;
5503
+ const result = await adminFetch({
5504
+ fetcher,
5505
+ adminAccessToken,
5506
+ domain,
5507
+ query: `
5508
+ mutation customerCreate( $input : CustomerInput! ) {
5509
+ customerCreate( input : $input ) {
5510
+ customer {
5511
+ id
5512
+ }
5513
+ userErrors {
5514
+ field
5515
+ message
5516
+ }
5517
+ }
5518
+ }
5519
+ `,
5520
+ variables: { input }
5521
+ });
5522
+ const userErrors = (_d = result == null ? void 0 : result.customerCreate) == null ? void 0 : _d.userErrors;
5523
+ if (userErrors == null ? void 0 : userErrors.length) {
5524
+ const emailTaken = userErrors.some((e) => {
5525
+ var _a2;
5526
+ return (_a2 = e.message) == null ? void 0 : _a2.includes("Email has already been taken");
5527
+ });
5528
+ if (emailTaken) {
5529
+ const retry = await adminFetch({
5530
+ fetcher,
5531
+ adminAccessToken,
5532
+ domain,
5533
+ query: lookupQuery,
5534
+ variables: { query: "email:" + email }
5535
+ });
5536
+ 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;
5537
+ if (found) return found;
5538
+ }
5539
+ ;
5540
+ throw new Error("Shopify customer create failed: " + userErrors[0].message);
5133
5541
  }
5542
+ ;
5543
+ return (_h = result == null ? void 0 : result.customerCreate) == null ? void 0 : _h.customer;
5134
5544
  };
5135
- var COMPLIANCE_TOPICS = /* @__PURE__ */ new Set([
5136
- "customers/data_request",
5137
- "customers/redact",
5138
- "shop/redact"
5139
- ]);
5140
- var shopify_default2 = {
5141
- // THE WORDS ON THE BUTTONS. `listing` was `content.redirect.title`, which put
5142
- // a BUTTON LABEL inside the copy object next to a url — the title and the
5143
- // address it belongs to sat at different levels and could drift apart.
5144
- //
5145
- // It names where the link GOES rather than what it does: installing happens on
5146
- // the App Store listing, and the dashboard must never imply a store can be
5147
- // linked from inside it.
5148
- actions: {
5149
- create: null,
5150
- listing: "View on the Shopify App Store",
5151
- manage: null,
5152
- update: null
5153
- },
5154
- // INSTALL, not oauth. The grant is an OAuth grant, but the merchant never
5155
- // sees a consent screen we sent them to -- they start at the App Store, and
5156
- // the install completes inside Shopify admin without redirecting back. A
5157
- // Connect button here would be lying about where connecting happens.
5158
- auth: {
5159
- // ONE STORE PER ORGANIZATION. A Shopify install IS a store, and a second
5545
+ var getActiveAppSubscriptions = async ({ fetcher, adminAccessToken, domain }) => {
5546
+ var _a, _b;
5547
+ const data = await adminFetch({
5548
+ fetcher,
5549
+ adminAccessToken,
5550
+ domain,
5551
+ query: `{
5552
+ currentAppInstallation {
5553
+ activeSubscriptions {
5554
+ id
5555
+ name
5556
+ status
5557
+ test
5558
+ lineItems {
5559
+ id
5560
+ plan {
5561
+ pricingDetails {
5562
+ __typename
5563
+ }
5564
+ }
5565
+ }
5566
+ }
5567
+ }
5568
+ shop {
5569
+ myshopifyDomain
5570
+ }
5571
+ }`
5572
+ });
5573
+ return {
5574
+ shopDomain: ((_a = data == null ? void 0 : data.shop) == null ? void 0 : _a.myshopifyDomain) || null,
5575
+ subscriptions: (((_b = data == null ? void 0 : data.currentAppInstallation) == null ? void 0 : _b.activeSubscriptions) || []).map((subscription) => {
5576
+ var _a2;
5577
+ return {
5578
+ ...subscription,
5579
+ metered: ((subscription == null ? void 0 : subscription.lineItems) || []).some(
5580
+ (item) => {
5581
+ var _a3, _b2;
5582
+ return ((_b2 = (_a3 = item == null ? void 0 : item.plan) == null ? void 0 : _a3.pricingDetails) == null ? void 0 : _b2.__typename) === "AppUsagePricing";
5583
+ }
5584
+ ),
5585
+ // The usage line's own id — the address appUsageRecordCreate charges
5586
+ // against. Null when the approval carries no usage component.
5587
+ usageLineItemId: ((_a2 = ((subscription == null ? void 0 : subscription.lineItems) || []).find(
5588
+ (item) => {
5589
+ var _a3, _b2;
5590
+ return ((_b2 = (_a3 = item == null ? void 0 : item.plan) == null ? void 0 : _a3.pricingDetails) == null ? void 0 : _b2.__typename) === "AppUsagePricing";
5591
+ }
5592
+ )) == null ? void 0 : _a2.id) || null
5593
+ };
5594
+ })
5595
+ };
5596
+ };
5597
+ var createUsageSubscription = async ({ fetcher, adminAccessToken, cappedAmount, currencyCode = "USD", domain, name, recurringPrice = 0, returnUrl, terms, test = false }) => {
5598
+ if (!name || !returnUrl || !terms || !(Number(cappedAmount) > 0)) {
5599
+ throw new Error("createUsageSubscription requires name, returnUrl, terms, and a positive cappedAmount");
5600
+ }
5601
+ ;
5602
+ const data = await adminFetch({
5603
+ fetcher,
5604
+ adminAccessToken,
5605
+ domain,
5606
+ query: `mutation createUsageSubscription( $lineItems : [AppSubscriptionLineItemInput!]!, $name : String!, $returnUrl : URL!, $test : Boolean ) {
5607
+ appSubscriptionCreate( lineItems : $lineItems, name : $name, returnUrl : $returnUrl, test : $test ) {
5608
+ appSubscription { id name status test lineItems { id plan { pricingDetails { __typename } } } }
5609
+ confirmationUrl
5610
+ userErrors { field message }
5611
+ }
5612
+ }`,
5613
+ variables: {
5614
+ lineItems: [
5615
+ {
5616
+ plan: {
5617
+ appRecurringPricingDetails: {
5618
+ interval: "EVERY_30_DAYS",
5619
+ price: { amount: Number(recurringPrice), currencyCode }
5620
+ }
5621
+ }
5622
+ },
5623
+ {
5624
+ plan: {
5625
+ appUsagePricingDetails: {
5626
+ cappedAmount: { amount: Number(cappedAmount), currencyCode },
5627
+ terms
5628
+ }
5629
+ }
5630
+ }
5631
+ ],
5632
+ name,
5633
+ returnUrl,
5634
+ test
5635
+ }
5636
+ });
5637
+ const payload = data == null ? void 0 : data.appSubscriptionCreate;
5638
+ const userErrors = (payload == null ? void 0 : payload.userErrors) || [];
5639
+ if (userErrors.length) {
5640
+ throw new Error("Shopify subscription create failed: " + userErrors.map((entry) => entry.message).join("; "));
5641
+ }
5642
+ ;
5643
+ if (!(payload == null ? void 0 : payload.confirmationUrl)) {
5644
+ throw new Error("Shopify subscription create failed: no confirmation url returned");
5645
+ }
5646
+ ;
5647
+ return {
5648
+ confirmationUrl: payload.confirmationUrl,
5649
+ subscription: payload.appSubscription
5650
+ };
5651
+ };
5652
+ var createUsageRecord = async ({ fetcher, adminAccessToken, amount, currencyCode = "USD", description, domain, idempotencyKey, subscriptionLineItemId }) => {
5653
+ var _a;
5654
+ if (!subscriptionLineItemId || !description || !(Number(amount) > 0)) {
5655
+ throw new Error("createUsageRecord requires subscriptionLineItemId, description, and a positive amount");
5656
+ }
5657
+ ;
5658
+ const data = await adminFetch({
5659
+ fetcher,
5660
+ adminAccessToken,
5661
+ domain,
5662
+ query: `mutation createUsageRecord( $description : String!, $idempotencyKey : String, $price : MoneyInput!, $subscriptionLineItemId : ID! ) {
5663
+ appUsageRecordCreate( description : $description, idempotencyKey : $idempotencyKey, price : $price, subscriptionLineItemId : $subscriptionLineItemId ) {
5664
+ appUsageRecord { id }
5665
+ userErrors { field message }
5666
+ }
5667
+ }`,
5668
+ variables: {
5669
+ description,
5670
+ idempotencyKey: idempotencyKey ? String(idempotencyKey) : null,
5671
+ price: { amount: Number(amount), currencyCode },
5672
+ subscriptionLineItemId
5673
+ }
5674
+ });
5675
+ const payload = data == null ? void 0 : data.appUsageRecordCreate;
5676
+ const userErrors = (payload == null ? void 0 : payload.userErrors) || [];
5677
+ if (userErrors.length || !((_a = payload == null ? void 0 : payload.appUsageRecord) == null ? void 0 : _a.id)) {
5678
+ throw new Error("Shopify usage record failed: " + (userErrors.map((entry) => entry.message).join("; ") || "no record returned"));
5679
+ }
5680
+ ;
5681
+ return { id: payload.appUsageRecord.id };
5682
+ };
5683
+ var getProductInventory = async ({ fetcher, adminAccessToken, domain, productId }) => {
5684
+ var _a, _b;
5685
+ const data = await adminFetch({
5686
+ fetcher,
5687
+ adminAccessToken,
5688
+ domain,
5689
+ query: `{
5690
+ product( id : "${productId}" ) {
5691
+ variants( first : 100 ) {
5692
+ edges {
5693
+ node {
5694
+ id
5695
+ inventoryQuantity
5696
+ }
5697
+ }
5698
+ }
5699
+ }
5700
+ }`
5701
+ });
5702
+ const edges = ((_b = (_a = data == null ? void 0 : data.product) == null ? void 0 : _a.variants) == null ? void 0 : _b.edges) || [];
5703
+ return edges.reduce((accumulator, edge) => {
5704
+ var _a2, _b2;
5705
+ const id = (_a2 = edge == null ? void 0 : edge.node) == null ? void 0 : _a2.id;
5706
+ const quantity = (_b2 = edge == null ? void 0 : edge.node) == null ? void 0 : _b2.inventoryQuantity;
5707
+ if (id) {
5708
+ accumulator[id] = Number.isFinite(quantity) ? quantity : 0;
5709
+ }
5710
+ ;
5711
+ return accumulator;
5712
+ }, {});
5713
+ };
5714
+ var getProductUpdatedAt = async ({ adminAccessToken, domain, fetcher, productId }) => {
5715
+ var _a;
5716
+ const data = await adminFetch({
5717
+ fetcher,
5718
+ adminAccessToken,
5719
+ domain,
5720
+ query: `
5721
+ query ProductUpdatedAt($id: ID!) {
5722
+ product(id: $id) {
5723
+ updatedAt
5724
+ }
5725
+ }
5726
+ `,
5727
+ variables: { id: productId }
5728
+ });
5729
+ return ((_a = data == null ? void 0 : data.product) == null ? void 0 : _a.updatedAt) || null;
5730
+ };
5731
+ var NOT_ON_CHANNEL = "not available to the channel";
5732
+ var OUTDATED_FEEDBACK = "later version";
5733
+ var sendProductResourceFeedback = async ({ fetcher, adminAccessToken, domain, productId, state, messages = [] }) => {
5734
+ var _a, _b, _c;
5735
+ const productUpdatedAt = await getProductUpdatedAt({ adminAccessToken, domain, fetcher, productId });
5736
+ if (!productUpdatedAt) return null;
5737
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5738
+ const submit = async (version) => {
5739
+ const data = await adminFetch({
5740
+ fetcher,
5741
+ adminAccessToken,
5742
+ domain,
5743
+ query: `
5744
+ mutation ProductFeedback($feedbackInput: [ProductResourceFeedbackInput!]!) {
5745
+ bulkProductResourceFeedbackCreate(feedbackInput: $feedbackInput) {
5746
+ feedback {
5747
+ productId
5748
+ state
5749
+ }
5750
+ userErrors {
5751
+ field
5752
+ message
5753
+ }
5754
+ }
5755
+ }
5756
+ `,
5757
+ variables: {
5758
+ feedbackInput: [
5759
+ {
5760
+ productId,
5761
+ state,
5762
+ feedbackGeneratedAt: now,
5763
+ productUpdatedAt: version,
5764
+ messages
5765
+ }
5766
+ ]
5767
+ }
5768
+ });
5769
+ return data == null ? void 0 : data.bulkProductResourceFeedbackCreate;
5770
+ };
5771
+ let result = await submit(productUpdatedAt);
5772
+ if ((((_b = (_a = result == null ? void 0 : result.userErrors) == null ? void 0 : _a[0]) == null ? void 0 : _b.message) || "").toLowerCase().includes(OUTDATED_FEEDBACK)) {
5773
+ result = await submit(now);
5774
+ }
5775
+ ;
5776
+ const feedbackErrors = result == null ? void 0 : result.userErrors;
5777
+ if (feedbackErrors == null ? void 0 : feedbackErrors.length) {
5778
+ const message = feedbackErrors[0].message || "";
5779
+ if (message.toLowerCase().includes(NOT_ON_CHANNEL)) return null;
5780
+ throw new Error("Shopify product feedback failed: " + message);
5781
+ }
5782
+ ;
5783
+ return ((_c = result == null ? void 0 : result.feedback) == null ? void 0 : _c[0]) || null;
5784
+ };
5785
+
5786
+ // lib/shopify/billing.js
5787
+ var billing_exports = {};
5788
+ __export(billing_exports, {
5789
+ sendAppEvent: () => sendAppEvent
5790
+ });
5791
+ var APP_API = "https://api.shopify.com";
5792
+ var APP_API_VERSION = process.env.SHOPIFY_APP_API_VERSION || SHOPIFY_APP_API_VERSION;
5793
+ var cachedTokens = {};
5794
+ var fetchAppToken = async ({ clientId, clientSecret, fetcher }) => {
5795
+ const data = await request({
5796
+ fetcher,
5797
+ method: "POST",
5798
+ url: APP_API + "/auth/access_token",
5799
+ body: {
5800
+ client_id: clientId,
5801
+ client_secret: clientSecret,
5802
+ grant_type: "client_credentials"
5803
+ }
5804
+ });
5805
+ if (!(data == null ? void 0 : data.access_token)) {
5806
+ throw new Error("Shopify app token request failed: no access token returned");
5807
+ }
5808
+ ;
5809
+ const ttl = data.expires_in ? data.expires_in * 1e3 : 60 * 60 * 1e3;
5810
+ cachedTokens[clientId] = {
5811
+ expiresAt: Date.now() + ttl - 60 * 1e3,
5812
+ token: data.access_token
5813
+ };
5814
+ return data.access_token;
5815
+ };
5816
+ var getAppToken = async ({ clientId, clientSecret, fetcher }) => {
5817
+ const cached = cachedTokens[clientId];
5818
+ if (cached && cached.expiresAt > Date.now()) {
5819
+ return cached.token;
5820
+ }
5821
+ ;
5822
+ return fetchAppToken({ clientId, clientSecret, fetcher });
5823
+ };
5824
+ var toShopGid = (shopId) => String(shopId).startsWith("gid://") ? String(shopId) : "gid://shopify/Shop/" + shopId;
5825
+ var sendAppEvent = async ({ fetcher, clientId, clientSecret, eventHandle, idempotencyKey, reference, revision, shopId, timestamp, value }) => {
5826
+ if (!shopId || !eventHandle || !(Number(value) > 0)) {
5827
+ throw new Error("sendAppEvent requires shopId, eventHandle, and a positive value");
5828
+ }
5829
+ ;
5830
+ if (!clientId || !clientSecret) {
5831
+ throw new Error("sendAppEvent requires clientId and clientSecret");
5832
+ }
5833
+ ;
5834
+ const suffix = revision ? ".r" + revision : "";
5835
+ const key = idempotencyKey && String(idempotencyKey).slice(0, Math.max(0, 64 - suffix.length)) + suffix;
5836
+ const body = {
5837
+ attributes: {
5838
+ value: Number(value),
5839
+ ...reference && {
5840
+ reference: String(reference).slice(0, 128)
5841
+ }
5842
+ },
5843
+ event_handle: eventHandle,
5844
+ shop_id: toShopGid(shopId),
5845
+ timestamp: timestamp || (/* @__PURE__ */ new Date()).toISOString(),
5846
+ ...key && {
5847
+ idempotency_key: key
5848
+ }
5849
+ };
5850
+ const send2 = async (token) => request({
5851
+ method: "POST",
5852
+ url: APP_API + "/app/" + APP_API_VERSION + "/events",
5853
+ headers: {
5854
+ "Authorization": "Bearer " + token
5855
+ },
5856
+ body
5857
+ });
5858
+ try {
5859
+ return await send2(await getAppToken({ clientId, clientSecret, fetcher }));
5860
+ } catch (error) {
5861
+ if ((error == null ? void 0 : error.status) === 401) {
5862
+ delete cachedTokens[clientId];
5863
+ return send2(await fetchAppToken({ clientId, clientSecret, fetcher }));
5864
+ }
5865
+ ;
5866
+ throw error;
5867
+ }
5868
+ };
5869
+
5870
+ // lib/shopify/oauth.js
5871
+ var oauth_exports = {};
5872
+ __export(oauth_exports, {
5873
+ SHOPIFY_REQUIRED_SCOPES: () => SHOPIFY_REQUIRED_SCOPES,
5874
+ createStorefrontToken: () => createStorefrontToken,
5875
+ getAdminToken: () => getAdminToken,
5876
+ getShop: () => getShop,
5877
+ missingScopes: () => missingScopes2,
5878
+ ping: () => ping,
5879
+ refreshAdminToken: () => refreshAdminToken,
5880
+ resolveConnectionSettings: () => resolveConnectionSettings
5881
+ });
5882
+ var required = (name, value) => {
5883
+ if (!value) {
5884
+ throw new Error("Shopify " + name + " is required");
5885
+ }
5886
+ ;
5887
+ return value;
5888
+ };
5889
+ var missingScopes2 = (granted) => {
5890
+ const grantedSet = new Set(
5891
+ (Array.isArray(granted) ? granted : String(granted || "").split(",")).map((scope) => scope.trim()).filter(Boolean)
5892
+ );
5893
+ const satisfied = (scope) => grantedSet.has(scope) || grantedSet.has(scope.replace(/(^|_)read_/, "$1write_"));
5894
+ return SHOPIFY_REQUIRED_SCOPES.filter((scope) => !satisfied(scope));
5895
+ };
5896
+ var ping = async ({ fetcher, adminAccessToken, domain }) => {
5897
+ var _a;
5898
+ const response = await fetch(
5899
+ `https://${domain}/admin/api/${SHOPIFY_ADMIN_API_VERSION}/graphql.json`,
5900
+ {
5901
+ body: JSON.stringify({ query: "{ shop { name } }" }),
5902
+ headers: {
5903
+ "Content-Type": "application/json",
5904
+ "X-Shopify-Access-Token": adminAccessToken
5905
+ },
5906
+ method: "POST"
5907
+ }
5908
+ );
5909
+ if (!response.ok) {
5910
+ const text = await response.text().catch(() => "");
5911
+ const error = new Error(response.status + ": " + text);
5912
+ error.status = response.status;
5913
+ throw error;
5914
+ }
5915
+ ;
5916
+ const { errors } = await response.json().catch(() => ({}));
5917
+ if (errors == null ? void 0 : errors.length) {
5918
+ throw new Error("GraphQL: " + (((_a = errors[0]) == null ? void 0 : _a.message) || "unknown error"));
5919
+ }
5920
+ ;
5921
+ };
5922
+ var OAUTH_ERROR_TITLE_PATTERN = /Oauth error (\w+)/i;
5923
+ var parseOAuthErrorCode = (text) => {
5924
+ var _a;
5925
+ try {
5926
+ const parsed = JSON.parse(text);
5927
+ if (parsed == null ? void 0 : parsed.error) return parsed.error;
5928
+ } catch {
5929
+ }
5930
+ ;
5931
+ return ((_a = text.match(OAUTH_ERROR_TITLE_PATTERN)) == null ? void 0 : _a[1]) || null;
5932
+ };
5933
+ var shopifyOAuthFetch = async (url, body) => {
5934
+ const response = await fetch(url, {
5935
+ method: "POST",
5936
+ headers: {
5937
+ "Content-Type": "application/json"
5938
+ },
5939
+ body: JSON.stringify(body)
5940
+ });
5941
+ if (!response.ok) {
5942
+ const text = await response.text().catch(() => "");
5943
+ const error = new Error(response.status + ": " + text);
5944
+ error.status = response.status;
5945
+ error.code = parseOAuthErrorCode(text);
5946
+ throw error;
5947
+ }
5948
+ ;
5949
+ return response.json();
5950
+ };
5951
+ var getShop = async ({ fetcher, adminAccessToken, shop }) => {
5952
+ const data = await adminFetch({
5953
+ fetcher,
5954
+ adminAccessToken,
5955
+ domain: shop,
5956
+ query: `{
5957
+ shop {
5958
+ currencyCode
5959
+ id
5960
+ myshopifyDomain
5961
+ name
5962
+ }
5963
+ }`
5964
+ });
5965
+ const shopData = data == null ? void 0 : data.shop;
5966
+ if (!(shopData == null ? void 0 : shopData.id)) {
5967
+ throw new Error("Shopify shop lookup failed: no shop returned");
5968
+ }
5969
+ ;
5970
+ return {
5971
+ currency: shopData.currencyCode || null,
5972
+ id: shopData.id.split("/").pop(),
5973
+ myshopifyDomain: shopData.myshopifyDomain,
5974
+ name: shopData.name
5975
+ };
5976
+ };
5977
+ var createStorefrontToken = async ({ fetcher, adminAccessToken, shop }) => {
5978
+ var _a, _b, _c, _d, _e;
5979
+ try {
5980
+ const listed = await adminFetch({
5981
+ fetcher,
5982
+ adminAccessToken,
5983
+ domain: shop,
5984
+ query: `{
5985
+ shop {
5986
+ storefrontAccessTokens(first: 100) {
5987
+ edges {
5988
+ node {
5989
+ id
5990
+ title
5991
+ }
5992
+ }
5993
+ }
5994
+ }
5995
+ }`
5996
+ });
5997
+ 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);
5998
+ const orphaned = existing.filter((token) => (token == null ? void 0 : token.title) === "Drawbridge");
5999
+ await Promise.allSettled(
6000
+ orphaned.map((token) => adminFetch({
6001
+ adminAccessToken,
6002
+ domain: shop,
6003
+ query: `
6004
+ mutation StorefrontAccessTokenDelete($input: StorefrontAccessTokenDeleteInput!) {
6005
+ storefrontAccessTokenDelete(input: $input) {
6006
+ deletedStorefrontAccessTokenId
6007
+ userErrors {
6008
+ field
6009
+ message
6010
+ }
6011
+ }
6012
+ }
6013
+ `,
6014
+ variables: {
6015
+ input: {
6016
+ id: token.id
6017
+ }
6018
+ }
6019
+ }))
6020
+ );
6021
+ } catch {
6022
+ }
6023
+ const created = await adminFetch({
6024
+ fetcher,
6025
+ adminAccessToken,
6026
+ domain: shop,
6027
+ query: `
6028
+ mutation StorefrontAccessTokenCreate($input: StorefrontAccessTokenInput!) {
6029
+ storefrontAccessTokenCreate(input: $input) {
6030
+ storefrontAccessToken {
6031
+ accessToken
6032
+ }
6033
+ userErrors {
6034
+ field
6035
+ message
6036
+ }
6037
+ }
6038
+ }
6039
+ `,
6040
+ variables: {
6041
+ input: {
6042
+ title: "Drawbridge"
6043
+ }
6044
+ }
6045
+ });
6046
+ const createErrors = (_c = created == null ? void 0 : created.storefrontAccessTokenCreate) == null ? void 0 : _c.userErrors;
6047
+ if (createErrors == null ? void 0 : createErrors.length) {
6048
+ throw new Error("Shopify storefront token create failed: " + createErrors[0].message);
6049
+ }
6050
+ ;
6051
+ return ((_e = (_d = created == null ? void 0 : created.storefrontAccessTokenCreate) == null ? void 0 : _d.storefrontAccessToken) == null ? void 0 : _e.accessToken) || null;
6052
+ };
6053
+ var resolveTokenContext = async ({ connection, controller }) => {
6054
+ const decrypted = (connection == null ? void 0 : connection.settings) ? decrypt(connection.settings) : {};
6055
+ if ((decrypted == null ? void 0 : decrypted.ref) !== "shop") {
6056
+ return {
6057
+ raw: (connection == null ? void 0 : connection.settings) || null,
6058
+ session: null,
6059
+ settings: decrypted,
6060
+ shop: null,
6061
+ target: "connection"
6062
+ };
6063
+ }
6064
+ ;
6065
+ const shop = decrypted.shop;
6066
+ if (!controller || !shop) {
6067
+ return { raw: null, session: {}, settings: {}, shop, target: "shop" };
6068
+ }
6069
+ ;
6070
+ const record = await controller.get({ collection: "shop", query: { shop } });
6071
+ const session = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : {};
6072
+ const storefront = (record == null ? void 0 : record.storefront) ? decrypt(record.storefront) : null;
6073
+ return {
6074
+ raw: (record == null ? void 0 : record.settings) || null,
6075
+ session,
6076
+ settings: {
6077
+ adminAccessToken: session.accessToken || null,
6078
+ refreshToken: session.refreshToken || null,
6079
+ refreshTokenExpiresAt: session.refreshTokenExpires || null,
6080
+ storefrontAccessToken: (storefront == null ? void 0 : storefront.token) || null,
6081
+ tokenExpiresAt: session.expires || null
6082
+ },
6083
+ shop,
6084
+ target: "shop"
6085
+ };
6086
+ };
6087
+ var resolveConnectionSettings = async ({ fetcher, connection, controller }) => {
6088
+ const { settings } = await resolveTokenContext({ connection, controller });
6089
+ return settings;
6090
+ };
6091
+ var refreshAdminToken = async ({ fetcher, clientId, clientSecret, connection, controller }) => {
6092
+ var _a;
6093
+ const { raw, session, settings, shop, target } = await resolveTokenContext({ connection, controller });
6094
+ const domain = (connection == null ? void 0 : connection.shop) || ((_a = settings.source) == null ? void 0 : _a.domain) || settings.domain || shop;
6095
+ const { refreshToken } = settings;
6096
+ const data = await shopifyOAuthFetch(
6097
+ `https://${domain}/admin/oauth/access_token`,
6098
+ {
6099
+ grant_type: "refresh_token",
6100
+ // Throw before the grant: rotation RETIRES the old pair the moment it
6101
+ // returns, so a credential-less call that Shopify rejects opaquely is
6102
+ // the one failure mode worth being loud about.
6103
+ client_id: required("clientId", clientId),
6104
+ client_secret: required("clientSecret", clientSecret),
6105
+ refresh_token: refreshToken
6106
+ }
6107
+ );
6108
+ const adminAccessToken = data.access_token;
6109
+ const newRefreshToken = data.refresh_token;
6110
+ const expiresIn = data.expires_in;
6111
+ const tokenExpiresAt = expiresIn ? new Date(Date.now() + expiresIn * 1e3) : null;
6112
+ const refreshTokenExpiresAt = new Date(Date.now() + REFRESH_TOKEN_LIFETIME_MS);
6113
+ let liveToken = adminAccessToken;
6114
+ if (target === "shop") {
6115
+ const written = await controller.update({
6116
+ collection: "shop",
6117
+ data: {
6118
+ $set: {
6119
+ settings: encrypt({
6120
+ ...session,
6121
+ accessToken: adminAccessToken,
6122
+ expires: tokenExpiresAt,
6123
+ refreshToken: newRefreshToken,
6124
+ refreshTokenExpires: refreshTokenExpiresAt
6125
+ })
6126
+ }
6127
+ },
6128
+ query: {
6129
+ shop,
6130
+ ...raw && { settings: raw }
6131
+ }
6132
+ });
6133
+ if (!written) {
6134
+ const current = await controller.get({ collection: "shop", query: { shop } });
6135
+ if (!(current == null ? void 0 : current.settings)) {
6136
+ throw new Error("Shopify token refresh write-back failed: shop record missing for " + shop);
6137
+ }
6138
+ ;
6139
+ const currentSession = decrypt(current.settings);
6140
+ if ((currentSession == null ? void 0 : currentSession.accessToken) && currentSession.accessToken !== settings.adminAccessToken) {
6141
+ liveToken = currentSession.accessToken;
6142
+ } else {
6143
+ throw new Error("Shopify token refresh write-back failed for " + shop);
6144
+ }
6145
+ ;
6146
+ }
6147
+ ;
6148
+ } else {
6149
+ const written = await controller.update({
6150
+ collection: "connection",
6151
+ data: {
6152
+ $set: {
6153
+ settings: encrypt({
6154
+ ...settings,
6155
+ adminAccessToken,
6156
+ refreshToken: newRefreshToken,
6157
+ refreshTokenExpiresAt,
6158
+ tokenExpiresAt
6159
+ })
6160
+ }
6161
+ },
6162
+ query: {
6163
+ id: connection.id,
6164
+ ...raw && { settings: raw }
6165
+ }
6166
+ });
6167
+ if (!written) {
6168
+ const current = await controller.get({ collection: "connection", query: { id: connection.id } });
6169
+ const currentSettings = (current == null ? void 0 : current.settings) ? decrypt(current.settings) : null;
6170
+ if ((currentSettings == null ? void 0 : currentSettings.adminAccessToken) && currentSettings.adminAccessToken !== settings.adminAccessToken) {
6171
+ liveToken = currentSettings.adminAccessToken;
6172
+ } else {
6173
+ throw new Error("Shopify token refresh write-back failed for connection " + (connection == null ? void 0 : connection.id));
6174
+ }
6175
+ ;
6176
+ }
6177
+ ;
6178
+ }
6179
+ ;
6180
+ await ping({ adminAccessToken: liveToken, domain });
6181
+ return liveToken;
6182
+ };
6183
+ var getAdminToken = async ({ fetcher, clientId, clientSecret, connection, controller }) => {
6184
+ required("clientId", clientId);
6185
+ required("clientSecret", clientSecret);
6186
+ const settings = await resolveConnectionSettings({ connection, controller });
6187
+ const { adminAccessToken, refreshToken, tokenExpiresAt } = settings;
6188
+ if (!adminAccessToken) {
6189
+ return null;
6190
+ }
6191
+ ;
6192
+ if (!refreshToken) {
6193
+ return adminAccessToken;
6194
+ }
6195
+ ;
6196
+ const needsRefresh = !tokenExpiresAt || new Date(tokenExpiresAt) < new Date(Date.now() + ACCESS_TOKEN_REFRESH_BUFFER_MS);
6197
+ if (needsRefresh) {
6198
+ return refreshAdminToken({ clientId, clientSecret, connection, controller });
6199
+ }
6200
+ ;
6201
+ return adminAccessToken;
6202
+ };
6203
+
6204
+ // lib/shopify/partner.js
6205
+ var partner_exports = {};
6206
+ __export(partner_exports, {
6207
+ getUsageChargeEvents: () => getUsageChargeEvents
6208
+ });
6209
+ var PARTNER_API = "https://partners.shopify.com";
6210
+ var getUsageChargeEvents = async ({ fetcher, appId, first = 10, occurredAtMin, organizationId, partnerToken, shopId }) => {
6211
+ var _a, _b, _c;
6212
+ if (!partnerToken || !organizationId || !appId) {
6213
+ throw new Error("getUsageChargeEvents requires partnerToken, organizationId, and appId");
6214
+ }
6215
+ ;
6216
+ const data = await request({
6217
+ fetcher,
6218
+ method: "POST",
6219
+ url: PARTNER_API + "/" + organizationId + "/api/" + PARTNER_API_VERSION + "/graphql.json",
6220
+ headers: {
6221
+ "X-Shopify-Access-Token": partnerToken
6222
+ },
6223
+ body: {
6224
+ query: `query usageCharges( $filter : EventFilterInput!, $first : Int! ) {
6225
+ events( filter : $filter, orderBy : OCCURRED_AT_DESC, first : $first ) {
6226
+ edges {
6227
+ node {
6228
+ id
6229
+ occurredAt
6230
+ eventType
6231
+ shop { id myshopifyDomain }
6232
+ ... on Charge {
6233
+ chargeId
6234
+ chargeType
6235
+ amount { amount currencyCode }
6236
+ usageQuantity
6237
+ planHandle
6238
+ description
6239
+ }
6240
+ }
6241
+ }
6242
+ pageInfo { hasNextPage endCursor }
6243
+ }
6244
+ }`,
6245
+ variables: {
6246
+ filter: {
6247
+ eventTypes: ["CHARGE_USAGE"],
6248
+ subjectId: String(appId),
6249
+ ...occurredAtMin && { occurredAtMin },
6250
+ ...shopId && { shopId: String(shopId) }
6251
+ },
6252
+ first
6253
+ }
6254
+ }
6255
+ });
6256
+ if ((_a = data == null ? void 0 : data.errors) == null ? void 0 : _a.length) {
6257
+ throw new Error("Shopify partner events query failed: " + data.errors.map((entry) => entry.message).join("; "));
6258
+ }
6259
+ ;
6260
+ return (((_c = (_b = data == null ? void 0 : data.data) == null ? void 0 : _b.events) == null ? void 0 : _c.edges) || []).map((edge) => {
6261
+ var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j;
6262
+ return {
6263
+ amount: ((_a2 = edge.node) == null ? void 0 : _a2.amount) || null,
6264
+ chargeId: ((_b2 = edge.node) == null ? void 0 : _b2.chargeId) || null,
6265
+ // USAGE vs the recurring plan charge an approval emits — the
6266
+ // disambiguator callers filter on.
6267
+ chargeType: ((_c2 = edge.node) == null ? void 0 : _c2.chargeType) || null,
6268
+ description: ((_d = edge.node) == null ? void 0 : _d.description) || null,
6269
+ eventType: ((_e = edge.node) == null ? void 0 : _e.eventType) || null,
6270
+ id: ((_f = edge.node) == null ? void 0 : _f.id) || null,
6271
+ occurredAt: ((_g = edge.node) == null ? void 0 : _g.occurredAt) || null,
6272
+ planHandle: ((_h = edge.node) == null ? void 0 : _h.planHandle) || null,
6273
+ shop: ((_i = edge.node) == null ? void 0 : _i.shop) || null,
6274
+ usageQuantity: ((_j = edge.node) == null ? void 0 : _j.usageQuantity) ?? null
6275
+ };
6276
+ });
6277
+ };
6278
+
6279
+ // lib/shopify/storefront.js
6280
+ var storefront_exports = {};
6281
+ __export(storefront_exports, {
6282
+ cartCreate: () => cartCreate,
6283
+ cartGet: () => cartGet,
6284
+ cartLinesAdd: () => cartLinesAdd,
6285
+ cartLinesRemove: () => cartLinesRemove,
6286
+ cartLinesUpdate: () => cartLinesUpdate,
6287
+ createCheckoutToken: () => createCheckoutToken,
6288
+ getProduct: () => getProduct,
6289
+ getProductVariantsPage: () => getProductVariantsPage,
6290
+ getProducts: () => getProducts,
6291
+ probeVariantsOutOfStock: () => probeVariantsOutOfStock
6292
+ });
6293
+ var SORT_KEY_MAP = {
6294
+ bestSelling: "BEST_SELLING",
6295
+ createdAt: "CREATED_AT",
6296
+ id: "ID",
6297
+ price: "PRICE",
6298
+ productType: "PRODUCT_TYPE",
6299
+ title: "TITLE",
6300
+ updatedAt: "UPDATED_AT",
6301
+ vendor: "VENDOR"
6302
+ };
6303
+ var resolveProductSort = (sort) => {
6304
+ const entry = sort && Object.entries(sort)[0];
6305
+ if (!entry) return null;
6306
+ const [field, direction] = entry;
6307
+ const sortKey = SORT_KEY_MAP[field];
6308
+ if (!sortKey) return null;
6309
+ return {
6310
+ sortKey,
6311
+ reverse: Number(direction) < 0
6312
+ };
6313
+ };
6314
+ var storefrontUrl = (domain) => `https://${domain}/api/${SHOPIFY_STOREFRONT_API_VERSION}/graphql.json`;
6315
+ var storefrontFetch = async ({ fetcher, domain, storefrontAccessToken, query, variables }) => {
6316
+ return request({
6317
+ method: "POST",
6318
+ url: storefrontUrl(domain),
6319
+ headers: {
6320
+ "X-Shopify-Storefront-Access-Token": storefrontAccessToken
6321
+ },
6322
+ body: {
6323
+ query,
6324
+ ...variables && { variables }
6325
+ }
6326
+ });
6327
+ };
6328
+ var shopCountryCache = {};
6329
+ var getShopCountry = async ({ domain, fetcher, storefrontAccessToken }) => {
6330
+ var _a, _b;
6331
+ if (shopCountryCache[domain]) return shopCountryCache[domain];
6332
+ const { data } = await storefrontFetch({
6333
+ fetcher,
6334
+ domain,
6335
+ storefrontAccessToken,
6336
+ query: `{
6337
+ shop {
6338
+ paymentSettings {
6339
+ countryCode
6340
+ }
6341
+ }
6342
+ }`
6343
+ });
6344
+ const countryCode = ((_b = (_a = data == null ? void 0 : data.shop) == null ? void 0 : _a.paymentSettings) == null ? void 0 : _b.countryCode) || null;
6345
+ if (countryCode) shopCountryCache[domain] = countryCode;
6346
+ return countryCode;
6347
+ };
6348
+ var OUT_OF_STOCK_WARNING_CODES = [
6349
+ "MERCHANDISE_OUT_OF_STOCK",
6350
+ "MERCHANDISE_NOT_ENOUGH_STOCK"
6351
+ ];
6352
+ var probeVariantsOutOfStock = async ({ fetcher, domain, storefrontAccessToken, variantIds, countryCode }) => {
6353
+ var _a, _b;
6354
+ if (!(variantIds == null ? void 0 : variantIds.length)) return [];
6355
+ const resolvedCountry = countryCode || await getShopCountry({ domain, fetcher, storefrontAccessToken });
6356
+ const { data, errors } = await storefrontFetch({
6357
+ fetcher,
6358
+ domain,
6359
+ storefrontAccessToken,
6360
+ query: `
6361
+ mutation probe( $input : CartInput! ){
6362
+ cartCreate( input : $input ){
6363
+ cart {
6364
+ lines( first : 250 ){
6365
+ edges {
6366
+ node {
6367
+ id
6368
+ merchandise {
6369
+ ... on ProductVariant {
6370
+ id
6371
+ }
6372
+ }
6373
+ }
6374
+ }
6375
+ }
6376
+ }
6377
+ warnings {
6378
+ code
6379
+ message
6380
+ target
6381
+ }
6382
+ }
6383
+ }
6384
+ `,
6385
+ variables: {
6386
+ input: {
6387
+ lines: variantIds.map((merchandiseId) => ({
6388
+ merchandiseId,
6389
+ quantity: 1
6390
+ })),
6391
+ ...resolvedCountry && {
6392
+ buyerIdentity: {
6393
+ countryCode: resolvedCountry
6394
+ }
6395
+ }
6396
+ }
6397
+ }
6398
+ });
6399
+ if (errors) return [];
6400
+ const payload = data == null ? void 0 : data.cartCreate;
6401
+ const soldOut = new Set(
6402
+ ((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)
6403
+ );
6404
+ 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 }) => {
6405
+ var _a2;
6406
+ return (_a2 = node == null ? void 0 : node.merchandise) == null ? void 0 : _a2.id;
6407
+ }).filter(Boolean);
6408
+ };
6409
+ var productsQuery = (search, cursor, limit, sort) => {
6410
+ const resolved = resolveProductSort(sort);
6411
+ const sortArgs = resolved ? `, sortKey: ${resolved.sortKey}, reverse: ${resolved.reverse}` : "";
6412
+ return `{
6413
+ products(first: ${limit}${search ? `, query: "title:*${search}*"` : ""}${cursor ? `, after: "${cursor}"` : ""}${sortArgs}) {
6414
+ edges {
6415
+ node {
6416
+ id
6417
+ title
6418
+ description
6419
+ handle
6420
+ productType
6421
+ featuredImage {
6422
+ url
6423
+ }
6424
+ variants(first: 10) {
6425
+ edges {
6426
+ node {
6427
+ id
6428
+ title
6429
+ image {
6430
+ url
6431
+ }
6432
+ price {
6433
+ amount
6434
+ currencyCode
6435
+ }
6436
+ compareAtPrice {
6437
+ amount
6438
+ currencyCode
6439
+ }
6440
+ availableForSale
6441
+ requiresShipping
6442
+ }
6443
+ }
6444
+ }
6445
+ }
6446
+ }
6447
+ pageInfo {
6448
+ endCursor
6449
+ hasNextPage
6450
+ hasPreviousPage
6451
+ startCursor
6452
+ }
6453
+ }
6454
+ }`;
6455
+ };
6456
+ var productQuery = (productId) => `{
6457
+ product(id: "${productId}") {
6458
+ id
6459
+ title
6460
+ description
6461
+ handle
6462
+ productType
6463
+ featuredImage {
6464
+ url
6465
+ }
6466
+ variants(first: 10) {
6467
+ edges {
6468
+ node {
6469
+ id
6470
+ title
6471
+ image {
6472
+ url
6473
+ }
6474
+ price {
6475
+ amount
6476
+ currencyCode
6477
+ }
6478
+ compareAtPrice {
6479
+ amount
6480
+ currencyCode
6481
+ }
6482
+ availableForSale
6483
+ requiresShipping
6484
+ }
6485
+ }
6486
+ }
6487
+ }
6488
+ }`;
6489
+ var variantsQuery = (productId, cursor) => `{
6490
+ product(id: "${productId}") {
6491
+ variants(first: 250${cursor ? `, after: "${cursor}"` : ""}) {
6492
+ edges {
6493
+ node {
6494
+ id
6495
+ title
6496
+ image {
6497
+ url
6498
+ }
6499
+ price {
6500
+ amount
6501
+ currencyCode
6502
+ }
6503
+ compareAtPrice {
6504
+ amount
6505
+ currencyCode
6506
+ }
6507
+ availableForSale
6508
+ requiresShipping
6509
+ }
6510
+ }
6511
+ pageInfo {
6512
+ hasNextPage
6513
+ endCursor
6514
+ }
6515
+ }
6516
+ }
6517
+ }`;
6518
+ var getProducts = async ({ fetcher, domain, storefrontAccessToken, search, cursor, limit, sort }) => {
6519
+ const { data, errors } = await storefrontFetch({
6520
+ fetcher,
6521
+ domain,
6522
+ storefrontAccessToken,
6523
+ query: productsQuery(search, cursor, limit, sort)
6524
+ });
6525
+ if (errors) {
6526
+ throw new Error("Failed to fetch Shopify products");
6527
+ }
6528
+ ;
6529
+ return data == null ? void 0 : data.products;
6530
+ };
6531
+ var getProduct = async ({ fetcher, domain, storefrontAccessToken, productId }) => {
6532
+ var _a;
6533
+ const { data, errors } = await storefrontFetch({
6534
+ fetcher,
6535
+ domain,
6536
+ storefrontAccessToken,
6537
+ query: productQuery(productId)
6538
+ });
6539
+ if (errors) {
6540
+ throw new Error("Shopify storefront error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
6541
+ }
6542
+ ;
6543
+ if (!(data == null ? void 0 : data.product)) {
6544
+ throw new Error("Shopify product not found");
6545
+ }
6546
+ ;
6547
+ return data.product;
6548
+ };
6549
+ var getProductVariantsPage = async ({ fetcher, domain, storefrontAccessToken, productId, cursor }) => {
6550
+ var _a;
6551
+ const { data, errors } = await storefrontFetch({
6552
+ fetcher,
6553
+ domain,
6554
+ storefrontAccessToken,
6555
+ query: variantsQuery(productId, cursor)
6556
+ });
6557
+ if (errors) {
6558
+ throw new Error("Shopify storefront error: " + ((_a = errors[0]) == null ? void 0 : _a.message));
6559
+ }
6560
+ ;
6561
+ if (!(data == null ? void 0 : data.product)) {
6562
+ throw new Error("Shopify product not found");
6563
+ }
6564
+ ;
6565
+ return data.product.variants;
6566
+ };
6567
+ var CART_FIELDS = `
6568
+ id
6569
+ checkoutUrl
6570
+ lines(first: 100) {
6571
+ edges {
6572
+ node {
6573
+ id
6574
+ quantity
6575
+ merchandise {
6576
+ ... on ProductVariant {
6577
+ id
6578
+ title
6579
+ availableForSale
6580
+ image {
6581
+ url
6582
+ }
6583
+ price {
6584
+ amount
6585
+ currencyCode
6586
+ }
6587
+ product {
6588
+ title
6589
+ }
6590
+ }
6591
+ }
6592
+ }
6593
+ }
6594
+ }
6595
+ `;
6596
+ var mapCart = (cart) => {
6597
+ var _a;
6598
+ if (!cart) return null;
6599
+ return {
6600
+ checkoutUrl: cart.checkoutUrl,
6601
+ id: cart.id,
6602
+ lines: (((_a = cart.lines) == null ? void 0 : _a.edges) || []).map(({ node }) => {
6603
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
6604
+ return {
6605
+ availableForSale: ((_a2 = node == null ? void 0 : node.merchandise) == null ? void 0 : _a2.availableForSale) ?? true,
6606
+ currency: ((_c = (_b = node == null ? void 0 : node.merchandise) == null ? void 0 : _b.price) == null ? void 0 : _c.currencyCode) || null,
6607
+ id: node.id,
6608
+ image: ((_e = (_d = node == null ? void 0 : node.merchandise) == null ? void 0 : _d.image) == null ? void 0 : _e.url) || null,
6609
+ price: ((_g = (_f = node == null ? void 0 : node.merchandise) == null ? void 0 : _f.price) == null ? void 0 : _g.amount) || null,
6610
+ productTitle: ((_i = (_h = node == null ? void 0 : node.merchandise) == null ? void 0 : _h.product) == null ? void 0 : _i.title) || null,
6611
+ quantity: node.quantity,
6612
+ variantId: (_j = node == null ? void 0 : node.merchandise) == null ? void 0 : _j.id,
6613
+ variantTitle: ((_k = node == null ? void 0 : node.merchandise) == null ? void 0 : _k.title) || null
6614
+ };
6615
+ })
6616
+ };
6617
+ };
6618
+ var firstUserError = (userErrors) => {
6619
+ const error = userErrors == null ? void 0 : userErrors[0];
6620
+ if (!error) return null;
6621
+ const message = new Error(error.message || "Shopify cart error");
6622
+ message.userError = true;
6623
+ return message;
6624
+ };
6625
+ var createCheckoutToken = async ({ fetcher, clientId, clientSecret } = {}) => {
6626
+ if (!clientId || !clientSecret) {
6627
+ throw new Error("createCheckoutToken requires clientId and clientSecret");
6628
+ }
6629
+ ;
6630
+ const response = await request({
6631
+ fetcher,
6632
+ method: "POST",
6633
+ url: "https://api.shopify.com/auth/access_token",
6634
+ body: {
6635
+ client_id: clientId,
6636
+ client_secret: clientSecret,
6637
+ grant_type: "client_credentials"
6638
+ }
6639
+ });
6640
+ const token = response == null ? void 0 : response.access_token;
6641
+ if (!token) {
6642
+ throw new Error("Failed to create Shopify checkout token");
6643
+ }
6644
+ ;
6645
+ return token;
6646
+ };
6647
+ var cartCreate = async ({ fetcher, domain, storefrontAccessToken, lines }) => {
6648
+ var _a, _b;
6649
+ const { data, errors } = await storefrontFetch({
6650
+ fetcher,
6651
+ domain,
6652
+ storefrontAccessToken,
6653
+ query: `
6654
+ mutation cartCreate($input: CartInput!) {
6655
+ cartCreate(input: $input) {
6656
+ cart {
6657
+ ${CART_FIELDS}
6658
+ }
6659
+ userErrors {
6660
+ field
6661
+ message
6662
+ }
6663
+ }
6664
+ }
6665
+ `,
6666
+ variables: {
6667
+ input: {
6668
+ lines
6669
+ }
6670
+ }
6671
+ });
6672
+ if (errors) {
6673
+ throw new Error("Failed to create Shopify cart");
6674
+ }
6675
+ ;
6676
+ const userError = firstUserError((_a = data == null ? void 0 : data.cartCreate) == null ? void 0 : _a.userErrors);
6677
+ if (userError) throw userError;
6678
+ return mapCart((_b = data == null ? void 0 : data.cartCreate) == null ? void 0 : _b.cart);
6679
+ };
6680
+ var cartGet = async ({ fetcher, domain, storefrontAccessToken, cartId }) => {
6681
+ const { data, errors } = await storefrontFetch({
6682
+ fetcher,
6683
+ domain,
6684
+ storefrontAccessToken,
6685
+ query: `
6686
+ query cart($id: ID!) {
6687
+ cart(id: $id) {
6688
+ ${CART_FIELDS}
6689
+ }
6690
+ }
6691
+ `,
6692
+ variables: {
6693
+ id: cartId
6694
+ }
6695
+ });
6696
+ if (errors) {
6697
+ throw new Error("Failed to fetch Shopify cart");
6698
+ }
6699
+ ;
6700
+ return mapCart(data == null ? void 0 : data.cart);
6701
+ };
6702
+ var cartLinesAdd = async ({ fetcher, domain, storefrontAccessToken, cartId, lines }) => {
6703
+ var _a, _b;
6704
+ const { data, errors } = await storefrontFetch({
6705
+ fetcher,
6706
+ domain,
6707
+ storefrontAccessToken,
6708
+ query: `
6709
+ mutation cartLinesAdd($cartId: ID!, $lines: [CartLineInput!]!) {
6710
+ cartLinesAdd(cartId: $cartId, lines: $lines) {
6711
+ cart {
6712
+ ${CART_FIELDS}
6713
+ }
6714
+ userErrors {
6715
+ field
6716
+ message
6717
+ }
6718
+ }
6719
+ }
6720
+ `,
6721
+ variables: {
6722
+ cartId,
6723
+ lines
6724
+ }
6725
+ });
6726
+ if (errors) {
6727
+ throw new Error("Failed to add Shopify cart lines");
6728
+ }
6729
+ ;
6730
+ const userError = firstUserError((_a = data == null ? void 0 : data.cartLinesAdd) == null ? void 0 : _a.userErrors);
6731
+ if (userError) throw userError;
6732
+ return mapCart((_b = data == null ? void 0 : data.cartLinesAdd) == null ? void 0 : _b.cart);
6733
+ };
6734
+ var cartLinesRemove = async ({ fetcher, domain, storefrontAccessToken, cartId, lineIds }) => {
6735
+ var _a, _b;
6736
+ const { data, errors } = await storefrontFetch({
6737
+ fetcher,
6738
+ domain,
6739
+ storefrontAccessToken,
6740
+ query: `
6741
+ mutation cartLinesRemove($cartId: ID!, $lineIds: [ID!]!) {
6742
+ cartLinesRemove(cartId: $cartId, lineIds: $lineIds) {
6743
+ cart {
6744
+ ${CART_FIELDS}
6745
+ }
6746
+ userErrors {
6747
+ field
6748
+ message
6749
+ }
6750
+ }
6751
+ }
6752
+ `,
6753
+ variables: {
6754
+ cartId,
6755
+ lineIds
6756
+ }
6757
+ });
6758
+ if (errors) {
6759
+ throw new Error("Failed to remove Shopify cart lines");
6760
+ }
6761
+ ;
6762
+ const userError = firstUserError((_a = data == null ? void 0 : data.cartLinesRemove) == null ? void 0 : _a.userErrors);
6763
+ if (userError) throw userError;
6764
+ return mapCart((_b = data == null ? void 0 : data.cartLinesRemove) == null ? void 0 : _b.cart);
6765
+ };
6766
+ var cartLinesUpdate = async ({ fetcher, domain, storefrontAccessToken, cartId, lines }) => {
6767
+ var _a, _b;
6768
+ const { data, errors } = await storefrontFetch({
6769
+ fetcher,
6770
+ domain,
6771
+ storefrontAccessToken,
6772
+ query: `
6773
+ mutation cartLinesUpdate($cartId: ID!, $lines: [CartLineUpdateInput!]!) {
6774
+ cartLinesUpdate(cartId: $cartId, lines: $lines) {
6775
+ cart {
6776
+ ${CART_FIELDS}
6777
+ }
6778
+ userErrors {
6779
+ field
6780
+ message
6781
+ }
6782
+ }
6783
+ }
6784
+ `,
6785
+ variables: {
6786
+ cartId,
6787
+ lines
6788
+ }
6789
+ });
6790
+ if (errors) {
6791
+ throw new Error("Failed to update Shopify cart lines");
6792
+ }
6793
+ ;
6794
+ const userError = firstUserError((_a = data == null ? void 0 : data.cartLinesUpdate) == null ? void 0 : _a.userErrors);
6795
+ if (userError) throw userError;
6796
+ return mapCart((_b = data == null ? void 0 : data.cartLinesUpdate) == null ? void 0 : _b.cart);
6797
+ };
6798
+
6799
+ // lib/email.js
6800
+ var GMAIL_DOMAINS = /* @__PURE__ */ new Set(["gmail.com", "googlemail.com"]);
6801
+ var toCanonicalEmail = (value) => {
6802
+ if (!value || typeof value !== "string") return null;
6803
+ const email = value.trim().toLowerCase();
6804
+ const at = email.lastIndexOf("@");
6805
+ if (at < 1 || at === email.length - 1) return null;
6806
+ let local = email.slice(0, at);
6807
+ const domain = email.slice(at + 1);
6808
+ const plus = local.indexOf("+");
6809
+ if (plus > 0) local = local.slice(0, plus);
6810
+ if (GMAIL_DOMAINS.has(domain)) local = local.replaceAll(".", "");
6811
+ if (!local) return null;
6812
+ return local + "@" + domain;
6813
+ };
6814
+
6815
+ // lib/oauth/index.js
6816
+ var lifetimes = {
6817
+ access: 60 * 60 * 8,
6818
+ // 8 hours
6819
+ authorizationCode: 10 * 60,
6820
+ // 10 minutes
6821
+ code: 15 * 60,
6822
+ // 15 minutes (email OTC)
6823
+ refresh: 30 * 24 * 60 * 60
6824
+ // 30 days
6825
+ };
6826
+ var tokenTypes = {
6827
+ access: "access",
6828
+ oauthState: "oauth.state",
6829
+ pat: "pat",
6830
+ refresh: "refresh"
6831
+ };
6832
+ var scopes = [
6833
+ "profile:read",
6834
+ "profile:write",
6835
+ "organization:read",
6836
+ "organization:write",
6837
+ "campaigns:read",
6838
+ "campaigns:write",
6839
+ "contacts:read",
6840
+ "contacts:write",
6841
+ "workflows:read",
6842
+ "workflows:write",
6843
+ "connections:read",
6844
+ "connections:write",
6845
+ "billing:read",
6846
+ "billing:write",
6847
+ "admin"
6848
+ ];
6849
+ var developer = [
6850
+ "profile:read",
6851
+ "organization:read",
6852
+ "campaigns:read",
6853
+ "campaigns:write",
6854
+ "contacts:read",
6855
+ "contacts:write",
6856
+ "workflows:read",
6857
+ "workflows:write",
6858
+ "connections:read",
6859
+ "connections:write"
6860
+ ];
6861
+ var scopeLabels = {
6862
+ "profile:read": "Read own profile",
6863
+ "profile:write": "Update own profile",
6864
+ "organization:read": "Read organization info",
6865
+ "organization:write": "Manage organization",
6866
+ "campaigns:read": "Read campaigns",
6867
+ "campaigns:write": "Manage campaigns",
6868
+ "contacts:read": "Read contacts",
6869
+ "contacts:write": "Manage contacts",
6870
+ "workflows:read": "Read workflows",
6871
+ "workflows:write": "Manage workflows",
6872
+ "connections:read": "Read integrations",
6873
+ "connections:write": "Manage integrations",
6874
+ "billing:read": "Read billing",
6875
+ "billing:write": "Manage billing",
6876
+ admin: "Admin access"
6877
+ };
6878
+ var toOption = (scope) => ({
6879
+ key: scopeLabels[scope] || scope,
6880
+ value: scope
6881
+ });
6882
+ var developerOptions = developer.map(toOption);
6883
+ var scopeOptions = scopes.map(toOption);
6884
+ var hashToken = (raw) => hash(raw, process.env.HMAC_OAUTH_TOKEN_KEY);
6885
+
6886
+ // lib/sanitize.js
6887
+ import disposableDomains from "disposable-email-domains/index.js";
6888
+ var disposableBlacklist = new Set(disposableDomains.map((d) => d.toLowerCase()));
6889
+ var sanitizeDomain = (value, pattern) => {
6890
+ if (!value) return value;
6891
+ const cleaned = value.trim().toLowerCase().replace(/^https?:\/\//i, "").replace(/\/+$/, "");
6892
+ if (pattern) {
6893
+ const match = cleaned.match(pattern);
6894
+ return match ? match[0] : cleaned;
6895
+ }
6896
+ return cleaned;
6897
+ };
6898
+
6899
+ // lib/slugify.js
6900
+ import slug from "slugify";
6901
+ var slugify = (value, nochars = false) => {
6902
+ const remove = nochars ? /[-?*+~.()'"!:@#^_{}\[\];,/\\]/g : /[?*+~.()'"!:@#^_{}\[\];,/\\]/g;
6903
+ const replacement = nochars ? "" : "-";
6904
+ return slug(
6905
+ value,
6906
+ {
6907
+ remove,
6908
+ replacement,
6909
+ lower: true,
6910
+ trim: true
6911
+ }
6912
+ );
6913
+ };
6914
+
6915
+ // lib/connections/manifests/shopify.js
6916
+ var client = Object.freeze({
6917
+ admin: admin_exports,
6918
+ billing: billing_exports,
6919
+ oauth: oauth_exports,
6920
+ partner: partner_exports,
6921
+ storefront: storefront_exports
6922
+ });
6923
+ var toLine = ({
6924
+ price,
6925
+ product_id: productId,
6926
+ quantity,
6927
+ title,
6928
+ variant_id: variantId,
6929
+ variant_title: variantTitle
6930
+ }) => ({
6931
+ price: parseFloat(price) || 0,
6932
+ productId: productId ? "gid://shopify/Product/" + productId : null,
6933
+ quantity: quantity || 1,
6934
+ title: title || null,
6935
+ variantId: variantId ? "gid://shopify/ProductVariant/" + variantId : null,
6936
+ variantTitle: variantTitle || null
6937
+ });
6938
+ var attributeLineItems = (lineItems = []) => lineItems.reduce(
6939
+ (acc, item) => {
6940
+ const attrs = (item.properties || []).reduce(
6941
+ (map, { name, value }) => {
6942
+ map[name] = value;
6943
+ return map;
6944
+ },
6945
+ {}
6946
+ );
6947
+ if (!attrs["_drwbrdg_ca"]) return acc;
6948
+ if (!Object.keys(acc.attrMap).length) acc.attrMap = attrs;
6949
+ const line = toLine(item);
6950
+ acc.attributedGross += line.price * line.quantity;
6951
+ acc.attributedLines.push(line);
6952
+ return acc;
6953
+ },
6954
+ { attrMap: {}, attributedGross: 0, attributedLines: [] }
6955
+ );
6956
+ var generateDiscountCode = customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8);
6957
+ var blockedReason = (discount) => {
6958
+ var _a;
6959
+ if ((discount == null ? void 0 : discount.status) === "EXPIRED") return "This discount has expired.";
6960
+ const buyers = (_a = discount == null ? void 0 : discount.context) == null ? void 0 : _a.__typename;
6961
+ if (buyers && buyers !== "DiscountBuyerSelectionAll") {
6962
+ 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.";
6963
+ }
6964
+ ;
6965
+ if (typeof (discount == null ? void 0 : discount.usageLimit) === "number" && discount.usageLimit > 0 && ((discount == null ? void 0 : discount.asyncUsageCount) || 0) >= discount.usageLimit) {
6966
+ return "This discount has reached its total usage limit.";
6967
+ }
6968
+ ;
6969
+ return null;
6970
+ };
6971
+ var discountWarning = (discount) => {
6972
+ if ((discount == null ? void 0 : discount.status) === "SCHEDULED") {
6973
+ return "This discount hasn't started yet, so codes issued before it does won't work until then.";
6974
+ }
6975
+ ;
6976
+ if (discount == null ? void 0 : discount.appliesOncePerCustomer) return "Each customer can use this discount only once.";
6977
+ return null;
6978
+ };
6979
+ var ORDER_EVENT_HANDLE = slugify("drawbridge-orders");
6980
+ var REFRESH_TOKEN_FRESHNESS_BUFFER_MS = 5 * 24 * 60 * 60 * 1e3;
6981
+ var OAUTH_ERROR_SOURCE = "oauth";
6982
+ var BILLING_ERROR_SOURCE = "billing";
6983
+ var BILLING_ERROR_MESSAGE = "Order billing isn't set up for this store \u2014 reselect and approve the plan from the Shopify connection page.";
6984
+ var OAUTH_GRANT_REVOKED_CODES = ["application_cannot_be_found", "invalid_grant"];
6985
+ var inbound = {
6986
+ headers: {
6987
+ event: "x-shopify-topic",
6988
+ id: "x-shopify-webhook-id",
6989
+ shop: "x-shopify-shop-domain",
6990
+ signature: "x-shopify-hmac-sha256"
6991
+ },
6992
+ signature: {
6993
+ algorithm: "sha256",
6994
+ encoding: "base64",
6995
+ secret: "SHOPIFY_API_SECRET"
6996
+ }
6997
+ };
6998
+ var COMPLIANCE_TOPICS = /* @__PURE__ */ new Set([
6999
+ "customers/data_request",
7000
+ "customers/redact",
7001
+ "shop/redact"
7002
+ ]);
7003
+ var refusal = (message, status) => Object.assign(new Error(message), { status });
7004
+ var LINK_TOKEN_TTL_MS = 30 * 60 * 1e3;
7005
+ var CONNECTABLE_STATUSES = ["active", "unsubscribed"];
7006
+ var merchantOrganizations = ({ read, user }) => read.aggregate({
7007
+ collection: "organization",
7008
+ pipeline: [
7009
+ // A member qualifies only at `manage`; an owner always qualifies.
7010
+ {
7011
+ $lookup: {
7012
+ as: "membership",
7013
+ from: "member",
7014
+ let: { organization: "$id" },
7015
+ pipeline: [
7016
+ {
7017
+ $match: {
7018
+ $expr: { $eq: ["$organization", "$$organization"] },
7019
+ "capabilities.connections": "manage",
7020
+ status: "accepted",
7021
+ user
7022
+ }
7023
+ },
7024
+ { $limit: 1 },
7025
+ { $project: { _id: 0, organization: 1 } }
7026
+ ]
7027
+ }
7028
+ },
7029
+ {
7030
+ $match: {
7031
+ status: { $ne: "canceled" },
7032
+ $or: [{ owner: user }, { "membership.0": { $exists: true } }]
7033
+ }
7034
+ },
7035
+ // `organization.subscription` is a subscription RECORD ID — resolved here so
7036
+ // the list can read the real plan and conversion rate. Without it every org
7037
+ // rendered as free tier.
7038
+ { $lookup: { as: "subscription", foreignField: "id", from: "subscription", localField: "subscription" } },
7039
+ { $unwind: { path: "$subscription", preserveNullAndEmptyArrays: true } },
7040
+ {
7041
+ $lookup: {
7042
+ as: "connection",
7043
+ foreignField: "organization",
7044
+ from: "connection",
7045
+ localField: "id",
7046
+ pipeline: [
7047
+ { $match: { slug: "shopify" } },
7048
+ { $limit: 1 },
7049
+ { $project: { _id: 0, id: 1, shop: 1, status: 1 } }
7050
+ ]
7051
+ }
7052
+ },
7053
+ { $unwind: { path: "$connection", preserveNullAndEmptyArrays: true } },
7054
+ { $project: { _id: 0, billingStatus: "$status", connection: 1, id: 1, name: "$title", subscription: 1 } },
7055
+ { $sort: { name: 1 } }
7056
+ ]
7057
+ });
7058
+ var storePlan = async ({ record, shopify }) => {
7059
+ var _a;
7060
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
7061
+ if (!(settings == null ? void 0 : settings.accessToken)) return { active: false, name: null };
7062
+ try {
7063
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
7064
+ adminAccessToken: settings.accessToken,
7065
+ domain: record.shop
7066
+ });
7067
+ const active = (subscriptions || []).length > 0;
7068
+ const metered = active && subscriptions.some((subscription) => subscription.metered === true) ? true : null;
7069
+ return { active, metered, name: active ? ((_a = subscriptions[0]) == null ? void 0 : _a.name) || null : null };
7070
+ } catch (_) {
7071
+ return { active: false, name: null, unavailable: true };
7072
+ }
7073
+ };
7074
+ var releaseApprovals = async ({ context, read, shopify }) => {
7075
+ var _a;
7076
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
7077
+ if (!shop) throw refusal("shop is required", 400);
7078
+ const record = await read.get({ collection: "shop", query: { shop } });
7079
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
7080
+ if (!(settings == null ? void 0 : settings.accessToken)) throw refusal("Store is not installed", 409);
7081
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
7082
+ adminAccessToken: settings.accessToken,
7083
+ domain: shop
7084
+ });
7085
+ for (const subscription of subscriptions || []) {
7086
+ const data = await shopify.admin.adminFetch({
7087
+ adminAccessToken: settings.accessToken,
7088
+ domain: shop,
7089
+ query: "mutation appSubscriptionCancel( $id : ID! ) { appSubscriptionCancel( id : $id ) { appSubscription { id status } userErrors { field message } } }",
7090
+ variables: { id: subscription.id }
7091
+ });
7092
+ const [userError] = ((_a = data == null ? void 0 : data.appSubscriptionCancel) == null ? void 0 : _a.userErrors) || [];
7093
+ if (userError) throw refusal(userError.message, 422);
7094
+ }
7095
+ return {
7096
+ message: "Released " + (subscriptions || []).length + " approval(s).",
7097
+ request: { shop },
7098
+ result: { ok: true }
7099
+ };
7100
+ };
7101
+ var LEDGER_WINDOW_MS = 30 * 24 * 60 * 60 * 1e3;
7102
+ var meterVerdict = async ({ adminAccessToken, ledgerFloor, partner, shop, shopId, shopify }) => {
7103
+ var _a;
7104
+ const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({ adminAccessToken, domain: shop });
7105
+ let metered = (_a = subscriptions.find((subscription) => subscription.usageLineItemId)) == null ? void 0 : _a.usageLineItemId;
7106
+ if (!((partner == null ? void 0 : partner.partnerToken) && (partner == null ? void 0 : partner.partnerOrgId) && (partner == null ? void 0 : partner.partnerAppId) && shopId)) {
7107
+ return { boundaries: [], ledger: false, metered };
7108
+ }
7109
+ const accruals = await shopify.partner.getUsageChargeEvents({
7110
+ appId: "gid://shopify/App/" + partner.partnerAppId,
7111
+ first: 10,
7112
+ occurredAtMin: ledgerFloor.toISOString(),
7113
+ organizationId: partner.partnerOrgId,
7114
+ partnerToken: partner.partnerToken,
7115
+ shopId: "gid://shopify/Shop/" + shopId
7116
+ });
7117
+ const boundaries = (accruals || []).filter((event) => event.occurredAt).sort((a, b) => new Date(a.occurredAt) - new Date(b.occurredAt));
7118
+ const accrued = [...boundaries].reverse().find((event) => Number(event.usageQuantity) > 0);
7119
+ if (accrued) metered = String(accrued.chargeId || accrued.id);
7120
+ return { boundaries, ledger: true, metered };
7121
+ };
7122
+ var toVariant = (edge) => {
7123
+ var _a, _b, _c, _d;
7124
+ return {
7125
+ availableForSale: edge.node.availableForSale || false,
7126
+ currency: ((_a = edge.node.price) == null ? void 0 : _a.currencyCode) || null,
7127
+ id: edge.node.id,
7128
+ image: ((_b = edge.node.image) == null ? void 0 : _b.url) || null,
7129
+ price: parseFloat((_c = edge.node.price) == null ? void 0 : _c.amount) || null,
7130
+ requiresShipping: edge.node.requiresShipping || false,
7131
+ sale: parseFloat((_d = edge.node.compareAtPrice) == null ? void 0 : _d.amount) || null,
7132
+ title: edge.node.title !== "Default Title" ? edge.node.title : null
7133
+ };
7134
+ };
7135
+ var applyOutOfStock = async ({ domain, shopify, storefrontAccessToken, variants }) => {
7136
+ try {
7137
+ const outOfStock = new Set(await shopify.storefront.probeVariantsOutOfStock({
7138
+ domain,
7139
+ storefrontAccessToken,
7140
+ variantIds: variants.map((variant) => variant.id)
7141
+ }));
7142
+ return variants.map((variant) => ({
7143
+ ...variant,
7144
+ availableForSale: variant.availableForSale && !outOfStock.has(variant.id)
7145
+ }));
7146
+ } catch (_) {
7147
+ return variants;
7148
+ }
7149
+ };
7150
+ var sendFeedback = async ({ adminToken, connection, messages, productId, shopify, state }) => {
7151
+ try {
7152
+ await shopify.admin.sendProductResourceFeedback({
7153
+ adminAccessToken: await adminToken(),
7154
+ domain: connection.shop,
7155
+ messages,
7156
+ productId,
7157
+ state
7158
+ });
7159
+ return null;
7160
+ } catch (error) {
7161
+ return error;
7162
+ }
7163
+ };
7164
+ var resolveProduct = async ({ connection, context, read }) => {
7165
+ const byId = (context == null ? void 0 : context.product) ? await read.get({ collection: "product", query: { id: context.product } }) : null;
7166
+ const row2 = byId || ((context == null ? void 0 : context.providerId) && ((context == null ? void 0 : context.shop) || (connection == null ? void 0 : connection.shop)) ? await read.get({
7167
+ collection: "product",
7168
+ query: {
7169
+ "provider.id": context.providerId,
7170
+ "provider.slug": "shopify",
7171
+ "source.domain": context.shop || connection.shop
7172
+ }
7173
+ }) : null);
7174
+ return row2;
7175
+ };
7176
+ var UNAVAILABLE_FEEDBACK = "Drawbridge can't display this product. Check it is active and available in the United States.";
7177
+ var NOT_FOUND = "Shopify product not found";
7178
+ var syncProduct = async ({ adminToken, connection, context, read, settings, shopify }) => {
7179
+ var _a, _b, _c;
7180
+ const row2 = await resolveProduct({ connection, context, read });
7181
+ if (!row2) return { message: "No product row to sync.", request: { product: (context == null ? void 0 : context.product) || null }, skipped: true };
7182
+ const domain = connection.shop;
7183
+ const providerId = (_a = row2.provider) == null ? void 0 : _a.id;
7184
+ const request2 = { product: row2.id, providerId: providerId || null, shop: domain };
7185
+ let product;
7186
+ try {
7187
+ product = await shopify.storefront.getProduct({
7188
+ domain,
7189
+ productId: providerId,
7190
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken
7191
+ });
7192
+ } catch (error) {
7193
+ if (error.message !== NOT_FOUND) throw error;
7194
+ const failed2 = await sendFeedback({
7195
+ adminToken,
7196
+ connection,
7197
+ messages: [UNAVAILABLE_FEEDBACK],
7198
+ productId: providerId,
7199
+ shopify,
7200
+ state: "REQUIRES_ACTION"
7201
+ });
7202
+ return {
7203
+ failed: failed2 ? [failed2.message] : void 0,
7204
+ message: "Storefront cannot see this product \u2014 deactivated.",
7205
+ request: request2,
7206
+ result: { status: "inactive" },
7207
+ writes: [
7208
+ {
7209
+ collection: "product",
7210
+ data: { $set: { status: "inactive" } },
7211
+ operation: "update",
7212
+ query: { id: row2.id }
7213
+ },
7214
+ {
7215
+ collection: "advertisement",
7216
+ data: { $set: { status: "drafted" } },
7217
+ multiple: true,
7218
+ operation: "update",
7219
+ query: { product: row2.id }
7220
+ }
7221
+ ]
7222
+ };
7223
+ }
7224
+ const variants = await applyOutOfStock({
7225
+ domain,
7226
+ shopify,
7227
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken,
7228
+ variants: (((_b = product == null ? void 0 : product.variants) == null ? void 0 : _b.edges) || []).map(toVariant)
7229
+ });
7230
+ const failed = await sendFeedback({
7231
+ adminToken,
7232
+ connection,
7233
+ messages: [],
7234
+ productId: providerId,
7235
+ shopify,
7236
+ state: "ACCEPTED"
7237
+ });
7238
+ return {
7239
+ // EVERYTHING PAST THE FIRST PAGE, filled in silently. The first page is
7240
+ // written above; a product with thousands of variants becomes N short
7241
+ // sequential jobs rather than one long loop that risks a BullMQ stall.
7242
+ enqueues: [{
7243
+ data: { operation: "variants", product: row2.id },
7244
+ name: "sync",
7245
+ options: { jobId: "product.shopify.variants." + row2.id + "." + Date.now() },
7246
+ queue: "product.shopify.variants"
7247
+ }],
7248
+ failed: failed ? [failed.message] : void 0,
7249
+ message: "Synced " + (product.title || "product") + ".",
7250
+ request: request2,
7251
+ result: { status: "active", variants: variants.length },
7252
+ writes: [{
7253
+ collection: "product",
7254
+ data: {
7255
+ $set: {
7256
+ description: product.description || null,
7257
+ image: ((_c = product.featuredImage) == null ? void 0 : _c.url) || null,
7258
+ // A successful sync PROVES channel visibility, which reverses the
7259
+ // deactivation above. Ads stay drafted.
7260
+ status: "active",
7261
+ title: product.title || null,
7262
+ type: product.productType || null,
7263
+ url: domain && product.handle ? "https://" + domain + "/products/" + product.handle : null,
7264
+ variants
7265
+ }
7266
+ },
7267
+ operation: "update",
7268
+ query: { id: row2.id }
7269
+ }]
7270
+ };
7271
+ };
7272
+ var syncVariants = async ({ connection, context, read, settings, shopify }) => {
7273
+ var _a, _b, _c;
7274
+ const row2 = await resolveProduct({ connection, context, read });
7275
+ if (!row2) return { message: "No product row to paginate.", request: { product: (context == null ? void 0 : context.product) || null }, skipped: true };
7276
+ const cursor = (context == null ? void 0 : context.cursor) || null;
7277
+ const request2 = { cursor, product: row2.id };
7278
+ let page;
7279
+ try {
7280
+ page = await shopify.storefront.getProductVariantsPage({
7281
+ cursor,
7282
+ domain: connection.shop,
7283
+ productId: (_a = row2.provider) == null ? void 0 : _a.id,
7284
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken
7285
+ });
7286
+ } catch (error) {
7287
+ if (error.message !== NOT_FOUND) throw error;
7288
+ return { message: "Storefront lost this product mid-pagination \u2014 stopping.", request: request2, skipped: true };
7289
+ }
7290
+ const variants = await applyOutOfStock({
7291
+ domain: connection.shop,
7292
+ shopify,
7293
+ storefrontAccessToken: settings == null ? void 0 : settings.storefrontAccessToken,
7294
+ variants: (page.edges || []).map(toVariant)
7295
+ });
7296
+ return {
7297
+ ...((_b = page.pageInfo) == null ? void 0 : _b.hasNextPage) && { enqueues: [{
7298
+ data: { cursor: page.pageInfo.endCursor, operation: "variants", product: row2.id },
7299
+ name: "page",
7300
+ options: { jobId: "product.shopify.variants." + row2.id + "." + Date.now() },
7301
+ queue: "product.shopify.variants"
7302
+ }] },
7303
+ message: variants.length + " variant(s) on this page.",
7304
+ request: request2,
7305
+ result: { hasNextPage: Boolean((_c = page.pageInfo) == null ? void 0 : _c.hasNextPage), variants: variants.length },
7306
+ writes: [{
7307
+ collection: "product",
7308
+ data: cursor ? { $push: { variants: { $each: variants } } } : { $set: { variants } },
7309
+ operation: "update",
7310
+ query: { id: row2.id }
7311
+ }]
7312
+ };
7313
+ };
7314
+ var shopify_default2 = {
7315
+ // THE WORDS ON THE BUTTONS. `listing` was `content.redirect.title`, which put
7316
+ // a BUTTON LABEL inside the copy object next to a url — the title and the
7317
+ // address it belongs to sat at different levels and could drift apart.
7318
+ //
7319
+ // It names where the link GOES rather than what it does: installing happens on
7320
+ // the App Store listing, and the dashboard must never imply a store can be
7321
+ // linked from inside it.
7322
+ actions: {
7323
+ create: null,
7324
+ listing: "View on the Shopify App Store",
7325
+ manage: null,
7326
+ update: null
7327
+ },
7328
+ // INSTALL, not oauth. The grant is an OAuth grant, but the merchant never
7329
+ // sees a consent screen we sent them to -- they start at the App Store, and
7330
+ // the install completes inside Shopify admin without redirecting back. A
7331
+ // Connect button here would be lying about where connecting happens.
7332
+ auth: {
7333
+ // ONE STORE PER ORGANIZATION. A Shopify install IS a store, and a second
5160
7334
  // one would give an organization two catalogues, two order streams and two
5161
7335
  // usage meters with nothing to say which is authoritative.
5162
7336
  //
@@ -5323,8 +7497,8 @@ var shopify_default2 = {
5323
7497
  // string; this answers what is missing from it.
5324
7498
  //
5325
7499
  // `shopify` is injected for the same reason it is everywhere else — this
5326
- // package cannot import @drawbridge/shopify, which depends on it.
5327
- scopes: ({ scope }, { shopify } = {}) => ({ result: { missing: scope ? shopify.oauth.missingScopes(scope) : null } }),
7500
+ // client is imported here and defaulted, never wired in by a caller.
7501
+ scopes: ({ scope }, { shopify = client } = {}) => ({ result: { missing: scope ? shopify.oauth.missingScopes(scope) : null } }),
5328
7502
  // Shopify's install grant is exchanged inside its own app flow, not
5329
7503
  // through the shared OAuth runner.
5330
7504
  token: false
@@ -5338,17 +7512,53 @@ var shopify_default2 = {
5338
7512
  // can reference another), `dispatch` (the caller's own coordinator table,
5339
7513
  // for the hooks that are dispatches).
5340
7514
  commerce: {
5341
- // NOT YET. The Checkout Kit cart path is `api/route/subdomain.js`, six direct
5342
- // calls into `@drawbridge/shopify/storefront` that write nothing — which is
5343
- // exactly why it never became a hook: a hook is reached to have its effects
5344
- // performed, and this one has none to perform. It moves here when the vendor
5345
- // client moves into the manifest and `subdomain.js` stops importing the
5346
- // package directly.
5347
- cart: false,
7515
+ // THE CHECKOUT KIT CART. Six operations that were six direct calls into
7516
+ // the storefront client from api/route/subdomain.js.
7517
+ //
7518
+ // IT WRITES NOTHING, which is exactly why it was the last surface to
7519
+ // become a hook a hook is usually reached to have its effects performed
7520
+ // and this one has none. That reasoning was wrong: a hook is also the one
7521
+ // place a vendor's client is allowed to be called from, and leaving the
7522
+ // cart out meant a public route importing a vendor SDK directly.
7523
+ //
7524
+ // ONE HOOK, OPERATION IN THE CONTEXT, the same shape `inbound.process`
7525
+ // uses for its topic table. Six slots would be six names in the closed
7526
+ // vocabulary for one question — what does this shopper's cart look like
7527
+ // now — asked six ways.
7528
+ //
7529
+ // A USER ERROR IS A 400 AND THE SHOPPER'S OWN WORDS. Shopify's cart
7530
+ // mutations answer "that variant is sold out" as a userError rather than a
7531
+ // transport failure, and the route it replaced already told the two apart.
7532
+ // runHook carries `status` off a thrown error, so it survives to the
7533
+ // caller; the rest of a thrown error's shape does not.
7534
+ cart: async ({ clientId, clientSecret, context, settings }, { fetcher, shopify = client } = {}) => {
7535
+ const { cartId, lineIds, lines, operation } = context || {};
7536
+ const { domain, storefrontAccessToken } = settings || {};
7537
+ if (operation === "checkout") {
7538
+ const token = await shopify.storefront.createCheckoutToken({ clientId, clientSecret, fetcher });
7539
+ return { message: "Checkout token minted.", result: { token } };
7540
+ }
7541
+ const storefront = { domain, fetcher, storefrontAccessToken };
7542
+ try {
7543
+ const cart = await ({
7544
+ create: () => shopify.storefront.cartCreate({ ...storefront, lines }),
7545
+ get: () => shopify.storefront.cartGet({ ...storefront, cartId }),
7546
+ linesAdd: () => shopify.storefront.cartLinesAdd({ ...storefront, cartId, lines }),
7547
+ linesRemove: () => shopify.storefront.cartLinesRemove({ ...storefront, cartId, lineIds }),
7548
+ linesUpdate: () => shopify.storefront.cartLinesUpdate({ ...storefront, cartId, lines })
7549
+ }[operation] || (() => {
7550
+ throw Object.assign(new Error("Unknown cart operation: " + operation), { status: 400 });
7551
+ }))();
7552
+ return { message: "Cart " + operation + ".", request: { cartId: cartId || null, operation }, result: cart };
7553
+ } catch (error) {
7554
+ if (error == null ? void 0 : error.userError) throw Object.assign(error, { status: 400 });
7555
+ throw error;
7556
+ }
7557
+ },
5348
7558
  // MINT A DISCOUNT CODE against the merchant's chosen discount, mapped to
5349
7559
  // one lead — which is what lets an order that redeems it be attributed
5350
7560
  // back.
5351
- code: async ({ connection, context, step }, { adminToken, shopify } = {}) => {
7561
+ code: async ({ connection, context, step }, { adminToken, shopify = client } = {}) => {
5352
7562
  var _a;
5353
7563
  const discount = (_a = step.settings) == null ? void 0 : _a.discount;
5354
7564
  const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection.shop };
@@ -5394,7 +7604,7 @@ var shopify_default2 = {
5394
7604
  // customer at the store is a support ticket: the context may already
5395
7605
  // carry the id from an earlier step, the lead may already be linked from
5396
7606
  // an earlier run, and Shopify's own get-or-create settles the rest.
5397
- customer: async ({ connection, context }, { adminToken, read, shopify } = {}) => {
7607
+ customer: async ({ connection, context }, { adminToken, read, shopify = client } = {}) => {
5398
7608
  const request2 = { email: (context == null ? void 0 : context.email) || null, lead: (context == null ? void 0 : context.lead) || null, shop: connection.shop };
5399
7609
  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 };
5400
7610
  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 };
@@ -5444,6 +7654,30 @@ var shopify_default2 = {
5444
7654
  }]
5445
7655
  };
5446
7656
  },
7657
+ // HOW MANY ARE LEFT. Read at the moment a campaign's product list is
7658
+ // rendered rather than stored on the product, because stock is the one
7659
+ // product fact that is stale the instant it is written down.
7660
+ //
7661
+ // SUMMED HERE, not by the caller. Shopify answers per variant and every
7662
+ // caller wanted the total; the one that existed summed it inline, and
7663
+ // summing `Object.values()` over the raw map is how a cache wrapper's own
7664
+ // bookkeeping key got counted as a quantity.
7665
+ inventory: async ({ connection, context }, { adminToken, shopify = client } = {}) => {
7666
+ const productId = context == null ? void 0 : context.product;
7667
+ const request2 = { product: productId || null, shop: connection.shop };
7668
+ if (!productId) return { message: "No product id \u2014 nothing to count.", request: request2, result: { total: null }, skipped: true };
7669
+ const adminAccessToken = await adminToken();
7670
+ const byVariant = await shopify.admin.getProductInventory({
7671
+ adminAccessToken,
7672
+ domain: connection.shop,
7673
+ productId
7674
+ });
7675
+ return {
7676
+ message: "Inventory read.",
7677
+ request: request2,
7678
+ result: { total: Object.values(byVariant || {}).reduce((sum, quantity) => sum + quantity, 0) }
7679
+ };
7680
+ },
5447
7681
  // AN ORDER ARRIVED AT THE STORE. The largest hook in the family, because
5448
7682
  // attribution genuinely is: an order can reach Drawbridge two ways and
5449
7683
  // they bill differently.
@@ -5803,10 +8037,28 @@ var shopify_default2 = {
5803
8037
  //
5804
8038
  // The shell has already refused a missing or inactive Shopify connection,
5805
8039
  // so what is left is the two things only this hook can know are wrong.
5806
- product: async ({ connection, context, workflow }, { mintId, read } = {}) => {
8040
+ // A PRODUCT, IN THREE MOVES. Nested by operation rather than by three
8041
+ // slots in the closed vocabulary, the same shape inbound.process uses
8042
+ // for its topic table — they are one subject, and a vendor that syncs
8043
+ // products has to answer all three or none.
8044
+ //
8045
+ // record a webhook said a product changed: upsert the row and
8046
+ // queue the pull
8047
+ // sync pull the product from the storefront and write what it
8048
+ // says, including what it says by NOT answering
8049
+ // variants one page of variants, self-chaining
8050
+ //
8051
+ // `sync` and `variants` were 443 lines of drawbridge-sync's
8052
+ // queue/product.js — a shadow implementation of the step this manifest
8053
+ // already declared, importing three of the vendor's client modules from
8054
+ // a worker file.
8055
+ product: async ({ connection, context, settings, workflow }, { adminToken, mintId, read, shopify = client } = {}) => {
8056
+ const operation = (context == null ? void 0 : context.operation) || "record";
8057
+ if (operation === "sync") return syncProduct({ adminToken, connection, context, read, settings, shopify });
8058
+ if (operation === "variants") return syncVariants({ connection, context, read, settings, shopify });
5807
8059
  const request2 = {
5808
8060
  numericId: (context == null ? void 0 : context.id) || null,
5809
- organizationId: workflow.organization,
8061
+ organizationId: (workflow == null ? void 0 : workflow.organization) || null,
5810
8062
  title: (context == null ? void 0 : context.title) || null
5811
8063
  };
5812
8064
  if (!(context == null ? void 0 : context.id)) return { message: "Skipped \u2014 product webhook payload had no id.", request: request2, response: { skipped: true }, skipped: true };
@@ -5856,9 +8108,612 @@ var shopify_default2 = {
5856
8108
  }
5857
8109
  },
5858
8110
  contacts: { remove: false, sync: false },
5859
- // The embedded-app surface. Only a vendor whose merchants arrive from its
5860
- // own app store has one.
5861
- install: false,
8111
+ // THE EMBEDDED-APP SURFACE. Only a vendor whose merchants arrive from its
8112
+ // own app store has one, and these thirteen slots are the thirteen routes
8113
+ // that used to live in api/route/shopify-embedded.js.
8114
+ //
8115
+ // A HOOK DESCRIBES ITS WRITES and the shell performs them, so none of these
8116
+ // holds a controller — `read` is the controller's read methods and nothing
8117
+ // else. Where one REFUSES it throws with a status, and the route answers
8118
+ // what it said. The helpers they share are above the manifest.
8119
+ install: {
8120
+ account: {
8121
+ // ESTABLISH THE DURABLE MERCHANT-TO-STORE LINK. The breakout
8122
+ // authenticates the merchant once, top-level, and stashes their user
8123
+ // token in `install.token.save`; App Bridge has already proven shop
8124
+ // control by the time this runs.
8125
+ //
8126
+ // THE STASHED TOKEN IS THE TRUST ANCHOR, not merely any valid user
8127
+ // token: the presented one must BE this shop's one-shot handoff token,
8128
+ // unexpired, and an access or pat record — a refresh or oauth-state
8129
+ // token that happens to resolve to a user must not qualify, which is
8130
+ // the rule a session is held to in drawbridge-api's middleware.
8131
+ link: async ({ context }, { read } = {}) => {
8132
+ var _a;
8133
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8134
+ const token = context == null ? void 0 : context.token;
8135
+ if (!shop || !token) throw refusal("shop and token are required", 400);
8136
+ const now = /* @__PURE__ */ new Date();
8137
+ const record = await read.get({ collection: "shop", query: { shop } });
8138
+ const stashed = (record == null ? void 0 : record.linkToken) ? (_a = decrypt(record.linkToken)) == null ? void 0 : _a.token : null;
8139
+ const expired = !(record == null ? void 0 : record.linkTokenExpiresAt) || new Date(record.linkTokenExpiresAt) <= now;
8140
+ if (!stashed || expired || stashed !== token) throw refusal("Invalid or expired link token", 401);
8141
+ const granted = await read.get({
8142
+ collection: "token",
8143
+ query: {
8144
+ revoked: false,
8145
+ tokenHash: hashToken(token),
8146
+ type: { $in: [tokenTypes.access, tokenTypes.pat] }
8147
+ }
8148
+ });
8149
+ if (!(granted == null ? void 0 : granted.user) || granted.expiresAt && new Date(granted.expiresAt) <= now) {
8150
+ throw refusal("Invalid or expired link token", 401);
8151
+ }
8152
+ const switching = Boolean(record == null ? void 0 : record.user) && record.user !== granted.user;
8153
+ const connections2 = switching ? await read.aggregate({
8154
+ collection: "connection",
8155
+ pipeline: [
8156
+ { $match: { shop, slug: "shopify" } },
8157
+ { $project: { _id: 0, id: 1 } }
8158
+ ]
8159
+ }) : [];
8160
+ return {
8161
+ message: switching ? "Linked to a different Drawbridge account." : "Linked.",
8162
+ request: { shop },
8163
+ result: { connected: true, switched: switching },
8164
+ // ALL OR NONE. A half-done switch is a store linked to the new
8165
+ // account while the old account's connections still serve from it.
8166
+ transaction: true,
8167
+ writes: [
8168
+ ...(connections2 || []).map((connection) => ({
8169
+ collection: "connection",
8170
+ operation: "delete",
8171
+ query: { id: connection.id }
8172
+ })),
8173
+ {
8174
+ collection: "shop",
8175
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null, user: granted.user } },
8176
+ operation: "update",
8177
+ query: { shop }
8178
+ }
8179
+ ]
8180
+ };
8181
+ },
8182
+ // DISCONNECT THE ACCOUNT FROM THE STORE. Every org connection goes and
8183
+ // the durable link clears; the offline token and the shop record stay,
8184
+ // because the app is still installed and the merchant may link a
8185
+ // different account next.
8186
+ unlink: async ({ context }, { read } = {}) => {
8187
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8188
+ if (!shop) throw refusal("shop is required", 400);
8189
+ const connections2 = await read.aggregate({
8190
+ collection: "connection",
8191
+ pipeline: [
8192
+ { $match: { shop, slug: "shopify" } },
8193
+ { $project: { _id: 0, id: 1 } }
8194
+ ]
8195
+ });
8196
+ return {
8197
+ message: "Unlinked " + (connections2 || []).length + " connection(s).",
8198
+ request: { shop },
8199
+ result: { ok: true },
8200
+ transaction: true,
8201
+ writes: [
8202
+ ...(connections2 || []).map((connection) => ({
8203
+ collection: "connection",
8204
+ operation: "delete",
8205
+ query: { id: connection.id }
8206
+ })),
8207
+ {
8208
+ collection: "shop",
8209
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null, user: null } },
8210
+ operation: "update",
8211
+ query: { shop }
8212
+ }
8213
+ ]
8214
+ };
8215
+ }
8216
+ },
8217
+ organizations: {
8218
+ // BIND ONE ORGANIZATION TO THIS STORE. The longest slot here, and every
8219
+ // gate in it came from a line in the route it replaces.
8220
+ add: async ({ context }, { currencies, mintId, read, shopify = client } = {}) => {
8221
+ var _a, _b;
8222
+ const organization = context == null ? void 0 : context.organization;
8223
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8224
+ if (!shop) throw refusal("shop is required", 400);
8225
+ if (!organization) throw refusal("organization is required", 400);
8226
+ const record = await read.get({ collection: "shop", query: { shop } });
8227
+ if (!(record == null ? void 0 : record.user)) throw refusal("Account is not connected for this store", 409);
8228
+ const owned = await merchantOrganizations({ read, user: record.user });
8229
+ const org = (owned || []).find((entry) => entry.id === organization);
8230
+ if (!org) throw refusal("No access to this organization", 403);
8231
+ if (!CONNECTABLE_STATUSES.includes(org.billingStatus)) {
8232
+ throw refusal("This organization can't accept connections right now \u2014 check its billing status in the dashboard", 403);
8233
+ }
8234
+ if (org.connection && org.connection.shop !== shop) {
8235
+ throw refusal("This organization is already connected to another Shopify store", 409);
8236
+ }
8237
+ const settings = (record == null ? void 0 : record.settings) ? decrypt(record.settings) : null;
8238
+ if (!(settings == null ? void 0 : settings.accessToken)) {
8239
+ throw refusal("Store is not installed \u2014 open the app in the Shopify admin first", 409);
8240
+ }
8241
+ const plan = await storePlan({ record, shopify });
8242
+ if (plan.unavailable) throw refusal("Couldn't verify the store's plan \u2014 try again shortly", 502);
8243
+ if (!plan.active) throw refusal("Approve a plan before connecting organizations", 402);
8244
+ let storefront = null;
8245
+ if (!record.storefront) {
8246
+ try {
8247
+ const minted2 = await shopify.oauth.createStorefrontToken({
8248
+ adminAccessToken: settings.accessToken,
8249
+ shop
8250
+ });
8251
+ if (minted2) storefront = encrypt({ token: minted2 });
8252
+ } catch (_) {
8253
+ }
8254
+ }
8255
+ let currency = (record == null ? void 0 : record.currency) || null;
8256
+ let source = (record == null ? void 0 : record.source) || null;
8257
+ try {
8258
+ const shopData = await shopify.oauth.getShop({ adminAccessToken: settings.accessToken, shop });
8259
+ if (shopData) {
8260
+ currency = String(shopData.currency || "").toLowerCase() || null;
8261
+ source = { domain: shopData.myshopifyDomain, id: String(shopData.id), label: shopData.name };
8262
+ }
8263
+ } catch (_) {
8264
+ }
8265
+ if (currency && currencies && !currencies.includes(currency)) {
8266
+ throw refusal("This store settles in a currency we can't bill yet. Connect a store with a supported settlement currency.", 422);
8267
+ }
8268
+ const minted = ((_a = org.connection) == null ? void 0 : _a.id) ? null : mintId();
8269
+ const connectionId = ((_b = org.connection) == null ? void 0 : _b.id) || minted.id;
8270
+ return {
8271
+ message: "Connected " + org.name + " to " + shop + ".",
8272
+ request: { organization, shop },
8273
+ result: { ok: true },
8274
+ transaction: true,
8275
+ writes: [
8276
+ ...storefront ? [{
8277
+ collection: "shop",
8278
+ data: { $set: { storefront } },
8279
+ operation: "update",
8280
+ query: { shop }
8281
+ }] : [],
8282
+ {
8283
+ collection: "connection",
8284
+ data: {
8285
+ $set: {
8286
+ currency,
8287
+ errors: [],
8288
+ // The token of record lives on the shared `shop` row; this
8289
+ // is the pointer that satisfies the required `settings`
8290
+ // string, and `auth.install.shared` declares how to read it.
8291
+ settings: encrypt({ ref: "shop", shop }),
8292
+ shop,
8293
+ status: "pending",
8294
+ ...source && { source }
8295
+ },
8296
+ $setOnInsert: {
8297
+ ...minted && { _id: minted._id, id: minted.id },
8298
+ feature: "organization:connection:shopify",
8299
+ organization,
8300
+ slug: "shopify"
8301
+ }
8302
+ },
8303
+ operation: "update",
8304
+ options: { upsert: true },
8305
+ query: { organization, slug: "shopify" }
8306
+ },
8307
+ {
8308
+ collection: "organization",
8309
+ data: {
8310
+ // $addToSet UNCONDITIONALLY. The route this replaces only
8311
+ // registered the refs when the upsert INSERTED, which meant an
8312
+ // org whose refs had drifted stayed drifted through every
8313
+ // re-link. Adding a member that is already there is a no-op,
8314
+ // so doing it every time costs nothing and repairs the drift.
8315
+ $addToSet: {
8316
+ "connections.groups": "ecommerce",
8317
+ "connections.ids": connectionId,
8318
+ "connections.keys": "shopify"
8319
+ },
8320
+ $set: { billingProvider: "shopify" }
8321
+ },
8322
+ operation: "update",
8323
+ query: { id: organization }
8324
+ }
8325
+ ]
8326
+ };
8327
+ },
8328
+ // WHAT THIS STORE CAN SEE: the linked merchant's organizations, the
8329
+ // store's live plan, and the products the merchant has to act on.
8330
+ //
8331
+ // AN ORG CONNECTED TO A DIFFERENT STORE IS OMITTED ENTIRELY, because
8332
+ // `add` would refuse it — a list that offers what the next call rejects
8333
+ // is worse than a shorter one.
8334
+ list: async ({ context }, { conversionRate, planTitle, read, shopify = client } = {}) => {
8335
+ var _a;
8336
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8337
+ if (!shop) throw refusal("shop is required", 400);
8338
+ const record = await read.get({ collection: "shop", query: { shop } });
8339
+ if (!(record == null ? void 0 : record.user)) {
8340
+ return {
8341
+ message: "No account linked to this store.",
8342
+ request: { shop },
8343
+ result: {
8344
+ account: null,
8345
+ connected: false,
8346
+ organizations: [],
8347
+ plan: { active: false, name: null },
8348
+ unavailableProducts: [],
8349
+ unavailableProductsTotal: 0
8350
+ }
8351
+ };
8352
+ }
8353
+ const owned = await merchantOrganizations({ read, user: record.user });
8354
+ const organizations = (owned || []).filter((org) => !org.connection || org.connection.shop === shop).map((org) => {
8355
+ var _a2;
8356
+ return {
8357
+ // The org's OWN billing status decides whether `add` accepts it.
8358
+ // Sent up so the app can disable Connect and name the reason
8359
+ // rather than letting the merchant click into a 403 —
8360
+ // listed-but-blocked beats hidden, because an org vanishing from
8361
+ // the list is indistinguishable from a bug.
8362
+ billingStatus: org.billingStatus || null,
8363
+ connectable: CONNECTABLE_STATUSES.includes(org.billingStatus),
8364
+ connected: Boolean(org.connection),
8365
+ conversion: conversionRate(org.subscription),
8366
+ id: org.id,
8367
+ name: org.name,
8368
+ plan: planTitle(org.subscription),
8369
+ status: ((_a2 = org.connection) == null ? void 0 : _a2.status) || null
8370
+ };
8371
+ });
8372
+ const connections2 = (owned || []).filter((org) => {
8373
+ var _a2;
8374
+ return ((_a2 = org.connection) == null ? void 0 : _a2.shop) === shop && org.connection.id;
8375
+ }).map((org) => org.connection.id);
8376
+ const [account, plan, unavailable] = await Promise.all([
8377
+ read.get({ collection: "user", query: { id: record.user } }),
8378
+ storePlan({ record, shopify }),
8379
+ connections2.length ? read.aggregate({
8380
+ collection: "product",
8381
+ pipeline: [
8382
+ { $match: { connections: { $in: connections2 }, "source.domain": shop, status: "inactive" } },
8383
+ // $facet so the app can name the first 25 AND report a
8384
+ // truthful total: listing 25 of 40 under "25 products need
8385
+ // attention" would understate the problem.
8386
+ {
8387
+ $facet: {
8388
+ items: [{ $sort: { title: 1 } }, { $limit: 25 }, { $project: { _id: 0, id: 1, title: 1 } }],
8389
+ total: [{ $count: "count" }]
8390
+ }
8391
+ }
8392
+ ]
8393
+ }) : []
8394
+ ]);
8395
+ const facet = (unavailable || [])[0] || {};
8396
+ if (plan.active && plan.metered !== true) {
8397
+ const stamped = await read.aggregate({
8398
+ collection: "connection",
8399
+ pipeline: [
8400
+ { $match: { shop, slug: "shopify" } },
8401
+ { $project: { _id: 0, "source.metered": 1 } }
8402
+ ]
8403
+ });
8404
+ const verdicts = (stamped || []).map((row2) => {
8405
+ var _a2;
8406
+ return (_a2 = row2 == null ? void 0 : row2.source) == null ? void 0 : _a2.metered;
8407
+ });
8408
+ if (verdicts.some((verdict) => typeof verdict === "string")) plan.metered = true;
8409
+ else if (verdicts.some((verdict) => verdict === null)) plan.metered = false;
8410
+ }
8411
+ return {
8412
+ message: organizations.length + " organization(s) for this store.",
8413
+ request: { shop },
8414
+ result: {
8415
+ account: { email: (account == null ? void 0 : account.email) || null },
8416
+ connected: true,
8417
+ organizations,
8418
+ plan,
8419
+ unavailableProducts: (facet.items || []).map((product) => ({
8420
+ id: product.id,
8421
+ title: product.title || "Untitled product"
8422
+ })),
8423
+ // The total can exceed the 25 listed above, and has to.
8424
+ unavailableProductsTotal: ((_a = (facet.total || [])[0]) == null ? void 0 : _a.count) || 0
8425
+ }
8426
+ };
8427
+ },
8428
+ // DISCONNECT ONE ORGANIZATION. The connection is deleted and nothing
8429
+ // else: every dependent — products, ads, steps, workflows, and the org's
8430
+ // own connection refs — is torn down by drawbridge-sync's connection
8431
+ // change stream. The shared token and the other orgs are untouched.
8432
+ remove: async ({ context }, { read } = {}) => {
8433
+ const organization = context == null ? void 0 : context.organization;
8434
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8435
+ if (!shop) throw refusal("shop is required", 400);
8436
+ if (!organization) throw refusal("organization is required", 400);
8437
+ const record = await read.get({ collection: "shop", query: { shop } });
8438
+ if (!(record == null ? void 0 : record.user)) throw refusal("Account is not connected for this store", 409);
8439
+ const owned = await merchantOrganizations({ read, user: record.user });
8440
+ if (!(owned || []).some((entry) => entry.id === organization)) {
8441
+ throw refusal("No access to this organization", 403);
8442
+ }
8443
+ const connection = await read.get({
8444
+ collection: "connection",
8445
+ query: { organization, shop, slug: "shopify" }
8446
+ });
8447
+ if (!connection) throw refusal("No connection to remove", 404);
8448
+ return {
8449
+ message: "Disconnected.",
8450
+ request: { organization, shop },
8451
+ result: { ok: true },
8452
+ writes: [{ collection: "connection", operation: "delete", query: { id: connection.id } }]
8453
+ };
8454
+ }
8455
+ },
8456
+ plan: {
8457
+ // RELEASE EVERY ACTIVE APPROVAL. The App Home then re-checks the plan
8458
+ // and falls back to "Choose a plan".
8459
+ cancel: ({ context }, { read, shopify = client } = {}) => releaseApprovals({ context, read, shopify }),
8460
+ // ONE ATTRIBUTED ORDER'S USAGE CHARGE. Enqueued per conversion by the
8461
+ // order step and run on a retrying queue, so this may be called
8462
+ // several times for one order — which is safe because the idempotency
8463
+ // key is PERMANENT for billing events and Shopify settles the repeat.
8464
+ //
8465
+ // THE HANDLE IS CHECKED AGAINST THE MANIFEST'S OWN DECLARATION, which
8466
+ // is a real strengthening of what it replaced: drawbridge-sync compared
8467
+ // the job's `handle` against the job's `transaction` — two fields from
8468
+ // the same enqueuer, so a drifted enqueuer agreed with itself. The
8469
+ // handle is the one string that decides whether the event bills at all,
8470
+ // and this is the file that publishes it.
8471
+ //
8472
+ // REFUSE BEFORE SENDING, because sending burns the order's PERMANENT
8473
+ // idempotency key on an event that misclassifies or mistraces. The
8474
+ // throw rides the queue's normal retry path and the abandoned-job alert
8475
+ // pages on exhaustion.
8476
+ //
8477
+ // DELIBERATELY NO TIMESTAMP. sendAppEvent defaults to the SEND time,
8478
+ // which is always inside the merchant's current billing cycle at the
8479
+ // moment of sending and so can never hit PERIOD_CLOSED. Pinning the
8480
+ // purchase time reads more correct and is strictly worse: a retry
8481
+ // backoff crossing a cycle boundary would carry a closed-cycle
8482
+ // timestamp, Shopify would 202-accept, silently drop it, and the
8483
+ // commission would be lost. Send-time's worst case is benign — the
8484
+ // charge lands in the next cycle, but it lands.
8485
+ charge: async ({ clientId, clientSecret, context, manifest }, { shopify = client } = {}) => {
8486
+ const { idempotencyKey, order, orderId, rate, revision, shopId, timestamp, transaction, value } = context || {};
8487
+ const handle = (context == null ? void 0 : context.handle) || manifest.auth.install.billing.handle;
8488
+ if (!transaction || !String(transaction).startsWith(handle + ".")) {
8489
+ throw new Error("shopify.usage.billing.handle.mismatch on order " + orderId + ": transaction " + (transaction || "null") + " does not carry handle " + handle + " \u2014 refusing to send");
8490
+ }
8491
+ await shopify.billing.sendAppEvent({
8492
+ clientId,
8493
+ clientSecret,
8494
+ eventHandle: handle,
8495
+ idempotencyKey,
8496
+ // The Shopify-side event record names the order that produced it.
8497
+ reference: transaction,
8498
+ // OPERATOR-ONLY, BOTH OF THEM, and absent on every automatic
8499
+ // send. `revision` suffixes the idempotency key, which is what
8500
+ // makes a second attempt possible once a key has been consumed;
8501
+ // the encoding is owned by sendAppEvent so no caller builds keys
8502
+ // itself. `timestamp` pins the PURCHASE time, which the automatic
8503
+ // path must never do — see the note above — and the recovery
8504
+ // migration must, because it is resending orders from a closed
8505
+ // window and bounds its own run to the merchant's current cycle.
8506
+ ...revision && { revision },
8507
+ ...timestamp && { timestamp },
8508
+ shopId,
8509
+ value
8510
+ });
8511
+ return {
8512
+ message: "Usage charge sent for order " + orderId + ".",
8513
+ request: { order: order || null, orderId: orderId || null, shopId: shopId || null, value },
8514
+ result: { transaction: String(transaction) },
8515
+ // TRACEABILITY. The App Events API returns no event id, so the
8516
+ // trace key into Shopify's event logs is the transaction id the
8517
+ // commerce.order hook minted and this sent as `reference`.
8518
+ // `amount` is the per-order usage value in cents, mirroring the
8519
+ // Stripe path's marker.
8520
+ ...order && { writes: [{
8521
+ collection: "order",
8522
+ data: {
8523
+ $set: {
8524
+ billed: {
8525
+ amount: value,
8526
+ date: /* @__PURE__ */ new Date(),
8527
+ rate: rate || 0,
8528
+ transaction: String(transaction)
8529
+ }
8530
+ }
8531
+ },
8532
+ operation: "update",
8533
+ query: { id: order }
8534
+ }] }
8535
+ };
8536
+ },
8537
+ // RESELECT, NOT CANCEL. The same mechanics — the current approval has to
8538
+ // be released before the pricing page will offer the plan again — but
8539
+ // the intent is a thirty-second round trip rather than a departure.
8540
+ //
8541
+ // `mark` IS A DECLARED CAPABILITY, and this is the only slot here that
8542
+ // needs one. The marker has to be persisted BEFORE the approval is
8543
+ // released: it is what tells sync's CANCELLED handler to hold the pause
8544
+ // — no connection error, no owner email — and start a timed recheck that
8545
+ // pauses honestly if the merchant abandons. A described write lands
8546
+ // after the hook returns, which is after the cancel, and a marker
8547
+ // written then can race the very webhook it exists to soften. Same
8548
+ // precedent as `resolveContact`: the one write a description cannot
8549
+ // carry.
8550
+ reselect: async ({ context }, { mark, read, shopify = client } = {}) => {
8551
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8552
+ if (!shop) throw refusal("shop is required", 400);
8553
+ await mark({ shop });
8554
+ return releaseApprovals({ context, read, shopify });
8555
+ },
8556
+ // IS THIS STORE'S ORDER BILLING ACTUALLY METERED? Not a merchant
8557
+ // action — the other two slots here are — but the same subject, and
8558
+ // the reason it is a declared hook rather than a helper is that the
8559
+ // answer was being derived in two places: `lifecycle.health` below,
8560
+ // and drawbridge-sync's app_subscriptions/update handler, whose copy
8561
+ // stated in its own comment that it matched this one and did not.
8562
+ //
8563
+ // THREE ANSWERS, and the caller must keep them apart:
8564
+ //
8565
+ // a string PROVEN. The charge id or usage line id, stamped on
8566
+ // the connection as the evidence.
8567
+ // null PROBED, and nothing is accruing.
8568
+ // undefined NO VERDICT — the probe could not run. `probed` says
8569
+ // which, because undefined does not survive JSON.
8570
+ verify: async ({ context }, { adminToken, read, shopify = client } = {}) => {
8571
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8572
+ if (!shop) throw refusal("shop is required", 400);
8573
+ const adminAccessToken = await adminToken();
8574
+ if (!adminAccessToken) {
8575
+ return { message: "No admin token for this store \u2014 no verdict.", request: { shop }, result: { metered: null, probed: false }, skipped: true };
8576
+ }
8577
+ const partnerRow = (read == null ? void 0 : read.get) ? await read.get({ collection: "provider", query: { slug: "shopify" } }) : null;
8578
+ const partner = (partnerRow == null ? void 0 : partnerRow.settings) ? decrypt(partnerRow.settings) : {};
8579
+ const { ledger, metered } = await meterVerdict({
8580
+ adminAccessToken,
8581
+ ledgerFloor: new Date(Date.now() - LEDGER_WINDOW_MS),
8582
+ partner,
8583
+ shop,
8584
+ shopId: (context == null ? void 0 : context.shopId) || null,
8585
+ shopify
8586
+ });
8587
+ return {
8588
+ message: typeof metered === "string" ? "Billing is metered." : "No meter evidence for this store.",
8589
+ request: { shop },
8590
+ // `probed` is the LEDGER, not the call: a store whose Partner
8591
+ // credentials are absent was not asked, and reporting that as
8592
+ // "probed, nothing accruing" would stamp an unmetered verdict on
8593
+ // a store nobody looked at.
8594
+ result: { metered: metered ?? null, probed: ledger || typeof metered === "string" }
8595
+ };
8596
+ }
8597
+ },
8598
+ // THE EMBEDDED APP'S SESSION STORE. The @shopify/shopify-app library
8599
+ // persists the offline session on token exchange and refresh; it lives
8600
+ // encrypted on the shared `shop` record, which is the same row every
8601
+ // organization's connection to this store points at.
8602
+ session: {
8603
+ // SOFT-CLEAR, NEVER A DELETE. The library calls this on session
8604
+ // invalidation and not only on uninstall, so hard-deleting the record
8605
+ // would orphan every org connection pointing at it — token resolution
8606
+ // silently nulls — and destroy the durable account link and the
8607
+ // storefront token with it. The next embedded load re-runs token
8608
+ // exchange. The full record delete belongs to the uninstall webhook.
8609
+ clear: async ({ context }) => {
8610
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8611
+ if (!shop) throw refusal("shop is required", 400);
8612
+ return {
8613
+ message: "Session cleared.",
8614
+ request: { shop },
8615
+ result: { ok: true },
8616
+ writes: [{
8617
+ collection: "shop",
8618
+ data: { $set: { settings: null } },
8619
+ operation: "update",
8620
+ query: { shop }
8621
+ }]
8622
+ };
8623
+ },
8624
+ read: async ({ context }, { read } = {}) => {
8625
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8626
+ if (!shop) throw refusal("shop is required", 400);
8627
+ const record = await read.get({ collection: "shop", query: { shop } });
8628
+ if (!(record == null ? void 0 : record.settings)) throw refusal("No session for this store", 404);
8629
+ return {
8630
+ message: "Session read.",
8631
+ request: { shop },
8632
+ result: { session: decrypt(record.settings) }
8633
+ };
8634
+ },
8635
+ save: async ({ context }) => {
8636
+ const session = context == null ? void 0 : context.session;
8637
+ const shop = sanitizeDomain(session == null ? void 0 : session.shop);
8638
+ if (!shop || !(session == null ? void 0 : session.accessToken)) throw refusal("session.shop and session.accessToken are required", 400);
8639
+ return {
8640
+ message: "Session saved.",
8641
+ request: { shop },
8642
+ result: { ok: true },
8643
+ writes: [{
8644
+ collection: "shop",
8645
+ data: {
8646
+ $set: { settings: encrypt(session), shop },
8647
+ $setOnInsert: { status: "pending" }
8648
+ },
8649
+ operation: "update",
8650
+ options: { upsert: true },
8651
+ query: { shop }
8652
+ }]
8653
+ };
8654
+ }
8655
+ },
8656
+ // THE LINK-TOKEN HANDOFF. The breakout callback runs top-level and can set
8657
+ // a first-party cookie; the embedded App Home cannot read that cookie from
8658
+ // inside the Shopify admin iframe. So the callback stashes the merchant's
8659
+ // user token here keyed by shop, and App Home reads it once and clears it.
8660
+ //
8661
+ // DURABLE RATHER THAN IN REDIS: a restart must not strand a merchant
8662
+ // mid-handoff. Short-lived and encrypted.
8663
+ token: {
8664
+ clear: async ({ context }) => {
8665
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8666
+ if (!shop) throw refusal("shop is required", 400);
8667
+ return {
8668
+ message: "Link token cleared.",
8669
+ request: { shop },
8670
+ result: { ok: true },
8671
+ writes: [{
8672
+ collection: "shop",
8673
+ data: { $set: { linkToken: null, linkTokenExpiresAt: null } },
8674
+ operation: "update",
8675
+ query: { shop }
8676
+ }]
8677
+ };
8678
+ },
8679
+ read: async ({ context }, { read } = {}) => {
8680
+ var _a;
8681
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8682
+ if (!shop) throw refusal("shop is required", 400);
8683
+ const record = await read.get({ collection: "shop", query: { shop } });
8684
+ const expiresAt = (record == null ? void 0 : record.linkTokenExpiresAt) ? new Date(record.linkTokenExpiresAt) : null;
8685
+ if (!(record == null ? void 0 : record.linkToken) || !expiresAt || expiresAt <= /* @__PURE__ */ new Date()) {
8686
+ throw refusal("No link token for this store", 404);
8687
+ }
8688
+ return {
8689
+ message: "Link token read.",
8690
+ request: { shop },
8691
+ result: { token: ((_a = decrypt(record.linkToken)) == null ? void 0 : _a.token) ?? null }
8692
+ };
8693
+ },
8694
+ save: async ({ context }) => {
8695
+ const shop = sanitizeDomain(context == null ? void 0 : context.shop);
8696
+ const token = context == null ? void 0 : context.token;
8697
+ if (!shop || !token) throw refusal("shop and token are required", 400);
8698
+ return {
8699
+ message: "Link token saved.",
8700
+ request: { shop },
8701
+ result: { ok: true },
8702
+ writes: [{
8703
+ collection: "shop",
8704
+ data: {
8705
+ $set: {
8706
+ linkToken: encrypt({ token }),
8707
+ linkTokenExpiresAt: new Date(Date.now() + LINK_TOKEN_TTL_MS)
8708
+ }
8709
+ },
8710
+ operation: "update",
8711
+ query: { shop }
8712
+ }]
8713
+ };
8714
+ }
8715
+ }
8716
+ },
5862
8717
  // Drawbridge sends its own notification email and SMS — see the private
5863
8718
  // `drawbridge` manifest. A vendor answering these would be a second sender,
5864
8719
  // which is the arrangement the platform sender replaced.
@@ -5920,8 +8775,8 @@ var shopify_default2 = {
5920
8775
  // access token still works, reconciles the scopes the store granted
5921
8776
  // against the ones the app now needs, and queues a webhook
5922
8777
  // reconciliation.
5923
- health: async ({ connection, workflow }, { adminToken, logger, read, reconcileScopes, resolveSettings, rotateToken, shopify } = {}) => {
5924
- var _a, _b, _c, _d, _e, _f;
8778
+ health: async ({ connection, workflow }, { adminToken, logger, read, reconcileScopes, resolveSettings, rotateToken, shopify = client } = {}) => {
8779
+ var _a, _b, _c, _d;
5925
8780
  const request2 = {
5926
8781
  connectionId: workflow.connection,
5927
8782
  organizationId: workflow.organization,
@@ -5958,33 +8813,26 @@ var shopify_default2 = {
5958
8813
  shopCurrency = String(shopData.currency || "").toLowerCase() || null;
5959
8814
  sourceRepaired = true;
5960
8815
  }
5961
- const { subscriptions } = await shopify.admin.getActiveAppSubscriptions({
5962
- adminAccessToken,
5963
- domain: connection.shop
5964
- });
5965
- const usageLine = (_a = subscriptions.find((subscription) => subscription.usageLineItemId)) == null ? void 0 : _a.usageLineItemId;
5966
- if (usageLine) metered = usageLine;
5967
8816
  const partnerRow = (read == null ? void 0 : read.get) ? await read.get({ collection: "provider", query: { slug: "shopify" } }) : null;
5968
8817
  const partner = (partnerRow == null ? void 0 : partnerRow.settings) ? decrypt(partnerRow.settings) : {};
5969
- if (partner.partnerToken && partner.partnerOrgId && partner.partnerAppId && (source == null ? void 0 : source.id) && ((_b = shopify.partner) == null ? void 0 : _b.getUsageChargeEvents)) {
5970
- const ledgerFloor = new Date(Date.now() - 30 * 24 * 60 * 60 * 1e3);
5971
- const accruals = await shopify.partner.getUsageChargeEvents({
5972
- appId: "gid://shopify/App/" + partner.partnerAppId,
5973
- first: 10,
5974
- occurredAtMin: ledgerFloor.toISOString(),
5975
- organizationId: partner.partnerOrgId,
5976
- partnerToken: partner.partnerToken,
5977
- shopId: "gid://shopify/Shop/" + source.id
5978
- });
5979
- const boundaries = accruals.filter((event) => event.occurredAt).sort((a, b) => new Date(a.occurredAt) - new Date(b.occurredAt));
5980
- const accrued = [...boundaries].reverse().find((event) => Number(event.usageQuantity) > 0);
5981
- if (accrued) metered = String(accrued.chargeId || accrued.id);
5982
- const stampedAt = (_c = boundaries.find(
8818
+ const ledgerFloor = new Date(Date.now() - LEDGER_WINDOW_MS);
8819
+ const verdict = await meterVerdict({
8820
+ adminAccessToken,
8821
+ ledgerFloor,
8822
+ partner,
8823
+ shop: connection.shop,
8824
+ shopId: source == null ? void 0 : source.id,
8825
+ shopify
8826
+ });
8827
+ if (verdict.metered !== void 0) metered = verdict.metered;
8828
+ const { boundaries } = verdict;
8829
+ if (boundaries.length) {
8830
+ const stampedAt = (_a = boundaries.find(
5983
8831
  (event) => {
5984
8832
  var _a2;
5985
8833
  return String(event.chargeId || event.id) === String(((_a2 = connection.source) == null ? void 0 : _a2.metered) || "");
5986
8834
  }
5987
- )) == null ? void 0 : _c.occurredAt;
8835
+ )) == null ? void 0 : _a.occurredAt;
5988
8836
  reconciliation = [];
5989
8837
  let windowStart = ledgerFloor;
5990
8838
  for (const boundary of boundaries) {
@@ -6034,7 +8882,7 @@ var shopify_default2 = {
6034
8882
  }
6035
8883
  });
6036
8884
  } else {
6037
- (_d = logger == null ? void 0 : logger.error) == null ? void 0 : _d.call(logger, new Error(
8885
+ (_b = logger == null ? void 0 : logger.error) == null ? void 0 : _b.call(logger, new Error(
6038
8886
  "shopify.usage.reconciliation.mismatch on shop " + connection.shop + ": charge " + charge + " charged " + charged + " cents but its window holds " + billed + " cents across " + orders.length + " billed orders \u2014 each cent of difference is commission that never charged"
6039
8887
  ), {
6040
8888
  extra: {
@@ -6053,13 +8901,13 @@ var shopify_default2 = {
6053
8901
  }
6054
8902
  } catch (probeError) {
6055
8903
  billingProbeFailed = true;
6056
- (_e = logger == null ? void 0 : logger.warn) == null ? void 0 : _e.call(logger, "shopify.health.billing.probe.failed", {
8904
+ (_c = logger == null ? void 0 : logger.warn) == null ? void 0 : _c.call(logger, "shopify.health.billing.probe.failed", {
6057
8905
  connectionId: connection.id,
6058
8906
  message: probeError == null ? void 0 : probeError.message,
6059
8907
  shop: connection.shop
6060
8908
  });
6061
8909
  }
6062
- if (sourceRepaired || metered !== void 0 && metered !== (((_f = connection.source) == null ? void 0 : _f.metered) ?? void 0)) {
8910
+ if (sourceRepaired || metered !== void 0 && metered !== (((_d = connection.source) == null ? void 0 : _d.metered) ?? void 0)) {
6063
8911
  writes.push({
6064
8912
  collection: "connection",
6065
8913
  data: {
@@ -6194,13 +9042,13 @@ var shopify_default2 = {
6194
9042
  // They are the same two questions every other vendor answers through
6195
9043
  // resources.*, so they answer them the same way now.
6196
9044
  //
6197
- // `shopify` is INJECTED: this package cannot import @drawbridge/shopify,
9045
+ // `shopify` DEFAULTS to the client this file imports; nothing injects it,
6198
9046
  // which depends on it. What arrives is the SDK's pure HTTP namespaces
6199
9047
  // and nothing else — no controller, no collection access. Resolving the
6200
9048
  // credential is the caller's job because it is Drawbridge's job: the
6201
9049
  // admin token refreshes and writes itself back, which is service work,
6202
9050
  // not vendor work.
6203
- products: async ({ cursor, limit = 100, search, settings, sort }, { shopify } = {}) => {
9051
+ products: async ({ cursor, limit = 100, search, settings, sort }, { shopify = client } = {}) => {
6204
9052
  var _a, _b, _c, _d;
6205
9053
  const products = await shopify.storefront.getProducts({
6206
9054
  cursor,
@@ -6222,7 +9070,7 @@ var shopify_default2 = {
6222
9070
  }
6223
9071
  };
6224
9072
  },
6225
- promotions: async ({ cursor, limit = 100, search, settings }, { shopify } = {}) => {
9073
+ promotions: async ({ cursor, limit = 100, search, settings }, { shopify = client } = {}) => {
6226
9074
  var _a, _b;
6227
9075
  const discounts = await shopify.admin.getDiscounts({
6228
9076
  adminAccessToken: settings == null ? void 0 : settings.adminAccessToken,
@@ -6509,7 +9357,7 @@ var shopify_default2 = {
6509
9357
  };
6510
9358
 
6511
9359
  // lib/connections/manifests/webhook.js
6512
- import crypto2 from "crypto";
9360
+ import crypto3 from "crypto";
6513
9361
 
6514
9362
  // lib/safe-http.js
6515
9363
  import dns2 from "dns";
@@ -6682,7 +9530,7 @@ var signature = ({ body, settings }) => {
6682
9530
  return [
6683
9531
  "t=" + timestamp,
6684
9532
  ...[settings.secret, ...previous].map(
6685
- (secret) => "v1=" + crypto2.createHmac(generated.algorithm, secret).update(payload).digest(generated.encoding)
9533
+ (secret) => "v1=" + crypto3.createHmac(generated.algorithm, secret).update(payload).digest(generated.encoding)
6686
9534
  )
6687
9535
  ].join(",");
6688
9536
  };
@@ -6727,14 +9575,15 @@ var webhook_default = {
6727
9575
  "Drawbridge can POST event payloads to your endpoint as activity happens in your account, so your own systems can react to it.",
6728
9576
  "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."
6729
9577
  ],
6730
- // NO VENDOR-SPECIFIC CONNECT COPY, and that is a decision rather than a gap.
6731
- // The dashboard already carries generic reasons for every way an
6732
- // authorization can fail declined, expired state, a vendor we are not set
6733
- // up for and a sentence here is an ADDITION to those, for a vendor whose
6734
- // failures need saying differently. This one's do not.
9578
+ // THERE IS NO CONSENT SCREEN TO FAIL. Connecting mints a signing secret;
9579
+ // nothing is authorized against a third party, so neither `denied` nor
9580
+ // `invalid` has a state it could describe. The failures this connection
9581
+ // really has are at DELIVERY a merchant's endpoint refusing a POST and
9582
+ // those reach them through the connection's own errors rather than through
9583
+ // connect copy.
6735
9584
  //
6736
- // Answered rather than omitted, because `errors` existed on two of six
6737
- // manifests and there was no way to tell "nothing to add" from "nobody
9585
+ // `false` is the recorded decision, not silence: `errors` existed on two of
9586
+ // six manifests and there was no way to tell "nothing to add" from "nobody
6738
9587
  // wrote it".
6739
9588
  errors: false,
6740
9589
  excerpt: "Sign outgoing webhook payloads with an HMAC secret to verify authenticity.",
@@ -7713,7 +10562,7 @@ var hookSupport = (name) => ({
7713
10562
  });
7714
10563
  var connectFields = (slug2) => {
7715
10564
  var _a;
7716
- return (((_a = connections[slug2]) == null ? void 0 : _a.fields) || []).map(({ copy, from, hook, input, key, label, message, options, placeholder, redact, required, search }) => ({
10565
+ return (((_a = connections[slug2]) == null ? void 0 : _a.fields) || []).map(({ copy, from, hook, input, key, label, message, options, placeholder, redact, required: required2, search }) => ({
7717
10566
  ...copy && { copy: true },
7718
10567
  ...hook && { hook },
7719
10568
  ...from && { from },
@@ -7726,7 +10575,7 @@ var connectFields = (slug2) => {
7726
10575
  // Declared false only where the vendor cannot filter, so a picker does not
7727
10576
  // offer a search box that quietly searches one page.
7728
10577
  ...search === false && { search: false },
7729
- required: Boolean(required),
10578
+ required: Boolean(required2),
7730
10579
  // A UI hint, not a leak: the form uses it to stop requiring the field once
7731
10580
  // the connection exists, and to say "leave blank to keep" — because the GET
7732
10581
  // response deliberately never returns the stored value.
@@ -7885,6 +10734,7 @@ export {
7885
10734
  buildVendor,
7886
10735
  catalogConnections,
7887
10736
  connectFields,
10737
+ connectionSettings,
7888
10738
  connectionSteps,
7889
10739
  connections,
7890
10740
  consentUrl,
@@ -7894,10 +10744,12 @@ export {
7894
10744
  isStale,
7895
10745
  isStatus,
7896
10746
  mergeSettings,
10747
+ perform,
7897
10748
  pkcePair,
7898
10749
  projectConnection,
7899
10750
  publicConnectionKeys,
7900
10751
  publicSettingsBySlug,
10752
+ reconcileConnectionScopes,
7901
10753
  redactSettings,
7902
10754
  resolveConnection,
7903
10755
  runHook,