@moonbase.sh/react 1.1.0 → 1.2.1

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/index.cjs CHANGED
@@ -24,49 +24,76 @@ __export(index_exports, {
24
24
  MoonbaseStorefront: () => MoonbaseStorefront,
25
25
  StorefrontProvider: () => StorefrontProvider,
26
26
  createStorefront: () => createStorefront,
27
+ getStorefront: () => getStorefront,
27
28
  useActivationRequest: () => useActivationRequest,
29
+ useAttributionConsent: () => useAttributionConsent,
28
30
  useAuth: () => useAuth,
29
31
  useBundle: () => useBundle,
30
32
  useBundles: () => useBundles,
31
33
  useCart: () => useCart,
34
+ useCartActions: () => useCartActions,
32
35
  useCartOffer: () => useCartOffer,
33
36
  useCatalog: () => useCatalog,
34
37
  useCheckout: () => useCheckout,
35
38
  useCommunicationPreferences: () => useCommunicationPreferences,
39
+ useCurrency: () => useCurrency,
36
40
  useEligibleOffers: () => useEligibleOffers,
37
41
  useGroups: () => useGroups,
38
42
  useInventory: () => useInventory,
39
43
  useLockedOffers: () => useLockedOffers,
40
44
  useOffer: () => useOffer,
41
45
  useOffers: () => useOffers,
46
+ useOrderHistory: () => useOrderHistory,
42
47
  useOrders: () => useOrders,
48
+ useOwnedProduct: () => useOwnedProduct,
49
+ useOwnedProducts: () => useOwnedProducts,
50
+ usePrice: () => usePrice,
43
51
  useProduct: () => useProduct,
52
+ useProductActivations: () => useProductActivations,
53
+ useProductLicenses: () => useProductLicenses,
44
54
  useProducts: () => useProducts,
45
55
  usePromotions: () => usePromotions,
46
56
  useReviews: () => useReviews,
47
57
  useStorefront: () => useStorefront,
48
58
  useStorefrontEvent: () => useStorefrontEvent,
49
59
  useStorefrontState: () => useStorefrontState,
60
+ useSubscription: () => useSubscription,
61
+ useSubscriptions: () => useSubscriptions,
50
62
  useVendor: () => useVendor,
51
63
  useVoucher: () => useVoucher
52
64
  });
53
65
  module.exports = __toCommonJS(index_exports);
54
- var import_storefront_api11 = require("@moonbase.sh/storefront-api");
66
+ var import_storefront_api13 = require("@moonbase.sh/storefront-api");
55
67
 
56
68
  // package.json
57
- var version = "1.1.0";
69
+ var version = "1.2.1";
58
70
 
59
71
  // src/storefront.ts
60
72
  var import_storefront_api5 = require("@moonbase.sh/storefront-api");
61
73
 
62
74
  // src/auth.ts
63
75
  var import_storefront_api = require("@moonbase.sh/storefront-api");
