@simpleapps-com/augur-hooks 2.4.0 → 2026.11.2

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.
Files changed (103) hide show
  1. package/EXPORTS.md +25 -65
  2. package/README.md +21 -246
  3. package/dist/checkout/create-checkout-provider.d.ts +25 -0
  4. package/dist/checkout/create-checkout-provider.d.ts.map +1 -0
  5. package/dist/checkout/index.cjs +123 -106
  6. package/dist/checkout/index.cjs.map +1 -1
  7. package/dist/checkout/index.d.ts +5 -293
  8. package/dist/checkout/index.d.ts.map +1 -0
  9. package/dist/checkout/index.js +99 -82
  10. package/dist/checkout/index.js.map +1 -1
  11. package/dist/checkout/{index.d.cts → types.d.ts} +18 -40
  12. package/dist/checkout/types.d.ts.map +1 -0
  13. package/dist/chunk-6Z6JGK2C.cjs.map +1 -1
  14. package/dist/chunk-JJX23M5N.js +532 -0
  15. package/dist/chunk-JJX23M5N.js.map +1 -0
  16. package/dist/chunk-UZAFXUAO.cjs +532 -0
  17. package/dist/chunk-UZAFXUAO.cjs.map +1 -0
  18. package/dist/duration.d.ts +16 -0
  19. package/dist/duration.d.ts.map +1 -0
  20. package/dist/hooks/use-cart-actions.d.ts +68 -0
  21. package/dist/hooks/use-cart-actions.d.ts.map +1 -0
  22. package/dist/hooks/use-cart-initialization.d.ts +60 -0
  23. package/dist/hooks/use-cart-initialization.d.ts.map +1 -0
  24. package/dist/hooks/use-cart-pricing.d.ts +41 -0
  25. package/dist/hooks/use-cart-pricing.d.ts.map +1 -0
  26. package/dist/hooks/use-checkout-persistence.d.ts +41 -0
  27. package/dist/hooks/use-checkout-persistence.d.ts.map +1 -0
  28. package/dist/hooks/use-debounce.d.ts +6 -0
  29. package/dist/hooks/use-debounce.d.ts.map +1 -0
  30. package/dist/hooks/use-format-price.d.ts +29 -0
  31. package/dist/hooks/use-format-price.d.ts.map +1 -0
  32. package/dist/hooks/use-latest.d.ts +8 -0
  33. package/dist/hooks/use-latest.d.ts.map +1 -0
  34. package/dist/hooks/use-modal-lifecycle.d.ts +11 -0
  35. package/dist/hooks/use-modal-lifecycle.d.ts.map +1 -0
  36. package/dist/hooks/use-order-readiness.d.ts +47 -0
  37. package/dist/hooks/use-order-readiness.d.ts.map +1 -0
  38. package/dist/hooks/use-pagination-prefetch.d.ts +27 -0
  39. package/dist/hooks/use-pagination-prefetch.d.ts.map +1 -0
  40. package/dist/{use-order-readiness-DZTIfRzw.d.ts → hooks/use-payment-flow.d.ts} +23 -67
  41. package/dist/hooks/use-payment-flow.d.ts.map +1 -0
  42. package/dist/hooks/use-stock.d.ts +32 -0
  43. package/dist/hooks/use-stock.d.ts.map +1 -0
  44. package/dist/index.cjs +227 -184
  45. package/dist/index.cjs.map +1 -1
  46. package/dist/index.d.ts +32 -456
  47. package/dist/index.d.ts.map +1 -0
  48. package/dist/index.js +205 -162
  49. package/dist/index.js.map +1 -1
  50. package/dist/persistence/apply-limits.d.ts +8 -0
  51. package/dist/persistence/apply-limits.d.ts.map +1 -0
  52. package/dist/persistence/create-persister.d.ts +10 -0
  53. package/dist/persistence/create-persister.d.ts.map +1 -0
  54. package/dist/persistence/serializer.d.ts +11 -0
  55. package/dist/persistence/serializer.d.ts.map +1 -0
  56. package/dist/persistence/use-persistence.d.ts +59 -0
  57. package/dist/persistence/use-persistence.d.ts.map +1 -0
  58. package/dist/persistence/use-storage-monitor.d.ts +11 -0
  59. package/dist/persistence/use-storage-monitor.d.ts.map +1 -0
  60. package/dist/provider.d.ts +89 -0
  61. package/dist/provider.d.ts.map +1 -0
  62. package/dist/queries/batch-query.d.ts +23 -0
  63. package/dist/queries/batch-query.d.ts.map +1 -0
  64. package/dist/queries/index.d.ts +3 -0
  65. package/dist/queries/index.d.ts.map +1 -0
  66. package/dist/query-action-registry.d.ts +19 -0
  67. package/dist/query-action-registry.d.ts.map +1 -0
  68. package/dist/rules.d.ts +133 -0
  69. package/dist/rules.d.ts.map +1 -0
  70. package/dist/server.cjs +2 -1
  71. package/dist/server.cjs.map +1 -1
  72. package/dist/server.d.ts +10 -12
  73. package/dist/server.d.ts.map +1 -0
  74. package/dist/server.js +2 -1
  75. package/dist/server.js.map +1 -1
  76. package/dist/stores/cart-store.d.ts +51 -0
  77. package/dist/stores/cart-store.d.ts.map +1 -0
  78. package/dist/stores/items-filters-store.d.ts +30 -0
  79. package/dist/stores/items-filters-store.d.ts.map +1 -0
  80. package/dist/types.d.ts +48 -0
  81. package/dist/types.d.ts.map +1 -0
  82. package/dist/web/use-image-with-fallback.d.ts +16 -0
  83. package/dist/web/use-image-with-fallback.d.ts.map +1 -0
  84. package/dist/web/use-mobile-detection.d.ts +28 -0
  85. package/dist/web/use-mobile-detection.d.ts.map +1 -0
  86. package/dist/web/use-mobile-optimized-intersection.d.ts +17 -0
  87. package/dist/web/use-mobile-optimized-intersection.d.ts.map +1 -0
  88. package/dist/web.cjs.map +1 -1
  89. package/dist/web.d.ts +4 -60
  90. package/dist/web.d.ts.map +1 -0
  91. package/dist/web.js.map +1 -1
  92. package/llms.txt +76 -54
  93. package/package.json +26 -14
  94. package/dist/batch-query-CTlvxSmL.d.cts +0 -165
  95. package/dist/batch-query-CTlvxSmL.d.ts +0 -165
  96. package/dist/chunk-F5DUFW57.cjs +0 -383
  97. package/dist/chunk-F5DUFW57.cjs.map +0 -1
  98. package/dist/chunk-JNOHB4OP.js +0 -383
  99. package/dist/chunk-JNOHB4OP.js.map +0 -1
  100. package/dist/index.d.cts +0 -456
  101. package/dist/server.d.cts +0 -44
  102. package/dist/use-order-readiness-DZTIfRzw.d.cts +0 -137
  103. package/dist/web.d.cts +0 -60
