@konfiqo/storefront-react 0.0.0-stage → 0.5.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/dist/index.cjs ADDED
@@ -0,0 +1,1153 @@
1
+ "use strict";
2
+ "use client";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/index.ts
32
+ var index_exports = {};
33
+ __export(index_exports, {
34
+ CheckoutChallenge: () => CheckoutChallenge,
35
+ Content: () => Content,
36
+ ORDER_POLL_MAX_MS: () => ORDER_POLL_MAX_MS,
37
+ ORDER_POLL_MIN_MS: () => ORDER_POLL_MIN_MS,
38
+ PaymentForm: () => PaymentForm,
39
+ StorefrontProvider: () => StorefrontProvider,
40
+ defaultCartStorage: () => defaultCartStorage,
41
+ isDeadCartError: () => isDeadCartError,
42
+ isOrderSettled: () => isOrderSettled,
43
+ orderPollDelay: () => orderPollDelay,
44
+ renderContent: () => renderContent,
45
+ useAccount: () => useAccount,
46
+ useCart: () => useCart,
47
+ useCartStorage: () => useCartStorage,
48
+ useCategories: () => useCategories,
49
+ useCheckout: () => useCheckout,
50
+ useOrder: () => useOrder,
51
+ useProduct: () => useProduct,
52
+ useProducts: () => useProducts,
53
+ useStore: () => useStore,
54
+ useStorefrontClient: () => useStorefrontClient
55
+ });
56
+ module.exports = __toCommonJS(index_exports);
57
+
58
+ // src/provider.tsx
59
+ var import_react = require("react");
60
+ var import_storefront_sdk2 = require("@konfiqo/storefront-sdk");
61
+
62
+ // src/cart-store.ts
63
+ var import_storefront_sdk = require("@konfiqo/storefront-sdk");
64
+ function isOrderedCartError(e) {
65
+ return (0, import_storefront_sdk.isStorefrontError)(e) && e.code === "cart_read_only" && e.details.status === "ordered";
66
+ }
67
+ function isDeadCartError(e) {
68
+ if (!(0, import_storefront_sdk.isStorefrontError)(e)) return false;
69
+ if (e.code === "cart_not_found") return true;
70
+ return e.code === "cart_read_only" && e.details.status === "expired";
71
+ }
72
+ var toError = (e) => e instanceof Error ? e : new Error(String(e));
73
+ var CartStore = class {
74
+ /**
75
+ * @param getClient - the provider's current client (read per call, so
76
+ * a new client — e.g. another `fetch` — keeps this cart state)
77
+ */
78
+ constructor(getClient, storeId, storage) {
79
+ this.getClient = getClient;
80
+ this.storeId = storeId;
81
+ this.storage = storage;
82
+ }
83
+ getClient;
84
+ storeId;
85
+ storage;
86
+ cartState = {
87
+ cart: null,
88
+ status: "idle",
89
+ isUpdating: false,
90
+ error: null,
91
+ previousCartId: null
92
+ };
93
+ checkoutState = {
94
+ isPending: false,
95
+ result: null,
96
+ error: null,
97
+ attempts: 0
98
+ };
99
+ listeners = /* @__PURE__ */ new Set();
100
+ queue = Promise.resolve();
101
+ cartId = null;
102
+ loadPromise = null;
103
+ reads = new AbortController();
104
+ pendingCheckout = null;
105
+ pendingWrites = 0;
106
+ /**
107
+ * Bumped by `reset()` (and a cart id changed in another tab): a queued
108
+ * operation that started under an older epoch drops its outcome instead
109
+ * of resurrecting (or persisting) the cart it was working on.
110
+ */
111
+ epoch = 0;
112
+ /**
113
+ * Bumped by `reset()` only. A checkout in flight keeps its outcome (the
114
+ * once-only order token) when another tab merely changes the cart id.
115
+ */
116
+ resetEpoch = 0;
117
+ /** Whether a checkout was started under this provider. */
118
+ checkoutStarted = false;
119
+ get client() {
120
+ return this.getClient();
121
+ }
122
+ // ------------------------------------------------------ subscription
123
+ subscribe = (listener) => {
124
+ this.listeners.add(listener);
125
+ return () => this.listeners.delete(listener);
126
+ };
127
+ getCart = () => this.cartState;
128
+ getCheckout = () => this.checkoutState;
129
+ setCart(patch) {
130
+ this.cartState = { ...this.cartState, ...patch };
131
+ this.emit();
132
+ }
133
+ setCheckout(patch) {
134
+ this.checkoutState = { ...this.checkoutState, ...patch };
135
+ this.emit();
136
+ }
137
+ emit() {
138
+ for (const l of this.listeners) l();
139
+ }
140
+ /** Runs `fn` after everything queued before it. */
141
+ enqueue(fn) {
142
+ const run = this.queue.then(fn);
143
+ this.queue = run.then(
144
+ () => void 0,
145
+ () => void 0
146
+ );
147
+ return run;
148
+ }
149
+ currentId() {
150
+ return this.cartId ?? (0, import_storefront_sdk.loadCartId)(this.storage(), this.storeId);
151
+ }
152
+ /** Forgets the cart: the next write creates a new one. */
153
+ forget() {
154
+ this.cartId = null;
155
+ (0, import_storefront_sdk.clearCartId)(this.storage(), this.storeId);
156
+ }
157
+ /** Puts a server cart view into the state (an expired cart is forgotten). */
158
+ apply(cart) {
159
+ if (cart.status === "expired") {
160
+ this.forget();
161
+ this.setCart({ cart: null, status: "ready", error: null });
162
+ return;
163
+ }
164
+ if (this.cartId !== cart.id) {
165
+ this.cartId = cart.id;
166
+ (0, import_storefront_sdk.saveCartId)(this.storage(), this.storeId, cart.id);
167
+ }
168
+ this.setCart({ cart, status: "ready", error: null });
169
+ }
170
+ // ------------------------------------------------------ reads
171
+ /** Reads the saved cart once (later calls share the first read). */
172
+ load = () => {
173
+ this.loadPromise ??= this.read();
174
+ return this.loadPromise;
175
+ };
176
+ /**
177
+ * Reads the cart again. Also how a cart whose payment failed shows up
178
+ * as `open` again: the read reopens it on the server.
179
+ */
180
+ refresh = () => this.read();
181
+ /** Cancels pending cart reads (the provider unmounted). */
182
+ abortReads() {
183
+ this.reads.abort();
184
+ this.reads = new AbortController();
185
+ this.loadPromise = null;
186
+ }
187
+ read() {
188
+ const signal = this.reads.signal;
189
+ return this.enqueue(async () => {
190
+ if (signal.aborted) {
191
+ if (this.cartState.status === "loading")
192
+ this.setCart({ status: "idle" });
193
+ return;
194
+ }
195
+ const epoch = this.epoch;
196
+ const id = this.currentId();
197
+ if (!id) {
198
+ this.setCart({ cart: null, status: "ready" });
199
+ return;
200
+ }
201
+ this.cartId = id;
202
+ if (this.cartState.cart === null) this.setCart({ status: "loading" });
203
+ try {
204
+ const cart = await this.client.carts.get(id, { signal });
205
+ if (epoch !== this.epoch) return;
206
+ this.apply(cart);
207
+ } catch (e) {
208
+ if (epoch !== this.epoch) return;
209
+ if (signal.aborted) {
210
+ if (this.cartState.status === "loading")
211
+ this.setCart({ status: "idle" });
212
+ return;
213
+ }
214
+ if (isDeadCartError(e)) {
215
+ this.forget();
216
+ this.setCart({ cart: null, status: "ready", error: null });
217
+ return;
218
+ }
219
+ this.setCart({ status: "ready", error: toError(e) });
220
+ }
221
+ });
222
+ }
223
+ // ------------------------------------------------------ writes
224
+ write(op) {
225
+ this.pendingWrites++;
226
+ this.setCart({ isUpdating: true });
227
+ return this.enqueue(async () => {
228
+ const epoch = this.epoch;
229
+ const current = () => epoch === this.epoch;
230
+ const attempt = async () => {
231
+ let id = this.currentId();
232
+ if (!id) {
233
+ const created = await this.client.carts.create();
234
+ if (!current()) {
235
+ throw new import_storefront_sdk.StorefrontError(
236
+ "aborted",
237
+ 0,
238
+ "The cart was reset while the write was pending",
239
+ void 0
240
+ );
241
+ }
242
+ this.apply(created);
243
+ id = created.id;
244
+ }
245
+ return op(id);
246
+ };
247
+ try {
248
+ let cart;
249
+ try {
250
+ cart = await attempt();
251
+ } catch (e) {
252
+ if (!current() || !isOrderedCartError(e)) throw e;
253
+ const previousCartId = this.currentId();
254
+ this.forget();
255
+ this.setCart({ cart: null, previousCartId });
256
+ cart = await attempt();
257
+ }
258
+ if (current()) this.apply(cart);
259
+ return cart;
260
+ } catch (e) {
261
+ if (current()) {
262
+ if (isDeadCartError(e)) {
263
+ this.forget();
264
+ this.setCart({ cart: null, status: "ready" });
265
+ }
266
+ this.setCart({ error: toError(e) });
267
+ }
268
+ throw e;
269
+ } finally {
270
+ this.pendingWrites--;
271
+ if (this.pendingWrites === 0) this.setCart({ isUpdating: false });
272
+ }
273
+ });
274
+ }
275
+ addLine = (input) => this.write((id) => this.client.carts.addLine(id, input));
276
+ updateLine = (lineId, input) => this.write((id) => this.client.carts.updateLine(id, lineId, input));
277
+ removeLine = (lineId) => this.write((id) => this.client.carts.removeLine(id, lineId));
278
+ setCustomer = (input) => this.write((id) => this.client.carts.setCustomer(id, input));
279
+ setAddress = (input) => this.write((id) => this.client.carts.setAddress(id, input));
280
+ setShippingOption = (optionId) => this.write((id) => this.client.carts.setShippingOption(id, optionId));
281
+ /** The shipping options of the cart (empty when there is no cart yet). */
282
+ shippingOptions = async (options) => {
283
+ const id = this.currentId();
284
+ if (!id) return { items: [] };
285
+ return this.client.carts.shippingOptions(id, options);
286
+ };
287
+ /**
288
+ * Forgets the cart (e.g. once its order is paid): the next write
289
+ * creates a new one. The old cart is not deleted on the server.
290
+ */
291
+ reset = () => {
292
+ this.epoch++;
293
+ this.resetEpoch++;
294
+ this.forget();
295
+ this.loadPromise = null;
296
+ this.setCart({
297
+ cart: null,
298
+ status: "ready",
299
+ error: null,
300
+ previousCartId: null
301
+ });
302
+ this.setCheckout({ result: null, error: null });
303
+ };
304
+ /**
305
+ * The saved cart id changed in another tab (a `storage` event for this
306
+ * store's key): follow it. Operations in flight on the old cart drop
307
+ * their outcome.
308
+ */
309
+ syncFromStorage = () => {
310
+ const id = (0, import_storefront_sdk.loadCartId)(this.storage(), this.storeId);
311
+ if (id === this.cartId) return;
312
+ this.epoch++;
313
+ this.cartId = id;
314
+ this.loadPromise = null;
315
+ if (id === null) {
316
+ this.setCart({ cart: null, status: "ready", error: null });
317
+ return;
318
+ }
319
+ void this.refresh();
320
+ };
321
+ /** The storage key this store persists its cart id under. */
322
+ get storageKey() {
323
+ return (0, import_storefront_sdk.cartIdKey)(this.storeId);
324
+ }
325
+ /** The storage the cart id is kept in (null: memory only). */
326
+ currentStorage() {
327
+ return this.storage();
328
+ }
329
+ // ------------------------------------------------------ checkout
330
+ /**
331
+ * Checks the cart out. Never aborted (the server may place the order
332
+ * anyway); a second call while one is in flight returns the same
333
+ * promise. The cart is read again afterwards.
334
+ */
335
+ checkout = (options = {}) => {
336
+ if (this.pendingCheckout) return this.pendingCheckout;
337
+ this.checkoutStarted = true;
338
+ this.setCheckout({ isPending: true, error: null });
339
+ let epoch = this.resetEpoch;
340
+ const run = this.enqueue(async () => {
341
+ epoch = this.resetEpoch;
342
+ const id = this.currentId();
343
+ if (!id) {
344
+ throw new import_storefront_sdk.StorefrontError(
345
+ "checkout_incomplete",
346
+ 0,
347
+ "There is no cart to check out",
348
+ { missing: ["lines"] }
349
+ );
350
+ }
351
+ return this.client.carts.checkout(id, {
352
+ turnstileToken: options.turnstileToken || void 0
353
+ });
354
+ });
355
+ this.pendingCheckout = run;
356
+ run.then(
357
+ (result) => this.settleCheckout(epoch, { result, error: null }),
358
+ (e) => this.settleCheckout(epoch, { result: null, error: toError(e) })
359
+ );
360
+ return run;
361
+ };
362
+ settleCheckout(epoch, patch) {
363
+ this.pendingCheckout = null;
364
+ this.setCheckout({
365
+ // After `reset()` the outcome belongs to a cart the buyer left.
366
+ ...epoch === this.resetEpoch ? patch : {},
367
+ isPending: false,
368
+ attempts: this.checkoutState.attempts + 1
369
+ });
370
+ void this.refresh();
371
+ }
372
+ /** Clears the last checkout result and error. */
373
+ clearCheckout = () => {
374
+ this.setCheckout({ result: null, error: null });
375
+ };
376
+ };
377
+ function defaultCartStorage() {
378
+ if (typeof window === "undefined") return null;
379
+ let local = null;
380
+ try {
381
+ local = window.localStorage;
382
+ } catch {
383
+ local = null;
384
+ }
385
+ const cookie = (0, import_storefront_sdk.cookieCartStorage)();
386
+ const attempt = (f) => {
387
+ try {
388
+ f();
389
+ return true;
390
+ } catch {
391
+ return false;
392
+ }
393
+ };
394
+ const tombstoneKey = (key) => `${key}:cleared`;
395
+ const legacyMarkerKey = (key) => `${key}:in-cookie`;
396
+ const cleared = (key) => {
397
+ try {
398
+ return local?.getItem(tombstoneKey(key)) === "1";
399
+ } catch {
400
+ return false;
401
+ }
402
+ };
403
+ const storage = {
404
+ // The area a `storage` event of another tab names.
405
+ storageArea: local,
406
+ getItem(key) {
407
+ let fromCookie = null;
408
+ try {
409
+ fromCookie = cookie.getItem(key);
410
+ } catch {
411
+ fromCookie = null;
412
+ }
413
+ if (fromCookie) {
414
+ attempt(() => cookie.setItem(key, fromCookie));
415
+ return fromCookie;
416
+ }
417
+ let fromLocal = null;
418
+ try {
419
+ fromLocal = local?.getItem(key) ?? null;
420
+ } catch {
421
+ fromLocal = null;
422
+ }
423
+ if (!fromLocal) return null;
424
+ if (cleared(key)) return null;
425
+ attempt(() => cookie.setItem(key, fromLocal));
426
+ return fromLocal;
427
+ },
428
+ setItem(key, value) {
429
+ const a = attempt(() => cookie.setItem(key, value));
430
+ const b = local ? attempt(() => local.setItem(key, value)) : false;
431
+ if (local) {
432
+ attempt(() => local.removeItem(tombstoneKey(key)));
433
+ attempt(() => local.removeItem(legacyMarkerKey(key)));
434
+ }
435
+ if (!a && !b) throw new Error("no cart storage available");
436
+ },
437
+ removeItem(key) {
438
+ attempt(() => cookie.removeItem(key));
439
+ if (local) {
440
+ attempt(() => local.removeItem(key));
441
+ attempt(() => local.setItem(tombstoneKey(key), "1"));
442
+ attempt(() => local.removeItem(legacyMarkerKey(key)));
443
+ }
444
+ }
445
+ };
446
+ return storage;
447
+ }
448
+
449
+ // src/provider.tsx
450
+ var import_jsx_runtime = require("react/jsx-runtime");
451
+ var StorefrontContext = (0, import_react.createContext)(null);
452
+ function StorefrontProvider({
453
+ storeId,
454
+ client,
455
+ config,
456
+ cartStorage,
457
+ children
458
+ }) {
459
+ const forbidden = ["serverKey", "trustedStorefrontKey", "buyerIp"].filter(
460
+ (k) => config !== void 0 && k in config
461
+ );
462
+ if (forbidden.length > 0) {
463
+ throw new Error(
464
+ `StorefrontProvider: config.${forbidden.join(", config.")} must not be passed to a client component (it would reach the browser). Create a server-side client instead.`
465
+ );
466
+ }
467
+ const baseUrl = config?.baseUrl;
468
+ const publishableKey = config?.publishableKey;
469
+ const timeoutMs = config?.timeoutMs;
470
+ const customFetch = config?.fetch;
471
+ const resolved = (0, import_react.useMemo)(() => {
472
+ if (client) return client;
473
+ if (baseUrl === void 0 || publishableKey === void 0) {
474
+ throw new Error("StorefrontProvider: pass `client` or `config`");
475
+ }
476
+ return (0, import_storefront_sdk2.createStorefrontClient)({
477
+ baseUrl,
478
+ publishableKey,
479
+ timeoutMs,
480
+ fetch: customFetch
481
+ });
482
+ }, [client, baseUrl, publishableKey, timeoutMs, customFetch]);
483
+ const clientRef = (0, import_react.useRef)(resolved);
484
+ clientRef.current = resolved;
485
+ const storageRef = (0, import_react.useRef)(cartStorage);
486
+ storageRef.current = cartStorage;
487
+ const cart = (0, import_react.useMemo)(
488
+ () => new CartStore(
489
+ () => clientRef.current,
490
+ storeId,
491
+ () => storageRef.current === void 0 ? defaultCartStorage() : storageRef.current
492
+ ),
493
+ [storeId]
494
+ );
495
+ (0, import_react.useEffect)(() => () => cart.abortReads(), [cart]);
496
+ (0, import_react.useEffect)(() => {
497
+ if (typeof window === "undefined") return;
498
+ const onStorage = (e) => {
499
+ const storage = cart.currentStorage();
500
+ if (!storage) return;
501
+ const area = storage.storageArea;
502
+ if (e.storageArea !== (area ?? storage)) return;
503
+ if (e.key !== null && e.key !== cart.storageKey) return;
504
+ cart.syncFromStorage();
505
+ };
506
+ window.addEventListener("storage", onStorage);
507
+ return () => window.removeEventListener("storage", onStorage);
508
+ }, [cart]);
509
+ const value = (0, import_react.useMemo)(
510
+ () => ({ client: resolved, storeId, cart }),
511
+ [resolved, storeId, cart]
512
+ );
513
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StorefrontContext.Provider, { value, children });
514
+ }
515
+ function useStorefrontContext() {
516
+ const ctx = (0, import_react.useContext)(StorefrontContext);
517
+ if (!ctx) {
518
+ throw new Error(
519
+ "Storefront hooks must be used inside <StorefrontProvider>"
520
+ );
521
+ }
522
+ return ctx;
523
+ }
524
+ function useOptionalStorefrontContext() {
525
+ return (0, import_react.useContext)(StorefrontContext);
526
+ }
527
+ function useStorefrontClient() {
528
+ return useStorefrontContext().client;
529
+ }
530
+
531
+ // src/use-resource.ts
532
+ var import_react2 = require("react");
533
+ var toError2 = (e) => e instanceof Error ? e : new Error(String(e));
534
+ function useResource(key, deps, fetcher) {
535
+ const [state, setState] = (0, import_react2.useState)({
536
+ key: null,
537
+ data: null,
538
+ error: null,
539
+ isLoading: key !== null
540
+ });
541
+ const [nonce, setNonce] = (0, import_react2.useState)(0);
542
+ const fetcherRef = (0, import_react2.useRef)(fetcher);
543
+ (0, import_react2.useEffect)(() => {
544
+ fetcherRef.current = fetcher;
545
+ });
546
+ (0, import_react2.useEffect)(() => {
547
+ if (key === null) {
548
+ setState({ key, data: null, error: null, isLoading: false });
549
+ return;
550
+ }
551
+ const controller = new AbortController();
552
+ setState(
553
+ (s) => s.key === key ? { ...s, isLoading: true } : { key, data: null, error: null, isLoading: true }
554
+ );
555
+ fetcherRef.current(controller.signal).then(
556
+ (data) => {
557
+ if (!controller.signal.aborted)
558
+ setState({ key, data, error: null, isLoading: false });
559
+ },
560
+ (e) => {
561
+ if (!controller.signal.aborted)
562
+ setState({ key, data: null, error: toError2(e), isLoading: false });
563
+ }
564
+ );
565
+ return () => controller.abort();
566
+ }, [key, deps, nonce]);
567
+ const refetch = (0, import_react2.useCallback)(() => setNonce((n) => n + 1), []);
568
+ if (state.key !== key) {
569
+ return { data: null, error: null, isLoading: key !== null, refetch };
570
+ }
571
+ return {
572
+ data: state.data,
573
+ error: state.error,
574
+ isLoading: state.isLoading,
575
+ refetch
576
+ };
577
+ }
578
+
579
+ // src/catalog.ts
580
+ function useStore() {
581
+ const { client } = useStorefrontContext();
582
+ return useResource("store", client, (signal) => client.store.get({ signal }));
583
+ }
584
+ function useCategories() {
585
+ const { client } = useStorefrontContext();
586
+ return useResource(
587
+ "categories",
588
+ client,
589
+ (signal) => client.categories.list({ signal })
590
+ );
591
+ }
592
+ function useProducts(params = {}) {
593
+ const { client } = useStorefrontContext();
594
+ const query = {
595
+ category: params.category,
596
+ q: params.q,
597
+ page: params.page,
598
+ pageSize: params.pageSize
599
+ };
600
+ return useResource(
601
+ JSON.stringify(query),
602
+ client,
603
+ (signal) => client.products.list(query, { signal })
604
+ );
605
+ }
606
+ function useProduct(slug) {
607
+ const { client } = useStorefrontContext();
608
+ return useResource(
609
+ slug ? `product:${slug}` : null,
610
+ client,
611
+ (signal) => client.products.get(slug, { signal })
612
+ );
613
+ }
614
+
615
+ // src/use-cart.ts
616
+ var import_react3 = require("react");
617
+ var SERVER_CART = {
618
+ cart: null,
619
+ status: "idle",
620
+ isUpdating: false,
621
+ error: null,
622
+ previousCartId: null
623
+ };
624
+ function useCart() {
625
+ const { cart: store } = useStorefrontContext();
626
+ const snapshot = (0, import_react3.useSyncExternalStore)(
627
+ store.subscribe,
628
+ store.getCart,
629
+ () => SERVER_CART
630
+ );
631
+ (0, import_react3.useEffect)(() => {
632
+ void store.load();
633
+ }, [store]);
634
+ const itemCount = snapshot.cart?.lines.reduce((n, line) => n + line.quantity, 0) ?? 0;
635
+ return {
636
+ ...snapshot,
637
+ itemCount,
638
+ addLine: store.addLine,
639
+ updateLine: store.updateLine,
640
+ removeLine: store.removeLine,
641
+ setCustomer: store.setCustomer,
642
+ setAddress: store.setAddress,
643
+ setShippingOption: store.setShippingOption,
644
+ shippingOptions: store.shippingOptions,
645
+ refresh: store.refresh,
646
+ reset: store.reset
647
+ };
648
+ }
649
+ function useCartStorage() {
650
+ const { cart } = useStorefrontContext();
651
+ return (0, import_react3.useMemo)(() => () => cart.currentStorage(), [cart]);
652
+ }
653
+
654
+ // src/use-account.ts
655
+ var import_react4 = require("react");
656
+ var import_storefront_sdk3 = require("@konfiqo/storefront-sdk");
657
+ function useAccount() {
658
+ const { client } = useStorefrontContext();
659
+ const [state, setState] = (0, import_react4.useState)({
660
+ account: null,
661
+ status: "loading",
662
+ error: null
663
+ });
664
+ const seq = (0, import_react4.useRef)(0);
665
+ const alive = (0, import_react4.useRef)(true);
666
+ const refresh = (0, import_react4.useCallback)(async () => {
667
+ const mine = ++seq.current;
668
+ try {
669
+ const account = await client.account.get();
670
+ if (!alive.current || mine !== seq.current) return;
671
+ setState({ account, status: "signedIn", error: null });
672
+ } catch (e) {
673
+ if (!alive.current || mine !== seq.current) return;
674
+ if ((0, import_storefront_sdk3.isStorefrontError)(e) && e.status === 401) {
675
+ setState({ account: null, status: "signedOut", error: null });
676
+ return;
677
+ }
678
+ const error = e instanceof Error ? e : new Error(String(e));
679
+ setState((s) => ({
680
+ account: s.account,
681
+ status: s.account ? "signedIn" : "signedOut",
682
+ error
683
+ }));
684
+ }
685
+ }, [client]);
686
+ (0, import_react4.useEffect)(() => {
687
+ alive.current = true;
688
+ void refresh();
689
+ return () => {
690
+ alive.current = false;
691
+ };
692
+ }, [refresh]);
693
+ return { ...state, refresh };
694
+ }
695
+
696
+ // src/use-checkout.ts
697
+ var import_react5 = require("react");
698
+ var SERVER_CHECKOUT = {
699
+ isPending: false,
700
+ result: null,
701
+ error: null,
702
+ attempts: 0
703
+ };
704
+ function useCheckout() {
705
+ const { cart: store } = useStorefrontContext();
706
+ const snapshot = (0, import_react5.useSyncExternalStore)(
707
+ store.subscribe,
708
+ store.getCheckout,
709
+ () => SERVER_CHECKOUT
710
+ );
711
+ (0, import_react5.useEffect)(() => {
712
+ if (store.checkoutStarted) void store.refresh();
713
+ }, [store]);
714
+ const checkout = (0, import_react5.useCallback)(
715
+ (options = {}) => store.checkout({ turnstileToken: options.turnstileToken ?? void 0 }),
716
+ [store]
717
+ );
718
+ return { ...snapshot, checkout, reset: store.clearCheckout };
719
+ }
720
+ function useCheckoutAttempts() {
721
+ const ctx = useOptionalStorefrontContext();
722
+ const store = ctx?.cart;
723
+ return (0, import_react5.useSyncExternalStore)(
724
+ store?.subscribe ?? noopSubscribe,
725
+ () => store?.getCheckout().attempts ?? 0,
726
+ () => 0
727
+ );
728
+ }
729
+ var noopSubscribe = () => () => {
730
+ };
731
+
732
+ // src/use-order.ts
733
+ var import_react6 = require("react");
734
+ var import_storefront_sdk4 = require("@konfiqo/storefront-sdk");
735
+ var ORDER_POLL_MIN_MS = 2e3;
736
+ var ORDER_POLL_MAX_MS = 15e3;
737
+ function orderPollDelay(attempt) {
738
+ return Math.min(ORDER_POLL_MIN_MS * 2 ** attempt, ORDER_POLL_MAX_MS);
739
+ }
740
+ function isOrderSettled(order) {
741
+ if (order.status !== "pendingPayment") return true;
742
+ return order.paymentStatus === "failed" || order.paymentStatus === "expired";
743
+ }
744
+ function isTransient(e) {
745
+ if (!(0, import_storefront_sdk4.isStorefrontError)(e)) return false;
746
+ switch (e.code) {
747
+ case "network_error":
748
+ case "timeout":
749
+ case "rate_limited":
750
+ case "order_unavailable":
751
+ case "http_error":
752
+ return true;
753
+ default:
754
+ return false;
755
+ }
756
+ }
757
+ function useOrder(orderId, token, options = {}) {
758
+ const { client } = useStorefrontContext();
759
+ const poll = options.pollUntilFinal ?? false;
760
+ const key = orderId && token ? `${orderId} ${token}` : null;
761
+ const [state, setState] = (0, import_react6.useState)({
762
+ key: null,
763
+ order: null,
764
+ error: null,
765
+ isPolling: false
766
+ });
767
+ const [nonce, setNonce] = (0, import_react6.useState)(0);
768
+ (0, import_react6.useEffect)(() => {
769
+ if (!orderId || !token) {
770
+ setState({ key: null, order: null, error: null, isPolling: false });
771
+ return;
772
+ }
773
+ const k = `${orderId} ${token}`;
774
+ const controller = new AbortController();
775
+ let timer;
776
+ let attempt = 0;
777
+ const schedule = (atLeastMs) => {
778
+ const delay = Math.max(orderPollDelay(attempt++), atLeastMs);
779
+ setState((s) => ({ ...s, isPolling: true }));
780
+ timer = setTimeout(tick, delay);
781
+ };
782
+ const tick = async () => {
783
+ try {
784
+ const order = await client.orders.get(orderId, token, {
785
+ signal: controller.signal
786
+ });
787
+ if (controller.signal.aborted) return;
788
+ setState({ key: k, order, error: null, isPolling: false });
789
+ if (poll && !isOrderSettled(order)) schedule(0);
790
+ } catch (e) {
791
+ if (controller.signal.aborted) return;
792
+ const error = e instanceof Error ? e : new Error(String(e));
793
+ setState((s) => ({
794
+ key: k,
795
+ order: s.key === k ? s.order : null,
796
+ error,
797
+ isPolling: false
798
+ }));
799
+ if (poll && isTransient(e)) {
800
+ const retryAfter = (0, import_storefront_sdk4.isStorefrontError)(e) && e.code === "rate_limited" ? (e.details.retryAfter ?? 0) * 1e3 : 0;
801
+ schedule(retryAfter);
802
+ }
803
+ }
804
+ };
805
+ void tick();
806
+ return () => {
807
+ controller.abort();
808
+ clearTimeout(timer);
809
+ };
810
+ }, [client, orderId, token, poll, nonce]);
811
+ const refetch = (0, import_react6.useCallback)(() => setNonce((n) => n + 1), []);
812
+ if (state.key !== key) {
813
+ return {
814
+ order: null,
815
+ error: null,
816
+ isLoading: key !== null,
817
+ isPolling: false,
818
+ refetch
819
+ };
820
+ }
821
+ return {
822
+ order: state.order,
823
+ error: state.error,
824
+ isLoading: false,
825
+ isPolling: state.isPolling,
826
+ refetch
827
+ };
828
+ }
829
+
830
+ // src/payment-form.tsx
831
+ var import_react7 = require("react");
832
+ var import_storefront_sdk5 = require("@konfiqo/storefront-sdk");
833
+ var import_jsx_runtime2 = require("react/jsx-runtime");
834
+ var embeddedContent = (p) => p.presentation === "embedded" && typeof p.embed.content === "string" ? p.embed.content : null;
835
+ function PaymentForm({
836
+ presentation,
837
+ onClosed,
838
+ onUnsupported,
839
+ onError,
840
+ ...divProps
841
+ }) {
842
+ const ref = (0, import_react7.useRef)(null);
843
+ const callbacks = (0, import_react7.useRef)({ onClosed, onUnsupported, onError });
844
+ (0, import_react7.useEffect)(() => {
845
+ callbacks.current = { onClosed, onUnsupported, onError };
846
+ });
847
+ const pending = (0, import_react7.useRef)(null);
848
+ const navigated = (0, import_react7.useRef)(null);
849
+ (0, import_react7.useEffect)(() => {
850
+ const element = ref.current;
851
+ if (!element) return;
852
+ const prev = pending.current;
853
+ pending.current = null;
854
+ if (prev) {
855
+ clearTimeout(prev.timer);
856
+ if (prev.content === null || prev.content !== embeddedContent(presentation))
857
+ prev.unmount();
858
+ }
859
+ if (presentation.presentation !== "embedded") {
860
+ if (navigated.current === presentation) return;
861
+ navigated.current = presentation;
862
+ }
863
+ let unmount = null;
864
+ try {
865
+ const mount = (0, import_storefront_sdk5.mountPayment)(element, presentation, {
866
+ onClosed: (page) => callbacks.current.onClosed?.(page)
867
+ });
868
+ if (mount.kind === "embedded") unmount = mount.unmount;
869
+ else if (mount.kind === "unsupported")
870
+ callbacks.current.onUnsupported?.(mount.embedKind);
871
+ } catch (e) {
872
+ callbacks.current.onError?.(
873
+ e instanceof Error ? e : new Error(String(e))
874
+ );
875
+ }
876
+ if (!unmount) return;
877
+ const remove = unmount;
878
+ return () => {
879
+ const entry = {
880
+ content: embeddedContent(presentation),
881
+ unmount: remove,
882
+ timer: setTimeout(() => {
883
+ if (pending.current === entry) pending.current = null;
884
+ remove();
885
+ }, 0)
886
+ };
887
+ pending.current = entry;
888
+ };
889
+ }, [presentation]);
890
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { ...divProps, ref });
891
+ }
892
+
893
+ // src/checkout-challenge.tsx
894
+ var import_react8 = require("react");
895
+ var import_storefront_sdk6 = require("@konfiqo/storefront-sdk");
896
+ var import_jsx_runtime3 = require("react/jsx-runtime");
897
+ var CheckoutChallenge = (0, import_react8.forwardRef)(function CheckoutChallenge2({ siteKey, onToken, onExpired, onError, ...divProps }, handle) {
898
+ const ref = (0, import_react8.useRef)(null);
899
+ const widget = (0, import_react8.useRef)(null);
900
+ const callbacks = (0, import_react8.useRef)({ onToken, onExpired, onError });
901
+ (0, import_react8.useEffect)(() => {
902
+ callbacks.current = { onToken, onExpired, onError };
903
+ });
904
+ (0, import_react8.useEffect)(() => {
905
+ const element = ref.current;
906
+ if (!element || !siteKey) return;
907
+ let active = true;
908
+ let rendered = null;
909
+ (0, import_storefront_sdk6.renderTurnstile)(element, siteKey, {
910
+ onToken: (t) => callbacks.current.onToken(t),
911
+ onExpired: () => callbacks.current.onExpired?.(),
912
+ onError: (code) => callbacks.current.onError?.(code)
913
+ }).then(
914
+ (w) => {
915
+ if (!active) {
916
+ w.remove();
917
+ return;
918
+ }
919
+ rendered = w;
920
+ widget.current = w;
921
+ },
922
+ (e) => {
923
+ if (active)
924
+ callbacks.current.onError?.(
925
+ e instanceof Error ? e : new Error(String(e))
926
+ );
927
+ }
928
+ );
929
+ return () => {
930
+ active = false;
931
+ if (rendered) {
932
+ rendered.remove();
933
+ if (widget.current === rendered) widget.current = null;
934
+ }
935
+ };
936
+ }, [siteKey]);
937
+ const reset = () => {
938
+ if (!widget.current) return;
939
+ callbacks.current.onExpired?.();
940
+ widget.current.reset();
941
+ };
942
+ (0, import_react8.useImperativeHandle)(handle, () => ({ reset }), []);
943
+ const attempts = useCheckoutAttempts();
944
+ const seen = (0, import_react8.useRef)(attempts);
945
+ (0, import_react8.useEffect)(() => {
946
+ if (attempts === seen.current) return;
947
+ seen.current = attempts;
948
+ reset();
949
+ });
950
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { ...divProps, ref });
951
+ });
952
+
953
+ // src/content.tsx
954
+ var import_markdoc = __toESM(require("@markdoc/markdoc"), 1);
955
+ var React = __toESM(require("react"), 1);
956
+ var import_react9 = require("react");
957
+ var import_storefront_sdk7 = require("@konfiqo/storefront-sdk");
958
+ var import_jsx_runtime4 = require("react/jsx-runtime");
959
+ var HTML_TAGS = new Set(
960
+ "article section div span p h1 h2 h3 h4 h5 h6 ul ol li strong em s del code pre blockquote hr br a table thead tbody tr th td figure figcaption small sub sup mark".split(" ")
961
+ );
962
+ var HTML_ATTRS = /* @__PURE__ */ new Set([
963
+ "class",
964
+ "title",
965
+ "align",
966
+ "colspan",
967
+ "rowspan",
968
+ "start"
969
+ ]);
970
+ var MAX_DEPTH = 40;
971
+ var MAX_NODES = 5e3;
972
+ var hasControl = (s) => Array.from(s).some((c) => {
973
+ const n = c.charCodeAt(0);
974
+ return n < 32 || n === 127;
975
+ });
976
+ function safeHref(v) {
977
+ if (typeof v !== "string") return null;
978
+ const href = v.trim();
979
+ if (href === "" || /\s/.test(href) || hasControl(href)) return null;
980
+ if (href.includes("\\") || /%5c/i.test(href)) return null;
981
+ if (href.startsWith("#")) return href;
982
+ if (href.startsWith("/")) return href[1] === "/" ? null : href;
983
+ return /^(https?:|mailto:|tel:)/i.test(href) ? href : null;
984
+ }
985
+ var isProp = (v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean";
986
+ function clean(node, w, depth) {
987
+ if (typeof node === "string") return node;
988
+ if (node === null || typeof node !== "object") return null;
989
+ const n = node;
990
+ if (n.$$mdtype !== "Tag" || typeof n.name !== "string" || depth > MAX_DEPTH || ++w.nodes > MAX_NODES) {
991
+ return null;
992
+ }
993
+ const name = n.name;
994
+ const raw = n.attributes && typeof n.attributes === "object" ? n.attributes : {};
995
+ const attributes = {};
996
+ if (name === "") return null;
997
+ const isHtml = name[0] === name[0].toLowerCase();
998
+ if (isHtml) {
999
+ if (!HTML_TAGS.has(name)) return null;
1000
+ for (const [k, v] of Object.entries(raw)) {
1001
+ if (name === "a" && k === "href") {
1002
+ const href = safeHref(v);
1003
+ if (href !== null) attributes.href = href;
1004
+ } else if (HTML_ATTRS.has(k) && isProp(v)) {
1005
+ attributes[k] = v;
1006
+ }
1007
+ }
1008
+ } else {
1009
+ if (!Object.hasOwn(w.components, name)) return null;
1010
+ for (const [k, v] of Object.entries(raw)) {
1011
+ if (!isProp(v)) continue;
1012
+ if (k === "ref" || k === "children" || /^on/i.test(k)) continue;
1013
+ if (k === "dangerouslySetInnerHTML") continue;
1014
+ if (k === "key") attributes.contentKey = v;
1015
+ else attributes[k] = v;
1016
+ }
1017
+ }
1018
+ const children = [];
1019
+ for (const c of Array.isArray(n.children) ? n.children : []) {
1020
+ const cleaned = clean(c, w, depth + 1);
1021
+ if (cleaned !== null) children.push(cleaned);
1022
+ }
1023
+ return { $$mdtype: "Tag", name, attributes, children };
1024
+ }
1025
+ var text = (v) => typeof v === "string" && v !== "" ? v : void 0;
1026
+ var slugOf = (v) => {
1027
+ const s = text(v);
1028
+ return s && !/[/\\?#]/.test(s) && s !== "." && s !== ".." ? s : null;
1029
+ };
1030
+ function ProductCard({
1031
+ product
1032
+ }) {
1033
+ const { client } = useStorefrontContext();
1034
+ const variant = product.variants[0];
1035
+ let price = null;
1036
+ try {
1037
+ price = variant ? (0, import_storefront_sdk7.formatMoney)(variant.priceMinor, variant.currency) : null;
1038
+ } catch {
1039
+ price = null;
1040
+ }
1041
+ let image = null;
1042
+ try {
1043
+ image = product.image ? client.media.url(product.image) : null;
1044
+ } catch {
1045
+ image = null;
1046
+ }
1047
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("a", { href: `/p/${encodeURIComponent(product.slug)}`, children: [
1048
+ image ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("img", { src: image, alt: "" }) : null,
1049
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { children: product.name }),
1050
+ price ? /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("span", { children: [
1051
+ " ",
1052
+ price
1053
+ ] }) : null
1054
+ ] });
1055
+ }
1056
+ function ProductGrid(props) {
1057
+ const category = text(props.category);
1058
+ const limit = Number(props.limit);
1059
+ const cap = Number.isInteger(limit) && limit > 0 ? Math.min(limit, 48) : 12;
1060
+ const { data } = useProducts({ category, pageSize: cap });
1061
+ if (!data) return null;
1062
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("ul", { className: "content-product-grid", children: data.items.slice(0, cap).map((p) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("li", { children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(ProductCard, { product: p }) }, p.id)) });
1063
+ }
1064
+ function ProductTag(props) {
1065
+ const { data } = useProduct(slugOf(props.slug));
1066
+ return data ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(ProductCard, { product: data }) : null;
1067
+ }
1068
+ function CategoryLink(props) {
1069
+ const slug = slugOf(props.slug);
1070
+ if (!slug) return null;
1071
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("a", { href: `/c/${encodeURIComponent(slug)}`, children: props.children ?? slug });
1072
+ }
1073
+ function ImageTag(props) {
1074
+ const { client } = useStorefrontContext();
1075
+ const key = text(props.contentKey);
1076
+ if (!key) return null;
1077
+ let src;
1078
+ try {
1079
+ src = client.media.url(key);
1080
+ } catch {
1081
+ return null;
1082
+ }
1083
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("img", { src, alt: text(props.alt) ?? "" });
1084
+ }
1085
+ function ButtonTag(props) {
1086
+ const href = safeHref(props.href);
1087
+ const label = text(props.label);
1088
+ if (!href || !label) return null;
1089
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("a", { className: "button", href, children: label });
1090
+ }
1091
+ var DEFAULT_COMPONENTS = {
1092
+ ProductGrid,
1093
+ Product: ProductTag,
1094
+ CategoryLink,
1095
+ Image: ImageTag,
1096
+ Button: ButtonTag
1097
+ };
1098
+ function renderContent(tree, components = {}) {
1099
+ try {
1100
+ const merged = { ...DEFAULT_COMPONENTS, ...components };
1101
+ const cleaned = clean(tree, { nodes: 0, components: merged }, 0);
1102
+ if (cleaned === null) return null;
1103
+ return import_markdoc.default.renderers.react(
1104
+ cleaned,
1105
+ React,
1106
+ { components: merged }
1107
+ );
1108
+ } catch {
1109
+ return null;
1110
+ }
1111
+ }
1112
+ function Content({ contentKey, components }) {
1113
+ const { client } = useStorefrontContext();
1114
+ const { data, error } = useResource(
1115
+ `content:${contentKey}`,
1116
+ client,
1117
+ (signal) => client.getContent(contentKey, { signal })
1118
+ );
1119
+ (0, import_react9.useEffect)(() => {
1120
+ if (error && typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
1121
+ console.warn(
1122
+ `<Content contentKey="${contentKey}">: ${error.message || "could not be read"}`
1123
+ );
1124
+ }
1125
+ }, [error, contentKey]);
1126
+ if (!data) return null;
1127
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_jsx_runtime4.Fragment, { children: renderContent(data.tree, components) });
1128
+ }
1129
+ // Annotate the CommonJS export names for ESM import in node:
1130
+ 0 && (module.exports = {
1131
+ CheckoutChallenge,
1132
+ Content,
1133
+ ORDER_POLL_MAX_MS,
1134
+ ORDER_POLL_MIN_MS,
1135
+ PaymentForm,
1136
+ StorefrontProvider,
1137
+ defaultCartStorage,
1138
+ isDeadCartError,
1139
+ isOrderSettled,
1140
+ orderPollDelay,
1141
+ renderContent,
1142
+ useAccount,
1143
+ useCart,
1144
+ useCartStorage,
1145
+ useCategories,
1146
+ useCheckout,
1147
+ useOrder,
1148
+ useProduct,
1149
+ useProducts,
1150
+ useStore,
1151
+ useStorefrontClient
1152
+ });
1153
+ //# sourceMappingURL=index.cjs.map