@merchi/cart 1.4.63 → 1.4.65
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/esm/CartProvider.js +337 -250
- package/esm/CartProvider.load.test.js +1236 -282
- package/esm/utilities/automatedClient.js +5 -0
- package/esm/utilities/automatedClient.test.js +9 -0
- package/lib/CartProvider.js +337 -250
- package/lib/utilities/automatedClient.d.ts +2 -0
- package/lib/utilities/automatedClient.js +11 -0
- package/lib/utilities/automatedClient.test.d.ts +1 -0
- package/package.json +1 -1
- package/src/CartProvider.load.test.tsx +278 -2
- package/src/CartProvider.tsx +85 -51
- package/src/utilities/automatedClient.test.ts +21 -0
- package/src/utilities/automatedClient.ts +6 -0
|
@@ -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
|
@@ -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
|
|
|
@@ -49,11 +54,29 @@ function Probe() {
|
|
|
49
54
|
return null;
|
|
50
55
|
}
|
|
51
56
|
|
|
57
|
+
const bindingNames = [
|
|
58
|
+
'addCartItem', 'toggleCartOpen', 'getCart', 'getMerchiCartValues',
|
|
59
|
+
'isMerchiCartFetching', 'setCartComplete', 'refetchCart', 'createCartAndCookie',
|
|
60
|
+
];
|
|
61
|
+
|
|
52
62
|
describe('cart load and replacement failures', () => {
|
|
53
63
|
let root: Root;
|
|
54
64
|
let container: HTMLDivElement;
|
|
65
|
+
const userAgentDescriptor = Object.getOwnPropertyDescriptor(navigator, 'userAgent');
|
|
66
|
+
const headlessUserAgent = 'Mozilla/5.0 (X11; Linux x86_64) HeadlessChrome/153.0.8010.0 Safari/537.36';
|
|
67
|
+
function setUserAgent(value: string) {
|
|
68
|
+
Object.defineProperty(navigator, 'userAgent', { configurable: true, value });
|
|
69
|
+
}
|
|
55
70
|
beforeEach(() => {
|
|
71
|
+
for (const name of bindingNames) delete (window as any)[name];
|
|
56
72
|
jest.clearAllMocks();
|
|
73
|
+
mockGet.mockReset();
|
|
74
|
+
mockPost.mockReset();
|
|
75
|
+
mockCreateItem.mockReset();
|
|
76
|
+
mockCreateItem.mockImplementation(function (this: any) {
|
|
77
|
+
return Promise.resolve({ toJson: () => ({ id: 7, cart: { id: this.cart.id } }) });
|
|
78
|
+
});
|
|
79
|
+
(getCartCookie as jest.Mock).mockReset();
|
|
57
80
|
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
|
58
81
|
container = document.createElement('div');
|
|
59
82
|
document.body.appendChild(container);
|
|
@@ -64,6 +87,8 @@ describe('cart load and replacement failures', () => {
|
|
|
64
87
|
afterEach(async () => {
|
|
65
88
|
await act(async () => root.unmount());
|
|
66
89
|
container.remove();
|
|
90
|
+
if (userAgentDescriptor) Object.defineProperty(navigator, 'userAgent', userAgentDescriptor);
|
|
91
|
+
else delete (navigator as any).userAgent;
|
|
67
92
|
});
|
|
68
93
|
async function mount(error: unknown) {
|
|
69
94
|
mockGet.mockRejectedValue(error);
|
|
@@ -84,6 +109,257 @@ describe('cart load and replacement failures', () => {
|
|
|
84
109
|
});
|
|
85
110
|
await act(async () => context.setActiveTabIndex(tabIdClearCart));
|
|
86
111
|
}
|
|
112
|
+
it('does not expose cart operations until a suspended provider commits', async () => {
|
|
113
|
+
setUserAgent(headlessUserAgent);
|
|
114
|
+
(getCartCookie as jest.Mock).mockResolvedValue(undefined);
|
|
115
|
+
let ready = false;
|
|
116
|
+
let release!: () => void;
|
|
117
|
+
const gate = new Promise<void>(resolve => { release = resolve; });
|
|
118
|
+
function Suspender() { if (!ready) throw gate; return null; }
|
|
119
|
+
await act(async () => root.render(
|
|
120
|
+
<React.Suspense fallback={<span>Loading</span>}>
|
|
121
|
+
<CartProvider domainId={5} createCartAndCookie={() => {}}>
|
|
122
|
+
<Suspender /><Probe />
|
|
123
|
+
</CartProvider>
|
|
124
|
+
</React.Suspense>,
|
|
125
|
+
));
|
|
126
|
+
for (const name of bindingNames) expect((window as any)[name]).toBeUndefined();
|
|
127
|
+
expect(mockPost).not.toHaveBeenCalled();
|
|
128
|
+
await act(async () => { ready = true; release(); });
|
|
129
|
+
for (const name of bindingNames) expect((window as any)[name]).toBeInstanceOf(Function);
|
|
130
|
+
await act(async () => { await (window as any).getCart(); });
|
|
131
|
+
expect(mockPost).toHaveBeenCalledTimes(1);
|
|
132
|
+
expect((await (window as any).getMerchiCartValues()).cart.id).toBe(99);
|
|
133
|
+
expect(context.cart.id).toBe(99);
|
|
134
|
+
});
|
|
135
|
+
it('preserves committed operations when another provider suspends and is abandoned', async () => {
|
|
136
|
+
setUserAgent(headlessUserAgent);
|
|
137
|
+
(getCartCookie as jest.Mock).mockResolvedValue(undefined);
|
|
138
|
+
await act(async () => root.render(
|
|
139
|
+
<CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
|
|
140
|
+
));
|
|
141
|
+
const committed = bindingNames.map(name => (window as any)[name]);
|
|
142
|
+
const otherRoot = createRoot(document.createElement('div'));
|
|
143
|
+
const gate = new Promise<void>(() => {});
|
|
144
|
+
function Suspender(): never { throw gate; }
|
|
145
|
+
try {
|
|
146
|
+
await act(async () => otherRoot.render(
|
|
147
|
+
<React.Suspense fallback={null}>
|
|
148
|
+
<CartProvider domainId={6} createCartAndCookie={() => {}}><Suspender /></CartProvider>
|
|
149
|
+
</React.Suspense>,
|
|
150
|
+
));
|
|
151
|
+
bindingNames.forEach((name, index) => expect((window as any)[name]).toBe(committed[index]));
|
|
152
|
+
await act(async () => { await (window as any).getCart(); });
|
|
153
|
+
expect(context.cart.id).toBe(99);
|
|
154
|
+
expect(mockPost).toHaveBeenCalledTimes(1);
|
|
155
|
+
} finally { await act(async () => otherRoot.unmount()); }
|
|
156
|
+
expect((await (window as any).getMerchiCartValues()).cart.id).toBe(99);
|
|
157
|
+
});
|
|
158
|
+
it('removes its own global operations on unmount', async () => {
|
|
159
|
+
await mountSavedCart();
|
|
160
|
+
await act(async () => root.render(null));
|
|
161
|
+
for (const name of bindingNames) expect((window as any)[name]).toBeUndefined();
|
|
162
|
+
});
|
|
163
|
+
it('keeps the committed domain bindings during a suspended transition', async () => {
|
|
164
|
+
setUserAgent(headlessUserAgent);
|
|
165
|
+
mockGet.mockResolvedValue({ toJson: () => ({ id: 42, cartItems: [] }) });
|
|
166
|
+
const gate = new Promise<void>(() => {});
|
|
167
|
+
function Suspender(): never { throw gate; }
|
|
168
|
+
const tree = (domainId: number, suspend: boolean) => (
|
|
169
|
+
<React.Suspense fallback={null}>
|
|
170
|
+
<CartProvider domainId={domainId} createCartAndCookie={() => {}}>
|
|
171
|
+
{suspend ? <Suspender /> : <Probe />}
|
|
172
|
+
</CartProvider>
|
|
173
|
+
</React.Suspense>
|
|
174
|
+
);
|
|
175
|
+
await act(async () => root.render(tree(5, false)));
|
|
176
|
+
const committed = bindingNames.map(name => (window as any)[name]);
|
|
177
|
+
await act(async () => { React.startTransition(() => root.render(tree(6, true))); });
|
|
178
|
+
bindingNames.forEach((name, index) => expect((window as any)[name]).toBe(committed[index]));
|
|
179
|
+
expect((await (window as any).getMerchiCartValues()).cart.id).toBe(42);
|
|
180
|
+
expect(mockGet).toHaveBeenCalledTimes(1);
|
|
181
|
+
expect(mockPost).not.toHaveBeenCalled();
|
|
182
|
+
});
|
|
183
|
+
it('does not remove global operations owned by another committed provider', async () => {
|
|
184
|
+
await mountSavedCart();
|
|
185
|
+
const otherRoot = createRoot(document.createElement('div'));
|
|
186
|
+
try {
|
|
187
|
+
await act(async () => otherRoot.render(
|
|
188
|
+
<CartProvider domainId={6} createCartAndCookie={() => {}}><Probe /></CartProvider>,
|
|
189
|
+
));
|
|
190
|
+
const otherBindings = bindingNames.map(name => (window as any)[name]);
|
|
191
|
+
await act(async () => root.render(null));
|
|
192
|
+
bindingNames.forEach((name, index) => expect((window as any)[name]).toBe(otherBindings[index]));
|
|
193
|
+
expect((await (window as any).getMerchiCartValues()).cart.id).toBe(42);
|
|
194
|
+
} finally { await act(async () => otherRoot.unmount()); }
|
|
195
|
+
for (const name of bindingNames) expect((window as any)[name]).toBeUndefined();
|
|
196
|
+
});
|
|
197
|
+
it('keeps globals usable after StrictMode setup and cleanup replay', async () => {
|
|
198
|
+
setUserAgent(headlessUserAgent);
|
|
199
|
+
(getCartCookie as jest.Mock).mockResolvedValue(undefined);
|
|
200
|
+
await act(async () => root.render(
|
|
201
|
+
<React.StrictMode>
|
|
202
|
+
<CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>
|
|
203
|
+
</React.StrictMode>,
|
|
204
|
+
));
|
|
205
|
+
await act(async () => { await (window as any).getCart(); });
|
|
206
|
+
expect(mockPost).toHaveBeenCalledTimes(1);
|
|
207
|
+
expect((await (window as any).getMerchiCartValues()).cart.id).toBe(99);
|
|
208
|
+
});
|
|
209
|
+
it.each([
|
|
210
|
+
'Mozilla/5.0 (X11; Linux x86_64) HeadlessChrome/153.0.8010.0 Safari/537.36',
|
|
211
|
+
'Mozilla/5.0 (compatible; Baiduspider-render/2.0)',
|
|
212
|
+
])('does not create an unused cart on automated startup: %s', async userAgent => {
|
|
213
|
+
setUserAgent(userAgent);
|
|
214
|
+
(getCartCookie as jest.Mock).mockResolvedValue(undefined);
|
|
215
|
+
await act(async () => root.render(
|
|
216
|
+
<CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
|
|
217
|
+
));
|
|
218
|
+
expect(mockGet).not.toHaveBeenCalled();
|
|
219
|
+
expect(mockPost).not.toHaveBeenCalled();
|
|
220
|
+
expect(context.fetchingCart).toBe(false);
|
|
221
|
+
expect(reportCartFailure).not.toHaveBeenCalled();
|
|
222
|
+
});
|
|
223
|
+
it('allows explicit cart opening and concurrent callers in an automated browser', async () => {
|
|
224
|
+
setUserAgent(headlessUserAgent);
|
|
225
|
+
(getCartCookie as jest.Mock).mockResolvedValue(undefined);
|
|
226
|
+
await act(async () => root.render(
|
|
227
|
+
<CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
|
|
228
|
+
));
|
|
229
|
+
expect(mockPost).not.toHaveBeenCalled();
|
|
230
|
+
await act(async () => {
|
|
231
|
+
context.toggleCartModal();
|
|
232
|
+
await Promise.all([(window as any).getCart(), (window as any).refetchCart()]);
|
|
233
|
+
});
|
|
234
|
+
expect(mockPost).toHaveBeenCalledTimes(1);
|
|
235
|
+
expect(context.cart.id).toBe(99);
|
|
236
|
+
});
|
|
237
|
+
it('creates once when explicit interaction joins a pending passive cookie lookup', async () => {
|
|
238
|
+
setUserAgent(headlessUserAgent);
|
|
239
|
+
let finishCookie!: (value: undefined) => void;
|
|
240
|
+
(getCartCookie as jest.Mock).mockImplementationOnce(
|
|
241
|
+
() => new Promise(resolve => { finishCookie = resolve; }),
|
|
242
|
+
).mockResolvedValue(undefined);
|
|
243
|
+
await act(async () => root.render(
|
|
244
|
+
<CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
|
|
245
|
+
));
|
|
246
|
+
let first!: Promise<void>, second!: Promise<void>;
|
|
247
|
+
await act(async () => {
|
|
248
|
+
first = (window as any).getCart();
|
|
249
|
+
second = (window as any).getCart();
|
|
250
|
+
context.toggleCartModal();
|
|
251
|
+
});
|
|
252
|
+
expect(mockPost).not.toHaveBeenCalled();
|
|
253
|
+
await act(async () => { finishCookie(undefined); await Promise.all([first, second]); });
|
|
254
|
+
expect(mockPost).toHaveBeenCalledTimes(1);
|
|
255
|
+
expect(context.cart.id).toBe(99);
|
|
256
|
+
});
|
|
257
|
+
it('restores saved carts for automated clients without duplicating an active read', async () => {
|
|
258
|
+
setUserAgent(headlessUserAgent);
|
|
259
|
+
let finish!: (value: unknown) => void;
|
|
260
|
+
mockGet.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
|
|
261
|
+
await act(async () => root.render(
|
|
262
|
+
<CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
|
|
263
|
+
));
|
|
264
|
+
let read!: Promise<void>;
|
|
265
|
+
await act(async () => { read = (window as any).getCart(); context.toggleCartModal(); });
|
|
266
|
+
expect(mockGet).toHaveBeenCalledTimes(1);
|
|
267
|
+
await act(async () => {
|
|
268
|
+
finish({ toJson: () => ({ id: 42, isTest: false, cartItems: [{ id: 7 }] }) });
|
|
269
|
+
await read;
|
|
270
|
+
});
|
|
271
|
+
expect(mockPost).not.toHaveBeenCalled();
|
|
272
|
+
expect(context.cart.cartItems).toHaveLength(1);
|
|
273
|
+
});
|
|
274
|
+
it('keeps explicit retry available after an automated client creation fails', async () => {
|
|
275
|
+
setUserAgent(headlessUserAgent);
|
|
276
|
+
(getCartCookie as jest.Mock).mockResolvedValue(undefined);
|
|
277
|
+
mockPost.mockRejectedValueOnce(new TypeError('Failed to fetch'));
|
|
278
|
+
await act(async () => root.render(
|
|
279
|
+
<CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
|
|
280
|
+
));
|
|
281
|
+
expect(mockPost).not.toHaveBeenCalled();
|
|
282
|
+
await act(async () => { await (window as any).getCart(); });
|
|
283
|
+
expect(mockPost).toHaveBeenCalledTimes(1);
|
|
284
|
+
expect(context.fetchingCart).toBe(false);
|
|
285
|
+
await act(async () => { await (window as any).getCart(); });
|
|
286
|
+
expect(mockPost).toHaveBeenCalledTimes(2);
|
|
287
|
+
expect(context.cart.id).toBe(99);
|
|
288
|
+
});
|
|
289
|
+
it('initializes a cart for a direct item operation without a storefront readiness helper', async () => {
|
|
290
|
+
setUserAgent(headlessUserAgent);
|
|
291
|
+
(getCartCookie as jest.Mock).mockResolvedValue(undefined);
|
|
292
|
+
await act(async () => root.render(
|
|
293
|
+
<CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
|
|
294
|
+
));
|
|
295
|
+
const onSuccess = jest.fn(), onError = jest.fn();
|
|
296
|
+
await act(async () => {
|
|
297
|
+
await (window as any).addCartItem({ product: { id: 44 }, quantity: 100 }, onSuccess, onError);
|
|
298
|
+
});
|
|
299
|
+
expect(mockPost).toHaveBeenCalledTimes(1);
|
|
300
|
+
expect(mockCreateItem).toHaveBeenCalledTimes(1);
|
|
301
|
+
expect(onSuccess).toHaveBeenCalledWith({ id: 7, cart: { id: 99 } });
|
|
302
|
+
expect(onError).not.toHaveBeenCalled();
|
|
303
|
+
});
|
|
304
|
+
it('rejects a direct item operation when initialization fails without posting an item', async () => {
|
|
305
|
+
setUserAgent(headlessUserAgent);
|
|
306
|
+
(getCartCookie as jest.Mock).mockResolvedValue(undefined);
|
|
307
|
+
mockPost.mockRejectedValueOnce(new TypeError('Failed to fetch'));
|
|
308
|
+
await act(async () => root.render(
|
|
309
|
+
<CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
|
|
310
|
+
));
|
|
311
|
+
const onSuccess = jest.fn(), onError = jest.fn();
|
|
312
|
+
await act(async () => {
|
|
313
|
+
await (window as any).addCartItem({ product: { id: 44 }, quantity: 100 }, onSuccess, onError);
|
|
314
|
+
});
|
|
315
|
+
expect(mockPost).toHaveBeenCalledTimes(1);
|
|
316
|
+
expect(mockCreateItem).not.toHaveBeenCalled();
|
|
317
|
+
expect(onSuccess).not.toHaveBeenCalled();
|
|
318
|
+
expect(onError).toHaveBeenCalledTimes(1);
|
|
319
|
+
expect(context.fetchingCart).toBe(false);
|
|
320
|
+
});
|
|
321
|
+
it('waits for ordinary startup before concurrent direct item operations', async () => {
|
|
322
|
+
(getCartCookie as jest.Mock).mockResolvedValue(undefined);
|
|
323
|
+
let finish!: (value: unknown) => void;
|
|
324
|
+
mockPost.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
|
|
325
|
+
await act(async () => root.render(
|
|
326
|
+
<CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
|
|
327
|
+
));
|
|
328
|
+
const onSuccess = jest.fn(), onError = jest.fn();
|
|
329
|
+
let first!: Promise<void>, second!: Promise<void>;
|
|
330
|
+
await act(async () => {
|
|
331
|
+
const job = { product: { id: 44 }, quantity: 100 };
|
|
332
|
+
first = (window as any).addCartItem(job, onSuccess, onError);
|
|
333
|
+
second = (window as any).addCartItem(job, onSuccess, onError);
|
|
334
|
+
});
|
|
335
|
+
expect(mockCreateItem).not.toHaveBeenCalled();
|
|
336
|
+
await act(async () => {
|
|
337
|
+
finish({ cart: { id: 99, token: 'new-token' } });
|
|
338
|
+
await Promise.all([first, second]);
|
|
339
|
+
});
|
|
340
|
+
expect(mockPost).toHaveBeenCalledTimes(1);
|
|
341
|
+
expect(onSuccess.mock.calls.map(call => call[0].cart.id)).toEqual([99, 99]);
|
|
342
|
+
expect(onError).not.toHaveBeenCalled();
|
|
343
|
+
});
|
|
344
|
+
it('does not automatically repeat a failed item write after explicit initialization', async () => {
|
|
345
|
+
setUserAgent(headlessUserAgent);
|
|
346
|
+
(getCartCookie as jest.Mock).mockResolvedValue(undefined);
|
|
347
|
+
mockCreateItem.mockRejectedValueOnce(new TypeError('Failed to fetch'));
|
|
348
|
+
await act(async () => root.render(
|
|
349
|
+
<CartProvider domainId={5} createCartAndCookie={() => {}}><Probe /></CartProvider>,
|
|
350
|
+
));
|
|
351
|
+
const onSuccess = jest.fn(), onError = jest.fn();
|
|
352
|
+
const job = { product: { id: 44 }, quantity: 100 };
|
|
353
|
+
await act(async () => { await (window as any).addCartItem(job, onSuccess, onError); });
|
|
354
|
+
expect(mockPost).toHaveBeenCalledTimes(1);
|
|
355
|
+
expect(mockCreateItem).toHaveBeenCalledTimes(1);
|
|
356
|
+
expect(onSuccess).not.toHaveBeenCalled();
|
|
357
|
+
expect(onError).toHaveBeenCalledTimes(1);
|
|
358
|
+
await act(async () => { await (window as any).addCartItem(job, onSuccess, onError); });
|
|
359
|
+
expect(mockPost).toHaveBeenCalledTimes(1);
|
|
360
|
+
expect(mockCreateItem).toHaveBeenCalledTimes(2);
|
|
361
|
+
expect(onSuccess).toHaveBeenCalledWith({ id: 7, cart: { id: 99 } });
|
|
362
|
+
});
|
|
87
363
|
it('shares cold initialization with opening the modal and concurrent getCart callers', async () => {
|
|
88
364
|
(getCartCookie as jest.Mock).mockResolvedValue(undefined);
|
|
89
365
|
let finish!: (value: unknown) => void;
|
package/src/CartProvider.tsx
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as React from 'react';
|
|
2
|
-
import { createContext, ReactNode, useContext, useEffect, useRef, useState } from 'react';
|
|
2
|
+
import { createContext, ReactNode, useContext, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
|
3
3
|
import { faCheckCircle, faExclamationTriangle, faInfoCircle } from '@fortawesome/free-solid-svg-icons';
|
|
4
4
|
import { Alert, Tab } from './types';
|
|
5
5
|
import {
|
|
@@ -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,
|
|
@@ -30,6 +31,8 @@ import {
|
|
|
30
31
|
jobSourceFieldsForApi,
|
|
31
32
|
} from './utilities/job_source';
|
|
32
33
|
|
|
34
|
+
const useCartBindingsEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;
|
|
35
|
+
|
|
33
36
|
export interface PropsCart {
|
|
34
37
|
cart: any;
|
|
35
38
|
cartClient?: any;
|
|
@@ -596,7 +599,9 @@ const CartProvider = ({
|
|
|
596
599
|
const [fetchingCart, setFetchingCart] = useState(false);
|
|
597
600
|
const [cartSettingsInvalid, setCartSettingsInvalid] = useState(false);
|
|
598
601
|
const appliedHandoffCart = useRef<string | null>(null);
|
|
599
|
-
const cartInitializations = useRef(new Map<
|
|
602
|
+
const cartInitializations = useRef(new Map<
|
|
603
|
+
number | undefined, Promise<{ skippedCreation: boolean; cart?: any }>
|
|
604
|
+
>());
|
|
600
605
|
|
|
601
606
|
async function attachSavedClientIfNeeded(cartJson: any) {
|
|
602
607
|
if (cartJson?.client?.id) {
|
|
@@ -650,12 +655,18 @@ const CartProvider = ({
|
|
|
650
655
|
cartJson = await attachSavedClientIfNeeded(cartJson);
|
|
651
656
|
setCart({...cartJson});
|
|
652
657
|
if (callback) callback();
|
|
658
|
+
return cartJson;
|
|
653
659
|
} catch (e: any) {
|
|
654
660
|
reportCartFailure(e, CART_FAILURE_SOURCES.create);
|
|
655
661
|
alertError(e?.errorMessage || e?.message || 'Unable to fetch cart.');
|
|
656
662
|
} finally {
|
|
657
663
|
setFetchingCart(false);
|
|
658
664
|
}
|
|
665
|
+
return undefined;
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
async function requestNewCart(callback?: () => void) {
|
|
669
|
+
await createCartAndCookie(callback);
|
|
659
670
|
}
|
|
660
671
|
|
|
661
672
|
async function getCart(cartIdAndToken: Array<string>) {
|
|
@@ -669,8 +680,7 @@ const CartProvider = ({
|
|
|
669
680
|
let cartJson = await cart.toJson();
|
|
670
681
|
const isTest = readTestCheckoutFlag();
|
|
671
682
|
if (Boolean(cartJson.isTest) !== isTest) {
|
|
672
|
-
await createCartAndCookie();
|
|
673
|
-
return;
|
|
683
|
+
return await createCartAndCookie();
|
|
674
684
|
}
|
|
675
685
|
const jobSource = jobSourceFieldsForApi(captureAndReadJobSource());
|
|
676
686
|
if (cartNeedsSourceUpdate(cartJson, jobSource)) {
|
|
@@ -688,6 +698,7 @@ const CartProvider = ({
|
|
|
688
698
|
if (stripeIsValidAndActive(cartJson) || isTest) {
|
|
689
699
|
cartJson = await attachSavedClientIfNeeded(cartJson);
|
|
690
700
|
setCart({...cartJson});
|
|
701
|
+
return cartJson;
|
|
691
702
|
} else {
|
|
692
703
|
console.error(
|
|
693
704
|
`MErhci cart error: Stripe payment ` +
|
|
@@ -699,7 +710,7 @@ const CartProvider = ({
|
|
|
699
710
|
}
|
|
700
711
|
} catch(e: any){
|
|
701
712
|
if (canReplaceMissingCart(e)) {
|
|
702
|
-
await createCartAndCookie();
|
|
713
|
+
return await createCartAndCookie();
|
|
703
714
|
} else {
|
|
704
715
|
// A network/server/auth failure does not mean the saved cart is gone.
|
|
705
716
|
// Preserve its cookie and contents so the shopper can retry the read.
|
|
@@ -709,6 +720,7 @@ const CartProvider = ({
|
|
|
709
720
|
} finally {
|
|
710
721
|
setFetchingCart(false);
|
|
711
722
|
}
|
|
723
|
+
return undefined;
|
|
712
724
|
}
|
|
713
725
|
|
|
714
726
|
// A checkout link can name the cart. Remember it once, then keep using the cookie
|
|
@@ -723,24 +735,32 @@ const CartProvider = ({
|
|
|
723
735
|
await setCartCookie(Number(domainId), { id: handoff[0], token: handoff[1] });
|
|
724
736
|
}
|
|
725
737
|
|
|
726
|
-
function actionGetMerchiCart() {
|
|
727
|
-
|
|
728
|
-
if (active) return active;
|
|
738
|
+
function actionGetMerchiCart(allowCreation = true): Promise<any> {
|
|
739
|
+
let active = cartInitializations.current.get(domainId);
|
|
729
740
|
// Mount, modal opening and explicit callers may run before React commits
|
|
730
741
|
// fetchingCart. Share the whole cookie lookup/read-or-create operation.
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
742
|
+
if (!active) {
|
|
743
|
+
active = Promise.resolve().then(async () => {
|
|
744
|
+
await adoptHandoffCart();
|
|
745
|
+
const cartIdAndToken = await getCartCookie((domainId as number));
|
|
746
|
+
if (cartIdAndToken) {
|
|
747
|
+
return { skippedCreation: false, cart: await getCart(cartIdAndToken) };
|
|
748
|
+
} else if (allowCreation) {
|
|
749
|
+
return { skippedCreation: false, cart: await createCartAndCookie() };
|
|
750
|
+
}
|
|
751
|
+
return { skippedCreation: true };
|
|
752
|
+
}).finally(() => {
|
|
753
|
+
cartInitializations.current.delete(domainId);
|
|
754
|
+
});
|
|
755
|
+
cartInitializations.current.set(domainId, active);
|
|
756
|
+
}
|
|
757
|
+
return active.then(result => {
|
|
758
|
+
// An explicit caller can join passive startup before its cookie lookup
|
|
759
|
+
// finishes. Once that no-op completes, create through the same shared
|
|
760
|
+
// initialization path so concurrent explicit callers still issue one POST.
|
|
761
|
+
if (result.skippedCreation && allowCreation) return actionGetMerchiCart();
|
|
762
|
+
return result.cart;
|
|
741
763
|
});
|
|
742
|
-
cartInitializations.current.set(domainId, initialization);
|
|
743
|
-
return initialization;
|
|
744
764
|
}
|
|
745
765
|
|
|
746
766
|
async function clearCart(callback?: () => void) {
|
|
@@ -855,25 +875,30 @@ const CartProvider = ({
|
|
|
855
875
|
onError: (e: any) => void,
|
|
856
876
|
) {
|
|
857
877
|
setFetchingCart(true);
|
|
858
|
-
const jobEnt = makeJob(jobJson, true);
|
|
859
|
-
const cartToken = await getCartCookieToken((domainId as number));
|
|
860
|
-
const cartEnt = makeCart(cart, false, cartToken);
|
|
861
|
-
const cartItemEnt = makeCartItem({}, true);
|
|
862
|
-
const cartItemProduct = makeProduct({ id: (jobEnt.product as any).id });
|
|
863
|
-
|
|
864
|
-
cartItemEnt.cart = cartEnt;
|
|
865
|
-
cartItemEnt.quantity = jobEnt.quantity;
|
|
866
|
-
cartItemEnt.product = cartItemProduct;
|
|
867
|
-
cartItemEnt.variations = jobEnt.variations;
|
|
868
|
-
cartItemEnt.variationsGroups = jobEnt.variationsGroups;
|
|
869
|
-
cartItemEnt.taxType = jobEnt.taxType;
|
|
870
|
-
cartItemEnt.ownDrafts = jobEnt.ownDrafts;
|
|
871
|
-
cartItemEnt.clientFiles = jobEnt.clientFiles;
|
|
872
|
-
cartItemEnt.tags = jobEnt.tags;
|
|
873
|
-
if (typeof jobJson.designInputNotes === 'string' && jobJson.designInputNotes) {
|
|
874
|
-
cartItemEnt.notes = jobJson.designInputNotes;
|
|
875
|
-
}
|
|
876
878
|
try {
|
|
879
|
+
const jobEnt = makeJob(jobJson, true);
|
|
880
|
+
const cartItemProduct = makeProduct({ id: (jobEnt.product as any).id });
|
|
881
|
+
// Legacy clients can call addCartItem directly, without first opening
|
|
882
|
+
// the cart or waiting for React to commit the initialized cart state.
|
|
883
|
+
const readyCart = cart?.id ? cart : await actionGetMerchiCart();
|
|
884
|
+
if (!readyCart?.id) throw new Error('Unable to initialize cart. Please try again.');
|
|
885
|
+
setFetchingCart(true);
|
|
886
|
+
const cartToken = await getCartCookieToken((domainId as number));
|
|
887
|
+
const cartEnt = makeCart(readyCart, false, cartToken);
|
|
888
|
+
const cartItemEnt = makeCartItem({}, true);
|
|
889
|
+
|
|
890
|
+
cartItemEnt.cart = cartEnt;
|
|
891
|
+
cartItemEnt.quantity = jobEnt.quantity;
|
|
892
|
+
cartItemEnt.product = cartItemProduct;
|
|
893
|
+
cartItemEnt.variations = jobEnt.variations;
|
|
894
|
+
cartItemEnt.variationsGroups = jobEnt.variationsGroups;
|
|
895
|
+
cartItemEnt.taxType = jobEnt.taxType;
|
|
896
|
+
cartItemEnt.ownDrafts = jobEnt.ownDrafts;
|
|
897
|
+
cartItemEnt.clientFiles = jobEnt.clientFiles;
|
|
898
|
+
cartItemEnt.tags = jobEnt.tags;
|
|
899
|
+
if (typeof jobJson.designInputNotes === 'string' && jobJson.designInputNotes) {
|
|
900
|
+
cartItemEnt.notes = jobJson.designInputNotes;
|
|
901
|
+
}
|
|
877
902
|
const item = await cartItemEnt.create();
|
|
878
903
|
const itemJson = await item.toJson();
|
|
879
904
|
onSuccess(itemJson);
|
|
@@ -900,21 +925,30 @@ const CartProvider = ({
|
|
|
900
925
|
}
|
|
901
926
|
};
|
|
902
927
|
|
|
903
|
-
//
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
928
|
+
// Publish only committed providers. Suspense can discard render-time state,
|
|
929
|
+
// so exposing these closures during render can strand a successful cart POST.
|
|
930
|
+
useCartBindingsEffect(() => {
|
|
931
|
+
const bindings = {
|
|
932
|
+
addCartItem,
|
|
933
|
+
toggleCartOpen: toggleCartModal,
|
|
934
|
+
getCart: async () => { await actionGetMerchiCart(); },
|
|
935
|
+
getMerchiCartValues,
|
|
936
|
+
isMerchiCartFetching,
|
|
937
|
+
setCartComplete,
|
|
938
|
+
refetchCart,
|
|
939
|
+
createCartAndCookie: requestNewCart,
|
|
940
|
+
};
|
|
941
|
+
Object.assign(window, bindings);
|
|
942
|
+
return () => {
|
|
943
|
+
for (const [name, binding] of Object.entries(bindings)) {
|
|
944
|
+
if ((window as any)[name] === binding) delete (window as any)[name];
|
|
945
|
+
}
|
|
946
|
+
};
|
|
947
|
+
});
|
|
914
948
|
|
|
915
949
|
useEffect(() => {
|
|
916
950
|
persistTestCheckoutFlag();
|
|
917
|
-
if (domainId) actionGetMerchiCart();
|
|
951
|
+
if (domainId) actionGetMerchiCart(!isAutomatedClient());
|
|
918
952
|
if (domainId && includeTheme) actionFetchTheme();
|
|
919
953
|
}, [domainId]);
|
|
920
954
|
return (
|
|
@@ -1051,7 +1085,7 @@ const CartProvider = ({
|
|
|
1051
1085
|
|
|
1052
1086
|
setCartComplete, // creates a token and cart and then reloads the page
|
|
1053
1087
|
refetchCart, // used to refetch the cart
|
|
1054
|
-
createCartAndCookie, // creates a new cart and cookie
|
|
1088
|
+
createCartAndCookie: requestNewCart, // creates a new cart and cookie
|
|
1055
1089
|
|
|
1056
1090
|
loading,
|
|
1057
1091
|
|
|
@@ -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
|
+
}
|