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