@simpleapps-com/augur-hooks 2.3.1 → 2.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.
@@ -115,6 +115,7 @@ function usePaymentFlow({
115
115
  }, []);
116
116
  const customerIdRef = useRef2(customerId);
117
117
  customerIdRef.current = customerId;
118
+ const hasVerifiedRef = useRef2(null);
118
119
  const postUnified = useCallback(async () => {
119
120
  if (!customerIdRef.current) return;
120
121
  try {
@@ -222,7 +223,10 @@ function usePaymentFlow({
222
223
  }
223
224
  }, [isOpen, shippingAccepted, paymentMethod, unified, postUnified]);
224
225
  useEffect2(() => {
225
- if (!isOpen && unified !== null && shippingAccepted && paymentMethod === "credit-card") {
226
+ const setupId = unified?.transactionSetupId;
227
+ if (!isOpen && setupId && shippingAccepted && paymentMethod === "credit-card") {
228
+ if (hasVerifiedRef.current === setupId) return;
229
+ hasVerifiedRef.current = setupId;
226
230
  void verifyUnified();
227
231
  }
228
232
  }, [isOpen, unified, shippingAccepted, paymentMethod, verifyUnified]);
@@ -246,6 +250,7 @@ function usePaymentFlow({
246
250
  setUnifiedBilling(false);
247
251
  setUnifiedResponse(false);
248
252
  setCapturedBin(null);
253
+ hasVerifiedRef.current = null;
249
254
  if (persistPayment) {
250
255
  clearFromSession(PAYMENT_STORAGE_KEY);
251
256
  }
@@ -265,6 +270,7 @@ function usePaymentFlow({
265
270
  clearFromSession(PAYMENT_STORAGE_KEY);
266
271
  return;
267
272
  }
273
+ hasVerifiedRef.current = transactionSetupId;
268
274
  setUnified({ transactionSetupId });
269
275
  setUnifiedPayment(account);
270
276
  setUnifiedResponse(true);
@@ -374,4 +380,4 @@ export {
374
380
  determineOrderReadiness,
375
381
  useOrderReadiness
376
382
  };
377
- //# sourceMappingURL=chunk-NRWH2BMN.js.map
383
+ //# sourceMappingURL=chunk-JNOHB4OP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/stores/cart-store.ts","../src/hooks/use-checkout-persistence.ts","../src/hooks/use-payment-flow.ts","../src/hooks/use-order-readiness.ts"],"sourcesContent":["import { create } from \"zustand\";\nimport { devtools } from \"zustand/middleware\";\nimport type { TCartLine } from \"@simpleapps-com/augur-utils\";\n\n/** Internal state shape for the cart Zustand store. */\ninterface CartState {\n /** P21 cart header UID; `undefined` when no cart exists. */\n cartHdrUid: number | string | undefined;\n /** Current line items in the cart. */\n cartLines: TCartLine[];\n /** Sum of `quantity` across all cart lines (auto-computed by `setCartLines`). */\n cartQuantityTotal: number;\n /** Number of distinct line items (auto-computed by `setCartLines`). */\n cartLineCount: number;\n setCartHdrUid: (cartHdrUid: number | string | undefined) => void;\n /** Replace all cart lines. Auto-recomputes `cartQuantityTotal` and `cartLineCount`. */\n setCartLines: (cartLines: TCartLine[]) => void;\n /** Reset the cart to its empty initial state. */\n clearCart: () => void;\n}\n\n/** Zustand store for cart state. Prefer the individual selector hooks below for optimal re-renders. */\nexport const useCartStore = create<CartState>()(\n devtools(\n (set) => ({\n cartHdrUid: undefined,\n cartLines: [],\n cartQuantityTotal: 0,\n cartLineCount: 0,\n\n setCartHdrUid: (cartHdrUid) => set({ cartHdrUid }, false, \"setCartHdrUid\"),\n\n setCartLines: (cartLines) => {\n const cartQuantityTotal = cartLines.reduce((sum, line) => sum + (line.quantity || 0), 0);\n const cartLineCount = cartLines.length;\n set({ cartLines, cartQuantityTotal, cartLineCount }, false, \"setCartLines\");\n },\n\n clearCart: () =>\n set(\n { cartHdrUid: undefined, cartLines: [], cartQuantityTotal: 0, cartLineCount: 0 },\n false,\n \"clearCart\",\n ),\n }),\n { name: \"CartStore\", enabled: process.env[\"NODE_ENV\"] === \"development\" },\n ),\n);\n\n// Selector hooks -- only re-render when specific state changes\n\n/** Select the current cart header UID. */\nexport const useCartHdrUid = () => useCartStore((s) => s.cartHdrUid);\n/** Select the current cart line items array. */\nexport const useCartLines = () => useCartStore((s) => s.cartLines);\n/** Select the total quantity summed across all cart lines. */\nexport const useCartQuantityTotal = () => useCartStore((s) => s.cartQuantityTotal);\n/** Select the number of distinct line items in the cart. */\nexport const useCartLineCount = () => useCartStore((s) => s.cartLineCount);\n/** Get the `setCartHdrUid` action (stable reference). */\nexport const useSetCartHdrUid = () => useCartStore((s) => s.setCartHdrUid);\n/** Get the `setCartLines` action (stable reference). Also recomputes totals. */\nexport const useSetCartLines = () => useCartStore((s) => s.setCartLines);\n/** Get the `clearCart` action (stable reference). */\nexport const useClearCart = () => useCartStore((s) => s.clearCart);\n","\"use client\";\n\nimport { useEffect, useRef } from \"react\";\n\n/** A single persisted field with its storage key and optional TTL. */\nexport interface CheckoutPersistField<T> {\n key: string;\n value: T;\n set: (value: T) => void;\n /** Valibot or custom validator. Return the parsed value or throw to reject. */\n validate?: (raw: unknown) => T;\n /** TTL in milliseconds. Default: 30 minutes. */\n ttl?: number;\n}\n\ninterface StorageEntry {\n value: unknown;\n savedAt: number;\n}\n\nconst DEFAULT_TTL = 30 * 60 * 1000; // 30 minutes\n\n/**\n * Saves a value to sessionStorage with a timestamp for TTL expiration.\n *\n * Fails silently on storage errors (private browsing, quota exceeded).\n */\nexport function saveToSession(key: string, value: unknown): void {\n try {\n const entry: StorageEntry = { value, savedAt: Date.now() };\n sessionStorage.setItem(key, JSON.stringify(entry));\n } catch {\n // sessionStorage unavailable (private browsing, quota)\n }\n}\n\n/**\n * Loads a value from sessionStorage, checking TTL and optionally validating.\n *\n * Returns null if missing, expired, invalid, or storage is unavailable.\n * Cleans up expired entries automatically.\n */\nexport function loadFromSession<T>(\n key: string,\n ttl: number = DEFAULT_TTL,\n validate?: (raw: unknown) => T,\n): T | null {\n try {\n const raw = sessionStorage.getItem(key);\n if (!raw) return null;\n\n const entry = JSON.parse(raw) as StorageEntry;\n if (Date.now() - entry.savedAt > ttl) {\n sessionStorage.removeItem(key);\n return null;\n }\n\n if (validate) {\n return validate(entry.value);\n }\n return entry.value as T;\n } catch {\n sessionStorage.removeItem(key);\n return null;\n }\n}\n\n/** Removes a checkout persistence key from sessionStorage. */\nexport function clearFromSession(key: string): void {\n try {\n sessionStorage.removeItem(key);\n } catch {\n // ignore\n }\n}\n\n/**\n * Hook that persists checkout state fields to sessionStorage and restores on mount.\n *\n * Each field is saved when its value changes and restored once on initial mount.\n * Validates restored values against an optional schema to guard against\n * corrupted or stale storage. Expired entries (past TTL) are discarded.\n */\nexport function useCheckoutPersistence(fields: CheckoutPersistField<unknown>[]): void {\n // Restore on mount (once). Capture fields in a ref so the effect has no deps.\n const fieldsRef = useRef(fields);\n fieldsRef.current = fields;\n\n useEffect(() => {\n for (const field of fieldsRef.current) {\n const restored = loadFromSession(field.key, field.ttl ?? DEFAULT_TTL, field.validate);\n if (restored !== null) {\n field.set(restored);\n }\n }\n }, []);\n\n // Save on change -- serialized values as dependency to avoid dynamic dep arrays\n const serialized = JSON.stringify(fields.map((f) => [f.key, f.value]));\n useEffect(() => {\n for (const field of fields) {\n if (field.value !== undefined && field.value !== null) {\n saveToSession(field.key, field.value);\n }\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [serialized]);\n}\n\n/**\n * Clears all checkout persistence keys from sessionStorage.\n *\n * Call after successful order submission to prevent stale data on next checkout.\n */\nexport function clearCheckoutPersistence(keys: string[]): void {\n for (const key of keys) {\n clearFromSession(key);\n }\n}\n","import { useCallback, useEffect, useRef, useState } from \"react\";\nimport type {\n TTransactionSetup,\n TCardInfo,\n TPaymentValidation,\n TAccountQuery,\n TBillingUpdate,\n} from \"@simpleapps-com/augur-utils\";\nimport { saveToSession, loadFromSession, clearFromSession } from \"./use-checkout-persistence\";\n\n/** Site-specific payment action callbacks injected into usePaymentFlow. */\nexport interface PaymentFlowCallbacks {\n /** Initialize a payment session. Returns transaction setup or undefined on failure. */\n transactionSetup: (params: { customerId: string }) => Promise<TTransactionSetup | undefined>;\n /** Retrieve card details after iframe entry. */\n cardInfo: (params: { transactionSetupId: string }) => Promise<TCardInfo | undefined>;\n /** Verify card is valid. */\n validatePayment: (params: {\n transactionSetupId: string;\n customerId: string;\n }) => Promise<TPaymentValidation | undefined>;\n /** Get payment account ID. */\n accountQuery: (params: {\n transactionSetupId: string;\n customerId: string;\n }) => Promise<TAccountQuery | undefined>;\n /** Send billing address to payment processor. */\n billingUpdate: (params: {\n transactionSetupId: string;\n address1: string;\n address2?: string;\n city: string;\n state: string;\n zip: string;\n }) => Promise<TBillingUpdate | undefined>;\n /** Optional toast notification callback. */\n toast?: {\n error?: (message: string) => void;\n };\n}\n\n/** Billing address shape accepted by the payment flow. */\nexport interface PaymentBillingAddress {\n address1: string;\n address2?: string;\n city: string;\n state: string;\n postalCode: string;\n}\n\ninterface UsePaymentFlowParams {\n callbacks: PaymentFlowCallbacks;\n customerId: string | number | undefined;\n billingAddress: PaymentBillingAddress | undefined;\n paymentMethod: string;\n shippingAccepted: boolean;\n /** Persist payment tokens to sessionStorage for cross-navigation recovery. */\n persistPayment?: boolean;\n}\n\n/** sessionStorage key for persisted payment tokens. */\nexport const PAYMENT_STORAGE_KEY = \"checkout:payment\";\n\n/** Shape of persisted payment data. Only token IDs, never card data (PCI-DSS). */\ninterface PersistedPayment {\n transactionSetupId: string;\n paymentAccountId: string;\n}\n\n/**\n * Manages the full Element/Unified payment lifecycle:\n * transactionSetup -> cardInfo -> validatePayment -> accountQuery -> billingUpdate\n *\n * Accepts site-specific server action callbacks so the hook has no dependency\n * on any particular server action implementation.\n *\n * @example\n * ```tsx\n * import { usePaymentFlow } from \"@simpleapps-com/augur-hooks\";\n * import { transactionSetup, cardInfo, validatePayment, accountQuery, billingUpdate } from \"@/lib/actions/payments\";\n *\n * const payment = usePaymentFlow({\n * callbacks: { transactionSetup, cardInfo, validatePayment, accountQuery, billingUpdate },\n * customerId,\n * billingAddress,\n * paymentMethod: \"credit-card\",\n * shippingAccepted: true,\n * });\n * ```\n */\nexport function usePaymentFlow({\n callbacks,\n customerId,\n billingAddress,\n paymentMethod,\n shippingAccepted,\n persistPayment,\n}: UsePaymentFlowParams) {\n const [isOpen, setIsOpen] = useState(false);\n const [unified, setUnified] = useState<TTransactionSetup | null>(null);\n const [unifiedCc, setUnifiedCc] = useState<TCardInfo | null>(null);\n const [unifiedResponse, setUnifiedResponse] = useState(false);\n const [unifiedBilling, setUnifiedBilling] = useState(false);\n const [unifiedPayment, setUnifiedPayment] = useState<TAccountQuery | null>(null);\n const [capturedBin, setCapturedBin] = useState<string | null>(null);\n const [editCc, setEditCc] = useState(false);\n\n const handleBinCapture = useCallback((bin: string) => {\n setCapturedBin(bin);\n }, []);\n\n // Ref ensures callbacks always read the latest customerId, avoiding stale\n // closures when React batches state updates (e.g., modal close + verify).\n const customerIdRef = useRef(customerId);\n customerIdRef.current = customerId;\n\n // @invariant verifyUnified runs at most once per transactionSetupId\n // (hasVerifiedRef.current ∈ {null} ∪ {setupId already verified}; a fresh\n // setupId ⇒ exactly one verify). Without this, the post-close verify effect\n // re-fires whenever the consumer's inline `callbacks` prop changes identity\n // (every parent render), spraying redundant validatePayment/cardInfo calls\n // at the payment gateway. Keyed by setupId, not a boolean, so a new setup\n // (edit-card) re-verifies while a restored setup is treated as done.\n const hasVerifiedRef = useRef<string | null>(null);\n\n // Step 1: Initialize payment session\n const postUnified = useCallback(async () => {\n if (!customerIdRef.current) return;\n try {\n const result = await callbacks.transactionSetup({\n customerId: String(customerIdRef.current),\n });\n if (!result) {\n callbacks.toast?.error?.(\"Unable to initialize payment. Please try again.\");\n return;\n }\n setUnified(result);\n } catch (error) {\n console.error(\"transactionSetup failed:\", error);\n callbacks.toast?.error?.(\"Unable to initialize payment. Please try again.\");\n }\n }, [callbacks]);\n\n // Step 2: Get card info after iframe entry\n const getCardInfo = useCallback(async () => {\n /* v8 ignore next -- defensive: caller (verifyUnified) already guards */\n if (!unified?.transactionSetupId) return;\n try {\n const result = await callbacks.cardInfo({ transactionSetupId: unified.transactionSetupId });\n if (!result) {\n callbacks.toast?.error?.(\"Unable to verify card details. Please try again.\");\n return;\n }\n setUnifiedCc(result);\n } catch (error) {\n console.error(\"cardInfo failed:\", error);\n callbacks.toast?.error?.(\"Unable to verify card details. Please try again.\");\n }\n }, [unified, callbacks]);\n\n // Step 3: Validate payment\n const verifyUnified = useCallback(async () => {\n if (!unified?.transactionSetupId || !customerIdRef.current) return;\n try {\n const result = await callbacks.validatePayment({\n transactionSetupId: unified.transactionSetupId,\n customerId: String(customerIdRef.current),\n });\n if (!result) {\n callbacks.toast?.error?.(\"Payment verification failed. Please try again.\");\n return;\n }\n setUnifiedResponse(result.valid);\n if (result.valid) {\n await getCardInfo();\n }\n } catch (error) {\n console.error(\"validatePayment failed:\", error);\n callbacks.toast?.error?.(\"Payment verification failed. Please try again.\");\n }\n }, [unified, getCardInfo, callbacks]);\n\n // Step 4: Get payment account info\n const getUnifiedPayment = useCallback(async () => {\n if (!unified?.transactionSetupId || !customerIdRef.current) return;\n try {\n const result = await callbacks.accountQuery({\n transactionSetupId: unified.transactionSetupId,\n customerId: String(customerIdRef.current),\n });\n if (!result) {\n callbacks.toast?.error?.(\"Unable to retrieve payment account. Please try again.\");\n return;\n }\n const payment = capturedBin && !result.Bin ? { ...result, Bin: capturedBin } : result;\n setUnifiedPayment(payment);\n if (persistPayment && result.PaymentAccountID) {\n saveToSession(PAYMENT_STORAGE_KEY, {\n transactionSetupId: unified.transactionSetupId,\n paymentAccountId: result.PaymentAccountID,\n } satisfies PersistedPayment);\n }\n } catch (error) {\n console.error(\"accountQuery failed:\", error);\n callbacks.toast?.error?.(\"Unable to retrieve payment account. Please try again.\");\n }\n }, [unified, capturedBin, callbacks, persistPayment]);\n\n // Step 5: Update billing info\n const updateUnifiedBilling = useCallback(async () => {\n /* v8 ignore next -- defensive: effect already guards billingAddress/unified */\n if (!unified?.transactionSetupId || !billingAddress) return;\n try {\n const result = await callbacks.billingUpdate({\n transactionSetupId: unified.transactionSetupId,\n address1: billingAddress.address1,\n address2: billingAddress.address2,\n city: billingAddress.city,\n state: billingAddress.state,\n zip: billingAddress.postalCode,\n });\n if (!result) {\n callbacks.toast?.error?.(\"Billing update failed. Please try again.\");\n return;\n }\n setUnifiedBilling(true);\n void getUnifiedPayment();\n } catch (error) {\n console.error(\"billingUpdate failed:\", error);\n callbacks.toast?.error?.(\"Billing update failed. Please try again.\");\n }\n }, [unified, billingAddress, getUnifiedPayment, callbacks]);\n\n // Close payment modal if preconditions are lost\n useEffect(() => {\n if (isOpen && (!shippingAccepted || paymentMethod !== \"credit-card\")) {\n setIsOpen(false);\n }\n }, [isOpen, shippingAccepted, paymentMethod]);\n\n // Initialize payment setup when modal opens with no transaction\n useEffect(() => {\n if (isOpen && shippingAccepted && paymentMethod === \"credit-card\" && unified === null) {\n void postUnified();\n }\n }, [isOpen, shippingAccepted, paymentMethod, unified, postUnified]);\n\n // Verify payment after modal closes. Guard by transactionSetupId so the\n // effect verifies once per setup instead of re-firing on every parent render\n // (the consumer's inline `callbacks` prop churns verifyUnified's identity).\n useEffect(() => {\n const setupId = unified?.transactionSetupId;\n if (!isOpen && setupId && shippingAccepted && paymentMethod === \"credit-card\") {\n if (hasVerifiedRef.current === setupId) return;\n hasVerifiedRef.current = setupId;\n void verifyUnified();\n }\n }, [isOpen, unified, shippingAccepted, paymentMethod, verifyUnified]);\n\n // Trigger billing update when card verified + billing address ready\n useEffect(() => {\n if (\n unifiedResponse &&\n billingAddress !== undefined &&\n unifiedCc?.transactionSetupId &&\n paymentMethod === \"credit-card\"\n ) {\n void updateUnifiedBilling();\n }\n }, [\n unifiedResponse,\n billingAddress,\n unifiedCc?.transactionSetupId,\n updateUnifiedBilling,\n paymentMethod,\n ]);\n\n // Reset all payment state when editing CC\n useEffect(() => {\n if (editCc) {\n setIsOpen(true);\n setUnified(null);\n setUnifiedCc(null);\n setUnifiedPayment(null);\n setUnifiedBilling(false);\n setUnifiedResponse(false);\n setCapturedBin(null);\n hasVerifiedRef.current = null;\n if (persistPayment) {\n clearFromSession(PAYMENT_STORAGE_KEY);\n }\n }\n }, [editCc, persistPayment]);\n\n // Restore persisted payment tokens on mount\n const restorePayment = useCallback(async () => {\n if (!customerIdRef.current) return;\n\n const saved = loadFromSession<PersistedPayment>(PAYMENT_STORAGE_KEY);\n if (!saved?.transactionSetupId || !saved?.paymentAccountId) return;\n\n const { transactionSetupId } = saved;\n try {\n const account = await callbacks.accountQuery({\n transactionSetupId,\n customerId: String(customerIdRef.current),\n });\n if (!account?.PaymentAccountID) {\n clearFromSession(PAYMENT_STORAGE_KEY);\n return;\n }\n // Restore already proved this setup valid (accountQuery succeeded);\n // mark it verified so the post-close effect does not re-validate it.\n hasVerifiedRef.current = transactionSetupId;\n setUnified({ transactionSetupId });\n setUnifiedPayment(account);\n setUnifiedResponse(true);\n setUnifiedBilling(true);\n const card = await callbacks.cardInfo({ transactionSetupId });\n if (card) setUnifiedCc(card);\n } catch {\n clearFromSession(PAYMENT_STORAGE_KEY);\n }\n }, [callbacks]);\n\n useEffect(() => {\n if (persistPayment) {\n void restorePayment();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [persistPayment]);\n\n return {\n isOpen,\n setIsOpen,\n editCc,\n setEditCc,\n unified,\n unifiedCc,\n unifiedResponse,\n unifiedBilling,\n unifiedPayment,\n capturedBin,\n handleBinCapture,\n };\n}\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n/** Parameters for order readiness validation. */\nexport interface OrderReadinessParams {\n cartHdrUid: string | number | undefined;\n shippingAddress: unknown;\n billingAddress: unknown;\n shippingMethodSaved: boolean;\n showBillingInfoSummary: boolean;\n processingOrder: boolean;\n paymentMethod: string;\n unifiedPaymentAccountId: string | undefined;\n unifiedBilling: boolean;\n isFreeShipping: boolean;\n carrierId: string;\n shippingFee: number | undefined;\n isEditShippingInfo: boolean;\n isEditShippingMethods: boolean;\n isEditBillingInfo: boolean;\n editCc: boolean;\n /**\n * Site-provided function to check if the order is ready.\n *\n * Return `true` or `false` to override the default gates. Return\n * `undefined` to defer to the default logic (useful when the override\n * only applies to specific order flows — e.g. sample-only or pickup).\n */\n customReadinessCheck?: (params: OrderReadinessParams) => boolean | undefined;\n}\n\n/**\n * Pure function that determines if an order is ready to submit.\n *\n * Checks all gates: cart exists, addresses present, shipping method saved,\n * billing shown, payment complete (for credit card), shipping fee present\n * (for non-free, non-pickup orders), and no sections being edited.\n */\nexport function determineOrderReadiness(params: OrderReadinessParams): boolean {\n if (params.customReadinessCheck) {\n const override = params.customReadinessCheck(params);\n if (override !== undefined) return override;\n }\n\n if (!params.cartHdrUid) return false;\n\n // Block if any section is being edited or addresses are missing\n const blockers = [\n params.isEditShippingInfo,\n params.isEditShippingMethods,\n params.isEditBillingInfo,\n params.editCc,\n params.shippingAddress === undefined,\n params.billingAddress === undefined,\n !params.shippingMethodSaved,\n !params.showBillingInfoSummary,\n params.processingOrder,\n ];\n if (blockers.some(Boolean)) return false;\n\n // Credit card requires completed payment flow\n if (\n params.paymentMethod === \"credit-card\" &&\n (!params.unifiedPaymentAccountId || !params.unifiedBilling)\n ) {\n return false;\n }\n\n // Non-free shipping requires a fee (unless carrier is pickup/freight)\n if (!params.isFreeShipping && params.shippingFee === undefined) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Debounced order readiness hook.\n *\n * Recomputes readiness 300ms after any dependency changes to avoid\n * excessive re-renders during rapid state transitions (e.g., typing\n * in address fields).\n */\nexport function useOrderReadiness(params: OrderReadinessParams) {\n const [enableProcessOrderBtn, setEnableProcessOrderBtn] = useState(false);\n const [processingValidation, setProcessingValidation] = useState(false);\n\n useEffect(() => {\n setProcessingValidation(true);\n\n const timeoutId = setTimeout(() => {\n const ready = determineOrderReadiness(params);\n setEnableProcessOrderBtn(ready);\n setProcessingValidation(false);\n }, 300);\n\n return () => clearTimeout(timeoutId);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n params.billingAddress,\n params.shippingAddress,\n params.isEditShippingInfo,\n params.isEditShippingMethods,\n params.isEditBillingInfo,\n params.editCc,\n params.isFreeShipping,\n params.unifiedPaymentAccountId,\n params.unifiedBilling,\n params.paymentMethod,\n params.processingOrder,\n params.carrierId,\n params.shippingFee,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AA,EACT;AAEA,SAAO;AACT;AASO,SAAS,kBAAkB,QAA8B;AAC9D,QAAM,CAAC,uBAAuB,wBAAwB,IAAIA,UAAS,KAAK;AACxE,QAAM,CAAC,sBAAsB,uBAAuB,IAAIA,UAAS,KAAK;AAEtE,EAAAD,WAAU,MAAM;AACd,4BAAwB,IAAI;AAE5B,UAAM,YAAY,WAAW,MAAM;AACjC,YAAM,QAAQ,wBAAwB,MAAM;AAC5C,+BAAyB,KAAK;AAC9B,8BAAwB,KAAK;AAAA,IAC/B,GAAG,GAAG;AAEN,WAAO,MAAM,aAAa,SAAS;AAAA,EAErC,GAAG;AAAA,IACD,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,EACT,CAAC;AAED,SAAO,EAAE,uBAAuB,qBAAqB;AACvD;","names":["useEffect","useRef","useRef","useEffect","useEffect","useState"]}
package/dist/index.cjs CHANGED
@@ -20,7 +20,7 @@ var _chunk6Z6JGK2Ccjs = require('./chunk-6Z6JGK2C.cjs');
20
20
 
21
21
 
22
22
 
23
- var _chunkI4A5L2I6cjs = require('./chunk-I4A5L2I6.cjs');
23
+ var _chunkF5DUFW57cjs = require('./chunk-F5DUFW57.cjs');
24
24
 
25
25
  // src/provider.tsx
26
26
  var _react = require('react');
@@ -231,11 +231,34 @@ function buildOptimisticAdd(cartLines, item, cartHdrUid, itemId) {
231
231
  }
232
232
  ];
233
233
  }
234
+ function reverseAdd(cartLines, invMastUid, quantity) {
235
+ return cartLines.map(
236
+ (line) => line.invMastUid === invMastUid ? { ...line, quantity: line.quantity - quantity } : line
237
+ ).filter((line) => line.invMastUid !== invMastUid || line.quantity > 0);
238
+ }
239
+ function reverseQuantity(cartLines, invMastUid, previousQuantity) {
240
+ if (previousQuantity === void 0) return cartLines;
241
+ return cartLines.map(
242
+ (line) => line.invMastUid === invMastUid ? { ...line, quantity: previousQuantity } : line
243
+ );
244
+ }
245
+ function restoreRemoved(cartLines, invMastUid, removedLine) {
246
+ if (!removedLine) return cartLines;
247
+ if (cartLines.some((line) => line.invMastUid === invMastUid)) return cartLines;
248
+ return [...cartLines, removedLine];
249
+ }
250
+ function mergeRestore(cartLines, snapshot) {
251
+ const merged = [...cartLines];
252
+ for (const line of snapshot) {
253
+ if (!merged.some((existing) => existing.invMastUid === line.invMastUid)) merged.push(line);
254
+ }
255
+ return merged;
256
+ }
234
257
  function useCartActions(callbacks) {
235
258
  const queryClient = _reactquery.useQueryClient.call(void 0, );
236
- const cartHdrUid = _chunkI4A5L2I6cjs.useCartHdrUid.call(void 0, );
237
- const cartLines = _chunkI4A5L2I6cjs.useCartLines.call(void 0, );
238
- const setCartLines = _chunkI4A5L2I6cjs.useSetCartLines.call(void 0, );
259
+ const cartHdrUid = _chunkF5DUFW57cjs.useCartHdrUid.call(void 0, );
260
+ const cartLines = _chunkF5DUFW57cjs.useCartLines.call(void 0, );
261
+ const setCartLines = _chunkF5DUFW57cjs.useSetCartLines.call(void 0, );
239
262
  const notify = callbacks.toast;
240
263
  const invalidateCartCache = _react.useCallback.call(void 0, () => {
241
264
  void queryClient.invalidateQueries({ queryKey: ["cartLines", cartHdrUid] });
@@ -246,9 +269,9 @@ function useCartActions(callbacks) {
246
269
  const addToCart = _react.useCallback.call(void 0,
247
270
  async (item, options = {}) => {
248
271
  const { showToast = true, itemId = "", onSuccess, onError } = options;
249
- const uid = requireCartUid(cartHdrUid);
250
- const previousCartLines = [...cartLines];
251
- setCartLines(buildOptimisticAdd(cartLines, item, uid, itemId));
272
+ const { cartHdrUid: liveUid, cartLines: liveLines } = _chunkF5DUFW57cjs.useCartStore.getState();
273
+ const uid = requireCartUid(liveUid);
274
+ setCartLines(buildOptimisticAdd(liveLines, item, uid, itemId));
252
275
  try {
253
276
  const success = await callbacks.addToCart(uid, [
254
277
  {
@@ -266,7 +289,7 @@ function useCartActions(callbacks) {
266
289
  _optionalChain([onSuccess, 'optionalCall', _9 => _9()]);
267
290
  return true;
268
291
  } catch (error) {
269
- setCartLines(previousCartLines);
292
+ setCartLines(reverseAdd(_chunkF5DUFW57cjs.useCartStore.getState().cartLines, item.invMastUid, item.quantity));
270
293
  if (showToast && _optionalChain([notify, 'optionalAccess', _10 => _10.error])) {
271
294
  notify.error("Failed to add item to cart. Please try again.");
272
295
  }
@@ -274,14 +297,15 @@ function useCartActions(callbacks) {
274
297
  return false;
275
298
  }
276
299
  },
277
- [cartHdrUid, cartLines, setCartLines, invalidateCartCache, callbacks, notify]
300
+ [setCartLines, invalidateCartCache, callbacks, notify]
278
301
  );
279
302
  const updateQuantity = _react.useCallback.call(void 0,
280
303
  async (invMastUid, newQuantity, options = {}) => {
281
304
  const { showToast = false, onSuccess, onError } = options;
282
- const uid = requireCartUid(cartHdrUid);
283
- const previousCartLines = [...cartLines];
284
- const updatedLines = cartLines.map(
305
+ const { cartHdrUid: liveUid, cartLines: liveLines } = _chunkF5DUFW57cjs.useCartStore.getState();
306
+ const uid = requireCartUid(liveUid);
307
+ const previousQuantity = _optionalChain([liveLines, 'access', _12 => _12.find, 'call', _13 => _13((line) => line.invMastUid === invMastUid), 'optionalAccess', _14 => _14.quantity]);
308
+ const updatedLines = liveLines.map(
285
309
  (line) => line.invMastUid === invMastUid ? { ...line, quantity: newQuantity } : line
286
310
  );
287
311
  setCartLines(updatedLines);
@@ -289,73 +313,76 @@ function useCartActions(callbacks) {
289
313
  const success = await callbacks.updateCartLines(uid, updatedLines);
290
314
  if (!success) throw new Error("Failed to update quantity");
291
315
  invalidateCartCache();
292
- _optionalChain([onSuccess, 'optionalCall', _12 => _12()]);
316
+ _optionalChain([onSuccess, 'optionalCall', _15 => _15()]);
293
317
  return true;
294
318
  } catch (error) {
295
- setCartLines(previousCartLines);
296
- if (showToast && _optionalChain([notify, 'optionalAccess', _13 => _13.error])) {
319
+ setCartLines(
320
+ reverseQuantity(_chunkF5DUFW57cjs.useCartStore.getState().cartLines, invMastUid, previousQuantity)
321
+ );
322
+ if (showToast && _optionalChain([notify, 'optionalAccess', _16 => _16.error])) {
297
323
  notify.error("Failed to update quantity. Please try again.");
298
324
  }
299
- _optionalChain([onError, 'optionalCall', _14 => _14(error)]);
325
+ _optionalChain([onError, 'optionalCall', _17 => _17(error)]);
300
326
  return false;
301
327
  }
302
328
  },
303
- [cartHdrUid, cartLines, setCartLines, invalidateCartCache, callbacks, notify]
329
+ [setCartLines, invalidateCartCache, callbacks, notify]
304
330
  );
305
331
  const removeFromCart = _react.useCallback.call(void 0,
306
332
  async (invMastUid, options = {}) => {
307
333
  const { showToast = true, itemId = "", onSuccess, onError } = options;
308
- const uid = requireCartUid(cartHdrUid);
309
- const previousCartLines = [...cartLines];
310
- setCartLines(cartLines.filter((line) => line.invMastUid !== invMastUid));
334
+ const { cartHdrUid: liveUid, cartLines: liveLines } = _chunkF5DUFW57cjs.useCartStore.getState();
335
+ const uid = requireCartUid(liveUid);
336
+ const removedLine = liveLines.find((line) => line.invMastUid === invMastUid);
337
+ setCartLines(liveLines.filter((line) => line.invMastUid !== invMastUid));
311
338
  try {
312
- const zeroedLines = cartLines.map(
339
+ const zeroedLines = liveLines.map(
313
340
  (line) => line.invMastUid === invMastUid ? { ...line, quantity: 0 } : line
314
341
  );
315
342
  const success = await callbacks.updateCartLines(uid, zeroedLines);
316
343
  if (!success) throw new Error("Failed to remove item");
317
344
  invalidateCartCache();
318
- if (showToast && _optionalChain([notify, 'optionalAccess', _15 => _15.info])) {
345
+ if (showToast && _optionalChain([notify, 'optionalAccess', _18 => _18.info])) {
319
346
  notify.info(`${itemId || "Item"} removed from cart`);
320
347
  }
321
- _optionalChain([onSuccess, 'optionalCall', _16 => _16()]);
348
+ _optionalChain([onSuccess, 'optionalCall', _19 => _19()]);
322
349
  return true;
323
350
  } catch (error) {
324
- setCartLines(previousCartLines);
325
- if (showToast && _optionalChain([notify, 'optionalAccess', _17 => _17.error])) {
351
+ setCartLines(restoreRemoved(_chunkF5DUFW57cjs.useCartStore.getState().cartLines, invMastUid, removedLine));
352
+ if (showToast && _optionalChain([notify, 'optionalAccess', _20 => _20.error])) {
326
353
  notify.error("Failed to remove item. Please try again.");
327
354
  }
328
- _optionalChain([onError, 'optionalCall', _18 => _18(error)]);
355
+ _optionalChain([onError, 'optionalCall', _21 => _21(error)]);
329
356
  return false;
330
357
  }
331
358
  },
332
- [cartHdrUid, cartLines, setCartLines, invalidateCartCache, callbacks, notify]
359
+ [setCartLines, invalidateCartCache, callbacks, notify]
333
360
  );
334
361
  const clearCart = _react.useCallback.call(void 0,
335
362
  async (options = {}) => {
336
363
  const { showToast = true, onSuccess, onError } = options;
337
- const uid = requireCartUid(cartHdrUid);
338
- const previousCartLines = [...cartLines];
364
+ const { cartHdrUid: liveUid, cartLines: snapshot } = _chunkF5DUFW57cjs.useCartStore.getState();
365
+ const uid = requireCartUid(liveUid);
339
366
  setCartLines([]);
340
367
  try {
341
368
  const success = await callbacks.deleteItemsFromCart(uid);
342
369
  if (!success) throw new Error("Failed to clear cart");
343
370
  invalidateCartCache();
344
- if (showToast && _optionalChain([notify, 'optionalAccess', _19 => _19.info])) {
371
+ if (showToast && _optionalChain([notify, 'optionalAccess', _22 => _22.info])) {
345
372
  notify.info("Cart cleared");
346
373
  }
347
- _optionalChain([onSuccess, 'optionalCall', _20 => _20()]);
374
+ _optionalChain([onSuccess, 'optionalCall', _23 => _23()]);
348
375
  return true;
349
376
  } catch (error) {
350
- setCartLines(previousCartLines);
351
- if (showToast && _optionalChain([notify, 'optionalAccess', _21 => _21.error])) {
377
+ setCartLines(mergeRestore(_chunkF5DUFW57cjs.useCartStore.getState().cartLines, snapshot));
378
+ if (showToast && _optionalChain([notify, 'optionalAccess', _24 => _24.error])) {
352
379
  notify.error("Failed to clear cart. Please try again.");
353
380
  }
354
- _optionalChain([onError, 'optionalCall', _22 => _22(error)]);
381
+ _optionalChain([onError, 'optionalCall', _25 => _25(error)]);
355
382
  return false;
356
383
  }
357
384
  },
358
- [cartHdrUid, cartLines, setCartLines, invalidateCartCache, callbacks, notify]
385
+ [setCartLines, invalidateCartCache, callbacks, notify]
359
386
  );
360
387
  const isInCart = _react.useCallback.call(void 0,
361
388
  (invMastUid) => {
@@ -365,7 +392,7 @@ function useCartActions(callbacks) {
365
392
  );
366
393
  const getItemQuantity = _react.useCallback.call(void 0,
367
394
  (invMastUid) => {
368
- return _nullishCoalesce(_optionalChain([cartLines, 'access', _23 => _23.find, 'call', _24 => _24((line) => line.invMastUid === invMastUid), 'optionalAccess', _25 => _25.quantity]), () => ( 0));
395
+ return _nullishCoalesce(_optionalChain([cartLines, 'access', _26 => _26.find, 'call', _27 => _27((line) => line.invMastUid === invMastUid), 'optionalAccess', _28 => _28.quantity]), () => ( 0));
369
396
  },
370
397
  [cartLines]
371
398
  );
@@ -418,14 +445,14 @@ function useCartInitialization(session, callbacks) {
418
445
  const saveCartToken = _nullishCoalesce(callbacks.saveCartToken, () => ( defaultSaveCartToken));
419
446
  const generateCartToken = _nullishCoalesce(callbacks.generateCartToken, () => ( defaultGenerateCartToken));
420
447
  const auth = useAugurAuth();
421
- const cartHdrUid = _chunkI4A5L2I6cjs.useCartHdrUid.call(void 0, );
422
- const setCartHdrUid = _chunkI4A5L2I6cjs.useSetCartHdrUid.call(void 0, );
423
- const setCartLines = _chunkI4A5L2I6cjs.useSetCartLines.call(void 0, );
424
- const clearCart = _chunkI4A5L2I6cjs.useClearCart.call(void 0, );
448
+ const cartHdrUid = _chunkF5DUFW57cjs.useCartHdrUid.call(void 0, );
449
+ const setCartHdrUid = _chunkF5DUFW57cjs.useSetCartHdrUid.call(void 0, );
450
+ const setCartLines = _chunkF5DUFW57cjs.useSetCartLines.call(void 0, );
451
+ const clearCart = _chunkF5DUFW57cjs.useClearCart.call(void 0, );
425
452
  const queryClient = _reactquery.useQueryClient.call(void 0, );
426
453
  const effectiveStatus = session.status;
427
- const effectiveUserId = _nullishCoalesce(session.userId, () => ( _optionalChain([auth, 'optionalAccess', _26 => _26.userId])));
428
- const effectiveCartHdrUid = _nullishCoalesce(session.cartHdrUid, () => ( _optionalChain([auth, 'optionalAccess', _27 => _27.cartHdrUid])));
454
+ const effectiveUserId = _nullishCoalesce(session.userId, () => ( _optionalChain([auth, 'optionalAccess', _29 => _29.userId])));
455
+ const effectiveCartHdrUid = _nullishCoalesce(session.cartHdrUid, () => ( _optionalChain([auth, 'optionalAccess', _30 => _30.cartHdrUid])));
429
456
  const effectiveSession = _react.useMemo.call(void 0,
430
457
  () => ({ status: effectiveStatus, userId: effectiveUserId, cartHdrUid: effectiveCartHdrUid }),
431
458
  [effectiveStatus, effectiveUserId, effectiveCartHdrUid]
@@ -454,6 +481,7 @@ function useCartInitialization(session, callbacks) {
454
481
  const initializeGuestCart = async () => {
455
482
  const existingToken = getCartToken();
456
483
  const cartToken = existingToken && typeof existingToken === "string" ? existingToken : generateCartToken();
484
+ let lastError;
457
485
  while (retryCountRef.current < MAX_RETRY_ATTEMPTS) {
458
486
  try {
459
487
  const cartHdr = await callbacks.cartHdrLookup("0", cartToken);
@@ -469,10 +497,7 @@ function useCartInitialization(session, callbacks) {
469
497
  await new Promise((resolve) => setTimeout(resolve, delay));
470
498
  }
471
499
  } catch (error) {
472
- console.error(
473
- `Cart initialization attempt ${retryCountRef.current + 1} failed:`,
474
- error
475
- );
500
+ lastError = error;
476
501
  retryCountRef.current++;
477
502
  if (retryCountRef.current < MAX_RETRY_ATTEMPTS) {
478
503
  const delay = Math.min(RETRY_DELAY_MS * Math.pow(1.5, retryCountRef.current), 1e4);
@@ -480,7 +505,7 @@ function useCartInitialization(session, callbacks) {
480
505
  }
481
506
  }
482
507
  }
483
- console.error(`Cart initialization failed after ${MAX_RETRY_ATTEMPTS} attempts`);
508
+ console.error(`Cart initialization failed after ${MAX_RETRY_ATTEMPTS} attempts`, lastError);
484
509
  isInitializingRef.current = false;
485
510
  };
486
511
  void initializeGuestCart();
@@ -519,14 +544,14 @@ function useCartPricing(options = {}) {
519
544
  const proxy = useAugurOptions();
520
545
  const auth = useAugurAuth();
521
546
  const site = useAugurSite();
522
- const cartLines = _chunkI4A5L2I6cjs.useCartLines.call(void 0, );
523
- const customerId = _nullishCoalesce(_nullishCoalesce(options.customerId, () => ( _optionalChain([auth, 'optionalAccess', _28 => _28.customerId]))), () => ( _optionalChain([site, 'optionalAccess', _29 => _29.defaults, 'optionalAccess', _30 => _30.customerId])));
547
+ const cartLines = _chunkF5DUFW57cjs.useCartLines.call(void 0, );
548
+ const customerId = _nullishCoalesce(_nullishCoalesce(options.customerId, () => ( _optionalChain([auth, 'optionalAccess', _31 => _31.customerId]))), () => ( _optionalChain([site, 'optionalAccess', _32 => _32.defaults, 'optionalAccess', _33 => _33.customerId])));
524
549
  const priceFn = options.queryFn;
525
550
  const priceQueries = _reactquery.useQueries.call(void 0, {
526
551
  queries: cartLines.map((line) => {
527
552
  if (priceFn) {
528
553
  return {
529
- queryKey: ["price", _optionalChain([line, 'access', _31 => _31.itemId, 'optionalAccess', _32 => _32.toUpperCase, 'call', _33 => _33()]) || "", customerId, line.quantity],
554
+ queryKey: ["price", _optionalChain([line, 'access', _34 => _34.itemId, 'optionalAccess', _35 => _35.toUpperCase, 'call', _36 => _36()]) || "", customerId, line.quantity],
530
555
  queryFn: () => priceFn(line.itemId, customerId, line.quantity),
531
556
  refetchOnReconnect: true,
532
557
  refetchOnWindowFocus: false,
@@ -535,7 +560,7 @@ function useCartPricing(options = {}) {
535
560
  };
536
561
  }
537
562
  const proxyOpts = proxy.pricing.priceEngine.list({
538
- itemId: _optionalChain([line, 'access', _34 => _34.itemId, 'optionalAccess', _35 => _35.toUpperCase, 'call', _36 => _36()]) || "",
563
+ itemId: _optionalChain([line, 'access', _37 => _37.itemId, 'optionalAccess', _38 => _38.toUpperCase, 'call', _39 => _39()]) || "",
539
564
  customerId: Number(customerId),
540
565
  quantity: line.quantity
541
566
  });
@@ -552,15 +577,16 @@ function useCartPricing(options = {}) {
552
577
  const map = {};
553
578
  cartLines.forEach((line, index) => {
554
579
  const queryResult = priceQueries[index];
555
- const rawData = _optionalChain([queryResult, 'optionalAccess', _37 => _37.data]);
580
+ const rawData = _optionalChain([queryResult, 'optionalAccess', _40 => _40.data]);
556
581
  if (rawData) {
557
582
  const priceData = _nullishCoalesce(rawData.data, () => ( rawData));
558
583
  const derived = _augurutils.derivePrice.call(void 0, {
559
584
  priceData,
560
585
  quantity: line.quantity
561
586
  });
587
+ const unitPrice = derived.state === "priced" ? derived.unitPrice : 0;
562
588
  map[line.itemId.toUpperCase()] = {
563
- unitPrice: derived.unitPrice,
589
+ unitPrice,
564
590
  priceData
565
591
  };
566
592
  }
@@ -569,7 +595,7 @@ function useCartPricing(options = {}) {
569
595
  }, [cartLines, priceQueries]);
570
596
  const getUnitPrice = _react.useMemo.call(void 0, () => {
571
597
  return (itemId) => {
572
- return _nullishCoalesce(_optionalChain([prices, 'access', _38 => _38[_optionalChain([itemId, 'optionalAccess', _39 => _39.toUpperCase, 'call', _40 => _40()])], 'optionalAccess', _41 => _41.unitPrice]), () => ( 0));
598
+ return _nullishCoalesce(_optionalChain([prices, 'access', _41 => _41[_optionalChain([itemId, 'optionalAccess', _42 => _42.toUpperCase, 'call', _43 => _43()])], 'optionalAccess', _44 => _44.unitPrice]), () => ( 0));
573
599
  };
574
600
  }, [prices]);
575
601
  const getItemTotal = _react.useMemo.call(void 0, () => {
@@ -579,7 +605,7 @@ function useCartPricing(options = {}) {
579
605
  }, [getUnitPrice]);
580
606
  const subtotal = _react.useMemo.call(void 0, () => {
581
607
  return cartLines.reduce((sum, line) => {
582
- const unitPrice = _nullishCoalesce(_optionalChain([prices, 'access', _42 => _42[line.itemId.toUpperCase()], 'optionalAccess', _43 => _43.unitPrice]), () => ( 0));
608
+ const unitPrice = _nullishCoalesce(_optionalChain([prices, 'access', _45 => _45[line.itemId.toUpperCase()], 'optionalAccess', _46 => _46.unitPrice]), () => ( 0));
583
609
  return sum + unitPrice * line.quantity;
584
610
  }, 0);
585
611
  }, [cartLines, prices]);
@@ -614,16 +640,12 @@ var usePaginationPrefetch = ({
614
640
  async (page) => {
615
641
  if (!enabled) return;
616
642
  const offset = (page - 1) * pageSize;
617
- try {
618
- await queryClient.prefetchQuery({
619
- queryKey: queryKeyFn ? queryKeyFn(queryKey, offset) : [...queryKey, offset],
620
- queryFn: () => queryFn(offset),
621
- staleTime,
622
- gcTime
623
- });
624
- } catch (error) {
625
- console.warn(`Error prefetching page ${page}:`, error);
626
- }
643
+ await queryClient.prefetchQuery({
644
+ queryKey: queryKeyFn ? queryKeyFn(queryKey, offset) : [...queryKey, offset],
645
+ queryFn: () => queryFn(offset),
646
+ staleTime,
647
+ gcTime
648
+ });
627
649
  },
628
650
  [queryKey, queryFn, pageSize, queryKeyFn, staleTime, gcTime, queryClient, enabled]
629
651
  );
@@ -656,7 +678,7 @@ function deserialize(data) {
656
678
 
657
679
  // src/persistence/apply-limits.ts
658
680
  function applyLimits(data, limits) {
659
- const queries = _optionalChain([data, 'access', _44 => _44.clientState, 'optionalAccess', _45 => _45.queries]);
681
+ const queries = _optionalChain([data, 'access', _47 => _47.clientState, 'optionalAccess', _48 => _48.queries]);
660
682
  if (!queries || Object.keys(limits).length === 0) return data;
661
683
  const entries = queries;
662
684
  const unlimited = [];
@@ -757,7 +779,7 @@ function useStorageMonitor(config) {
757
779
  const raw = storage.getItem(key);
758
780
  if (!raw) return;
759
781
  const parsed = JSON.parse(raw);
760
- if (!_optionalChain([parsed, 'access', _46 => _46.clientState, 'optionalAccess', _47 => _47.queries])) return;
782
+ if (!_optionalChain([parsed, 'access', _49 => _49.clientState, 'optionalAccess', _50 => _50.queries])) return;
761
783
  parsed.clientState.queries = parsed.clientState.queries.filter(
762
784
  (q) => {
763
785
  if (!Array.isArray(q.queryKey)) return true;
@@ -784,7 +806,7 @@ function useAugurPersistence(config) {
784
806
  setIsMounted(true);
785
807
  }, []);
786
808
  useStorageMonitor(config);
787
- const isDev = typeof process !== "undefined" && _optionalChain([process, 'access', _48 => _48.env, 'optionalAccess', _49 => _49["NODE_ENV"]]) === "development";
809
+ const isDev = typeof process !== "undefined" && _optionalChain([process, 'access', _51 => _51.env, 'optionalAccess', _52 => _52["NODE_ENV"]]) === "development";
788
810
  const { persistableKeys } = config;
789
811
  const dehydrateOptions = _react.useMemo.call(void 0,
790
812
  () => ({
@@ -841,5 +863,5 @@ function useAugurPersistence(config) {
841
863
 
842
864
 
843
865
 
844
- exports.AugurHooksProvider = AugurHooksProvider; exports.clearCheckoutPersistence = _chunkI4A5L2I6cjs.clearCheckoutPersistence; exports.clearFromSession = _chunkI4A5L2I6cjs.clearFromSession; exports.determineOrderReadiness = _chunkI4A5L2I6cjs.determineOrderReadiness; exports.executeBatchQuery = _chunk6Z6JGK2Ccjs.executeBatchQuery; exports.getRegisteredQueryAction = _chunk6Z6JGK2Ccjs.getRegisteredQueryAction; exports.loadFromSession = _chunkI4A5L2I6cjs.loadFromSession; exports.registerQueryAction = _chunk6Z6JGK2Ccjs.registerQueryAction; exports.saveToSession = _chunkI4A5L2I6cjs.saveToSession; exports.useAugurApi = useAugurApi; exports.useAugurApiOptional = useAugurApiOptional; exports.useAugurAuth = useAugurAuth; exports.useAugurCache = useAugurCache; exports.useAugurOptions = useAugurOptions; exports.useAugurPersistence = useAugurPersistence; exports.useAugurSite = useAugurSite; exports.useCartActions = useCartActions; exports.useCartHdrUid = _chunkI4A5L2I6cjs.useCartHdrUid; exports.useCartInitialization = useCartInitialization; exports.useCartLineCount = _chunkI4A5L2I6cjs.useCartLineCount; exports.useCartLines = _chunkI4A5L2I6cjs.useCartLines; exports.useCartPricing = useCartPricing; exports.useCartQuantityTotal = _chunkI4A5L2I6cjs.useCartQuantityTotal; exports.useCartStore = _chunkI4A5L2I6cjs.useCartStore; exports.useCheckoutPersistence = _chunkI4A5L2I6cjs.useCheckoutPersistence; exports.useClearCart = _chunkI4A5L2I6cjs.useClearCart; exports.useDebounce = useDebounce; exports.useFormatPrice = useFormatPrice; exports.useItemFiltersStore = useItemFiltersStore; exports.useModalLifecycle = useModalLifecycle; exports.useOrderReadiness = _chunkI4A5L2I6cjs.useOrderReadiness; exports.usePaginationPrefetch = usePaginationPrefetch; exports.usePaymentFlow = _chunkI4A5L2I6cjs.usePaymentFlow; exports.useSetCartHdrUid = _chunkI4A5L2I6cjs.useSetCartHdrUid; exports.useSetCartLines = _chunkI4A5L2I6cjs.useSetCartLines; exports.useStock = useStock;
866
+ exports.AugurHooksProvider = AugurHooksProvider; exports.clearCheckoutPersistence = _chunkF5DUFW57cjs.clearCheckoutPersistence; exports.clearFromSession = _chunkF5DUFW57cjs.clearFromSession; exports.determineOrderReadiness = _chunkF5DUFW57cjs.determineOrderReadiness; exports.executeBatchQuery = _chunk6Z6JGK2Ccjs.executeBatchQuery; exports.getRegisteredQueryAction = _chunk6Z6JGK2Ccjs.getRegisteredQueryAction; exports.loadFromSession = _chunkF5DUFW57cjs.loadFromSession; exports.registerQueryAction = _chunk6Z6JGK2Ccjs.registerQueryAction; exports.saveToSession = _chunkF5DUFW57cjs.saveToSession; exports.useAugurApi = useAugurApi; exports.useAugurApiOptional = useAugurApiOptional; exports.useAugurAuth = useAugurAuth; exports.useAugurCache = useAugurCache; exports.useAugurOptions = useAugurOptions; exports.useAugurPersistence = useAugurPersistence; exports.useAugurSite = useAugurSite; exports.useCartActions = useCartActions; exports.useCartHdrUid = _chunkF5DUFW57cjs.useCartHdrUid; exports.useCartInitialization = useCartInitialization; exports.useCartLineCount = _chunkF5DUFW57cjs.useCartLineCount; exports.useCartLines = _chunkF5DUFW57cjs.useCartLines; exports.useCartPricing = useCartPricing; exports.useCartQuantityTotal = _chunkF5DUFW57cjs.useCartQuantityTotal; exports.useCartStore = _chunkF5DUFW57cjs.useCartStore; exports.useCheckoutPersistence = _chunkF5DUFW57cjs.useCheckoutPersistence; exports.useClearCart = _chunkF5DUFW57cjs.useClearCart; exports.useDebounce = useDebounce; exports.useFormatPrice = useFormatPrice; exports.useItemFiltersStore = useItemFiltersStore; exports.useModalLifecycle = useModalLifecycle; exports.useOrderReadiness = _chunkF5DUFW57cjs.useOrderReadiness; exports.usePaginationPrefetch = usePaginationPrefetch; exports.usePaymentFlow = _chunkF5DUFW57cjs.usePaymentFlow; exports.useSetCartHdrUid = _chunkF5DUFW57cjs.useSetCartHdrUid; exports.useSetCartLines = _chunkF5DUFW57cjs.useSetCartLines; exports.useStock = useStock;
845
867
  //# sourceMappingURL=index.cjs.map