@konfiqo/storefront-react 0.0.0-stage → 0.4.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/LICENSE +21 -0
- package/README.md +346 -2
- package/dist/index.cjs +1153 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +355 -0
- package/dist/index.d.ts +355 -0
- package/dist/index.js +1120 -0
- package/dist/index.js.map +1 -0
- package/package.json +72 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/provider.tsx","../src/cart-store.ts","../src/use-resource.ts","../src/catalog.ts","../src/use-cart.ts","../src/use-account.ts","../src/use-checkout.ts","../src/use-order.ts","../src/payment-form.tsx","../src/checkout-challenge.tsx","../src/content.tsx"],"sourcesContent":["'use client';\n\n// Every export is a hook or a client component (React Server Components /\n// Next.js App Router). esbuild keeps this entry directive in the build.\nexport { StorefrontProvider, useStorefrontClient } from './provider';\nexport type { ClientConfig, StorefrontProviderProps } from './provider';\nexport { useStore, useCategories, useProducts, useProduct } from './catalog';\nexport type { ResourceResult } from './use-resource';\nexport { useCart, useCartStorage } from './use-cart';\nexport type { UseCartResult } from './use-cart';\nexport { isDeadCartError, defaultCartStorage } from './cart-store';\nexport type {\n CartSnapshot,\n CheckoutSnapshot,\n StorefrontHookError,\n} from './cart-store';\nexport { useAccount } from './use-account';\nexport type { UseAccountResult } from './use-account';\nexport { useCheckout } from './use-checkout';\nexport type { CheckoutCallOptions, UseCheckoutResult } from './use-checkout';\nexport {\n useOrder,\n isOrderSettled,\n orderPollDelay,\n ORDER_POLL_MIN_MS,\n ORDER_POLL_MAX_MS,\n} from './use-order';\nexport type { UseOrderOptions, UseOrderResult } from './use-order';\nexport { PaymentForm } from './payment-form';\nexport type { PaymentFormProps } from './payment-form';\nexport { CheckoutChallenge } from './checkout-challenge';\nexport type {\n CheckoutChallengeHandle,\n CheckoutChallengeProps,\n} from './checkout-challenge';\nexport { Content, renderContent } from './content';\nexport type { ContentComponents, ContentProps } from './content';\n","import {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n type ReactNode,\n} from 'react';\nimport {\n createStorefrontClient,\n type CartIdStorage,\n type StorefrontClient,\n type StorefrontClientOptions,\n} from '@konfiqo/storefront-sdk';\nimport { CartStore, defaultCartStorage } from './cart-store';\n\n/** Client options the provider accepts: no secret keys, no buyer IP. */\nexport type ClientConfig = Omit<\n StorefrontClientOptions,\n 'serverKey' | 'trustedStorefrontKey' | 'buyerIp'\n>;\n\n/** Props of {@link StorefrontProvider}. */\nexport interface StorefrontProviderProps {\n /**\n * The store's id: namespaces the persisted cart id, so one origin can\n * serve several stores.\n */\n storeId: string;\n /** A client to use. Give either `client` or `config`. */\n client?: StorefrontClient;\n /**\n * Options to create the client with (when `client` is not given). The\n * secret keys `serverKey` and `trustedStorefrontKey`, and `buyerIp`, are\n * refused: props of a client component are serialized into the page HTML.\n */\n config?: ClientConfig;\n /**\n * Where the cart id is persisted. Default: the first-party `__Host-konfiqo_cart`\n * cookie (shared with a store's own frontend on the same domain) with\n * `window.localStorage` as a fallback, read lazily (never during render, so server rendering is safe). `null`\n * keeps the cart id in memory only (lost on reload).\n */\n cartStorage?: CartIdStorage | null;\n /** The storefront. */\n children?: ReactNode;\n}\n\ninterface StorefrontContextValue {\n client: StorefrontClient;\n storeId: string;\n cart: CartStore;\n}\n\nconst StorefrontContext = createContext<StorefrontContextValue | null>(null);\n\n/**\n * Makes a Storefront client and the buyer's cart available to the hooks\n * below it. Holds the cart state, so every `useCart()` under one provider\n * sees the same cart.\n *\n * @throws Error when neither `client` nor `config` is given, or when\n * `config` holds `serverKey`, `trustedStorefrontKey` or `buyerIp`.\n */\nexport function StorefrontProvider({\n storeId,\n client,\n config,\n cartStorage,\n children,\n}: StorefrontProviderProps) {\n const forbidden = ['serverKey', 'trustedStorefrontKey', 'buyerIp'].filter(\n (k) => config !== undefined && k in config,\n );\n if (forbidden.length > 0) {\n throw new Error(\n `StorefrontProvider: config.${forbidden.join(', config.')} must not be passed to a client component (it would reach the browser). Create a server-side client instead.`,\n );\n }\n const baseUrl = config?.baseUrl;\n const publishableKey = config?.publishableKey;\n const timeoutMs = config?.timeoutMs;\n const customFetch = config?.fetch;\n const resolved = useMemo(() => {\n if (client) return client;\n if (baseUrl === undefined || publishableKey === undefined) {\n throw new Error('StorefrontProvider: pass `client` or `config`');\n }\n return createStorefrontClient({\n baseUrl,\n publishableKey,\n timeoutMs,\n fetch: customFetch,\n });\n }, [client, baseUrl, publishableKey, timeoutMs, customFetch]);\n\n // Read by the cart store per call. Assigned during render (an\n // idempotent write of the latest props) so the store — keyed by\n // `storeId` only — always uses the current client and storage, and the\n // cart state survives a new client (e.g. a new `fetch` identity).\n const clientRef = useRef(resolved);\n clientRef.current = resolved;\n const storageRef = useRef(cartStorage);\n storageRef.current = cartStorage;\n\n const cart = useMemo(\n () =>\n new CartStore(\n () => clientRef.current,\n storeId,\n () =>\n storageRef.current === undefined\n ? defaultCartStorage()\n : storageRef.current,\n ),\n [storeId],\n );\n // Cancels the cart read when the provider goes away. Writes (and\n // checkout) are never aborted: the server may apply them anyway.\n useEffect(() => () => cart.abortReads(), [cart]);\n // Another tab changed this store's cart id: follow it.\n useEffect(() => {\n if (typeof window === 'undefined') return;\n const onStorage = (e: StorageEvent) => {\n const storage = cart.currentStorage();\n if (!storage) return;\n // The default storage names the `localStorage` it writes through.\n const area = (storage as { storageArea?: unknown }).storageArea;\n if (e.storageArea !== (area ?? storage)) return;\n if (e.key !== null && e.key !== cart.storageKey) return;\n cart.syncFromStorage();\n };\n window.addEventListener('storage', onStorage);\n return () => window.removeEventListener('storage', onStorage);\n }, [cart]);\n\n const value = useMemo(\n () => ({ client: resolved, storeId, cart }),\n [resolved, storeId, cart],\n );\n return (\n <StorefrontContext.Provider value={value}>\n {children}\n </StorefrontContext.Provider>\n );\n}\n\n/** The provider's context. Internal. */\nexport function useStorefrontContext(): StorefrontContextValue {\n const ctx = useContext(StorefrontContext);\n if (!ctx) {\n throw new Error(\n 'Storefront hooks must be used inside <StorefrontProvider>',\n );\n }\n return ctx;\n}\n\n/** The provider's context, or null outside a provider. Internal. */\nexport function useOptionalStorefrontContext(): StorefrontContextValue | null {\n return useContext(StorefrontContext);\n}\n\n/**\n * The provider's {@link StorefrontClient}, for calls the hooks do not\n * cover.\n */\nexport function useStorefrontClient(): StorefrontClient {\n return useStorefrontContext().client;\n}\n","import {\n StorefrontError,\n cartIdKey,\n clearCartId,\n cookieCartStorage,\n isStorefrontError,\n loadCartId,\n saveCartId,\n type AnyStorefrontError,\n type Cart,\n type CartIdStorage,\n type CheckoutResult,\n type RequestOptions,\n type ShippingOptionList,\n type StorefrontClient,\n} from '@konfiqo/storefront-sdk';\n\n/**\n * An error a hook reports: a {@link StorefrontError} (narrow with\n * `isStorefrontError` and switch on `code`), or a plain `Error` for\n * programming mistakes (e.g. an invalid slug).\n */\nexport type StorefrontHookError = AnyStorefrontError | Error;\n\n/** The cart part of the shared state. */\nexport interface CartSnapshot {\n /** The cart, or null when the buyer has none yet (created on the first write). */\n cart: Cart | null;\n /**\n * `idle` before the first read (and during server rendering), `loading`\n * while the saved cart is read, `ready` afterwards.\n */\n status: 'idle' | 'loading' | 'ready';\n /** A write is in progress. */\n isUpdating: boolean;\n /** The last read or write error, cleared by the next success. */\n error: StorefrontHookError | null;\n /**\n * The id of a cart this provider left because it was already `ordered`\n * when the buyer changed it (a write moved to a fresh cart). Lets the\n * app offer \"continue your payment\" for that order. Cleared by `reset()`.\n */\n previousCartId: string | null;\n}\n\n/** The checkout part of the shared state. */\nexport interface CheckoutSnapshot {\n /** A checkout call is in flight. */\n isPending: boolean;\n /** The last checkout's result. Holds the once-only order `token`. */\n result: CheckoutResult | null;\n /** The last checkout's error. */\n error: StorefrontHookError | null;\n /** Settled checkout calls so far (a challenge widget resets on each). */\n attempts: number;\n}\n\n/** Whether a write error means \"this cart is already ordered\". */\nfunction isOrderedCartError(e: unknown): boolean {\n return (\n isStorefrontError(e) &&\n e.code === 'cart_read_only' &&\n e.details.status === 'ordered'\n );\n}\n\n/** Whether a cart error means \"this cart is gone: start a new one\". */\nexport function isDeadCartError(e: unknown): boolean {\n if (!isStorefrontError(e)) return false;\n if (e.code === 'cart_not_found') return true;\n return e.code === 'cart_read_only' && e.details.status === 'expired';\n}\n\nconst toError = (e: unknown): StorefrontHookError =>\n e instanceof Error ? (e as StorefrontHookError) : new Error(String(e));\n\n/**\n * The buyer's cart and checkout state, shared by every hook under one\n * provider. Writes and checkout run one at a time, in call order, and\n * every write replaces the state with the server's cart view. Internal.\n */\nexport class CartStore {\n private cartState: CartSnapshot = {\n cart: null,\n status: 'idle',\n isUpdating: false,\n error: null,\n previousCartId: null,\n };\n private checkoutState: CheckoutSnapshot = {\n isPending: false,\n result: null,\n error: null,\n attempts: 0,\n };\n private readonly listeners = new Set<() => void>();\n private queue: Promise<void> = Promise.resolve();\n private cartId: string | null = null;\n private loadPromise: Promise<void> | null = null;\n private reads = new AbortController();\n private pendingCheckout: Promise<CheckoutResult> | null = null;\n private pendingWrites = 0;\n /**\n * Bumped by `reset()` (and a cart id changed in another tab): a queued\n * operation that started under an older epoch drops its outcome instead\n * of resurrecting (or persisting) the cart it was working on.\n */\n private epoch = 0;\n /**\n * Bumped by `reset()` only. A checkout in flight keeps its outcome (the\n * once-only order token) when another tab merely changes the cart id.\n */\n private resetEpoch = 0;\n /** Whether a checkout was started under this provider. */\n checkoutStarted = false;\n\n /**\n * @param getClient - the provider's current client (read per call, so\n * a new client — e.g. another `fetch` — keeps this cart state)\n */\n constructor(\n private readonly getClient: () => StorefrontClient,\n private readonly storeId: string,\n private readonly storage: () => CartIdStorage | null,\n ) {}\n\n private get client(): StorefrontClient {\n return this.getClient();\n }\n\n // ------------------------------------------------------ subscription\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n };\n getCart = (): CartSnapshot => this.cartState;\n getCheckout = (): CheckoutSnapshot => this.checkoutState;\n\n private setCart(patch: Partial<CartSnapshot>): void {\n this.cartState = { ...this.cartState, ...patch };\n this.emit();\n }\n private setCheckout(patch: Partial<CheckoutSnapshot>): void {\n this.checkoutState = { ...this.checkoutState, ...patch };\n this.emit();\n }\n private emit(): void {\n for (const l of this.listeners) l();\n }\n\n /** Runs `fn` after everything queued before it. */\n private enqueue<T>(fn: () => Promise<T>): Promise<T> {\n const run = this.queue.then(fn);\n this.queue = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n }\n\n private currentId(): string | null {\n return this.cartId ?? loadCartId(this.storage(), this.storeId);\n }\n\n /** Forgets the cart: the next write creates a new one. */\n private forget(): void {\n this.cartId = null;\n clearCartId(this.storage(), this.storeId);\n }\n\n /** Puts a server cart view into the state (an expired cart is forgotten). */\n private apply(cart: Cart): void {\n if (cart.status === 'expired') {\n this.forget();\n this.setCart({ cart: null, status: 'ready', error: null });\n return;\n }\n if (this.cartId !== cart.id) {\n this.cartId = cart.id;\n saveCartId(this.storage(), this.storeId, cart.id);\n }\n this.setCart({ cart, status: 'ready', error: null });\n }\n\n // ------------------------------------------------------ reads\n\n /** Reads the saved cart once (later calls share the first read). */\n load = (): Promise<void> => {\n this.loadPromise ??= this.read();\n return this.loadPromise;\n };\n\n /**\n * Reads the cart again. Also how a cart whose payment failed shows up\n * as `open` again: the read reopens it on the server.\n */\n refresh = (): Promise<void> => this.read();\n\n /** Cancels pending cart reads (the provider unmounted). */\n abortReads(): void {\n this.reads.abort();\n this.reads = new AbortController();\n this.loadPromise = null;\n }\n\n private read(): Promise<void> {\n const signal = this.reads.signal;\n return this.enqueue(async () => {\n if (signal.aborted) {\n if (this.cartState.status === 'loading')\n this.setCart({ status: 'idle' });\n return;\n }\n const epoch = this.epoch;\n const id = this.currentId();\n if (!id) {\n this.setCart({ cart: null, status: 'ready' });\n return;\n }\n this.cartId = id;\n if (this.cartState.cart === null) this.setCart({ status: 'loading' });\n try {\n const cart = await this.client.carts.get(id, { signal });\n if (epoch !== this.epoch) return;\n this.apply(cart);\n } catch (e) {\n if (epoch !== this.epoch) return;\n if (signal.aborted) {\n if (this.cartState.status === 'loading')\n this.setCart({ status: 'idle' });\n return;\n }\n if (isDeadCartError(e)) {\n this.forget();\n this.setCart({ cart: null, status: 'ready', error: null });\n return;\n }\n this.setCart({ status: 'ready', error: toError(e) });\n }\n });\n }\n\n // ------------------------------------------------------ writes\n\n private write(op: (cartId: string) => Promise<Cart>): Promise<Cart> {\n this.pendingWrites++;\n this.setCart({ isUpdating: true });\n return this.enqueue(async () => {\n const epoch = this.epoch;\n const current = () => epoch === this.epoch;\n /** Runs `op` on the current cart, creating one if needed. */\n const attempt = async (): Promise<Cart> => {\n let id = this.currentId();\n if (!id) {\n // Created lazily: a buyer who only browses never gets a cart.\n const created = await this.client.carts.create();\n if (!current()) {\n // Reset (or another tab) while the cart was being created: do\n // not write into a cart nobody holds.\n throw new StorefrontError(\n 'aborted',\n 0,\n 'The cart was reset while the write was pending',\n undefined,\n );\n }\n this.apply(created);\n id = created.id;\n }\n return op(id);\n };\n try {\n let cart: Cart;\n try {\n cart = await attempt();\n } catch (e) {\n if (!current() || !isOrderedCartError(e)) throw e;\n // The cart was already checked out (its payment may still be\n // open): keep its id for the app, and replay the write once on\n // a fresh cart.\n const previousCartId = this.currentId();\n this.forget();\n this.setCart({ cart: null, previousCartId });\n cart = await attempt();\n }\n if (current()) this.apply(cart);\n return cart;\n } catch (e) {\n if (current()) {\n if (isDeadCartError(e)) {\n // Gone (expired / unknown): the next write starts a new cart.\n this.forget();\n this.setCart({ cart: null, status: 'ready' });\n }\n this.setCart({ error: toError(e) });\n }\n throw e;\n } finally {\n this.pendingWrites--;\n if (this.pendingWrites === 0) this.setCart({ isUpdating: false });\n }\n });\n }\n\n addLine = (input: { variantId: string; quantity: number }) =>\n this.write((id) => this.client.carts.addLine(id, input));\n updateLine = (variantId: string, input: { quantity: number }) =>\n this.write((id) => this.client.carts.updateLine(id, variantId, input));\n removeLine = (variantId: string) =>\n this.write((id) => this.client.carts.removeLine(id, variantId));\n setCustomer = (\n input: Parameters<StorefrontClient['carts']['setCustomer']>[1],\n ) => this.write((id) => this.client.carts.setCustomer(id, input));\n setAddress = (\n input: Parameters<StorefrontClient['carts']['setAddress']>[1],\n ) => this.write((id) => this.client.carts.setAddress(id, input));\n setShippingOption = (optionId: string) =>\n this.write((id) => this.client.carts.setShippingOption(id, optionId));\n\n /** The shipping options of the cart (empty when there is no cart yet). */\n shippingOptions = async (\n options?: RequestOptions,\n ): Promise<ShippingOptionList> => {\n const id = this.currentId();\n if (!id) return { items: [] };\n return this.client.carts.shippingOptions(id, options);\n };\n\n /**\n * Forgets the cart (e.g. once its order is paid): the next write\n * creates a new one. The old cart is not deleted on the server.\n */\n reset = (): void => {\n this.epoch++;\n this.resetEpoch++;\n this.forget();\n this.loadPromise = null;\n this.setCart({\n cart: null,\n status: 'ready',\n error: null,\n previousCartId: null,\n });\n this.setCheckout({ result: null, error: null });\n };\n\n /**\n * The saved cart id changed in another tab (a `storage` event for this\n * store's key): follow it. Operations in flight on the old cart drop\n * their outcome.\n */\n syncFromStorage = (): void => {\n const id = loadCartId(this.storage(), this.storeId);\n if (id === this.cartId) return;\n this.epoch++;\n this.cartId = id;\n this.loadPromise = null;\n if (id === null) {\n this.setCart({ cart: null, status: 'ready', error: null });\n return;\n }\n void this.refresh();\n };\n\n /** The storage key this store persists its cart id under. */\n get storageKey(): string {\n return cartIdKey(this.storeId);\n }\n\n /** The storage the cart id is kept in (null: memory only). */\n currentStorage(): CartIdStorage | null {\n return this.storage();\n }\n\n // ------------------------------------------------------ checkout\n\n /**\n * Checks the cart out. Never aborted (the server may place the order\n * anyway); a second call while one is in flight returns the same\n * promise. The cart is read again afterwards.\n */\n checkout = (\n options: { turnstileToken?: string } = {},\n ): Promise<CheckoutResult> => {\n if (this.pendingCheckout) return this.pendingCheckout;\n this.checkoutStarted = true;\n this.setCheckout({ isPending: true, error: null });\n let epoch = this.resetEpoch;\n const run = this.enqueue(async () => {\n epoch = this.resetEpoch;\n const id = this.currentId();\n if (!id) {\n throw new StorefrontError(\n 'checkout_incomplete',\n 0,\n 'There is no cart to check out',\n { missing: ['lines'] },\n );\n }\n return this.client.carts.checkout(id, {\n turnstileToken: options.turnstileToken || undefined,\n });\n });\n this.pendingCheckout = run;\n run.then(\n (result) => this.settleCheckout(epoch, { result, error: null }),\n (e: unknown) =>\n this.settleCheckout(epoch, { result: null, error: toError(e) }),\n );\n return run;\n };\n\n private settleCheckout(\n epoch: number,\n patch: Partial<CheckoutSnapshot>,\n ): void {\n this.pendingCheckout = null;\n this.setCheckout({\n // After `reset()` the outcome belongs to a cart the buyer left.\n ...(epoch === this.resetEpoch ? patch : {}),\n isPending: false,\n attempts: this.checkoutState.attempts + 1,\n });\n // Shows what the server now has: `ordered`, or the new prices after\n // `cart_changed`.\n void this.refresh();\n }\n\n /** Clears the last checkout result and error. */\n clearCheckout = (): void => {\n this.setCheckout({ result: null, error: null });\n };\n}\n\n/**\n * The default cart-id storage in a browser: the first-party `__Host-konfiqo_cart`\n * cookie (shared with a store's own frontend on the same domain) backed by\n * `localStorage`. Reads prefer the cookie, and each read that finds it\n * rewrites it, renewing its expiry. Safari caps a script-written cookie to\n * 7 days, so a cookie may expire while `localStorage` still holds the id:\n * then the id is read from `localStorage` and written back into the cookie.\n * Writes go to both, so the cart still persists when cookies are blocked.\n *\n * `removeItem` (the cart deliberately cleared on this origin) leaves a\n * tombstone in `localStorage`, which every frontend on the store origin\n * shares: while it is there an id left in `localStorage` is not brought\n * back. `setItem` clears it. Null on a server.\n */\nexport function defaultCartStorage(): CartIdStorage | null {\n if (typeof window === 'undefined') return null;\n let local: Storage | null = null;\n try {\n local = window.localStorage;\n } catch {\n local = null;\n }\n const cookie = cookieCartStorage();\n const attempt = (f: () => void): boolean => {\n try {\n f();\n return true;\n } catch {\n return false;\n }\n };\n const tombstoneKey = (key: string) => `${key}:cleared`;\n /** The marker an earlier version set; removed wherever it is seen. */\n const legacyMarkerKey = (key: string) => `${key}:in-cookie`;\n const cleared = (key: string): boolean => {\n try {\n return local?.getItem(tombstoneKey(key)) === '1';\n } catch {\n return false;\n }\n };\n const storage: CartIdStorage & { storageArea: Storage | null } = {\n // The area a `storage` event of another tab names.\n storageArea: local,\n getItem(key) {\n let fromCookie: string | null = null;\n try {\n fromCookie = cookie.getItem(key);\n } catch {\n fromCookie = null;\n }\n if (fromCookie) {\n // Renews the expiry (Safari: 7 days from the last write).\n attempt(() => cookie.setItem(key, fromCookie));\n return fromCookie;\n }\n let fromLocal: string | null = null;\n try {\n fromLocal = local?.getItem(key) ?? null;\n } catch {\n fromLocal = null;\n }\n if (!fromLocal) return null;\n // Cleared on purpose on this origin: do not bring the old id back.\n if (cleared(key)) return null;\n // The cookie expired, or never existed: put the id back into it.\n attempt(() => cookie.setItem(key, fromLocal));\n return fromLocal;\n },\n setItem(key, value) {\n const a = attempt(() => cookie.setItem(key, value));\n const b = local ? attempt(() => local.setItem(key, value)) : false;\n if (local) {\n attempt(() => local.removeItem(tombstoneKey(key)));\n attempt(() => local.removeItem(legacyMarkerKey(key)));\n }\n if (!a && !b) throw new Error('no cart storage available');\n },\n removeItem(key) {\n attempt(() => cookie.removeItem(key));\n if (local) {\n attempt(() => local.removeItem(key));\n attempt(() => local.setItem(tombstoneKey(key), '1'));\n attempt(() => local.removeItem(legacyMarkerKey(key)));\n }\n },\n };\n return storage;\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport type { StorefrontHookError } from './cart-store';\n\n/** What a read hook returns. */\nexport interface ResourceResult<T> {\n /** The data, or null before it arrives (and after an error). */\n data: T | null;\n /** The error of the last read, or null. */\n error: StorefrontHookError | null;\n /** A read is in progress. */\n isLoading: boolean;\n /** Reads again. */\n refetch: () => void;\n}\n\ninterface State<T> {\n key: string | null;\n data: T | null;\n error: StorefrontHookError | null;\n isLoading: boolean;\n}\n\nconst toError = (e: unknown): StorefrontHookError =>\n e instanceof Error ? (e as StorefrontHookError) : new Error(String(e));\n\n/**\n * Reads `fetcher` whenever `key` changes (null = nothing to read). Each\n * read has its own AbortSignal, aborted when the key changes or the\n * component unmounts, so a stale answer never replaces a newer one.\n * Internal.\n */\nexport function useResource<T>(\n key: string | null,\n deps: unknown,\n fetcher: (signal: AbortSignal) => Promise<T>,\n): ResourceResult<T> {\n const [state, setState] = useState<State<T>>({\n key: null,\n data: null,\n error: null,\n isLoading: key !== null,\n });\n const [nonce, setNonce] = useState(0);\n const fetcherRef = useRef(fetcher);\n useEffect(() => {\n fetcherRef.current = fetcher;\n });\n\n useEffect(() => {\n if (key === null) {\n setState({ key, data: null, error: null, isLoading: false });\n return;\n }\n const controller = new AbortController();\n setState((s) =>\n s.key === key\n ? { ...s, isLoading: true }\n : { key, data: null, error: null, isLoading: true },\n );\n fetcherRef.current(controller.signal).then(\n (data) => {\n if (!controller.signal.aborted)\n setState({ key, data, error: null, isLoading: false });\n },\n (e: unknown) => {\n if (!controller.signal.aborted)\n setState({ key, data: null, error: toError(e), isLoading: false });\n },\n );\n return () => controller.abort();\n }, [key, deps, nonce]);\n\n const refetch = useCallback(() => setNonce((n) => n + 1), []);\n // Until the effect runs for a new key, do not show the old key's data.\n if (state.key !== key) {\n return { data: null, error: null, isLoading: key !== null, refetch };\n }\n return {\n data: state.data,\n error: state.error,\n isLoading: state.isLoading,\n refetch,\n };\n}\n","import type {\n CategoryList,\n Product,\n ProductListQuery,\n ProductPage,\n Store,\n} from '@konfiqo/storefront-sdk';\nimport { useStorefrontContext } from './provider';\nimport { useResource, type ResourceResult } from './use-resource';\n\n/** The store (`store.get()`): name, currency, theme, legal texts, checkout challenge. */\nexport function useStore(): ResourceResult<Store> {\n const { client } = useStorefrontContext();\n return useResource('store', client, (signal) => client.store.get({ signal }));\n}\n\n/** The active category tree (`categories.list()`). */\nexport function useCategories(): ResourceResult<CategoryList> {\n const { client } = useStorefrontContext();\n return useResource('categories', client, (signal) =>\n client.categories.list({ signal }),\n );\n}\n\n/**\n * A page of products (`products.list(params)`). Reads again when a\n * parameter changes, cancelling the previous read.\n */\nexport function useProducts(\n params: ProductListQuery = {},\n): ResourceResult<ProductPage> {\n const { client } = useStorefrontContext();\n const query: ProductListQuery = {\n category: params.category,\n q: params.q,\n page: params.page,\n pageSize: params.pageSize,\n };\n return useResource(JSON.stringify(query), client, (signal) =>\n client.products.list(query, { signal }),\n );\n}\n\n/**\n * One product by slug (`products.get(slug)`); an unknown slug is the\n * error `product_not_found`. A null / empty slug reads nothing.\n */\nexport function useProduct(\n slug: string | null | undefined,\n): ResourceResult<Product> {\n const { client } = useStorefrontContext();\n return useResource(slug ? `product:${slug}` : null, client, (signal) =>\n client.products.get(slug!, { signal }),\n );\n}\n","import { useEffect, useMemo, useSyncExternalStore } from 'react';\nimport type {\n AddLineInput,\n AddressInput,\n Cart,\n CartIdStorage,\n CustomerInput,\n RequestOptions,\n ShippingOptionList,\n UpdateLineInput,\n} from '@konfiqo/storefront-sdk';\nimport type { CartSnapshot } from './cart-store';\nimport { useStorefrontContext } from './provider';\n\n/** What {@link useCart} returns. */\nexport interface UseCartResult extends CartSnapshot {\n /** Total units in the cart (for a badge). */\n itemCount: number;\n /** Adds units of a variant. Creates the cart on the first write. */\n addLine(input: AddLineInput): Promise<Cart>;\n /** Sets a line's quantity. */\n updateLine(variantId: string, input: UpdateLineInput): Promise<Cart>;\n /** Removes a line. */\n removeLine(variantId: string): Promise<Cart>;\n /** Sets the buyer. */\n setCustomer(input: CustomerInput): Promise<Cart>;\n /** Sets the shipping (and billing) address. */\n setAddress(input: AddressInput): Promise<Cart>;\n /** Selects a shipping option. */\n setShippingOption(optionId: string): Promise<Cart>;\n /** The shipping options of the cart (`{ items: [] }` without a cart). */\n shippingOptions(options?: RequestOptions): Promise<ShippingOptionList>;\n /** Reads the cart again (a cart whose payment failed comes back `open`). */\n refresh(): Promise<void>;\n /** Forgets the cart (e.g. after its order is paid); the next write starts a new one. */\n reset(): void;\n}\n\nconst SERVER_CART: CartSnapshot = {\n cart: null,\n status: 'idle',\n isUpdating: false,\n error: null,\n previousCartId: null,\n};\n\n/**\n * The buyer's cart, shared by every component under the provider.\n *\n * The saved cart id is read on mount (after hydration: nothing is read\n * during render). No cart is created until the first write. Every write\n * replaces the state with the server's cart view — prices are never\n * computed locally. Writes reject with a {@link StorefrontHookError} (and\n * also set `error`); a cart that expired or is unknown is forgotten, and\n * the next write starts a new one.\n */\nexport function useCart(): UseCartResult {\n const { cart: store } = useStorefrontContext();\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getCart,\n () => SERVER_CART,\n );\n useEffect(() => {\n void store.load();\n }, [store]);\n const itemCount =\n snapshot.cart?.lines.reduce((n, line) => n + line.quantity, 0) ?? 0;\n return {\n ...snapshot,\n itemCount,\n addLine: store.addLine,\n updateLine: store.updateLine,\n removeLine: store.removeLine,\n setCustomer: store.setCustomer,\n setAddress: store.setAddress,\n setShippingOption: store.setShippingOption,\n shippingOptions: store.shippingOptions,\n refresh: store.refresh,\n reset: store.reset,\n };\n}\n\n/**\n * Where this provider keeps the cart id, as a getter (read it inside an\n * effect or handler, never during render: it is null on a server). Lets a\n * page that learns a cart id out of band (e.g. cart recovery) save it\n * where the cart reads it, with `saveCartId(getStorage(), storeId, id)`.\n */\nexport function useCartStorage(): () => CartIdStorage | null {\n const { cart } = useStorefrontContext();\n return useMemo(() => () => cart.currentStorage(), [cart]);\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport { isStorefrontError, type Account } from '@konfiqo/storefront-sdk';\nimport type { StorefrontHookError } from './cart-store';\nimport { useStorefrontContext } from './provider';\n\n/** What {@link useAccount} returns. */\nexport interface UseAccountResult {\n /** The signed-in buyer's account, or null. */\n account: Account | null;\n /** `loading` until the first read answers; `signedOut` on a 401. */\n status: 'loading' | 'signedOut' | 'signedIn';\n /**\n * The last read's error when it was not a 401 (e.g. network, timeout),\n * else null. The status is `signedOut` then, unless an earlier read\n * succeeded (the account is kept).\n */\n error: StorefrontHookError | null;\n /** Reads the account again (call after sign-in, sign-out or a save). */\n refresh(): Promise<void>;\n}\n\ninterface State {\n account: Account | null;\n status: UseAccountResult['status'];\n error: StorefrontHookError | null;\n}\n\n/**\n * The buyer's account (`client.account.get()`), read after mount. A 401\n * (no or an ended session) means `signedOut`. Sign in / out and saves go\n * through `useStorefrontClient().account`; call `refresh()` afterwards.\n */\nexport function useAccount(): UseAccountResult {\n const { client } = useStorefrontContext();\n const [state, setState] = useState<State>({\n account: null,\n status: 'loading',\n error: null,\n });\n const seq = useRef(0);\n const alive = useRef(true);\n\n const refresh = useCallback(async () => {\n const mine = ++seq.current;\n try {\n const account = await client.account.get();\n if (!alive.current || mine !== seq.current) return;\n setState({ account, status: 'signedIn', error: null });\n } catch (e) {\n if (!alive.current || mine !== seq.current) return;\n if (isStorefrontError(e) && e.status === 401) {\n setState({ account: null, status: 'signedOut', error: null });\n return;\n }\n const error =\n e instanceof Error ? (e as StorefrontHookError) : new Error(String(e));\n setState((s) => ({\n account: s.account,\n status: s.account ? 'signedIn' : 'signedOut',\n error,\n }));\n }\n }, [client]);\n\n useEffect(() => {\n alive.current = true;\n void refresh();\n return () => {\n alive.current = false;\n };\n }, [refresh]);\n\n return { ...state, refresh };\n}\n","import { useCallback, useEffect, useSyncExternalStore } from 'react';\nimport type { CheckoutResult } from '@konfiqo/storefront-sdk';\nimport type { CheckoutSnapshot } from './cart-store';\nimport { useOptionalStorefrontContext, useStorefrontContext } from './provider';\n\n/** Options of `checkout()`. */\nexport interface CheckoutCallOptions {\n /**\n * The checkout challenge token (from `<CheckoutChallenge>`), required\n * when `store.checkoutChallenge` is set. Single-use.\n */\n turnstileToken?: string | null;\n}\n\n/** What {@link useCheckout} returns. */\nexport interface UseCheckoutResult extends CheckoutSnapshot {\n /**\n * Checks the cart out: `carts.checkout(cartId, { turnstileToken })`.\n * Resolves with the result (present it with `<PaymentForm>`; keep its\n * `token`, returned only once) or rejects with the error (also in\n * `error`). A call while one is in flight returns the same promise.\n */\n checkout(options?: CheckoutCallOptions): Promise<CheckoutResult>;\n /** Clears `result` and `error`. */\n reset(): void;\n}\n\nconst SERVER_CHECKOUT: CheckoutSnapshot = {\n isPending: false,\n result: null,\n error: null,\n attempts: 0,\n};\n\n/**\n * Checkout for the provider's cart. The state is shared under the\n * provider, and a checkout is **never aborted** — not even when the\n * component unmounts — because the server may place the order anyway.\n * When a component using this hook mounts after a checkout was started,\n * the cart is read again so it shows what the server has.\n *\n * Errors are {@link StorefrontError}s: switch on `error.code`. For\n * `cart_changed`, `error.details` has the new `lines`, totals and\n * `shippingOptions` (the cart is also read again): show them and let the\n * buyer confirm before calling `checkout()` again — never retry silently.\n */\nexport function useCheckout(): UseCheckoutResult {\n const { cart: store } = useStorefrontContext();\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getCheckout,\n () => SERVER_CHECKOUT,\n );\n useEffect(() => {\n if (store.checkoutStarted) void store.refresh();\n }, [store]);\n const checkout = useCallback(\n (options: CheckoutCallOptions = {}) =>\n store.checkout({ turnstileToken: options.turnstileToken ?? undefined }),\n [store],\n );\n return { ...snapshot, checkout, reset: store.clearCheckout };\n}\n\n/** Settled checkout attempts under the provider (0 outside one). Internal. */\nexport function useCheckoutAttempts(): number {\n const ctx = useOptionalStorefrontContext();\n const store = ctx?.cart;\n return useSyncExternalStore(\n store?.subscribe ?? noopSubscribe,\n () => store?.getCheckout().attempts ?? 0,\n () => 0,\n );\n}\n\nconst noopSubscribe = () => () => {};\n","import { useCallback, useEffect, useState } from 'react';\nimport { isStorefrontError, type Order } from '@konfiqo/storefront-sdk';\nimport type { StorefrontHookError } from './cart-store';\nimport { useStorefrontContext } from './provider';\n\n/** First poll delay, milliseconds. */\nexport const ORDER_POLL_MIN_MS = 2_000;\n/** Longest poll delay, milliseconds. */\nexport const ORDER_POLL_MAX_MS = 15_000;\n\n/** The delay before poll number `attempt` (0-based): 2 s, 4 s, 8 s, then 15 s. */\nexport function orderPollDelay(attempt: number): number {\n return Math.min(ORDER_POLL_MIN_MS * 2 ** attempt, ORDER_POLL_MAX_MS);\n}\n\n/**\n * Whether an order no longer changes on its own soon: anything past\n * `pendingPayment` (`paid`, `fulfilling`, `shipped`, `delivered`,\n * `cancelled`, `refunded`, …), or a pending order whose payment `failed`\n * / `expired` (the buyer has to check out again).\n */\nexport function isOrderSettled(order: Order): boolean {\n if (order.status !== 'pendingPayment') return true;\n return order.paymentStatus === 'failed' || order.paymentStatus === 'expired';\n}\n\n/** Errors worth polling through (the service may answer next time). */\nfunction isTransient(e: unknown): boolean {\n if (!isStorefrontError(e)) return false;\n switch (e.code) {\n case 'network_error':\n case 'timeout':\n case 'rate_limited':\n case 'order_unavailable':\n case 'http_error':\n return true;\n default:\n return false;\n }\n}\n\n/** Options of {@link useOrder}. */\nexport interface UseOrderOptions {\n /**\n * Keep reading until the order is settled ({@link isOrderSettled}),\n * backing off 2 s → 4 s → 8 s → 15 s (then every 15 s). Transient\n * errors (network, timeout, throttling, `order_unavailable`) keep\n * polling; others stop it.\n */\n pollUntilFinal?: boolean;\n}\n\n/** What {@link useOrder} returns. */\nexport interface UseOrderResult {\n /** The order, or null before it arrives. Kept through a failed poll. */\n order: Order | null;\n /** The last read's error, or null. */\n error: StorefrontHookError | null;\n /** The first read is in progress. */\n isLoading: boolean;\n /** Another read is scheduled. */\n isPolling: boolean;\n /** Reads again now (and restarts polling). */\n refetch: () => void;\n}\n\ninterface State {\n key: string | null;\n order: Order | null;\n error: StorefrontHookError | null;\n isPolling: boolean;\n}\n\n/**\n * The buyer's order (`orders.get(orderId, token)`), e.g. on the page the\n * payment provider returns to (`/orders/{orderId}?token=`). The token is\n * the buyer's only key to the order: this hook never logs it or puts it\n * anywhere but the request; do not send it to analytics either.\n */\nexport function useOrder(\n orderId: string | null | undefined,\n token: string | null | undefined,\n options: UseOrderOptions = {},\n): UseOrderResult {\n const { client } = useStorefrontContext();\n const poll = options.pollUntilFinal ?? false;\n const key = orderId && token ? `${orderId} ${token}` : null;\n const [state, setState] = useState<State>({\n key: null,\n order: null,\n error: null,\n isPolling: false,\n });\n const [nonce, setNonce] = useState(0);\n\n useEffect(() => {\n if (!orderId || !token) {\n setState({ key: null, order: null, error: null, isPolling: false });\n return;\n }\n const k = `${orderId} ${token}`;\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n let attempt = 0;\n const schedule = (atLeastMs: number) => {\n const delay = Math.max(orderPollDelay(attempt++), atLeastMs);\n setState((s) => ({ ...s, isPolling: true }));\n timer = setTimeout(tick, delay);\n };\n const tick = async () => {\n try {\n const order = await client.orders.get(orderId, token, {\n signal: controller.signal,\n });\n if (controller.signal.aborted) return;\n setState({ key: k, order, error: null, isPolling: false });\n if (poll && !isOrderSettled(order)) schedule(0);\n } catch (e) {\n if (controller.signal.aborted) return;\n const error =\n e instanceof Error\n ? (e as StorefrontHookError)\n : new Error(String(e));\n setState((s) => ({\n key: k,\n order: s.key === k ? s.order : null,\n error,\n isPolling: false,\n }));\n if (poll && isTransient(e)) {\n const retryAfter =\n isStorefrontError(e) && e.code === 'rate_limited'\n ? (e.details.retryAfter ?? 0) * 1000\n : 0;\n schedule(retryAfter);\n }\n }\n };\n void tick();\n return () => {\n controller.abort();\n clearTimeout(timer);\n };\n }, [client, orderId, token, poll, nonce]);\n\n const refetch = useCallback(() => setNonce((n) => n + 1), []);\n if (state.key !== key) {\n return {\n order: null,\n error: null,\n isLoading: key !== null,\n isPolling: false,\n refetch,\n };\n }\n return {\n order: state.order,\n error: state.error,\n isLoading: false,\n isPolling: state.isPolling,\n refetch,\n };\n}\n","import { useEffect, useRef, type HTMLAttributes } from 'react';\nimport {\n mountPayment,\n type CheckoutResult,\n type ClosedCheckoutPage,\n type PaymentPresentation,\n} from '@konfiqo/storefront-sdk';\n\n/** Props of {@link PaymentForm}. */\nexport interface PaymentFormProps extends Omit<\n HTMLAttributes<HTMLDivElement>,\n 'children' | 'onError'\n> {\n /**\n * The **unmodified** result of `checkout()` (or its presentation part).\n * Never build it from user input, URL parameters or storage: embedded\n * content runs as script.\n */\n presentation: PaymentPresentation | CheckoutResult;\n /**\n * Payment cannot be (re)opened (`presentation: \"closed\"`): show the\n * order status page for `page` (`paid`, `cancelled`, `processing`, …).\n */\n onClosed?: (page: ClosedCheckoutPage) => void;\n /** The embed is of a kind this SDK cannot render: show a fallback. */\n onUnsupported?: (embedKind: string) => void;\n /** Presenting failed (e.g. a redirect URL that is not http(s)). */\n onError?: (error: Error) => void;\n}\n\ninterface Pending {\n timer: ReturnType<typeof setTimeout>;\n content: string | null;\n unmount: () => void;\n}\n\nconst embeddedContent = (p: PaymentPresentation | CheckoutResult) =>\n p.presentation === 'embedded' && typeof p.embed.content === 'string'\n ? p.embed.content\n : null;\n\n/**\n * Presents payment with the SDK's `mountPayment`: renders the provider's\n * embedded form inside a `<div>` (its scripts run once), sends the browser\n * to a `redirect` URL, or calls `onClosed`. The form is removed on\n * unmount. Card data never passes through your code. Unstyled: pass\n * `className` / `style` for the wrapper.\n */\nexport function PaymentForm({\n presentation,\n onClosed,\n onUnsupported,\n onError,\n ...divProps\n}: PaymentFormProps) {\n const ref = useRef<HTMLDivElement>(null);\n const callbacks = useRef({ onClosed, onUnsupported, onError });\n useEffect(() => {\n callbacks.current = { onClosed, onUnsupported, onError };\n });\n const pending = useRef<Pending | null>(null);\n const navigated = useRef<unknown>(null);\n\n useEffect(() => {\n const element = ref.current;\n if (!element) return;\n // A removal deferred by the previous cleanup: skip it when the same\n // form is mounted again (React Strict Mode re-runs effects), so the\n // provider's scripts are not injected twice.\n const prev = pending.current;\n pending.current = null;\n if (prev) {\n clearTimeout(prev.timer);\n if (\n prev.content === null ||\n prev.content !== embeddedContent(presentation)\n )\n prev.unmount();\n }\n // A redirect / closed result is acted on once, even if the effect\n // re-runs (Strict Mode): one navigation, one `onClosed`.\n if (presentation.presentation !== 'embedded') {\n if (navigated.current === presentation) return;\n navigated.current = presentation;\n }\n\n let unmount: (() => void) | null = null;\n try {\n const mount = mountPayment(element, presentation, {\n onClosed: (page) => callbacks.current.onClosed?.(page),\n });\n if (mount.kind === 'embedded') unmount = mount.unmount;\n else if (mount.kind === 'unsupported')\n callbacks.current.onUnsupported?.(mount.embedKind);\n } catch (e) {\n callbacks.current.onError?.(\n e instanceof Error ? e : new Error(String(e)),\n );\n }\n if (!unmount) return;\n const remove = unmount;\n return () => {\n const entry: Pending = {\n content: embeddedContent(presentation),\n unmount: remove,\n timer: setTimeout(() => {\n if (pending.current === entry) pending.current = null;\n remove();\n }, 0),\n };\n pending.current = entry;\n };\n }, [presentation]);\n\n return <div {...divProps} ref={ref} />;\n}\n","import {\n forwardRef,\n useEffect,\n useImperativeHandle,\n useRef,\n type HTMLAttributes,\n} from 'react';\nimport { renderTurnstile, type TurnstileWidget } from '@konfiqo/storefront-sdk';\nimport { useCheckoutAttempts } from './use-checkout';\n\n/** Props of {@link CheckoutChallenge}. */\nexport interface CheckoutChallengeProps extends Omit<\n HTMLAttributes<HTMLDivElement>,\n 'children' | 'onError'\n> {\n /**\n * The store's Turnstile site key (`store.checkoutChallenge?.siteKey`).\n * Null / empty renders an empty `<div>` (the store has no challenge).\n */\n siteKey: string | null | undefined;\n /** A token is ready: pass it to `checkout({ turnstileToken })`. */\n onToken: (token: string) => void;\n /**\n * The current token can no longer be used — it expired, or a checkout\n * consumed it and the widget was reset. Drop it; a new one follows.\n */\n onExpired?: () => void;\n /** The widget failed to load or render. */\n onError?: (error: Error | string | undefined) => void;\n}\n\n/** Imperative handle of {@link CheckoutChallenge} (via `ref`). */\nexport interface CheckoutChallengeHandle {\n /** Gets a new token (the current one is dropped: `onExpired` is called). */\n reset(): void;\n}\n\n/**\n * Renders the store's checkout challenge (Cloudflare Turnstile) with the\n * SDK's `renderTurnstile`. Tokens are single-use: under a\n * `StorefrontProvider` the widget resets itself after every checkout\n * attempt of `useCheckout()`; call `ref.current.reset()` to reset it\n * yourself. The widget is removed on unmount.\n */\nexport const CheckoutChallenge = forwardRef<\n CheckoutChallengeHandle,\n CheckoutChallengeProps\n>(function CheckoutChallenge(\n { siteKey, onToken, onExpired, onError, ...divProps },\n handle,\n) {\n const ref = useRef<HTMLDivElement>(null);\n const widget = useRef<TurnstileWidget | null>(null);\n const callbacks = useRef({ onToken, onExpired, onError });\n useEffect(() => {\n callbacks.current = { onToken, onExpired, onError };\n });\n\n useEffect(() => {\n const element = ref.current;\n if (!element || !siteKey) return;\n let active = true;\n let rendered: TurnstileWidget | null = null;\n renderTurnstile(element, siteKey, {\n onToken: (t) => callbacks.current.onToken(t),\n onExpired: () => callbacks.current.onExpired?.(),\n onError: (code) => callbacks.current.onError?.(code),\n }).then(\n (w) => {\n if (!active) {\n w.remove();\n return;\n }\n rendered = w;\n widget.current = w;\n },\n (e: unknown) => {\n if (active)\n callbacks.current.onError?.(\n e instanceof Error ? e : new Error(String(e)),\n );\n },\n );\n return () => {\n active = false;\n if (rendered) {\n rendered.remove();\n if (widget.current === rendered) widget.current = null;\n }\n };\n }, [siteKey]);\n\n const reset = () => {\n if (!widget.current) return;\n callbacks.current.onExpired?.();\n widget.current.reset();\n };\n useImperativeHandle(handle, () => ({ reset }), []);\n\n // Tokens are single-use: every settled checkout consumed (or rejected)\n // the current one.\n const attempts = useCheckoutAttempts();\n const seen = useRef(attempts);\n useEffect(() => {\n if (attempts === seen.current) return;\n seen.current = attempts;\n reset();\n });\n\n return <div {...divProps} ref={ref} />;\n});\n","import Markdoc from '@markdoc/markdoc';\nimport * as React from 'react';\nimport { useEffect } from 'react';\nimport type { ComponentType, ReactNode } from 'react';\nimport { formatMoney, type ContentNode } from '@konfiqo/storefront-sdk';\nimport { useProduct, useProducts } from './catalog';\nimport { useStorefrontContext } from './provider';\nimport { useResource } from './use-resource';\n\n/** Components by tag name (`ProductGrid`, `Button`, …), e.g. to replace a default. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ContentComponents = Record<string, ComponentType<any>>;\n\n// ---------------------------------------------------------------- safety\n\n/** Plain tags content may use. Everything else is dropped with its children. */\nconst HTML_TAGS = new Set(\n (\n 'article section div span p h1 h2 h3 h4 h5 h6 ul ol li strong em s del ' +\n 'code pre blockquote hr br a table thead tbody tr th td figure figcaption ' +\n 'small sub sup mark'\n ).split(' '),\n);\n/** The attributes a plain tag keeps (`href` only on `a`, and only if safe). */\nconst HTML_ATTRS = new Set([\n 'class',\n 'title',\n 'align',\n 'colspan',\n 'rowspan',\n 'start',\n]);\nconst MAX_DEPTH = 40;\nconst MAX_NODES = 5000;\n\nconst hasControl = (s: string): boolean =>\n Array.from(s).some((c) => {\n const n = c.charCodeAt(0);\n return n < 0x20 || n === 0x7f;\n });\n\n/** A link target a page may follow: relative, http(s), mailto or tel. */\nfunction safeHref(v: unknown): string | null {\n if (typeof v !== 'string') return null;\n const href = v.trim();\n // No whitespace or control characters inside (`java\\nscript:` tricks).\n if (href === '' || /\\s/.test(href) || hasControl(href)) return null;\n // Browsers read `\\` like `/`: `/\\host` is protocol-relative. Refuse any\n // backslash, also percent-encoded.\n if (href.includes('\\\\') || /%5c/i.test(href)) return null;\n if (href.startsWith('#')) return href;\n if (href.startsWith('/')) return href[1] === '/' ? null : href;\n return /^(https?:|mailto:|tel:)/i.test(href) ? href : null;\n}\n\ntype Prop = string | number | boolean;\nconst isProp = (v: unknown): v is Prop =>\n typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean';\n\ninterface Walk {\n nodes: number;\n components: ContentComponents;\n}\n\nfunction clean(node: unknown, w: Walk, depth: number): ContentNode | null {\n if (typeof node === 'string') return node;\n if (node === null || typeof node !== 'object') return null;\n const n = node as Partial<Exclude<ContentNode, string>>;\n if (\n n.$$mdtype !== 'Tag' ||\n typeof n.name !== 'string' ||\n depth > MAX_DEPTH ||\n ++w.nodes > MAX_NODES\n ) {\n return null;\n }\n const name = n.name;\n const raw =\n n.attributes && typeof n.attributes === 'object' ? n.attributes : {};\n const attributes: Record<string, Prop> = {};\n if (name === '') return null;\n const isHtml = name[0] === name[0]!.toLowerCase();\n if (isHtml) {\n if (!HTML_TAGS.has(name)) return null;\n for (const [k, v] of Object.entries(raw)) {\n if (name === 'a' && k === 'href') {\n const href = safeHref(v);\n if (href !== null) attributes.href = href;\n } else if (HTML_ATTRS.has(k) && isProp(v)) {\n attributes[k] = v;\n }\n }\n } else {\n if (!Object.hasOwn(w.components, name)) return null;\n for (const [k, v] of Object.entries(raw)) {\n if (!isProp(v)) continue;\n if (k === 'ref' || k === 'children' || /^on/i.test(k)) continue;\n if (k === 'dangerouslySetInnerHTML') continue;\n // `key` would be swallowed by React as the element key.\n if (k === 'key') attributes.contentKey = v;\n else attributes[k] = v;\n }\n }\n const children: ContentNode[] = [];\n for (const c of Array.isArray(n.children) ? n.children : []) {\n const cleaned = clean(c, w, depth + 1);\n if (cleaned !== null) children.push(cleaned);\n }\n return { $$mdtype: 'Tag', name, attributes, children };\n}\n\n// ------------------------------------------------------ default components\n\nconst text = (v: unknown): string | undefined =>\n typeof v === 'string' && v !== '' ? v : undefined;\nconst slugOf = (v: unknown): string | null => {\n const s = text(v);\n return s && !/[/\\\\?#]/.test(s) && s !== '.' && s !== '..' ? s : null;\n};\n\nfunction ProductCard({\n product,\n}: {\n product: import('@konfiqo/storefront-sdk').Product;\n}) {\n const { client } = useStorefrontContext();\n const variant = product.variants[0];\n let price: string | null = null;\n try {\n price = variant ? formatMoney(variant.priceMinor, variant.currency) : null;\n } catch {\n price = null;\n }\n let image: string | null = null;\n try {\n image = product.image ? client.media.url(product.image) : null;\n } catch {\n image = null;\n }\n return (\n <a href={`/p/${encodeURIComponent(product.slug)}`}>\n {image ? <img src={image} alt=\"\" /> : null}\n <span>{product.name}</span>\n {price ? <span> {price}</span> : null}\n </a>\n );\n}\n\nfunction ProductGrid(props: { category?: unknown; limit?: unknown }) {\n const category = text(props.category);\n const limit = Number(props.limit);\n const cap = Number.isInteger(limit) && limit > 0 ? Math.min(limit, 48) : 12;\n const { data } = useProducts({ category, pageSize: cap });\n if (!data) return null;\n return (\n <ul className=\"content-product-grid\">\n {data.items.slice(0, cap).map((p) => (\n <li key={p.id}>\n <ProductCard product={p} />\n </li>\n ))}\n </ul>\n );\n}\n\nfunction ProductTag(props: { slug?: unknown }) {\n const { data } = useProduct(slugOf(props.slug));\n return data ? <ProductCard product={data} /> : null;\n}\n\nfunction CategoryLink(props: { slug?: unknown; children?: ReactNode }) {\n const slug = slugOf(props.slug);\n if (!slug) return null;\n return (\n <a href={`/c/${encodeURIComponent(slug)}`}>{props.children ?? slug}</a>\n );\n}\n\nfunction ImageTag(props: { contentKey?: unknown; alt?: unknown }) {\n const { client } = useStorefrontContext();\n const key = text(props.contentKey);\n if (!key) return null;\n let src: string;\n try {\n // Always through the media path, never a URL taken from the content.\n src = client.media.url(key);\n } catch {\n return null;\n }\n return <img src={src} alt={text(props.alt) ?? ''} />;\n}\n\nfunction ButtonTag(props: { href?: unknown; label?: unknown }) {\n const href = safeHref(props.href);\n const label = text(props.label);\n if (!href || !label) return null;\n return (\n <a className=\"button\" href={href}>\n {label}\n </a>\n );\n}\n\nconst DEFAULT_COMPONENTS: ContentComponents = {\n ProductGrid,\n Product: ProductTag,\n CategoryLink,\n Image: ImageTag,\n Button: ButtonTag,\n};\n\n// ------------------------------------------------------------------ render\n\n/**\n * Renders a store-content tree (`StoreContent.tree`) with React. Only\n * plain text tags and the known components are rendered (raw images,\n * unknown tags, ids, styles and event handlers are dropped); output goes\n * through `Markdoc.renderers.react`, never as HTML. The default components\n * (`ProductGrid`, `Product`, `CategoryLink`, `Image`, `Button`) need a\n * `<StorefrontProvider>`; `components` replaces or adds components. A\n * component gets an `Image` / custom tag's `key` attribute as `contentKey`.\n */\nexport function renderContent(\n tree: ContentNode,\n components: ContentComponents = {},\n): ReactNode {\n try {\n const merged = { ...DEFAULT_COMPONENTS, ...components };\n const cleaned = clean(tree, { nodes: 0, components: merged }, 0);\n if (cleaned === null) return null;\n return Markdoc.renderers.react(\n cleaned as unknown as Parameters<typeof Markdoc.renderers.react>[0],\n React,\n { components: merged },\n );\n } catch {\n return null;\n }\n}\n\n/** Props of {@link Content}. */\nexport interface ContentProps {\n /** The content key (`home.hero`, `about-us`, …). */\n contentKey: string;\n /** Components by tag name, replacing or adding to the defaults. */\n components?: ContentComponents;\n}\n\n/**\n * A piece of store content (Markdoc written in the console), read by key\n * from the store. Renders nothing while loading, or when the key does not\n * exist or cannot be read (a warning in development only).\n */\nexport function Content({ contentKey, components }: ContentProps): ReactNode {\n const { client } = useStorefrontContext();\n const { data, error } = useResource(\n `content:${contentKey}`,\n client,\n (signal) => client.getContent(contentKey, { signal }),\n );\n useEffect(() => {\n if (\n error &&\n typeof process !== 'undefined' &&\n process.env?.NODE_ENV !== 'production'\n ) {\n console.warn(\n `<Content contentKey=\"${contentKey}\">: ${error.message || 'could not be read'}`,\n );\n }\n }, [error, contentKey]);\n if (!data) return null;\n return <>{renderContent(data.tree, components)}</>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAOO;AACP,IAAAA,yBAKO;;;ACbP,4BAeO;AA2CP,SAAS,mBAAmB,GAAqB;AAC/C,aACE,yCAAkB,CAAC,KACnB,EAAE,SAAS,oBACX,EAAE,QAAQ,WAAW;AAEzB;AAGO,SAAS,gBAAgB,GAAqB;AACnD,MAAI,KAAC,yCAAkB,CAAC,EAAG,QAAO;AAClC,MAAI,EAAE,SAAS,iBAAkB,QAAO;AACxC,SAAO,EAAE,SAAS,oBAAoB,EAAE,QAAQ,WAAW;AAC7D;AAEA,IAAM,UAAU,CAAC,MACf,aAAa,QAAS,IAA4B,IAAI,MAAM,OAAO,CAAC,CAAC;AAOhE,IAAM,YAAN,MAAgB;AAAA;AAAA;AAAA;AAAA;AAAA,EAuCrB,YACmB,WACA,SACA,SACjB;AAHiB;AACA;AACA;AAAA,EAChB;AAAA,EAHgB;AAAA,EACA;AAAA,EACA;AA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;AAAA,EACP,QAAQ;AACV;AAaO,SAAS,cACd,MACA,aAAgC,CAAC,GACtB;AACX,MAAI;AACF,UAAM,SAAS,EAAE,GAAG,oBAAoB,GAAG,WAAW;AACtD,UAAM,UAAU,MAAM,MAAM,EAAE,OAAO,GAAG,YAAY,OAAO,GAAG,CAAC;AAC/D,QAAI,YAAY,KAAM,QAAO;AAC7B,WAAO,eAAAC,QAAQ,UAAU;AAAA,MACvB;AAAA,MACA;AAAA,MACA,EAAE,YAAY,OAAO;AAAA,IACvB;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAeO,SAAS,QAAQ,EAAE,YAAY,WAAW,GAA4B;AAC3E,QAAM,EAAE,OAAO,IAAI,qBAAqB;AACxC,QAAM,EAAE,MAAM,MAAM,IAAI;AAAA,IACtB,WAAW,UAAU;AAAA,IACrB;AAAA,IACA,CAAC,WAAW,OAAO,WAAW,YAAY,EAAE,OAAO,CAAC;AAAA,EACtD;AACA,+BAAU,MAAM;AACd,QACE,SACA,OAAO,YAAY,eACnB,QAAQ,KAAK,aAAa,cAC1B;AACA,cAAQ;AAAA,QACN,wBAAwB,UAAU,OAAO,MAAM,WAAW,mBAAmB;AAAA,MAC/E;AAAA,IACF;AAAA,EACF,GAAG,CAAC,OAAO,UAAU,CAAC;AACtB,MAAI,CAAC,KAAM,QAAO;AAClB,SAAO,6EAAG,wBAAc,KAAK,MAAM,UAAU,GAAE;AACjD;","names":["import_storefront_sdk","import_react","toError","import_react","import_react","import_storefront_sdk","import_react","import_react","import_storefront_sdk","import_react","import_storefront_sdk","import_jsx_runtime","import_react","import_storefront_sdk","import_jsx_runtime","CheckoutChallenge","import_react","import_storefront_sdk","import_jsx_runtime","Markdoc"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
import { ReactNode, HTMLAttributes, ComponentType } from 'react';
|
|
3
|
+
import { Cart, AnyStorefrontError, CheckoutResult, CartIdStorage, StorefrontClientOptions, StorefrontClient, CategoryList, Product, ProductListQuery, ProductPage, Store, AddLineInput, UpdateLineInput, CustomerInput, AddressInput, RequestOptions, ShippingOptionList, Account, Order, PaymentPresentation, ClosedCheckoutPage, ContentNode } from '@konfiqo/storefront-sdk';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* An error a hook reports: a {@link StorefrontError} (narrow with
|
|
7
|
+
* `isStorefrontError` and switch on `code`), or a plain `Error` for
|
|
8
|
+
* programming mistakes (e.g. an invalid slug).
|
|
9
|
+
*/
|
|
10
|
+
type StorefrontHookError = AnyStorefrontError | Error;
|
|
11
|
+
/** The cart part of the shared state. */
|
|
12
|
+
interface CartSnapshot {
|
|
13
|
+
/** The cart, or null when the buyer has none yet (created on the first write). */
|
|
14
|
+
cart: Cart | null;
|
|
15
|
+
/**
|
|
16
|
+
* `idle` before the first read (and during server rendering), `loading`
|
|
17
|
+
* while the saved cart is read, `ready` afterwards.
|
|
18
|
+
*/
|
|
19
|
+
status: 'idle' | 'loading' | 'ready';
|
|
20
|
+
/** A write is in progress. */
|
|
21
|
+
isUpdating: boolean;
|
|
22
|
+
/** The last read or write error, cleared by the next success. */
|
|
23
|
+
error: StorefrontHookError | null;
|
|
24
|
+
/**
|
|
25
|
+
* The id of a cart this provider left because it was already `ordered`
|
|
26
|
+
* when the buyer changed it (a write moved to a fresh cart). Lets the
|
|
27
|
+
* app offer "continue your payment" for that order. Cleared by `reset()`.
|
|
28
|
+
*/
|
|
29
|
+
previousCartId: string | null;
|
|
30
|
+
}
|
|
31
|
+
/** The checkout part of the shared state. */
|
|
32
|
+
interface CheckoutSnapshot {
|
|
33
|
+
/** A checkout call is in flight. */
|
|
34
|
+
isPending: boolean;
|
|
35
|
+
/** The last checkout's result. Holds the once-only order `token`. */
|
|
36
|
+
result: CheckoutResult | null;
|
|
37
|
+
/** The last checkout's error. */
|
|
38
|
+
error: StorefrontHookError | null;
|
|
39
|
+
/** Settled checkout calls so far (a challenge widget resets on each). */
|
|
40
|
+
attempts: number;
|
|
41
|
+
}
|
|
42
|
+
/** Whether a cart error means "this cart is gone: start a new one". */
|
|
43
|
+
declare function isDeadCartError(e: unknown): boolean;
|
|
44
|
+
/**
|
|
45
|
+
* The default cart-id storage in a browser: the first-party `__Host-konfiqo_cart`
|
|
46
|
+
* cookie (shared with a store's own frontend on the same domain) backed by
|
|
47
|
+
* `localStorage`. Reads prefer the cookie, and each read that finds it
|
|
48
|
+
* rewrites it, renewing its expiry. Safari caps a script-written cookie to
|
|
49
|
+
* 7 days, so a cookie may expire while `localStorage` still holds the id:
|
|
50
|
+
* then the id is read from `localStorage` and written back into the cookie.
|
|
51
|
+
* Writes go to both, so the cart still persists when cookies are blocked.
|
|
52
|
+
*
|
|
53
|
+
* `removeItem` (the cart deliberately cleared on this origin) leaves a
|
|
54
|
+
* tombstone in `localStorage`, which every frontend on the store origin
|
|
55
|
+
* shares: while it is there an id left in `localStorage` is not brought
|
|
56
|
+
* back. `setItem` clears it. Null on a server.
|
|
57
|
+
*/
|
|
58
|
+
declare function defaultCartStorage(): CartIdStorage | null;
|
|
59
|
+
|
|
60
|
+
/** Client options the provider accepts: no secret keys, no buyer IP. */
|
|
61
|
+
type ClientConfig = Omit<StorefrontClientOptions, 'serverKey' | 'trustedStorefrontKey' | 'buyerIp'>;
|
|
62
|
+
/** Props of {@link StorefrontProvider}. */
|
|
63
|
+
interface StorefrontProviderProps {
|
|
64
|
+
/**
|
|
65
|
+
* The store's id: namespaces the persisted cart id, so one origin can
|
|
66
|
+
* serve several stores.
|
|
67
|
+
*/
|
|
68
|
+
storeId: string;
|
|
69
|
+
/** A client to use. Give either `client` or `config`. */
|
|
70
|
+
client?: StorefrontClient;
|
|
71
|
+
/**
|
|
72
|
+
* Options to create the client with (when `client` is not given). The
|
|
73
|
+
* secret keys `serverKey` and `trustedStorefrontKey`, and `buyerIp`, are
|
|
74
|
+
* refused: props of a client component are serialized into the page HTML.
|
|
75
|
+
*/
|
|
76
|
+
config?: ClientConfig;
|
|
77
|
+
/**
|
|
78
|
+
* Where the cart id is persisted. Default: the first-party `__Host-konfiqo_cart`
|
|
79
|
+
* cookie (shared with a store's own frontend on the same domain) with
|
|
80
|
+
* `window.localStorage` as a fallback, read lazily (never during render, so server rendering is safe). `null`
|
|
81
|
+
* keeps the cart id in memory only (lost on reload).
|
|
82
|
+
*/
|
|
83
|
+
cartStorage?: CartIdStorage | null;
|
|
84
|
+
/** The storefront. */
|
|
85
|
+
children?: ReactNode;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Makes a Storefront client and the buyer's cart available to the hooks
|
|
89
|
+
* below it. Holds the cart state, so every `useCart()` under one provider
|
|
90
|
+
* sees the same cart.
|
|
91
|
+
*
|
|
92
|
+
* @throws Error when neither `client` nor `config` is given, or when
|
|
93
|
+
* `config` holds `serverKey`, `trustedStorefrontKey` or `buyerIp`.
|
|
94
|
+
*/
|
|
95
|
+
declare function StorefrontProvider({ storeId, client, config, cartStorage, children, }: StorefrontProviderProps): react.JSX.Element;
|
|
96
|
+
/**
|
|
97
|
+
* The provider's {@link StorefrontClient}, for calls the hooks do not
|
|
98
|
+
* cover.
|
|
99
|
+
*/
|
|
100
|
+
declare function useStorefrontClient(): StorefrontClient;
|
|
101
|
+
|
|
102
|
+
/** What a read hook returns. */
|
|
103
|
+
interface ResourceResult<T> {
|
|
104
|
+
/** The data, or null before it arrives (and after an error). */
|
|
105
|
+
data: T | null;
|
|
106
|
+
/** The error of the last read, or null. */
|
|
107
|
+
error: StorefrontHookError | null;
|
|
108
|
+
/** A read is in progress. */
|
|
109
|
+
isLoading: boolean;
|
|
110
|
+
/** Reads again. */
|
|
111
|
+
refetch: () => void;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The store (`store.get()`): name, currency, theme, legal texts, checkout challenge. */
|
|
115
|
+
declare function useStore(): ResourceResult<Store>;
|
|
116
|
+
/** The active category tree (`categories.list()`). */
|
|
117
|
+
declare function useCategories(): ResourceResult<CategoryList>;
|
|
118
|
+
/**
|
|
119
|
+
* A page of products (`products.list(params)`). Reads again when a
|
|
120
|
+
* parameter changes, cancelling the previous read.
|
|
121
|
+
*/
|
|
122
|
+
declare function useProducts(params?: ProductListQuery): ResourceResult<ProductPage>;
|
|
123
|
+
/**
|
|
124
|
+
* One product by slug (`products.get(slug)`); an unknown slug is the
|
|
125
|
+
* error `product_not_found`. A null / empty slug reads nothing.
|
|
126
|
+
*/
|
|
127
|
+
declare function useProduct(slug: string | null | undefined): ResourceResult<Product>;
|
|
128
|
+
|
|
129
|
+
/** What {@link useCart} returns. */
|
|
130
|
+
interface UseCartResult extends CartSnapshot {
|
|
131
|
+
/** Total units in the cart (for a badge). */
|
|
132
|
+
itemCount: number;
|
|
133
|
+
/** Adds units of a variant. Creates the cart on the first write. */
|
|
134
|
+
addLine(input: AddLineInput): Promise<Cart>;
|
|
135
|
+
/** Sets a line's quantity. */
|
|
136
|
+
updateLine(variantId: string, input: UpdateLineInput): Promise<Cart>;
|
|
137
|
+
/** Removes a line. */
|
|
138
|
+
removeLine(variantId: string): Promise<Cart>;
|
|
139
|
+
/** Sets the buyer. */
|
|
140
|
+
setCustomer(input: CustomerInput): Promise<Cart>;
|
|
141
|
+
/** Sets the shipping (and billing) address. */
|
|
142
|
+
setAddress(input: AddressInput): Promise<Cart>;
|
|
143
|
+
/** Selects a shipping option. */
|
|
144
|
+
setShippingOption(optionId: string): Promise<Cart>;
|
|
145
|
+
/** The shipping options of the cart (`{ items: [] }` without a cart). */
|
|
146
|
+
shippingOptions(options?: RequestOptions): Promise<ShippingOptionList>;
|
|
147
|
+
/** Reads the cart again (a cart whose payment failed comes back `open`). */
|
|
148
|
+
refresh(): Promise<void>;
|
|
149
|
+
/** Forgets the cart (e.g. after its order is paid); the next write starts a new one. */
|
|
150
|
+
reset(): void;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* The buyer's cart, shared by every component under the provider.
|
|
154
|
+
*
|
|
155
|
+
* The saved cart id is read on mount (after hydration: nothing is read
|
|
156
|
+
* during render). No cart is created until the first write. Every write
|
|
157
|
+
* replaces the state with the server's cart view — prices are never
|
|
158
|
+
* computed locally. Writes reject with a {@link StorefrontHookError} (and
|
|
159
|
+
* also set `error`); a cart that expired or is unknown is forgotten, and
|
|
160
|
+
* the next write starts a new one.
|
|
161
|
+
*/
|
|
162
|
+
declare function useCart(): UseCartResult;
|
|
163
|
+
/**
|
|
164
|
+
* Where this provider keeps the cart id, as a getter (read it inside an
|
|
165
|
+
* effect or handler, never during render: it is null on a server). Lets a
|
|
166
|
+
* page that learns a cart id out of band (e.g. cart recovery) save it
|
|
167
|
+
* where the cart reads it, with `saveCartId(getStorage(), storeId, id)`.
|
|
168
|
+
*/
|
|
169
|
+
declare function useCartStorage(): () => CartIdStorage | null;
|
|
170
|
+
|
|
171
|
+
/** What {@link useAccount} returns. */
|
|
172
|
+
interface UseAccountResult {
|
|
173
|
+
/** The signed-in buyer's account, or null. */
|
|
174
|
+
account: Account | null;
|
|
175
|
+
/** `loading` until the first read answers; `signedOut` on a 401. */
|
|
176
|
+
status: 'loading' | 'signedOut' | 'signedIn';
|
|
177
|
+
/**
|
|
178
|
+
* The last read's error when it was not a 401 (e.g. network, timeout),
|
|
179
|
+
* else null. The status is `signedOut` then, unless an earlier read
|
|
180
|
+
* succeeded (the account is kept).
|
|
181
|
+
*/
|
|
182
|
+
error: StorefrontHookError | null;
|
|
183
|
+
/** Reads the account again (call after sign-in, sign-out or a save). */
|
|
184
|
+
refresh(): Promise<void>;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* The buyer's account (`client.account.get()`), read after mount. A 401
|
|
188
|
+
* (no or an ended session) means `signedOut`. Sign in / out and saves go
|
|
189
|
+
* through `useStorefrontClient().account`; call `refresh()` afterwards.
|
|
190
|
+
*/
|
|
191
|
+
declare function useAccount(): UseAccountResult;
|
|
192
|
+
|
|
193
|
+
/** Options of `checkout()`. */
|
|
194
|
+
interface CheckoutCallOptions {
|
|
195
|
+
/**
|
|
196
|
+
* The checkout challenge token (from `<CheckoutChallenge>`), required
|
|
197
|
+
* when `store.checkoutChallenge` is set. Single-use.
|
|
198
|
+
*/
|
|
199
|
+
turnstileToken?: string | null;
|
|
200
|
+
}
|
|
201
|
+
/** What {@link useCheckout} returns. */
|
|
202
|
+
interface UseCheckoutResult extends CheckoutSnapshot {
|
|
203
|
+
/**
|
|
204
|
+
* Checks the cart out: `carts.checkout(cartId, { turnstileToken })`.
|
|
205
|
+
* Resolves with the result (present it with `<PaymentForm>`; keep its
|
|
206
|
+
* `token`, returned only once) or rejects with the error (also in
|
|
207
|
+
* `error`). A call while one is in flight returns the same promise.
|
|
208
|
+
*/
|
|
209
|
+
checkout(options?: CheckoutCallOptions): Promise<CheckoutResult>;
|
|
210
|
+
/** Clears `result` and `error`. */
|
|
211
|
+
reset(): void;
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Checkout for the provider's cart. The state is shared under the
|
|
215
|
+
* provider, and a checkout is **never aborted** — not even when the
|
|
216
|
+
* component unmounts — because the server may place the order anyway.
|
|
217
|
+
* When a component using this hook mounts after a checkout was started,
|
|
218
|
+
* the cart is read again so it shows what the server has.
|
|
219
|
+
*
|
|
220
|
+
* Errors are {@link StorefrontError}s: switch on `error.code`. For
|
|
221
|
+
* `cart_changed`, `error.details` has the new `lines`, totals and
|
|
222
|
+
* `shippingOptions` (the cart is also read again): show them and let the
|
|
223
|
+
* buyer confirm before calling `checkout()` again — never retry silently.
|
|
224
|
+
*/
|
|
225
|
+
declare function useCheckout(): UseCheckoutResult;
|
|
226
|
+
|
|
227
|
+
/** First poll delay, milliseconds. */
|
|
228
|
+
declare const ORDER_POLL_MIN_MS = 2000;
|
|
229
|
+
/** Longest poll delay, milliseconds. */
|
|
230
|
+
declare const ORDER_POLL_MAX_MS = 15000;
|
|
231
|
+
/** The delay before poll number `attempt` (0-based): 2 s, 4 s, 8 s, then 15 s. */
|
|
232
|
+
declare function orderPollDelay(attempt: number): number;
|
|
233
|
+
/**
|
|
234
|
+
* Whether an order no longer changes on its own soon: anything past
|
|
235
|
+
* `pendingPayment` (`paid`, `fulfilling`, `shipped`, `delivered`,
|
|
236
|
+
* `cancelled`, `refunded`, …), or a pending order whose payment `failed`
|
|
237
|
+
* / `expired` (the buyer has to check out again).
|
|
238
|
+
*/
|
|
239
|
+
declare function isOrderSettled(order: Order): boolean;
|
|
240
|
+
/** Options of {@link useOrder}. */
|
|
241
|
+
interface UseOrderOptions {
|
|
242
|
+
/**
|
|
243
|
+
* Keep reading until the order is settled ({@link isOrderSettled}),
|
|
244
|
+
* backing off 2 s → 4 s → 8 s → 15 s (then every 15 s). Transient
|
|
245
|
+
* errors (network, timeout, throttling, `order_unavailable`) keep
|
|
246
|
+
* polling; others stop it.
|
|
247
|
+
*/
|
|
248
|
+
pollUntilFinal?: boolean;
|
|
249
|
+
}
|
|
250
|
+
/** What {@link useOrder} returns. */
|
|
251
|
+
interface UseOrderResult {
|
|
252
|
+
/** The order, or null before it arrives. Kept through a failed poll. */
|
|
253
|
+
order: Order | null;
|
|
254
|
+
/** The last read's error, or null. */
|
|
255
|
+
error: StorefrontHookError | null;
|
|
256
|
+
/** The first read is in progress. */
|
|
257
|
+
isLoading: boolean;
|
|
258
|
+
/** Another read is scheduled. */
|
|
259
|
+
isPolling: boolean;
|
|
260
|
+
/** Reads again now (and restarts polling). */
|
|
261
|
+
refetch: () => void;
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* The buyer's order (`orders.get(orderId, token)`), e.g. on the page the
|
|
265
|
+
* payment provider returns to (`/orders/{orderId}?token=`). The token is
|
|
266
|
+
* the buyer's only key to the order: this hook never logs it or puts it
|
|
267
|
+
* anywhere but the request; do not send it to analytics either.
|
|
268
|
+
*/
|
|
269
|
+
declare function useOrder(orderId: string | null | undefined, token: string | null | undefined, options?: UseOrderOptions): UseOrderResult;
|
|
270
|
+
|
|
271
|
+
/** Props of {@link PaymentForm}. */
|
|
272
|
+
interface PaymentFormProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'onError'> {
|
|
273
|
+
/**
|
|
274
|
+
* The **unmodified** result of `checkout()` (or its presentation part).
|
|
275
|
+
* Never build it from user input, URL parameters or storage: embedded
|
|
276
|
+
* content runs as script.
|
|
277
|
+
*/
|
|
278
|
+
presentation: PaymentPresentation | CheckoutResult;
|
|
279
|
+
/**
|
|
280
|
+
* Payment cannot be (re)opened (`presentation: "closed"`): show the
|
|
281
|
+
* order status page for `page` (`paid`, `cancelled`, `processing`, …).
|
|
282
|
+
*/
|
|
283
|
+
onClosed?: (page: ClosedCheckoutPage) => void;
|
|
284
|
+
/** The embed is of a kind this SDK cannot render: show a fallback. */
|
|
285
|
+
onUnsupported?: (embedKind: string) => void;
|
|
286
|
+
/** Presenting failed (e.g. a redirect URL that is not http(s)). */
|
|
287
|
+
onError?: (error: Error) => void;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Presents payment with the SDK's `mountPayment`: renders the provider's
|
|
291
|
+
* embedded form inside a `<div>` (its scripts run once), sends the browser
|
|
292
|
+
* to a `redirect` URL, or calls `onClosed`. The form is removed on
|
|
293
|
+
* unmount. Card data never passes through your code. Unstyled: pass
|
|
294
|
+
* `className` / `style` for the wrapper.
|
|
295
|
+
*/
|
|
296
|
+
declare function PaymentForm({ presentation, onClosed, onUnsupported, onError, ...divProps }: PaymentFormProps): react.JSX.Element;
|
|
297
|
+
|
|
298
|
+
/** Props of {@link CheckoutChallenge}. */
|
|
299
|
+
interface CheckoutChallengeProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'onError'> {
|
|
300
|
+
/**
|
|
301
|
+
* The store's Turnstile site key (`store.checkoutChallenge?.siteKey`).
|
|
302
|
+
* Null / empty renders an empty `<div>` (the store has no challenge).
|
|
303
|
+
*/
|
|
304
|
+
siteKey: string | null | undefined;
|
|
305
|
+
/** A token is ready: pass it to `checkout({ turnstileToken })`. */
|
|
306
|
+
onToken: (token: string) => void;
|
|
307
|
+
/**
|
|
308
|
+
* The current token can no longer be used — it expired, or a checkout
|
|
309
|
+
* consumed it and the widget was reset. Drop it; a new one follows.
|
|
310
|
+
*/
|
|
311
|
+
onExpired?: () => void;
|
|
312
|
+
/** The widget failed to load or render. */
|
|
313
|
+
onError?: (error: Error | string | undefined) => void;
|
|
314
|
+
}
|
|
315
|
+
/** Imperative handle of {@link CheckoutChallenge} (via `ref`). */
|
|
316
|
+
interface CheckoutChallengeHandle {
|
|
317
|
+
/** Gets a new token (the current one is dropped: `onExpired` is called). */
|
|
318
|
+
reset(): void;
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Renders the store's checkout challenge (Cloudflare Turnstile) with the
|
|
322
|
+
* SDK's `renderTurnstile`. Tokens are single-use: under a
|
|
323
|
+
* `StorefrontProvider` the widget resets itself after every checkout
|
|
324
|
+
* attempt of `useCheckout()`; call `ref.current.reset()` to reset it
|
|
325
|
+
* yourself. The widget is removed on unmount.
|
|
326
|
+
*/
|
|
327
|
+
declare const CheckoutChallenge: react.ForwardRefExoticComponent<CheckoutChallengeProps & react.RefAttributes<CheckoutChallengeHandle>>;
|
|
328
|
+
|
|
329
|
+
/** Components by tag name (`ProductGrid`, `Button`, …), e.g. to replace a default. */
|
|
330
|
+
type ContentComponents = Record<string, ComponentType<any>>;
|
|
331
|
+
/**
|
|
332
|
+
* Renders a store-content tree (`StoreContent.tree`) with React. Only
|
|
333
|
+
* plain text tags and the known components are rendered (raw images,
|
|
334
|
+
* unknown tags, ids, styles and event handlers are dropped); output goes
|
|
335
|
+
* through `Markdoc.renderers.react`, never as HTML. The default components
|
|
336
|
+
* (`ProductGrid`, `Product`, `CategoryLink`, `Image`, `Button`) need a
|
|
337
|
+
* `<StorefrontProvider>`; `components` replaces or adds components. A
|
|
338
|
+
* component gets an `Image` / custom tag's `key` attribute as `contentKey`.
|
|
339
|
+
*/
|
|
340
|
+
declare function renderContent(tree: ContentNode, components?: ContentComponents): ReactNode;
|
|
341
|
+
/** Props of {@link Content}. */
|
|
342
|
+
interface ContentProps {
|
|
343
|
+
/** The content key (`home.hero`, `about-us`, …). */
|
|
344
|
+
contentKey: string;
|
|
345
|
+
/** Components by tag name, replacing or adding to the defaults. */
|
|
346
|
+
components?: ContentComponents;
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* A piece of store content (Markdoc written in the console), read by key
|
|
350
|
+
* from the store. Renders nothing while loading, or when the key does not
|
|
351
|
+
* exist or cannot be read (a warning in development only).
|
|
352
|
+
*/
|
|
353
|
+
declare function Content({ contentKey, components }: ContentProps): ReactNode;
|
|
354
|
+
|
|
355
|
+
export { type CartSnapshot, type CheckoutCallOptions, CheckoutChallenge, type CheckoutChallengeHandle, type CheckoutChallengeProps, type CheckoutSnapshot, type ClientConfig, Content, type ContentComponents, type ContentProps, ORDER_POLL_MAX_MS, ORDER_POLL_MIN_MS, PaymentForm, type PaymentFormProps, type ResourceResult, type StorefrontHookError, StorefrontProvider, type StorefrontProviderProps, type UseAccountResult, type UseCartResult, type UseCheckoutResult, type UseOrderOptions, type UseOrderResult, defaultCartStorage, isDeadCartError, isOrderSettled, orderPollDelay, renderContent, useAccount, useCart, useCartStorage, useCategories, useCheckout, useOrder, useProduct, useProducts, useStore, useStorefrontClient };
|