@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
@@ -65,6 +65,20 @@ export interface CartStore {
65
65
  undoRemove(): Promise<StorefrontFailure | null>;
66
66
  applyDiscount(code: string): Promise<StorefrontAck>;
67
67
  removeDiscount(code: string): Promise<StorefrontFailure | null>;
68
+ /** The cart's currency, or `undefined` before there is a cart. */
69
+ currency: Ref<string | undefined>;
70
+ /** Lines with no price in the cart's currency. While there are any, `checkoutUrl` is `null`. */
71
+ notSold: ComputedRef<StorefrontCartLine[]>;
72
+ /** Moves the whole cart to `code`. Nothing to do without a cart, or when it is in `code` already. */
73
+ setCurrency(code: string): Promise<StorefrontFailure | null | undefined>;
74
+ /** The last read of the cart failed (a timeout or 5xx); the basket id is kept. */
75
+ loadFailed: Ref<boolean>;
76
+ /** `none`: no cart. `loaded`: the cart is shown. `unloaded`: a cart is remembered but not read yet, or its read failed. */
77
+ loadState: Ref<CartLoadState>;
78
+ /** Reads the cart again, as another tab may have changed it. */
79
+ reload(): Promise<StorefrontFailure | null>;
80
+ /** Removes every line in `notSold`: "Remove and check out". */
81
+ removeNotSold(): Promise<StorefrontFailure | null>;
68
82
  checkoutUrl: ComputedRef<string | null>;
69
83
  /**
70
84
  * The shopper followed the Check out link. Does nothing here — the link itself does the
@@ -81,6 +95,14 @@ export interface CartStore {
81
95
  * (`StorefrontProduct.productId`/`variantId`) or from a cart line (`StorefrontCartLine`); a product
82
96
  * card carries no variant at all, by design (`app/storefront/types.ts`).
83
97
  */
98
+ export type CartLoadState = 'none' | 'loaded' | 'unloaded';
99
+
100
+ /** A write refused locally: the cart could not be read, so nothing was sent. */
101
+ export const CART_NOT_LOADED = 'CART_NOT_LOADED';
102
+
103
+ /** A cart read that has not answered after this long counts as failed. */
104
+ export const CART_READ_TIMEOUT_MS = 8000;
105
+
84
106
  export interface CartAddInput {
85
107
  productId: string;
86
108
  variantId: string;
@@ -90,6 +112,8 @@ export interface CartAddInput {
90
112
  export interface CartSnapshot {
91
113
  lines: StorefrontCartLine[];
92
114
  totals: StorefrontCartTotals;
115
+ /** The cart's own currency; absent from a backend that does not say. */
116
+ currency?: string;
93
117
  }
94
118
 
95
119
  /**
@@ -106,6 +130,8 @@ export interface CartOps {
106
130
  remove(lineId: string): Promise<CartSnapshot>;
107
131
  applyDiscount(code: string): Promise<{ ack: StorefrontAck; snapshot?: CartSnapshot }>;
108
132
  removeDiscount(): Promise<CartSnapshot>;
133
+ /** Reprices the cart in `code`. Absent: the backend cannot change a cart's currency. */
134
+ setCurrency?(code: string): Promise<CartSnapshot>;
109
135
  /** Reactive so a cart id assigned after the first `add()` updates the link immediately. */
110
136
  checkoutUrl: Ref<string | null>;
111
137
  }
@@ -144,32 +170,183 @@ export function createCartStore(ops: CartOps): CartStore {
144
170
  index: number;
145
171
  } | null>;
146
172
 
173
+ const currency = ref<string | undefined>(undefined);
147
174
  const count = computed(() => lines.value.reduce((sum, line) => sum + line.quantity, 0));
148
- const checkoutUrl = computed(() => ops.checkoutUrl.value);
175
+ const notSold = computed(() => lines.value.filter((line) => line.soldInCurrency === false));
176
+ const checkoutUrl = computed(() => (notSold.value.length > 0 ? null : ops.checkoutUrl.value));
177
+
178
+ // Every write runs through one queue, in the shopper's order, one request at a time, so the last
179
+ // answer applied is always the newest server state.
180
+ let tail: Promise<unknown> = Promise.resolve();
181
+ let queuedWrites = 0;
182
+ let reads = 0;
183
+ let writeEpoch = 0;
184
+ let reading: Promise<unknown> = Promise.resolve();
185
+ let latestRead = 0;
186
+ const loadFailed = ref(false);
187
+ const loadState = ref<CartLoadState>('unloaded');
188
+ const notLoaded: StorefrontFailure = {
189
+ message: 'The cart could not be read.',
190
+ errorId: CART_NOT_LOADED,
191
+ code: null,
192
+ status: null,
193
+ };
194
+ const settleBusy = (): void => {
195
+ pending.value = queuedWrites > 0 || reads > 0;
196
+ };
149
197
 
150
- let inFlight = 0;
198
+ function apply(snapshot: CartSnapshot): void {
199
+ lines.value = snapshot.lines;
200
+ totals.value = snapshot.totals;
201
+ currency.value = snapshot.currency;
202
+ loadFailed.value = false;
203
+ loadState.value =
204
+ snapshot.currency !== undefined || snapshot.lines.length > 0 ? 'loaded' : 'none';
205
+ }
151
206
 
152
- async function run(task: () => Promise<CartSnapshot>): Promise<StorefrontFailure | null> {
153
- inFlight += 1;
207
+ function serial<T>(task: () => Promise<T>, refused: () => T): Promise<T> {
208
+ queuedWrites += 1;
154
209
  pending.value = true;
210
+ const next = tail.then(async () => {
211
+ // A write waits for a read in flight, and a failed read is tried once more first; a cart that
212
+ // still cannot be read takes no write, so a write never lands in a cart the page has not shown.
213
+ // The newest read, not only the one current when this write began waiting.
214
+ let awaited: Promise<unknown>;
215
+ do {
216
+ awaited = reading;
217
+ await awaited;
218
+ } while (awaited !== reading);
219
+ if (loadFailed.value) await read();
220
+ if (loadFailed.value) {
221
+ queuedWrites -= 1;
222
+ settleBusy();
223
+ lastFailure.value = notLoaded;
224
+ error.value = notLoaded.message;
225
+ return refused();
226
+ }
227
+ writeEpoch += 1;
228
+ try {
229
+ return await task();
230
+ } finally {
231
+ writeEpoch += 1;
232
+ queuedWrites -= 1;
233
+ settleBusy();
234
+ }
235
+ });
236
+ tail = next.catch(() => undefined);
237
+ return next;
238
+ }
239
+
240
+ async function attempt(task: () => Promise<CartSnapshot>): Promise<StorefrontFailure | null> {
155
241
  clearFailure();
156
242
  try {
157
- const snapshot = await task();
158
- lines.value = snapshot.lines;
159
- totals.value = snapshot.totals;
243
+ apply(await task());
160
244
  return null;
161
245
  } catch (caught) {
162
246
  return fail(caught);
163
- } finally {
164
- inFlight -= 1;
165
- if (inFlight === 0) pending.value = false;
166
247
  }
167
248
  }
168
249
 
250
+ const run = (task: () => Promise<CartSnapshot>): Promise<StorefrontFailure | null> =>
251
+ serial(
252
+ () => attempt(task),
253
+ () => notLoaded
254
+ );
255
+
256
+ /** Only the newest read applies, and only when no write started or settled since it was sent. */
257
+ function read(): Promise<StorefrontFailure | null> {
258
+ const issuedAt = writeEpoch;
259
+ latestRead += 1;
260
+ const mine = latestRead;
261
+ reads += 1;
262
+ pending.value = true;
263
+ clearFailure();
264
+ let timer: ReturnType<typeof setTimeout> | undefined;
265
+ const timedOut = new Promise<never>((_resolve, reject) => {
266
+ timer = setTimeout(() => reject(new Error('The cart read timed out.')), CART_READ_TIMEOUT_MS);
267
+ });
268
+ const answer = Promise.race([ops.init(), timedOut]).then(
269
+ (snapshot) => {
270
+ if (mine === latestRead && writeEpoch === issuedAt) apply(snapshot);
271
+ return null;
272
+ },
273
+ (caught: unknown) => {
274
+ // A read overtaken by a newer read or by a write says nothing about the cart shown now.
275
+ if (mine !== latestRead || writeEpoch !== issuedAt) return null;
276
+ loadFailed.value = true;
277
+ if (loadState.value !== 'none') loadState.value = 'unloaded';
278
+ return fail(caught);
279
+ }
280
+ );
281
+ const settled = answer.finally(() => {
282
+ clearTimeout(timer);
283
+ reads -= 1;
284
+ settleBusy();
285
+ });
286
+ reading = settled;
287
+ return settled;
288
+ }
289
+
290
+ // Consecutive currency choices waiting in the queue collapse into the last one; only that one is
291
+ // sent, and the choices it replaced answer `undefined`.
292
+ type MoveAnswer = StorefrontFailure | null | undefined;
293
+ let waitingMove: {
294
+ code: string;
295
+ callers: Array<{ code: string; resolve: (answer: MoveAnswer) => void }>;
296
+ } | null = null;
297
+
298
+ function moveCurrency(code: string): Promise<MoveAnswer> {
299
+ const change = ops.setCurrency;
300
+ // A backend that cannot move a cart still answers in turn, after the read the choice waited for.
301
+ if (change === undefined) {
302
+ return serial(
303
+ async () => null,
304
+ () => notLoaded
305
+ );
306
+ }
307
+ const joining = waitingMove;
308
+ if (joining !== null) {
309
+ joining.code = code;
310
+ return new Promise((resolve) => joining.callers.push({ code, resolve }));
311
+ }
312
+ const move = {
313
+ code,
314
+ callers: [] as Array<{ code: string; resolve: (answer: MoveAnswer) => void }>,
315
+ };
316
+ waitingMove = move;
317
+ const own = new Promise<MoveAnswer>((resolve) => move.callers.push({ code, resolve }));
318
+ void serial(
319
+ async () => {
320
+ waitingMove = null;
321
+ const target = move.code;
322
+ const before = currency.value;
323
+ const failure =
324
+ before === undefined || before === target ? null : await attempt(() => change(target));
325
+ if (failure === null && before !== target && currency.value === target) {
326
+ lastRemoved.value = null;
327
+ }
328
+ for (const caller of move.callers) {
329
+ if (caller.code !== target) caller.resolve(undefined);
330
+ }
331
+ [...move.callers]
332
+ .reverse()
333
+ .find((caller) => caller.code === target)
334
+ ?.resolve(failure);
335
+ for (const caller of move.callers) caller.resolve(undefined);
336
+ },
337
+ () => {
338
+ waitingMove = null;
339
+ [...move.callers].reverse()[0]?.resolve(notLoaded);
340
+ for (const caller of move.callers) caller.resolve(undefined);
341
+ }
342
+ );
343
+ return own;
344
+ }
345
+
169
346
  // Loads whatever cart already exists (a remembered cart id for the gateway, the Northwind
170
347
  // fixture for the demo) as soon as the store is created — no separate "refresh" the caller has
171
348
  // to remember to call first.
172
- void run(() => ops.init());
349
+ void read();
173
350
 
174
351
  return {
175
352
  lines,
@@ -198,55 +375,55 @@ export function createCartStore(ops: CartOps): CartStore {
198
375
  async undoRemove() {
199
376
  const removed = lastRemoved.value;
200
377
  if (!removed) return null;
201
- // Reinsert at the exact index it was removed from — trusting a re-`add()`'s own returned
202
- // line order would not guarantee that, so this half is local and synchronous.
203
- lines.value = [
204
- ...lines.value.slice(0, removed.index),
205
- removed.line,
206
- ...lines.value.slice(removed.index),
207
- ];
208
378
  lastRemoved.value = null;
209
- inFlight += 1;
210
- pending.value = true;
211
- clearFailure();
212
- try {
379
+ // The restored line comes from the server's answer, in the cart's currency, put back where it was.
380
+ return run(async () => {
213
381
  const snapshot = await ops.add({
214
382
  productId: removed.line.productId,
215
383
  variantId: removed.line.variantId,
216
384
  quantity: removed.line.quantity,
217
385
  });
218
- // Only totals are trusted from the backend here — `lines` stays the locally-restored
219
- // order above.
220
- totals.value = snapshot.totals;
221
- return null;
222
- } catch (caught) {
223
- return fail(caught);
224
- } finally {
225
- inFlight -= 1;
226
- if (inFlight === 0) pending.value = false;
227
- }
228
- },
229
- async applyDiscount(code) {
230
- inFlight += 1;
231
- pending.value = true;
232
- clearFailure();
233
- try {
234
- const { ack, snapshot } = await ops.applyDiscount(code);
235
- if (snapshot) {
236
- lines.value = snapshot.lines;
237
- totals.value = snapshot.totals;
238
- }
239
- return ack;
240
- } catch (caught) {
241
- fail(caught);
242
- return { ok: false, reason: 'failed' };
243
- } finally {
244
- inFlight -= 1;
245
- if (inFlight === 0) pending.value = false;
246
- }
386
+ const at = snapshot.lines.findIndex((line) => line.variantId === removed.line.variantId);
387
+ if (at === -1) return snapshot;
388
+ const others = snapshot.lines.filter((_line, index) => index !== at);
389
+ others.splice(Math.min(removed.index, others.length), 0, snapshot.lines[at]!);
390
+ return { ...snapshot, lines: others };
391
+ });
247
392
  },
393
+ applyDiscount: (code) =>
394
+ serial(
395
+ async () => {
396
+ clearFailure();
397
+ try {
398
+ const { ack, snapshot } = await ops.applyDiscount(code);
399
+ if (snapshot) apply(snapshot);
400
+ return ack;
401
+ } catch (caught) {
402
+ fail(caught);
403
+ return { ok: false, reason: 'failed' } as StorefrontAck;
404
+ }
405
+ },
406
+ () => ({ ok: false, reason: 'failed' }) as StorefrontAck
407
+ ),
248
408
  // `code` identifies which applied-discount chip the caller removed; a cart only ever carries
249
409
  // one discount today, so `ops.removeDiscount()` itself needs no argument.
250
410
  removeDiscount: (_code) => run(() => ops.removeDiscount()),
411
+ currency,
412
+ notSold,
413
+ setCurrency: moveCurrency,
414
+ loadFailed,
415
+ loadState,
416
+ reload: read,
417
+ removeNotSold: () =>
418
+ serial(
419
+ async () => {
420
+ for (const line of [...notSold.value]) {
421
+ const failure = await attempt(() => ops.remove(line.id));
422
+ if (failure !== null) return failure;
423
+ }
424
+ return null;
425
+ },
426
+ () => notLoaded
427
+ ),
251
428
  };
252
429
  }
@@ -26,11 +26,17 @@ export function toStorefrontCommerce(value: unknown): StorefrontCommerce | null
26
26
  // report.
27
27
  if (value === null || value === undefined || value === '') return null;
28
28
  if (typeof value !== 'object') return discard(value, 'commerce is not an object');
29
- const { currency, taxInclusivePricing, defaultTaxRate } = value as Record<string, unknown>;
29
+ const { currency, taxInclusivePricing, defaultTaxRate, currencies } = value as Record<
30
+ string,
31
+ unknown
32
+ >;
30
33
  if (typeof currency !== 'string' || currency === '') return discard(value, 'currency');
31
34
  if (typeof taxInclusivePricing !== 'boolean') return discard(value, 'taxInclusivePricing');
32
35
  if (typeof defaultTaxRate !== 'number') return discard(value, 'defaultTaxRate');
33
- return { currency, taxInclusivePricing, defaultTaxRate };
36
+ // The list was cleaned at build (`@eldrajs/theme-nuxt`); here it is only checked to be one.
37
+ return Array.isArray(currencies) && currencies.every((code) => typeof code === 'string')
38
+ ? { currency, taxInclusivePricing, defaultTaxRate, currencies: currencies as string[] }
39
+ : { currency, taxInclusivePricing, defaultTaxRate };
34
40
  }
35
41
 
36
42
  /**
@@ -0,0 +1,205 @@
1
+ import { computed, ref, watch, type ComputedRef, type Ref } from 'vue';
2
+ import { createCurrencyPreference, type EldraCurrencyPreference } from '@eldrajs/sdk';
3
+ import { resolveVisitorCurrency, VISITOR_COUNTRY_PATH } from '@eldrajs/theme-core';
4
+ import type { CartStore } from './cart';
5
+ import type { StorefrontFailure } from './feedback';
6
+
7
+ /** The visitor's currency, derived: the cart's, else the preference, else `base` (docs/starter-kit.md, "Currencies"). */
8
+ export interface CurrencyStore {
9
+ /** The store's own currency, or `undefined` when it publishes none. */
10
+ base: string | undefined;
11
+ /** What the visitor may pick from, `base` first. One entry or none: no picker. */
12
+ offered: Ref<readonly string[]>;
13
+ /** The currency the site shows: `base` until `start` settles, then the cart's, the preference's or `base`. */
14
+ active: ComputedRef<string | undefined>;
15
+ /** `start` has settled. */
16
+ started: Ref<boolean>;
17
+ /** Prices on screen may still change currency: more than one is offered and `start` has not settled. */
18
+ pending: ComputedRef<boolean>;
19
+ /** A move of the cart is in flight or queued. */
20
+ busy: ComputedRef<boolean>;
21
+ /** The currency catalog reads ask for, or `undefined` to read in `base` exactly as the build did. */
22
+ requested: ComputedRef<string | undefined>;
23
+ /** Set when the visitor was moved off a currency, for a one-time notice. */
24
+ movedTo: Ref<string | null>;
25
+ /** A cart move that failed for another reason than the currency, for an error toast. */
26
+ failure: Ref<StorefrontFailure | null>;
27
+ /** The visitor's explicit choice. With a cart it moves the cart, last choice wins. */
28
+ choose(code: string): void;
29
+ chooseBase(): void;
30
+ /** Stops following other tabs; for a store made for one component (a demo, a story), not the app's. */
31
+ dispose(): void;
32
+ /** Reads the stored preference, else the visitor's country. Call once, after mount. */
33
+ start(country: () => Promise<string | null>): Promise<void>;
34
+ }
35
+
36
+ export const CURRENCY_NOT_SOLD = 'CART_CURRENCY_NOT_SOLD';
37
+ const CURRENCY_PREFERENCE_KEY = 'eldra.currency';
38
+
39
+ function refusedForCurrency(failure: StorefrontFailure | null): boolean {
40
+ return failure?.errorId === CURRENCY_NOT_SOLD;
41
+ }
42
+
43
+ /** Builds the store over `cart`; the returned cart's `add` retries once when its currency is refused. */
44
+ export function createCurrencyStore(
45
+ commerce: { currency: string; currencies?: readonly string[] } | null,
46
+ cart: CartStore,
47
+ preference: EldraCurrencyPreference = createCurrencyPreference()
48
+ ): { currency: CurrencyStore; cart: CartStore } {
49
+ const base = commerce?.currency;
50
+ const offered = ref<readonly string[]>(
51
+ base === undefined ? [] : (commerce?.currencies ?? [base])
52
+ );
53
+ const preferred = ref<string | null>(null);
54
+ const started = ref(false);
55
+ const movedTo = ref<string | null>(null);
56
+ const failure = ref<StorefrontFailure | null>(null);
57
+
58
+ const active = computed(() => {
59
+ if (!started.value) return base;
60
+ const own = cart.currency.value;
61
+ if (own !== undefined) return own;
62
+ return preferred.value !== null && offered.value.includes(preferred.value)
63
+ ? preferred.value
64
+ : base;
65
+ });
66
+ const requested = computed(() => (active.value === base ? undefined : active.value));
67
+ const pending = computed(() => !started.value && offered.value.length > 1);
68
+
69
+ function withdraw(code: string): void {
70
+ if (code === base) return;
71
+ offered.value = offered.value.filter((offer) => offer !== code);
72
+ if (preference.read() === code) preference.forget();
73
+ if (preferred.value === code) preferred.value = null;
74
+ }
75
+
76
+ // Moves go through the cart's own write queue, where a newer choice replaces a waiting one.
77
+ const busy = computed(() => cart.pending.value);
78
+
79
+ async function move(code: string, notice = false): Promise<void> {
80
+ const answer = await cart.setCurrency(code);
81
+ // A later choice replaced this one before it was sent.
82
+ if (answer === undefined) return;
83
+ if (answer === null) {
84
+ // No cart came of the work this choice waited behind: it is the preference.
85
+ if (hasNoCart()) {
86
+ preferred.value = code;
87
+ preference.remember(code);
88
+ } else if (cart.currency.value === code) {
89
+ preferred.value = code;
90
+ preference.remember(code);
91
+ if (notice) movedTo.value = code;
92
+ }
93
+ } else {
94
+ if (refusedForCurrency(answer)) withdraw(code);
95
+ failure.value = answer;
96
+ }
97
+ }
98
+
99
+ // A cart that is remembered but not read is still a cart; one without a currency (a demo) is not.
100
+ const hasNoCart = (): boolean =>
101
+ cart.loadState.value !== 'unloaded' && cart.currency.value === undefined;
102
+
103
+ const leavingDropped = (): boolean => {
104
+ const own = cart.currency.value;
105
+ return own !== undefined && base !== undefined && !offered.value.includes(own);
106
+ };
107
+
108
+ // A cart in a currency this build no longer offers is moved to the store's own; the watch fires on a change only, so a failed move is not retried in a loop.
109
+ watch([started, cart.currency], ([isStarted, own]) => {
110
+ if (!isStarted || own === undefined || base === undefined) return;
111
+ if (offered.value.includes(own)) return;
112
+ void move(base, true);
113
+ });
114
+
115
+ const onStorage = (event: StorageEvent): void => {
116
+ if (event.key !== CURRENCY_PREFERENCE_KEY) return;
117
+ preferred.value = event.newValue;
118
+ if (cart.currency.value !== undefined) void cart.reload();
119
+ };
120
+ const listens = typeof window !== 'undefined' && typeof window.addEventListener === 'function';
121
+ if (listens) window.addEventListener('storage', onStorage);
122
+
123
+ const currency: CurrencyStore = {
124
+ base,
125
+ offered,
126
+ active,
127
+ started,
128
+ pending,
129
+ busy,
130
+ requested,
131
+ movedTo,
132
+ failure,
133
+ choose(code) {
134
+ if (!offered.value.includes(code)) return;
135
+ // Only with no cart and nothing in flight is a choice just a preference; else it queues behind that work.
136
+ if (hasNoCart() && !cart.pending.value) {
137
+ preferred.value = code;
138
+ preference.remember(code);
139
+ return;
140
+ }
141
+ void move(code);
142
+ },
143
+ dispose() {
144
+ if (listens) window.removeEventListener('storage', onStorage);
145
+ },
146
+ chooseBase() {
147
+ if (base !== undefined) currency.choose(base);
148
+ },
149
+ async start(country) {
150
+ let forgotten = false;
151
+ if (base !== undefined && offered.value.length > 1) {
152
+ const stored = preference.read();
153
+ if (stored !== null && offered.value.includes(stored)) {
154
+ if (preferred.value === null) preferred.value = stored;
155
+ } else {
156
+ if (stored !== null) preference.forget();
157
+ forgotten = stored !== null;
158
+ const visitorCountry = await country();
159
+ // A choice made during the lookup, or a cart, wins over the country.
160
+ if (cart.currency.value === undefined && preferred.value === null) {
161
+ const fromCountry = resolveVisitorCurrency({
162
+ base,
163
+ offered: offered.value,
164
+ country: visitorCountry,
165
+ });
166
+ if (fromCountry !== base) preferred.value = fromCountry;
167
+ }
168
+ }
169
+ }
170
+ started.value = true;
171
+ if (forgotten) movedTo.value = active.value ?? null;
172
+ },
173
+ };
174
+
175
+ const followingCart: CartStore = {
176
+ ...cart,
177
+ async add(input) {
178
+ // The visitor's next cart action tries again to leave a currency the store no longer offers.
179
+ if (leavingDropped() && base !== undefined) await move(base, true);
180
+ const hadCart = cart.currency.value !== undefined;
181
+ const sentIn = active.value;
182
+ const answer = await cart.add(input);
183
+ // The store checks the currency only when the add creates the cart.
184
+ if (hadCart || !refusedForCurrency(answer) || sentIn === undefined || sentIn === base) {
185
+ return answer;
186
+ }
187
+ withdraw(sentIn);
188
+ if (active.value !== sentIn) movedTo.value = active.value ?? null;
189
+ return cart.add(input);
190
+ },
191
+ };
192
+
193
+ return { currency, cart: followingCart };
194
+ }
195
+
196
+ /** The visitor's country from the site's own edge route; `null` on any failure or after `timeoutMs`, so a slow edge never holds Add to cart. */
197
+ export function fetchVisitorCountry(timeoutMs = 1500): Promise<string | null> {
198
+ const controller = new AbortController();
199
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
200
+ return fetch(VISITOR_COUNTRY_PATH, { signal: controller.signal })
201
+ .then((response) => (response.ok ? response.json() : null))
202
+ .then((body: { country?: string | null } | null) => body?.country ?? null)
203
+ .catch(() => null)
204
+ .finally(() => clearTimeout(timer));
205
+ }
@@ -2,6 +2,7 @@ import { nextTick, reactive, ref, watch, type Ref } from 'vue';
2
2
  import { starterFormSeeds } from '../formSeeds';
3
3
  import { localizeFormDefinition } from './forms';
4
4
  import { createCartStore, type CartOps, type CartSnapshot } from './cart';
5
+ import { createCurrencyStore } from './currency';
5
6
  import { createHistoryStore, createWishlistStore } from './history';
6
7
  import { roundMoney } from './money';
7
8
  import { optionDisplayType } from './options';
@@ -1342,12 +1343,19 @@ export function createDemoStorefront(options: DemoStorefrontOptions = {}): Store
1342
1343
  },
1343
1344
  };
