@merchi/cart 1.4.61 → 1.4.63

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.
@@ -434,41 +434,42 @@ var CartProvider = function CartProvider(_ref) {
434
434
  cartSettingsInvalid = _useState16[0],
435
435
  setCartSettingsInvalid = _useState16[1];
436
436
  var appliedHandoffCart = (0, _react.useRef)(null);
437
+ var cartInitializations = (0, _react.useRef)(new Map());
437
438
  function attachSavedClientIfNeeded(_x) {
438
439
  return _attachSavedClientIfNeeded.apply(this, arguments);
439
440
  } // Create cart and save cart cookie
440
441
  function _attachSavedClientIfNeeded() {
441
- _attachSavedClientIfNeeded = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(cartJson) {
442
+ _attachSavedClientIfNeeded = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(cartJson) {
442
443
  var _cartJson$client;
443
444
  var savedCustomer, _nextCart$client, cartToken, clientEnt, cartEnt, savedCart, nextCart, _t, _t2;
444
- return _regenerator().w(function (_context) {
445
- while (1) switch (_context.p = _context.n) {
445
+ return _regenerator().w(function (_context2) {
446
+ while (1) switch (_context2.p = _context2.n) {
446
447
  case 0:
447
448
  if (!(cartJson !== null && cartJson !== void 0 && (_cartJson$client = cartJson.client) !== null && _cartJson$client !== void 0 && _cartJson$client.id)) {
448
- _context.n = 1;
449
+ _context2.n = 1;
449
450
  break;
450
451
  }
451
452
  setCartClient(cartJson.client);
452
- return _context.a(2, cartJson);
453
+ return _context2.a(2, cartJson);
453
454
  case 1:
454
455
  savedCustomer = (0, _local_storage.getSavedCheckoutCustomer)(domainId);
455
456
  if (savedCustomer !== null && savedCustomer !== void 0 && savedCustomer.id) {
456
- _context.n = 2;
457
+ _context2.n = 2;
457
458
  break;
458
459
  }
459
460
  setCartClient(null);
460
- return _context.a(2, cartJson);
461
+ return _context2.a(2, cartJson);
461
462
  case 2:
462
- _context.p = 2;
463
+ _context2.p = 2;
463
464
  _t = cartJson.token;
464
465
  if (_t) {
465
- _context.n = 4;
466
+ _context2.n = 4;
466
467
  break;
467
468
  }
468
- _context.n = 3;
469
+ _context2.n = 3;
469
470
  return (0, _cookie.getCartCookieToken)(domainId);
470
471
  case 3:
471
- _t = _context.v;
472
+ _t = _context2.v;
472
473
  case 4:
473
474
  cartToken = _t;
474
475
  clientEnt = (0, _user.makeUser)({
@@ -476,30 +477,30 @@ var CartProvider = function CartProvider(_ref) {
476
477
  }, true);
477
478
  cartEnt = (0, _cart3.makeCart)(_objectSpread({}, cartJson), false, cartToken);
478
479
  cartEnt.client = clientEnt;
479
- _context.n = 5;
480
+ _context2.n = 5;
480
481
  return cartEnt.save({
481
482
  embed: _helpers.cartEmbed
482
483
  });
483
484
  case 5:
484
- savedCart = _context.v;
485
+ savedCart = _context2.v;
485
486
  nextCart = savedCart.toJson();
486
487
  if (!(nextCart !== null && nextCart !== void 0 && (_nextCart$client = nextCart.client) !== null && _nextCart$client !== void 0 && _nextCart$client.id)) {
487
- _context.n = 6;
488
+ _context2.n = 6;
488
489
  break;
489
490
  }
490
491
  setCartClient(nextCart.client);
491
- return _context.a(2, nextCart);
492
+ return _context2.a(2, nextCart);
492
493
  case 6:
493
- _context.n = 8;
494
+ _context2.n = 8;
494
495
  break;
495
496
  case 7:
496
- _context.p = 7;
497
- _t2 = _context.v;
497
+ _context2.p = 7;
498
+ _t2 = _context2.v;
498
499
  case 8:
499
500
  setCartClient(null);
500
- return _context.a(2, cartJson);
501
+ return _context2.a(2, cartJson);
501
502
  }
502
- }, _callee, null, [[2, 7]]);
503
+ }, _callee2, null, [[2, 7]]);
503
504
  }));
504
505
  return _attachSavedClientIfNeeded.apply(this, arguments);
505
506
  }
@@ -507,13 +508,13 @@ var CartProvider = function CartProvider(_ref) {
507
508
  return _createCartAndCookie.apply(this, arguments);
508
509
  }
509
510
  function _createCartAndCookie() {
510
- _createCartAndCookie = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(callback) {
511
+ _createCartAndCookie = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(callback) {
511
512
  var isTest, jobSource, _cart, query, created, cartJson, _t3;
512
- return _regenerator().w(function (_context2) {
513
- while (1) switch (_context2.p = _context2.n) {
513
+ return _regenerator().w(function (_context3) {
514
+ while (1) switch (_context3.p = _context3.n) {
514
515
  case 0:
515
516
  setFetchingCart(true);
516
- _context2.p = 1;
517
+ _context3.p = 1;
517
518
  isTest = (0, _test_checkout.readTestCheckoutFlag)();
518
519
  jobSource = (0, _job_source.jobSourceFieldsForApi)((0, _job_source.captureAndReadJobSource)());
519
520
  _cart = (0, _cart3.makeCart)({
@@ -524,41 +525,41 @@ var CartProvider = function CartProvider(_ref) {
524
525
  }, true);
525
526
  query = [['embed', JSON.stringify(_helpers.cartEmbed)], ['skip_rights', 'y']];
526
527
  if (isTest) query.push(['is_test', 'true']);
527
- _context2.n = 2;
528
+ _context3.n = 2;
528
529
  return merchi.authenticatedFetch('/carts/', {
529
530
  method: 'POST',
530
531
  body: (0, _job_source.appendJobSourceToFormData)(_cart.toFormData(), jobSource),
531
532
  query: query
532
533
  });
533
534
  case 2:
534
- created = _context2.v;
535
+ created = _context3.v;
535
536
  _cart.fromJson(created.cart);
536
- _context2.n = 3;
537
+ _context3.n = 3;
537
538
  return _cart.toJson();
538
539
  case 3:
539
- cartJson = _context2.v;
540
+ cartJson = _context3.v;
540
541
  if (domainId) (0, _cookie.setCartCookie)(Number(domainId), cartJson, undefined, isTest);
541
- _context2.n = 4;
542
+ _context3.n = 4;
542
543
  return attachSavedClientIfNeeded(cartJson);
543
544
  case 4:
544
- cartJson = _context2.v;
545
+ cartJson = _context3.v;
545
546
  setCart(_objectSpread({}, cartJson));
546
547
  if (callback) callback();
547
- _context2.n = 6;
548
+ _context3.n = 6;
548
549
  break;
549
550
  case 5:
550
- _context2.p = 5;
551
- _t3 = _context2.v;
551
+ _context3.p = 5;
552
+ _t3 = _context3.v;
552
553
  (0, _reportFailure.reportCartFailure)(_t3, _reportFailure.CART_FAILURE_SOURCES.create);
553
554
  alertError((_t3 === null || _t3 === void 0 ? void 0 : _t3.errorMessage) || (_t3 === null || _t3 === void 0 ? void 0 : _t3.message) || 'Unable to fetch cart.');
554
555
  case 6:
555
- _context2.p = 6;
556
+ _context3.p = 6;
556
557
  setFetchingCart(false);
557
- return _context2.f(6);
558
+ return _context3.f(6);
558
559
  case 7:
559
- return _context2.a(2);
560
+ return _context3.a(2);
560
561
  }
561
- }, _callee2, null, [[1, 5, 6, 7]]);
562
+ }, _callee3, null, [[1, 5, 6, 7]]);
562
563
  }));
563
564
  return _createCartAndCookie.apply(this, arguments);
564
565
  }
@@ -567,79 +568,79 @@ var CartProvider = function CartProvider(_ref) {
567
568
  } // A checkout link can name the cart. Remember it once, then keep using the cookie
568
569
  // so a later refetch does not put that cart back after the shopper replaced it.
569
570
  function _getCart() {
570
- _getCart = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(cartIdAndToken) {
571
+ _getCart = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(cartIdAndToken) {
571
572
  var id, _cart2, cartJson, isTest, jobSource, saved, _t4;
572
- return _regenerator().w(function (_context3) {
573
- while (1) switch (_context3.p = _context3.n) {
573
+ return _regenerator().w(function (_context4) {
574
+ while (1) switch (_context4.p = _context4.n) {
574
575
  case 0:
575
576
  id = Number(cartIdAndToken[0]); // Set the cart token on the merchi entity
576
577
  if (cartIdAndToken[1]) merchi.cartToken = cartIdAndToken[1];
577
578
  setFetchingCart(true);
578
- _context3.p = 1;
579
- _context3.n = 2;
579
+ _context4.p = 1;
580
+ _context4.n = 2;
580
581
  return merchi.Cart.get(id, {
581
582
  embed: _helpers.cartEmbed
582
583
  });
583
584
  case 2:
584
- _cart2 = _context3.v;
585
- _context3.n = 3;
585
+ _cart2 = _context4.v;
586
+ _context4.n = 3;
586
587
  return _cart2.toJson();
587
588
  case 3:
588
- cartJson = _context3.v;
589
+ cartJson = _context4.v;
589
590
  isTest = (0, _test_checkout.readTestCheckoutFlag)();
590
591
  if (!(Boolean(cartJson.isTest) !== isTest)) {
591
- _context3.n = 5;
592
+ _context4.n = 5;
592
593
  break;
593
594
  }
594
- _context3.n = 4;
595
+ _context4.n = 4;
595
596
  return createCartAndCookie();
596
597
  case 4:
597
- return _context3.a(2);
598
+ return _context4.a(2);
598
599
  case 5:
599
600
  jobSource = (0, _job_source.jobSourceFieldsForApi)((0, _job_source.captureAndReadJobSource)());
600
601
  if (!(0, _job_source.cartNeedsSourceUpdate)(cartJson, jobSource)) {
601
- _context3.n = 7;
602
+ _context4.n = 7;
602
603
  break;
603
604
  }
604
- _context3.n = 6;
605
+ _context4.n = 6;
605
606
  return merchi.authenticatedFetch("/carts/".concat(_cart2.id, "/"), {
606
607
  method: 'PATCH',
607
608
  body: (0, _job_source.appendJobSourceToFormData)(_cart2.toFormData(), jobSource),
608
609
  query: [['embed', JSON.stringify(_helpers.cartEmbed)], ['skip_rights', 'y']]
609
610
  });
610
611
  case 6:
611
- saved = _context3.v;
612
+ saved = _context4.v;
612
613
  _cart2.fromJson(saved.cart);
613
614
  cartJson = _cart2.toJson();
614
615
  case 7:
615
616
  if (!((0, _cart3.stripeIsValidAndActive)(cartJson) || isTest)) {
616
- _context3.n = 9;
617
+ _context4.n = 9;
617
618
  break;
618
619
  }
619
- _context3.n = 8;
620
+ _context4.n = 8;
620
621
  return attachSavedClientIfNeeded(cartJson);
621
622
  case 8:
622
- cartJson = _context3.v;
623
+ cartJson = _context4.v;
623
624
  setCart(_objectSpread({}, cartJson));
624
- _context3.n = 10;
625
+ _context4.n = 10;
625
626
  break;
626
627
  case 9:
627
628
  console.error("MErhci cart error: Stripe payment " + "options have not been correctly set up. " + "Check the company profile payment options tab " + "to set and edit stripe payment options.");
628
629
  setCartSettingsInvalid(true);
629
630
  case 10:
630
- _context3.n = 14;
631
+ _context4.n = 14;
631
632
  break;
632
633
  case 11:
633
- _context3.p = 11;
634
- _t4 = _context3.v;
634
+ _context4.p = 11;
635
+ _t4 = _context4.v;
635
636
  if (!(0, _cartLoadFailure.canReplaceMissingCart)(_t4)) {
636
- _context3.n = 13;
637
+ _context4.n = 13;
637
638
  break;
638
639
  }
639
- _context3.n = 12;
640
+ _context4.n = 12;
640
641
  return createCartAndCookie();
641
642
  case 12:
642
- _context3.n = 14;
643
+ _context4.n = 14;
643
644
  break;
644
645
  case 13:
645
646
  // A network/server/auth failure does not mean the saved cart is gone.
@@ -647,13 +648,13 @@ var CartProvider = function CartProvider(_ref) {
647
648
  (0, _reportFailure.reportCartFailure)(_t4, _reportFailure.CART_FAILURE_SOURCES.load);
648
649
  alertError((_t4 === null || _t4 === void 0 ? void 0 : _t4.errorMessage) || (_t4 === null || _t4 === void 0 ? void 0 : _t4.message) || 'Unable to load cart. Please try again.');
649
650
  case 14:
650
- _context3.p = 14;
651
+ _context4.p = 14;
651
652
  setFetchingCart(false);
652
- return _context3.f(14);
653
+ return _context4.f(14);
653
654
  case 15:
654
- return _context3.a(2);
655
+ return _context4.a(2);
655
656
  }
656
- }, _callee3, null, [[1, 11, 14, 15]]);
657
+ }, _callee4, null, [[1, 11, 14, 15]]);
657
658
  }));
658
659
  return _getCart.apply(this, arguments);
659
660
  }
@@ -661,78 +662,82 @@ var CartProvider = function CartProvider(_ref) {
661
662
  return _adoptHandoffCart.apply(this, arguments);
662
663
  }
663
664
  function _adoptHandoffCart() {
664
- _adoptHandoffCart = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4() {
665
+ _adoptHandoffCart = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5() {
665
666
  var raw, handoff;
666
- return _regenerator().w(function (_context4) {
667
- while (1) switch (_context4.n) {
667
+ return _regenerator().w(function (_context5) {
668
+ while (1) switch (_context5.n) {
668
669
  case 0:
669
670
  if (!(typeof window === 'undefined' || !domainId)) {
670
- _context4.n = 1;
671
+ _context5.n = 1;
671
672
  break;
672
673
  }
673
- return _context4.a(2);
674
+ return _context5.a(2);
674
675
  case 1:
675
676
  raw = new URLSearchParams(window.location.search).get('cart');
676
677
  if (!(!raw || raw === appliedHandoffCart.current)) {
677
- _context4.n = 2;
678
+ _context5.n = 2;
678
679
  break;
679
680
  }
680
- return _context4.a(2);
681
+ return _context5.a(2);
681
682
  case 2:
682
683
  handoff = (0, _cookie.readHandoffCart)(window.location.search);
683
684
  if (handoff) {
684
- _context4.n = 3;
685
+ _context5.n = 3;
685
686
  break;
686
687
  }
687
- return _context4.a(2);
688
+ return _context5.a(2);
688
689
  case 3:
689
690
  appliedHandoffCart.current = raw;
690
- _context4.n = 4;
691
+ _context5.n = 4;
691
692
  return (0, _cookie.setCartCookie)(Number(domainId), {
692
693
  id: handoff[0],
693
694
  token: handoff[1]
694
695
  });
695
696
  case 4:
696
- return _context4.a(2);
697
+ return _context5.a(2);
697
698
  }
698
- }, _callee4);
699
+ }, _callee5);
699
700
  }));
700
701
  return _adoptHandoffCart.apply(this, arguments);
701
702
  }
702
703
  function actionGetMerchiCart() {
703
- return _actionGetMerchiCart.apply(this, arguments);
704
- }
705
- function _actionGetMerchiCart() {
706
- _actionGetMerchiCart = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5() {
704
+ var active = cartInitializations.current.get(domainId);
705
+ if (active) return active;
706
+ // Mount, modal opening and explicit callers may run before React commits
707
+ // fetchingCart. Share the whole cookie lookup/read-or-create operation.
708
+ var initialization = Promise.resolve().then(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
707
709
  var cartIdAndToken;
708
- return _regenerator().w(function (_context5) {
709
- while (1) switch (_context5.n) {
710
+ return _regenerator().w(function (_context) {
711
+ while (1) switch (_context.n) {
710
712
  case 0:
711
- _context5.n = 1;
713
+ _context.n = 1;
712
714
  return adoptHandoffCart();
713
715
  case 1:
714
- _context5.n = 2;
716
+ _context.n = 2;
715
717
  return (0, _cookie.getCartCookie)(domainId);
716
718
  case 2:
717
- cartIdAndToken = _context5.v;
719
+ cartIdAndToken = _context.v;
718
720
  if (!cartIdAndToken) {
719
- _context5.n = 4;
721
+ _context.n = 4;
720
722
  break;
721
723
  }
722
- _context5.n = 3;
724
+ _context.n = 3;
723
725
  return getCart(cartIdAndToken);
724
726
  case 3:
725
- _context5.n = 5;
727
+ _context.n = 5;
726
728
  break;
727
729
  case 4:
728
- _context5.n = 5;
730
+ _context.n = 5;
729
731
  return createCartAndCookie();
730
732
  case 5:
731
- return _context5.a(2);
733
+ return _context.a(2);
732
734
  }
733
- }, _callee5);
734
- }));
735
- return _actionGetMerchiCart.apply(this, arguments);
735
+ }, _callee);
736
+ })))["finally"](function () {
737
+ cartInitializations.current["delete"](domainId);
738
+ });
739
+ cartInitializations.current.set(domainId, initialization);
740
+ return initialization;
736
741
  }
