@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.
@@ -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 (`lineId` is `CartLine.id`). */
136
+ updateLine(lineId: string, input: UpdateLineInput): Promise<Cart>;
137
+ /** Removes a line. */
138
+ removeLine(lineId: 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 };