1344
1345
 
1346
+ const commerce = options.commerce === undefined ? DEMO_COMMERCE : options.commerce;
1347
+ const { currency, cart } = createCurrencyStore(
1348
+ commerce,
1349
+ createCartStore(createDemoCartOps(options.cartLines ?? []))
1350
+ );
1351
+
1345
1352
  return {
1346
1353
  ready: ref(true),
1347
- commerce: options.commerce === undefined ? DEMO_COMMERCE : options.commerce,
1354
+ commerce,
1348
1355
  route,
1349
1356
  catalog,
1350
- cart: createCartStore(createDemoCartOps(options.cartLines ?? [])),
1357
+ cart,
1358
+ currency,
1351
1359
  search,
1352
1360
  orders,
1353
1361
  forms,
@@ -75,6 +75,8 @@ const MESSAGE_BY_ERROR_ID: Record<string, MessageKey> = {
75
75
  // store has moved on from, and reloading is the one thing that fixes it.
76
76
  CART_NOT_FOUND: 'storefront.cartOutOfDate',
77
77
  CART_ITEM_NOT_FOUND: 'storefront.cartOutOfDate',
78
+ // Refused in the browser: the cart could not be read, so nothing was sent.
79
+ CART_NOT_LOADED: 'cart.loadFailed',
78
80
  };
79
81
 
80
82
  /**