@eldrajs/theme-cli 0.2.5 → 0.2.6

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.
Files changed (90) hide show
  1. package/package.json +3 -3
  2. package/template/.eldra/block-types.d.ts +1 -1
  3. package/template/.eldra/manifest.json +30 -2
  4. package/template/.eldra/previews.json +35 -35
  5. package/template/app/app.vue +15 -0
  6. package/template/app/composables/useStorefront.ts +7 -2
  7. package/template/app/plugins/eldra-storefront.ts +9 -0
  8. package/template/app/storefront/analytics.ts +15 -7
  9. package/template/app/storefront/cart.ts +228 -51
  10. package/template/app/storefront/commerce.ts +8 -2
  11. package/template/app/storefront/currency.ts +205 -0
  12. package/template/app/storefront/demo.ts +10 -2
  13. package/template/app/storefront/feedback.ts +2 -0
  14. package/template/app/storefront/gateway.ts +153 -35
  15. package/template/app/storefront/money.ts +6 -18
  16. package/template/app/storefront/structuredData.ts +16 -5
  17. package/template/app/storefront/toProductCard.ts +14 -14
  18. package/template/app/storefront/types.ts +13 -0
  19. package/template/app/storefront/volatile.ts +4 -0
  20. package/template/app/utils/seoInput.ts +4 -3
  21. package/template/blocks/announcement-bar/preview.png +0 -0
  22. package/template/blocks/article/preview.png +0 -0
  23. package/template/blocks/article-list/preview.png +0 -0
  24. package/template/blocks/breadcrumbs/preview.png +0 -0
  25. package/template/blocks/cart/Block.vue +41 -22
  26. package/template/blocks/cart/__tests__/Block.spec.ts +2 -3
  27. package/template/blocks/cart/__tests__/loadFailed.spec.ts +135 -0
  28. package/template/blocks/cart/__tests__/notSold.spec.ts +109 -0
  29. package/template/blocks/cart/parts/CartLines.vue +14 -2
  30. package/template/blocks/cart/parts/CheckoutButton.vue +45 -0
  31. package/template/blocks/cart/parts/LoadFailed.vue +37 -0
  32. package/template/blocks/cart/parts/NotSoldNotice.vue +69 -0
  33. package/template/blocks/cart/parts/Summary.vue +9 -21
  34. package/template/blocks/cart/parts/notSold.ts +19 -0
  35. package/template/blocks/cart/preview.png +0 -0
  36. package/template/blocks/collection-grid/Block.vue +15 -2
  37. package/template/blocks/collection-grid/__tests__/Block.spec.ts +14 -0
  38. package/template/blocks/collection-grid/preview.png +0 -0
  39. package/template/blocks/collection-header/preview.png +0 -0
  40. package/template/blocks/contact/preview.png +0 -0
  41. package/template/blocks/cta/preview.png +0 -0
  42. package/template/blocks/faq/preview.png +0 -0
  43. package/template/blocks/feature-grid/preview.png +0 -0
  44. package/template/blocks/footer/Block.vue +20 -45
  45. package/template/blocks/footer/preview.png +0 -0
  46. package/template/blocks/form/preview.png +0 -0
  47. package/template/blocks/gallery/preview.png +0 -0
  48. package/template/blocks/hero/preview.png +0 -0
  49. package/template/blocks/image/preview.png +0 -0
  50. package/template/blocks/logo-cloud/preview.png +0 -0
  51. package/template/blocks/navigation/Block.vue +39 -3
  52. package/template/blocks/navigation/preview.png +0 -0
  53. package/template/blocks/newsletter/preview.png +0 -0
  54. package/template/blocks/order-status/Block.vue +15 -6
  55. package/template/blocks/order-status/preview.png +0 -0
  56. package/template/blocks/pricing-table/preview.png +0 -0
  57. package/template/blocks/product-carousel/Block.vue +5 -2
  58. package/template/blocks/product-carousel/preview.png +0 -0
  59. package/template/blocks/product-detail/Block.vue +46 -10
  60. package/template/blocks/product-detail/__tests__/Block.spec.ts +78 -1
  61. package/template/blocks/product-detail/preview.png +0 -0
  62. package/template/blocks/quote/preview.png +0 -0
  63. package/template/blocks/rich-text/preview.png +0 -0
  64. package/template/blocks/search/Block.vue +8 -2
  65. package/template/blocks/search/TypeSection.vue +8 -2
  66. package/template/blocks/search/preview.png +0 -0
  67. package/template/blocks/search/results.ts +5 -2
  68. package/template/blocks/split-content/preview.png +0 -0
  69. package/template/blocks/stats/preview.png +0 -0
  70. package/template/blocks/tabs/preview.png +0 -0
  71. package/template/blocks/team/preview.png +0 -0
  72. package/template/blocks/testimonials/preview.png +0 -0
  73. package/template/blocks/timeline/preview.png +0 -0
  74. package/template/blocks/trust-strip/preview.png +0 -0
  75. package/template/blocks/video-embed/preview.png +0 -0
  76. package/template/blocks/wishlist/Block.vue +5 -1
  77. package/template/blocks/wishlist/preview.png +0 -0
  78. package/template/i18n/en-US.json +19 -3
  79. package/template/i18n/is-IS.json +19 -3
  80. package/template/test/currencyPicker.spec.ts +66 -0
  81. package/template/test/seoInput.spec.ts +22 -0
  82. package/template/test/storefront/analytics.spec.ts +15 -0
  83. package/template/test/storefront/cart.spec.ts +4 -4
  84. package/template/test/storefront/currency.spec.ts +549 -0
  85. package/template/test/storefront/currencyStore.spec.ts +845 -0
  86. package/template/test/storefront/gateway.spec.ts +22 -0
  87. package/template/test/storefront/money.spec.ts +2 -8
  88. package/template/test/storefront/structuredData.spec.ts +45 -0
  89. package/template/test/storefront/toProductCard.spec.ts +1 -1
  90. package/template/test/storefront/volatile.spec.ts +11 -0