76
+ var confirmationReuse = 5e3;
64
77
  function createAuth(storefront, internals) {
65
78
  const { setUser } = internals;
66
79
  const signedIn = () => storefront.getState().user !== null;
67
80
  const refreshCatalog = () => {
68
81
  storefront.refreshCatalog().catch((err) => console.error("Could not load the Moonbase catalog", err));
69
82
  };
83
+ const confirmations = /* @__PURE__ */ new Map();
84
+ const confirmOnce = (kind, email, code, confirm) => {
85
+ const key = JSON.stringify([kind, email, code]);
86
+ const pending = confirmations.get(key);
87
+ if (pending)
88
+ return pending;
89
+ const result = confirm();
90
+ confirmations.set(key, result);
91
+ const forget = () => {
92
+ setTimeout(() => confirmations.delete(key), confirmationReuse);
93
+ };
94
+ result.then(forget, forget);
95
+ return result;
96
+ };
70
97
  return {
71
98
  signIn: async (email, password) => {
72
99
  const user = await storefront.client.identity.signIn(email, password);
@@ -121,19 +148,19 @@ function createAuth(storefront, internals) {
121
148
  setPassword: (currentPassword, newPassword) => storefront.client.identity.setPassword(currentPassword, newPassword),
122
149
  forgotPassword: (email) => storefront.client.identity.forgotPassword(email),
123
150
  resetPassword: (email, newPassword, code) => storefront.client.identity.resetPassword(email, newPassword, code),
124
- confirmAccount: async (email, code) => {
151
+ confirmAccount: (email, code) => confirmOnce("account", email, code, async () => {
125
152
  const result = await storefront.client.identity.confirmAccount(email, code);
126
153
  if (result.status === "SignedIn") {
127
154
  setUser(import_storefront_api.schemas.identity.userSchema.parse(storefront.client.tokenStore.user));
128
155
  refreshCatalog();
129
156
  }
130
157
  return result;
131
- },
132
- confirmEmail: (email, code) => storefront.client.identity.confirmEmail(email, code),
133
- confirmEmailChange: async (email, code) => {
158
+ }),
159
+ confirmEmail: (email, code) => confirmOnce("email", email, code, () => storefront.client.identity.confirmEmail(email, code)),
160
+ confirmEmailChange: (email, code) => confirmOnce("email-change", email, code, async () => {
134
161
  await storefront.client.identity.confirmEmailChange(email, code);
135
162
  return await storefront.refreshUser();
136
- },
163
+ }),
137
164
  getConnectionUrl: (provider, redirectUri, loginId) => storefront.client.identity.getConnectionUrl(provider, redirectUri, loginId),
138
165
  disconnectAccount: async (provider) => {
139
166
  await storefront.client.identity.disconnectAccount(provider);
@@ -148,7 +175,6 @@ var import_storefront_api4 = require("@moonbase.sh/storefront-api");
148
175
 
149
176
  // src/checkout.ts
150
177
  var import_storefront_api2 = require("@moonbase.sh/storefront-api");
151
- var import_uuid = require("uuid");
152
178
  var wrapperId = "moonbase-checkout-wrapper";
153
179
  function checkoutInProgress() {
154
180
  return typeof window !== "undefined" && !!document.getElementById(wrapperId);
@@ -229,13 +255,13 @@ async function checkout(storefront, items, options = {}) {
229
255
  let resumed = await (0, import_storefront_api2.resumePurchase)(storefront.client, userId, options.couponCode);
230
256
  let order;
231
257
  try {
232
- order = await pushOrder((_d = resumed == null ? void 0 : resumed.orderId) != null ? _d : (0, import_uuid.v4)());
258
+ order = await pushOrder((_d = resumed == null ? void 0 : resumed.orderId) != null ? _d : (0, import_storefront_api2.randomUuid)());
233
259
  } catch (err) {
234
260
  if (!resumed || !(0, import_storefront_api2.isClosedOrderRefusal)(err))
235
261
  throw err;
236
262
  (0, import_storefront_api2.forgetPurchase)(resumed.orderId);
237
263
  resumed = null;
238
- order = await pushOrder((0, import_uuid.v4)());
264
+ order = await pushOrder((0, import_storefront_api2.randomUuid)());
239
265
  }
240
266
  await (0, import_storefront_api2.recordCheckoutGroups)(storefront.client, order.id, options.groupIds);
241
267
  let ownCoupon = (_e = resumed == null ? void 0 : resumed.couponCode) != null ? _e : null;
@@ -280,7 +306,6 @@ async function checkout(storefront, items, options = {}) {
280
306
 
281
307
  // src/order.ts
282
308
  var import_storefront_api3 = require("@moonbase.sh/storefront-api");
283
- var import_uuid2 = require("uuid");
284
309
  function emptyCatalog() {
285
310
  return {
286
311
  suggestedCurrency: "",
@@ -293,7 +318,7 @@ function emptyCatalog() {
293
318
  }
294
319
  function newOrder(currency = "", items = []) {
295
320
  return {
296
- id: (0, import_uuid2.v4)(),
321
+ id: (0, import_storefront_api3.randomUuid)(),
297
322
  status: import_storefront_api3.OrderStatus.Open,
298
323
  currency,
299
324
  items,
@@ -598,6 +623,10 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
598
623
  this.client = client;
599
624
  this.listeners = /* @__PURE__ */ new Set();
600
625
  this.refreshOrderAbortController = new AbortController();
626
+ /** Aborted by `dispose`, which takes the storefront's window listeners with it. */
627
+ this.lifetime = new AbortController();
628
+ /** Whether the storefront took the hosted checkout's parameters off the address as it was made. */
629
+ this.tookCheckoutReturn = false;
601
630
  // Catalog refreshes are numbered as they start, and one only lands if no later one has landed first.
602
631
  // They overlap: a checkout's billing details and its completion each start one a moment apart, and
603
632
  // when the first to start is the last to answer, its catalog is from before the purchase and would
@@ -619,7 +648,18 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
619
648
  this.listeners.delete(listener);
620
649
  };
621
650
  };
622
- var _a;
651
+ /**
652
+ * Records the visitor's answer to the site's own cookie banner: remembered in this browser, so the
653
+ * storefront starts from it on their next visit, and passed on with `setAttributionConsent`. Other tabs
654
+ * follow it. `useAttributionConsent` hands it out. A banner that asks for Google's two consent mode
655
+ * signals separately passes them to `setAttributionConsent` instead.
656
+ */
657
+ this.answerAttributionConsent = (granted) => {
658
+ (0, import_storefront_api5.writeStorage)(_MoonbaseStorefront.attributionConsentKey, String(granted));
659
+ this.setState({ attributionConsentAnswer: granted });
660
+ this.setAttributionConsent(granted);
661
+ };
662
+ var _a, _b, _c;
623
663
  this.autoApplyItemOffers = (_a = options.autoApplyItemOffers) != null ? _a : false;
624
664
  this.catalogLoadedPromise = new Promise((resolve) => this.resolveCatalogLoaded = resolve);
625
665
  this.userLoadedPromise = new Promise((resolve) => this.resolveUserLoaded = resolve);
@@ -627,6 +667,10 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
627
667
  this.cart = createCart(this, { setOrder: (order2) => this.setState({ order: order2 }) });
628
668
  const initialCatalog = options.initialCatalog ? _MoonbaseStorefront.normalizeCatalog(options.initialCatalog) : emptyCatalog();
629
669
  this.serverState = {
670
+ attributionConsentAnswer: null,
671
+ attributionConsentRequired: void 0,
672
+ attributionConsentStatus: "unknown",
673
+ attributionConsentStatusByPlatform: { meta: "unknown", googleAnalytics: "unknown" },
630
674
  catalog: initialCatalog,
631
675
  catalogLoaded: !!options.initialCatalog,
632
676
  closed: false,
@@ -642,8 +686,12 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
642
686
  this.resolveUserLoaded();
643
687
  return;
644
688
  }
645
- window.addEventListener("storage", (event) => this.handleStorageUpdate(event));
646
- this.client.tokenStore.onSessionEnded(() => this.endSession());
689
+ const { signal } = this.lifetime;
690
+ window.addEventListener("storage", (event) => this.handleStorageUpdate(event), { signal });
691
+ this.client.tokenStore.onSessionEnded(() => {
692
+ if (!this.disposed)
693
+ this.endSession();
694
+ });
647
695
  const urlParams = new URLSearchParams(window.location.search);
648
696
  const fresh = {
649
697
  referrer: (0, import_storefront_api5.parseOffSiteReferrer)(window.document.referrer, window.location.origin),
@@ -663,7 +711,8 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
663
711
  ttclid: urlParams.get("ttclid") || void 0
664
712
  };
665
713
  fresh.adClicks = (0, import_storefront_api5.adClicksOf)(fresh);
666
- this.attributionConsentSetting = (0, import_storefront_api5.copyConsent)(configuration.attributionConsent);
714
+ const answer = _MoonbaseStorefront.parseAnswer((0, import_storefront_api5.readStorage)(_MoonbaseStorefront.attributionConsentKey));
715
+ this.attributionConsentSetting = (0, import_storefront_api5.copyConsent)((_c = (_b = configuration.attributionConsent) != null ? _b : answer) != null ? _c : void 0);
667
716
  const sessionRaw = (0, import_storefront_api5.readStorage)(_MoonbaseStorefront.utmKey, "session");
668
717
  const sessionCached = _MoonbaseStorefront.parseCachedUtm(sessionRaw);
669
718
  const cached = sessionCached != null ? sessionCached : configuration.persistUtm && this.attributionConsent ? _MoonbaseStorefront.parseCachedUtm((0, import_storefront_api5.readStorage)(_MoonbaseStorefront.utmKey, "local")) : void 0;
@@ -693,7 +742,7 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
693
742
  }
694
743
  const cachedCatalogJson = (0, import_storefront_api5.readStorage)(_MoonbaseStorefront.storefrontKey);
695
744
  const cachedCatalog = cachedCatalogJson ? _MoonbaseStorefront.parseCachedCatalog(cachedCatalogJson) : null;
696
- const catalog = cachedCatalog != null ? cachedCatalog : this.serverState.catalog;
745
+ const catalog = cachedCatalog ? { ...cachedCatalog, tracking: void 0 } : this.serverState.catalog;
697
746
  const cachedOrder = _MoonbaseStorefront.parseCachedOrder((0, import_storefront_api5.readStorage)(_MoonbaseStorefront.sessionKey));
698
747
  const order = cachedOrder != null ? cachedOrder : newOrder();
699
748
  let user = null;
@@ -706,6 +755,9 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
706
755
  }
707
756
  }
708
757
  this.state = {
758
+ attributionConsentAnswer: answer,
759
+ attributionConsentRequired: void 0,
760
+ ...this.consentStatus(catalog.tracking),
709
761
  catalog,
710
762
  catalogLoaded: !!cachedCatalog || this.serverState.catalogLoaded,
711
763
  closed: false,
@@ -718,6 +770,7 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
718
770
  };
719
771
  if (this.state.catalogLoaded)
720
772
  this.resolveCatalogLoaded();
773
+ void this.reportAdConsentRefusal();
721
774
  if (cachedOrder) {
722
775
  void this.refreshOrder();
723
776
  } else if (this.hasUtmOrReferrer && this.attributionConsent) {
@@ -737,21 +790,22 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
737
790
  else
738
791
  (0, import_storefront_api5.mountSubscription)(finalEndpoint.toString());
739
792
  window.history.replaceState(window.history.state, "", (0, import_storefront_api5.withoutHandshakeParams)(window.location.href));
793
+ this.tookCheckoutReturn = true;
740
794
  }
741
795
  window.addEventListener("moonbase-checkout-billing-details-updated", () => {
742
796
  this.refreshInBackground();
743
- });
797
+ }, { signal });
744
798
  window.addEventListener("moonbase-checkout-completed", (event) => {
745
799
  const completed = event.detail.order;
746
800
  if (completed.id === this.state.order.id)
747
801
  this.resetOrder();
748
802
  (0, import_storefront_api5.forgetPurchase)(completed.id);
749
803
  this.refreshInBackground();
750
- });
804
+ }, { signal });
751
805
  }
752
806
  /**
753
807
  * Calls `callback` each time the storefront reports `event`, and returns the function that stops it.
754
- * In a component, `useStorefrontEvent` does the subscribing and the cleaning up.
808
+ * `dispose` stops it too. In a component, `useStorefrontEvent` does the subscribing and the cleaning up.
755
809
  */
756
810
  on(event, callback) {
757
811
  if (typeof window === "undefined")
@@ -759,9 +813,50 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
759
813
  };
760
814
  const [name, read] = windowEvents[event];
761
815
  const listener = (e) => callback(...read(e.detail));
762
- window.addEventListener(name, listener);
816
+ window.addEventListener(name, listener, { signal: this.lifetime.signal });
763
817
  return () => window.removeEventListener(name, listener);
764
818
  }
819
+ /** Whether `dispose` has stopped the storefront. */
820
+ get disposed() {
821
+ return this.lifetime.signal.aborted;
822
+ }
823
+ /**
824
+ * Stops the storefront, for a test or for a page that swaps it for another: it stops following other
825
+ * tabs, the checkout and the customer's session, stops calling what `on` subscribed, stops renewing
826
+ * their sign-in, and ignores what requests still in flight bring back. A cart change still waiting to
827
+ * be sent goes at once. What it stored in the browser stays, for the next storefront to pick up.
828
+ * `getStorefront` makes a new one after this.
829
+ */
830
+ dispose() {
831
+ var _a;
832
+ if (this.disposed)
833
+ return;
834
+ this.lifetime.abort();
835
+ this.refreshOrderAbortController.abort();
836
+ clearTimeout(this.pushTimeout);
837
+ (_a = this.pendingPush) == null ? void 0 : _a.call(this);
838
+ this.client.tokenStore.dispose();
839
+ this.listeners.clear();
840
+ }
841
+ /**
842
+ * Takes the hosted checkout's parameters off the address again, when the storefront took them off as
843
+ * it was made and a router has since put them back, and has the router read the address again.
844
+ * `<StorefrontProvider>` calls it once the page has hydrated, which is all a page needs.
845
+ *
846
+ * Next.js's router is why: it reads the address before any of the page's own code runs, and writes it
847
+ * back as the page hydrates. It is told with a `popstate`, as for Back, since it ignores an address
848
+ * changed under the history entry it wrote, and `useSearchParams()` would go on listing the parameters.
849
+ */
850
+ clearCheckoutReturn() {
851
+ if (!this.tookCheckoutReturn || this.disposed || typeof window === "undefined")
852
+ return;
853
+ this.tookCheckoutReturn = false;
854
+ const address = (0, import_storefront_api5.withoutHandshakeParams)(window.location.href);
855
+ if (address === window.location.href)
856
+ return;
857
+ window.history.replaceState(window.history.state, "", address);
858
+ window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
859
+ }
765
860
  get hasUtm() {
766
861
  const utm = this.state.utm;
767
862
  return !!utm && !!(utm.source || utm.medium || utm.campaign || utm.term || utm.content || utm.id || utm.gadSource || utm.gadCampaignId);
@@ -802,6 +897,8 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
802
897
  const before = this.attributionConsent;
803
898
  this.attributionConsentSetting = (0, import_storefront_api5.copyConsent)(granted);
804
899
  this.attributionConsentChanged(before);
900
+ this.setState(this.consentStatus(this.state.catalog.tracking));
901
+ void this.reportAdConsentRefusal();
805
902
  if ((0, import_storefront_api5.grantsClickIds)(this.attributionConsentSetting) === false && typeof window !== "undefined") {
806
903
  if (this.hasUtmOrReferrer)
807
904
  (0, import_storefront_api5.writeStorage)(_MoonbaseStorefront.utmKey, JSON.stringify(this.state.utm), "session");
@@ -814,14 +911,17 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
814
911
  /**
815
912
  * What the storefront's requests say of the visit for ad measurement, beside `utm`: what the site last
816
913
  * reported of the visitor's consent, left out until it says, and when and on which page the visit's
817
- * tagged arrival landed, left out for a visit without tags.
914
+ * tagged arrival landed, left out for a visit without tags. Where the store connected Meta or Google
915
+ * Analytics in Moonbase, and while the visitor's consent lets click IDs go, also their browser IDs and
916
+ * the page the request is made on.
818
917
  */
819
918
  adSignals() {
820
919
  const landing = (0, import_storefront_api5.hasCampaignData)(this.state.utm) ? this.landing : void 0;
821
920
  return {
822
921
  consent: (0, import_storefront_api5.copyConsent)(this.attributionConsentSetting),
823
922
  arrivedAt: landing == null ? void 0 : landing.arrivedAt,
824
- landingPage: landing == null ? void 0 : landing.landingPage
923
+ landingPage: landing == null ? void 0 : landing.landingPage,
924
+ ...this.browserIdentifiers(landing)
825
925
  };
826
926
  }
827
927
  /** Asks Moonbase who is signed in. `state.user` is null when nobody is, or the session has run out. */
@@ -851,10 +951,11 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
851
951
  } catch (err) {
852
952
  if (!(err instanceof import_storefront_api5.StoreClosedError))
853
953
  throw err;
854
- this.closeStore();
954
+ if (!this.disposed)
955
+ this.closeStore();
855
956
  return this.state.catalog;
856
957
  }
857
- if (refresh < this.catalogRefreshLanded || !latest)
958
+ if (refresh < this.catalogRefreshLanded || !latest || this.disposed)
858
959
  return this.state.catalog;
859
960
  this.catalogRefreshLanded = refresh;
860
961
  (0, import_storefront_api5.writeStorage)(_MoonbaseStorefront.storefrontKey, JSON.stringify(latest));
@@ -868,8 +969,11 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
868
969
  const consentedBefore = this.attributionConsent;
869
970
  this.storeAllowsAttribution = latest.cookieConsentRequired === false;
870
971
  this.attributionConsentChanged(consentedBefore);
871
- if (typeof window !== "undefined")
972
+ this.setState(this.consentStatus(this.state.catalog.tracking));
973
+ if (typeof window !== "undefined") {
974
+ this.setState({ attributionConsentRequired: latest.cookieConsentRequired !== false });
872
975
  window.dispatchEvent(new CustomEvent("moonbase-storefront-updated", { detail: { storefront: latest } }));
976
+ }
873
977
  return latest;
874
978
  }
875
979
  /**
@@ -882,11 +986,15 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
882
986
  this.refreshOrderAbortController = new AbortController();
883
987
  const pushed = this.state.order;
884
988
  clearTimeout(this.pushTimeout);
885
- this.pushTimeout = setTimeout(() => {
989
+ const push = () => {
990
+ this.pushTimeout = void 0;
991
+ this.pendingPush = void 0;
886
992
  const latest = this.state.order;
887
993
  const order = latest.id === pushed.id ? latest : pushed;
888
994
  this.client.orders.pushContent(order, void 0, this.hasUtmOrReferrer ? this.state.utm : void 0, this.adSignals()).catch((err) => console.warn("Could not save the Moonbase cart", err));
889
- }, 500);
995
+ };
996
+ this.pendingPush = push;
997
+ this.pushTimeout = setTimeout(push, 500);
890
998
  }
891
999
  /**
892
1000
  * Starts a new, empty cart, or with `keepItems` a new cart holding the same lines, under a new ID.
@@ -943,8 +1051,9 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
943
1051
  }
944
1052
  setState(patch) {
945
1053
  const keys = Object.keys(patch);
946
- if (keys.every((key) => Object.is(this.state[key], patch[key])))
1054
+ if (this.disposed || keys.every((key) => Object.is(this.state[key], patch[key])))
947
1055
  return;
1056
+ const before = this.state;
948
1057
  this.state = { ...this.state, ...patch };
949
1058
  if (this.state.catalogLoaded)
950
1059
  this.resolveCatalogLoaded();
@@ -952,6 +1061,8 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
952
1061
  this.resolveUserLoaded();
953
1062
  for (const listener of [...this.listeners])
954
1063
  listener();
1064
+ if (this.state.user !== before.user)
1065
+ void this.reportAdConsentRefusal();
955
1066
  }
956
1067
  /**
957
1068
  * The server refused to renew the buyer's session: they signed out of it elsewhere, changed their
@@ -1021,6 +1132,65 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
1021
1132
  consentedUtm(utm) {
1022
1133
  return this.attributionConsent ? utm : (0, import_storefront_api5.withoutClickIds)(utm);
1023
1134
  }
1135
+ /**
1136
+ * The visitor's Meta and Google Analytics browser IDs, and this page, for a store that connected either
1137
+ * in Moonbase, while the visitor's consent lets click IDs go. A browser that sends Global Privacy Control
1138
+ * gives only those of a platform the store set to ignore it. Read as each request is made, since the
1139
+ * vendors' tags write their cookies after the storefront starts.
1140
+ */
1141
+ browserIdentifiers(landing) {
1142
+ var _a, _b, _c, _d, _e;
1143
+ const tracking = this.state.catalog.tracking;
1144
+ const meta = ((_b = (_a = tracking == null ? void 0 : tracking.meta) == null ? void 0 : _a.pixels.length) != null ? _b : 0) > 0 && !(0, import_storefront_api5.refusedByGlobalPrivacyControl)(tracking == null ? void 0 : tracking.meta);
1145
+ const googleAnalytics = (0, import_storefront_api5.refusedByGlobalPrivacyControl)(tracking == null ? void 0 : tracking.googleAnalytics) ? [] : (_d = (_c = tracking == null ? void 0 : tracking.googleAnalytics) == null ? void 0 : _c.streams.map((stream) => stream.id)) != null ? _d : [];
1146
+ if (!meta && googleAnalytics.length === 0 || !this.attributionConsent || typeof window === "undefined")
1147
+ return {};
1148
+ return {
1149
+ ...(0, import_storefront_api5.readBrowserIdentifiers)({
1150
+ cookies: (0, import_storefront_api5.readCookies)(),
1151
+ meta,
1152
+ googleAnalytics,
1153
+ arrival: { fbclid: (_e = this.state.utm) == null ? void 0 : _e.fbclid, arrivedAt: landing == null ? void 0 : landing.arrivedAt }
1154
+ }),
1155
+ pageUrl: `${window.location.origin}${window.location.pathname}`
1156
+ };
1157
+ }
1158
+ consentStatus(tracking) {
1159
+ const answered = (0, import_storefront_api5.grantsClickIds)(this.attributionConsentSetting) === false ? "refused" : this.attributionConsent ? "granted" : "unknown";
1160
+ return {
1161
+ attributionConsentStatus: (0, import_storefront_api5.globalPrivacyControlRefuses)(tracking) ? "refused" : answered,
1162
+ attributionConsentStatusByPlatform: {
1163
+ meta: (0, import_storefront_api5.refusedByGlobalPrivacyControl)(tracking == null ? void 0 : tracking.meta) ? "refused" : answered,
1164
+ googleAnalytics: (0, import_storefront_api5.refusedByGlobalPrivacyControl)(tracking == null ? void 0 : tracking.googleAnalytics) ? "refused" : answered
1165
+ }
1166
+ };
1167
+ }
1168
+ /**
1169
+ * Tells Moonbase when the site reports that a signed-in customer refuses ad tracking, which renewals
1170
+ * and other events sent without a visit then follow. Once per tab for each customer and report, as a
1171
+ * site's banner often reports the same choice on every page.
1172
+ */
1173
+ async reportAdConsentRefusal() {
1174
+ if (typeof window === "undefined")
1175
+ return;
1176
+ const user = this.state.user;
1177
+ const consent = this.attributionConsentSetting;
1178
+ const globalPrivacyControl = (0, import_storefront_api5.sendsGlobalPrivacyControl)();
1179
+ if (!(0, import_storefront_api5.refusesAny)(consent) && !globalPrivacyControl) {
1180
+ if (consent !== void 0)
1181
+ (0, import_storefront_api5.removeStorage)(_MoonbaseStorefront.adConsentReportedKey, "session");
1182
+ return;
1183
+ }
1184
+ const reported = JSON.stringify({ user: user == null ? void 0 : user.id, consent, globalPrivacyControl });
1185
+ if (!user || (0, import_storefront_api5.readStorage)(_MoonbaseStorefront.adConsentReportedKey, "session") === reported)
1186
+ return;
1187
+ (0, import_storefront_api5.writeStorage)(_MoonbaseStorefront.adConsentReportedKey, reported, "session");
1188
+ try {
1189
+ await this.client.identity.reportAdConsent(this.adSignals());
1190
+ } catch (e) {
1191
+ (0, import_storefront_api5.removeStorage)(_MoonbaseStorefront.adConsentReportedKey, "session");
1192
+ }
1193
+ }
1024
1194
  handleStorageUpdate(event) {
1025
1195
  var _a;
1026
1196
  switch (event.key) {
@@ -1043,6 +1213,13 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
1043
1213
  }
1044
1214
  break;
1045
1215
  }
1216
+ case _MoonbaseStorefront.attributionConsentKey: {
1217
+ const answer = _MoonbaseStorefront.parseAnswer(event.newValue);
1218
+ this.setState({ attributionConsentAnswer: answer });
1219
+ if (answer !== null)
1220
+ this.setAttributionConsent(answer);
1221
+ break;
1222
+ }
1046
1223
  case _MoonbaseStorefront.arrivalKey: {
1047
1224
  const landing = (0, import_storefront_api5.parseLanding)(event.newValue);
1048
1225
  if (landing)
@@ -1068,7 +1245,7 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
1068
1245
  const refreshingId = this.state.order.id;
1069
1246
  try {
1070
1247
  const latest = await this.client.orders.get(refreshingId, { abort: this.refreshOrderAbortController.signal });
1071
- if (this.state.order.id !== refreshingId || !latest)
1248
+ if (this.state.order.id !== refreshingId || !latest || this.disposed)
1072
1249
  return;
1073
1250
  if (latest.status !== import_storefront_api5.OrderStatus.Open) {
1074
1251
  this.resetOrder();
@@ -1086,6 +1263,9 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
1086
1263
  this.resetOrder();
1087
1264
  }
1088
1265
  }
1266
+ static parseAnswer(raw) {
1267
+ return raw === "true" ? true : raw === "false" ? false : null;
1268
+ }
1089
1269
  static parseCachedUtm(raw) {
1090
1270
  if (!raw)
1091
1271
  return void 0;
@@ -1131,12 +1311,18 @@ _MoonbaseStorefront.sessionKey = "moonbase_session";
1131
1311
  _MoonbaseStorefront.storefrontKey = "moonbase_storefront";
1132
1312
  _MoonbaseStorefront.utmKey = "moonbase_utm";
1133
1313
  _MoonbaseStorefront.arrivalKey = "moonbase_arrival";
1314
+ _MoonbaseStorefront.adConsentReportedKey = "moonbase_ad_consent_reported";
1315
+ _MoonbaseStorefront.attributionConsentKey = "moonbase_attribution_consent";
1134
1316
  var MoonbaseStorefront = _MoonbaseStorefront;
1135
1317
 
1136
1318
  // src/provider.ts
1137
1319
  var import_react = require("react");
1138
1320
  var StorefrontContext = (0, import_react.createContext)(null);
1139
1321
  function StorefrontProvider({ storefront, children }) {
1322
+ (0, import_react.useEffect)(() => {
1323
+ const timeout = setTimeout(() => storefront.clearCheckoutReturn());
1324
+ return () => clearTimeout(timeout);
1325
+ }, [storefront]);
1140
1326
  return (0, import_react.createElement)(StorefrontContext.Provider, { value: storefront }, children);
1141
1327
  }
1142
1328
  function useStorefront() {
@@ -1259,29 +1445,152 @@ function useCartOffer() {
1259
1445
  return (0, import_react2.useMemo)(() => cartOfferState(catalog, order), [catalog, order]);
1260
1446
  }
1261
1447
 
1262
- // src/hooks/useActivationRequest.ts
1448
+ // src/hooks/useAccountData.ts
1263
1449
  var import_storefront_api7 = require("@moonbase.sh/storefront-api");
1264
1450
  var import_react3 = require("react");
1265
- var pollInterval = 1500;
1266
- function useActivationRequest(token) {
1451
+ var caches = /* @__PURE__ */ new WeakMap();
1452
+ function cacheOf(storefront) {
1267
1453
  var _a;
1454
+ let cache = caches.get(storefront);
1455
+ if (!cache) {
1456
+ const created = new import_storefront_api7.AccountDataCache();
1457
+ let customer = (_a = storefront.getState().user) == null ? void 0 : _a.id;
1458
+ storefront.subscribe(() => {
1459
+ var _a2;
1460
+ const now = (_a2 = storefront.getState().user) == null ? void 0 : _a2.id;
1461
+ if (now !== customer) {
1462
+ customer = now;
1463
+ created.clear();
1464
+ }
1465
+ });
1466
+ caches.set(storefront, created);
1467
+ cache = created;
1468
+ }
1469
+ return cache;
1470
+ }
1471
+ var nothing = { data: null, loading: false, error: null, hasMore: false, next: null };
1472
+ async function noop() {
1473
+ }
1474
+ function useEntry(resource) {
1475
+ const storefront = useStorefront();
1476
+ const cache = cacheOf(storefront);
1477
+ const customer = useStorefrontState((state) => {
1478
+ var _a, _b;
1479
+ return (_b = (_a = state.user) == null ? void 0 : _a.id) != null ? _b : null;
1480
+ });
1481
+ const userLoaded = useStorefrontState((state) => state.userLoaded);
1482
+ const key = customer && resource !== null ? `${customer}
1483
+ ${resource}` : null;
1484
+ const entry = (0, import_react3.useSyncExternalStore)(
1485
+ cache.subscribe,
1486
+ () => {
1487
+ var _a;
1488
+ return (_a = key ? cache.get(key) : void 0) != null ? _a : nothing;
1489
+ },
1490
+ () => nothing
1491
+ );
1492
+ const pending = resource !== null && (customer ? entry === nothing : !userLoaded);
1493
+ return { storefront, cache, key, entry, pending };
1494
+ }
1495
+ function useAccountItem(kind, id, fetch) {
1496
+ const resource = id == null ? null : `${kind}
1497
+ ${id}`;
1498
+ const { storefront, cache, key, entry, pending } = useEntry(resource);
1499
+ const reload = (0, import_react3.useCallback)(
1500
+ () => key && id != null ? cache.refresh(key, () => fetch(storefront.client, id)) : noop(),
1501
+ [cache, key, id, fetch, storefront]
1502
+ );
1503
+ (0, import_react3.useEffect)(() => {
1504
+ if (key)
1505
+ cache.ensure(key, reload);
1506
+ }, [cache, key, reload]);
1507
+ return (0, import_react3.useMemo)(() => ({
1508
+ data: entry.data,
1509
+ loading: entry.loading || pending,
1510
+ error: entry.error,
1511
+ reload
1512
+ }), [entry, pending, reload]);
1513
+ }
1514
+ function useAccountPages(kind, id, fetchPage) {
1515
+ const resource = id == null ? null : `${kind}
1516
+ ${id}`;
1517
+ const { storefront, cache, key, entry, pending } = useEntry(resource);
1518
+ const reload = (0, import_react3.useCallback)(
1519
+ () => key && id != null ? cache.refreshPages(key, (next) => fetchPage(storefront.client, id, next)) : noop(),
1520
+ [cache, key, id, fetchPage, storefront]
1521
+ );
1522
+ const loadMore = (0, import_react3.useCallback)(
1523
+ () => key && id != null ? cache.loadMore(key, (next) => fetchPage(storefront.client, id, next)) : noop(),
1524
+ [cache, key, id, fetchPage, storefront]
1525
+ );
1526
+ (0, import_react3.useEffect)(() => {
1527
+ if (key)
1528
+ cache.ensure(key, reload);
1529
+ }, [cache, key, reload]);
1530
+ return (0, import_react3.useMemo)(() => ({
1531
+ data: entry.data,
1532
+ loading: entry.loading || pending,
1533
+ error: entry.error,
1534
+ hasMore: entry.hasMore,
1535
+ reload,
1536
+ loadMore
1537
+ }), [entry, pending, reload, loadMore]);
1538
+ }
1539
+ var ownedProducts = (client, _, next) => client.inventory.products.getOwned(next);
1540
+ var ownedProduct = (client, productId) => client.inventory.products.get(productId);
1541
+ var productActivations = (client, productId, next) => client.inventory.products.getActivations(productId, next);
1542
+ var productLicenses = (client, productId, next) => client.inventory.products.getLicenses(productId, next);
1543
+ var orderHistory = (client, _, next) => client.orders.getHistory(next);
1544
+ var subscriptions = (client, _, next) => client.inventory.subscriptions.get(next);
1545
+ var subscription = (client, subscriptionId) => client.inventory.subscriptions.getById(subscriptionId);
1546
+ function useOwnedProducts() {
1547
+ return useAccountPages("products", "", ownedProducts);
1548
+ }
1549
+ function useOwnedProduct(productId) {
1550
+ return useAccountItem("product", productId, ownedProduct);
1551
+ }
1552
+ function useProductActivations(productId) {
1553
+ return useAccountPages("product-activations", productId, productActivations);
1554
+ }
1555
+ function useProductLicenses(productId) {
1556
+ return useAccountPages("product-licenses", productId, productLicenses);
1557
+ }
1558
+ function useOrderHistory() {
1559
+ return useAccountPages("orders", "", orderHistory);
1560
+ }
1561
+ function useSubscriptions() {
1562
+ return useAccountPages("subscriptions", "", subscriptions);
1563
+ }
1564
+ function useSubscription(subscriptionId) {
1565
+ return useAccountItem("subscription", subscriptionId, subscription);
1566
+ }
1567
+
1568
+ // src/hooks/useActivationRequest.ts
1569
+ var import_storefront_api8 = require("@moonbase.sh/storefront-api");
1570
+ var import_react4 = require("react");
1571
+ var pollInterval = 1500;
1572
+ function errorMessage(err) {
1573
+ return err instanceof import_storefront_api8.NotAuthenticatedError ? "You need to be signed in to do this" : err.message;
1574
+ }
1575
+ function useActivationRequest(token, options = {}) {
1576
+ var _a, _b, _c;
1268
1577
  const storefront = useStorefront();
1269
1578
  const userId = useStorefrontState((state) => {
1270
- var _a2, _b;
1271
- return (_b = (_a2 = state.user) == null ? void 0 : _a2.id) != null ? _b : null;
1579
+ var _a2, _b2;
1580
+ return (_b2 = (_a2 = state.user) == null ? void 0 : _a2.id) != null ? _b2 : null;
1272
1581
  });
1273
- const [activationRequest, setActivationRequest] = (0, import_react3.useState)(null);
1274
- const [fetched, setFetched] = (0, import_react3.useState)(null);
1275
- const [fulfilling, setFulfilling] = (0, import_react3.useState)(false);
1276
- const [completing, setCompleting] = (0, import_react3.useState)(false);
1277
- const [error, setError] = (0, import_react3.useState)(null);
1278
- const adopt = (0, import_react3.useCallback)((request) => {
1582
+ const [activationRequest, setActivationRequest] = (0, import_react4.useState)(null);
1583
+ const [fetched, setFetched] = (0, import_react4.useState)(null);
1584
+ const [fulfilling, setFulfilling] = (0, import_react4.useState)(false);
1585
+ const [completing, setCompleting] = (0, import_react4.useState)(false);
1586
+ const [error, setError] = (0, import_react4.useState)(null);
1587
+ const adopt = (0, import_react4.useCallback)((request) => {
1279
1588
  setActivationRequest(request);
1280
- if (request.status === import_storefront_api7.ActivationRequestStatus.Fulfilled)
1589
+ if (request.status === import_storefront_api8.ActivationRequestStatus.Fulfilled)
1281
1590
  setCompleting(true);
1282
1591
  }, []);
1283
1592
  const upToDate = !!token && (fetched == null ? void 0 : fetched.token) === token && (fetched.userId === userId || !!((_a = activationRequest == null ? void 0 : activationRequest.licenseEligibility) == null ? void 0 : _a.eligible));
1284
- (0, import_react3.useEffect)(() => {
1593
+ (0, import_react4.useEffect)(() => {
1285
1594
  if (!token || upToDate)
1286
1595
  return;
1287
1596
  let current = true;
@@ -1291,7 +1600,7 @@ function useActivationRequest(token) {
1291
1600
  };
1292
1601
  }, [storefront, token, userId, upToDate, adopt]);
1293
1602
  const requestId = activationRequest == null ? void 0 : activationRequest.id;
1294
- (0, import_react3.useEffect)(() => {
1603
+ (0, import_react4.useEffect)(() => {
1295
1604
  if (!completing || !requestId)
1296
1605
  return;
1297
1606
  let current = true;
@@ -1302,7 +1611,7 @@ function useActivationRequest(token) {
1302
1611
  if (!current)
1303
1612
  return;
1304
1613
  if (completed) {
1305
- setActivationRequest((request) => request && { ...request, status: import_storefront_api7.ActivationRequestStatus.Completed });
1614
+ setActivationRequest((request) => request && { ...request, status: import_storefront_api8.ActivationRequestStatus.Completed });
1306
1615
  setCompleting(false);
1307
1616
  return;
1308
1617
  }
@@ -1318,9 +1627,10 @@ function useActivationRequest(token) {
1318
1627
  clearTimeout(timeout);
1319
1628
  };
1320
1629
  }, [storefront, completing, requestId]);
1321
- const fulfillLicense = (0, import_react3.useCallback)(async () => {
1630
+ const fulfillLicense = (0, import_react4.useCallback)(async () => {
1322
1631
  if (!requestId)
1323
1632
  return;
1633
+ setError(null);
1324
1634
  setFulfilling(true);
1325
1635
  try {
1326
1636
  adopt(await storefront.client.activationRequests.fulfillLicense(requestId));
@@ -1329,9 +1639,10 @@ function useActivationRequest(token) {
1329
1639
  setFulfilling(false);
1330
1640
  }
1331
1641
  }, [storefront, requestId, adopt]);
1332
- const fulfillTrial = (0, import_react3.useCallback)(async (newsletterOptIn = false) => {
1642
+ const fulfillTrial = (0, import_react4.useCallback)(async (newsletterOptIn = false) => {
1333
1643
  if (!requestId)
1334
1644
  return;
1645
+ setError(null);
1335
1646
  setFulfilling(true);
1336
1647
  try {
1337
1648
  const user = storefront.getState().user;
@@ -1346,13 +1657,25 @@ function useActivationRequest(token) {
1346
1657
  setCompleting(true);
1347
1658
  } catch (err) {
1348
1659
  console.warn("Could not fulfill trial: ", err);
1349
- setError(err instanceof import_storefront_api7.NotAuthenticatedError ? "You need to be signed in to do this" : err.message);
1660
+ setError(errorMessage(err));
1350
1661
  } finally {
1351
1662
  setFulfilling(false);
1352
1663
  }
1353
1664
  }, [storefront, requestId, adopt]);
1354
- const cancel = (0, import_react3.useCallback)(async () => {
1355
- if (!activationRequest || activationRequest.status === import_storefront_api7.ActivationRequestStatus.Cancelled)
1665
+ const autoFulfill = (_b = options.autoFulfill) != null ? _b : false;
1666
+ const autoFulfilled = (0, import_react4.useRef)(null);
1667
+ const eligible = (activationRequest == null ? void 0 : activationRequest.status) === import_storefront_api8.ActivationRequestStatus.Requested && !!((_c = activationRequest.licenseEligibility) == null ? void 0 : _c.eligible);
1668
+ (0, import_react4.useEffect)(() => {
1669
+ if (!autoFulfill || !eligible || !requestId || autoFulfilled.current === requestId)
1670
+ return;
1671
+ autoFulfilled.current = requestId;
1672
+ fulfillLicense().catch((err) => {
1673
+ console.warn("Could not activate with the customer's license: ", err);
1674
+ setError(errorMessage(err));
1675
+ });
1676
+ }, [autoFulfill, eligible, requestId, fulfillLicense]);
1677
+ const cancel = (0, import_react4.useCallback)(async () => {
1678
+ if (!activationRequest || activationRequest.status === import_storefront_api8.ActivationRequestStatus.Cancelled)
1356
1679
  return;
1357
1680
  adopt(await storefront.client.activationRequests.cancel(activationRequest.id));
1358
1681
  }, [storefront, activationRequest, adopt]);
@@ -1362,37 +1685,45 @@ function useActivationRequest(token) {
1362
1685
  fulfilling,
1363
1686
  completing,
1364
1687
  error,
1365
- isInstalled: (activationRequest == null ? void 0 : activationRequest.status) === import_storefront_api7.ActivationRequestStatus.Completed,
1688
+ isInstalled: (activationRequest == null ? void 0 : activationRequest.status) === import_storefront_api8.ActivationRequestStatus.Completed,
1366
1689
  fulfillLicense,
1367
1690
  fulfillTrial,
1368
1691
  cancel
1369
1692
  };
1370
1693
  }
1371
1694
 
1695
+ // src/hooks/useAttributionConsent.ts
1696
+ function useAttributionConsent() {
1697
+ const storefront = useStorefront();
1698
+ const required = useStorefrontState((state) => state.attributionConsentRequired);
1699
+ const answer = useStorefrontState((state) => state.attributionConsentAnswer);
1700
+ return { required, answer, setAnswer: storefront.answerAttributionConsent };
1701
+ }
1702
+
1372
1703
  // src/hooks/useAuth.ts
1373
- var import_react4 = require("react");
1704
+ var import_react5 = require("react");
1374
1705
  function useAuth() {
1375
1706
  const storefront = useStorefront();
1376
1707
  const user = useStorefrontState((state) => state.user);
1377
1708
  const loaded = useStorefrontState((state) => state.userLoaded);
1378
- return (0, import_react4.useMemo)(() => ({ ...storefront.auth, user, loaded }), [storefront, user, loaded]);
1709
+ return (0, import_react5.useMemo)(() => ({ ...storefront.auth, user, loaded }), [storefront, user, loaded]);
1379
1710
  }
1380
1711
 
1381
1712
  // src/hooks/useCart.ts
1382
- var import_storefront_api8 = require("@moonbase.sh/storefront-api");
1383
- var import_react5 = require("react");
1713
+ var import_storefront_api9 = require("@moonbase.sh/storefront-api");
1714
+ var import_react6 = require("react");
1384
1715
  function useCart() {
1385
1716
  const storefront = useStorefront();
1386
1717
  const catalog = useStorefrontState((state) => state.catalog);
1387
1718
  const order = useStorefrontState((state) => state.order);
1388
- return (0, import_react5.useMemo)(() => {
1389
- const currency = (0, import_storefront_api8.resolveDisplayCurrency)(order, catalog);
1390
- const breakdown = import_storefront_api8.CartUtils.total(catalog, order, currency);
1719
+ return (0, import_react6.useMemo)(() => {
1720
+ const currency = (0, import_storefront_api9.resolveDisplayCurrency)(order, catalog);
1721
+ const breakdown = import_storefront_api9.CartUtils.total(catalog, order, currency);
1391
1722
  const items = enrichLineItems(catalog, order);
1392
1723
  return {
1393
1724
  ...storefront.cart,
1394
1725
  items,
1395
- soldOutItems: items.filter((item) => import_storefront_api8.CartUtils.isSoldOut(catalog, item)),
1726
+ soldOutItems: items.filter((item) => import_storefront_api9.CartUtils.isSoldOut(catalog, item)),
1396
1727
  currency,
1397
1728
  total: { amount: breakdown.amount, currency: breakdown.currency },
1398
1729
  breakdown,
@@ -1400,19 +1731,25 @@ function useCart() {
1400
1731
  };
1401
1732
  }, [storefront, catalog, order]);
1402
1733
  }
1734
+ function useCurrency() {
1735
+ return useStorefrontState((state) => (0, import_storefront_api9.resolveDisplayCurrency)(state.order, state.catalog));
1736
+ }
1737
+ function useCartActions() {
1738
+ return useStorefront().cart;
1739
+ }
1403
1740
 
1404
1741
  // src/hooks/useCheckout.ts
1405
- var import_react6 = require("react");
1742
+ var import_react7 = require("react");
1406
1743
  function useCheckout() {
1407
1744
  const storefront = useStorefront();
1408
- return (0, import_react6.useCallback)((items, options) => storefront.checkout(items, options), [storefront]);
1745
+ return (0, import_react7.useCallback)((items, options) => storefront.checkout(items, options), [storefront]);
1409
1746
  }
1410
1747
 
1411
1748
  // src/hooks/useCommunicationPreferences.ts
1412
- var import_react7 = require("react");
1749
+ var import_react8 = require("react");
1413
1750
  function useCommunicationPreferences() {
1414
1751
  const storefront = useStorefront();
1415
- return (0, import_react7.useMemo)(() => {
1752
+ return (0, import_react8.useMemo)(() => {
1416
1753
  const communications = storefront.client.communications;
1417
1754
  return {
1418
1755
  subscribe: (input) => communications.subscribe(input, storefront.adSignals()),
@@ -1425,17 +1762,17 @@ function useCommunicationPreferences() {
1425
1762
  }
1426
1763
 
1427
1764
  // src/hooks/useGroups.ts
1428
- var import_react8 = require("react");
1765
+ var import_react9 = require("react");
1429
1766
  function useGroups() {
1430
1767
  const storefront = useStorefront();
1431
- return (0, import_react8.useMemo)(() => ({ join: (groupId) => storefront.client.groups.join(groupId) }), [storefront]);
1768
+ return (0, import_react9.useMemo)(() => ({ join: (groupId) => storefront.client.groups.join(groupId) }), [storefront]);
1432
1769
  }
1433
1770
 
1434
1771
  // src/hooks/useInventory.ts
1435
- var import_react9 = require("react");
1772
+ var import_react10 = require("react");
1436
1773
 
1437
1774
  // src/inventory.ts
1438
- var import_storefront_api9 = require("@moonbase.sh/storefront-api");
1775
+ var import_storefront_api10 = require("@moonbase.sh/storefront-api");
1439
1776
  function createInventory(storefront) {
1440
1777
  const inventory = storefront.client.inventory;
1441
1778
  return {
@@ -1451,7 +1788,7 @@ function createInventory(storefront) {
1451
1788
  downloadProduct: async (download) => {
1452
1789
  if (!download.path)
1453
1790
  throw new Error("Product is not downloadable");
1454
- window.location.href = await inventory.products.getDownloadUrl(download.path, storefront.adSignals());
1791
+ window.location.href = await inventory.products.getDownloadUrl(download.path, storefront.adSignals(), storefront.hasUtmOrReferrer ? storefront.getState().utm : void 0);
1455
1792
  },
1456
1793
  getSubscriptions: (nextUrl) => inventory.subscriptions.get(nextUrl),
1457
1794
  getSubscription: (subscriptionId) => inventory.subscriptions.getById(subscriptionId),
@@ -1462,23 +1799,23 @@ function createInventory(storefront) {
1462
1799
  renewSubscription: async (subscriptionId, options = {}) => {
1463
1800
  if (checkoutInProgress())
1464
1801
  return waitForCheckoutClose();
1465
- const redirect = (0, import_storefront_api9.resolveRedirect)(options.redirect);
1802
+ const redirect = (0, import_storefront_api10.resolveRedirect)(options.redirect);
1466
1803
  const { location: url } = await inventory.subscriptions.renew(subscriptionId, checkoutReturnUrl(options.returnUrl), !redirect);
1467
1804
  if (redirect) {
1468
- window.location.href = (0, import_storefront_api9.withPriceFormat)(url);
1805
+ window.location.href = (0, import_storefront_api10.withPriceFormat)(url);
1469
1806
  return { next: void 0, completed: false, redirected: true };
1470
1807
  }
1471
1808
  const closed = waitForCheckoutClose();
1472
- (0, import_storefront_api9.mountCheckout)(url);
1809
+ (0, import_storefront_api10.mountCheckout)(url);
1473
1810
  return closed;
1474
1811
  },
1475
- updateSubscriptionPaymentMethod: async (subscription, options = {}) => {
1476
- const response = await inventory.subscriptions.getById(subscription.id, {
1812
+ updateSubscriptionPaymentMethod: async (subscription2, options = {}) => {
1813
+ const response = await inventory.subscriptions.getById(subscription2.id, {
1477
1814
  toUpdatePaymentMethod: true,
1478
1815
  returnUrl: checkoutReturnUrl(options.returnUrl)
1479
1816
  });
1480
1817
  window.dispatchEvent(new CustomEvent("moonbase-subscription-payment-method-update-initiated", {
1481
- detail: { subscription }
1818
+ detail: { subscription: subscription2 }
1482
1819
  }));
1483
1820
  const url = response.embeddedUpdatePaymentUrl;
1484
1821
  if (!url)
@@ -1487,7 +1824,7 @@ function createInventory(storefront) {
1487
1824
  window.addEventListener("moonbase-subscription-closed", (event) => {
1488
1825
  resolve({ completed: event.detail.completed });
1489
1826
  }, { once: true });
1490
- (0, import_storefront_api9.mountSubscription)(url);
1827
+ (0, import_storefront_api10.mountSubscription)(url);
1491
1828
  });
1492
1829
  }
1493
1830
  };
@@ -1496,14 +1833,14 @@ function createInventory(storefront) {
1496
1833
  // src/hooks/useInventory.ts
1497
1834
  function useInventory() {
1498
1835
  const storefront = useStorefront();
1499
- return (0, import_react9.useMemo)(() => createInventory(storefront), [storefront]);
1836
+ return (0, import_react10.useMemo)(() => createInventory(storefront), [storefront]);
1500
1837
  }
1501
1838
 
1502
1839
  // src/hooks/useOrders.ts
1503
- var import_react10 = require("react");
1840
+ var import_react11 = require("react");
1504
1841
  function useOrders() {
1505
1842
  const storefront = useStorefront();
1506
- return (0, import_react10.useMemo)(() => ({
1843
+ return (0, import_react11.useMemo)(() => ({
1507
1844
  getOrders: (nextUrl) => storefront.client.orders.getHistory(nextUrl),
1508
1845
  getReceipt: (order) => storefront.client.orders.getReceipt(order.id),
1509
1846
  downloadReceipt: async (order) => {
@@ -1520,12 +1857,31 @@ function useOrders() {
1520
1857
  }), [storefront]);
1521
1858
  }
1522
1859
 
1860
+ // src/hooks/usePrice.ts
1861
+ var import_storefront_api11 = require("@moonbase.sh/storefront-api");
1862
+ var import_react12 = require("react");
1863
+ function usePrice(variation, format) {
1864
+ const currency = useCurrency();
1865
+ return (0, import_react12.useMemo)(() => {
1866
+ const amount = variation == null ? void 0 : variation.price[currency];
1867
+ const original = (variation == null ? void 0 : variation.hasDiscount) ? variation.originalPrice[currency] : void 0;
1868
+ const saving = amount !== void 0 && original !== void 0 ? Number((original - amount).toFixed(6)) : void 0;
1869
+ return {
1870
+ currency,
1871
+ price: amount === void 0 ? void 0 : (0, import_storefront_api11.formatMoney)(amount, currency, format),
1872
+ originalPrice: original === void 0 ? void 0 : (0, import_storefront_api11.formatMoney)(original, currency, format),
1873
+ saving: saving === void 0 || saving <= 0 ? void 0 : (0, import_storefront_api11.formatMoney)(saving, currency, format),
1874
+ amount
1875
+ };
1876
+ }, [variation, currency, format]);
1877
+ }
1878
+
1523
1879
  // src/hooks/useReviews.ts
1524
- var import_react11 = require("react");
1880
+ var import_react13 = require("react");
1525
1881
  function useReviews() {
1526
1882
  const storefront = useStorefront();
1527
1883
  const enabled = useStorefrontState((state) => !!state.catalog.reviewsEnabled);
1528
- return (0, import_react11.useMemo)(() => {
1884
+ return (0, import_react13.useMemo)(() => {
1529
1885
  const reviews = storefront.client.reviews;
1530
1886
  return {
1531
1887
  enabled,
@@ -1540,11 +1896,11 @@ function useReviews() {
1540
1896
  }
1541
1897
 
1542
1898
  // src/hooks/useVendor.ts
1543
- var import_react12 = require("react");
1899
+ var import_react14 = require("react");
1544
1900
  function useVendor() {
1545
1901
  const storefront = useStorefront();
1546
- const [state, setState] = (0, import_react12.useState)({ vendor: null, loading: true });
1547
- (0, import_react12.useEffect)(() => {
1902
+ const [state, setState] = (0, import_react14.useState)({ vendor: null, loading: true });
1903
+ (0, import_react14.useEffect)(() => {
1548
1904
  let current = true;
1549
1905
  storefront.client.vendor.get().then((vendor) => current && setState({ vendor, loading: false })).catch(() => current && setState({ vendor: null, loading: false }));
1550
1906
  return () => {
@@ -1555,16 +1911,16 @@ function useVendor() {
1555
1911
  }
1556
1912
 
1557
1913
  // src/hooks/useVoucher.ts
1558
- var import_storefront_api10 = require("@moonbase.sh/storefront-api");
1559
- var import_react13 = require("react");
1914
+ var import_storefront_api12 = require("@moonbase.sh/storefront-api");
1915
+ var import_react15 = require("react");
1560
1916
  function useVoucher() {
1561
1917
  const storefront = useStorefront();
1562
- return (0, import_react13.useMemo)(() => {
1918
+ return (0, import_react15.useMemo)(() => {
1563
1919
  const known = async (lookup) => {
1564
1920
  try {
1565
1921
  return await lookup;
1566
1922
  } catch (err) {
1567
- if (err instanceof import_storefront_api10.NotFoundError)
1923
+ if (err instanceof import_storefront_api12.NotFoundError)
1568
1924
  throw new Error("Voucher code invalid");
1569
1925
  throw err;
1570
1926
  }
@@ -1587,36 +1943,59 @@ function createStorefront(endpoint, options = {}) {
1587
1943
  // Named in `x-mb-client` ahead of `@moonbase.sh/storefront-api`, after any SDK wrapping this one.
1588
1944
  sdk: `${(_a = config.sdk) != null ? _a : ""} @moonbase.sh/react/${version}`.trim().replace(/\s+/g, " ")
1589
1945
  };
1590
- return new MoonbaseStorefront(configuration, new import_storefront_api11.MoonbaseClient(configuration), { initialCatalog, autoApplyItemOffers });
1946
+ return new MoonbaseStorefront(configuration, new import_storefront_api13.MoonbaseClient(configuration), { initialCatalog, autoApplyItemOffers });
1947
+ }
1948
+ var browserStorefronts = /* @__PURE__ */ new Map();
1949
+ function getStorefront(endpoint, options = {}) {
1950
+ if (typeof window === "undefined")
1951
+ return createStorefront(endpoint, options);
1952
+ let storefront = browserStorefronts.get(endpoint);
1953
+ if (!storefront || storefront.disposed) {
1954
+ storefront = createStorefront(endpoint, options);
1955
+ browserStorefronts.set(endpoint, storefront);
1956
+ }
1957
+ return storefront;
1591
1958
  }
1592
1959
  // Annotate the CommonJS export names for ESM import in node:
1593
1960
  0 && (module.exports = {
1594
1961
  MoonbaseStorefront,
1595
1962
  StorefrontProvider,
1596
1963
  createStorefront,
1964
+ getStorefront,
1597
1965
  useActivationRequest,
1966
+ useAttributionConsent,
1598
1967
  useAuth,
1599
1968
  useBundle,
1600
1969
  useBundles,
1601
1970
  useCart,
1971
+ useCartActions,
1602
1972
  useCartOffer,
1603
1973
  useCatalog,
1604
1974
  useCheckout,
1605
1975
  useCommunicationPreferences,
1976
+ useCurrency,
1606
1977
  useEligibleOffers,
1607
1978
  useGroups,
1608
1979
  useInventory,
1609
1980
  useLockedOffers,
1610
1981
  useOffer,
1611
1982
  useOffers,
1983
+ useOrderHistory,
1612
1984
  useOrders,
1985
+ useOwnedProduct,
1986
+ useOwnedProducts,
1987
+ usePrice,
1613
1988
  useProduct,
1989
+ useProductActivations,
1990
+ useProductLicenses,
1614
1991
  useProducts,
1615
1992
  usePromotions,
1616
1993
  useReviews,
1617
1994
  useStorefront,
1618
1995
  useStorefrontEvent,
1619
1996
  useStorefrontState,
1997
+ useSubscription,
1998
+ useSubscriptions,
1620
1999
  useVendor,
1621
2000
  useVoucher,
1622
2001
  ...require("@moonbase.sh/storefront-api")