@moonbase.sh/react 0.0.0-stage → 1.1.0
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 +246 -2
- package/dist/index.cjs +1623 -0
- package/dist/index.d.cts +670 -0
- package/dist/index.d.ts +670 -0
- package/dist/index.js +1631 -0
- package/package.json +44 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1623 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
|
19
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
+
|
|
21
|
+
// src/index.ts
|
|
22
|
+
var index_exports = {};
|
|
23
|
+
__export(index_exports, {
|
|
24
|
+
MoonbaseStorefront: () => MoonbaseStorefront,
|
|
25
|
+
StorefrontProvider: () => StorefrontProvider,
|
|
26
|
+
createStorefront: () => createStorefront,
|
|
27
|
+
useActivationRequest: () => useActivationRequest,
|
|
28
|
+
useAuth: () => useAuth,
|
|
29
|
+
useBundle: () => useBundle,
|
|
30
|
+
useBundles: () => useBundles,
|
|
31
|
+
useCart: () => useCart,
|
|
32
|
+
useCartOffer: () => useCartOffer,
|
|
33
|
+
useCatalog: () => useCatalog,
|
|
34
|
+
useCheckout: () => useCheckout,
|
|
35
|
+
useCommunicationPreferences: () => useCommunicationPreferences,
|
|
36
|
+
useEligibleOffers: () => useEligibleOffers,
|
|
37
|
+
useGroups: () => useGroups,
|
|
38
|
+
useInventory: () => useInventory,
|
|
39
|
+
useLockedOffers: () => useLockedOffers,
|
|
40
|
+
useOffer: () => useOffer,
|
|
41
|
+
useOffers: () => useOffers,
|
|
42
|
+
useOrders: () => useOrders,
|
|
43
|
+
useProduct: () => useProduct,
|
|
44
|
+
useProducts: () => useProducts,
|
|
45
|
+
usePromotions: () => usePromotions,
|
|
46
|
+
useReviews: () => useReviews,
|
|
47
|
+
useStorefront: () => useStorefront,
|
|
48
|
+
useStorefrontEvent: () => useStorefrontEvent,
|
|
49
|
+
useStorefrontState: () => useStorefrontState,
|
|
50
|
+
useVendor: () => useVendor,
|
|
51
|
+
useVoucher: () => useVoucher
|
|
52
|
+
});
|
|
53
|
+
module.exports = __toCommonJS(index_exports);
|
|
54
|
+
var import_storefront_api11 = require("@moonbase.sh/storefront-api");
|
|
55
|
+
|
|
56
|
+
// package.json
|
|
57
|
+
var version = "1.1.0";
|
|
58
|
+
|
|
59
|
+
// src/storefront.ts
|
|
60
|
+
var import_storefront_api5 = require("@moonbase.sh/storefront-api");
|
|
61
|
+
|
|
62
|
+
// src/auth.ts
|
|
63
|
+
var import_storefront_api = require("@moonbase.sh/storefront-api");
|
|
64
|
+
function createAuth(storefront, internals) {
|
|
65
|
+
const { setUser } = internals;
|
|
66
|
+
const signedIn = () => storefront.getState().user !== null;
|
|
67
|
+
const refreshCatalog = () => {
|
|
68
|
+
storefront.refreshCatalog().catch((err) => console.error("Could not load the Moonbase catalog", err));
|
|
69
|
+
};
|
|
70
|
+
return {
|
|
71
|
+
signIn: async (email, password) => {
|
|
72
|
+
const user = await storefront.client.identity.signIn(email, password);
|
|
73
|
+
setUser(user);
|
|
74
|
+
refreshCatalog();
|
|
75
|
+
return user;
|
|
76
|
+
},
|
|
77
|
+
signUp: async (name, email, password, address, acceptedPrivacyPolicy, acceptedTermsAndConditions, communicationOptIn, options) => {
|
|
78
|
+
var _a, _b;
|
|
79
|
+
const result = await storefront.client.identity.signUp(
|
|
80
|
+
name,
|
|
81
|
+
email,
|
|
82
|
+
password,
|
|
83
|
+
address,
|
|
84
|
+
acceptedPrivacyPolicy,
|
|
85
|
+
acceptedTermsAndConditions,
|
|
86
|
+
communicationOptIn,
|
|
87
|
+
{
|
|
88
|
+
...options,
|
|
89
|
+
// The tags the visitor arrived with, as orders carry them, unless the caller names its own.
|
|
90
|
+
utm: (_a = options == null ? void 0 : options.utm) != null ? _a : storefront.hasUtmOrReferrer ? storefront.getState().utm : void 0,
|
|
91
|
+
signals: (_b = options == null ? void 0 : options.signals) != null ? _b : storefront.adSignals()
|
|
92
|
+
}
|
|
93
|
+
);
|
|
94
|
+
if (result.status === "signed-in") {
|
|
95
|
+
setUser(result.user);
|
|
96
|
+
refreshCatalog();
|
|
97
|
+
}
|
|
98
|
+
return result;
|
|
99
|
+
},
|
|
100
|
+
signOut: async () => {
|
|
101
|
+
const revoked = storefront.client.identity.signOut();
|
|
102
|
+
setUser(null);
|
|
103
|
+
storefront.resetOrder({ keepItems: true });
|
|
104
|
+
(0, import_storefront_api.forgetPurchase)();
|
|
105
|
+
await storefront.refreshCatalog();
|
|
106
|
+
await revoked;
|
|
107
|
+
},
|
|
108
|
+
getAccessToken: () => storefront.client.tokenStore.getAccessToken(),
|
|
109
|
+
update: async (name, email, emailConfirmationToken, communicationPreferences) => {
|
|
110
|
+
const result = await storefront.client.identity.update(name, email, emailConfirmationToken, communicationPreferences);
|
|
111
|
+
if (signedIn())
|
|
112
|
+
setUser(result.user);
|
|
113
|
+
return result;
|
|
114
|
+
},
|
|
115
|
+
updateAddress: async (address) => {
|
|
116
|
+
const user = await storefront.client.identity.updateAddress(address);
|
|
117
|
+
if (signedIn())
|
|
118
|
+
setUser(user);
|
|
119
|
+
return user;
|
|
120
|
+
},
|
|
121
|
+
setPassword: (currentPassword, newPassword) => storefront.client.identity.setPassword(currentPassword, newPassword),
|
|
122
|
+
forgotPassword: (email) => storefront.client.identity.forgotPassword(email),
|
|
123
|
+
resetPassword: (email, newPassword, code) => storefront.client.identity.resetPassword(email, newPassword, code),
|
|
124
|
+
confirmAccount: async (email, code) => {
|
|
125
|
+
const result = await storefront.client.identity.confirmAccount(email, code);
|
|
126
|
+
if (result.status === "SignedIn") {
|
|
127
|
+
setUser(import_storefront_api.schemas.identity.userSchema.parse(storefront.client.tokenStore.user));
|
|
128
|
+
refreshCatalog();
|
|
129
|
+
}
|
|
130
|
+
return result;
|
|
131
|
+
},
|
|
132
|
+
confirmEmail: (email, code) => storefront.client.identity.confirmEmail(email, code),
|
|
133
|
+
confirmEmailChange: async (email, code) => {
|
|
134
|
+
await storefront.client.identity.confirmEmailChange(email, code);
|
|
135
|
+
return await storefront.refreshUser();
|
|
136
|
+
},
|
|
137
|
+
getConnectionUrl: (provider, redirectUri, loginId) => storefront.client.identity.getConnectionUrl(provider, redirectUri, loginId),
|
|
138
|
+
disconnectAccount: async (provider) => {
|
|
139
|
+
await storefront.client.identity.disconnectAccount(provider);
|
|
140
|
+
return await storefront.refreshUser();
|
|
141
|
+
},
|
|
142
|
+
refreshUser: () => storefront.refreshUser()
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// src/cart.ts
|
|
147
|
+
var import_storefront_api4 = require("@moonbase.sh/storefront-api");
|
|
148
|
+
|
|
149
|
+
// src/checkout.ts
|
|
150
|
+
var import_storefront_api2 = require("@moonbase.sh/storefront-api");
|
|
151
|
+
var import_uuid = require("uuid");
|
|
152
|
+
var wrapperId = "moonbase-checkout-wrapper";
|
|
153
|
+
function checkoutInProgress() {
|
|
154
|
+
return typeof window !== "undefined" && !!document.getElementById(wrapperId);
|
|
155
|
+
}
|
|
156
|
+
function waitForCheckoutClose(onClose) {
|
|
157
|
+
return new Promise((resolve) => window.addEventListener("moonbase-checkout-closed", (event) => {
|
|
158
|
+
onClose == null ? void 0 : onClose();
|
|
159
|
+
const { detail } = event;
|
|
160
|
+
resolve({ next: detail.intent, completed: detail.completed, redirected: false });
|
|
161
|
+
}, { once: true }));
|
|
162
|
+
}
|
|
163
|
+
function checkoutReturnUrl(returnUrl) {
|
|
164
|
+
return (0, import_storefront_api2.withoutHandshakeParams)(new URL(returnUrl != null ? returnUrl : (0, import_storefront_api2.currentPageUrl)(), document.baseURI).href);
|
|
165
|
+
}
|
|
166
|
+
function lineQuantity(quantity) {
|
|
167
|
+
const parsed = Math.trunc(Number(quantity));
|
|
168
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : 1;
|
|
169
|
+
}
|
|
170
|
+
async function checkout(storefront, items, options = {}) {
|
|
171
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
|
|
172
|
+
if (checkoutInProgress())
|
|
173
|
+
return waitForCheckoutClose();
|
|
174
|
+
const redirect = (0, import_storefront_api2.resolveRedirect)(options.redirect);
|
|
175
|
+
const lines = [];
|
|
176
|
+
for (const { item, ...line } of items) {
|
|
177
|
+
const licenseId = item.type === "Product" ? (0, import_storefront_api2.targetLicenseId)(line.targetLicenseId) : void 0;
|
|
178
|
+
const variation = item.type === "Product" && licenseId ? (0, import_storefront_api2.upgradeVariation)(item, licenseId, line.variation) : (_a = line.variation) != null ? _a : item.defaultVariation;
|
|
179
|
+
if (!variation)
|
|
180
|
+
throw new Error("Added item does not have a default variation, and none have been specified");
|
|
181
|
+
const quantity = licenseId ? 1 : lineQuantity(line.quantity);
|
|
182
|
+
const id = (0, import_storefront_api2.lineItemId)(item.type, item.id, variation.id, licenseId);
|
|
183
|
+
if (licenseId && lines.some((l) => l.type === "Product" && l.targetLicenseId === licenseId))
|
|
184
|
+
continue;
|
|
185
|
+
if (item.type === "Bundle") {
|
|
186
|
+
lines.push({
|
|
187
|
+
id,
|
|
188
|
+
type: "Bundle",
|
|
189
|
+
bundleId: item.id,
|
|
190
|
+
bundle: item,
|
|
191
|
+
quantity,
|
|
192
|
+
variation,
|
|
193
|
+
variationId: variation.id,
|
|
194
|
+
price: variation.price,
|
|
195
|
+
appliedDiscount: variation.discount
|
|
196
|
+
});
|
|
197
|
+
} else if (item.type === "Product") {
|
|
198
|
+
lines.push({
|
|
199
|
+
id,
|
|
200
|
+
type: "Product",
|
|
201
|
+
productId: item.id,
|
|
202
|
+
product: item,
|
|
203
|
+
quantity,
|
|
204
|
+
variation,
|
|
205
|
+
variationId: variation.id,
|
|
206
|
+
price: variation.price,
|
|
207
|
+
appliedDiscount: variation.discount,
|
|
208
|
+
...licenseId ? { targetLicenseId: licenseId } : {}
|
|
209
|
+
});
|
|
210
|
+
} else {
|
|
211
|
+
throw new import_storefront_api2.MoonbaseError("Invalid input", `Could not handle item of type '${item.type}'`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
const userId = (_c = (_b = storefront.getState().user) == null ? void 0 : _b.id) != null ? _c : null;
|
|
215
|
+
(0, import_storefront_api2.showCheckoutLoader)();
|
|
216
|
+
try {
|
|
217
|
+
const returnUrl = checkoutReturnUrl(options.returnUrl);
|
|
218
|
+
const pushOrder = (id) => storefront.client.orders.pushContent({
|
|
219
|
+
id,
|
|
220
|
+
currency: storefront.getState().catalog.suggestedCurrency,
|
|
221
|
+
items: lines
|
|
222
|
+
}, {
|
|
223
|
+
// Always sent. A redirected buyer has to come back for the storefront to report the completed
|
|
224
|
+
// checkout.
|
|
225
|
+
returnUrl,
|
|
226
|
+
// Saves minting a checkout login token for a hosted checkout URL that is about to be stripped.
|
|
227
|
+
embedded: !redirect
|
|
228
|
+
}, storefront.hasUtmOrReferrer ? storefront.getState().utm : void 0, storefront.adSignals());
|
|
229
|
+
let resumed = await (0, import_storefront_api2.resumePurchase)(storefront.client, userId, options.couponCode);
|
|
230
|
+
let order;
|
|
231
|
+
try {
|
|
232
|
+
order = await pushOrder((_d = resumed == null ? void 0 : resumed.orderId) != null ? _d : (0, import_uuid.v4)());
|
|
233
|
+
} catch (err) {
|
|
234
|
+
if (!resumed || !(0, import_storefront_api2.isClosedOrderRefusal)(err))
|
|
235
|
+
throw err;
|
|
236
|
+
(0, import_storefront_api2.forgetPurchase)(resumed.orderId);
|
|
237
|
+
resumed = null;
|
|
238
|
+
order = await pushOrder((0, import_uuid.v4)());
|
|
239
|
+
}
|
|
240
|
+
await (0, import_storefront_api2.recordCheckoutGroups)(storefront.client, order.id, options.groupIds);
|
|
241
|
+
let ownCoupon = (_e = resumed == null ? void 0 : resumed.couponCode) != null ? _e : null;
|
|
242
|
+
if (options.couponCode && !(0, import_storefront_api2.hasCoupon)(order, options.couponCode)) {
|
|
243
|
+
try {
|
|
244
|
+
const withCoupon = await storefront.client.orders.addCouponCode(order.id, options.couponCode);
|
|
245
|
+
order = {
|
|
246
|
+
...withCoupon,
|
|
247
|
+
checkoutUrl: (_f = withCoupon.checkoutUrl) != null ? _f : order.checkoutUrl,
|
|
248
|
+
hostedCheckoutUrl: (_g = withCoupon.hostedCheckoutUrl) != null ? _g : order.hostedCheckoutUrl,
|
|
249
|
+
embeddedCheckoutUrl: (_h = withCoupon.embeddedCheckoutUrl) != null ? _h : order.embeddedCheckoutUrl
|
|
250
|
+
};
|
|
251
|
+
ownCoupon = options.couponCode;
|
|
252
|
+
} catch (error) {
|
|
253
|
+
(_i = options.onCouponRejected) == null ? void 0 : _i.call(options, options.couponCode, error);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
(0, import_storefront_api2.rememberPurchase)(order.id, userId, ownCoupon);
|
|
257
|
+
if (!checkoutInProgress())
|
|
258
|
+
return { next: void 0, completed: false, redirected: false };
|
|
259
|
+
order.items = storefront.enrichLineItems(order.items);
|
|
260
|
+
const priced = import_storefront_api2.CartUtils.total(storefront.getState().catalog, order, order.currency);
|
|
261
|
+
window.dispatchEvent(new CustomEvent("moonbase-checkout-initiated", {
|
|
262
|
+
detail: { order, total: { amount: priced.amount, currency: priced.currency } }
|
|
263
|
+
}));
|
|
264
|
+
const hostedUrl = redirect ? (0, import_storefront_api2.buildHostedRedirectUrl)(order, returnUrl) : null;
|
|
265
|
+
if (hostedUrl) {
|
|
266
|
+
window.location.href = hostedUrl;
|
|
267
|
+
return { next: void 0, completed: false, redirected: true };
|
|
268
|
+
}
|
|
269
|
+
if (!order.embeddedCheckoutUrl)
|
|
270
|
+
throw new Error("No checkout URL found");
|
|
271
|
+
const stopWatching = (0, import_storefront_api2.watchForTakeover)(order.id, import_storefront_api2.closeCheckout);
|
|
272
|
+
const closed = waitForCheckoutClose(stopWatching);
|
|
273
|
+
(0, import_storefront_api2.mountCheckout)(order.embeddedCheckoutUrl);
|
|
274
|
+
return await closed;
|
|
275
|
+
} catch (err) {
|
|
276
|
+
(0, import_storefront_api2.hideCheckoutLoader)();
|
|
277
|
+
throw err;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// src/order.ts
|
|
282
|
+
var import_storefront_api3 = require("@moonbase.sh/storefront-api");
|
|
283
|
+
var import_uuid2 = require("uuid");
|
|
284
|
+
function emptyCatalog() {
|
|
285
|
+
return {
|
|
286
|
+
suggestedCurrency: "",
|
|
287
|
+
enabledCurrencies: [],
|
|
288
|
+
bundles: [],
|
|
289
|
+
products: [],
|
|
290
|
+
offers: [],
|
|
291
|
+
promotions: []
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
function newOrder(currency = "", items = []) {
|
|
295
|
+
return {
|
|
296
|
+
id: (0, import_uuid2.v4)(),
|
|
297
|
+
status: import_storefront_api3.OrderStatus.Open,
|
|
298
|
+
currency,
|
|
299
|
+
items,
|
|
300
|
+
couponsApplied: []
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
function conditionContext(catalog, order) {
|
|
304
|
+
return import_storefront_api3.CartUtils.conditionContext(catalog, order, (0, import_storefront_api3.resolveDisplayCurrency)(order, catalog));
|
|
305
|
+
}
|
|
306
|
+
function enrichLineItems(catalog, order, lineItems = order.items) {
|
|
307
|
+
const context = conditionContext(catalog, order);
|
|
308
|
+
return lineItems.map((item) => {
|
|
309
|
+
var _a, _b, _c, _d;
|
|
310
|
+
const offer = (_a = catalog.offers) == null ? void 0 : _a.find((o) => o.id === item.offerId);
|
|
311
|
+
if (item.type === "Product") {
|
|
312
|
+
const product = catalog.products.find((p) => p.id === item.productId);
|
|
313
|
+
let variation2 = import_storefront_api3.CartUtils.productLineVariation(product, item.variationId, item.targetLicenseId);
|
|
314
|
+
if (offer && variation2 && import_storefront_api3.OfferUtils.eligible(offer, context))
|
|
315
|
+
variation2 = import_storefront_api3.OfferUtils.applyToVariation(offer, variation2);
|
|
316
|
+
return {
|
|
317
|
+
...item,
|
|
318
|
+
product,
|
|
319
|
+
variation: variation2,
|
|
320
|
+
price: variation2 == null ? void 0 : variation2.price,
|
|
321
|
+
appliedDiscount: (_b = variation2 == null ? void 0 : variation2.discount) != null ? _b : item.appliedDiscount
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
const bundle = catalog.bundles.find((b) => b.id === item.bundleId);
|
|
325
|
+
let variation = (_c = bundle == null ? void 0 : bundle.variations) == null ? void 0 : _c.find((v) => v.id === item.variationId);
|
|
326
|
+
if (offer && variation && import_storefront_api3.OfferUtils.eligible(offer, context))
|
|
327
|
+
variation = import_storefront_api3.OfferUtils.applyToVariation(offer, variation);
|
|
328
|
+
return {
|
|
329
|
+
...item,
|
|
330
|
+
bundle,
|
|
331
|
+
variation,
|
|
332
|
+
price: variation == null ? void 0 : variation.price,
|
|
333
|
+
appliedDiscount: (_d = variation == null ? void 0 : variation.discount) != null ? _d : item.appliedDiscount
|
|
334
|
+
};
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
function withBestCartOffer(catalog, order) {
|
|
338
|
+
if (order.status !== import_storefront_api3.OrderStatus.Open)
|
|
339
|
+
return order;
|
|
340
|
+
const best = import_storefront_api3.CartUtils.bestCartOffer(catalog, order, (0, import_storefront_api3.resolveDisplayCurrency)(order, catalog));
|
|
341
|
+
if ((best == null ? void 0 : best.id) === order.offerId)
|
|
342
|
+
return order;
|
|
343
|
+
return { ...order, offerId: best == null ? void 0 : best.id };
|
|
344
|
+
}
|
|
345
|
+
function draftOf(order) {
|
|
346
|
+
return { ...order, items: order.items.map((item) => ({ ...item })) };
|
|
347
|
+
}
|
|
348
|
+
function keepUnchangedLines(before, after) {
|
|
349
|
+
return after.map((line) => {
|
|
350
|
+
const previous = before.find((item) => item.id === line.id);
|
|
351
|
+
return previous && shallowEqual(previous, line) ? previous : line;
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
function shallowEqual(a, b) {
|
|
355
|
+
const aKeys = Object.keys(a);
|
|
356
|
+
const bKeys = Object.keys(b);
|
|
357
|
+
return aKeys.length === bKeys.length && aKeys.every((key) => Object.is(a[key], b[key]));
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// src/cart.ts
|
|
361
|
+
function createCart(storefront, internals) {
|
|
362
|
+
function change(edit) {
|
|
363
|
+
const before = storefront.getState().order;
|
|
364
|
+
const draft = draftOf(before);
|
|
365
|
+
edit(draft);
|
|
366
|
+
pruneIneligibleOffers(draft);
|
|
367
|
+
applyEligibleItemOffers(draft);
|
|
368
|
+
const settled = withBestCartOffer(storefront.getState().catalog, draft);
|
|
369
|
+
internals.setOrder({ ...settled, items: keepUnchangedLines(before.items, settled.items) });
|
|
370
|
+
storefront.pushOrderContent();
|
|
371
|
+
}
|
|
372
|
+
function pruneIneligibleOffers(draft) {
|
|
373
|
+
var _a;
|
|
374
|
+
const catalog = storefront.getState().catalog;
|
|
375
|
+
const context = conditionContext(catalog, draft);
|
|
376
|
+
for (const item of draft.items) {
|
|
377
|
+
if (!item.offerId)
|
|
378
|
+
continue;
|
|
379
|
+
const offer = (_a = catalog.offers) == null ? void 0 : _a.find((o) => o.id === item.offerId);
|
|
380
|
+
if (!offer || !import_storefront_api4.OfferUtils.eligible(offer, context))
|
|
381
|
+
item.offerId = void 0;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
function applyEligibleItemOffers(draft) {
|
|
385
|
+
if (!storefront.autoApplyItemOffers || draft.status !== import_storefront_api4.OrderStatus.Open)
|
|
386
|
+
return;
|
|
387
|
+
const catalog = storefront.getState().catalog;
|
|
388
|
+
const context = conditionContext(catalog, draft);
|
|
389
|
+
for (const { itemId, offerId } of import_storefront_api4.CartUtils.assignItemOffers(catalog, draft, (0, import_storefront_api4.resolveDisplayCurrency)(draft, catalog), context)) {
|
|
390
|
+
const item = draft.items.find((i) => i.id === itemId);
|
|
391
|
+
if (item)
|
|
392
|
+
item.offerId = offerId;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
function productLineRecurrence(lineItem) {
|
|
396
|
+
var _a, _b, _c, _d;
|
|
397
|
+
if (lineItem.type !== "Product")
|
|
398
|
+
return void 0;
|
|
399
|
+
return (_d = (_c = lineItem.variation) != null ? _c : (_b = (_a = storefront.getState().catalog.products.find((p) => p.id === lineItem.productId)) == null ? void 0 : _a.variations) == null ? void 0 : _b.find((v) => v.id === lineItem.variationId)) == null ? void 0 : _d.recurrence;
|
|
400
|
+
}
|
|
401
|
+
function addReplacedBundleProducts(draft, cartItem, insertAt) {
|
|
402
|
+
var _a, _b, _c;
|
|
403
|
+
if (cartItem.type !== "Bundle" || !((_a = cartItem.replaced) == null ? void 0 : _a.length))
|
|
404
|
+
return;
|
|
405
|
+
const catalog = storefront.getState().catalog;
|
|
406
|
+
let cursor = insertAt;
|
|
407
|
+
for (const composite of cartItem.replaced) {
|
|
408
|
+
const [productId, variationId] = composite.split("/");
|
|
409
|
+
const product = catalog.products.find((p) => p.id === productId);
|
|
410
|
+
const variation = (_b = product == null ? void 0 : product.variations) == null ? void 0 : _b.find((v) => v.id === variationId);
|
|
411
|
+
const alreadyInCart = draft.items.some((i) => {
|
|
412
|
+
var _a2;
|
|
413
|
+
return i.type === "Product" && i.productId === productId && !i.targetLicenseId && ((_a2 = productLineRecurrence(i)) == null ? void 0 : _a2.type) === (variation == null ? void 0 : variation.recurrence.type);
|
|
414
|
+
});
|
|
415
|
+
if (!product || !variation || alreadyInCart)
|
|
416
|
+
continue;
|
|
417
|
+
const line = {
|
|
418
|
+
id: (0, import_storefront_api4.lineItemId)("Product", product.id, variationId),
|
|
419
|
+
type: "Product",
|
|
420
|
+
productId: product.id,
|
|
421
|
+
product,
|
|
422
|
+
quantity: 1,
|
|
423
|
+
variation,
|
|
424
|
+
variationId,
|
|
425
|
+
price: variation.price,
|
|
426
|
+
appliedDiscount: variation.discount,
|
|
427
|
+
isDefaultVariation: variation.id === ((_c = product.defaultVariation) == null ? void 0 : _c.id)
|
|
428
|
+
};
|
|
429
|
+
if (cursor !== void 0)
|
|
430
|
+
draft.items.splice(cursor++, 0, line);
|
|
431
|
+
else
|
|
432
|
+
draft.items.push(line);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
function addToCart(item, variation, offer, options) {
|
|
436
|
+
const licenseId = item.type === "Product" ? (0, import_storefront_api4.targetLicenseId)(options == null ? void 0 : options.targetLicenseId) : void 0;
|
|
437
|
+
const chosen = item.type === "Product" && licenseId ? (0, import_storefront_api4.upgradeVariation)(item, licenseId, variation) : variation != null ? variation : item.defaultVariation;
|
|
438
|
+
if (!chosen)
|
|
439
|
+
throw new Error("Added item does not have a default variation, and none have been specified");
|
|
440
|
+
const id = (0, import_storefront_api4.lineItemId)(item.type, item.id, chosen.id, licenseId);
|
|
441
|
+
change((draft) => {
|
|
442
|
+
var _a, _b, _c, _d, _e, _f;
|
|
443
|
+
if (licenseId) {
|
|
444
|
+
const index = draft.items.findIndex((i) => {
|
|
445
|
+
var _a2;
|
|
446
|
+
return i.type === "Product" && i.id !== id && ((_a2 = i.targetLicenseId) == null ? void 0 : _a2.toLowerCase()) === licenseId;
|
|
447
|
+
});
|
|
448
|
+
if (index >= 0)
|
|
449
|
+
draft.items.splice(index, 1);
|
|
450
|
+
}
|
|
451
|
+
const existing = draft.items.find((i) => i.id === id);
|
|
452
|
+
if (existing) {
|
|
453
|
+
if (existing.type === "Product" && existing.targetLicenseId)
|
|
454
|
+
existing.quantity = 1;
|
|
455
|
+
else
|
|
456
|
+
existing.quantity += 1;
|
|
457
|
+
(_a = existing.offerId) != null ? _a : existing.offerId = offer == null ? void 0 : offer.id;
|
|
458
|
+
(_b = existing.variation) != null ? _b : existing.variation = chosen;
|
|
459
|
+
if (!existing.price)
|
|
460
|
+
existing.price = chosen.price;
|
|
461
|
+
if (!existing.appliedDiscount && chosen.discount)
|
|
462
|
+
existing.appliedDiscount = chosen.discount;
|
|
463
|
+
if (existing.type === "Product" && item.type === "Product")
|
|
464
|
+
(_c = existing.product) != null ? _c : existing.product = item;
|
|
465
|
+
if (existing.type === "Bundle" && item.type === "Bundle")
|
|
466
|
+
(_d = existing.bundle) != null ? _d : existing.bundle = item;
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
if (item.type === "Bundle") {
|
|
470
|
+
const line = {
|
|
471
|
+
id,
|
|
472
|
+
type: "Bundle",
|
|
473
|
+
bundleId: item.id,
|
|
474
|
+
bundle: item,
|
|
475
|
+
quantity: 1,
|
|
476
|
+
variation: chosen,
|
|
477
|
+
variationId: chosen.id,
|
|
478
|
+
offerId: offer == null ? void 0 : offer.id,
|
|
479
|
+
price: chosen.price,
|
|
480
|
+
appliedDiscount: chosen.discount,
|
|
481
|
+
isDefaultVariation: chosen.id === ((_e = item.defaultVariation) == null ? void 0 : _e.id)
|
|
482
|
+
};
|
|
483
|
+
if ((options == null ? void 0 : options.bundleBehaviour) === "replace") {
|
|
484
|
+
const recurrenceType = chosen.recurrence.type;
|
|
485
|
+
const replaced = draft.items.filter((i) => {
|
|
486
|
+
var _a2;
|
|
487
|
+
return i.type === "Product" && !i.targetLicenseId && item.products.some((p) => p.included && p.id === i.productId) && ((_a2 = productLineRecurrence(i)) == null ? void 0 : _a2.type) === recurrenceType;
|
|
488
|
+
});
|
|
489
|
+
draft.items = draft.items.filter((i) => !replaced.includes(i));
|
|
490
|
+
line.replaced = replaced.flatMap((i) => i.type === "Product" ? [`${i.productId}/${i.variationId}`] : []);
|
|
491
|
+
}
|
|
492
|
+
draft.items.push(line);
|
|
493
|
+
} else if (item.type === "Product") {
|
|
494
|
+
draft.items.push({
|
|
495
|
+
id,
|
|
496
|
+
type: "Product",
|
|
497
|
+
productId: item.id,
|
|
498
|
+
product: item,
|
|
499
|
+
quantity: 1,
|
|
500
|
+
variation: chosen,
|
|
501
|
+
variationId: chosen.id,
|
|
502
|
+
offerId: offer == null ? void 0 : offer.id,
|
|
503
|
+
price: chosen.price,
|
|
504
|
+
appliedDiscount: chosen.discount,
|
|
505
|
+
isDefaultVariation: chosen.id === ((_f = item.defaultVariation) == null ? void 0 : _f.id),
|
|
506
|
+
...licenseId ? { targetLicenseId: licenseId } : {}
|
|
507
|
+
});
|
|
508
|
+
} else {
|
|
509
|
+
throw new import_storefront_api4.MoonbaseError("Invalid input", `Could not handle item of type '${item.type}'`);
|
|
510
|
+
}
|
|
511
|
+
});
|
|
512
|
+
return storefront.getState().order.items.find((i) => i.id === id);
|
|
513
|
+
}
|
|
514
|
+
function setQuantity(cartItem, quantity) {
|
|
515
|
+
var _a;
|
|
516
|
+
if (!storefront.getState().order.items.some((i) => i.id === cartItem.id))
|
|
517
|
+
throw new Error("Cart item not found");
|
|
518
|
+
change((draft) => {
|
|
519
|
+
const index = draft.items.findIndex((i) => i.id === cartItem.id);
|
|
520
|
+
const line = draft.items[index];
|
|
521
|
+
line.quantity = line.type === "Product" && line.targetLicenseId ? Math.min(quantity, 1) : quantity;
|
|
522
|
+
if (line.quantity <= 0) {
|
|
523
|
+
draft.items.splice(index, 1);
|
|
524
|
+
addReplacedBundleProducts(draft, cartItem, index);
|
|
525
|
+
}
|
|
526
|
+
});
|
|
527
|
+
return (_a = storefront.getState().order.items.find((i) => i.id === cartItem.id)) != null ? _a : cartItem;
|
|
528
|
+
}
|
|
529
|
+
function removeFromCart(cartItem) {
|
|
530
|
+
if (!storefront.getState().order.items.some((i) => i.id === cartItem.id))
|
|
531
|
+
return;
|
|
532
|
+
change((draft) => {
|
|
533
|
+
const index = draft.items.findIndex((i) => i.id === cartItem.id);
|
|
534
|
+
draft.items.splice(index, 1);
|
|
535
|
+
addReplacedBundleProducts(draft, cartItem, index);
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
async function checkout2(options = {}) {
|
|
539
|
+
if (checkoutInProgress())
|
|
540
|
+
return waitForCheckoutClose();
|
|
541
|
+
const redirect = (0, import_storefront_api4.resolveRedirect)(options.redirect);
|
|
542
|
+
const returnUrl = checkoutReturnUrl(options.returnUrl);
|
|
543
|
+
storefront.reconcileCartOffer();
|
|
544
|
+
const updatedOrder = await storefront.client.orders.pushContent(storefront.getState().order, {
|
|
545
|
+
// Always sent. A redirected buyer has to come back for the storefront to report the completed
|
|
546
|
+
// checkout and clear the cart.
|
|
547
|
+
returnUrl,
|
|
548
|
+
// Saves minting a checkout login token for a hosted checkout URL that is about to be stripped.
|
|
549
|
+
embedded: !redirect
|
|
550
|
+
}, storefront.hasUtmOrReferrer ? storefront.getState().utm : void 0, storefront.adSignals());
|
|
551
|
+
await (0, import_storefront_api4.recordCheckoutGroups)(storefront.client, updatedOrder.id, options.groupIds);
|
|
552
|
+
updatedOrder.items = storefront.enrichLineItems(updatedOrder.items);
|
|
553
|
+
const { catalog, order } = storefront.getState();
|
|
554
|
+
const breakdown = import_storefront_api4.CartUtils.total(catalog, order, (0, import_storefront_api4.resolveDisplayCurrency)(order, catalog));
|
|
555
|
+
window.dispatchEvent(new CustomEvent("moonbase-checkout-initiated", {
|
|
556
|
+
detail: { order: updatedOrder, total: { amount: breakdown.amount, currency: breakdown.currency } }
|
|
557
|
+
}));
|
|
558
|
+
const hostedUrl = redirect ? (0, import_storefront_api4.buildHostedRedirectUrl)(updatedOrder, returnUrl) : null;
|
|
559
|
+
if (hostedUrl) {
|
|
560
|
+
window.location.href = hostedUrl;
|
|
561
|
+
return { next: void 0, completed: false, redirected: true };
|
|
562
|
+
}
|
|
563
|
+
if (!updatedOrder.embeddedCheckoutUrl)
|
|
564
|
+
throw new Error("No checkout URL found");
|
|
565
|
+
const closed = waitForCheckoutClose();
|
|
566
|
+
(0, import_storefront_api4.mountCheckout)(updatedOrder.embeddedCheckoutUrl);
|
|
567
|
+
return closed;
|
|
568
|
+
}
|
|
569
|
+
return {
|
|
570
|
+
addToCart,
|
|
571
|
+
setQuantity,
|
|
572
|
+
removeFromCart,
|
|
573
|
+
checkout: checkout2,
|
|
574
|
+
removeCartOffer: () => storefront.removeCartOffer()
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// src/storefront.ts
|
|
579
|
+
var windowEvents = {
|
|
580
|
+
checkoutInitiated: ["moonbase-checkout-initiated", (detail) => [detail.order, detail.total]],
|
|
581
|
+
checkoutBillingDetailsAdded: ["moonbase-checkout-billing-details-updated", (detail) => [detail.order]],
|
|
582
|
+
checkoutPaymentStarted: ["moonbase-checkout-payment-started", (detail) => [detail.order]],
|
|
583
|
+
checkoutPaymentFailed: ["moonbase-checkout-payment-failed", (detail) => [detail.order, detail.error]],
|
|
584
|
+
checkoutCouponApplied: ["moonbase-checkout-coupon-applied", (detail) => [detail.order, detail.code]],
|
|
585
|
+
checkoutCouponRemoved: ["moonbase-checkout-coupon-removed", (detail) => [detail.order, detail.code]],
|
|
586
|
+
checkoutCouponRejected: ["moonbase-checkout-coupon-rejected", (detail) => [detail.code, detail.message]],
|
|
587
|
+
checkoutCompleted: ["moonbase-checkout-completed", (detail) => [detail.order]],
|
|
588
|
+
checkoutClosed: ["moonbase-checkout-closed", (detail) => [detail.intent, detail.completed === true, detail.order]],
|
|
589
|
+
catalogUpdated: ["moonbase-storefront-updated", (detail) => [detail.storefront]],
|
|
590
|
+
sessionEnded: ["moonbase-session-ended", (detail) => [detail.user]]
|
|
591
|
+
};
|
|
592
|
+
function hasUtmOrReferrer(utm) {
|
|
593
|
+
return !!utm && Object.values(utm).some((v) => !!v);
|
|
594
|
+
}
|
|
595
|
+
var _MoonbaseStorefront = class _MoonbaseStorefront {
|
|
596
|
+
constructor(configuration, client, options = {}) {
|
|
597
|
+
this.configuration = configuration;
|
|
598
|
+
this.client = client;
|
|
599
|
+
this.listeners = /* @__PURE__ */ new Set();
|
|
600
|
+
this.refreshOrderAbortController = new AbortController();
|
|
601
|
+
// Catalog refreshes are numbered as they start, and one only lands if no later one has landed first.
|
|
602
|
+
// They overlap: a checkout's billing details and its completion each start one a moment apart, and
|
|
603
|
+
// when the first to start is the last to answer, its catalog is from before the purchase and would
|
|
604
|
+
// put `owned` back to `false`.
|
|
605
|
+
this.catalogRefreshesStarted = 0;
|
|
606
|
+
this.catalogRefreshLanded = 0;
|
|
607
|
+
/** The current state. A new object whenever anything in it changes, and the same one otherwise. */
|
|
608
|
+
this.getState = () => this.state;
|
|
609
|
+
/**
|
|
610
|
+
* The state a server renders with, and so what React hydrates against: the initial catalog, if any,
|
|
611
|
+
* an empty cart and nobody signed in. On the server itself, where there is nothing to hydrate, the
|
|
612
|
+
* current state, so a page that awaits `refreshCatalog()` before rendering renders with it.
|
|
613
|
+
*/
|
|
614
|
+
this.getServerState = () => typeof window === "undefined" ? this.state : this.serverState;
|
|
615
|
+
/** Calls `listener` after every change to the state, and returns the function that stops it. */
|
|
616
|
+
this.subscribe = (listener) => {
|
|
617
|
+
this.listeners.add(listener);
|
|
618
|
+
return () => {
|
|
619
|
+
this.listeners.delete(listener);
|
|
620
|
+
};
|
|
621
|
+
};
|
|
622
|
+
var _a;
|
|
623
|
+
this.autoApplyItemOffers = (_a = options.autoApplyItemOffers) != null ? _a : false;
|
|
624
|
+
this.catalogLoadedPromise = new Promise((resolve) => this.resolveCatalogLoaded = resolve);
|
|
625
|
+
this.userLoadedPromise = new Promise((resolve) => this.resolveUserLoaded = resolve);
|
|
626
|
+
this.auth = createAuth(this, { setUser: (user2) => this.setState({ user: user2 }) });
|
|
627
|
+
this.cart = createCart(this, { setOrder: (order2) => this.setState({ order: order2 }) });
|
|
628
|
+
const initialCatalog = options.initialCatalog ? _MoonbaseStorefront.normalizeCatalog(options.initialCatalog) : emptyCatalog();
|
|
629
|
+
this.serverState = {
|
|
630
|
+
catalog: initialCatalog,
|
|
631
|
+
catalogLoaded: !!options.initialCatalog,
|
|
632
|
+
closed: false,
|
|
633
|
+
order: newOrder(initialCatalog.suggestedCurrency),
|
|
634
|
+
user: null,
|
|
635
|
+
userLoaded: false,
|
|
636
|
+
utm: void 0
|
|
637
|
+
};
|
|
638
|
+
if (typeof window === "undefined") {
|
|
639
|
+
this.state = this.serverState;
|
|
640
|
+
if (this.serverState.catalogLoaded)
|
|
641
|
+
this.resolveCatalogLoaded();
|
|
642
|
+
this.resolveUserLoaded();
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
window.addEventListener("storage", (event) => this.handleStorageUpdate(event));
|
|
646
|
+
this.client.tokenStore.onSessionEnded(() => this.endSession());
|
|
647
|
+
const urlParams = new URLSearchParams(window.location.search);
|
|
648
|
+
const fresh = {
|
|
649
|
+
referrer: (0, import_storefront_api5.parseOffSiteReferrer)(window.document.referrer, window.location.origin),
|
|
650
|
+
source: urlParams.get("utm_source") || void 0,
|
|
651
|
+
medium: urlParams.get("utm_medium") || void 0,
|
|
652
|
+
campaign: urlParams.get("utm_campaign") || void 0,
|
|
653
|
+
term: urlParams.get("utm_term") || void 0,
|
|
654
|
+
content: urlParams.get("utm_content") || void 0,
|
|
655
|
+
id: urlParams.get("utm_id") || void 0,
|
|
656
|
+
gadSource: urlParams.get("gad_source") || void 0,
|
|
657
|
+
gadCampaignId: urlParams.get("gad_campaignid") || void 0,
|
|
658
|
+
gclid: urlParams.get("gclid") || void 0,
|
|
659
|
+
gbraid: urlParams.get("gbraid") || void 0,
|
|
660
|
+
wbraid: urlParams.get("wbraid") || void 0,
|
|
661
|
+
fbclid: urlParams.get("fbclid") || void 0,
|
|
662
|
+
msclkid: urlParams.get("msclkid") || void 0,
|
|
663
|
+
ttclid: urlParams.get("ttclid") || void 0
|
|
664
|
+
};
|
|
665
|
+
fresh.adClicks = (0, import_storefront_api5.adClicksOf)(fresh);
|
|
666
|
+
this.attributionConsentSetting = (0, import_storefront_api5.copyConsent)(configuration.attributionConsent);
|
|
667
|
+
const sessionRaw = (0, import_storefront_api5.readStorage)(_MoonbaseStorefront.utmKey, "session");
|
|
668
|
+
const sessionCached = _MoonbaseStorefront.parseCachedUtm(sessionRaw);
|
|
669
|
+
const cached = sessionCached != null ? sessionCached : configuration.persistUtm && this.attributionConsent ? _MoonbaseStorefront.parseCachedUtm((0, import_storefront_api5.readStorage)(_MoonbaseStorefront.utmKey, "local")) : void 0;
|
|
670
|
+
const full = (0, import_storefront_api5.resolveUtm)(cached, fresh);
|
|
671
|
+
this.arrival = full;
|
|
672
|
+
const resolved = this.consentedUtm(full);
|
|
673
|
+
const sessionLanding = (0, import_storefront_api5.parseLanding)((0, import_storefront_api5.readStorage)(_MoonbaseStorefront.arrivalKey, "session"));
|
|
674
|
+
if (!(0, import_storefront_api5.hasCampaignData)(full))
|
|
675
|
+
this.landing = void 0;
|
|
676
|
+
else if (full !== fresh)
|
|
677
|
+
this.landing = full === sessionCached ? sessionLanding : (0, import_storefront_api5.parseLanding)((0, import_storefront_api5.readStorage)(_MoonbaseStorefront.arrivalKey, "local"));
|
|
678
|
+
else if (sessionCached && sessionLanding && (0, import_storefront_api5.isSameArrival)(sessionCached, fresh))
|
|
679
|
+
this.landing = sessionLanding;
|
|
680
|
+
else
|
|
681
|
+
this.landing = (0, import_storefront_api5.landingHere)();
|
|
682
|
+
const refused = (0, import_storefront_api5.grantsClickIds)(this.attributionConsentSetting) === false;
|
|
683
|
+
if (hasUtmOrReferrer(resolved) && (full !== sessionCached || refused) && JSON.stringify(resolved) !== sessionRaw)
|
|
684
|
+
(0, import_storefront_api5.writeStorage)(_MoonbaseStorefront.utmKey, JSON.stringify(resolved), "session");
|
|
685
|
+
if (this.landing !== sessionLanding)
|
|
686
|
+
this.storeLanding("session");
|
|
687
|
+
if (configuration.persistUtm && this.attributionConsent && hasUtmOrReferrer(resolved)) {
|
|
688
|
+
(0, import_storefront_api5.writeStorage)(_MoonbaseStorefront.utmKey, JSON.stringify(resolved), "local");
|
|
689
|
+
this.storeLanding("local");
|
|
690
|
+
} else if (configuration.persistUtm && refused) {
|
|
691
|
+
(0, import_storefront_api5.removeStorage)(_MoonbaseStorefront.utmKey, "local");
|
|
692
|
+
(0, import_storefront_api5.removeStorage)(_MoonbaseStorefront.arrivalKey, "local");
|
|
693
|
+
}
|
|
694
|
+
const cachedCatalogJson = (0, import_storefront_api5.readStorage)(_MoonbaseStorefront.storefrontKey);
|
|
695
|
+
const cachedCatalog = cachedCatalogJson ? _MoonbaseStorefront.parseCachedCatalog(cachedCatalogJson) : null;
|
|
696
|
+
const catalog = cachedCatalog != null ? cachedCatalog : this.serverState.catalog;
|
|
697
|
+
const cachedOrder = _MoonbaseStorefront.parseCachedOrder((0, import_storefront_api5.readStorage)(_MoonbaseStorefront.sessionKey));
|
|
698
|
+
const order = cachedOrder != null ? cachedOrder : newOrder();
|
|
699
|
+
let user = null;
|
|
700
|
+
if (this.client.tokenStore.user) {
|
|
701
|
+
try {
|
|
702
|
+
user = import_storefront_api5.schemas.identity.userSchema.parse(this.client.tokenStore.user);
|
|
703
|
+
} catch (err) {
|
|
704
|
+
console.warn("Could not read the stored Moonbase user, signing out", err);
|
|
705
|
+
this.client.tokenStore.clear();
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
this.state = {
|
|
709
|
+
catalog,
|
|
710
|
+
catalogLoaded: !!cachedCatalog || this.serverState.catalogLoaded,
|
|
711
|
+
closed: false,
|
|
712
|
+
// The order's currency starts from the catalog's suggestion, so the first paint uses the same
|
|
713
|
+
// source of truth the refreshes settle on, rather than a possibly stale one stored with the cart.
|
|
714
|
+
order: { ...order, currency: (0, import_storefront_api5.resolveDisplayCurrency)(order, catalog) },
|
|
715
|
+
user,
|
|
716
|
+
userLoaded: false,
|
|
717
|
+
utm: resolved
|
|
718
|
+
};
|
|
719
|
+
if (this.state.catalogLoaded)
|
|
720
|
+
this.resolveCatalogLoaded();
|
|
721
|
+
if (cachedOrder) {
|
|
722
|
+
void this.refreshOrder();
|
|
723
|
+
} else if (this.hasUtmOrReferrer && this.attributionConsent) {
|
|
724
|
+
this.pushOrderContent();
|
|
725
|
+
}
|
|
726
|
+
(0, import_storefront_api5.pruneRememberedPurchase)();
|
|
727
|
+
this.refreshInBackground();
|
|
728
|
+
const intent = urlParams.get("mb_intent");
|
|
729
|
+
const endpoint = urlParams.get("mb_endpoint");
|
|
730
|
+
if ((intent === "checkout" || intent === "update_subscription") && urlParams.get("mb_complete") && endpoint) {
|
|
731
|
+
const parameters = Object.fromEntries([...urlParams.entries()].filter(([key]) => !key.startsWith("mb_")));
|
|
732
|
+
const finalEndpoint = new URL(decodeURIComponent(endpoint));
|
|
733
|
+
for (const [key, value] of Object.entries(parameters))
|
|
734
|
+
finalEndpoint.searchParams.append(key, value);
|
|
735
|
+
if (intent === "checkout")
|
|
736
|
+
(0, import_storefront_api5.mountCheckout)(finalEndpoint.toString());
|
|
737
|
+
else
|
|
738
|
+
(0, import_storefront_api5.mountSubscription)(finalEndpoint.toString());
|
|
739
|
+
window.history.replaceState(window.history.state, "", (0, import_storefront_api5.withoutHandshakeParams)(window.location.href));
|
|
740
|
+
}
|
|
741
|
+
window.addEventListener("moonbase-checkout-billing-details-updated", () => {
|
|
742
|
+
this.refreshInBackground();
|
|
743
|
+
});
|
|
744
|
+
window.addEventListener("moonbase-checkout-completed", (event) => {
|
|
745
|
+
const completed = event.detail.order;
|
|
746
|
+
if (completed.id === this.state.order.id)
|
|
747
|
+
this.resetOrder();
|
|
748
|
+
(0, import_storefront_api5.forgetPurchase)(completed.id);
|
|
749
|
+
this.refreshInBackground();
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
/**
|
|
753
|
+
* 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.
|
|
755
|
+
*/
|
|
756
|
+
on(event, callback) {
|
|
757
|
+
if (typeof window === "undefined")
|
|
758
|
+
return () => {
|
|
759
|
+
};
|
|
760
|
+
const [name, read] = windowEvents[event];
|
|
761
|
+
const listener = (e) => callback(...read(e.detail));
|
|
762
|
+
window.addEventListener(name, listener);
|
|
763
|
+
return () => window.removeEventListener(name, listener);
|
|
764
|
+
}
|
|
765
|
+
get hasUtm() {
|
|
766
|
+
const utm = this.state.utm;
|
|
767
|
+
return !!utm && !!(utm.source || utm.medium || utm.campaign || utm.term || utm.content || utm.id || utm.gadSource || utm.gadCampaignId);
|
|
768
|
+
}
|
|
769
|
+
get hasUtmOrReferrer() {
|
|
770
|
+
return hasUtmOrReferrer(this.state.utm);
|
|
771
|
+
}
|
|
772
|
+
/** Whether the storefront may keep and send ad click IDs and record an arrival before any action. */
|
|
773
|
+
get attributionConsent() {
|
|
774
|
+
var _a;
|
|
775
|
+
return (_a = (0, import_storefront_api5.grantsClickIds)(this.attributionConsentSetting)) != null ? _a : this.storeAllowsAttribution === true;
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* Buys these items straight away, without touching the cart: the "Buy now" path. Opens the checkout
|
|
779
|
+
* over the page, or on a phone sends the buyer to Moonbase's own checkout page (see `redirect`), and
|
|
780
|
+
* settles once the overlay closes or the page is on its way.
|
|
781
|
+
*/
|
|
782
|
+
checkout(items, options = {}) {
|
|
783
|
+
return checkout(this, items, options);
|
|
784
|
+
}
|
|
785
|
+
/** Closes the checkout overlay, if one is open. */
|
|
786
|
+
closeCheckout() {
|
|
787
|
+
(0, import_storefront_api5.closeCheckout)();
|
|
788
|
+
}
|
|
789
|
+
/**
|
|
790
|
+
* Say whether the visitor has agreed to marketing cookies, typically from a cookie banner's callback.
|
|
791
|
+
* `StorefrontOptions.attributionConsent` sets where it starts. Until either says, the storefront
|
|
792
|
+
* follows the store's own setting in Moonbase, which the catalog reports for this visitor once it
|
|
793
|
+
* loads. A banner that asks for Google's two parts separately can pass `{ adUserData, adPersonalization }`,
|
|
794
|
+
* which counts as granted here when `adUserData` is.
|
|
795
|
+
*
|
|
796
|
+
* Granting it adds the ad click IDs the visitor arrived with in this tab (`gclid`, `fbclid` and the
|
|
797
|
+
* rest) to `utm`, and records the arrival on a new cart if there is none yet, so a visitor who leaves
|
|
798
|
+
* and comes back to buy is still put down to it. Withdrawing it drops the click IDs from `utm` and the
|
|
799
|
+
* browser's storage again. What has already been sent stays with the order.
|
|
800
|
+
*/
|
|
801
|
+
setAttributionConsent(granted) {
|
|
802
|
+
const before = this.attributionConsent;
|
|
803
|
+
this.attributionConsentSetting = (0, import_storefront_api5.copyConsent)(granted);
|
|
804
|
+
this.attributionConsentChanged(before);
|
|
805
|
+
if ((0, import_storefront_api5.grantsClickIds)(this.attributionConsentSetting) === false && typeof window !== "undefined") {
|
|
806
|
+
if (this.hasUtmOrReferrer)
|
|
807
|
+
(0, import_storefront_api5.writeStorage)(_MoonbaseStorefront.utmKey, JSON.stringify(this.state.utm), "session");
|
|
808
|
+
if (this.configuration.persistUtm) {
|
|
809
|
+
(0, import_storefront_api5.removeStorage)(_MoonbaseStorefront.utmKey, "local");
|
|
810
|
+
(0, import_storefront_api5.removeStorage)(_MoonbaseStorefront.arrivalKey, "local");
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
/**
|
|
815
|
+
* What the storefront's requests say of the visit for ad measurement, beside `utm`: what the site last
|
|
816
|
+
* 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.
|
|
818
|
+
*/
|
|
819
|
+
adSignals() {
|
|
820
|
+
const landing = (0, import_storefront_api5.hasCampaignData)(this.state.utm) ? this.landing : void 0;
|
|
821
|
+
return {
|
|
822
|
+
consent: (0, import_storefront_api5.copyConsent)(this.attributionConsentSetting),
|
|
823
|
+
arrivedAt: landing == null ? void 0 : landing.arrivedAt,
|
|
824
|
+
landingPage: landing == null ? void 0 : landing.landingPage
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
/** Asks Moonbase who is signed in. `state.user` is null when nobody is, or the session has run out. */
|
|
828
|
+
async refreshUser() {
|
|
829
|
+
const requested = this.client.tokenStore.user;
|
|
830
|
+
try {
|
|
831
|
+
const user = await this.client.identity.get();
|
|
832
|
+
this.setState({ user, userLoaded: true });
|
|
833
|
+
} catch (err) {
|
|
834
|
+
const stored = this.client.tokenStore.user;
|
|
835
|
+
if (stored !== null && stored !== requested) {
|
|
836
|
+
this.setState({ userLoaded: true });
|
|
837
|
+
return this.state.user;
|
|
838
|
+
}
|
|
839
|
+
if (!(err instanceof import_storefront_api5.NotAuthenticatedError || err instanceof import_storefront_api5.StoreClosedError))
|
|
840
|
+
console.error("Could not load user", err);
|
|
841
|
+
this.setState({ user: null, userLoaded: true });
|
|
842
|
+
}
|
|
843
|
+
return this.state.user;
|
|
844
|
+
}
|
|
845
|
+
/** Asks Moonbase for the catalog again, for this visitor and whoever is signed in. */
|
|
846
|
+
async refreshCatalog() {
|
|
847
|
+
const refresh = ++this.catalogRefreshesStarted;
|
|
848
|
+
let latest;
|
|
849
|
+
try {
|
|
850
|
+
latest = await this.client.storefront.get(this.hasUtmOrReferrer ? this.state.utm : void 0);
|
|
851
|
+
} catch (err) {
|
|
852
|
+
if (!(err instanceof import_storefront_api5.StoreClosedError))
|
|
853
|
+
throw err;
|
|
854
|
+
this.closeStore();
|
|
855
|
+
return this.state.catalog;
|
|
856
|
+
}
|
|
857
|
+
if (refresh < this.catalogRefreshLanded || !latest)
|
|
858
|
+
return this.state.catalog;
|
|
859
|
+
this.catalogRefreshLanded = refresh;
|
|
860
|
+
(0, import_storefront_api5.writeStorage)(_MoonbaseStorefront.storefrontKey, JSON.stringify(latest));
|
|
861
|
+
const current = this.state.order;
|
|
862
|
+
const order = { ...current, currency: (0, import_storefront_api5.resolveDisplayCurrency)(current, latest) };
|
|
863
|
+
order.items = enrichLineItems(latest, order);
|
|
864
|
+
const withOffer = withBestCartOffer(latest, order);
|
|
865
|
+
this.setState({ catalog: latest, catalogLoaded: true, order: withOffer });
|
|
866
|
+
if (withOffer !== order && withOffer.items.length > 0)
|
|
867
|
+
this.pushOrderContent();
|
|
868
|
+
const consentedBefore = this.attributionConsent;
|
|
869
|
+
this.storeAllowsAttribution = latest.cookieConsentRequired === false;
|
|
870
|
+
this.attributionConsentChanged(consentedBefore);
|
|
871
|
+
if (typeof window !== "undefined")
|
|
872
|
+
window.dispatchEvent(new CustomEvent("moonbase-storefront-updated", { detail: { storefront: latest } }));
|
|
873
|
+
return latest;
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* Saves the cart in this browser and sends it to Moonbase, half a second after the last change, so a
|
|
877
|
+
* buyer pressing "+" five times sends one request.
|
|
878
|
+
*/
|
|
879
|
+
pushOrderContent() {
|
|
880
|
+
(0, import_storefront_api5.writeStorage)(_MoonbaseStorefront.sessionKey, JSON.stringify(this.state.order));
|
|
881
|
+
this.refreshOrderAbortController.abort();
|
|
882
|
+
this.refreshOrderAbortController = new AbortController();
|
|
883
|
+
const pushed = this.state.order;
|
|
884
|
+
clearTimeout(this.pushTimeout);
|
|
885
|
+
this.pushTimeout = setTimeout(() => {
|
|
886
|
+
const latest = this.state.order;
|
|
887
|
+
const order = latest.id === pushed.id ? latest : pushed;
|
|
888
|
+
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);
|
|
890
|
+
}
|
|
891
|
+
/**
|
|
892
|
+
* Starts a new, empty cart, or with `keepItems` a new cart holding the same lines, under a new ID.
|
|
893
|
+
* Coupons are not carried over: they are checked again for each order and customer.
|
|
894
|
+
*/
|
|
895
|
+
resetOrder(opts) {
|
|
896
|
+
var _a;
|
|
897
|
+
const keep = (_a = opts == null ? void 0 : opts.keepItems) != null ? _a : false;
|
|
898
|
+
const order = newOrder(this.state.catalog.suggestedCurrency || "", keep ? this.state.order.items : []);
|
|
899
|
+
this.setState({ order });
|
|
900
|
+
if (keep && order.items.length > 0)
|
|
901
|
+
(0, import_storefront_api5.writeStorage)(_MoonbaseStorefront.sessionKey, JSON.stringify(order));
|
|
902
|
+
else
|
|
903
|
+
(0, import_storefront_api5.removeStorage)(_MoonbaseStorefront.sessionKey);
|
|
904
|
+
}
|
|
905
|
+
/** Takes the billing details off the cart's order in Moonbase, as a buyer leaving it would want. */
|
|
906
|
+
async surrenderOrder() {
|
|
907
|
+
try {
|
|
908
|
+
await this.client.orders.removeBillingDetails(this.state.order.id);
|
|
909
|
+
} catch (err) {
|
|
910
|
+
if (err instanceof import_storefront_api5.NotFoundError)
|
|
911
|
+
return;
|
|
912
|
+
console.warn("Could not surrender order:", err);
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
/** The lines with their products, bundles and prices from the current catalog. */
|
|
916
|
+
enrichLineItems(lineItems, order = this.state.order) {
|
|
917
|
+
return enrichLineItems(this.state.catalog, order, lineItems);
|
|
918
|
+
}
|
|
919
|
+
/** The context an offer's condition is judged against: the cart, unless another order is given. */
|
|
920
|
+
offerConditionContext(order = this.state.order) {
|
|
921
|
+
return conditionContext(this.state.catalog, order);
|
|
922
|
+
}
|
|
923
|
+
/** Puts the best cart offer the cart qualifies for on it, returning whether that changed anything. */
|
|
924
|
+
reconcileCartOffer() {
|
|
925
|
+
const order = withBestCartOffer(this.state.catalog, this.state.order);
|
|
926
|
+
if (order === this.state.order)
|
|
927
|
+
return false;
|
|
928
|
+
this.setState({ order });
|
|
929
|
+
return true;
|
|
930
|
+
}
|
|
931
|
+
/**
|
|
932
|
+
* Takes the cart offer off the order without sending the cart again. Cart offers apply themselves,
|
|
933
|
+
* but a page driving the cart itself may want to.
|
|
934
|
+
*/
|
|
935
|
+
async removeCartOffer() {
|
|
936
|
+
let order = this.state.order;
|
|
937
|
+
if (order.status === import_storefront_api5.OrderStatus.Open && order.offerId) {
|
|
938
|
+
order = { ...order, offerId: void 0 };
|
|
939
|
+
this.setState({ order });
|
|
940
|
+
}
|
|
941
|
+
(0, import_storefront_api5.writeStorage)(_MoonbaseStorefront.sessionKey, JSON.stringify(order));
|
|
942
|
+
await this.client.orders.removeOffer(order.id);
|
|
943
|
+
}
|
|
944
|
+
setState(patch) {
|
|
945
|
+
const keys = Object.keys(patch);
|
|
946
|
+
if (keys.every((key) => Object.is(this.state[key], patch[key])))
|
|
947
|
+
return;
|
|
948
|
+
this.state = { ...this.state, ...patch };
|
|
949
|
+
if (this.state.catalogLoaded)
|
|
950
|
+
this.resolveCatalogLoaded();
|
|
951
|
+
if (this.state.userLoaded)
|
|
952
|
+
this.resolveUserLoaded();
|
|
953
|
+
for (const listener of [...this.listeners])
|
|
954
|
+
listener();
|
|
955
|
+
}
|
|
956
|
+
/**
|
|
957
|
+
* The server refused to renew the buyer's session: they signed out of it elsewhere, changed their
|
|
958
|
+
* password, or stayed away too long. Goes anonymous the way signing out does, and says so, since
|
|
959
|
+
* nobody on this page signed out and the page would otherwise never hear of it.
|
|
960
|
+
*/
|
|
961
|
+
endSession() {
|
|
962
|
+
const user = this.state.user;
|
|
963
|
+
if (!user)
|
|
964
|
+
return;
|
|
965
|
+
this.resetOrder({ keepItems: true });
|
|
966
|
+
(0, import_storefront_api5.forgetPurchase)();
|
|
967
|
+
this.setState({ user: null });
|
|
968
|
+
window.dispatchEvent(new CustomEvent("moonbase-session-ended", { detail: { user } }));
|
|
969
|
+
this.refreshInBackground({ user: false });
|
|
970
|
+
}
|
|
971
|
+
refreshInBackground(what = {}) {
|
|
972
|
+
this.refreshCatalog().catch((err) => console.error("Could not load the Moonbase catalog", err));
|
|
973
|
+
if (what.user !== false)
|
|
974
|
+
void this.refreshUser();
|
|
975
|
+
}
|
|
976
|
+
/**
|
|
977
|
+
* The store has closed for good, so nothing kept for it is any use: not the catalog a returning
|
|
978
|
+
* visitor would otherwise be shown, not the cart, and not the buyer's session.
|
|
979
|
+
*/
|
|
980
|
+
closeStore() {
|
|
981
|
+
(0, import_storefront_api5.removeStorage)(_MoonbaseStorefront.storefrontKey);
|
|
982
|
+
this.setState({ closed: true, catalog: emptyCatalog(), catalogLoaded: true });
|
|
983
|
+
this.resetOrder();
|
|
984
|
+
this.client.tokenStore.clear();
|
|
985
|
+
this.setState({ user: null });
|
|
986
|
+
}
|
|
987
|
+
/** Brings `utm`, its storage and the cart in line with the visitor's consent, when that changed. */
|
|
988
|
+
attributionConsentChanged(before) {
|
|
989
|
+
var _a, _b;
|
|
990
|
+
const granted = this.attributionConsent;
|
|
991
|
+
if (typeof window === "undefined" || granted === before)
|
|
992
|
+
return;
|
|
993
|
+
if (granted && this.configuration.persistUtm) {
|
|
994
|
+
const persisted = _MoonbaseStorefront.parseCachedUtm((0, import_storefront_api5.readStorage)(_MoonbaseStorefront.utmKey, "local"));
|
|
995
|
+
const arrival = (0, import_storefront_api5.resolveUtm)(persisted, (_a = this.arrival) != null ? _a : {});
|
|
996
|
+
if (persisted && arrival === persisted)
|
|
997
|
+
this.landing = (0, import_storefront_api5.hasCampaignData)(persisted) ? (0, import_storefront_api5.parseLanding)((0, import_storefront_api5.readStorage)(_MoonbaseStorefront.arrivalKey, "local")) : void 0;
|
|
998
|
+
this.arrival = arrival;
|
|
999
|
+
}
|
|
1000
|
+
const resolved = this.consentedUtm((_b = this.arrival) != null ? _b : {});
|
|
1001
|
+
this.setState({ utm: resolved });
|
|
1002
|
+
if (this.hasUtmOrReferrer) {
|
|
1003
|
+
(0, import_storefront_api5.writeStorage)(_MoonbaseStorefront.utmKey, JSON.stringify(resolved), "session");
|
|
1004
|
+
this.storeLanding("session");
|
|
1005
|
+
if (granted && this.configuration.persistUtm) {
|
|
1006
|
+
(0, import_storefront_api5.writeStorage)(_MoonbaseStorefront.utmKey, JSON.stringify(resolved), "local");
|
|
1007
|
+
this.storeLanding("local");
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
if (granted && this.hasUtmOrReferrer && !(0, import_storefront_api5.readStorage)(_MoonbaseStorefront.sessionKey))
|
|
1011
|
+
this.pushOrderContent();
|
|
1012
|
+
}
|
|
1013
|
+
/** Keeps `landing` beside the arrival in `kind` storage, or clears what is there for an arrival without one. */
|
|
1014
|
+
storeLanding(kind) {
|
|
1015
|
+
if (this.landing)
|
|
1016
|
+
(0, import_storefront_api5.writeStorage)(_MoonbaseStorefront.arrivalKey, JSON.stringify(this.landing), kind);
|
|
1017
|
+
else
|
|
1018
|
+
(0, import_storefront_api5.removeStorage)(_MoonbaseStorefront.arrivalKey, kind);
|
|
1019
|
+
}
|
|
1020
|
+
/** `utm` as the storefront may keep and send it: with its ad click IDs only once the visitor agreed. */
|
|
1021
|
+
consentedUtm(utm) {
|
|
1022
|
+
return this.attributionConsent ? utm : (0, import_storefront_api5.withoutClickIds)(utm);
|
|
1023
|
+
}
|
|
1024
|
+
handleStorageUpdate(event) {
|
|
1025
|
+
var _a;
|
|
1026
|
+
switch (event.key) {
|
|
1027
|
+
case _MoonbaseStorefront.sessionKey:
|
|
1028
|
+
this.setState({
|
|
1029
|
+
order: (_a = _MoonbaseStorefront.parseCachedOrder(event.newValue)) != null ? _a : newOrder(this.state.catalog.suggestedCurrency || "")
|
|
1030
|
+
});
|
|
1031
|
+
break;
|
|
1032
|
+
case _MoonbaseStorefront.storefrontKey: {
|
|
1033
|
+
const catalog = event.newValue ? _MoonbaseStorefront.parseCachedCatalog(event.newValue) : null;
|
|
1034
|
+
if (catalog)
|
|
1035
|
+
this.setState({ catalog });
|
|
1036
|
+
break;
|
|
1037
|
+
}
|
|
1038
|
+
case _MoonbaseStorefront.utmKey: {
|
|
1039
|
+
const utm = _MoonbaseStorefront.parseCachedUtm(event.newValue);
|
|
1040
|
+
if (utm) {
|
|
1041
|
+
this.arrival = utm;
|
|
1042
|
+
this.setState({ utm: this.consentedUtm(utm) });
|
|
1043
|
+
}
|
|
1044
|
+
break;
|
|
1045
|
+
}
|
|
1046
|
+
case _MoonbaseStorefront.arrivalKey: {
|
|
1047
|
+
const landing = (0, import_storefront_api5.parseLanding)(event.newValue);
|
|
1048
|
+
if (landing)
|
|
1049
|
+
this.landing = landing;
|
|
1050
|
+
break;
|
|
1051
|
+
}
|
|
1052
|
+
case import_storefront_api5.TokenStore.storageKey:
|
|
1053
|
+
if (!event.newValue) {
|
|
1054
|
+
const user = this.state.user;
|
|
1055
|
+
this.setState({ user: null });
|
|
1056
|
+
if (user)
|
|
1057
|
+
window.dispatchEvent(new CustomEvent("moonbase-session-ended", { detail: { user } }));
|
|
1058
|
+
} else {
|
|
1059
|
+
try {
|
|
1060
|
+
this.setState({ user: import_storefront_api5.schemas.identity.userSchema.parse(JSON.parse(event.newValue)) });
|
|
1061
|
+
} catch (err) {
|
|
1062
|
+
console.warn("Could not read the updated Moonbase user", err);
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
async refreshOrder() {
|
|
1068
|
+
const refreshingId = this.state.order.id;
|
|
1069
|
+
try {
|
|
1070
|
+
const latest = await this.client.orders.get(refreshingId, { abort: this.refreshOrderAbortController.signal });
|
|
1071
|
+
if (this.state.order.id !== refreshingId || !latest)
|
|
1072
|
+
return;
|
|
1073
|
+
if (latest.status !== import_storefront_api5.OrderStatus.Open) {
|
|
1074
|
+
this.resetOrder();
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
const catalog = this.state.catalog;
|
|
1078
|
+
const adopted = { ...latest, currency: (0, import_storefront_api5.resolveDisplayCurrency)(latest, catalog) };
|
|
1079
|
+
adopted.items = enrichLineItems(catalog, adopted, latest.items);
|
|
1080
|
+
(0, import_storefront_api5.writeStorage)(_MoonbaseStorefront.sessionKey, JSON.stringify(adopted));
|
|
1081
|
+
this.setState({ order: adopted });
|
|
1082
|
+
if (this.state.catalogLoaded && this.reconcileCartOffer() && adopted.items.length > 0)
|
|
1083
|
+
this.pushOrderContent();
|
|
1084
|
+
} catch (err) {
|
|
1085
|
+
if (err instanceof import_storefront_api5.NotAuthorizedError && this.state.order.id === refreshingId)
|
|
1086
|
+
this.resetOrder();
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
static parseCachedUtm(raw) {
|
|
1090
|
+
if (!raw)
|
|
1091
|
+
return void 0;
|
|
1092
|
+
try {
|
|
1093
|
+
return JSON.parse(raw);
|
|
1094
|
+
} catch (err) {
|
|
1095
|
+
console.warn(`Could not parse cached UTM from ${_MoonbaseStorefront.utmKey}`, err);
|
|
1096
|
+
return void 0;
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
static parseCachedOrder(raw) {
|
|
1100
|
+
if (!raw)
|
|
1101
|
+
return null;
|
|
1102
|
+
try {
|
|
1103
|
+
return JSON.parse(raw);
|
|
1104
|
+
} catch (err) {
|
|
1105
|
+
console.warn("Could not read the cart stored in this browser; starting a new one", err);
|
|
1106
|
+
return null;
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
/**
|
|
1110
|
+
* Reads a catalog out of local storage, normalising it through the schema, which fills in the
|
|
1111
|
+
* defaults a catalog cached by an older version lacks. One the schema rejects is still used as it
|
|
1112
|
+
* is: a catalog only partly understood beats an empty one while the refresh is in flight. Only
|
|
1113
|
+
* unreadable JSON gives up.
|
|
1114
|
+
*/
|
|
1115
|
+
static parseCachedCatalog(json) {
|
|
1116
|
+
let raw;
|
|
1117
|
+
try {
|
|
1118
|
+
raw = JSON.parse(json);
|
|
1119
|
+
} catch (err) {
|
|
1120
|
+
console.warn("Could not parse the cached storefront; starting from an empty one", err);
|
|
1121
|
+
return null;
|
|
1122
|
+
}
|
|
1123
|
+
return _MoonbaseStorefront.normalizeCatalog(raw);
|
|
1124
|
+
}
|
|
1125
|
+
static normalizeCatalog(raw) {
|
|
1126
|
+
const parsed = import_storefront_api5.schemas.storefront.storefrontSchema.safeParse(raw);
|
|
1127
|
+
return parsed.success ? parsed.data : raw;
|
|
1128
|
+
}
|
|
1129
|
+
};
|
|
1130
|
+
_MoonbaseStorefront.sessionKey = "moonbase_session";
|
|
1131
|
+
_MoonbaseStorefront.storefrontKey = "moonbase_storefront";
|
|
1132
|
+
_MoonbaseStorefront.utmKey = "moonbase_utm";
|
|
1133
|
+
_MoonbaseStorefront.arrivalKey = "moonbase_arrival";
|
|
1134
|
+
var MoonbaseStorefront = _MoonbaseStorefront;
|
|
1135
|
+
|
|
1136
|
+
// src/provider.ts
|
|
1137
|
+
var import_react = require("react");
|
|
1138
|
+
var StorefrontContext = (0, import_react.createContext)(null);
|
|
1139
|
+
function StorefrontProvider({ storefront, children }) {
|
|
1140
|
+
return (0, import_react.createElement)(StorefrontContext.Provider, { value: storefront }, children);
|
|
1141
|
+
}
|
|
1142
|
+
function useStorefront() {
|
|
1143
|
+
const storefront = (0, import_react.useContext)(StorefrontContext);
|
|
1144
|
+
if (!storefront)
|
|
1145
|
+
throw new Error("No storefront configured: render this inside a <StorefrontProvider>");
|
|
1146
|
+
return storefront;
|
|
1147
|
+
}
|
|
1148
|
+
function useStorefrontState(selector) {
|
|
1149
|
+
const storefront = useStorefront();
|
|
1150
|
+
return (0, import_react.useSyncExternalStore)(
|
|
1151
|
+
storefront.subscribe,
|
|
1152
|
+
() => selector(storefront.getState()),
|
|
1153
|
+
() => selector(storefront.getServerState())
|
|
1154
|
+
);
|
|
1155
|
+
}
|
|
1156
|
+
function useStorefrontEvent(event, handler) {
|
|
1157
|
+
const storefront = useStorefront();
|
|
1158
|
+
const latest = (0, import_react.useRef)(handler);
|
|
1159
|
+
(0, import_react.useEffect)(() => {
|
|
1160
|
+
latest.current = handler;
|
|
1161
|
+
});
|
|
1162
|
+
(0, import_react.useEffect)(() => storefront.on(event, (...args) => latest.current(...args)), [storefront, event]);
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
// src/hooks/catalog.ts
|
|
1166
|
+
var none = [];
|
|
1167
|
+
function useCatalog() {
|
|
1168
|
+
return useStorefrontState((state) => state.catalog);
|
|
1169
|
+
}
|
|
1170
|
+
function useProducts() {
|
|
1171
|
+
return useStorefrontState((state) => state.catalog.products);
|
|
1172
|
+
}
|
|
1173
|
+
function useProduct(productId) {
|
|
1174
|
+
return useStorefrontState((state) => {
|
|
1175
|
+
var _a;
|
|
1176
|
+
return (_a = state.catalog.products.find((p) => p.id === productId)) != null ? _a : null;
|
|
1177
|
+
});
|
|
1178
|
+
}
|
|
1179
|
+
function useBundles() {
|
|
1180
|
+
return useStorefrontState((state) => state.catalog.bundles);
|
|
1181
|
+
}
|
|
1182
|
+
function useBundle(bundleId) {
|
|
1183
|
+
return useStorefrontState((state) => {
|
|
1184
|
+
var _a;
|
|
1185
|
+
return (_a = state.catalog.bundles.find((b) => b.id === bundleId)) != null ? _a : null;
|
|
1186
|
+
});
|
|
1187
|
+
}
|
|
1188
|
+
function useOffers() {
|
|
1189
|
+
return useStorefrontState((state) => {
|
|
1190
|
+
var _a;
|
|
1191
|
+
return (_a = state.catalog.offers) != null ? _a : none;
|
|
1192
|
+
});
|
|
1193
|
+
}
|
|
1194
|
+
function useOffer(offerId) {
|
|
1195
|
+
return useStorefrontState((state) => {
|
|
1196
|
+
var _a, _b;
|
|
1197
|
+
return (_b = (_a = state.catalog.offers) == null ? void 0 : _a.find((o) => o.id === offerId)) != null ? _b : null;
|
|
1198
|
+
});
|
|
1199
|
+
}
|
|
1200
|
+
function usePromotions() {
|
|
1201
|
+
return useStorefrontState((state) => {
|
|
1202
|
+
var _a;
|
|
1203
|
+
return (_a = state.catalog.promotions) != null ? _a : none;
|
|
1204
|
+
});
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
// src/hooks/offers.ts
|
|
1208
|
+
var import_react2 = require("react");
|
|
1209
|
+
|
|
1210
|
+
// src/offers.ts
|
|
1211
|
+
var import_storefront_api6 = require("@moonbase.sh/storefront-api");
|
|
1212
|
+
function eligibleOffers(catalog, order) {
|
|
1213
|
+
var _a;
|
|
1214
|
+
const context = conditionContext(catalog, order);
|
|
1215
|
+
return ((_a = catalog.offers) != null ? _a : []).filter((o) => import_storefront_api6.OfferUtils.eligible(o, context) && !offerIsInCart(o, order) && !offerTargetIsInCart(o, order));
|
|
1216
|
+
}
|
|
1217
|
+
function lockedOffers(catalog, order) {
|
|
1218
|
+
var _a;
|
|
1219
|
+
const context = conditionContext(catalog, order);
|
|
1220
|
+
return ((_a = catalog.offers) != null ? _a : []).filter((o) => o.scope !== "Cart" && !offerIsInCart(o, order) && !offerTargetIsInCart(o, order)).map((offer) => ({ offer, progress: import_storefront_api6.OfferUtils.progress(offer, context) })).filter((locked) => locked.progress !== null && !locked.progress.eligible && locked.progress.unit === "Money" && locked.progress.remaining > 0).sort((a, b) => b.progress.fraction - a.progress.fraction);
|
|
1221
|
+
}
|
|
1222
|
+
function cartOfferState(catalog, order) {
|
|
1223
|
+
var _a, _b;
|
|
1224
|
+
const currency = (0, import_storefront_api6.resolveDisplayCurrency)(order, catalog);
|
|
1225
|
+
const offers = (_a = catalog.offers) != null ? _a : [];
|
|
1226
|
+
if (offers.length === 0 || order.items.length === 0)
|
|
1227
|
+
return null;
|
|
1228
|
+
const context = conditionContext(catalog, order);
|
|
1229
|
+
const breakdown = import_storefront_api6.CartUtils.total(catalog, order, currency);
|
|
1230
|
+
const applied = breakdown.cartOffer ? { offer: breakdown.cartOffer.offer, saving: breakdown.cartOffer.discount } : null;
|
|
1231
|
+
const candidates = offers.map((offer) => ({ offer, progress: import_storefront_api6.OfferUtils.progress(offer, context) })).filter((candidate) => candidate.progress !== null && !candidate.progress.eligible && candidate.progress.remaining > 0 && candidate.offer.scope === "Cart").sort((a, b) => b.progress.fraction - a.progress.fraction);
|
|
1232
|
+
const appliedValue = applied ? import_storefront_api6.CartUtils.cartOfferValue(catalog, order, applied.offer, currency, context) : 0;
|
|
1233
|
+
const next = (_b = applied ? candidates.find((c) => import_storefront_api6.CartUtils.cartOfferValue(catalog, order, c.offer, currency, context) > appliedValue) : candidates[0]) != null ? _b : null;
|
|
1234
|
+
if (!applied && !next)
|
|
1235
|
+
return null;
|
|
1236
|
+
return { applied, next, subtotal: breakdown.subtotal, currency };
|
|
1237
|
+
}
|
|
1238
|
+
function offerIsInCart(offer, order) {
|
|
1239
|
+
return order.items.some((i) => i.offerId === offer.id);
|
|
1240
|
+
}
|
|
1241
|
+
function offerTargetIsInCart(offer, order) {
|
|
1242
|
+
return import_storefront_api6.OfferUtils.allTargetsInCart(offer, order.items);
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
// src/hooks/offers.ts
|
|
1246
|
+
function useEligibleOffers() {
|
|
1247
|
+
const catalog = useStorefrontState((state) => state.catalog);
|
|
1248
|
+
const order = useStorefrontState((state) => state.order);
|
|
1249
|
+
return (0, import_react2.useMemo)(() => eligibleOffers(catalog, order), [catalog, order]);
|
|
1250
|
+
}
|
|
1251
|
+
function useLockedOffers() {
|
|
1252
|
+
const catalog = useStorefrontState((state) => state.catalog);
|
|
1253
|
+
const order = useStorefrontState((state) => state.order);
|
|
1254
|
+
return (0, import_react2.useMemo)(() => lockedOffers(catalog, order), [catalog, order]);
|
|
1255
|
+
}
|
|
1256
|
+
function useCartOffer() {
|
|
1257
|
+
const catalog = useStorefrontState((state) => state.catalog);
|
|
1258
|
+
const order = useStorefrontState((state) => state.order);
|
|
1259
|
+
return (0, import_react2.useMemo)(() => cartOfferState(catalog, order), [catalog, order]);
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
// src/hooks/useActivationRequest.ts
|
|
1263
|
+
var import_storefront_api7 = require("@moonbase.sh/storefront-api");
|
|
1264
|
+
var import_react3 = require("react");
|
|
1265
|
+
var pollInterval = 1500;
|
|
1266
|
+
function useActivationRequest(token) {
|
|
1267
|
+
var _a;
|
|
1268
|
+
const storefront = useStorefront();
|
|
1269
|
+
const userId = useStorefrontState((state) => {
|
|
1270
|
+
var _a2, _b;
|
|
1271
|
+
return (_b = (_a2 = state.user) == null ? void 0 : _a2.id) != null ? _b : null;
|
|
1272
|
+
});
|
|
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) => {
|
|
1279
|
+
setActivationRequest(request);
|
|
1280
|
+
if (request.status === import_storefront_api7.ActivationRequestStatus.Fulfilled)
|
|
1281
|
+
setCompleting(true);
|
|
1282
|
+
}, []);
|
|
1283
|
+
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)(() => {
|
|
1285
|
+
if (!token || upToDate)
|
|
1286
|
+
return;
|
|
1287
|
+
let current = true;
|
|
1288
|
+
storefront.client.activationRequests.get(token).then((request) => current && adopt(request)).catch((err) => current && setError(err.message)).finally(() => current && setFetched({ token, userId }));
|
|
1289
|
+
return () => {
|
|
1290
|
+
current = false;
|
|
1291
|
+
};
|
|
1292
|
+
}, [storefront, token, userId, upToDate, adopt]);
|
|
1293
|
+
const requestId = activationRequest == null ? void 0 : activationRequest.id;
|
|
1294
|
+
(0, import_react3.useEffect)(() => {
|
|
1295
|
+
if (!completing || !requestId)
|
|
1296
|
+
return;
|
|
1297
|
+
let current = true;
|
|
1298
|
+
let timeout;
|
|
1299
|
+
const check = async () => {
|
|
1300
|
+
try {
|
|
1301
|
+
const completed = await storefront.client.activationRequests.isCompleted(requestId);
|
|
1302
|
+
if (!current)
|
|
1303
|
+
return;
|
|
1304
|
+
if (completed) {
|
|
1305
|
+
setActivationRequest((request) => request && { ...request, status: import_storefront_api7.ActivationRequestStatus.Completed });
|
|
1306
|
+
setCompleting(false);
|
|
1307
|
+
return;
|
|
1308
|
+
}
|
|
1309
|
+
} catch (err) {
|
|
1310
|
+
console.warn("Could not check whether the activation has completed", err);
|
|
1311
|
+
}
|
|
1312
|
+
if (current)
|
|
1313
|
+
timeout = setTimeout(check, pollInterval);
|
|
1314
|
+
};
|
|
1315
|
+
void check();
|
|
1316
|
+
return () => {
|
|
1317
|
+
current = false;
|
|
1318
|
+
clearTimeout(timeout);
|
|
1319
|
+
};
|
|
1320
|
+
}, [storefront, completing, requestId]);
|
|
1321
|
+
const fulfillLicense = (0, import_react3.useCallback)(async () => {
|
|
1322
|
+
if (!requestId)
|
|
1323
|
+
return;
|
|
1324
|
+
setFulfilling(true);
|
|
1325
|
+
try {
|
|
1326
|
+
adopt(await storefront.client.activationRequests.fulfillLicense(requestId));
|
|
1327
|
+
setCompleting(true);
|
|
1328
|
+
} finally {
|
|
1329
|
+
setFulfilling(false);
|
|
1330
|
+
}
|
|
1331
|
+
}, [storefront, requestId, adopt]);
|
|
1332
|
+
const fulfillTrial = (0, import_react3.useCallback)(async (newsletterOptIn = false) => {
|
|
1333
|
+
if (!requestId)
|
|
1334
|
+
return;
|
|
1335
|
+
setFulfilling(true);
|
|
1336
|
+
try {
|
|
1337
|
+
const user = storefront.getState().user;
|
|
1338
|
+
if (newsletterOptIn && user && !user.communicationPreferences.newsletterOptIn) {
|
|
1339
|
+
await storefront.auth.update(user.name, user.email, void 0, { ...user.communicationPreferences, newsletterOptIn: true });
|
|
1340
|
+
}
|
|
1341
|
+
adopt(await storefront.client.activationRequests.fulfillTrial(
|
|
1342
|
+
requestId,
|
|
1343
|
+
storefront.hasUtmOrReferrer ? storefront.getState().utm : void 0,
|
|
1344
|
+
storefront.adSignals()
|
|
1345
|
+
));
|
|
1346
|
+
setCompleting(true);
|
|
1347
|
+
} catch (err) {
|
|
1348
|
+
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);
|
|
1350
|
+
} finally {
|
|
1351
|
+
setFulfilling(false);
|
|
1352
|
+
}
|
|
1353
|
+
}, [storefront, requestId, adopt]);
|
|
1354
|
+
const cancel = (0, import_react3.useCallback)(async () => {
|
|
1355
|
+
if (!activationRequest || activationRequest.status === import_storefront_api7.ActivationRequestStatus.Cancelled)
|
|
1356
|
+
return;
|
|
1357
|
+
adopt(await storefront.client.activationRequests.cancel(activationRequest.id));
|
|
1358
|
+
}, [storefront, activationRequest, adopt]);
|
|
1359
|
+
return {
|
|
1360
|
+
activationRequest,
|
|
1361
|
+
loading: !!token && !upToDate,
|
|
1362
|
+
fulfilling,
|
|
1363
|
+
completing,
|
|
1364
|
+
error,
|
|
1365
|
+
isInstalled: (activationRequest == null ? void 0 : activationRequest.status) === import_storefront_api7.ActivationRequestStatus.Completed,
|
|
1366
|
+
fulfillLicense,
|
|
1367
|
+
fulfillTrial,
|
|
1368
|
+
cancel
|
|
1369
|
+
};
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
// src/hooks/useAuth.ts
|
|
1373
|
+
var import_react4 = require("react");
|
|
1374
|
+
function useAuth() {
|
|
1375
|
+
const storefront = useStorefront();
|
|
1376
|
+
const user = useStorefrontState((state) => state.user);
|
|
1377
|
+
const loaded = useStorefrontState((state) => state.userLoaded);
|
|
1378
|
+
return (0, import_react4.useMemo)(() => ({ ...storefront.auth, user, loaded }), [storefront, user, loaded]);
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
// src/hooks/useCart.ts
|
|
1382
|
+
var import_storefront_api8 = require("@moonbase.sh/storefront-api");
|
|
1383
|
+
var import_react5 = require("react");
|
|
1384
|
+
function useCart() {
|
|
1385
|
+
const storefront = useStorefront();
|
|
1386
|
+
const catalog = useStorefrontState((state) => state.catalog);
|
|
1387
|
+
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);
|
|
1391
|
+
const items = enrichLineItems(catalog, order);
|
|
1392
|
+
return {
|
|
1393
|
+
...storefront.cart,
|
|
1394
|
+
items,
|
|
1395
|
+
soldOutItems: items.filter((item) => import_storefront_api8.CartUtils.isSoldOut(catalog, item)),
|
|
1396
|
+
currency,
|
|
1397
|
+
total: { amount: breakdown.amount, currency: breakdown.currency },
|
|
1398
|
+
breakdown,
|
|
1399
|
+
cartOffer: breakdown.cartOffer
|
|
1400
|
+
};
|
|
1401
|
+
}, [storefront, catalog, order]);
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
// src/hooks/useCheckout.ts
|
|
1405
|
+
var import_react6 = require("react");
|
|
1406
|
+
function useCheckout() {
|
|
1407
|
+
const storefront = useStorefront();
|
|
1408
|
+
return (0, import_react6.useCallback)((items, options) => storefront.checkout(items, options), [storefront]);
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
// src/hooks/useCommunicationPreferences.ts
|
|
1412
|
+
var import_react7 = require("react");
|
|
1413
|
+
function useCommunicationPreferences() {
|
|
1414
|
+
const storefront = useStorefront();
|
|
1415
|
+
return (0, import_react7.useMemo)(() => {
|
|
1416
|
+
const communications = storefront.client.communications;
|
|
1417
|
+
return {
|
|
1418
|
+
subscribe: (input) => communications.subscribe(input, storefront.adSignals()),
|
|
1419
|
+
confirm: (email, token) => communications.confirm(email, token),
|
|
1420
|
+
get: (email, token) => communications.getPreferences(email, token),
|
|
1421
|
+
update: (email, token, preferences) => communications.updatePreferences(email, token, preferences),
|
|
1422
|
+
unsubscribe: (email, token) => communications.unsubscribe(email, token)
|
|
1423
|
+
};
|
|
1424
|
+
}, [storefront]);
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
// src/hooks/useGroups.ts
|
|
1428
|
+
var import_react8 = require("react");
|
|
1429
|
+
function useGroups() {
|
|
1430
|
+
const storefront = useStorefront();
|
|
1431
|
+
return (0, import_react8.useMemo)(() => ({ join: (groupId) => storefront.client.groups.join(groupId) }), [storefront]);
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
// src/hooks/useInventory.ts
|
|
1435
|
+
var import_react9 = require("react");
|
|
1436
|
+
|
|
1437
|
+
// src/inventory.ts
|
|
1438
|
+
var import_storefront_api9 = require("@moonbase.sh/storefront-api");
|
|
1439
|
+
function createInventory(storefront) {
|
|
1440
|
+
const inventory = storefront.client.inventory;
|
|
1441
|
+
return {
|
|
1442
|
+
getLicenses: (nextUrl) => inventory.licenses.get(nextUrl),
|
|
1443
|
+
getLicenseActivations: (licenseId, nextUrl) => inventory.licenses.getActivations(licenseId, nextUrl),
|
|
1444
|
+
getProduct: (productId, version2) => inventory.products.get(productId, version2),
|
|
1445
|
+
getProductReleases: (productId, nextUrl) => inventory.products.getReleases(productId, nextUrl),
|
|
1446
|
+
getProducts: (nextUrl) => inventory.products.getOwned(nextUrl),
|
|
1447
|
+
getProductLicenses: (productId, nextUrl) => inventory.products.getLicenses(productId, nextUrl),
|
|
1448
|
+
getProductActivations: (productId, nextUrl) => inventory.products.getActivations(productId, nextUrl),
|
|
1449
|
+
revokeActivation: (activation) => inventory.licenses.revokeActivation(activation.licenseId, activation.id),
|
|
1450
|
+
activateProduct: (deviceToken, activationMethod) => inventory.activation.activate(deviceToken, activationMethod),
|
|
1451
|
+
downloadProduct: async (download) => {
|
|
1452
|
+
if (!download.path)
|
|
1453
|
+
throw new Error("Product is not downloadable");
|
|
1454
|
+
window.location.href = await inventory.products.getDownloadUrl(download.path, storefront.adSignals());
|
|
1455
|
+
},
|
|
1456
|
+
getSubscriptions: (nextUrl) => inventory.subscriptions.get(nextUrl),
|
|
1457
|
+
getSubscription: (subscriptionId) => inventory.subscriptions.getById(subscriptionId),
|
|
1458
|
+
cancelSubscription: (subscriptionId, feedback) => inventory.subscriptions.cancel(subscriptionId, feedback),
|
|
1459
|
+
getSubscriptionPlanOptions: (subscriptionId) => inventory.subscriptions.getPlanOptions(subscriptionId),
|
|
1460
|
+
changeSubscriptionPlan: (subscriptionId, variationId) => inventory.subscriptions.changePlan(subscriptionId, variationId),
|
|
1461
|
+
cancelSubscriptionPlanChange: (subscriptionId) => inventory.subscriptions.cancelPlanChange(subscriptionId),
|
|
1462
|
+
renewSubscription: async (subscriptionId, options = {}) => {
|
|
1463
|
+
if (checkoutInProgress())
|
|
1464
|
+
return waitForCheckoutClose();
|
|
1465
|
+
const redirect = (0, import_storefront_api9.resolveRedirect)(options.redirect);
|
|
1466
|
+
const { location: url } = await inventory.subscriptions.renew(subscriptionId, checkoutReturnUrl(options.returnUrl), !redirect);
|
|
1467
|
+
if (redirect) {
|
|
1468
|
+
window.location.href = (0, import_storefront_api9.withPriceFormat)(url);
|
|
1469
|
+
return { next: void 0, completed: false, redirected: true };
|
|
1470
|
+
}
|
|
1471
|
+
const closed = waitForCheckoutClose();
|
|
1472
|
+
(0, import_storefront_api9.mountCheckout)(url);
|
|
1473
|
+
return closed;
|
|
1474
|
+
},
|
|
1475
|
+
updateSubscriptionPaymentMethod: async (subscription, options = {}) => {
|
|
1476
|
+
const response = await inventory.subscriptions.getById(subscription.id, {
|
|
1477
|
+
toUpdatePaymentMethod: true,
|
|
1478
|
+
returnUrl: checkoutReturnUrl(options.returnUrl)
|
|
1479
|
+
});
|
|
1480
|
+
window.dispatchEvent(new CustomEvent("moonbase-subscription-payment-method-update-initiated", {
|
|
1481
|
+
detail: { subscription }
|
|
1482
|
+
}));
|
|
1483
|
+
const url = response.embeddedUpdatePaymentUrl;
|
|
1484
|
+
if (!url)
|
|
1485
|
+
throw new Error("No update URL found");
|
|
1486
|
+
return new Promise((resolve) => {
|
|
1487
|
+
window.addEventListener("moonbase-subscription-closed", (event) => {
|
|
1488
|
+
resolve({ completed: event.detail.completed });
|
|
1489
|
+
}, { once: true });
|
|
1490
|
+
(0, import_storefront_api9.mountSubscription)(url);
|
|
1491
|
+
});
|
|
1492
|
+
}
|
|
1493
|
+
};
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1496
|
+
// src/hooks/useInventory.ts
|
|
1497
|
+
function useInventory() {
|
|
1498
|
+
const storefront = useStorefront();
|
|
1499
|
+
return (0, import_react9.useMemo)(() => createInventory(storefront), [storefront]);
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
// src/hooks/useOrders.ts
|
|
1503
|
+
var import_react10 = require("react");
|
|
1504
|
+
function useOrders() {
|
|
1505
|
+
const storefront = useStorefront();
|
|
1506
|
+
return (0, import_react10.useMemo)(() => ({
|
|
1507
|
+
getOrders: (nextUrl) => storefront.client.orders.getHistory(nextUrl),
|
|
1508
|
+
getReceipt: (order) => storefront.client.orders.getReceipt(order.id),
|
|
1509
|
+
downloadReceipt: async (order) => {
|
|
1510
|
+
const receipt = await storefront.client.orders.getReceipt(order.id);
|
|
1511
|
+
const url = URL.createObjectURL(receipt);
|
|
1512
|
+
const link = document.createElement("a");
|
|
1513
|
+
link.href = url;
|
|
1514
|
+
link.download = `Receipt_${order.id}.pdf`;
|
|
1515
|
+
document.body.append(link);
|
|
1516
|
+
link.click();
|
|
1517
|
+
link.remove();
|
|
1518
|
+
setTimeout(() => URL.revokeObjectURL(url), 6e4);
|
|
1519
|
+
}
|
|
1520
|
+
}), [storefront]);
|
|
1521
|
+
}
|
|
1522
|
+
|
|
1523
|
+
// src/hooks/useReviews.ts
|
|
1524
|
+
var import_react11 = require("react");
|
|
1525
|
+
function useReviews() {
|
|
1526
|
+
const storefront = useStorefront();
|
|
1527
|
+
const enabled = useStorefrontState((state) => !!state.catalog.reviewsEnabled);
|
|
1528
|
+
return (0, import_react11.useMemo)(() => {
|
|
1529
|
+
const reviews = storefront.client.reviews;
|
|
1530
|
+
return {
|
|
1531
|
+
enabled,
|
|
1532
|
+
getReviews: (productId, filter) => reviews.get(productId, filter),
|
|
1533
|
+
getMoreReviews: (next) => reviews.getMore(next),
|
|
1534
|
+
getMyReview: (productId) => reviews.getMine(productId),
|
|
1535
|
+
saveReview: (productId, review, existing) => existing ? reviews.edit(productId, review) : reviews.submit(productId, review),
|
|
1536
|
+
withdrawReview: (productId) => reviews.withdraw(productId),
|
|
1537
|
+
voteOnReview: (productId, reviewId, direction) => reviews.vote(productId, reviewId, direction)
|
|
1538
|
+
};
|
|
1539
|
+
}, [storefront, enabled]);
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
// src/hooks/useVendor.ts
|
|
1543
|
+
var import_react12 = require("react");
|
|
1544
|
+
function useVendor() {
|
|
1545
|
+
const storefront = useStorefront();
|
|
1546
|
+
const [state, setState] = (0, import_react12.useState)({ vendor: null, loading: true });
|
|
1547
|
+
(0, import_react12.useEffect)(() => {
|
|
1548
|
+
let current = true;
|
|
1549
|
+
storefront.client.vendor.get().then((vendor) => current && setState({ vendor, loading: false })).catch(() => current && setState({ vendor: null, loading: false }));
|
|
1550
|
+
return () => {
|
|
1551
|
+
current = false;
|
|
1552
|
+
};
|
|
1553
|
+
}, [storefront]);
|
|
1554
|
+
return state;
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
// src/hooks/useVoucher.ts
|
|
1558
|
+
var import_storefront_api10 = require("@moonbase.sh/storefront-api");
|
|
1559
|
+
var import_react13 = require("react");
|
|
1560
|
+
function useVoucher() {
|
|
1561
|
+
const storefront = useStorefront();
|
|
1562
|
+
return (0, import_react13.useMemo)(() => {
|
|
1563
|
+
const known = async (lookup) => {
|
|
1564
|
+
try {
|
|
1565
|
+
return await lookup;
|
|
1566
|
+
} catch (err) {
|
|
1567
|
+
if (err instanceof import_storefront_api10.NotFoundError)
|
|
1568
|
+
throw new Error("Voucher code invalid");
|
|
1569
|
+
throw err;
|
|
1570
|
+
}
|
|
1571
|
+
};
|
|
1572
|
+
return {
|
|
1573
|
+
peek: (code) => known(storefront.client.vouchers.peek(code)),
|
|
1574
|
+
redeem: (code) => known(storefront.client.vouchers.redeem(code))
|
|
1575
|
+
};
|
|
1576
|
+
}, [storefront]);
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
// src/index.ts
|
|
1580
|
+
__reExport(index_exports, require("@moonbase.sh/storefront-api"), module.exports);
|
|
1581
|
+
function createStorefront(endpoint, options = {}) {
|
|
1582
|
+
var _a;
|
|
1583
|
+
const { initialCatalog, autoApplyItemOffers, ...config } = options;
|
|
1584
|
+
const configuration = {
|
|
1585
|
+
...config,
|
|
1586
|
+
endpoint,
|
|
1587
|
+
// Named in `x-mb-client` ahead of `@moonbase.sh/storefront-api`, after any SDK wrapping this one.
|
|
1588
|
+
sdk: `${(_a = config.sdk) != null ? _a : ""} @moonbase.sh/react/${version}`.trim().replace(/\s+/g, " ")
|
|
1589
|
+
};
|
|
1590
|
+
return new MoonbaseStorefront(configuration, new import_storefront_api11.MoonbaseClient(configuration), { initialCatalog, autoApplyItemOffers });
|
|
1591
|
+
}
|
|
1592
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1593
|
+
0 && (module.exports = {
|
|
1594
|
+
MoonbaseStorefront,
|
|
1595
|
+
StorefrontProvider,
|
|
1596
|
+
createStorefront,
|
|
1597
|
+
useActivationRequest,
|
|
1598
|
+
useAuth,
|
|
1599
|
+
useBundle,
|
|
1600
|
+
useBundles,
|
|
1601
|
+
useCart,
|
|
1602
|
+
useCartOffer,
|
|
1603
|
+
useCatalog,
|
|
1604
|
+
useCheckout,
|
|
1605
|
+
useCommunicationPreferences,
|
|
1606
|
+
useEligibleOffers,
|
|
1607
|
+
useGroups,
|
|
1608
|
+
useInventory,
|
|
1609
|
+
useLockedOffers,
|
|
1610
|
+
useOffer,
|
|
1611
|
+
useOffers,
|
|
1612
|
+
useOrders,
|
|
1613
|
+
useProduct,
|
|
1614
|
+
useProducts,
|
|
1615
|
+
usePromotions,
|
|
1616
|
+
useReviews,
|
|
1617
|
+
useStorefront,
|
|
1618
|
+
useStorefrontEvent,
|
|
1619
|
+
useStorefrontState,
|
|
1620
|
+
useVendor,
|
|
1621
|
+
useVoucher,
|
|
1622
|
+
...require("@moonbase.sh/storefront-api")
|
|
1623
|
+
});
|