@@ -1,293 +1,5 @@
1
- import { ReactNode, ReactElement } from 'react';
2
- import { a as PaymentFlowCallbacks, O as OrderReadinessParams } from '../use-order-readiness-DZTIfRzw.js';
3
- import { TCardInfo, TAccountQuery, TCartLine, CustomerDocument } from '@simpleapps-com/augur-utils';
4
- export { TCartLine } from '@simpleapps-com/augur-utils';
5
-
6
- /**
7
- * Address shape used by the checkout state machine.
8
- *
9
- * Core fields match augur-utils ShippingAddressSchema/BillingAddressSchema.
10
- * Index signature allows sites to pass schema outputs without casting.
11
- */
12
- interface CheckoutAddress {
13
- address1: string;
14
- address2?: string;
15
- city: string;
16
- state: string;
17
- postalCode: string;
18
- country?: string;
19
- firstName?: string;
20
- lastName?: string;
21
- /** Company name. Matches augur-utils ShippingAddressSchema field. */
22
- companyName?: string;
23
- /** Phone number. Matches augur-utils ShippingAddressSchema field. */
24
- phoneNumber?: string;
25
- email?: string;
26
- notes?: string;
27
- /** ZIP+4 code for tax calculation precision. */
28
- plus4Code?: string;
29
- /** PO number (billing addresses). */
30
- poNumber?: string;
31
- /** Allow additional fields from augur-utils schemas without casting. */
32
- [key: string]: unknown;
33
- }
34
- /** Default checkout steps. Sites can use any string as a step name. */
35
- type DefaultCheckoutStep = "shipping" | "method" | "billing" | "payment" | "review";
36
- /** Shipping configuration for the checkout provider. */
37
- interface CheckoutShippingConfig {
38
- /** Map of carrier ID to display name. */
39
- carriers: Record<string, string>;
40
- /** Default carrier ID selected on load. */
41
- defaultCarrierId: string;
42
- /** Free shipping thresholds by customer class. Key is class code, value is dollar threshold. */
43
- freeShippingThresholds?: Record<string, number>;
44
- }
45
- /**
46
- * Payment configuration for the checkout provider.
47
- * Entirely optional -- B2B sites without payment processing omit this.
48
- */
49
- interface CheckoutPaymentConfig {
50
- /** Allowed postMessage origins for the payment iframe. */
51
- allowedOrigins?: string[];
52
- /** Whether invoice payment is available. Receives auth context. */
53
- allowInvoice?: (auth: {
54
- isAuthenticated: boolean;
55
- [key: string]: unknown;
56
- }) => boolean;
57
- /** Payment server action callbacks for usePaymentFlow. Only needed for Element/Unified payment. */
58
- callbacks?: PaymentFlowCallbacks;
59
- /** Persist payment tokens to sessionStorage for cross-navigation recovery. Default: false. */
60
- persistence?: boolean;
61
- }
62
- /** Order configuration for the checkout provider. */
63
- interface CheckoutOrderConfig {
64
- /** Redirect path after successful order submission. */
65
- successRedirect: string;
66
- /** Custom redirect function. Default: window.location.href assignment. */
67
- redirect?: (url: string) => void;
68
- /** Persist order result to sessionStorage before redirect. Default: true. */
69
- persistence?: boolean;
70
- /** Submit the order. Receives assembled order data and cartHdrUid. */
71
- submitOrder: (orderData: Record<string, unknown>, cartHdrUid: number) => Promise<{
72
- ok: boolean;
73
- data?: unknown;
74
- error?: string;
75
- }>;
76
- /** Fetch client IP for fraud detection. Return undefined to skip. */
77
- fetchClientIp?: () => Promise<string | undefined>;
78
- /**
79
- * Calculate tax for the current checkout state. Called when billing address changes.
80
- * Sites choose their own tax engine (pricing.taxEngine, Avalara, or none).
81
- * Return the tax amount or undefined to skip.
82
- */
83
- calculateTax?: (params: {
84
- customerId?: string | number;
85
- postalCode: string;
86
- items: unknown[];
87
- customerDoc: CustomerDocument | null;
88
- }) => Promise<number | undefined>;
89
- }
90
- /** UI callbacks for the checkout provider. */
91
- interface CheckoutUIConfig {
92
- /** Called when an error needs to be displayed to the user. */
93
- onError?: (title: string, message: string) => void;
94
- }
95
- /** Identity resolution — how the provider resolves customer/contact/user. */
96
- interface CheckoutIdentityConfig {
97
- /** Current user session. */
98
- userId?: string | number;
99
- userEmail?: string;
100
- contactId?: string | number;
101
- customerId?: string | number;
102
- companyId?: string;
103
- isAuthenticated?: boolean;
104
- /** Fetch customer document. Called once on mount with customerId. */
105
- fetchCustomerDoc?: (customerId: string | number) => Promise<CustomerDocument | null>;
106
- }
107
- /**
108
- * Lifecycle hooks that sites inject for customization.
109
- *
110
- * Hooks SHOULD be referenced stably (defined at module scope or memoized
111
- * with `useMemo` / `useCallback`). A fresh function identity on every render
112
- * is tolerated today but may cause redundant effect runs if dependency
113
- * handling tightens in future versions.
114
- */
115
- interface CheckoutLifecycleHooks<TCustom extends Record<string, unknown>> {
116
- /**
117
- * Called after shipping address is accepted.
118
- *
119
- * The 3rd argument is the shipping-resolved `TOrderCartLine[]` shape
120
- * (snake_case P21 payload), not the raw `TCartLine[]` from the cart store.
121
- * Read raw cart lines from `CheckoutContextValue.cartLines` instead.
122
- */
123
- onShippingAccepted?: (ctx: CheckoutContext<TCustom>, address: CheckoutAddress, orderCartLines: unknown[]) => void;
124
- /** Called before order submission. Return false to cancel. */
125
- onBeforeSubmit?: (ctx: CheckoutContext<TCustom>) => boolean | void;
126
- /** Called after successful order submission. */
127
- onAfterSubmit?: (ctx: CheckoutContext<TCustom>, result: unknown) => void;
128
- /** Called when the user moves between checkout steps. */
129
- onStepChange?: (ctx: CheckoutContext<TCustom>, fromStep: string, toStep: string) => void;
130
- /** Custom validation. Return a string to block submission with a message. */
131
- onValidate?: (ctx: CheckoutContext<TCustom>) => string | undefined;
132
- /**
133
- * Resolve the default payment method. Called once on mount.
134
- *
135
- * When omitted, the provider defaults to `"credit-card"` if
136
- * `config.payments.callbacks` is configured and `"invoice"` otherwise.
137
- * Sites with non-standard flows (sample-only, invoice-only) SHOULD
138
- * return the correct default for their flow from here.
139
- */
140
- getDefaultPaymentMethod?: () => string;
141
- /** Assemble the order payload from checkout state. If not provided, uses buildCheckoutPayload. */
142
- assembleOrder?: (ctx: CheckoutContext<TCustom>, state: CheckoutContextValue<TCustom>) => {
143
- order: Record<string, unknown>;
144
- error?: string;
145
- };
146
- /**
147
- * Custom order-readiness check for non-standard order flows
148
- * (sample-only, pickup-only, invoice-only, quote-only).
149
- *
150
- * Return `true` or `false` to override the default Process Order
151
- * button gates (shipping-method, billing, credit-card validation).
152
- * Return `undefined` to defer to the default gates.
153
- *
154
- * Compose default gates with site-specific logic by invoking
155
- * `determineOrderReadiness` with a nulled override:
156
- *
157
- * ```ts
158
- * isOrderReady: (ctx, params) => {
159
- * if (!ctx.get("isSampleItems")) return undefined; // defer
160
- * return determineOrderReadiness({ ...params, customReadinessCheck: undefined });
161
- * }
162
- * ```
163
- */
164
- isOrderReady?: (ctx: CheckoutContext<TCustom>, params: OrderReadinessParams) => boolean | undefined;
165
- }
166
- /** Full checkout provider configuration. */
167
- interface CheckoutProviderConfig<TCustom extends Record<string, unknown> = Record<string, never>> {
168
- shipping: CheckoutShippingConfig;
169
- /** Payment config. Omit entirely for B2B sites without payment processing. */
170
- payments?: CheckoutPaymentConfig;
171
- order: CheckoutOrderConfig;
172
- identity?: CheckoutIdentityConfig;
173
- ui?: CheckoutUIConfig;
174
- hooks?: CheckoutLifecycleHooks<TCustom>;
175
- /** Type-safe custom state for site-specific values. */
176
- customState?: TCustom;
177
- /** Initial step. Default: "shipping". */
178
- initialStep?: string;
179
- }
180
- /** Mutable context object passed to lifecycle hooks. */
181
- interface CheckoutContext<TCustom extends Record<string, unknown>> {
182
- /** Get a custom state value. */
183
- get: <K extends keyof TCustom>(key: K) => TCustom[K];
184
- /** Set a custom state value. */
185
- set: <K extends keyof TCustom>(key: K, value: TCustom[K]) => void;
186
- /** Skip to a specific checkout step. */
187
- skipToStep: (step: string) => void;
188
- /** Set the billing address programmatically. */
189
- setBillingAddress: (address: CheckoutAddress) => void;
190
- /** Set the carrier ID programmatically. */
191
- setCarrierId: (carrierId: string) => void;
192
- }
193
- /** Payment modal state. Only present when payments.callbacks is provided. */
194
- interface CheckoutPaymentModal {
195
- isOpen: boolean;
196
- setIsOpen: (open: boolean) => void;
197
- editCc: boolean;
198
- setEditCc: (edit: boolean) => void;
199
- unified: unknown;
200
- unifiedCc: TCardInfo | null;
201
- unifiedResponse: boolean;
202
- unifiedBilling: boolean;
203
- unifiedPayment: TAccountQuery | null;
204
- handleBinCapture: (bin: string) => void;
205
- hasValidPayment: boolean;
206
- }
207
- /** Full checkout context value returned by useCheckout(). */
208
- interface CheckoutContextValue<TCustom extends Record<string, unknown> = Record<string, never>> {
209
- shippingAddress: CheckoutAddress | undefined;
210
- setShippingAddress: (address: CheckoutAddress | undefined) => void;
211
- shippingFee: number | undefined;
212
- setShippingFee: (fee: number | undefined) => void;
213
- shippingMethod: string | undefined;
214
- setShippingMethod: (method: string | undefined) => void;
215
- shippingAccepted: boolean;
216
- setShippingAccepted: (accepted: boolean) => void;
217
- shippingMethodSaved: boolean;
218
- setShippingMethodSaved: (saved: boolean) => void;
219
- isFreeShipping: boolean;
220
- setIsFreeShipping: (free: boolean) => void;
221
- carrierId: string;
222
- setCarrierId: (id: string) => void;
223
- showShippingMethod: boolean;
224
- setShowShippingMethod: (show: boolean) => void;
225
- billingAddress: CheckoutAddress | undefined;
226
- setBillingAddress: (address: CheckoutAddress | undefined) => void;
227
- paymentMethod: string;
228
- setPaymentMethod: (method: string) => void;
229
- showBillingInfoSummary: boolean;
230
- setShowBillingInfoSummary: (show: boolean) => void;
231
- paymentModal: CheckoutPaymentModal | undefined;
232
- /**
233
- * Raw cart lines from the cart store.
234
- *
235
- * Use this shape (camelCase: `invMastUid`, `itemId`, `quantity`, `unitOfMeasure`)
236
- * in `assembleOrder` for non-standard order paths (sample, pickup, invoice-only)
237
- * that bypass shipping-method resolution. For the shipping-resolved payload shape,
238
- * see `orderCartLines`.
239
- */
240
- cartLines: TCartLine[];
241
- orderCartLines: unknown[] | undefined;
242
- setOrderCartLines: (lines: unknown[]) => void;
243
- processingOrder: boolean;
244
- processOrder: () => Promise<void>;
245
- /** Reset processingOrder to false. Escape hatch for site-level error handlers. */
246
- resetProcessing: () => void;
247
- customerDoc: CustomerDocument | null;
248
- taxRate: number | undefined;
249
- setTaxRate: (rate: number | undefined) => void;
250
- clientIp: string | undefined;
251
- cartToken: string;
252
- isEditShippingInfo: boolean;
253
- setIsEditShippingInfo: (editing: boolean) => void;
254
- isEditShippingMethods: boolean;
255
- setIsEditShippingMethods: (editing: boolean) => void;
256
- isEditBillingInfo: boolean;
257
- setIsEditBillingInfo: (editing: boolean) => void;
258
- enableProcessOrderBtn: boolean;
259
- processingValidation: boolean;
260
- currentStep: string;
261
- goToStep: (step: string) => void;
262
- custom: TCustom;
263
- setCustom: <K extends keyof TCustom>(key: K, value: TCustom[K]) => void;
264
- config: CheckoutProviderConfig<TCustom>;
265
- }
266
- /** Props for the generated CheckoutProvider component. */
267
- interface CheckoutProviderProps {
268
- children: ReactNode;
269
- /** Runtime identity from hooks (useAugurAuth, useSession, etc.). Overrides config.identity. */
270
- identity?: CheckoutIdentityConfig;
271
- }
272
-
273
- /** sessionStorage key for persisted order confirmation data. */
274
- declare const ORDER_CONFIRMATION_KEY = "orderConfirmation";
275
- /** Shape of persisted order confirmation data. */
276
- interface OrderConfirmation {
277
- orderData: Record<string, unknown>;
278
- result: unknown;
279
- shippingAddress: CheckoutAddress | undefined;
280
- billingAddress: CheckoutAddress | undefined;
281
- shippingFee: number | undefined;
282
- shippingMethod: string | undefined;
283
- taxRate: number | undefined;
284
- paymentMethod: string;
285
- carrierId: string;
286
- orderCartLines: unknown[] | undefined;
287
- }
288
- declare function createCheckoutProvider<TCustom extends Record<string, unknown> = Record<string, never>>(config: CheckoutProviderConfig<TCustom>): {
289
- CheckoutProvider: ({ children, identity: propsIdentity, }: CheckoutProviderProps) => ReactElement;
290
- useCheckout: () => CheckoutContextValue<TCustom>;
291
- };
292
-
293
- export { type CheckoutAddress, type CheckoutContext, type CheckoutContextValue, type CheckoutIdentityConfig, type CheckoutLifecycleHooks, type CheckoutOrderConfig, type CheckoutPaymentConfig, type CheckoutPaymentModal, type CheckoutProviderConfig, type CheckoutProviderProps, type CheckoutShippingConfig, type CheckoutUIConfig, type DefaultCheckoutStep, ORDER_CONFIRMATION_KEY, type OrderConfirmation, createCheckoutProvider };
1
+ export { createCheckoutProvider, ORDER_CONFIRMATION_KEY } from "./create-checkout-provider";
2
+ export type { OrderConfirmation } from "./create-checkout-provider";
3
+ export type { CheckoutAddress, DefaultCheckoutStep, CheckoutShippingConfig, CheckoutPaymentConfig, CheckoutOrderConfig, CheckoutUIConfig, CheckoutIdentityConfig, CheckoutLifecycleHooks, CheckoutProviderConfig, CheckoutContext, CheckoutContextValue, CheckoutPaymentModal, CheckoutProviderProps, } from "./types";
4
+ export type { TCartLine } from "@simpleapps-com/augur-utils";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/checkout/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAC5F,YAAY,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AACpE,YAAY,EACV,eAAe,EACf,mBAAmB,EACnB,sBAAsB,EACtB,qBAAqB,EACrB,mBAAmB,EACnB,gBAAgB,EAChB,sBAAsB,EACtB,sBAAsB,EACtB,sBAAsB,EACtB,eAAe,EACf,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,GACtB,MAAM,SAAS,CAAC;AACjB,YAAY,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC"}
@@ -1,12 +1,17 @@
1
1
  import {
2
2
  PAYMENT_STORAGE_KEY,
3
+ checkoutCartUid,
3
4
  clearFromSession,
5
+ defaultPaymentMethodOf,
6
+ preSubmitOutcome,
7
+ secondEqualsField,
4
8
  useCartHdrUid,
5
9
  useCartLines,
6
10
  useClearCart,
11
+ useLatest,
7
12
  useOrderReadiness,
8
13
  usePaymentFlow
9
- } from "../chunk-JNOHB4OP.js";
14
+ } from "../chunk-JJX23M5N.js";
10
15
 
