@simpleapps-com/augur-hooks 2026.11.4 → 2026.11.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -4,18 +4,24 @@ import {
4
4
  registerQueryAction
5
5
  } from "./chunk-7SUD5Z2V.js";
6
6
  import {
7
+ acceptsLookup,
8
+ cartIdle,
7
9
  clearCheckoutPersistence,
8
10
  clearFromSession,
9
11
  determineOrderReadiness,
10
12
  hasNumberFrom,
11
13
  indexOfUidFrom,
14
+ indexOfUnitFrom,
15
+ initStepOf,
12
16
  keepsAfterReverse,
13
17
  keyPathFrom,
14
18
  leadingTextsFrom,
15
19
  loadFromSession,
16
20
  qtyOrZero,
17
21
  requiredCartUid,
22
+ rollsBack,
18
23
  saveToSession,
24
+ sendsPrice,
19
25
  shouldPersistOf,
20
26
  stockEnabled,
21
27
  stockRetryDelay,
@@ -31,7 +37,7 @@ import {
31
37
  usePaymentFlow,
32
38
  useSetCartHdrUid,
33
39
  useSetCartLines
34
- } from "./chunk-63ZJ4UTX.js";
40
+ } from "./chunk-LLTE6COX.js";
35
41
 
36
42
  // src/provider.tsx
37
43
  import { createContext, useContext, useMemo } from "react";
