@moonbase.sh/react 0.0.0-next-20261111171316 → 0.0.0-next-20261111171533
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/README.md +48 -6
- package/dist/index.cjs +132 -24
- package/dist/index.d.cts +100 -14
- package/dist/index.d.ts +100 -14
- package/dist/index.js +132 -25
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -31,7 +31,8 @@ createRoot(document.getElementById('root')!).render(
|
|
|
31
31
|
|
|
32
32
|
Make the storefront at module level, not in a component: it reads the address the visitor arrived at, keeps the cart
|
|
33
33
|
in step with other tabs, and coming back from the hosted checkout it reopens the checkout and takes Moonbase's `mb_*`
|
|
34
|
-
parameters off the address. Make it before your router, which reads the address as it is made.
|
|
34
|
+
parameters off the address. Make it before your router, which reads the address as it is made. Where it has to be made
|
|
35
|
+
in a component, such as from a catalog the server fetched, use `getStorefront` (see [Server rendering](#server-rendering)).
|
|
35
36
|
|
|
36
37
|
## Use hooks in components
|
|
37
38
|
|
|
@@ -97,8 +98,9 @@ identity across renders, so it can go in a dependency list or to a memoized chil
|
|
|
97
98
|
cancelling, renewing, changing plan and changing the card they're paid with.
|
|
98
99
|
- `useOrders()` - the signed-in customer's completed orders, newest first, and their receipt PDFs.
|
|
99
100
|
- `useVoucher()` - what a voucher code gives, and redeeming it.
|
|
100
|
-
- `useActivationRequest(token)` - activating a product in the browser: the request the app made, granting it a
|
|
101
|
-
or a trial, and waiting for the app to pick it up.
|
|
101
|
+
- `useActivationRequest(token, options)` - activating a product in the browser: the request the app made, granting it a
|
|
102
|
+
license or a trial, and waiting for the app to pick it up. With `{ autoFulfill: true }` it activates with the signed-in
|
|
103
|
+
customer's license as soon as the request says they can, once per request, leaving a failure in `error`.
|
|
102
104
|
- `useGroups()` - join the signed-in customer to a customer list of the store's that has been opened to sign-ups.
|
|
103
105
|
Throws `NotFoundError` for every reason a join can be refused, which the API deliberately does not distinguish.
|
|
104
106
|
- `useReviews()` - product reviews: `enabled` says whether the store takes them, `getReviews` and `getMoreReviews` read
|
|
@@ -108,7 +110,8 @@ identity across renders, so it can go in a dependency list or to a memoized chil
|
|
|
108
110
|
- `useCommunicationPreferences()` - newsletter sign-ups, and the preferences page an email's footer links to.
|
|
109
111
|
- `useVendor()` - who runs the store.
|
|
110
112
|
- `useStorefront()` - the storefront itself, and `useStorefrontState(state => ...)` for any part of its state
|
|
111
|
-
(`attributionConsentStatus`, `catalog`, `catalogLoaded`, `closed`, `order`, `user`,
|
|
113
|
+
(`attributionConsentRequired`, `attributionConsentStatus`, `catalog`, `catalogLoaded`, `closed`, `order`, `user`,
|
|
114
|
+
`userLoaded`, `utm`).
|
|
112
115
|
|
|
113
116
|
### Where checkout happens
|
|
114
117
|
|
|
@@ -188,6 +191,10 @@ your page is not loaded then: subscribe a webhook to `OrderPaymentFailed` to fol
|
|
|
188
191
|
|
|
189
192
|
Outside of React, `storefront.on('checkoutCompleted', order => ...)` does the same and returns the function that stops it.
|
|
190
193
|
|
|
194
|
+
`useStorefrontEvent` starts listening once its component has mounted, so it misses what the storefront reported before
|
|
195
|
+
then, such as the first `catalogUpdated` on a slow phone. Read what a page needs from the start from the state with
|
|
196
|
+
`useStorefrontState`, or subscribe with `storefront.on` where the storefront is made.
|
|
197
|
+
|
|
191
198
|
## Outside of components
|
|
192
199
|
|
|
193
200
|
Nothing in the storefront depends on React, so a router loader, an analytics script or your own store can use it
|
|
@@ -238,6 +245,28 @@ cookies as each request is made) and the page's origin and path. `storefront.adS
|
|
|
238
245
|
or `'unknown'`). When your banner reports a refusal for a signed-in customer, the storefront tells Moonbase, once per
|
|
239
246
|
tab.
|
|
240
247
|
|
|
248
|
+
`attributionConsentRequired` in the state says whether the store's setting asks this visitor at all: `true` or `false`
|
|
249
|
+
once the browser has loaded the catalog for them, and `undefined` until then, since a catalog fetched on a server
|
|
250
|
+
describes where the server is. A banner of your own asks when the store asks and nobody has answered yet:
|
|
251
|
+
|
|
252
|
+
```tsx
|
|
253
|
+
function CookieBanner() {
|
|
254
|
+
const required = useStorefrontState(state => state.attributionConsentRequired)
|
|
255
|
+
const status = useStorefrontState(state => state.attributionConsentStatus)
|
|
256
|
+
const storefront = useStorefront()
|
|
257
|
+
|
|
258
|
+
if (!required || status !== 'unknown')
|
|
259
|
+
return null
|
|
260
|
+
|
|
261
|
+
return (
|
|
262
|
+
<div role="dialog">
|
|
263
|
+
<button onClick={() => storefront.setAttributionConsent(true)}>Accept</button>
|
|
264
|
+
<button onClick={() => storefront.setAttributionConsent(false)}>Decline</button>
|
|
265
|
+
</div>
|
|
266
|
+
)
|
|
267
|
+
}
|
|
268
|
+
```
|
|
269
|
+
|
|
241
270
|
## Server rendering
|
|
242
271
|
|
|
243
272
|
`fetchCatalog(endpoint, options)` fetches the catalog on a server, as anyone sees it, for the `initialCatalog` a page's
|
|
@@ -253,13 +282,26 @@ storefront made at module level in a client module, as above, renders on the ser
|
|
|
253
282
|
own fallback prices until it loads, and the browser takes over from there. The browser hydrates against that same
|
|
254
283
|
server state before switching to its own, so a catalog it cached on an earlier visit never causes a hydration mismatch.
|
|
255
284
|
|
|
256
|
-
To have the server render real prices, fetch the catalog there and start the page's storefront from it
|
|
285
|
+
To have the server render real prices, fetch the catalog there and start the page's storefront from it. The storefront
|
|
286
|
+
is then made in a component, so make it with `getStorefront`, which hands back the same storefront every time in a
|
|
287
|
+
browser and a new one for each render on a server:
|
|
257
288
|
|
|
258
289
|
```tsx
|
|
259
290
|
'use client'
|
|
260
291
|
|
|
261
292
|
export function Providers({ catalog, children }: { catalog: Storefront, children: ReactNode }) {
|
|
262
|
-
const
|
|
293
|
+
const storefront = getStorefront('https://demo.moonbase.sh', { initialCatalog: catalog })
|
|
263
294
|
return <StorefrontProvider storefront={storefront}>{children}</StorefrontProvider>
|
|
264
295
|
}
|
|
265
296
|
```
|
|
297
|
+
|
|
298
|
+
Not `createStorefront` in a `useState` initializer: React runs one twice under Strict Mode, and the storefront it throws
|
|
299
|
+
away would go on following the tab. The options only count the first time, when the storefront is made.
|
|
300
|
+
|
|
301
|
+
A router that reads the address before the storefront is made, as Next.js's does, puts the hosted checkout's `mb_*`
|
|
302
|
+
parameters back as the page hydrates. `<StorefrontProvider>` takes them off again once the page has hydrated, and tells
|
|
303
|
+
the router with a `popstate`, so `useSearchParams()` no longer lists them either.
|
|
304
|
+
|
|
305
|
+
`storefront.dispose()` stops a storefront for good: it stops following other tabs and the checkout, stops renewing the
|
|
306
|
+
customer's sign-in, and ignores what its requests still in flight bring back. That is for tests, or a page that swaps one
|
|
307
|
+
storefront for another. After it, `getStorefront` makes a new one.
|
package/dist/index.cjs
CHANGED
|
@@ -24,6 +24,7 @@ __export(index_exports, {
|
|
|
24
24
|
MoonbaseStorefront: () => MoonbaseStorefront,
|
|
25
25
|
StorefrontProvider: () => StorefrontProvider,
|
|
26
26
|
createStorefront: () => createStorefront,
|
|
27
|
+
getStorefront: () => getStorefront,
|
|
27
28
|
useActivationRequest: () => useActivationRequest,
|
|
28
29
|
useAuth: () => useAuth,
|
|
29
30
|
useBundle: () => useBundle,
|
|
@@ -57,19 +58,34 @@ module.exports = __toCommonJS(index_exports);
|
|
|
57
58
|
var import_storefront_api12 = require("@moonbase.sh/storefront-api");
|
|
58
59
|
|
|
59
60
|
// package.json
|
|
60
|
-
var version = "0.0.0-next-
|
|
61
|
+
var version = "0.0.0-next-20261111171533";
|
|
61
62
|
|
|
62
63
|
// src/storefront.ts
|
|
63
64
|
var import_storefront_api5 = require("@moonbase.sh/storefront-api");
|
|
64
65
|
|
|
65
66
|
// src/auth.ts
|
|
66
67
|
var import_storefront_api = require("@moonbase.sh/storefront-api");
|
|
68
|
+
var confirmationReuse = 5e3;
|
|
67
69
|
function createAuth(storefront, internals) {
|
|
68
70
|
const { setUser } = internals;
|
|
69
71
|
const signedIn = () => storefront.getState().user !== null;
|
|
70
72
|
const refreshCatalog = () => {
|
|
71
73
|
storefront.refreshCatalog().catch((err) => console.error("Could not load the Moonbase catalog", err));
|
|
72
74
|
};
|
|
75
|
+
const confirmations = /* @__PURE__ */ new Map();
|
|
76
|
+
const confirmOnce = (kind, email, code, confirm) => {
|
|
77
|
+
const key = JSON.stringify([kind, email, code]);
|
|
78
|
+
const pending = confirmations.get(key);
|
|
79
|
+
if (pending)
|
|
80
|
+
return pending;
|
|
81
|
+
const result = confirm();
|
|
82
|
+
confirmations.set(key, result);
|
|
83
|
+
const forget = () => {
|
|
84
|
+
setTimeout(() => confirmations.delete(key), confirmationReuse);
|
|
85
|
+
};
|
|
86
|
+
result.then(forget, forget);
|
|
87
|
+
return result;
|
|
88
|
+
};
|
|
73
89
|
return {
|
|
74
90
|
signIn: async (email, password) => {
|
|
75
91
|
const user = await storefront.client.identity.signIn(email, password);
|
|
@@ -124,19 +140,19 @@ function createAuth(storefront, internals) {
|
|
|
124
140
|
setPassword: (currentPassword, newPassword) => storefront.client.identity.setPassword(currentPassword, newPassword),
|
|
125
141
|
forgotPassword: (email) => storefront.client.identity.forgotPassword(email),
|
|
126
142
|
resetPassword: (email, newPassword, code) => storefront.client.identity.resetPassword(email, newPassword, code),
|
|
127
|
-
confirmAccount:
|
|
143
|
+
confirmAccount: (email, code) => confirmOnce("account", email, code, async () => {
|
|
128
144
|
const result = await storefront.client.identity.confirmAccount(email, code);
|
|
129
145
|
if (result.status === "SignedIn") {
|
|
130
146
|
setUser(import_storefront_api.schemas.identity.userSchema.parse(storefront.client.tokenStore.user));
|
|
131
147
|
refreshCatalog();
|
|
132
148
|
}
|
|
133
149
|
return result;
|
|
134
|
-
},
|
|
135
|
-
confirmEmail: (email, code) => storefront.client.identity.confirmEmail(email, code),
|
|
136
|
-
confirmEmailChange:
|
|
150
|
+
}),
|
|
151
|
+
confirmEmail: (email, code) => confirmOnce("email", email, code, () => storefront.client.identity.confirmEmail(email, code)),
|
|
152
|
+
confirmEmailChange: (email, code) => confirmOnce("email-change", email, code, async () => {
|
|
137
153
|
await storefront.client.identity.confirmEmailChange(email, code);
|
|
138
154
|
return await storefront.refreshUser();
|
|
139
|
-
},
|
|
155
|
+
}),
|
|
140
156
|
getConnectionUrl: (provider, redirectUri, loginId) => storefront.client.identity.getConnectionUrl(provider, redirectUri, loginId),
|
|
141
157
|
disconnectAccount: async (provider) => {
|
|
142
158
|
await storefront.client.identity.disconnectAccount(provider);
|
|
@@ -599,6 +615,10 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
599
615
|
this.client = client;
|
|
600
616
|
this.listeners = /* @__PURE__ */ new Set();
|
|
601
617
|
this.refreshOrderAbortController = new AbortController();
|
|
618
|
+
/** Aborted by `dispose`, which takes the storefront's window listeners with it. */
|
|
619
|
+
this.lifetime = new AbortController();
|
|
620
|
+
/** Whether the storefront took the hosted checkout's parameters off the address as it was made. */
|
|
621
|
+
this.tookCheckoutReturn = false;
|
|
602
622
|
// Catalog refreshes are numbered as they start, and one only lands if no later one has landed first.
|
|
603
623
|
// They overlap: a checkout's billing details and its completion each start one a moment apart, and
|
|
604
624
|
// when the first to start is the last to answer, its catalog is from before the purchase and would
|
|
@@ -628,6 +648,7 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
628
648
|
this.cart = createCart(this, { setOrder: (order2) => this.setState({ order: order2 }) });
|
|
629
649
|
const initialCatalog = options.initialCatalog ? _MoonbaseStorefront.normalizeCatalog(options.initialCatalog) : emptyCatalog();
|
|
630
650
|
this.serverState = {
|
|
651
|
+
attributionConsentRequired: void 0,
|
|
631
652
|
attributionConsentStatus: "unknown",
|
|
632
653
|
catalog: initialCatalog,
|
|
633
654
|
catalogLoaded: !!options.initialCatalog,
|
|
@@ -644,8 +665,12 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
644
665
|
this.resolveUserLoaded();
|
|
645
666
|
return;
|
|
646
667
|
}
|
|
647
|
-
|
|
648
|
-
|
|
668
|
+
const { signal } = this.lifetime;
|
|
669
|
+
window.addEventListener("storage", (event) => this.handleStorageUpdate(event), { signal });
|
|
670
|
+
this.client.tokenStore.onSessionEnded(() => {
|
|
671
|
+
if (!this.disposed)
|
|
672
|
+
this.endSession();
|
|
673
|
+
});
|
|
649
674
|
const urlParams = new URLSearchParams(window.location.search);
|
|
650
675
|
const fresh = {
|
|
651
676
|
referrer: (0, import_storefront_api5.parseOffSiteReferrer)(window.document.referrer, window.location.origin),
|
|
@@ -708,6 +733,7 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
708
733
|
}
|
|
709
734
|
}
|
|
710
735
|
this.state = {
|
|
736
|
+
attributionConsentRequired: void 0,
|
|
711
737
|
attributionConsentStatus: this.consentStatus(),
|
|
712
738
|
catalog,
|
|
713
739
|
catalogLoaded: !!cachedCatalog || this.serverState.catalogLoaded,
|
|
@@ -741,21 +767,22 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
741
767
|
else
|
|
742
768
|
(0, import_storefront_api5.mountSubscription)(finalEndpoint.toString());
|
|
743
769
|
window.history.replaceState(window.history.state, "", (0, import_storefront_api5.withoutHandshakeParams)(window.location.href));
|
|
770
|
+
this.tookCheckoutReturn = true;
|
|
744
771
|
}
|
|
745
772
|
window.addEventListener("moonbase-checkout-billing-details-updated", () => {
|
|
746
773
|
this.refreshInBackground();
|
|
747
|
-
});
|
|
774
|
+
}, { signal });
|
|
748
775
|
window.addEventListener("moonbase-checkout-completed", (event) => {
|
|
749
776
|
const completed = event.detail.order;
|
|
750
777
|
if (completed.id === this.state.order.id)
|
|
751
778
|
this.resetOrder();
|
|
752
779
|
(0, import_storefront_api5.forgetPurchase)(completed.id);
|
|
753
780
|
this.refreshInBackground();
|
|
754
|
-
});
|
|
781
|
+
}, { signal });
|
|
755
782
|
}
|
|
756
783
|
/**
|
|
757
784
|
* Calls `callback` each time the storefront reports `event`, and returns the function that stops it.
|
|
758
|
-
* In a component, `useStorefrontEvent` does the subscribing and the cleaning up.
|
|
785
|
+
* `dispose` stops it too. In a component, `useStorefrontEvent` does the subscribing and the cleaning up.
|
|
759
786
|
*/
|
|
760
787
|
on(event, callback) {
|
|
761
788
|
if (typeof window === "undefined")
|
|
@@ -763,9 +790,50 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
763
790
|
};
|
|
764
791
|
const [name, read] = windowEvents[event];
|
|
765
792
|
const listener = (e) => callback(...read(e.detail));
|
|
766
|
-
window.addEventListener(name, listener);
|
|
793
|
+
window.addEventListener(name, listener, { signal: this.lifetime.signal });
|
|
767
794
|
return () => window.removeEventListener(name, listener);
|
|
768
795
|
}
|
|
796
|
+
/** Whether `dispose` has stopped the storefront. */
|
|
797
|
+
get disposed() {
|
|
798
|
+
return this.lifetime.signal.aborted;
|
|
799
|
+
}
|
|
800
|
+
/**
|
|
801
|
+
* Stops the storefront, for a test or for a page that swaps it for another: it stops following other
|
|
802
|
+
* tabs, the checkout and the customer's session, stops calling what `on` subscribed, stops renewing
|
|
803
|
+
* their sign-in, and ignores what requests still in flight bring back. A cart change still waiting to
|
|
804
|
+
* be sent goes at once. What it stored in the browser stays, for the next storefront to pick up.
|
|
805
|
+
* `getStorefront` makes a new one after this.
|
|
806
|
+
*/
|
|
807
|
+
dispose() {
|
|
808
|
+
var _a;
|
|
809
|
+
if (this.disposed)
|
|
810
|
+
return;
|
|
811
|
+
this.lifetime.abort();
|
|
812
|
+
this.refreshOrderAbortController.abort();
|
|
813
|
+
clearTimeout(this.pushTimeout);
|
|
814
|
+
(_a = this.pendingPush) == null ? void 0 : _a.call(this);
|
|
815
|
+
this.client.tokenStore.dispose();
|
|
816
|
+
this.listeners.clear();
|
|
817
|
+
}
|
|
818
|
+
/**
|
|
819
|
+
* Takes the hosted checkout's parameters off the address again, when the storefront took them off as
|
|
820
|
+
* it was made and a router has since put them back, and has the router read the address again.
|
|
821
|
+
* `<StorefrontProvider>` calls it once the page has hydrated, which is all a page needs.
|
|
822
|
+
*
|
|
823
|
+
* Next.js's router is why: it reads the address before any of the page's own code runs, and writes it
|
|
824
|
+
* back as the page hydrates. It is told with a `popstate`, as for Back, since it ignores an address
|
|
825
|
+
* changed under the history entry it wrote, and `useSearchParams()` would go on listing the parameters.
|
|
826
|
+
*/
|
|
827
|
+
clearCheckoutReturn() {
|
|
828
|
+
if (!this.tookCheckoutReturn || this.disposed || typeof window === "undefined")
|
|
829
|
+
return;
|
|
830
|
+
this.tookCheckoutReturn = false;
|
|
831
|
+
const address = (0, import_storefront_api5.withoutHandshakeParams)(window.location.href);
|
|
832
|
+
if (address === window.location.href)
|
|
833
|
+
return;
|
|
834
|
+
window.history.replaceState(window.history.state, "", address);
|
|
835
|
+
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
|
|
836
|
+
}
|
|
769
837
|
get hasUtm() {
|
|
770
838
|
const utm = this.state.utm;
|
|
771
839
|
return !!utm && !!(utm.source || utm.medium || utm.campaign || utm.term || utm.content || utm.id || utm.gadSource || utm.gadCampaignId);
|
|
@@ -860,10 +928,11 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
860
928
|
} catch (err) {
|
|
861
929
|
if (!(err instanceof import_storefront_api5.StoreClosedError))
|
|
862
930
|
throw err;
|
|
863
|
-
this.
|
|
931
|
+
if (!this.disposed)
|
|
932
|
+
this.closeStore();
|
|
864
933
|
return this.state.catalog;
|
|
865
934
|
}
|
|
866
|
-
if (refresh < this.catalogRefreshLanded || !latest)
|
|
935
|
+
if (refresh < this.catalogRefreshLanded || !latest || this.disposed)
|
|
867
936
|
return this.state.catalog;
|
|
868
937
|
this.catalogRefreshLanded = refresh;
|
|
869
938
|
(0, import_storefront_api5.writeStorage)(_MoonbaseStorefront.storefrontKey, JSON.stringify(latest));
|
|
@@ -878,8 +947,10 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
878
947
|
this.storeAllowsAttribution = latest.cookieConsentRequired === false;
|
|
879
948
|
this.attributionConsentChanged(consentedBefore);
|
|
880
949
|
this.setState({ attributionConsentStatus: this.consentStatus() });
|
|
881
|
-
if (typeof window !== "undefined")
|
|
950
|
+
if (typeof window !== "undefined") {
|
|
951
|
+
this.setState({ attributionConsentRequired: latest.cookieConsentRequired !== false });
|
|
882
952
|
window.dispatchEvent(new CustomEvent("moonbase-storefront-updated", { detail: { storefront: latest } }));
|
|
953
|
+
}
|
|
883
954
|
return latest;
|
|
884
955
|
}
|
|
885
956
|
/**
|
|
@@ -892,11 +963,15 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
892
963
|
this.refreshOrderAbortController = new AbortController();
|
|
893
964
|
const pushed = this.state.order;
|
|
894
965
|
clearTimeout(this.pushTimeout);
|
|
895
|
-
|
|
966
|
+
const push = () => {
|
|
967
|
+
this.pushTimeout = void 0;
|
|
968
|
+
this.pendingPush = void 0;
|
|
896
969
|
const latest = this.state.order;
|
|
897
970
|
const order = latest.id === pushed.id ? latest : pushed;
|
|
898
971
|
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));
|
|
899
|
-
}
|
|
972
|
+
};
|
|
973
|
+
this.pendingPush = push;
|
|
974
|
+
this.pushTimeout = setTimeout(push, 500);
|
|
900
975
|
}
|
|
901
976
|
/**
|
|
902
977
|
* Starts a new, empty cart, or with `keepItems` a new cart holding the same lines, under a new ID.
|
|
@@ -953,7 +1028,7 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
953
1028
|
}
|
|
954
1029
|
setState(patch) {
|
|
955
1030
|
const keys = Object.keys(patch);
|
|
956
|
-
if (keys.every((key) => Object.is(this.state[key], patch[key])))
|
|
1031
|
+
if (this.disposed || keys.every((key) => Object.is(this.state[key], patch[key])))
|
|
957
1032
|
return;
|
|
958
1033
|
const before = this.state;
|
|
959
1034
|
this.state = { ...this.state, ...patch };
|
|
@@ -1132,7 +1207,7 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
1132
1207
|
const refreshingId = this.state.order.id;
|
|
1133
1208
|
try {
|
|
1134
1209
|
const latest = await this.client.orders.get(refreshingId, { abort: this.refreshOrderAbortController.signal });
|
|
1135
|
-
if (this.state.order.id !== refreshingId || !latest)
|
|
1210
|
+
if (this.state.order.id !== refreshingId || !latest || this.disposed)
|
|
1136
1211
|
return;
|
|
1137
1212
|
if (latest.status !== import_storefront_api5.OrderStatus.Open) {
|
|
1138
1213
|
this.resetOrder();
|
|
@@ -1202,6 +1277,10 @@ var MoonbaseStorefront = _MoonbaseStorefront;
|
|
|
1202
1277
|
var import_react = require("react");
|
|
1203
1278
|
var StorefrontContext = (0, import_react.createContext)(null);
|
|
1204
1279
|
function StorefrontProvider({ storefront, children }) {
|
|
1280
|
+
(0, import_react.useEffect)(() => {
|
|
1281
|
+
const timeout = setTimeout(() => storefront.clearCheckoutReturn());
|
|
1282
|
+
return () => clearTimeout(timeout);
|
|
1283
|
+
}, [storefront]);
|
|
1205
1284
|
return (0, import_react.createElement)(StorefrontContext.Provider, { value: storefront }, children);
|
|
1206
1285
|
}
|
|
1207
1286
|
function useStorefront() {
|
|
@@ -1328,12 +1407,15 @@ function useCartOffer() {
|
|
|
1328
1407
|
var import_storefront_api7 = require("@moonbase.sh/storefront-api");
|
|
1329
1408
|
var import_react3 = require("react");
|
|
1330
1409
|
var pollInterval = 1500;
|
|
1331
|
-
function
|
|
1332
|
-
|
|
1410
|
+
function errorMessage(err) {
|
|
1411
|
+
return err instanceof import_storefront_api7.NotAuthenticatedError ? "You need to be signed in to do this" : err.message;
|
|
1412
|
+
}
|
|
1413
|
+
function useActivationRequest(token, options = {}) {
|
|
1414
|
+
var _a, _b, _c;
|
|
1333
1415
|
const storefront = useStorefront();
|
|
1334
1416
|
const userId = useStorefrontState((state) => {
|
|
1335
|
-
var _a2,
|
|
1336
|
-
return (
|
|
1417
|
+
var _a2, _b2;
|
|
1418
|
+
return (_b2 = (_a2 = state.user) == null ? void 0 : _a2.id) != null ? _b2 : null;
|
|
1337
1419
|
});
|
|
1338
1420
|
const [activationRequest, setActivationRequest] = (0, import_react3.useState)(null);
|
|
1339
1421
|
const [fetched, setFetched] = (0, import_react3.useState)(null);
|
|
@@ -1386,6 +1468,7 @@ function useActivationRequest(token) {
|
|
|
1386
1468
|
const fulfillLicense = (0, import_react3.useCallback)(async () => {
|
|
1387
1469
|
if (!requestId)
|
|
1388
1470
|
return;
|
|
1471
|
+
setError(null);
|
|
1389
1472
|
setFulfilling(true);
|
|
1390
1473
|
try {
|
|
1391
1474
|
adopt(await storefront.client.activationRequests.fulfillLicense(requestId));
|
|
@@ -1397,6 +1480,7 @@ function useActivationRequest(token) {
|
|
|
1397
1480
|
const fulfillTrial = (0, import_react3.useCallback)(async (newsletterOptIn = false) => {
|
|
1398
1481
|
if (!requestId)
|
|
1399
1482
|
return;
|
|
1483
|
+
setError(null);
|
|
1400
1484
|
setFulfilling(true);
|
|
1401
1485
|
try {
|
|
1402
1486
|
const user = storefront.getState().user;
|
|
@@ -1411,11 +1495,23 @@ function useActivationRequest(token) {
|
|
|
1411
1495
|
setCompleting(true);
|
|
1412
1496
|
} catch (err) {
|
|
1413
1497
|
console.warn("Could not fulfill trial: ", err);
|
|
1414
|
-
setError(err
|
|
1498
|
+
setError(errorMessage(err));
|
|
1415
1499
|
} finally {
|
|
1416
1500
|
setFulfilling(false);
|
|
1417
1501
|
}
|
|
1418
1502
|
}, [storefront, requestId, adopt]);
|
|
1503
|
+
const autoFulfill = (_b = options.autoFulfill) != null ? _b : false;
|
|
1504
|
+
const autoFulfilled = (0, import_react3.useRef)(null);
|
|
1505
|
+
const eligible = (activationRequest == null ? void 0 : activationRequest.status) === import_storefront_api7.ActivationRequestStatus.Requested && !!((_c = activationRequest.licenseEligibility) == null ? void 0 : _c.eligible);
|
|
1506
|
+
(0, import_react3.useEffect)(() => {
|
|
1507
|
+
if (!autoFulfill || !eligible || !requestId || autoFulfilled.current === requestId)
|
|
1508
|
+
return;
|
|
1509
|
+
autoFulfilled.current = requestId;
|
|
1510
|
+
fulfillLicense().catch((err) => {
|
|
1511
|
+
console.warn("Could not activate with the customer's license: ", err);
|
|
1512
|
+
setError(errorMessage(err));
|
|
1513
|
+
});
|
|
1514
|
+
}, [autoFulfill, eligible, requestId, fulfillLicense]);
|
|
1419
1515
|
const cancel = (0, import_react3.useCallback)(async () => {
|
|
1420
1516
|
if (!activationRequest || activationRequest.status === import_storefront_api7.ActivationRequestStatus.Cancelled)
|
|
1421
1517
|
return;
|
|
@@ -1679,11 +1775,23 @@ function createStorefront(endpoint, options = {}) {
|
|
|
1679
1775
|
};
|
|
1680
1776
|
return new MoonbaseStorefront(configuration, new import_storefront_api12.MoonbaseClient(configuration), { initialCatalog, autoApplyItemOffers });
|
|
1681
1777
|
}
|
|
1778
|
+
var browserStorefronts = /* @__PURE__ */ new Map();
|
|
1779
|
+
function getStorefront(endpoint, options = {}) {
|
|
1780
|
+
if (typeof window === "undefined")
|
|
1781
|
+
return createStorefront(endpoint, options);
|
|
1782
|
+
let storefront = browserStorefronts.get(endpoint);
|
|
1783
|
+
if (!storefront || storefront.disposed) {
|
|
1784
|
+
storefront = createStorefront(endpoint, options);
|
|
1785
|
+
browserStorefronts.set(endpoint, storefront);
|
|
1786
|
+
}
|
|
1787
|
+
return storefront;
|
|
1788
|
+
}
|
|
1682
1789
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1683
1790
|
0 && (module.exports = {
|
|
1684
1791
|
MoonbaseStorefront,
|
|
1685
1792
|
StorefrontProvider,
|
|
1686
1793
|
createStorefront,
|
|
1794
|
+
getStorefront,
|
|
1687
1795
|
useActivationRequest,
|
|
1688
1796
|
useAuth,
|
|
1689
1797
|
useBundle,
|
package/dist/index.d.cts
CHANGED
|
@@ -31,7 +31,13 @@ interface StorefrontAuth {
|
|
|
31
31
|
setPassword: (currentPassword: string, newPassword: string) => Promise<void>;
|
|
32
32
|
forgotPassword: (email: string) => Promise<void>;
|
|
33
33
|
resetPassword: (email: string, newPassword: string, code: string) => Promise<void>;
|
|
34
|
-
/**
|
|
34
|
+
/**
|
|
35
|
+
* Confirms a new account from the code in its welcome email, which signs the customer in. A code works
|
|
36
|
+
* once, so calling this again with the same email and code, while the first call is in flight or for
|
|
37
|
+
* a few seconds after, hands back the first call's result rather than asking Moonbase twice: a page
|
|
38
|
+
* confirming as it loads can be run twice by React. The same goes for `confirmEmail` and
|
|
39
|
+
* `confirmEmailChange`.
|
|
40
|
+
*/
|
|
35
41
|
confirmAccount: (email: string, code: string) => Promise<UserAccountConfirmed>;
|
|
36
42
|
confirmEmail: (email: string, code: string) => Promise<void>;
|
|
37
43
|
confirmEmailChange: (email: string, code: string) => Promise<User | null>;
|
|
@@ -130,6 +136,14 @@ interface StorefrontCart {
|
|
|
130
136
|
type AttributionConsentStatus = 'granted' | 'refused' | 'unknown';
|
|
131
137
|
/** Everything a storefront knows that a page draws from. Replaced, never changed in place, on every update. */
|
|
132
138
|
interface StorefrontState {
|
|
139
|
+
/**
|
|
140
|
+
* Whether the store asks this visitor to agree to marketing cookies before it keeps the ad click IDs
|
|
141
|
+
* they arrived with, as its "Ad and campaign tracking" setting in Moonbase decides for where they are.
|
|
142
|
+
* `undefined` until a catalog loaded in this browser says: one a server fetched, such as
|
|
143
|
+
* `initialCatalog`, describes where the server is. A cookie banner asks when this is `true` and
|
|
144
|
+
* `attributionConsentStatus` is still `'unknown'`.
|
|
145
|
+
*/
|
|
146
|
+
attributionConsentRequired: boolean | undefined;
|
|
133
147
|
/**
|
|
134
148
|
* Where the visitor's consent to marketing cookies stands: `'refused'` once the site reports a refusal,
|
|
135
149
|
* `'granted'` once the site reports consent or the store's own setting lets them go unasked, and
|
|
@@ -192,7 +206,11 @@ interface StorefrontEvents {
|
|
|
192
206
|
* called), and `order` is the order it was open for, when the checkout sent it.
|
|
193
207
|
*/
|
|
194
208
|
checkoutClosed: (intent: string | undefined, completed: boolean, order: Order | undefined) => void;
|
|
195
|
-
/**
|
|
209
|
+
/**
|
|
210
|
+
* A fresh catalog arrived from Moonbase. The first one can arrive before a component's effects run, so
|
|
211
|
+
* a component that needs what it says reads it from the state instead: `catalog`, or
|
|
212
|
+
* `attributionConsentRequired` for whether to ask for consent.
|
|
213
|
+
*/
|
|
196
214
|
catalogUpdated: (catalog: Storefront) => void;
|
|
197
215
|
/**
|
|
198
216
|
* Moonbase refused to renew the buyer's session: they signed out of it elsewhere, changed their
|
|
@@ -263,6 +281,12 @@ declare class MoonbaseStorefront {
|
|
|
263
281
|
private storeAllowsAttribution;
|
|
264
282
|
private refreshOrderAbortController;
|
|
265
283
|
private pushTimeout;
|
|
284
|
+
/** Sends the cart change `pushTimeout` is waiting to send. */
|
|
285
|
+
private pendingPush;
|
|
286
|
+
/** Aborted by `dispose`, which takes the storefront's window listeners with it. */
|
|
287
|
+
private readonly lifetime;
|
|
288
|
+
/** Whether the storefront took the hosted checkout's parameters off the address as it was made. */
|
|
289
|
+
private tookCheckoutReturn;
|
|
266
290
|
private catalogRefreshesStarted;
|
|
267
291
|
private catalogRefreshLanded;
|
|
268
292
|
constructor(configuration: MoonbaseConfiguration, client: MoonbaseClient, options?: Pick<StorefrontOptions, 'initialCatalog' | 'autoApplyItemOffers'>);
|
|
@@ -278,9 +302,29 @@ declare class MoonbaseStorefront {
|
|
|
278
302
|
readonly subscribe: (listener: () => void) => (() => void);
|
|
279
303
|
/**
|
|
280
304
|
* Calls `callback` each time the storefront reports `event`, and returns the function that stops it.
|
|
281
|
-
* In a component, `useStorefrontEvent` does the subscribing and the cleaning up.
|
|
305
|
+
* `dispose` stops it too. In a component, `useStorefrontEvent` does the subscribing and the cleaning up.
|
|
282
306
|
*/
|
|
283
307
|
on<K extends keyof StorefrontEvents>(event: K, callback: StorefrontEvents[K]): () => void;
|
|
308
|
+
/** Whether `dispose` has stopped the storefront. */
|
|
309
|
+
get disposed(): boolean;
|
|
310
|
+
/**
|
|
311
|
+
* Stops the storefront, for a test or for a page that swaps it for another: it stops following other
|
|
312
|
+
* tabs, the checkout and the customer's session, stops calling what `on` subscribed, stops renewing
|
|
313
|
+
* their sign-in, and ignores what requests still in flight bring back. A cart change still waiting to
|
|
314
|
+
* be sent goes at once. What it stored in the browser stays, for the next storefront to pick up.
|
|
315
|
+
* `getStorefront` makes a new one after this.
|
|
316
|
+
*/
|
|
317
|
+
dispose(): void;
|
|
318
|
+
/**
|
|
319
|
+
* Takes the hosted checkout's parameters off the address again, when the storefront took them off as
|
|
320
|
+
* it was made and a router has since put them back, and has the router read the address again.
|
|
321
|
+
* `<StorefrontProvider>` calls it once the page has hydrated, which is all a page needs.
|
|
322
|
+
*
|
|
323
|
+
* Next.js's router is why: it reads the address before any of the page's own code runs, and writes it
|
|
324
|
+
* back as the page hydrates. It is told with a `popstate`, as for Back, since it ignores an address
|
|
325
|
+
* changed under the history entry it wrote, and `useSearchParams()` would go on listing the parameters.
|
|
326
|
+
*/
|
|
327
|
+
clearCheckoutReturn(): void;
|
|
284
328
|
get hasUtm(): boolean;
|
|
285
329
|
get hasUtmOrReferrer(): boolean;
|
|
286
330
|
/** Whether the storefront may keep and send ad click IDs and record an arrival before any action. */
|
|
@@ -392,14 +436,17 @@ declare class MoonbaseStorefront {
|
|
|
392
436
|
/** The store's catalog for this visitor, with `useStorefrontState(state => state.catalogLoaded)` saying whether it has loaded. */
|
|
393
437
|
declare function useCatalog(): Storefront;
|
|
394
438
|
declare function useProducts(): StorefrontProduct[];
|
|
395
|
-
/**
|
|
396
|
-
|
|
439
|
+
/**
|
|
440
|
+
* The product with this ID in the catalog, or null, as before the catalog has loaded. Null for no ID, so a
|
|
441
|
+
* component that may have none, such as a cart line holding a bundle, can still call it.
|
|
442
|
+
*/
|
|
443
|
+
declare function useProduct(productId: string | null | undefined): StorefrontProduct | null;
|
|
397
444
|
declare function useBundles(): StorefrontBundle[];
|
|
398
|
-
/** The bundle with this ID in the catalog, or null. */
|
|
399
|
-
declare function useBundle(bundleId: string): StorefrontBundle | null;
|
|
445
|
+
/** The bundle with this ID in the catalog, or null, also for no ID. */
|
|
446
|
+
declare function useBundle(bundleId: string | null | undefined): StorefrontBundle | null;
|
|
400
447
|
declare function useOffers(): StorefrontOffer[];
|
|
401
|
-
/** The offer with this ID in the catalog, or null. */
|
|
402
|
-
declare function useOffer(offerId: string): StorefrontOffer | null;
|
|
448
|
+
/** The offer with this ID in the catalog, or null, also for no ID. */
|
|
449
|
+
declare function useOffer(offerId: string | null | undefined): StorefrontOffer | null;
|
|
403
450
|
/**
|
|
404
451
|
* The sales currently running across the store's catalog.
|
|
405
452
|
*
|
|
@@ -468,12 +515,21 @@ interface ActivationRequestState {
|
|
|
468
515
|
/** Turns the request down, as a customer who didn't make it would. */
|
|
469
516
|
cancel: () => Promise<void>;
|
|
470
517
|
}
|
|
518
|
+
interface ActivationRequestOptions {
|
|
519
|
+
/**
|
|
520
|
+
* Activates with a license the signed-in customer owns as soon as the request says they can: once
|
|
521
|
+
* `activationRequest.licenseEligibility.eligible` is true while it is still `Requested`. Tried once per
|
|
522
|
+
* request. A failure is left in `error`, and `fulfillLicense` tries again.
|
|
523
|
+
*/
|
|
524
|
+
autoFulfill?: boolean;
|
|
525
|
+
}
|
|
471
526
|
/**
|
|
472
527
|
* Activating a product in the browser: the page an app opens with a `token` when its customer chooses
|
|
473
528
|
* to activate online. Loads the request, again when someone signs in, and once it has been granted
|
|
474
|
-
* waits for the app to pick it up. Without a token, as on a link that lost it, it loads nothing.
|
|
529
|
+
* waits for the app to pick it up. Without a token, as on a link that lost it, it loads nothing. With
|
|
530
|
+
* `autoFulfill`, it activates with the customer's license as soon as the request says they can.
|
|
475
531
|
*/
|
|
476
|
-
declare function useActivationRequest(token: string | null | undefined): ActivationRequestState;
|
|
532
|
+
declare function useActivationRequest(token: string | null | undefined, options?: ActivationRequestOptions): ActivationRequestState;
|
|
477
533
|
|
|
478
534
|
interface Auth extends StorefrontAuth {
|
|
479
535
|
/** The signed-in customer, or null. */
|
|
@@ -680,7 +736,10 @@ interface Vouchers {
|
|
|
680
736
|
declare function useVoucher(): Vouchers;
|
|
681
737
|
|
|
682
738
|
interface StorefrontProviderProps {
|
|
683
|
-
/**
|
|
739
|
+
/**
|
|
740
|
+
* The storefront: one `createStorefront` made outside of any component, or one `getStorefront` hands
|
|
741
|
+
* back in a component.
|
|
742
|
+
*/
|
|
684
743
|
storefront: MoonbaseStorefront;
|
|
685
744
|
children?: ReactNode;
|
|
686
745
|
}
|
|
@@ -702,6 +761,11 @@ declare function useStorefrontState<T>(selector: (state: StorefrontState) => T):
|
|
|
702
761
|
* ```tsx
|
|
703
762
|
* useStorefrontEvent('checkoutCompleted', order => setThanks(order))
|
|
704
763
|
* ```
|
|
764
|
+
*
|
|
765
|
+
* It starts listening once the component has mounted, after hydration, so it misses what the storefront
|
|
766
|
+
* reported before then, such as the first `catalogUpdated` on a slow phone. Read what has to be known
|
|
767
|
+
* from the start from the state instead, with `useStorefrontState`, or subscribe with `storefront.on`
|
|
768
|
+
* where the storefront is made.
|
|
705
769
|
*/
|
|
706
770
|
declare function useStorefrontEvent<K extends keyof StorefrontEvents>(event: K, handler: StorefrontEvents[K]): void;
|
|
707
771
|
|
|
@@ -720,8 +784,30 @@ declare function useStorefrontEvent<K extends keyof StorefrontEvents>(event: K,
|
|
|
720
784
|
* ```
|
|
721
785
|
*
|
|
722
786
|
* Coming back from the hosted checkout, it takes Moonbase's parameters off the address as it is made,
|
|
723
|
-
* so make it before a router that reads the address.
|
|
787
|
+
* so make it before a router that reads the address. To make it in a component instead, such as from
|
|
788
|
+
* a catalog the server fetched, use `getStorefront`.
|
|
724
789
|
*/
|
|
725
790
|
declare function createStorefront(endpoint: string, options?: StorefrontOptions): MoonbaseStorefront;
|
|
791
|
+
/**
|
|
792
|
+
* The storefront for `endpoint`: in a browser, made the first time it is asked for and the same one every
|
|
793
|
+
* time after, and on a server, a new one each time, as each render there is for another visitor. For
|
|
794
|
+
* making the storefront in a component, such as a Next.js layout's providers starting it from a catalog
|
|
795
|
+
* the server fetched:
|
|
796
|
+
*
|
|
797
|
+
* ```tsx
|
|
798
|
+
* 'use client'
|
|
799
|
+
*
|
|
800
|
+
* export function Providers({ catalog, children }: { catalog: Storefront, children: ReactNode }) {
|
|
801
|
+
* const storefront = getStorefront('https://demo.moonbase.sh', { initialCatalog: catalog })
|
|
802
|
+
* return <StorefrontProvider storefront={storefront}>{children}</StorefrontProvider>
|
|
803
|
+
* }
|
|
804
|
+
* ```
|
|
805
|
+
*
|
|
806
|
+
* React can render a component, and run a `useState` initializer, more than once for one page, and each
|
|
807
|
+
* `createStorefront` there would be another storefront following the tab. `options` only count when the
|
|
808
|
+
* storefront is made, so a later `initialCatalog` is ignored: the storefront already has a fresher
|
|
809
|
+
* catalog by then. Once the storefront is disposed, the next call makes a new one.
|
|
810
|
+
*/
|
|
811
|
+
declare function getStorefront(endpoint: string, options?: StorefrontOptions): MoonbaseStorefront;
|
|
726
812
|
|
|
727
|
-
export { type ActivationRequestState, type AddToCartOptions, type AttributionConsentStatus, type Auth, type Cart, type CartCheckoutOptions, type CartItem, type CartOfferState, type CheckoutItem, type CheckoutOptions, type CheckoutRedirectOptions, type CheckoutResult, type Communications, type Groups, type LockedOffer, MoonbaseStorefront, type Orders, type ProductReviews, type StorefrontAuth, type StorefrontCart, type StorefrontEvents, type StorefrontInventory, type StorefrontOptions, StorefrontProvider, type StorefrontProviderProps, type StorefrontState, type VariationPrice, type VendorState, type Vouchers, createStorefront, useActivationRequest, useAuth, useBundle, useBundles, useCart, useCartActions, useCartOffer, useCatalog, useCheckout, useCommunicationPreferences, useCurrency, useEligibleOffers, useGroups, useInventory, useLockedOffers, useOffer, useOffers, useOrders, usePrice, useProduct, useProducts, usePromotions, useReviews, useStorefront, useStorefrontEvent, useStorefrontState, useVendor, useVoucher };
|
|
813
|
+
export { type ActivationRequestOptions, type ActivationRequestState, type AddToCartOptions, type AttributionConsentStatus, type Auth, type Cart, type CartCheckoutOptions, type CartItem, type CartOfferState, type CheckoutItem, type CheckoutOptions, type CheckoutRedirectOptions, type CheckoutResult, type Communications, type Groups, type LockedOffer, MoonbaseStorefront, type Orders, type ProductReviews, type StorefrontAuth, type StorefrontCart, type StorefrontEvents, type StorefrontInventory, type StorefrontOptions, StorefrontProvider, type StorefrontProviderProps, type StorefrontState, type VariationPrice, type VendorState, type Vouchers, createStorefront, getStorefront, useActivationRequest, useAuth, useBundle, useBundles, useCart, useCartActions, useCartOffer, useCatalog, useCheckout, useCommunicationPreferences, useCurrency, useEligibleOffers, useGroups, useInventory, useLockedOffers, useOffer, useOffers, useOrders, usePrice, useProduct, useProducts, usePromotions, useReviews, useStorefront, useStorefrontEvent, useStorefrontState, useVendor, useVoucher };
|
package/dist/index.d.ts
CHANGED
|
@@ -31,7 +31,13 @@ interface StorefrontAuth {
|
|
|
31
31
|
setPassword: (currentPassword: string, newPassword: string) => Promise<void>;
|
|
32
32
|
forgotPassword: (email: string) => Promise<void>;
|
|
33
33
|
resetPassword: (email: string, newPassword: string, code: string) => Promise<void>;
|
|
34
|
-
/**
|
|
34
|
+
/**
|
|
35
|
+
* Confirms a new account from the code in its welcome email, which signs the customer in. A code works
|
|
36
|
+
* once, so calling this again with the same email and code, while the first call is in flight or for
|
|
37
|
+
* a few seconds after, hands back the first call's result rather than asking Moonbase twice: a page
|
|
38
|
+
* confirming as it loads can be run twice by React. The same goes for `confirmEmail` and
|
|
39
|
+
* `confirmEmailChange`.
|
|
40
|
+
*/
|
|
35
41
|
confirmAccount: (email: string, code: string) => Promise<UserAccountConfirmed>;
|
|
36
42
|
confirmEmail: (email: string, code: string) => Promise<void>;
|
|
37
43
|
confirmEmailChange: (email: string, code: string) => Promise<User | null>;
|
|
@@ -130,6 +136,14 @@ interface StorefrontCart {
|
|
|
130
136
|
type AttributionConsentStatus = 'granted' | 'refused' | 'unknown';
|
|
131
137
|
/** Everything a storefront knows that a page draws from. Replaced, never changed in place, on every update. */
|
|
132
138
|
interface StorefrontState {
|
|
139
|
+
/**
|
|
140
|
+
* Whether the store asks this visitor to agree to marketing cookies before it keeps the ad click IDs
|
|
141
|
+
* they arrived with, as its "Ad and campaign tracking" setting in Moonbase decides for where they are.
|
|
142
|
+
* `undefined` until a catalog loaded in this browser says: one a server fetched, such as
|
|
143
|
+
* `initialCatalog`, describes where the server is. A cookie banner asks when this is `true` and
|
|
144
|
+
* `attributionConsentStatus` is still `'unknown'`.
|
|
145
|
+
*/
|
|
146
|
+
attributionConsentRequired: boolean | undefined;
|
|
133
147
|
/**
|
|
134
148
|
* Where the visitor's consent to marketing cookies stands: `'refused'` once the site reports a refusal,
|
|
135
149
|
* `'granted'` once the site reports consent or the store's own setting lets them go unasked, and
|
|
@@ -192,7 +206,11 @@ interface StorefrontEvents {
|
|
|
192
206
|
* called), and `order` is the order it was open for, when the checkout sent it.
|
|
193
207
|
*/
|
|
194
208
|
checkoutClosed: (intent: string | undefined, completed: boolean, order: Order | undefined) => void;
|
|
195
|
-
/**
|
|
209
|
+
/**
|
|
210
|
+
* A fresh catalog arrived from Moonbase. The first one can arrive before a component's effects run, so
|
|
211
|
+
* a component that needs what it says reads it from the state instead: `catalog`, or
|
|
212
|
+
* `attributionConsentRequired` for whether to ask for consent.
|
|
213
|
+
*/
|
|
196
214
|
catalogUpdated: (catalog: Storefront) => void;
|
|
197
215
|
/**
|
|
198
216
|
* Moonbase refused to renew the buyer's session: they signed out of it elsewhere, changed their
|
|
@@ -263,6 +281,12 @@ declare class MoonbaseStorefront {
|
|
|
263
281
|
private storeAllowsAttribution;
|
|
264
282
|
private refreshOrderAbortController;
|
|
265
283
|
private pushTimeout;
|
|
284
|
+
/** Sends the cart change `pushTimeout` is waiting to send. */
|
|
285
|
+
private pendingPush;
|
|
286
|
+
/** Aborted by `dispose`, which takes the storefront's window listeners with it. */
|
|
287
|
+
private readonly lifetime;
|
|
288
|
+
/** Whether the storefront took the hosted checkout's parameters off the address as it was made. */
|
|
289
|
+
private tookCheckoutReturn;
|
|
266
290
|
private catalogRefreshesStarted;
|
|
267
291
|
private catalogRefreshLanded;
|
|
268
292
|
constructor(configuration: MoonbaseConfiguration, client: MoonbaseClient, options?: Pick<StorefrontOptions, 'initialCatalog' | 'autoApplyItemOffers'>);
|
|
@@ -278,9 +302,29 @@ declare class MoonbaseStorefront {
|
|
|
278
302
|
readonly subscribe: (listener: () => void) => (() => void);
|
|
279
303
|
/**
|
|
280
304
|
* Calls `callback` each time the storefront reports `event`, and returns the function that stops it.
|
|
281
|
-
* In a component, `useStorefrontEvent` does the subscribing and the cleaning up.
|
|
305
|
+
* `dispose` stops it too. In a component, `useStorefrontEvent` does the subscribing and the cleaning up.
|
|
282
306
|
*/
|
|
283
307
|
on<K extends keyof StorefrontEvents>(event: K, callback: StorefrontEvents[K]): () => void;
|
|
308
|
+
/** Whether `dispose` has stopped the storefront. */
|
|
309
|
+
get disposed(): boolean;
|
|
310
|
+
/**
|
|
311
|
+
* Stops the storefront, for a test or for a page that swaps it for another: it stops following other
|
|
312
|
+
* tabs, the checkout and the customer's session, stops calling what `on` subscribed, stops renewing
|
|
313
|
+
* their sign-in, and ignores what requests still in flight bring back. A cart change still waiting to
|
|
314
|
+
* be sent goes at once. What it stored in the browser stays, for the next storefront to pick up.
|
|
315
|
+
* `getStorefront` makes a new one after this.
|
|
316
|
+
*/
|
|
317
|
+
dispose(): void;
|
|
318
|
+
/**
|
|
319
|
+
* Takes the hosted checkout's parameters off the address again, when the storefront took them off as
|
|
320
|
+
* it was made and a router has since put them back, and has the router read the address again.
|
|
321
|
+
* `<StorefrontProvider>` calls it once the page has hydrated, which is all a page needs.
|
|
322
|
+
*
|
|
323
|
+
* Next.js's router is why: it reads the address before any of the page's own code runs, and writes it
|
|
324
|
+
* back as the page hydrates. It is told with a `popstate`, as for Back, since it ignores an address
|
|
325
|
+
* changed under the history entry it wrote, and `useSearchParams()` would go on listing the parameters.
|
|
326
|
+
*/
|
|
327
|
+
clearCheckoutReturn(): void;
|
|
284
328
|
get hasUtm(): boolean;
|
|
285
329
|
get hasUtmOrReferrer(): boolean;
|
|
286
330
|
/** Whether the storefront may keep and send ad click IDs and record an arrival before any action. */
|
|
@@ -392,14 +436,17 @@ declare class MoonbaseStorefront {
|
|
|
392
436
|
/** The store's catalog for this visitor, with `useStorefrontState(state => state.catalogLoaded)` saying whether it has loaded. */
|
|
393
437
|
declare function useCatalog(): Storefront;
|
|
394
438
|
declare function useProducts(): StorefrontProduct[];
|
|
395
|
-
/**
|
|
396
|
-
|
|
439
|
+
/**
|
|
440
|
+
* The product with this ID in the catalog, or null, as before the catalog has loaded. Null for no ID, so a
|
|
441
|
+
* component that may have none, such as a cart line holding a bundle, can still call it.
|
|
442
|
+
*/
|
|
443
|
+
declare function useProduct(productId: string | null | undefined): StorefrontProduct | null;
|
|
397
444
|
declare function useBundles(): StorefrontBundle[];
|
|
398
|
-
/** The bundle with this ID in the catalog, or null. */
|
|
399
|
-
declare function useBundle(bundleId: string): StorefrontBundle | null;
|
|
445
|
+
/** The bundle with this ID in the catalog, or null, also for no ID. */
|
|
446
|
+
declare function useBundle(bundleId: string | null | undefined): StorefrontBundle | null;
|
|
400
447
|
declare function useOffers(): StorefrontOffer[];
|
|
401
|
-
/** The offer with this ID in the catalog, or null. */
|
|
402
|
-
declare function useOffer(offerId: string): StorefrontOffer | null;
|
|
448
|
+
/** The offer with this ID in the catalog, or null, also for no ID. */
|
|
449
|
+
declare function useOffer(offerId: string | null | undefined): StorefrontOffer | null;
|
|
403
450
|
/**
|
|
404
451
|
* The sales currently running across the store's catalog.
|
|
405
452
|
*
|
|
@@ -468,12 +515,21 @@ interface ActivationRequestState {
|
|
|
468
515
|
/** Turns the request down, as a customer who didn't make it would. */
|
|
469
516
|
cancel: () => Promise<void>;
|
|
470
517
|
}
|
|
518
|
+
interface ActivationRequestOptions {
|
|
519
|
+
/**
|
|
520
|
+
* Activates with a license the signed-in customer owns as soon as the request says they can: once
|
|
521
|
+
* `activationRequest.licenseEligibility.eligible` is true while it is still `Requested`. Tried once per
|
|
522
|
+
* request. A failure is left in `error`, and `fulfillLicense` tries again.
|
|
523
|
+
*/
|
|
524
|
+
autoFulfill?: boolean;
|
|
525
|
+
}
|
|
471
526
|
/**
|
|
472
527
|
* Activating a product in the browser: the page an app opens with a `token` when its customer chooses
|
|
473
528
|
* to activate online. Loads the request, again when someone signs in, and once it has been granted
|
|
474
|
-
* waits for the app to pick it up. Without a token, as on a link that lost it, it loads nothing.
|
|
529
|
+
* waits for the app to pick it up. Without a token, as on a link that lost it, it loads nothing. With
|
|
530
|
+
* `autoFulfill`, it activates with the customer's license as soon as the request says they can.
|
|
475
531
|
*/
|
|
476
|
-
declare function useActivationRequest(token: string | null | undefined): ActivationRequestState;
|
|
532
|
+
declare function useActivationRequest(token: string | null | undefined, options?: ActivationRequestOptions): ActivationRequestState;
|
|
477
533
|
|
|
478
534
|
interface Auth extends StorefrontAuth {
|
|
479
535
|
/** The signed-in customer, or null. */
|
|
@@ -680,7 +736,10 @@ interface Vouchers {
|
|
|
680
736
|
declare function useVoucher(): Vouchers;
|
|
681
737
|
|
|
682
738
|
interface StorefrontProviderProps {
|
|
683
|
-
/**
|
|
739
|
+
/**
|
|
740
|
+
* The storefront: one `createStorefront` made outside of any component, or one `getStorefront` hands
|
|
741
|
+
* back in a component.
|
|
742
|
+
*/
|
|
684
743
|
storefront: MoonbaseStorefront;
|
|
685
744
|
children?: ReactNode;
|
|
686
745
|
}
|
|
@@ -702,6 +761,11 @@ declare function useStorefrontState<T>(selector: (state: StorefrontState) => T):
|
|
|
702
761
|
* ```tsx
|
|
703
762
|
* useStorefrontEvent('checkoutCompleted', order => setThanks(order))
|
|
704
763
|
* ```
|
|
764
|
+
*
|
|
765
|
+
* It starts listening once the component has mounted, after hydration, so it misses what the storefront
|
|
766
|
+
* reported before then, such as the first `catalogUpdated` on a slow phone. Read what has to be known
|
|
767
|
+
* from the start from the state instead, with `useStorefrontState`, or subscribe with `storefront.on`
|
|
768
|
+
* where the storefront is made.
|
|
705
769
|
*/
|
|
706
770
|
declare function useStorefrontEvent<K extends keyof StorefrontEvents>(event: K, handler: StorefrontEvents[K]): void;
|
|
707
771
|
|
|
@@ -720,8 +784,30 @@ declare function useStorefrontEvent<K extends keyof StorefrontEvents>(event: K,
|
|
|
720
784
|
* ```
|
|
721
785
|
*
|
|
722
786
|
* Coming back from the hosted checkout, it takes Moonbase's parameters off the address as it is made,
|
|
723
|
-
* so make it before a router that reads the address.
|
|
787
|
+
* so make it before a router that reads the address. To make it in a component instead, such as from
|
|
788
|
+
* a catalog the server fetched, use `getStorefront`.
|
|
724
789
|
*/
|
|
725
790
|
declare function createStorefront(endpoint: string, options?: StorefrontOptions): MoonbaseStorefront;
|
|
791
|
+
/**
|
|
792
|
+
* The storefront for `endpoint`: in a browser, made the first time it is asked for and the same one every
|
|
793
|
+
* time after, and on a server, a new one each time, as each render there is for another visitor. For
|
|
794
|
+
* making the storefront in a component, such as a Next.js layout's providers starting it from a catalog
|
|
795
|
+
* the server fetched:
|
|
796
|
+
*
|
|
797
|
+
* ```tsx
|
|
798
|
+
* 'use client'
|
|
799
|
+
*
|
|
800
|
+
* export function Providers({ catalog, children }: { catalog: Storefront, children: ReactNode }) {
|
|
801
|
+
* const storefront = getStorefront('https://demo.moonbase.sh', { initialCatalog: catalog })
|
|
802
|
+
* return <StorefrontProvider storefront={storefront}>{children}</StorefrontProvider>
|
|
803
|
+
* }
|
|
804
|
+
* ```
|
|
805
|
+
*
|
|
806
|
+
* React can render a component, and run a `useState` initializer, more than once for one page, and each
|
|
807
|
+
* `createStorefront` there would be another storefront following the tab. `options` only count when the
|
|
808
|
+
* storefront is made, so a later `initialCatalog` is ignored: the storefront already has a fresher
|
|
809
|
+
* catalog by then. Once the storefront is disposed, the next call makes a new one.
|
|
810
|
+
*/
|
|
811
|
+
declare function getStorefront(endpoint: string, options?: StorefrontOptions): MoonbaseStorefront;
|
|
726
812
|
|
|
727
|
-
export { type ActivationRequestState, type AddToCartOptions, type AttributionConsentStatus, type Auth, type Cart, type CartCheckoutOptions, type CartItem, type CartOfferState, type CheckoutItem, type CheckoutOptions, type CheckoutRedirectOptions, type CheckoutResult, type Communications, type Groups, type LockedOffer, MoonbaseStorefront, type Orders, type ProductReviews, type StorefrontAuth, type StorefrontCart, type StorefrontEvents, type StorefrontInventory, type StorefrontOptions, StorefrontProvider, type StorefrontProviderProps, type StorefrontState, type VariationPrice, type VendorState, type Vouchers, createStorefront, useActivationRequest, useAuth, useBundle, useBundles, useCart, useCartActions, useCartOffer, useCatalog, useCheckout, useCommunicationPreferences, useCurrency, useEligibleOffers, useGroups, useInventory, useLockedOffers, useOffer, useOffers, useOrders, usePrice, useProduct, useProducts, usePromotions, useReviews, useStorefront, useStorefrontEvent, useStorefrontState, useVendor, useVoucher };
|
|
813
|
+
export { type ActivationRequestOptions, type ActivationRequestState, type AddToCartOptions, type AttributionConsentStatus, type Auth, type Cart, type CartCheckoutOptions, type CartItem, type CartOfferState, type CheckoutItem, type CheckoutOptions, type CheckoutRedirectOptions, type CheckoutResult, type Communications, type Groups, type LockedOffer, MoonbaseStorefront, type Orders, type ProductReviews, type StorefrontAuth, type StorefrontCart, type StorefrontEvents, type StorefrontInventory, type StorefrontOptions, StorefrontProvider, type StorefrontProviderProps, type StorefrontState, type VariationPrice, type VendorState, type Vouchers, createStorefront, getStorefront, useActivationRequest, useAuth, useBundle, useBundles, useCart, useCartActions, useCartOffer, useCatalog, useCheckout, useCommunicationPreferences, useCurrency, useEligibleOffers, useGroups, useInventory, useLockedOffers, useOffer, useOffers, useOrders, usePrice, useProduct, useProducts, usePromotions, useReviews, useStorefront, useStorefrontEvent, useStorefrontState, useVendor, useVoucher };
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { MoonbaseClient } from "@moonbase.sh/storefront-api";
|
|
3
3
|
|
|
4
4
|
// package.json
|
|
5
|
-
var version = "0.0.0-next-
|
|
5
|
+
var version = "0.0.0-next-20261111171533";
|
|
6
6
|
|
|
7
7
|
// src/storefront.ts
|
|
8
8
|
import {
|
|
@@ -41,12 +41,27 @@ import {
|
|
|
41
41
|
|
|
42
42
|
// src/auth.ts
|
|
43
43
|
import { forgetPurchase, schemas } from "@moonbase.sh/storefront-api";
|
|
44
|
+
var confirmationReuse = 5e3;
|
|
44
45
|
function createAuth(storefront, internals) {
|
|
45
46
|
const { setUser } = internals;
|
|
46
47
|
const signedIn = () => storefront.getState().user !== null;
|
|
47
48
|
const refreshCatalog = () => {
|
|
48
49
|
storefront.refreshCatalog().catch((err) => console.error("Could not load the Moonbase catalog", err));
|
|
49
50
|
};
|
|
51
|
+
const confirmations = /* @__PURE__ */ new Map();
|
|
52
|
+
const confirmOnce = (kind, email, code, confirm) => {
|
|
53
|
+
const key = JSON.stringify([kind, email, code]);
|
|
54
|
+
const pending = confirmations.get(key);
|
|
55
|
+
if (pending)
|
|
56
|
+
return pending;
|
|
57
|
+
const result = confirm();
|
|
58
|
+
confirmations.set(key, result);
|
|
59
|
+
const forget = () => {
|
|
60
|
+
setTimeout(() => confirmations.delete(key), confirmationReuse);
|
|
61
|
+
};
|
|
62
|
+
result.then(forget, forget);
|
|
63
|
+
return result;
|
|
64
|
+
};
|
|
50
65
|
return {
|
|
51
66
|
signIn: async (email, password) => {
|
|
52
67
|
const user = await storefront.client.identity.signIn(email, password);
|
|
@@ -101,19 +116,19 @@ function createAuth(storefront, internals) {
|
|
|
101
116
|
setPassword: (currentPassword, newPassword) => storefront.client.identity.setPassword(currentPassword, newPassword),
|
|
102
117
|
forgotPassword: (email) => storefront.client.identity.forgotPassword(email),
|
|
103
118
|
resetPassword: (email, newPassword, code) => storefront.client.identity.resetPassword(email, newPassword, code),
|
|
104
|
-
confirmAccount:
|
|
119
|
+
confirmAccount: (email, code) => confirmOnce("account", email, code, async () => {
|
|
105
120
|
const result = await storefront.client.identity.confirmAccount(email, code);
|
|
106
121
|
if (result.status === "SignedIn") {
|
|
107
122
|
setUser(schemas.identity.userSchema.parse(storefront.client.tokenStore.user));
|
|
108
123
|
refreshCatalog();
|
|
109
124
|
}
|
|
110
125
|
return result;
|
|
111
|
-
},
|
|
112
|
-
confirmEmail: (email, code) => storefront.client.identity.confirmEmail(email, code),
|
|
113
|
-
confirmEmailChange:
|
|
126
|
+
}),
|
|
127
|
+
confirmEmail: (email, code) => confirmOnce("email", email, code, () => storefront.client.identity.confirmEmail(email, code)),
|
|
128
|
+
confirmEmailChange: (email, code) => confirmOnce("email-change", email, code, async () => {
|
|
114
129
|
await storefront.client.identity.confirmEmailChange(email, code);
|
|
115
130
|
return await storefront.refreshUser();
|
|
116
|
-
},
|
|
131
|
+
}),
|
|
117
132
|
getConnectionUrl: (provider, redirectUri, loginId) => storefront.client.identity.getConnectionUrl(provider, redirectUri, loginId),
|
|
118
133
|
disconnectAccount: async (provider) => {
|
|
119
134
|
await storefront.client.identity.disconnectAccount(provider);
|
|
@@ -611,6 +626,10 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
611
626
|
this.client = client;
|
|
612
627
|
this.listeners = /* @__PURE__ */ new Set();
|
|
613
628
|
this.refreshOrderAbortController = new AbortController();
|
|
629
|
+
/** Aborted by `dispose`, which takes the storefront's window listeners with it. */
|
|
630
|
+
this.lifetime = new AbortController();
|
|
631
|
+
/** Whether the storefront took the hosted checkout's parameters off the address as it was made. */
|
|
632
|
+
this.tookCheckoutReturn = false;
|
|
614
633
|
// Catalog refreshes are numbered as they start, and one only lands if no later one has landed first.
|
|
615
634
|
// They overlap: a checkout's billing details and its completion each start one a moment apart, and
|
|
616
635
|
// when the first to start is the last to answer, its catalog is from before the purchase and would
|
|
@@ -640,6 +659,7 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
640
659
|
this.cart = createCart(this, { setOrder: (order2) => this.setState({ order: order2 }) });
|
|
641
660
|
const initialCatalog = options.initialCatalog ? _MoonbaseStorefront.normalizeCatalog(options.initialCatalog) : emptyCatalog();
|
|
642
661
|
this.serverState = {
|
|
662
|
+
attributionConsentRequired: void 0,
|
|
643
663
|
attributionConsentStatus: "unknown",
|
|
644
664
|
catalog: initialCatalog,
|
|
645
665
|
catalogLoaded: !!options.initialCatalog,
|
|
@@ -656,8 +676,12 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
656
676
|
this.resolveUserLoaded();
|
|
657
677
|
return;
|
|
658
678
|
}
|
|
659
|
-
|
|
660
|
-
|
|
679
|
+
const { signal } = this.lifetime;
|
|
680
|
+
window.addEventListener("storage", (event) => this.handleStorageUpdate(event), { signal });
|
|
681
|
+
this.client.tokenStore.onSessionEnded(() => {
|
|
682
|
+
if (!this.disposed)
|
|
683
|
+
this.endSession();
|
|
684
|
+
});
|
|
661
685
|
const urlParams = new URLSearchParams(window.location.search);
|
|
662
686
|
const fresh = {
|
|
663
687
|
referrer: parseOffSiteReferrer(window.document.referrer, window.location.origin),
|
|
@@ -720,6 +744,7 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
720
744
|
}
|
|
721
745
|
}
|
|
722
746
|
this.state = {
|
|
747
|
+
attributionConsentRequired: void 0,
|
|
723
748
|
attributionConsentStatus: this.consentStatus(),
|
|
724
749
|
catalog,
|
|
725
750
|
catalogLoaded: !!cachedCatalog || this.serverState.catalogLoaded,
|
|
@@ -753,21 +778,22 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
753
778
|
else
|
|
754
779
|
mountSubscription(finalEndpoint.toString());
|
|
755
780
|
window.history.replaceState(window.history.state, "", withoutHandshakeParams2(window.location.href));
|
|
781
|
+
this.tookCheckoutReturn = true;
|
|
756
782
|
}
|
|
757
783
|
window.addEventListener("moonbase-checkout-billing-details-updated", () => {
|
|
758
784
|
this.refreshInBackground();
|
|
759
|
-
});
|
|
785
|
+
}, { signal });
|
|
760
786
|
window.addEventListener("moonbase-checkout-completed", (event) => {
|
|
761
787
|
const completed = event.detail.order;
|
|
762
788
|
if (completed.id === this.state.order.id)
|
|
763
789
|
this.resetOrder();
|
|
764
790
|
forgetPurchase3(completed.id);
|
|
765
791
|
this.refreshInBackground();
|
|
766
|
-
});
|
|
792
|
+
}, { signal });
|
|
767
793
|
}
|
|
768
794
|
/**
|
|
769
795
|
* Calls `callback` each time the storefront reports `event`, and returns the function that stops it.
|
|
770
|
-
* In a component, `useStorefrontEvent` does the subscribing and the cleaning up.
|
|
796
|
+
* `dispose` stops it too. In a component, `useStorefrontEvent` does the subscribing and the cleaning up.
|
|
771
797
|
*/
|
|
772
798
|
on(event, callback) {
|
|
773
799
|
if (typeof window === "undefined")
|
|
@@ -775,9 +801,50 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
775
801
|
};
|
|
776
802
|
const [name, read] = windowEvents[event];
|
|
777
803
|
const listener = (e) => callback(...read(e.detail));
|
|
778
|
-
window.addEventListener(name, listener);
|
|
804
|
+
window.addEventListener(name, listener, { signal: this.lifetime.signal });
|
|
779
805
|
return () => window.removeEventListener(name, listener);
|
|
780
806
|
}
|
|
807
|
+
/** Whether `dispose` has stopped the storefront. */
|
|
808
|
+
get disposed() {
|
|
809
|
+
return this.lifetime.signal.aborted;
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* Stops the storefront, for a test or for a page that swaps it for another: it stops following other
|
|
813
|
+
* tabs, the checkout and the customer's session, stops calling what `on` subscribed, stops renewing
|
|
814
|
+
* their sign-in, and ignores what requests still in flight bring back. A cart change still waiting to
|
|
815
|
+
* be sent goes at once. What it stored in the browser stays, for the next storefront to pick up.
|
|
816
|
+
* `getStorefront` makes a new one after this.
|
|
817
|
+
*/
|
|
818
|
+
dispose() {
|
|
819
|
+
var _a;
|
|
820
|
+
if (this.disposed)
|
|
821
|
+
return;
|
|
822
|
+
this.lifetime.abort();
|
|
823
|
+
this.refreshOrderAbortController.abort();
|
|
824
|
+
clearTimeout(this.pushTimeout);
|
|
825
|
+
(_a = this.pendingPush) == null ? void 0 : _a.call(this);
|
|
826
|
+
this.client.tokenStore.dispose();
|
|
827
|
+
this.listeners.clear();
|
|
828
|
+
}
|
|
829
|
+
/**
|
|
830
|
+
* Takes the hosted checkout's parameters off the address again, when the storefront took them off as
|
|
831
|
+
* it was made and a router has since put them back, and has the router read the address again.
|
|
832
|
+
* `<StorefrontProvider>` calls it once the page has hydrated, which is all a page needs.
|
|
833
|
+
*
|
|
834
|
+
* Next.js's router is why: it reads the address before any of the page's own code runs, and writes it
|
|
835
|
+
* back as the page hydrates. It is told with a `popstate`, as for Back, since it ignores an address
|
|
836
|
+
* changed under the history entry it wrote, and `useSearchParams()` would go on listing the parameters.
|
|
837
|
+
*/
|
|
838
|
+
clearCheckoutReturn() {
|
|
839
|
+
if (!this.tookCheckoutReturn || this.disposed || typeof window === "undefined")
|
|
840
|
+
return;
|
|
841
|
+
this.tookCheckoutReturn = false;
|
|
842
|
+
const address = withoutHandshakeParams2(window.location.href);
|
|
843
|
+
if (address === window.location.href)
|
|
844
|
+
return;
|
|
845
|
+
window.history.replaceState(window.history.state, "", address);
|
|
846
|
+
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
|
|
847
|
+
}
|
|
781
848
|
get hasUtm() {
|
|
782
849
|
const utm = this.state.utm;
|
|
783
850
|
return !!utm && !!(utm.source || utm.medium || utm.campaign || utm.term || utm.content || utm.id || utm.gadSource || utm.gadCampaignId);
|
|
@@ -872,10 +939,11 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
872
939
|
} catch (err) {
|
|
873
940
|
if (!(err instanceof StoreClosedError))
|
|
874
941
|
throw err;
|
|
875
|
-
this.
|
|
942
|
+
if (!this.disposed)
|
|
943
|
+
this.closeStore();
|
|
876
944
|
return this.state.catalog;
|
|
877
945
|
}
|
|
878
|
-
if (refresh < this.catalogRefreshLanded || !latest)
|
|
946
|
+
if (refresh < this.catalogRefreshLanded || !latest || this.disposed)
|
|
879
947
|
return this.state.catalog;
|
|
880
948
|
this.catalogRefreshLanded = refresh;
|
|
881
949
|
writeStorage(_MoonbaseStorefront.storefrontKey, JSON.stringify(latest));
|
|
@@ -890,8 +958,10 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
890
958
|
this.storeAllowsAttribution = latest.cookieConsentRequired === false;
|
|
891
959
|
this.attributionConsentChanged(consentedBefore);
|
|
892
960
|
this.setState({ attributionConsentStatus: this.consentStatus() });
|
|
893
|
-
if (typeof window !== "undefined")
|
|
961
|
+
if (typeof window !== "undefined") {
|
|
962
|
+
this.setState({ attributionConsentRequired: latest.cookieConsentRequired !== false });
|
|
894
963
|
window.dispatchEvent(new CustomEvent("moonbase-storefront-updated", { detail: { storefront: latest } }));
|
|
964
|
+
}
|
|
895
965
|
return latest;
|
|
896
966
|
}
|
|
897
967
|
/**
|
|
@@ -904,11 +974,15 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
904
974
|
this.refreshOrderAbortController = new AbortController();
|
|
905
975
|
const pushed = this.state.order;
|
|
906
976
|
clearTimeout(this.pushTimeout);
|
|
907
|
-
|
|
977
|
+
const push = () => {
|
|
978
|
+
this.pushTimeout = void 0;
|
|
979
|
+
this.pendingPush = void 0;
|
|
908
980
|
const latest = this.state.order;
|
|
909
981
|
const order = latest.id === pushed.id ? latest : pushed;
|
|
910
982
|
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));
|
|
911
|
-
}
|
|
983
|
+
};
|
|
984
|
+
this.pendingPush = push;
|
|
985
|
+
this.pushTimeout = setTimeout(push, 500);
|
|
912
986
|
}
|
|
913
987
|
/**
|
|
914
988
|
* Starts a new, empty cart, or with `keepItems` a new cart holding the same lines, under a new ID.
|
|
@@ -965,7 +1039,7 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
965
1039
|
}
|
|
966
1040
|
setState(patch) {
|
|
967
1041
|
const keys = Object.keys(patch);
|
|
968
|
-
if (keys.every((key) => Object.is(this.state[key], patch[key])))
|
|
1042
|
+
if (this.disposed || keys.every((key) => Object.is(this.state[key], patch[key])))
|
|
969
1043
|
return;
|
|
970
1044
|
const before = this.state;
|
|
971
1045
|
this.state = { ...this.state, ...patch };
|
|
@@ -1144,7 +1218,7 @@ var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
|
1144
1218
|
const refreshingId = this.state.order.id;
|
|
1145
1219
|
try {
|
|
1146
1220
|
const latest = await this.client.orders.get(refreshingId, { abort: this.refreshOrderAbortController.signal });
|
|
1147
|
-
if (this.state.order.id !== refreshingId || !latest)
|
|
1221
|
+
if (this.state.order.id !== refreshingId || !latest || this.disposed)
|
|
1148
1222
|
return;
|
|
1149
1223
|
if (latest.status !== OrderStatus3.Open) {
|
|
1150
1224
|
this.resetOrder();
|
|
@@ -1214,6 +1288,10 @@ var MoonbaseStorefront = _MoonbaseStorefront;
|
|
|
1214
1288
|
import { createContext, createElement, useContext, useEffect, useRef, useSyncExternalStore } from "react";
|
|
1215
1289
|
var StorefrontContext = createContext(null);
|
|
1216
1290
|
function StorefrontProvider({ storefront, children }) {
|
|
1291
|
+
useEffect(() => {
|
|
1292
|
+
const timeout = setTimeout(() => storefront.clearCheckoutReturn());
|
|
1293
|
+
return () => clearTimeout(timeout);
|
|
1294
|
+
}, [storefront]);
|
|
1217
1295
|
return createElement(StorefrontContext.Provider, { value: storefront }, children);
|
|
1218
1296
|
}
|
|
1219
1297
|
function useStorefront() {
|
|
@@ -1338,14 +1416,17 @@ function useCartOffer() {
|
|
|
1338
1416
|
|
|
1339
1417
|
// src/hooks/useActivationRequest.ts
|
|
1340
1418
|
import { ActivationRequestStatus, NotAuthenticatedError as NotAuthenticatedError2 } from "@moonbase.sh/storefront-api";
|
|
1341
|
-
import { useCallback, useEffect as useEffect2, useState } from "react";
|
|
1419
|
+
import { useCallback, useEffect as useEffect2, useRef as useRef2, useState } from "react";
|
|
1342
1420
|
var pollInterval = 1500;
|
|
1343
|
-
function
|
|
1344
|
-
|
|
1421
|
+
function errorMessage(err) {
|
|
1422
|
+
return err instanceof NotAuthenticatedError2 ? "You need to be signed in to do this" : err.message;
|
|
1423
|
+
}
|
|
1424
|
+
function useActivationRequest(token, options = {}) {
|
|
1425
|
+
var _a, _b, _c;
|
|
1345
1426
|
const storefront = useStorefront();
|
|
1346
1427
|
const userId = useStorefrontState((state) => {
|
|
1347
|
-
var _a2,
|
|
1348
|
-
return (
|
|
1428
|
+
var _a2, _b2;
|
|
1429
|
+
return (_b2 = (_a2 = state.user) == null ? void 0 : _a2.id) != null ? _b2 : null;
|
|
1349
1430
|
});
|
|
1350
1431
|
const [activationRequest, setActivationRequest] = useState(null);
|
|
1351
1432
|
const [fetched, setFetched] = useState(null);
|
|
@@ -1398,6 +1479,7 @@ function useActivationRequest(token) {
|
|
|
1398
1479
|
const fulfillLicense = useCallback(async () => {
|
|
1399
1480
|
if (!requestId)
|
|
1400
1481
|
return;
|
|
1482
|
+
setError(null);
|
|
1401
1483
|
setFulfilling(true);
|
|
1402
1484
|
try {
|
|
1403
1485
|
adopt(await storefront.client.activationRequests.fulfillLicense(requestId));
|
|
@@ -1409,6 +1491,7 @@ function useActivationRequest(token) {
|
|
|
1409
1491
|
const fulfillTrial = useCallback(async (newsletterOptIn = false) => {
|
|
1410
1492
|
if (!requestId)
|
|
1411
1493
|
return;
|
|
1494
|
+
setError(null);
|
|
1412
1495
|
setFulfilling(true);
|
|
1413
1496
|
try {
|
|
1414
1497
|
const user = storefront.getState().user;
|
|
@@ -1423,11 +1506,23 @@ function useActivationRequest(token) {
|
|
|
1423
1506
|
setCompleting(true);
|
|
1424
1507
|
} catch (err) {
|
|
1425
1508
|
console.warn("Could not fulfill trial: ", err);
|
|
1426
|
-
setError(err
|
|
1509
|
+
setError(errorMessage(err));
|
|
1427
1510
|
} finally {
|
|
1428
1511
|
setFulfilling(false);
|
|
1429
1512
|
}
|
|
1430
1513
|
}, [storefront, requestId, adopt]);
|
|
1514
|
+
const autoFulfill = (_b = options.autoFulfill) != null ? _b : false;
|
|
1515
|
+
const autoFulfilled = useRef2(null);
|
|
1516
|
+
const eligible = (activationRequest == null ? void 0 : activationRequest.status) === ActivationRequestStatus.Requested && !!((_c = activationRequest.licenseEligibility) == null ? void 0 : _c.eligible);
|
|
1517
|
+
useEffect2(() => {
|
|
1518
|
+
if (!autoFulfill || !eligible || !requestId || autoFulfilled.current === requestId)
|
|
1519
|
+
return;
|
|
1520
|
+
autoFulfilled.current = requestId;
|
|
1521
|
+
fulfillLicense().catch((err) => {
|
|
1522
|
+
console.warn("Could not activate with the customer's license: ", err);
|
|
1523
|
+
setError(errorMessage(err));
|
|
1524
|
+
});
|
|
1525
|
+
}, [autoFulfill, eligible, requestId, fulfillLicense]);
|
|
1431
1526
|
const cancel = useCallback(async () => {
|
|
1432
1527
|
if (!activationRequest || activationRequest.status === ActivationRequestStatus.Cancelled)
|
|
1433
1528
|
return;
|
|
@@ -1691,10 +1786,22 @@ function createStorefront(endpoint, options = {}) {
|
|
|
1691
1786
|
};
|
|
1692
1787
|
return new MoonbaseStorefront(configuration, new MoonbaseClient(configuration), { initialCatalog, autoApplyItemOffers });
|
|
1693
1788
|
}
|
|
1789
|
+
var browserStorefronts = /* @__PURE__ */ new Map();
|
|
1790
|
+
function getStorefront(endpoint, options = {}) {
|
|
1791
|
+
if (typeof window === "undefined")
|
|
1792
|
+
return createStorefront(endpoint, options);
|
|
1793
|
+
let storefront = browserStorefronts.get(endpoint);
|
|
1794
|
+
if (!storefront || storefront.disposed) {
|
|
1795
|
+
storefront = createStorefront(endpoint, options);
|
|
1796
|
+
browserStorefronts.set(endpoint, storefront);
|
|
1797
|
+
}
|
|
1798
|
+
return storefront;
|
|
1799
|
+
}
|
|
1694
1800
|
export {
|
|
1695
1801
|
MoonbaseStorefront,
|
|
1696
1802
|
StorefrontProvider,
|
|
1697
1803
|
createStorefront,
|
|
1804
|
+
getStorefront,
|
|
1698
1805
|
useActivationRequest,
|
|
1699
1806
|
useAuth,
|
|
1700
1807
|
useBundle,
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@moonbase.sh/react",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.0.0-next-
|
|
4
|
+
"version": "0.0.0-next-20261111171533",
|
|
5
5
|
"description": "Package to let you build React storefronts with Moonbase.sh as payment and delivery provider",
|
|
6
6
|
"author": "Tobias Lønnerød Madsen <m@dsen.tv>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"react": ">=18"
|
|
17
17
|
},
|
|
18
18
|
"dependencies": {
|
|
19
|
-
"@moonbase.sh/storefront-api": "0.0.0-next-
|
|
19
|
+
"@moonbase.sh/storefront-api": "0.0.0-next-20261111171533"
|
|
20
20
|
},
|
|
21
21
|
"devDependencies": {
|
|
22
22
|
"@types/node": "^22.5.4",
|