@@ -0,0 +1,549 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import { nextTick, ref } from 'vue';
3
+ import type { EldraClient } from '@eldrajs/sdk';
4
+ import { createGatewayStorefront } from '../../app/storefront/gateway';
5
+ import { EldraHttpError } from '@eldrajs/sdk';
6
+ import { fetchVisitorCountry } from '../../app/storefront/currency';
7
+
8
+ const CURRENCY_STORAGE_KEY = 'eldra.currency';
9
+
10
+ function notSold(): EldraHttpError {
11
+ return new EldraHttpError(new Response('{}', { status: 400, statusText: 'Bad Request' }), {
12
+ errorId: 'CART_CURRENCY_NOT_SOLD',
13
+ });
14
+ }
15
+ import type { StorefrontCommerce, StorefrontRoute } from '../../app/storefront/types';
16
+
17
+ const MULTI: StorefrontCommerce = {
18
+ currency: 'ISK',
19
+ taxInclusivePricing: true,
20
+ defaultTaxRate: 0.24,
21
+ currencies: ['ISK', 'EUR', 'USD'],
22
+ };
23
+ const ISK_ONLY: StorefrontCommerce = {
24
+ currency: 'ISK',
25
+ taxInclusivePricing: true,
26
+ defaultTaxRate: 0.24,
27
+ };
28
+
29
+ function fakeRoute(): StorefrontRoute {
30
+ return {
31
+ productHandle: null,
32
+ collectionHandle: null,
33
+ categorySlug: null,
34
+ categoryPath: null,
35
+ orderToken: null,
36
+ query: null,
37
+ page: 1,
38
+ sort: null,
39
+ columns: null,
40
+ filters: {},
41
+ setQuery: () => {},
42
+ };
43
+ }
44
+
45
+ function installStorage(initial: Record<string, string> = {}): Map<string, string> {
46
+ const data = new Map(Object.entries(initial));
47
+ (globalThis as { localStorage?: Storage }).localStorage = {
48
+ getItem: (key: string) => data.get(key) ?? null,
49
+ setItem: (key: string, value: string) => void data.set(key, value),
50
+ removeItem: (key: string) => void data.delete(key),
51
+ clear: () => data.clear(),
52
+ key: () => null,
53
+ get length() {
54
+ return data.size;
55
+ },
56
+ } as Storage;
57
+ return data;
58
+ }
59
+
60
+ afterEach(() => {
61
+ delete (globalThis as { localStorage?: Storage }).localStorage;
62
+ });
63
+
64
+ const PRODUCT = {
65
+ id: 'p1',
66
+ slug: 'mug',
67
+ title: 'Mug',
68
+ status: 'ACTIVE',
69
+ options: [],
70
+ categoryIds: [],
71
+ mediaLinks: [],
72
+ };
73
+
74
+ function catalogClient(): { client: EldraClient; productOptions: unknown[] } {
75
+ const productOptions: unknown[] = [];
76
+ const client = {
77
+ catalog: {
78
+ getProduct: async (_handle: string, options: Record<string, unknown> | undefined) => {
79
+ productOptions.push(options);
80
+ const currency = options?.currency as string | undefined;
81
+ return {
82
+ ...PRODUCT,
83
+ variants: [
84
+ currency === 'EUR'
85
+ ? {
86
+ id: 'v1',
87
+ sku: 'M',
88
+ price: 19.9,
89
+ currency: 'EUR',
90
+ soldInCurrency: true,
91
+ status: 'ACTIVE',
92
+ }
93
+ : currency === 'USD'
94
+ ? {
95
+ id: 'v1',
96
+ sku: 'M',
97
+ price: 2900,
98
+ currency: 'ISK',
99
+ soldInCurrency: false,
100
+ status: 'ACTIVE',
101
+ }
102
+ : { id: 'v1', sku: 'M', price: 2900, status: 'ACTIVE' },
103
+ ],
104
+ };
105
+ },
106
+ listCategories: async () => [],
107
+ },
108
+ inventory: { availability: async () => [] },
109
+ cart: { get: async () => ({}) },
110
+ checkout: { url: async () => 'https://checkout.example/x' },
111
+ } as unknown as EldraClient;
112
+ return { client, productOptions };
113
+ }
114
+
115
+ describe('catalog reads in the chosen currency', () => {
116
+ it('reads in the store currency as the build did, then in the chosen one', async () => {
117
+ installStorage();
118
+ const { client, productOptions } = catalogClient();
119
+ const storefront = createGatewayStorefront(client, { route: fakeRoute(), commerce: MULTI });
120
+ const product = storefront.catalog.product(ref('mug'));
121
+ await vi.waitFor(() => expect(product.data.value).not.toBeNull());
122
+ expect(productOptions[0]).toEqual({});
123
+ expect(product.data.value?.price).toEqual({ amount: 2900, compareAt: null });
124
+
125
+ await storefront.currency.start(async () => null);
126
+ storefront.currency.choose('EUR');
127
+ await nextTick();
128
+ await vi.waitFor(() => expect(product.data.value?.price.currency).toBe('EUR'));
129
+ expect(productOptions.at(-1)).toEqual({ currency: 'EUR' });
130
+ expect(product.data.value?.price.amount).toBe(19.9);
131
+ });
132
+
133
+ it('marks a product with no price in the chosen currency as not sold, keeping its own currency', async () => {
134
+ installStorage();
135
+ const { client } = catalogClient();
136
+ const storefront = createGatewayStorefront(client, { route: fakeRoute(), commerce: MULTI });
137
+ await storefront.currency.start(async () => null);
138
+ storefront.currency.choose('USD');
139
+ const product = storefront.catalog.product(ref('mug'));
140
+ await vi.waitFor(() => expect(product.data.value).not.toBeNull());
141
+ expect(product.data.value?.price).toMatchObject({
142
+ amount: 2900,
143
+ currency: 'ISK',
144
+ soldInCurrency: false,
145
+ });
146
+ });
147
+
148
+ it('never sends a currency for a one-currency store', async () => {
149
+ installStorage({ [CURRENCY_STORAGE_KEY]: 'EUR' });
150
+ const { client, productOptions } = catalogClient();
151
+ const storefront = createGatewayStorefront(client, { route: fakeRoute(), commerce: ISK_ONLY });
152
+ await storefront.currency.start(async () => 'DE');
153
+ const product = storefront.catalog.product(ref('mug'));
154
+ await vi.waitFor(() => expect(product.data.value).not.toBeNull());
155
+ expect(productOptions).toEqual([{}]);
156
+ });
157
+ });
158
+
159
+ function cartResponse(currency: string, soldInCurrency = true): Record<string, unknown> {
160
+ return {
161
+ id: 'cart-1',
162
+ currency,
163
+ items: [
164
+ {
165
+ id: 'line-1',
166
+ productId: 'p1',
167
+ variantId: 'v1',
168
+ title: 'Mug',
169
+ price: currency === 'ISK' ? 2900 : 19.9,
170
+ quantity: 1,
171
+ soldInCurrency,
172
+ },
173
+ ],
174
+ totals: { subtotal: 0, discount: 0, taxAmount: 0, total: 0 },
175
+ };
176
+ }
177
+
178
+ function cartClient(initial: Record<string, unknown> | null) {
179
+ const calls: Array<{ method: string; args: unknown[] }> = [];
180
+ let current = initial;
181
+ const client = {
182
+ cart: {
183
+ get: async () => current,
184
+ addItem: async (input: Record<string, unknown>) => {
185
+ calls.push({ method: 'addItem', args: [input] });
186
+ current = cartResponse((input.currency as string | undefined) ?? 'ISK');
187
+ return current;
188
+ },
189
+ setCurrency: async (cartId: string, currency: string) => {
190
+ calls.push({ method: 'setCurrency', args: [cartId, currency] });
191
+ if (currency === 'USD') throw Object.assign(new Error('not sold'), { status: 400 });
192
+ current = cartResponse(currency, currency !== 'EUR');
193
+ return current;
194
+ },
195
+ removeItem: async () => {
196
+ calls.push({ method: 'removeItem', args: [] });
197
+ current = { ...cartResponse('EUR'), items: [] };
198
+ return current;
199
+ },
200
+ },
201
+ checkout: { url: async () => 'https://checkout.example/checkout/org/cart-1' },
202
+ } as unknown as EldraClient;
203
+ return { client, calls };
204
+ }
205
+
206
+ describe('the cart follows the chosen currency', () => {
207
+ it('creates a new cart in the chosen currency', async () => {
208
+ installStorage();
209
+ const { client, calls } = cartClient(null);
210
+ const storefront = createGatewayStorefront(client, { route: fakeRoute(), commerce: MULTI });
211
+ await storefront.currency.start(async () => null);
212
+ storefront.currency.choose('EUR');
213
+ await storefront.cart.add({ productId: 'p1', variantId: 'v1', quantity: 1 });
214
+ expect(calls[0]).toEqual({
215
+ method: 'addItem',
216
+ args: [{ cartId: undefined, productId: 'p1', variantId: 'v1', quantity: 1, currency: 'EUR' }],
217
+ });
218
+ expect(storefront.cart.currency.value).toBe('EUR');
219
+ });
220
+
221
+ it('moves the whole cart when the visitor switches, and holds checkout while a line is not sold', async () => {
222
+ installStorage({ 'eldra.cartId': 'cart-1' });
223
+ const { client, calls } = cartClient(cartResponse('ISK'));
224
+ const storefront = createGatewayStorefront(client, { route: fakeRoute(), commerce: MULTI });
225
+ await vi.waitFor(() => expect(storefront.cart.currency.value).toBe('ISK'));
226
+ await storefront.currency.start(async () => null);
227
+ await vi.waitFor(() => expect(storefront.cart.checkoutUrl.value).not.toBeNull());
228
+
229
+ storefront.currency.choose('EUR');
230
+ await vi.waitFor(() => expect(storefront.cart.currency.value).toBe('EUR'));
231
+ expect(calls).toContainEqual({ method: 'setCurrency', args: ['cart-1', 'EUR'] });
232
+ expect(storefront.cart.notSold.value.map((line) => line.title)).toEqual(['Mug']);
233
+ expect(storefront.cart.checkoutUrl.value).toBeNull();
234
+
235
+ await storefront.cart.removeNotSold();
236
+ expect(storefront.cart.notSold.value).toEqual([]);
237
+ expect(storefront.cart.checkoutUrl.value).not.toBeNull();
238
+ });
239
+
240
+ it('adopts the cart currency it finds instead of moving the cart (another tab chose it)', async () => {
241
+ installStorage({ 'eldra.cartId': 'cart-1' });
242
+ const { client, calls } = cartClient(cartResponse('ISK'));
243
+ const storefront = createGatewayStorefront(client, { route: fakeRoute(), commerce: MULTI });
244
+ await vi.waitFor(() => expect(storefront.cart.currency.value).toBe('ISK'));
245
+ await storefront.currency.start(async () => null);
246
+ client.cart.addItem = (async () => cartResponse('EUR')) as typeof client.cart.addItem;
247
+ await storefront.cart.add({ productId: 'p1', variantId: 'v1', quantity: 1 });
248
+ await vi.waitFor(() => expect(storefront.currency.active.value).toBe('EUR'));
249
+ expect(calls.filter((call) => call.method === 'setCurrency')).toEqual([]);
250
+ });
251
+
252
+ it('does not move the cart before start() has settled', async () => {
253
+ installStorage({ 'eldra.cartId': 'cart-1' });
254
+ const { client, calls } = cartClient(cartResponse('EUR'));
255
+ const storefront = createGatewayStorefront(client, { route: fakeRoute(), commerce: MULTI });
256
+ await vi.waitFor(() => expect(storefront.cart.currency.value).toBe('EUR'));
257
+ await nextTick();
258
+ expect(calls).toEqual([]);
259
+ expect(storefront.currency.active.value).toBe('ISK');
260
+ });
261
+
262
+ it('puts the visitor back in the cart currency and forgets the choice when the cart refuses to move', async () => {
263
+ const data = installStorage({ 'eldra.cartId': 'cart-1' });
264
+ const { client } = cartClient(cartResponse('ISK'));
265
+ const storefront = createGatewayStorefront(client, { route: fakeRoute(), commerce: MULTI });
266
+ await vi.waitFor(() => expect(storefront.cart.currency.value).toBe('ISK'));
267
+ await storefront.currency.start(async () => null);
268
+ storefront.currency.choose('USD');
269
+ expect(storefront.currency.busy.value).toBe(true);
270
+ await vi.waitFor(() => expect(storefront.currency.busy.value).toBe(false));
271
+ expect(storefront.currency.active.value).toBe('ISK');
272
+ expect(storefront.cart.currency.value).toBe('ISK');
273
+ expect(data.has(CURRENCY_STORAGE_KEY)).toBe(false);
274
+ });
275
+
276
+ it('withdraws a currency the cart may not move to because the shop stopped selling in it', async () => {
277
+ installStorage({ 'eldra.cartId': 'cart-1' });
278
+ const { client } = cartClient(cartResponse('ISK'));
279
+ client.cart.setCurrency = (async () => {
280
+ throw notSold();
281
+ }) as typeof client.cart.setCurrency;
282
+ const storefront = createGatewayStorefront(client, { route: fakeRoute(), commerce: MULTI });
283
+ await vi.waitFor(() => expect(storefront.cart.currency.value).toBe('ISK'));
284
+ await storefront.currency.start(async () => null);
285
+ storefront.currency.choose('EUR');
286
+ await vi.waitFor(() => expect(storefront.currency.offered.value).toEqual(['ISK', 'USD']));
287
+ expect(storefront.currency.active.value).toBe('ISK');
288
+ expect(storefront.currency.failure.value?.errorId).toBe('CART_CURRENCY_NOT_SOLD');
289
+ });
290
+
291
+ it('withdraws a currency the shop stopped selling in and adds in the store currency instead', async () => {
292
+ const data = installStorage();
293
+ const sent: Array<string | undefined> = [];
294
+ const client = {
295
+ cart: {
296
+ get: async () => null,
297
+ addItem: async (input: Record<string, unknown>) => {
298
+ sent.push(input.currency as string | undefined);
299
+ if (input.currency === 'EUR') throw notSold();
300
+ return cartResponse('ISK');
301
+ },
302
+ },
303
+ checkout: { url: async () => 'https://checkout.example/x' },
304
+ } as unknown as EldraClient;
305
+ const storefront = createGatewayStorefront(client, { route: fakeRoute(), commerce: MULTI });
306
+ await storefront.currency.start(async () => 'DE');
307
+ expect(storefront.currency.active.value).toBe('EUR');
308
+
309
+ const failure = await storefront.cart.add({ productId: 'p1', variantId: 'v1', quantity: 1 });
310
+
311
+ expect(failure).toBeNull();
312
+ expect(sent).toEqual(['EUR', undefined]);
313
+ expect(storefront.currency.active.value).toBe('ISK');
314
+ expect(storefront.currency.offered.value).toEqual(['ISK', 'USD']);
315
+ expect(storefront.currency.movedTo.value).toBe('ISK');
316
+ expect(data.has(CURRENCY_STORAGE_KEY)).toBe(false);
317
+ expect(storefront.cart.lines.value).toHaveLength(1);
318
+ });
319
+ });
320
+
321
+ describe('price filters in the chosen currency', () => {
322
+ it('sends no price filter and shows no price facet outside the store currency', async () => {
323
+ installStorage();
324
+ const queries: Array<Record<string, unknown>> = [];
325
+ const client = {
326
+ catalog: {
327
+ listProducts: async (options: Record<string, unknown>) => {
328
+ queries.push(options);
329
+ return {
330
+ data: [],
331
+ meta: {
332
+ page: 1,
333
+ pageSize: 24,
334
+ total: 0,
335
+ totalPages: 0,
336
+ rows: 0,
337
+ hasNext: false,
338
+ hasPrev: false,
339
+ },
340
+ facets: {
341
+ price: { min: 1000, max: 9000 },
342
+ categories: [],
343
+ collections: [],
344
+ options: [],
345
+ },
346
+ };
347
+ },
348
+ listCategories: async () => [],
349
+ },
350
+ cart: { get: async () => null },
351
+ checkout: { url: async () => 'x' },
352
+ } as unknown as EldraClient;
353
+ const storefront = createGatewayStorefront(client, { route: fakeRoute(), commerce: MULTI });
354
+ const opts = ref({ page: 1, pageSize: 24, filters: { price: ['10-20'] } });
355
+ const result = storefront.catalog.products(opts);
356
+ await vi.waitFor(() => expect(result.data.value).not.toBeNull());
357
+ expect(queries[0]).toMatchObject({ minPrice: 10, maxPrice: 20 });
358
+ expect(result.data.value?.facets?.price).toBeDefined();
359
+
360
+ await storefront.currency.start(async () => null);
361
+ storefront.currency.choose('EUR');
362
+ await vi.waitFor(() => expect(queries).toHaveLength(2));
363
+ await vi.waitFor(() => expect(result.data.value?.facets?.price).toBeUndefined());
364
+ expect(queries[1]).not.toHaveProperty('minPrice');
365
+ expect(queries[1]).not.toHaveProperty('maxPrice');
366
+ expect(queries[1]).toMatchObject({ currency: 'EUR' });
367
+ });
368
+ });
369
+
370
+ describe('search in the chosen currency', () => {
371
+ it('prices search results in the chosen currency', async () => {
372
+ installStorage();
373
+ const listed: unknown[] = [];
374
+ const client = {
375
+ catalog: {
376
+ search: async () => ({
377
+ results: [
378
+ { id: 'r1', sourceId: 'p1', kind: 'PRODUCT', title: 'Mug', targetUrl: '/products/mug' },
379
+ ],
380
+ total: 1,
381
+ }),
382
+ listProducts: async (options: Record<string, unknown>) => {
383
+ listed.push(options);
384
+ return {
385
+ data: [
386
+ {
387
+ id: 'p1',
388
+ slug: 'mug',
389
+ title: 'Mug',
390
+ status: 'ACTIVE',
391
+ minPrice: 19.9,
392
+ maxPrice: 19.9,
393
+ totalVariants: 1,
394
+ currency: 'EUR',
395
+ soldInCurrency: true,
396
+ },
397
+ ],
398
+ meta: {
399
+ page: 1,
400
+ pageSize: 1,
401
+ total: 1,
402
+ totalPages: 1,
403
+ rows: 1,
404
+ hasNext: false,
405
+ hasPrev: false,
406
+ },
407
+ };
408
+ },
409
+ },
410
+ cart: { get: async () => null },
411
+ checkout: { url: async () => 'x' },
412
+ } as unknown as EldraClient;
413
+ const storefront = createGatewayStorefront(client, { route: fakeRoute(), commerce: MULTI });
414
+ await storefront.currency.start(async () => null);
415
+ storefront.currency.choose('EUR');
416
+ await vi.waitFor(() => expect(storefront.currency.active.value).toBe('EUR'));
417
+ const result = storefront.search.run(ref('mug'));
418
+ await vi.waitFor(() => expect(result.data.value?.products[0]?.price?.amount).toBe(19.9));
419
+ expect(listed.every((options) => (options as { currency?: string }).currency === 'EUR')).toBe(
420
+ true
421
+ );
422
+ expect(result.data.value?.products[0]?.price).toMatchObject({ amount: 19.9, currency: 'EUR' });
423
+ });
424
+ });
425
+
426
+ describe('fetchVisitorCountry', () => {
427
+ it('gives up after the timeout so Add to cart is not held', async () => {
428
+ vi.useFakeTimers();
429
+ vi.stubGlobal(
430
+ 'fetch',
431
+ (_path: string, init: { signal: AbortSignal }) =>
432
+ new Promise((_resolve, reject) =>
433
+ init.signal.addEventListener('abort', () => reject(new Error('aborted')))
434
+ )
435
+ );
436
+ try {
437
+ const answer = fetchVisitorCountry(1500);
438
+ await vi.advanceTimersByTimeAsync(1500);
439
+ await expect(answer).resolves.toBeNull();
440
+ } finally {
441
+ vi.useRealTimers();
442
+ vi.unstubAllGlobals();
443
+ }
444
+ });
445
+
446
+ it('answers the country the edge reports', async () => {
447
+ vi.stubGlobal('fetch', async () => ({ ok: true, json: async () => ({ country: 'DE' }) }));
448
+ try {
449
+ await expect(fetchVisitorCountry()).resolves.toBe('DE');
450
+ } finally {
451
+ vi.unstubAllGlobals();
452
+ }
453
+ });
454
+ });
455
+
456
+ describe('a cart read that fails (K3)', () => {
457
+ function readFailure(status: number): EldraHttpError {
458
+ return new EldraHttpError(new Response('{}', { status, statusText: `S${status}` }), {
459
+ errorId: status === 404 ? 'CART_NOT_FOUND' : 'UNAVAILABLE',
460
+ });
461
+ }
462
+
463
+ function cartReads(answers: Array<() => unknown>) {
464
+ return {
465
+ cart: {
466
+ get: async () => {
467
+ const next = answers.shift()!;
468
+ return next();
469
+ },
470
+ },
471
+ checkout: { url: async () => 'https://checkout.example/x' },
472
+ } as unknown as EldraClient;
473
+ }
474
+
475
+ it('keeps the cart and its currency when the read times out or the gateway answers 5xx', async () => {
476
+ const data = installStorage({ 'eldra.cartId': 'cart-1', [CURRENCY_STORAGE_KEY]: 'USD' });
477
+ const client = cartReads([
478
+ () => cartResponse('EUR'),
479
+ () => {
480
+ throw readFailure(503);
481
+ },
482
+ ]);
483
+ const storefront = createGatewayStorefront(client, { route: fakeRoute(), commerce: MULTI });
484
+ await vi.waitFor(() => expect(storefront.cart.currency.value).toBe('EUR'));
485
+ await storefront.currency.start(async () => null);
486
+
487
+ const failure = await storefront.cart.reload();
488
+ expect(failure?.status).toBe(503);
489
+ expect(data.get('eldra.cartId')).toBe('cart-1');
490
+ expect(storefront.cart.currency.value).toBe('EUR');
491
+ expect(storefront.currency.active.value).toBe('EUR');
492
+ expect(storefront.cart.lines.value).toHaveLength(1);
493
+ });
494
+
495
+ it('forgets a cart the gateway says is gone, and the preference applies again', async () => {
496
+ const data = installStorage({ 'eldra.cartId': 'cart-1', [CURRENCY_STORAGE_KEY]: 'USD' });
497
+ const client = cartReads([
498
+ () => cartResponse('EUR'),
499
+ () => {
500
+ throw readFailure(404);
501
+ },
502
+ ]);
503
+ const storefront = createGatewayStorefront(client, { route: fakeRoute(), commerce: MULTI });
504
+ await vi.waitFor(() => expect(storefront.cart.currency.value).toBe('EUR'));
505
+ await storefront.currency.start(async () => null);
506
+
507
+ expect(await storefront.cart.reload()).toBeNull();
508
+ expect(data.has('eldra.cartId')).toBe(false);
509
+ expect(storefront.cart.currency.value).toBeUndefined();
510
+ expect(storefront.currency.active.value).toBe('USD');
511
+ });
512
+ });
513
+
514
+ describe('CodeRabbit review on #162: gateway', () => {
515
+ it('4662896726: a stale read that finds the old cart gone does not forget the newer cart', async () => {
516
+ const data = installStorage({ 'eldra.cartId': 'cart-c' });
517
+ const gets: Array<{ resolve: (value: unknown) => void; reject: (error: unknown) => void }> = [];
518
+ const gone = () =>
519
+ new EldraHttpError(new Response('{}', { status: 404, statusText: 'Not Found' }), {
520
+ errorId: 'CART_NOT_FOUND',
521
+ });
522
+ const client = {
523
+ cart: {
524
+ get: () =>
525
+ new Promise((resolve, reject) => {
526
+ gets.push({ resolve, reject });
527
+ }),
528
+ addItem: async () => ({ ...cartResponse('ISK'), id: 'cart-d' }),
529
+ },
530
+ checkout: { url: async () => 'https://checkout.example/x' },
531
+ } as unknown as EldraClient;
532
+ const storefront = createGatewayStorefront(client, { route: fakeRoute(), commerce: ISK_ONLY });
533
+ gets.shift()!.resolve({ ...cartResponse('ISK'), id: 'cart-c' });
534
+ await vi.waitFor(() => expect(storefront.cart.currency.value).toBe('ISK'));
535
+
536
+ void storefront.cart.reload();
537
+ void storefront.cart.reload();
538
+ const older = gets.shift()!;
539
+ gets.shift()!.reject(gone());
540
+ await vi.waitFor(() => expect(data.has('eldra.cartId')).toBe(false));
541
+ await storefront.cart.add({ productId: 'p1', variantId: 'v1', quantity: 1 });
542
+ expect(data.get('eldra.cartId')).toBe('cart-d');
543
+
544
+ older.reject(gone());
545
+ await nextTick();
546
+ await new Promise((resolve) => setTimeout(resolve, 0));
547
+ expect(data.get('eldra.cartId')).toBe('cart-d');
548
+ });
549
+ });