737
742
  function clearCart(_x4) {
738
743
  return _clearCart.apply(this, arguments);
@@ -866,11 +871,11 @@ var CartProvider = function CartProvider(_ref) {
866
871
  }
867
872
  function _getMerchiCartValues() {
868
873
  _getMerchiCartValues = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee9() {
869
- var _ref2, cartItems, currency, subtotalCost, taxAmount, totalCost, cartItemsCount;
874
+ var _ref3, cartItems, currency, subtotalCost, taxAmount, totalCost, cartItemsCount;
870
875
  return _regenerator().w(function (_context9) {
871
876
  while (1) switch (_context9.n) {
872
877
  case 0:
873
- _ref2 = cart, cartItems = _ref2.cartItems, currency = _ref2.currency, subtotalCost = _ref2.subtotalCost, taxAmount = _ref2.taxAmount, totalCost = _ref2.totalCost;
878
+ _ref3 = cart, cartItems = _ref3.cartItems, currency = _ref3.currency, subtotalCost = _ref3.subtotalCost, taxAmount = _ref3.taxAmount, totalCost = _ref3.totalCost;
874
879
  cartItemsCount = cartItems ? cartItems.length : 0;
875
880
  return _context9.a(2, {
876
881
  cart: cart,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@merchi/cart",
3
- "version": "1.4.61",
3
+ "version": "1.4.63",
4
4
  "description": "Merchi's cart",
5
5
  "source": "src/index.ts",
6
6
  "main": "lib/index.js",
@@ -93,8 +93,8 @@
93
93
  "@fortawesome/fontawesome-svg-core": "6.4.2",
94
94
  "@fortawesome/free-solid-svg-icons": "6.4.2",
95
95
  "@fortawesome/react-fontawesome": "^0.2.0",
96
- "@merchi/error-catch": "^0.1.10",
97
- "@merchi/invoice": "^1.3.15",
96
+ "@merchi/error-catch": "^0.1.11",
97
+ "@merchi/invoice": "^1.3.16",
98
98
  "@merchi/product-form": "^1.19.54",
99
99
  "@merchi/product-form-sdk": "^1.0.35",
100
100
  "@merchi/sdk": "^1.42.24",
@@ -59,6 +59,7 @@ describe('cart load and replacement failures', () => {
59
59
  document.body.appendChild(container);
60
60
  root = createRoot(container);
61
61
  mockPost.mockResolvedValue({ cart: { id: 99, token: 'new-token' } });
62
+ (getCartCookie as jest.Mock).mockResolvedValue(['42', 'saved-token']);
62
63
  });
63
64
  afterEach(async () => {
64
65
  await act(async () => root.unmount());
@@ -83,6 +84,82 @@ describe('cart load and replacement failures', () => {
83
84
  });
84
85
  await act(async () => context.setActiveTabIndex(tabIdClearCart));
85
86
  }
87
+ it('shares cold initialization with opening the modal and concurrent getCart callers', async () => {
88
+ (getCartCookie as jest.Mock).mockResolvedValue(undefined);
89
+ let finish!: (value: unknown) => void;
90
+ mockPost.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
91
+ await act(async () => root.render(
92
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
93
+ ));
94
+ let first!: Promise<void>, second!: Promise<void>;
95
+ await act(async () => {
96
+ context.toggleCartModal();
97
+ first = (window as any).getCart();
98
+ second = (window as any).getCart();
99
+ });
100
+ expect(mockPost).toHaveBeenCalledTimes(1);
101
+ expect(context.fetchingCart).toBe(true);
102
+ await act(async () => {
103
+ finish({ cart: { id: 99, token: 'new-token' } });
104
+ await Promise.all([first, second]);
105
+ });
106
+ expect(context.cart.id).toBe(99);
107
+ expect(context.fetchingCart).toBe(false);
108
+ expect(setCartCookie).toHaveBeenCalledTimes(1);
109
+ });
110
+ it('shares an active saved-cart read and allows a later refresh', async () => {
111
+ let finish!: (value: unknown) => void;
112
+ const saved = { toJson: () => ({ id: 42, isTest: false, cartItems: [{ id: 7 }] }) };
113
+ mockGet.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }))
114
+ .mockResolvedValue(saved);
115
+ await act(async () => root.render(
116
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
117
+ ));
118
+ let read!: Promise<void>;
119
+ await act(async () => {
120
+ context.toggleCartModal();
121
+ read = (window as any).getCart();
122
+ });
123
+ expect(mockGet).toHaveBeenCalledTimes(1);
124
+ await act(async () => { finish(saved); await read; });
125
+ await act(async () => { await (window as any).getCart(); });
126
+ expect(mockGet).toHaveBeenCalledTimes(2);
127
+ expect(mockPost).not.toHaveBeenCalled();
128
+ expect(context.cart.cartItems).toHaveLength(1);
129
+ });
130
+ it('releases failed initialization so an explicit retry can create the cart', async () => {
131
+ (getCartCookie as jest.Mock).mockResolvedValue(undefined);
132
+ mockPost.mockRejectedValueOnce(new TypeError('Failed to fetch'));
133
+ await act(async () => root.render(
134
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
135
+ ));
136
+ expect(mockPost).toHaveBeenCalledTimes(1);
137
+ expect(context.fetchingCart).toBe(false);
138
+ await act(async () => {
139
+ await Promise.all([(window as any).getCart(), (window as any).getCart()]);
140
+ });
141
+ expect(mockPost).toHaveBeenCalledTimes(2);
142
+ expect(context.cart.id).toBe(99);
143
+ expect(context.fetchingCart).toBe(false);
144
+ });
145
+ it('initializes a changed domain independently of the previous pending domain', async () => {
146
+ const finish: Record<number, (value: unknown) => void> = {};
147
+ (getCartCookie as jest.Mock).mockImplementation(id => Promise.resolve([String(id), 'token']));
148
+ mockGet.mockImplementation(id => new Promise(resolve => { finish[id] = resolve; }));
149
+ const view = (id: number) => <CartProvider domainId={id} createCartAndCookie={() => {}}><Probe /></CartProvider>;
150
+ await act(async () => root.render(view(5)));
151
+ await act(async () => root.render(view(6)));
152
+ expect(mockGet).toHaveBeenCalledTimes(2);
153
+ await act(async () => finish[5]({ toJson: () => ({ id: 5, isTest: false }) }));
154
+ let current!: Promise<void>;
155
+ await act(async () => { current = (window as any).getCart(); });
156
+ expect(mockGet).toHaveBeenCalledTimes(2);
157
+ await act(async () => {
158
+ finish[6]({ toJson: () => ({ id: 6, isTest: false }) });
159
+ await current;
160
+ });
161
+ expect(context.cart.id).toBe(6);
162
+ });
86
163
  it.each([new TypeError('Load failed'), { statusCode: 502, message: 'Gateway unavailable' }, { statusCode: 403, message: 'Forbidden' }])('preserves the saved cart and never POSTs a replacement after %s', async error => {
87
164
  await mount(error);
88
165
  expect(getCartCookie).toHaveBeenCalledWith(5);
@@ -596,6 +596,7 @@ const CartProvider = ({
596
596
  const [fetchingCart, setFetchingCart] = useState(false);
597
597
  const [cartSettingsInvalid, setCartSettingsInvalid] = useState(false);
598
598
  const appliedHandoffCart = useRef<string | null>(null);
599
+ const cartInitializations = useRef(new Map<number | undefined, Promise<void>>());
599
600
 
600
601
  async function attachSavedClientIfNeeded(cartJson: any) {
601
602
  if (cartJson?.client?.id) {
@@ -722,14 +723,24 @@ const CartProvider = ({
722
723
  await setCartCookie(Number(domainId), { id: handoff[0], token: handoff[1] });
723
724
  }
724
725
 
725
- async function actionGetMerchiCart() {
726
- await adoptHandoffCart();
727
- const cartIdAndToken = await getCartCookie((domainId as number));
728
- if (cartIdAndToken) {
729
- await getCart(cartIdAndToken);
730
- } else {
731
- await createCartAndCookie();
732
- }
726
+ function actionGetMerchiCart() {
727
+ const active = cartInitializations.current.get(domainId);
728
+ if (active) return active;
729
+ // Mount, modal opening and explicit callers may run before React commits
730
+ // fetchingCart. Share the whole cookie lookup/read-or-create operation.
731
+ const initialization = Promise.resolve().then(async () => {
732
+ await adoptHandoffCart();
733
+ const cartIdAndToken = await getCartCookie((domainId as number));
734
+ if (cartIdAndToken) {
735
+ await getCart(cartIdAndToken);
736
+ } else {
737
+ await createCartAndCookie();
738
+ }
739
+ }).finally(() => {
740
+ cartInitializations.current.delete(domainId);
741
+ });
742
+ cartInitializations.current.set(domainId, initialization);
743
+ return initialization;
733
744
  }
734
745
 
735
746
  async function clearCart(callback?: () => void) {