@merchi/cart 1.4.62 → 1.4.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ /** A startup optimization only; explicit cart operations remain available. */
2
+ export declare function isAutomatedClient(userAgent?: string): boolean;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.isAutomatedClient = isAutomatedClient;
7
+ /** A startup optimization only; explicit cart operations remain available. */
8
+ function isAutomatedClient() {
9
+ var userAgent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : typeof navigator === 'undefined' ? '' : navigator.userAgent;
10
+ return /HeadlessChrome|bot|crawler|spider|slurp|SEBot-WA/i.test(userAgent);
11
+ }
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@merchi/cart",
3
- "version": "1.4.62",
3
+ "version": "1.4.64",
4
4
  "description": "Merchi's cart",
5
5
  "source": "src/index.ts",
6
6
  "main": "lib/index.js",
@@ -9,6 +9,7 @@ import { tabIdClearCart, tabIdItems } from './utilities/tabs';
9
9
 
10
10
  const mockGet = jest.fn();
11
11
  const mockPost = jest.fn();
12
+ const mockCreateItem = jest.fn();
12
13
 
13
14
  jest.mock('@merchi/sdk', () => ({
14
15
  Merchi: jest.fn().mockImplementation(() => ({
@@ -16,13 +17,16 @@ jest.mock('@merchi/sdk', () => ({
16
17
  authenticatedFetch: (...args: unknown[]) => mockPost(...args),
17
18
  })),
18
19
  }));
19
- jest.mock('./utilities/product', () => ({ makeProduct: jest.fn() }));
20
+ jest.mock('./utilities/product', () => ({ makeProduct: jest.fn(json => json) }));
21
+ jest.mock('./utilities/job', () => ({ makeJob: jest.fn(json => json) }));
20
22
  jest.mock('./utilities/cart', () => ({
21
- makeCart: () => ({
23
+ makeCart: (json: any) => ({
24
+ ...json,
22
25
  toFormData: () => new FormData(),
23
26
  fromJson: jest.fn(),
24
27
  toJson: () => ({ id: 99, token: 'new-token', isTest: false }),
25
28
  }),
29
+ makeCartItem: () => ({ create: mockCreateItem }),
26
30
  stripeIsValidAndActive: () => true,
27
31
  }));
28
32
  jest.mock('./utilities/cookie', () => ({
@@ -40,6 +44,7 @@ jest.mock('./utilities/job_source', () => ({
40
44
  }));
41
45
  jest.mock('./utilities/reportFailure', () => ({
42
46
  reportCartFailure: jest.fn(),
47
+ reportAddCartItemFailure: jest.fn((error, onError) => onError(error)),
43
48
  CART_FAILURE_SOURCES: { load: 'cart.load', create: 'cart.create' },
44
49
  }));
45
50
 
@@ -52,17 +57,32 @@ function Probe() {
52
57
  describe('cart load and replacement failures', () => {
53
58
  let root: Root;
54
59
  let container: HTMLDivElement;
60
+ const userAgentDescriptor = Object.getOwnPropertyDescriptor(navigator, 'userAgent');
61
+ const headlessUserAgent = 'Mozilla/5.0 (X11; Linux x86_64) HeadlessChrome/153.0.8010.0 Safari/537.36';
62
+ function setUserAgent(value: string) {
63
+ Object.defineProperty(navigator, 'userAgent', { configurable: true, value });
64
+ }
55
65
  beforeEach(() => {
56
66
  jest.clearAllMocks();
67
+ mockGet.mockReset();
68
+ mockPost.mockReset();
69
+ mockCreateItem.mockReset();
70
+ mockCreateItem.mockImplementation(function (this: any) {
71
+ return Promise.resolve({ toJson: () => ({ id: 7, cart: { id: this.cart.id } }) });
72
+ });
73
+ (getCartCookie as jest.Mock).mockReset();
57
74
  (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
58
75
  container = document.createElement('div');
59
76
  document.body.appendChild(container);
60
77
  root = createRoot(container);
61
78
  mockPost.mockResolvedValue({ cart: { id: 99, token: 'new-token' } });
79
+ (getCartCookie as jest.Mock).mockResolvedValue(['42', 'saved-token']);
62
80
  });
63
81
  afterEach(async () => {
64
82
  await act(async () => root.unmount());
65
83
  container.remove();
84
+ if (userAgentDescriptor) Object.defineProperty(navigator, 'userAgent', userAgentDescriptor);
85
+ else delete (navigator as any).userAgent;
66
86
  });
67
87
  async function mount(error: unknown) {
68
88
  mockGet.mockRejectedValue(error);
@@ -83,6 +103,236 @@ describe('cart load and replacement failures', () => {
83
103
  });
84
104
  await act(async () => context.setActiveTabIndex(tabIdClearCart));
85
105
  }
106
+ it.each([
107
+ 'Mozilla/5.0 (X11; Linux x86_64) HeadlessChrome/153.0.8010.0 Safari/537.36',
108
+ 'Mozilla/5.0 (compatible; Baiduspider-render/2.0)',
109
+ ])('does not create an unused cart on automated startup: %s', async userAgent => {
110
+ setUserAgent(userAgent);
111
+ (getCartCookie as jest.Mock).mockResolvedValue(undefined);
112
+ await act(async () => root.render(
113
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
114
+ ));
115
+ expect(mockGet).not.toHaveBeenCalled();
116
+ expect(mockPost).not.toHaveBeenCalled();
117
+ expect(context.fetchingCart).toBe(false);
118
+ expect(reportCartFailure).not.toHaveBeenCalled();
119
+ });
120
+ it('allows explicit cart opening and concurrent callers in an automated browser', async () => {
121
+ setUserAgent(headlessUserAgent);
122
+ (getCartCookie as jest.Mock).mockResolvedValue(undefined);
123
+ await act(async () => root.render(
124
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
125
+ ));
126
+ expect(mockPost).not.toHaveBeenCalled();
127
+ await act(async () => {
128
+ context.toggleCartModal();
129
+ await Promise.all([(window as any).getCart(), (window as any).refetchCart()]);
130
+ });
131
+ expect(mockPost).toHaveBeenCalledTimes(1);
132
+ expect(context.cart.id).toBe(99);
133
+ });
134
+ it('creates once when explicit interaction joins a pending passive cookie lookup', async () => {
135
+ setUserAgent(headlessUserAgent);
136
+ let finishCookie!: (value: undefined) => void;
137
+ (getCartCookie as jest.Mock).mockImplementationOnce(
138
+ () => new Promise(resolve => { finishCookie = resolve; }),
139
+ ).mockResolvedValue(undefined);
140
+ await act(async () => root.render(
141
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
142
+ ));
143
+ let first!: Promise<void>, second!: Promise<void>;
144
+ await act(async () => {
145
+ first = (window as any).getCart();
146
+ second = (window as any).getCart();
147
+ context.toggleCartModal();
148
+ });
149
+ expect(mockPost).not.toHaveBeenCalled();
150
+ await act(async () => { finishCookie(undefined); await Promise.all([first, second]); });
151
+ expect(mockPost).toHaveBeenCalledTimes(1);
152
+ expect(context.cart.id).toBe(99);
153
+ });
154
+ it('restores saved carts for automated clients without duplicating an active read', async () => {
155
+ setUserAgent(headlessUserAgent);
156
+ let finish!: (value: unknown) => void;
157
+ mockGet.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
158
+ await act(async () => root.render(
159
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
160
+ ));
161
+ let read!: Promise<void>;
162
+ await act(async () => { read = (window as any).getCart(); context.toggleCartModal(); });
163
+ expect(mockGet).toHaveBeenCalledTimes(1);
164
+ await act(async () => {
165
+ finish({ toJson: () => ({ id: 42, isTest: false, cartItems: [{ id: 7 }] }) });
166
+ await read;
167
+ });
168
+ expect(mockPost).not.toHaveBeenCalled();
169
+ expect(context.cart.cartItems).toHaveLength(1);
170
+ });
171
+ it('keeps explicit retry available after an automated client creation fails', async () => {
172
+ setUserAgent(headlessUserAgent);
173
+ (getCartCookie as jest.Mock).mockResolvedValue(undefined);
174
+ mockPost.mockRejectedValueOnce(new TypeError('Failed to fetch'));
175
+ await act(async () => root.render(
176
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
177
+ ));
178
+ expect(mockPost).not.toHaveBeenCalled();
179
+ await act(async () => { await (window as any).getCart(); });
180
+ expect(mockPost).toHaveBeenCalledTimes(1);
181
+ expect(context.fetchingCart).toBe(false);
182
+ await act(async () => { await (window as any).getCart(); });
183
+ expect(mockPost).toHaveBeenCalledTimes(2);
184
+ expect(context.cart.id).toBe(99);
185
+ });
186
+ it('initializes a cart for a direct item operation without a storefront readiness helper', async () => {
187
+ setUserAgent(headlessUserAgent);
188
+ (getCartCookie as jest.Mock).mockResolvedValue(undefined);
189
+ await act(async () => root.render(
190
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
191
+ ));
192
+ const onSuccess = jest.fn(), onError = jest.fn();
193
+ await act(async () => {
194
+ await (window as any).addCartItem({ product: { id: 44 }, quantity: 100 }, onSuccess, onError);
195
+ });
196
+ expect(mockPost).toHaveBeenCalledTimes(1);
197
+ expect(mockCreateItem).toHaveBeenCalledTimes(1);
198
+ expect(onSuccess).toHaveBeenCalledWith({ id: 7, cart: { id: 99 } });
199
+ expect(onError).not.toHaveBeenCalled();
200
+ });
201
+ it('rejects a direct item operation when initialization fails without posting an item', async () => {
202
+ setUserAgent(headlessUserAgent);
203
+ (getCartCookie as jest.Mock).mockResolvedValue(undefined);
204
+ mockPost.mockRejectedValueOnce(new TypeError('Failed to fetch'));
205
+ await act(async () => root.render(
206
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
207
+ ));
208
+ const onSuccess = jest.fn(), onError = jest.fn();
209
+ await act(async () => {
210
+ await (window as any).addCartItem({ product: { id: 44 }, quantity: 100 }, onSuccess, onError);
211
+ });
212
+ expect(mockPost).toHaveBeenCalledTimes(1);
213
+ expect(mockCreateItem).not.toHaveBeenCalled();
214
+ expect(onSuccess).not.toHaveBeenCalled();
215
+ expect(onError).toHaveBeenCalledTimes(1);
216
+ expect(context.fetchingCart).toBe(false);
217
+ });
218
+ it('waits for ordinary startup before concurrent direct item operations', async () => {
219
+ (getCartCookie as jest.Mock).mockResolvedValue(undefined);
220
+ let finish!: (value: unknown) => void;
221
+ mockPost.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
222
+ await act(async () => root.render(
223
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
224
+ ));
225
+ const onSuccess = jest.fn(), onError = jest.fn();
226
+ let first!: Promise<void>, second!: Promise<void>;
227
+ await act(async () => {
228
+ const job = { product: { id: 44 }, quantity: 100 };
229
+ first = (window as any).addCartItem(job, onSuccess, onError);
230
+ second = (window as any).addCartItem(job, onSuccess, onError);
231
+ });
232
+ expect(mockCreateItem).not.toHaveBeenCalled();
233
+ await act(async () => {
234
+ finish({ cart: { id: 99, token: 'new-token' } });
235
+ await Promise.all([first, second]);
236
+ });
237
+ expect(mockPost).toHaveBeenCalledTimes(1);
238
+ expect(onSuccess.mock.calls.map(call => call[0].cart.id)).toEqual([99, 99]);
239
+ expect(onError).not.toHaveBeenCalled();
240
+ });
241
+ it('does not automatically repeat a failed item write after explicit initialization', async () => {
242
+ setUserAgent(headlessUserAgent);
243
+ (getCartCookie as jest.Mock).mockResolvedValue(undefined);
244
+ mockCreateItem.mockRejectedValueOnce(new TypeError('Failed to fetch'));
245
+ await act(async () => root.render(
246
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
247
+ ));
248
+ const onSuccess = jest.fn(), onError = jest.fn();
249
+ const job = { product: { id: 44 }, quantity: 100 };
250
+ await act(async () => { await (window as any).addCartItem(job, onSuccess, onError); });
251
+ expect(mockPost).toHaveBeenCalledTimes(1);
252
+ expect(mockCreateItem).toHaveBeenCalledTimes(1);
253
+ expect(onSuccess).not.toHaveBeenCalled();
254
+ expect(onError).toHaveBeenCalledTimes(1);
255
+ await act(async () => { await (window as any).addCartItem(job, onSuccess, onError); });
256
+ expect(mockPost).toHaveBeenCalledTimes(1);
257
+ expect(mockCreateItem).toHaveBeenCalledTimes(2);
258
+ expect(onSuccess).toHaveBeenCalledWith({ id: 7, cart: { id: 99 } });
259
+ });
260
+ it('shares cold initialization with opening the modal and concurrent getCart callers', async () => {
261
+ (getCartCookie as jest.Mock).mockResolvedValue(undefined);
262
+ let finish!: (value: unknown) => void;
263
+ mockPost.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
264
+ await act(async () => root.render(
265
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
266
+ ));
267
+ let first!: Promise<void>, second!: Promise<void>;
268
+ await act(async () => {
269
+ context.toggleCartModal();
270
+ first = (window as any).getCart();
271
+ second = (window as any).getCart();
272
+ });
273
+ expect(mockPost).toHaveBeenCalledTimes(1);
274
+ expect(context.fetchingCart).toBe(true);
275
+ await act(async () => {
276
+ finish({ cart: { id: 99, token: 'new-token' } });
277
+ await Promise.all([first, second]);
278
+ });
279
+ expect(context.cart.id).toBe(99);
280
+ expect(context.fetchingCart).toBe(false);
281
+ expect(setCartCookie).toHaveBeenCalledTimes(1);
282
+ });
283
+ it('shares an active saved-cart read and allows a later refresh', async () => {
284
+ let finish!: (value: unknown) => void;
285
+ const saved = { toJson: () => ({ id: 42, isTest: false, cartItems: [{ id: 7 }] }) };
286
+ mockGet.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }))
287
+ .mockResolvedValue(saved);
288
+ await act(async () => root.render(
289
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
290
+ ));
291
+ let read!: Promise<void>;
292
+ await act(async () => {
293
+ context.toggleCartModal();
294
+ read = (window as any).getCart();
295
+ });
296
+ expect(mockGet).toHaveBeenCalledTimes(1);
297
+ await act(async () => { finish(saved); await read; });
298
+ await act(async () => { await (window as any).getCart(); });
299
+ expect(mockGet).toHaveBeenCalledTimes(2);
300
+ expect(mockPost).not.toHaveBeenCalled();
301
+ expect(context.cart.cartItems).toHaveLength(1);
302
+ });
303
+ it('releases failed initialization so an explicit retry can create the cart', async () => {
304
+ (getCartCookie as jest.Mock).mockResolvedValue(undefined);
305
+ mockPost.mockRejectedValueOnce(new TypeError('Failed to fetch'));
306
+ await act(async () => root.render(
307
+ <CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
308
+ ));
309
+ expect(mockPost).toHaveBeenCalledTimes(1);
310
+ expect(context.fetchingCart).toBe(false);
311
+ await act(async () => {
312
+ await Promise.all([(window as any).getCart(), (window as any).getCart()]);
313
+ });
314
+ expect(mockPost).toHaveBeenCalledTimes(2);
315
+ expect(context.cart.id).toBe(99);
316
+ expect(context.fetchingCart).toBe(false);
317
+ });
318
+ it('initializes a changed domain independently of the previous pending domain', async () => {
319
+ const finish: Record<number, (value: unknown) => void> = {};
320
+ (getCartCookie as jest.Mock).mockImplementation(id => Promise.resolve([String(id), 'token']));
321
+ mockGet.mockImplementation(id => new Promise(resolve => { finish[id] = resolve; }));
322
+ const view = (id: number) => <CartProvider domainId={id} createCartAndCookie={() => {}}><Probe /></CartProvider>;
323
+ await act(async () => root.render(view(5)));
324
+ await act(async () => root.render(view(6)));
325
+ expect(mockGet).toHaveBeenCalledTimes(2);
326
+ await act(async () => finish[5]({ toJson: () => ({ id: 5, isTest: false }) }));
327
+ let current!: Promise<void>;
328
+ await act(async () => { current = (window as any).getCart(); });
329
+ expect(mockGet).toHaveBeenCalledTimes(2);
330
+ await act(async () => {
331
+ finish[6]({ toJson: () => ({ id: 6, isTest: false }) });
332
+ await current;
333
+ });
334
+ expect(context.cart.id).toBe(6);
335
+ });
86
336
  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
337
  await mount(error);
88
338
  expect(getCartCookie).toHaveBeenCalledWith(5);
@@ -22,6 +22,7 @@ import {
22
22
  import { makeUser } from './utilities/user';
23
23
  import { persistTestCheckoutFlag, readTestCheckoutFlag } from './utilities/test_checkout';
24
24
  import { reportAddCartItemFailure, reportCartFailure, CART_FAILURE_SOURCES } from './utilities/reportFailure';
25
+ import { isAutomatedClient } from './utilities/automatedClient';
25
26
  import { canReplaceMissingCart } from './utilities/cartLoadFailure';
26
27
  import {
27
28
  appendJobSourceToFormData,
@@ -596,6 +597,9 @@ const CartProvider = ({
596
597
  const [fetchingCart, setFetchingCart] = useState(false);
597
598
  const [cartSettingsInvalid, setCartSettingsInvalid] = useState(false);
598
599
  const appliedHandoffCart = useRef<string | null>(null);
600
+ const cartInitializations = useRef(new Map<
601
+ number | undefined, Promise<{ skippedCreation: boolean; cart?: any }>
602
+ >());
599
603
 
600
604
  async function attachSavedClientIfNeeded(cartJson: any) {
601
605
  if (cartJson?.client?.id) {
@@ -649,12 +653,18 @@ const CartProvider = ({
649
653
  cartJson = await attachSavedClientIfNeeded(cartJson);
650
654
  setCart({...cartJson});
651
655
  if (callback) callback();
656
+ return cartJson;
652
657
  } catch (e: any) {
653
658
  reportCartFailure(e, CART_FAILURE_SOURCES.create);
654
659
  alertError(e?.errorMessage || e?.message || 'Unable to fetch cart.');
655
660
  } finally {
656
661
  setFetchingCart(false);
657
662
  }
663
+ return undefined;
664
+ }
665
+
666
+ async function requestNewCart(callback?: () => void) {
667
+ await createCartAndCookie(callback);
658
668
  }
659
669
 
660
670
  async function getCart(cartIdAndToken: Array<string>) {
@@ -668,8 +678,7 @@ const CartProvider = ({
668
678
  let cartJson = await cart.toJson();
669
679
  const isTest = readTestCheckoutFlag();
670
680
  if (Boolean(cartJson.isTest) !== isTest) {
671
- await createCartAndCookie();
672
- return;
681
+ return await createCartAndCookie();
673
682
  }
674
683
  const jobSource = jobSourceFieldsForApi(captureAndReadJobSource());
675
684
  if (cartNeedsSourceUpdate(cartJson, jobSource)) {
@@ -687,6 +696,7 @@ const CartProvider = ({
687
696
  if (stripeIsValidAndActive(cartJson) || isTest) {
688
697
  cartJson = await attachSavedClientIfNeeded(cartJson);
689
698
  setCart({...cartJson});
699
+ return cartJson;
690
700
  } else {
691
701
  console.error(
692
702
  `MErhci cart error: Stripe payment ` +
@@ -698,7 +708,7 @@ const CartProvider = ({
698
708
  }
699
709
  } catch(e: any){
700
710
  if (canReplaceMissingCart(e)) {
701
- await createCartAndCookie();
711
+ return await createCartAndCookie();
702
712
  } else {
703
713
  // A network/server/auth failure does not mean the saved cart is gone.
704
714
  // Preserve its cookie and contents so the shopper can retry the read.
@@ -708,6 +718,7 @@ const CartProvider = ({
708
718
  } finally {
709
719
  setFetchingCart(false);
710
720
  }
721
+ return undefined;
711
722
  }
712
723
 
713
724
  // A checkout link can name the cart. Remember it once, then keep using the cookie
@@ -722,14 +733,32 @@ const CartProvider = ({
722
733
  await setCartCookie(Number(domainId), { id: handoff[0], token: handoff[1] });
723
734
  }
724
735
 
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();
736
+ function actionGetMerchiCart(allowCreation = true): Promise<any> {
737
+ let active = cartInitializations.current.get(domainId);
738
+ // Mount, modal opening and explicit callers may run before React commits
739
+ // fetchingCart. Share the whole cookie lookup/read-or-create operation.
740
+ if (!active) {
741
+ active = Promise.resolve().then(async () => {
742
+ await adoptHandoffCart();
743
+ const cartIdAndToken = await getCartCookie((domainId as number));
744
+ if (cartIdAndToken) {
745
+ return { skippedCreation: false, cart: await getCart(cartIdAndToken) };
746
+ } else if (allowCreation) {
747
+ return { skippedCreation: false, cart: await createCartAndCookie() };
748
+ }
749
+ return { skippedCreation: true };
750
+ }).finally(() => {
751
+ cartInitializations.current.delete(domainId);
752
+ });
753
+ cartInitializations.current.set(domainId, active);
732
754
  }
755
+ return active.then(result => {
756
+ // An explicit caller can join passive startup before its cookie lookup
757
+ // finishes. Once that no-op completes, create through the same shared
758
+ // initialization path so concurrent explicit callers still issue one POST.
759
+ if (result.skippedCreation && allowCreation) return actionGetMerchiCart();
760
+ return result.cart;
761
+ });
733
762
  }
734
763
 
735
764
  async function clearCart(callback?: () => void) {
@@ -844,25 +873,30 @@ const CartProvider = ({
844
873
  onError: (e: any) => void,
845
874
  ) {
846
875
  setFetchingCart(true);
847
- const jobEnt = makeJob(jobJson, true);
848
- const cartToken = await getCartCookieToken((domainId as number));
849
- const cartEnt = makeCart(cart, false, cartToken);
850
- const cartItemEnt = makeCartItem({}, true);
851
- const cartItemProduct = makeProduct({ id: (jobEnt.product as any).id });
852
-
853
- cartItemEnt.cart = cartEnt;
854
- cartItemEnt.quantity = jobEnt.quantity;
855
- cartItemEnt.product = cartItemProduct;
856
- cartItemEnt.variations = jobEnt.variations;
857
- cartItemEnt.variationsGroups = jobEnt.variationsGroups;
858
- cartItemEnt.taxType = jobEnt.taxType;
859
- cartItemEnt.ownDrafts = jobEnt.ownDrafts;
860
- cartItemEnt.clientFiles = jobEnt.clientFiles;
861
- cartItemEnt.tags = jobEnt.tags;
862
- if (typeof jobJson.designInputNotes === 'string' && jobJson.designInputNotes) {
863
- cartItemEnt.notes = jobJson.designInputNotes;
864
- }
865
876
  try {
877
+ const jobEnt = makeJob(jobJson, true);
878
+ const cartItemProduct = makeProduct({ id: (jobEnt.product as any).id });
879
+ // Legacy clients can call addCartItem directly, without first opening
880
+ // the cart or waiting for React to commit the initialized cart state.
881
+ const readyCart = cart?.id ? cart : await actionGetMerchiCart();
882
+ if (!readyCart?.id) throw new Error('Unable to initialize cart. Please try again.');
883
+ setFetchingCart(true);
884
+ const cartToken = await getCartCookieToken((domainId as number));
885
+ const cartEnt = makeCart(readyCart, false, cartToken);
886
+ const cartItemEnt = makeCartItem({}, true);
887
+
888
+ cartItemEnt.cart = cartEnt;
889
+ cartItemEnt.quantity = jobEnt.quantity;
890
+ cartItemEnt.product = cartItemProduct;
891
+ cartItemEnt.variations = jobEnt.variations;
892
+ cartItemEnt.variationsGroups = jobEnt.variationsGroups;
893
+ cartItemEnt.taxType = jobEnt.taxType;
894
+ cartItemEnt.ownDrafts = jobEnt.ownDrafts;
895
+ cartItemEnt.clientFiles = jobEnt.clientFiles;
896
+ cartItemEnt.tags = jobEnt.tags;
897
+ if (typeof jobJson.designInputNotes === 'string' && jobJson.designInputNotes) {
898
+ cartItemEnt.notes = jobJson.designInputNotes;
899
+ }
866
900
  const item = await cartItemEnt.create();
867
901
  const itemJson = await item.toJson();
868
902
  onSuccess(itemJson);
@@ -893,17 +927,17 @@ const CartProvider = ({
893
927
  if (typeof window !== 'undefined') {
894
928
  (window as any).addCartItem = addCartItem;
895
929
  (window as any).toggleCartOpen = toggleCartModal;
896
- (window as any).getCart = () => actionGetMerchiCart();
930
+ (window as any).getCart = async () => { await actionGetMerchiCart(); };
897
931
  (window as any).getMerchiCartValues = getMerchiCartValues;
898
932
  (window as any).isMerchiCartFetching = isMerchiCartFetching;
899
933
  (window as any).setCartComplete = setCartComplete;
900
934
  (window as any).refetchCart = refetchCart;
901
- (window as any).createCartAndCookie = createCartAndCookie;
935
+ (window as any).createCartAndCookie = requestNewCart;
902
936
  }
903
937
 
904
938
  useEffect(() => {
905
939
  persistTestCheckoutFlag();
906
- if (domainId) actionGetMerchiCart();
940
+ if (domainId) actionGetMerchiCart(!isAutomatedClient());
907
941
  if (domainId && includeTheme) actionFetchTheme();
908
942
  }, [domainId]);
909
943
  return (
@@ -1040,7 +1074,7 @@ const CartProvider = ({
1040
1074
 
1041
1075
  setCartComplete, // creates a token and cart and then reloads the page
1042
1076
  refetchCart, // used to refetch the cart
1043
- createCartAndCookie, // creates a new cart and cookie
1077
+ createCartAndCookie: requestNewCart, // creates a new cart and cookie
1044
1078
 
1045
1079
  loading,
1046
1080
 
@@ -0,0 +1,21 @@
1
+ import { isAutomatedClient } from './automatedClient';
2
+
3
+ describe('automated startup hint', () => {
4
+ it.each([
5
+ 'Mozilla/5.0 (X11; Linux x86_64) HeadlessChrome/153.0.8010.0 Safari/537.36',
6
+ 'Mozilla/5.0 (compatible; Baiduspider-render/2.0)',
7
+ 'Mozilla/5.0 (compatible; bingbot/2.0)',
8
+ 'Mozilla/5.0 (compatible; Googlebot/2.1)',
9
+ 'Mozilla/5.0 (compatible; SEBot-WA/1.0)',
10
+ ])('recognizes an automated visitor: %s', userAgent => {
11
+ expect(isAutomatedClient(userAgent)).toBe(true);
12
+ });
13
+ it.each([
14
+ '',
15
+ 'Mozilla/5.0 Chrome/153.0.0.0 Safari/537.36',
16
+ 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) Version/26.6.1 Mobile/15E148 Safari/604.1',
17
+ 'Mozilla/5.0 (Linux; Android 15) Chrome/153.0.0.0 Mobile Safari/537.36 [FBAN/FB4A]',
18
+ ])('keeps ordinary startup behavior: %s', userAgent => {
19
+ expect(isAutomatedClient(userAgent)).toBe(false);
20
+ });
21
+ });
@@ -0,0 +1,6 @@
1
+ /** A startup optimization only; explicit cart operations remain available. */
2
+ export function isAutomatedClient(
3
+ userAgent = typeof navigator === 'undefined' ? '' : navigator.userAgent,
4
+ ): boolean {
5
+ return /HeadlessChrome|bot|crawler|spider|slurp|SEBot-WA/i.test(userAgent);
6
+ }