11
16
  // src/checkout/create-checkout-provider.tsx
12
17
  import {
@@ -24,16 +29,9 @@ function defaultRedirect(url) {
24
29
  window.location.href = url;
25
30
  }
26
31
  function runPreSubmitChecks(config, ctx, shippingAddress) {
27
- if (config.hooks?.onValidate) {
28
- const error = config.hooks.onValidate(ctx);
29
- if (error) return error;
30
- }
31
- if (config.hooks?.onBeforeSubmit) {
32
- const result = config.hooks.onBeforeSubmit(ctx);
33
- if (result === false) return "__cancelled__";
34
- }
35
- if (!shippingAddress) return "Shipping address is required.";
36
- return null;
32
+ const validateError = config.hooks?.onValidate?.(ctx);
33
+ const vetoed = !validateError && config.hooks?.onBeforeSubmit?.(ctx) === false;
34
+ return preSubmitOutcome(validateError, vetoed, !!shippingAddress);
37
35
  }
38
36
  function buildOrderData(s) {
39
37
  return {
@@ -62,12 +60,13 @@ function handleOrderError(config, setProcessingOrder, error) {
62
60
  }
63
61
  function resolveCartHdrUid(cartHdrUid) {
64
62
  if (typeof cartHdrUid === "string") return Number(cartHdrUid);
65
- return cartHdrUid ?? 0;
63
+ return checkoutCartUid(cartHdrUid);
66
64
  }
67
65
  function resolveDefaultPaymentMethod(config) {
68
- const explicit = config.hooks?.getDefaultPaymentMethod?.();
69
- if (explicit) return explicit;
70
- return config.payments?.callbacks ? "credit-card" : "invoice";
66
+ return defaultPaymentMethodOf(
67
+ config.hooks?.getDefaultPaymentMethod?.(),
68
+ !!config.payments?.callbacks
69
+ );
71
70
  }
72
71
  function buildReadinessOverride(config, ctxRef) {
73
72
  const siteIsOrderReady = config.hooks?.isOrderReady;
@@ -83,23 +82,23 @@ function assembleOrderPayload(config, ctx, contextValue, stateSnapshot) {
83
82
  return { orderData: buildOrderData(stateSnapshot) };
84
83
  }
85
84
  function validateOrderPayload(orderData) {
86
- if (orderData === null || typeof orderData !== "object" || Array.isArray(orderData)) {
87
- return "Order payload is empty or malformed.";
88
- }
89
- if ("lines" in orderData) {
90
- const lines = orderData["lines"];
91
- if (!Array.isArray(lines) || lines.length === 0) {
92
- return "Order has no line items.";
93
- }
94
- }
95
- if ("header" in orderData) {
96
- const header = orderData["header"];
97
- if (header !== null && typeof header === "object" && !Array.isArray(header)) {
98
- const customerId = header["customer_id"];
99
- if (customerId == null || String(customerId).trim() === "") {
100
- return "Order is missing a customer.";
101
- }
102
- }
85
+ if (!isPlainObject(orderData)) return "Order payload is empty or malformed.";
86
+ return linesError(orderData) ?? headerError(orderData);
87
+ }
88
+ function isPlainObject(value) {
89
+ return value !== null && typeof value === "object" && !Array.isArray(value);
90
+ }
91
+ function linesError(orderData) {
92
+ if (!("lines" in orderData)) return null;
93
+ const lines = orderData["lines"];
94
+ return Array.isArray(lines) && lines.length > 0 ? null : "Order has no line items.";
95
+ }
96
+ function headerError(orderData) {
97
+ const header = orderData["header"];
98
+ if (!isPlainObject(header)) return null;
99
+ const customerId = header["customer_id"];
100
+ if (customerId == null || String(customerId).trim() === "") {
101
+ return "Order is missing a customer.";
103
102
  }
104
103
  return null;
105
104
  }
@@ -156,15 +155,30 @@ function handleOrderSuccess(config, ctx, resultData, confirmation, setProcessing
156
155
  redirect(config.order.successRedirect);
157
156
  setProcessingOrder(false);
158
157
  }
158
+ function preSubmitBlocked(config, ctx, shippingAddress) {
159
+ const preCheck = runPreSubmitChecks(config, ctx, shippingAddress);
160
+ if (preCheck.kind === "refused") config.ui?.onError?.("Missing Information", preCheck.message);
161
+ return preCheck.kind !== "ok";
162
+ }
163
+ async function submitOrderOnce(config, orderData, cartHdrUid, setProcessingOrder) {
164
+ let result;
165
+ try {
166
+ result = await config.order.submitOrder(orderData, resolveCartHdrUid(cartHdrUid));
167
+ } catch (error) {
168
+ handleOrderError(config, setProcessingOrder, error);
169
+ return null;
170
+ }
171
+ if (!result.ok) {
172
+ setProcessingOrder(false);
173
+ config.ui?.onError?.("Order Failed", result.error ?? "Something went wrong.");
174
+ return null;
175
+ }
176
+ return { data: result.data };
177
+ }
159
178
  async function executeOrder(config, ctxRef, stateRef, contextValueRef, cartHdrUid, setProcessingOrder, redirect, queryClient, clearCart) {
160
179
  const ctx = ctxRef.current;
161
180
  const s = stateRef.current;
162
- const preCheck = runPreSubmitChecks(config, ctx, s.shippingAddress);
163
- if (preCheck === "__cancelled__") return;
164
- if (preCheck) {
165
- config.ui?.onError?.("Missing Information", preCheck);
166
- return;
167
- }
181
+ if (preSubmitBlocked(config, ctx, s.shippingAddress)) return;
168
182
  setProcessingOrder(true);
169
183
  const orderData = prepareOrderPayload(
170
184
  config,
@@ -174,18 +188,8 @@ async function executeOrder(config, ctxRef, stateRef, contextValueRef, cartHdrUi
174
188
  setProcessingOrder
175
189
  );
176
190
  if (!orderData) return;
177
- let result;
178
- try {
179
- result = await config.order.submitOrder(orderData, resolveCartHdrUid(cartHdrUid));
180
- } catch (error) {
181
- handleOrderError(config, setProcessingOrder, error);
182
- return;
183
- }
184
- if (!result.ok) {
185
- setProcessingOrder(false);
186
- config.ui?.onError?.("Order Failed", result.error ?? "Something went wrong.");
187
- return;
188
- }
191
+ const result = await submitOrderOnce(config, orderData, cartHdrUid, setProcessingOrder);
192
+ if (!result) return;
189
193
  const confirmation = buildOrderConfirmation(
190
194
  orderData,
191
195
  result.data,
@@ -211,8 +215,29 @@ var NOOP_PAYMENT_CALLBACKS = {
211
215
  billingUpdate: async () => void 0
212
216
  };
213
217
  var Ctx = createContext(null);
218
+ function buildPaymentModal(hasPaymentFlow, payment) {
219
+ if (!hasPaymentFlow) return void 0;
220
+ return {
221
+ isOpen: payment.isOpen,
222
+ setIsOpen: payment.setIsOpen,
223
+ editCc: payment.editCc,
224
+ setEditCc: payment.setEditCc,
225
+ unified: payment.unified,
226
+ unifiedCc: payment.unifiedCc,
227
+ unifiedResponse: payment.unifiedResponse,
228
+ unifiedBilling: payment.unifiedBilling,
229
+ unifiedPayment: payment.unifiedPayment,
230
+ handleBinCapture: payment.handleBinCapture,
231
+ hasValidPayment: !!payment.unifiedPayment?.PaymentAccountID
232
+ };
233
+ }
234
+ function cartTokenFrom(doc) {
235
+ const match = doc?.cookie.split(";").find((c) => c.trim().startsWith("cartToken="));
236
+ return (match === void 0 ? "" : secondEqualsField(match)) || void 0;
237
+ }
214
238
  function createCheckoutProvider(config) {
215
239
  const hasPaymentFlow = !!config.payments?.callbacks;
240
+ const paymentCallbacks = config.payments?.callbacks ?? NOOP_PAYMENT_CALLBACKS;
216
241
  function CheckoutProvider({
217
242
  children,
218
243
  identity: propsIdentity
@@ -246,26 +271,14 @@ function createCheckoutProvider(config) {
246
271
  }, []);
247
272
  const identity = propsIdentity ?? config.identity;
248
273
  const payment = usePaymentFlow({
249
- callbacks: config.payments?.callbacks ?? NOOP_PAYMENT_CALLBACKS,
274
+ callbacks: paymentCallbacks,
250
275
  customerId: identity?.customerId,
251
276
  billingAddress,
252
277
  paymentMethod,
253
278
  shippingAccepted,
254
279
  persistPayment: config.payments?.persistence
255
280
  });
256
- const paymentModal = hasPaymentFlow ? {
257
- isOpen: payment.isOpen,
258
- setIsOpen: payment.setIsOpen,
259
- editCc: payment.editCc,
260
- setEditCc: payment.setEditCc,
261
- unified: payment.unified,
262
- unifiedCc: payment.unifiedCc,
263
- unifiedResponse: payment.unifiedResponse,
264
- unifiedBilling: payment.unifiedBilling,
265
- unifiedPayment: payment.unifiedPayment,
266
- handleBinCapture: payment.handleBinCapture,
267
- hasValidPayment: !!payment.unifiedPayment?.PaymentAccountID
268
- } : void 0;
281
+ const paymentModal = buildPaymentModal(hasPaymentFlow, payment);
269
282
  const ctxRef = useRef(null);
270
283
  ctxRef.current = {
271
284
  get: (key) => customState[key],
@@ -325,41 +338,45 @@ function createCheckoutProvider(config) {
325
338
  void config.order.fetchClientIp().then(setClientIp);
326
339
  }
327
340
  }, []);
341
+ const identityRef = useLatest(identity);
342
+ const customerId = identity?.customerId;
328
343
  useEffect(() => {
329
- const custId = identity?.customerId;
330
- if (custId && identity?.fetchCustomerDoc) {
331
- void identity.fetchCustomerDoc(custId).then(setCustomerDoc).catch(() => setCustomerDoc(null));
344
+ const current = identityRef.current;
345
+ if (customerId && current?.fetchCustomerDoc) {
346
+ void current.fetchCustomerDoc(customerId).then(setCustomerDoc).catch(() => setCustomerDoc(null));
332
347
  }
333
- }, [identity?.customerId]);
348
+ }, [customerId, identityRef]);
349
+ const customerDocRef = useLatest(customerDoc);
350
+ const postalCode = billingAddress?.postalCode;
334
351
  useEffect(() => {
335
- if (!config.order.calculateTax || !billingAddress?.postalCode) return;
352
+ if (!config.order.calculateTax || !postalCode) return;
336
353
  void config.order.calculateTax({
337
- customerId: identity?.customerId,
338
- postalCode: billingAddress.postalCode,
354
+ customerId: identityRef.current?.customerId,
355
+ postalCode,
339
356
  items: orderCartLines ?? [],
340
- customerDoc
357
+ customerDoc: customerDocRef.current
341
358
  }).then((tax) => {
342
359
  if (tax !== void 0) setTaxRate(tax);
343
360
  });
344
- }, [billingAddress?.postalCode, orderCartLines]);
361
+ }, [postalCode, orderCartLines, identityRef, customerDocRef]);
345
362
  useEffect(() => {
346
363
  if (shippingAccepted && shippingAddress && !billingAddress) {
347
364
  setBillingAddress(shippingAddress);
348
365
  }
349
366
  }, [shippingAccepted, shippingAddress, billingAddress]);
367
+ const orderCartLinesRef = useLatest(orderCartLines);
350
368
  useEffect(() => {
351
369
  if (config.hooks?.onShippingAccepted && shippingAccepted && shippingAddress) {
352
- config.hooks.onShippingAccepted(ctxRef.current, shippingAddress, orderCartLines ?? []);
370
+ config.hooks.onShippingAccepted(
371
+ ctxRef.current,
372
+ shippingAddress,
373
+ orderCartLinesRef.current ?? []
374
+ );
353
375
  }
354
- }, [shippingAccepted, shippingAddress]);
376
+ }, [shippingAccepted, shippingAddress, orderCartLinesRef]);
355
377
  useEffect(() => {
356
- if (typeof document === "undefined") return;
357
- const cookies = document.cookie.split(";");
358
- const match = cookies.find((c) => c.trim().startsWith("cartToken="));
359
- if (match) {
360
- const token = match.split("=")[1];
361
- if (token) setCartToken(token);
362
- }
378
+ const token = cartTokenFrom(globalThis.document);
379
+ if (token) setCartToken(token);
363
380
  }, []);
364
381
  const resetProcessing = useCallback(() => setProcessingOrder(false), []);
365
382
  const isProcessingRef = useRef(false);