@@ -208,9 +214,12 @@ function useStock(invMastUid, options = {}) {
208
214
  // src/hooks/use-cart-actions.ts
209
215
  import { useCallback } from "react";
210
216
  import { useQueryClient } from "@tanstack/react-query";
211
- function requireCartUid(cartHdrUid) {
217
+ function cartUidOf(cartHdrUid) {
212
218
  const num = typeof cartHdrUid === "string" ? Number(cartHdrUid) : cartHdrUid;
213
- const uid = requiredCartUid(num === void 0 || Number.isNaN(num) ? void 0 : num);
219
+ return num === void 0 || Number.isNaN(num) ? void 0 : num;
220
+ }
221
+ function requireCartUid(cartHdrUid) {
222
+ const uid = requiredCartUid(cartUidOf(cartHdrUid));
214
223
  if (uid === null) throw new Error("Cart UID is not set");
215
224
  return uid;
216
225
  }
@@ -243,20 +252,45 @@ function buildOptimisticAdd(cartLines, item, cartHdrUid, itemId) {
243
252
  ];
244
253
  }
245
254
  function reverseAdd(cartLines, invMastUid, quantity) {
246
- return cartLines.flatMap((line) => {
247
- if (line.invMastUid !== invMastUid) return [line];
248
- return keepsAfterReverse(line.quantity, quantity) ? [{ ...line, quantity: qtyOrZero(line.quantity) - quantity }] : [];
249
- });
255
+ const index = indexOfUidFrom(uidsOf(cartLines), invMastUid, 0);
256
+ if (index < 0) return cartLines;
257
+ const line = cartLines[index];
258
+ if (!keepsAfterReverse(line.quantity, quantity)) {
259
+ return [...cartLines.slice(0, index), ...cartLines.slice(index + 1)];
260
+ }
261
+ return cartLines.map(
262
+ (l, i) => i === index ? { ...l, quantity: qtyOrZero(l.quantity) - quantity } : l
263
+ );
250
264
  }
251
- function reverseQuantity(cartLines, invMastUid, previousQuantity) {
252
- if (previousQuantity === void 0) return cartLines;
265
+ function targetOf(cartLines, invMastUid, unitOfMeasure) {
266
+ const first = indexOfUidFrom(uidsOf(cartLines), invMastUid, 0);
267
+ if (first < 0) return null;
268
+ const unit = unitOfMeasure ?? unitOf(cartLines[first]);
269
+ if (indexOfUnitFrom(uidsOf(cartLines), unitsOf(cartLines), invMastUid, unit, 0) < 0) return null;
270
+ return { invMastUid, unit };
271
+ }
272
+ function isTarget(line, target) {
273
+ return indexOfUnitFrom([line.invMastUid], [unitOf(line)], target.invMastUid, target.unit, 0) === 0;
274
+ }
275
+ function targetLine(cartLines, target) {
276
+ const index = indexOfUnitFrom(
277
+ uidsOf(cartLines),
278
+ unitsOf(cartLines),
279
+ target.invMastUid,
280
+ target.unit,
281
+ 0
282
+ );
283
+ return cartLines[index];
284
+ }
285
+ function reverseQuantity(cartLines, target, previousQuantity) {
253
286
  return cartLines.map(
254
- (line) => line.invMastUid === invMastUid ? { ...line, quantity: previousQuantity } : line
287
+ (line) => isTarget(line, target) ? { ...line, quantity: previousQuantity } : line
255
288
  );
256
289
  }
257
- function restoreRemoved(cartLines, invMastUid, removedLine) {
258
- if (!removedLine) return cartLines;
259
- if (hasNumberFrom(uidsOf(cartLines), invMastUid, 0)) return cartLines;
290
+ function restoreRemoved(cartLines, target, removedLine) {
291
+ if (indexOfUnitFrom(uidsOf(cartLines), unitsOf(cartLines), target.invMastUid, target.unit, 0) >= 0) {
292
+ return cartLines;
293
+ }
260
294
  return [...cartLines, removedLine];
261
295
  }
262
296
  function mergeRestore(cartLines, snapshot) {
@@ -266,26 +300,42 @@ function mergeRestore(cartLines, snapshot) {
266
300
  }
267
301
  return merged;
268
302
  }
303
+ function sentLine(line, quantity) {
304
+ const { unitPrice, ...rest } = line;
305
+ const sent = { ...rest, quantity, lineNo: 0 };
306
+ if (sendsPrice(unitPrice)) sent.unitPrice = unitPrice;
307
+ return sent;
308
+ }
269
309
  function uidsOf(cartLines) {
270
310
  return cartLines.map((line) => line.invMastUid);
271
311
  }
312
+ function unitOf(line) {
313
+ return line.unitOfMeasure ?? "";
314
+ }
315
+ function unitsOf(cartLines) {
316
+ return cartLines.map(unitOf);
317
+ }
272
318
  function sendToast(notify, kind, showToast, message) {
273
319
  if (showToast && message !== void 0) notify?.[kind]?.(message);
274
320
  }
275
321
  async function settleCartOp(op, options, notify, invalidate) {
322
+ const { endCartOp } = useCartStore.getState();
276
323
  try {
277
324
  const success = await op.call();
278
325
  if (!success) throw new Error(op.failure);
279
- invalidate();
280
- sendToast(notify, "info", op.showToast, op.infoMessage);
281
- options.onSuccess?.();
282
- return true;
283
326
  } catch (error) {
284
- op.rollback();
327
+ if (rollsBack(cartUidOf(useCartStore.getState().cartHdrUid), op.cartUid)) op.rollback();
328
+ endCartOp();
329
+ invalidate();
285
330
  sendToast(notify, "error", op.showToast, op.errorMessage);
286
331
  options.onError?.(error);
287
332
  return false;
288
333
  }
334
+ endCartOp();
335
+ invalidate();
336
+ sendToast(notify, "info", op.showToast, op.infoMessage);
337
+ options.onSuccess?.();
338
+ return true;
289
339
  }
290
340
  function useCartActions(callbacks) {
291
341
  const queryClient = useQueryClient();
@@ -294,7 +344,7 @@ function useCartActions(callbacks) {
294
344
  const setCartLines = useSetCartLines();
295
345
  const notify = callbacks.toast;
296
346
  const invalidateCartCache = useCallback(() => {
297
- void queryClient.invalidateQueries({ queryKey: ["cartLines", cartHdrUid] });
347
+ void queryClient.invalidateQueries({ queryKey: ["cartLines"] });
298
348
  void queryClient.invalidateQueries({
299
349
  queryKey: ["cart-also-bought", cartHdrUid]
300
350
  });
@@ -303,9 +353,11 @@ function useCartActions(callbacks) {
303
353
  async (item, options = {}) => {
304
354
  const { showToast = true, itemId = "" } = options;
305
355
  const { uid, lines: liveLines } = liveCart();
356
+ useCartStore.getState().beginCartOp();
306
357
  setCartLines(buildOptimisticAdd(liveLines, item, uid, itemId));
307
358
  return settleCartOp(
308
359
  {
360
+ cartUid: uid,
309
361
  call: () => callbacks.addToCart(uid, [
310
362
  {
311
363
  cartHdrUid: uid,
@@ -331,21 +383,25 @@ function useCartActions(callbacks) {
331
383
  );
332
384
  const updateQuantity = useCallback(
333
385
  async (invMastUid, newQuantity, options = {}) => {
334
- const { showToast = false } = options;
386
+ const { showToast = false, unitOfMeasure } = options;
335
387
  const { uid, lines: liveLines } = liveCart();
336
- const previousQuantity = liveLines.find((line) => line.invMastUid === invMastUid)?.quantity;
337
- const updatedLines = liveLines.map(
338
- (line) => line.invMastUid === invMastUid ? { ...line, quantity: newQuantity } : line
388
+ const target = targetOf(liveLines, invMastUid, unitOfMeasure);
389
+ if (target === null) return true;
390
+ const line = targetLine(liveLines, target);
391
+ const previousQuantity = line.quantity;
392
+ useCartStore.getState().beginCartOp();
393
+ setCartLines(
394
+ liveLines.map((l) => isTarget(l, target) ? { ...l, quantity: newQuantity } : l)
339
395
  );
340
- setCartLines(updatedLines);
341
396
  return settleCartOp(
342
397
  {
343
- call: () => callbacks.updateCartLines(uid, updatedLines),
398
+ cartUid: uid,
399
+ call: () => callbacks.updateCartLines(uid, [sentLine(line, newQuantity)]),
344
400
  failure: "Failed to update quantity",
345
401
  errorMessage: "Failed to update quantity. Please try again.",
346
402
  showToast,
347
403
  rollback: () => setCartLines(
348
- reverseQuantity(useCartStore.getState().cartLines, invMastUid, previousQuantity)
404
+ reverseQuantity(useCartStore.getState().cartLines, target, previousQuantity)
349
405
  )
350
406
  },
351
407
  options,
@@ -357,23 +413,22 @@ function useCartActions(callbacks) {
357
413
  );
358
414
  const removeFromCart = useCallback(
359
415
  async (invMastUid, options = {}) => {
360
- const { showToast = true, itemId = "" } = options;
416
+ const { showToast = true, itemId = "", unitOfMeasure } = options;
361
417
  const { uid, lines: liveLines } = liveCart();
362
- const removedLine = liveLines.find((line) => line.invMastUid === invMastUid);
363
- setCartLines(liveLines.filter((line) => line.invMastUid !== invMastUid));
364
- const zeroedLines = liveLines.map(
365
- (line) => line.invMastUid === invMastUid ? { ...line, quantity: 0 } : line
366
- );
418
+ const target = targetOf(liveLines, invMastUid, unitOfMeasure);
419
+ if (target === null) return true;
420
+ const removedLine = targetLine(liveLines, target);
421
+ useCartStore.getState().beginCartOp();
422
+ setCartLines(liveLines.filter((l) => !isTarget(l, target)));
367
423
  return settleCartOp(
368
424
  {
369
- call: () => callbacks.updateCartLines(uid, zeroedLines),
425
+ cartUid: uid,
426
+ call: () => callbacks.updateCartLines(uid, [sentLine(removedLine, 0)]),
370
427
  failure: "Failed to remove item",
371
428
  infoMessage: `${itemId || "Item"} removed from cart`,
372
429
  errorMessage: "Failed to remove item. Please try again.",
373
430
  showToast,
374
- rollback: () => setCartLines(
375
- restoreRemoved(useCartStore.getState().cartLines, invMastUid, removedLine)
376
- )
431
+ rollback: () => setCartLines(restoreRemoved(useCartStore.getState().cartLines, target, removedLine))
377
432
  },
378
433
  options,
379
434
  notify,
@@ -386,9 +441,11 @@ function useCartActions(callbacks) {
386
441
  async (options = {}) => {
387
442
  const { showToast = true } = options;
388
443
  const { uid, lines: snapshot } = liveCart();
444
+ useCartStore.getState().beginCartOp();
389
445
  setCartLines([]);
390
446
  return settleCartOp(
391
447
  {
448
+ cartUid: uid,
392
449
  call: () => callbacks.deleteItemsFromCart(uid),
393
450
  failure: "Failed to clear cart",
394
451
  infoMessage: "Cart cleared",
@@ -452,10 +509,11 @@ function useModalLifecycle(isOpen, onClose) {
452
509
  }
453
510
 
454
511
  // src/hooks/use-cart-initialization.ts
455
- import { useEffect as useEffect3, useMemo as useMemo3, useRef } from "react";
512
+ import { useEffect as useEffect3, useMemo as useMemo3, useRef, useState as useState3 } from "react";
456
513
  import { useQuery as useQuery2, useQueryClient as useQueryClient2 } from "@tanstack/react-query";
457
514
  var MAX_RETRY_ATTEMPTS = 7;
458
515
  var RETRY_DELAY_MS = 1e3;
516
+ var LOOKUP_RESTART_MS = 3e4;
459
517
  async function waitBeforeRetry(attempt) {
460
518
  if (attempt >= MAX_RETRY_ATTEMPTS) return;
461
519
  const delay = Math.min(RETRY_DELAY_MS * Math.pow(1.5, attempt), 1e4);
@@ -464,6 +522,9 @@ async function waitBeforeRetry(attempt) {
464
522
  var defaultGetCartToken = () => localStorage.getItem("cartToken");
465
523
  var defaultSaveCartToken = (token) => localStorage.setItem("cartToken", token);
466
524
  var defaultGenerateCartToken = () => crypto.randomUUID();
525
+ function cartKey(uid) {
526
+ return uid === void 0 ? void 0 : String(uid);
527
+ }
467
528
  function useCartInitialization(session, callbacks) {
468
529
  const getCartToken = callbacks.getCartToken ?? defaultGetCartToken;
469
530
  const saveCartToken = callbacks.saveCartToken ?? defaultSaveCartToken;
@@ -484,6 +545,11 @@ function useCartInitialization(session, callbacks) {
484
545
  const retryCountRef = useRef(0);
485
546
  const isInitializingRef = useRef(false);
486
547
  const prevStatusRef = useRef(effectiveSession.status);
548
+ const statusRef = useRef(effectiveSession.status);
549
+ statusRef.current = effectiveSession.status;
550
+ const [lookupRound, setLookupRound] = useState3(0);
551
+ const restartTimerRef = useRef(void 0);
552
+ useEffect3(() => () => clearTimeout(restartTimerRef.current), []);
487
553
  useEffect3(() => {
488
554
  const prevStatus = prevStatusRef.current;
489
555
  prevStatusRef.current = effectiveSession.status;
@@ -494,40 +560,57 @@ function useCartInitialization(session, callbacks) {
494
560
  }
495
561
  }, [effectiveSession.status, clearCart, queryClient]);
496
562
  useEffect3(() => {
497
- if (cartHdrUid || effectiveSession.status === "loading") return;
498
- if (effectiveSession.cartHdrUid && effectiveSession.status === "authenticated") {
563
+ const step = initStepOf(
564
+ effectiveSession.status === "loading",
565
+ effectiveSession.status === "authenticated",
566
+ !!effectiveSession.cartHdrUid,
567
+ cartKey(cartHdrUid) === cartKey(effectiveSession.cartHdrUid),
568
+ !!cartHdrUid,
569
+ effectiveSession.userId !== void 0,
570
+ isInitializingRef.current
571
+ );
572
+ if (step.kind === "stay") return;
573
+ if (step.kind === "session") {
499
574
  setCartHdrUid(effectiveSession.cartHdrUid);
500
575
  return;
501
576
  }
502
- if (effectiveSession.status === "unauthenticated" && !isInitializingRef.current) {
503
- isInitializingRef.current = true;
504
- retryCountRef.current = 0;
505
- const initializeGuestCart = async () => {
506
- const existingToken = getCartToken();
507
- const cartToken = existingToken && typeof existingToken === "string" ? existingToken : generateCartToken();
508
- let lastError;
509
- while (retryCountRef.current < MAX_RETRY_ATTEMPTS) {
510
- try {
511
- const cartHdr = await callbacks.cartHdrLookup("0", cartToken);
512
- if (cartHdr && cartHdr.cartHdrUid !== 0) {
577
+ const forUser = step.kind === "user";
578
+ const lookupUserId = forUser ? effectiveSession.userId : "0";
579
+ isInitializingRef.current = true;
580
+ retryCountRef.current = 0;
581
+ const lookUpCart = async () => {
582
+ const existingToken = getCartToken();
583
+ const cartToken = existingToken && typeof existingToken === "string" ? existingToken : generateCartToken();
584
+ let lastError;
585
+ while (retryCountRef.current < MAX_RETRY_ATTEMPTS) {
586
+ try {
587
+ const cartHdr = await callbacks.cartHdrLookup(lookupUserId, cartToken);
588
+ if (cartHdr && cartHdr.cartHdrUid !== 0) {
589
+ const stillApplies = acceptsLookup(
590
+ forUser,
591
+ statusRef.current === "authenticated",
592
+ !!useCartStore.getState().cartHdrUid
593
+ );
594
+ if (stillApplies) {
513
595
  saveCartToken(cartToken);
514
596
  setCartHdrUid(cartHdr.cartHdrUid);
515
- isInitializingRef.current = false;
516
- return;
517
597
  }
518
- retryCountRef.current++;
519
- await waitBeforeRetry(retryCountRef.current);
520
- } catch (error) {
521
- lastError = error;
522
- retryCountRef.current++;
523
- await waitBeforeRetry(retryCountRef.current);
598
+ isInitializingRef.current = false;
599
+ return;
524
600
  }
601
+ retryCountRef.current++;
602
+ await waitBeforeRetry(retryCountRef.current);
603
+ } catch (error) {
604
+ lastError = error;
605
+ retryCountRef.current++;
606
+ await waitBeforeRetry(retryCountRef.current);
525
607
  }
526
- console.error(`Cart initialization failed after ${MAX_RETRY_ATTEMPTS} attempts`, lastError);
527
- isInitializingRef.current = false;
528
- };
529
- void initializeGuestCart();
530
- }
608
+ }
609
+ console.error(`Cart initialization failed after ${MAX_RETRY_ATTEMPTS} attempts`, lastError);
610
+ isInitializingRef.current = false;
611
+ restartTimerRef.current = setTimeout(() => setLookupRound((n) => n + 1), LOOKUP_RESTART_MS);
612
+ };
613
+ void lookUpCart();
531
614
  }, [
532
615
  effectiveSession,
533
616
  cartHdrUid,
@@ -535,15 +618,17 @@ function useCartInitialization(session, callbacks) {
535
618
  callbacks,
536
619
  getCartToken,
537
620
  saveCartToken,
538
- generateCartToken
621
+ generateCartToken,
622
+ lookupRound
539
623
  ]);
540
624
  const { data: cartLinesData } = useQuery2({
541
625
  queryKey: ["cartLines", cartHdrUid],
542
626
  queryFn: async () => await callbacks.getCartLines(Number(cartHdrUid)) ?? [],
543
- enabled: !!cartHdrUid
627
+ enabled: !!cartHdrUid,
628
+ structuralSharing: false
544
629
  });
545
630
  useEffect3(() => {
546
- if (cartLinesData) {
631
+ if (cartLinesData && cartIdle(useCartStore.getState().pendingCartOps)) {
547
632
  setCartLines(cartLinesData);
548
633
  }
549
634
  }, [cartLinesData, setCartLines]);
@@ -692,7 +777,7 @@ var usePaginationPrefetch = ({
692
777
 
693
778
  // src/persistence/use-persistence.ts
694
779
  import { hours, toMillis as toMillis4 } from "@simpleapps-com/augur-utils";
695
- import { useState as useState3, useEffect as useEffect5, useMemo as useMemo5 } from "react";
780
+ import { useState as useState4, useEffect as useEffect5, useMemo as useMemo5 } from "react";
696
781
 
697
782
  // src/persistence/create-persister.ts
698
783
  import { seconds, toMillis as toMillis2 } from "@simpleapps-com/augur-utils";
@@ -834,8 +919,8 @@ function useStorageMonitor(config) {
834
919
  // src/persistence/use-persistence.ts
835
920
  var PERSISTED_DATA_FORMAT = "augur-2";
836
921
  function useAugurPersistence(config) {
837
- const [persister] = useState3(() => createPersister(config));
838
- const [isMounted, setIsMounted] = useState3(false);
922
+ const [persister] = useState4(() => createPersister(config));
923
+ const [isMounted, setIsMounted] = useState4(false);
839
924
  useEffect5(() => {
840
925
  setIsMounted(true);
841
926
  }, []);