@usequeek/theme-kit 0.1.30 → 0.1.31

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/client.ts CHANGED
@@ -17,6 +17,7 @@ export * from './components/image';
17
17
  export * from './components/product-metafields';
18
18
  export * from './components/powered-by-queek';
19
19
  export * from './components/language-switcher';
20
+ export * from './components/market-switcher';
20
21
  export * from './components/default-metaobject-page';
21
22
  export * from './components/product-media-frame';
22
23
  export * from './components/variant-picker';
@@ -33,6 +34,7 @@ export * from './api/collections';
33
34
  export * from './api/orders';
34
35
  export * from './hooks/use-href';
35
36
  export * from './hooks/use-locales';
37
+ export * from './hooks/use-markets';
36
38
  export * from './hooks/use-auth';
37
39
  export * from './hooks/use-cart';
38
40
  export * from './hooks/use-shop-cart';
@@ -8,7 +8,7 @@ import { useStorefront } from '../../provider';
8
8
  import { useHref } from '../../hooks/use-href';
9
9
  import { useShopCart } from '../../hooks/use-shop-cart';
10
10
  import { useCartPanelStore } from '../../stores/cart-panel-store';
11
- import { normalizeCurrencyCode } from '../../utils/format';
11
+ import { useDisplayCurrency } from '../../hooks/use-markets';
12
12
  import type { CartServerPricing } from '../../utils/cart-pricing';
13
13
 
14
14
  /** What {@link CartPanelController} hands to your render function: the panel state, this shop's lines, and the actions that change them. */
@@ -45,6 +45,7 @@ export function CartPanelController({
45
45
  children: (props: CartPanelControllerRenderProps) => ReactNode;
46
46
  }): JSX.Element {
47
47
  const { vendor } = useStorefront();
48
+ const currency = useDisplayCurrency();
48
49
  const href = useHref();
49
50
  const router = useRouter();
50
51
  const isOpen = useCartPanelStore((state) => state.isOpen);
@@ -75,9 +76,9 @@ export function CartPanelController({
75
76
  items,
76
77
  total,
77
78
  pricing,
78
- // Store-wide display uses the vendor's currency; item rows carry their own.
79
+ // Store-wide display uses the shopper's market currency, else the vendor's; item rows carry their own.
79
80
  // List-level meta.currency is never read (platform default, wrong per store).
80
- currency: normalizeCurrencyCode(vendor.currency),
81
+ currency,
81
82
  onClose: closePanel,
82
83
  onCheckout: () => navigate('/checkout'),
83
84
  onViewCart: () => navigate('/cart'),
@@ -0,0 +1,82 @@
1
+ 'use client';
2
+
3
+ import { useContext, type JSX, type ReactNode } from 'react';
4
+ import { StorefrontContext, useThemeStrings } from '../provider';
5
+ import { useMarkets, type MarketsState } from '../hooks/use-markets';
6
+ import type { StoreMarket } from '../utils/market';
7
+ import './language-switcher.css';
8
+
9
+ /** Props for `MarketSwitcher`. */
10
+ export interface MarketSwitcherProps {
11
+ /** Extra class on the root, to position or restyle the control. */
12
+ className?: string;
13
+ /**
14
+ * Take over the presentation. Called with the markets, the chosen one and
15
+ * `select`; whatever it returns renders instead of the default control.
16
+ * Still renders nothing on a store with no published market.
17
+ */
18
+ children?: (state: MarketsState & { label: string; labelFor: (market: StoreMarket | null) => string; displayName: (market: StoreMarket | null) => string }) => ReactNode;
19
+ }
20
+
21
+ /**
22
+ * The storefront's market control: the store's own currency plus each published
23
+ * market, one native select. Renders nothing outside a storefront or on a store
24
+ * with no published market, so it is safe to place unconditionally. Choosing an
25
+ * option reloads the page with every price in that currency; the choice is
26
+ * explicit and remembered for the store (nothing is guessed from the shopper's
27
+ * location). It reuses the language control's `qn-lang` look and tokens, so it
28
+ * mirrors in right-to-left storefronts.
29
+ *
30
+ * A theme that places this sets `marketSwitcher: 'theme'` in its manifest, so
31
+ * the storefront does not also render its own floating control.
32
+ */
33
+ export function MarketSwitcher(props: MarketSwitcherProps): JSX.Element | null {
34
+ const inStorefront = useContext(StorefrontContext) !== null;
35
+ if (!inStorefront) return null;
36
+ return <MarketSwitcherInner {...props} />;
37
+ }
38
+
39
+ function MarketSwitcherInner({ className, children }: MarketSwitcherProps): JSX.Element | null {
40
+ const t = useThemeStrings();
41
+ const state = useMarkets();
42
+ const { markets, hasMarkets, active, shopCurrency, select } = state;
43
+
44
+ if (!hasMarkets) return null;
45
+
46
+ const label = t('market.label');
47
+ // The store's own currency is its bare ISO code: a localized currency name can differ between the server's ICU and
48
+ // the browser's, and a select whose text differs between the two does not hydrate cleanly.
49
+ const displayName = (market: StoreMarket | null): string => (market ? `${market.name} · ${market.currency}` : shopCurrency);
50
+ const labelFor = (market: StoreMarket | null): string => t('market.named', { name: displayName(market) });
51
+
52
+ if (children) return <>{children({ ...state, label, labelFor, displayName })}</>;
53
+
54
+ const rootClass = ['qn-lang', 'qn-lang--select', 'qn-market', className].filter(Boolean).join(' ');
55
+
56
+ return (
57
+ <div className={rootClass} role="group" aria-label={label} data-qn-market-switcher="" data-variant="select">
58
+ <svg className="qn-lang__icon" aria-hidden="true" viewBox="0 0 24 24" focusable="false">
59
+ <circle cx="12" cy="12" r="9" />
60
+ <path d="M14.5 9.2c-.4-.8-1.4-1.2-2.5-1.2-1.4 0-2.4.7-2.4 1.8 0 2.4 5 1.1 5 3.6 0 1.1-1.1 1.8-2.6 1.8-1.2 0-2.2-.5-2.6-1.4M12 6.5V8m0 8v1.5" />
61
+ </svg>
62
+ <span className="qn-lang__field">
63
+ <select
64
+ className="qn-lang__select"
65
+ aria-label={labelFor(active)}
66
+ value={active ? String(active.id) : ''}
67
+ onChange={(event) => select(event.target.value === '' ? null : Number(event.target.value))}
68
+ >
69
+ <option value="">{displayName(null)}</option>
70
+ {markets.map((market) => (
71
+ <option key={market.id} value={String(market.id)}>
72
+ {displayName(market)}
73
+ </option>
74
+ ))}
75
+ </select>
76
+ <svg className="qn-lang__chevron" aria-hidden="true" viewBox="0 0 10 10" focusable="false">
77
+ <path d="M1 3.5 5 7.5 9 3.5" />
78
+ </svg>
79
+ </span>
80
+ </div>
81
+ );
82
+ }
@@ -0,0 +1,55 @@
1
+ 'use client';
2
+
3
+ import { useCallback, useContext, useMemo } from 'react';
4
+ import { StorefrontContext } from '../provider';
5
+ import { chooseMarket } from '../utils/market-choice';
6
+ import { normalizeCurrencyCode } from '../utils/format';
7
+ import type { StoreMarket } from '../utils/market';
8
+
9
+ export interface MarketsState {
10
+ /** The store's published markets. Empty on a store that sells in its own currency only. */
11
+ markets: StoreMarket[];
12
+ /** More than zero published markets: whether a market choice makes sense at all. */
13
+ hasMarkets: boolean;
14
+ /** The market the shopper chose, or null for the store's own currency. */
15
+ active: StoreMarket | null;
16
+ /** The store's own currency (ISO 4217). */
17
+ shopCurrency: string;
18
+ /** The currency prices are shown and charged in: the active market's, else the store's own. */
19
+ displayCurrency: string;
20
+ /** Chooses a market (`null` = the store's own currency) and reloads the page in it. */
21
+ select: (marketId: number | null) => void;
22
+ }
23
+
24
+ /**
25
+ * The store's markets and the shopper's choice, for a theme that builds its own
26
+ * currency control. Reads what the host passed to `StorefrontProvider`; outside a
27
+ * provider, or on a store with no published market, it reports no markets and
28
+ * the store's own currency. Most themes want `MarketSwitcher` instead.
29
+ */
30
+ export function useMarkets(): MarketsState {
31
+ const context = useContext(StorefrontContext);
32
+ const markets = context?.markets;
33
+ const activeMarketId = context?.activeMarketId ?? null;
34
+ const vendorSlug = context?.vendor.slug ?? '';
35
+ const vendorId = context?.vendor.id ?? '';
36
+ const shopCurrency = normalizeCurrencyCode(context?.vendor.currency);
37
+
38
+ const list = useMemo(() => markets ?? [], [markets]);
39
+ const active = useMemo(() => list.find((m) => m.id === activeMarketId) ?? null, [list, activeMarketId]);
40
+ const select = useCallback((marketId: number | null) => chooseMarket(vendorSlug, vendorId, marketId), [vendorSlug, vendorId]);
41
+
42
+ return useMemo(
43
+ () => ({ markets: list, hasMarkets: list.length > 0, active, shopCurrency, displayCurrency: active?.currency ?? shopCurrency, select }),
44
+ [list, active, shopCurrency, select],
45
+ );
46
+ }
47
+
48
+ /**
49
+ * The ISO currency code store-wide amounts (cart totals, delivery, checkout) are
50
+ * shown in: the shopper's market currency, else the store's own. A product price
51
+ * reads its own `currency`, which the API already answers in the market currency.
52
+ */
53
+ export function useDisplayCurrency(): string {
54
+ return useMarkets().displayCurrency;
55
+ }
package/index.ts CHANGED
@@ -48,6 +48,7 @@ export * from './utils/cart-pricing';
48
48
  export * from './utils/announcement';
49
49
  export * from './utils/locale';
50
50
  export * from './utils/locale-switch';
51
+ export * from './utils/market';
51
52
 
52
53
  // Theme strings — the pure/server-safe i18n core (no next/*, no React).
53
54
  export * from './strings/theme-strings';
@@ -181,5 +181,9 @@
181
181
  "embed": {
182
182
  "placeholder": "Paste the link or embed code of the content you want to show",
183
183
  "title": "Embedded content"
184
+ },
185
+ "market": {
186
+ "label": "Currency",
187
+ "named": "Currency: {name}"
184
188
  }
185
189
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usequeek/theme-kit",
3
- "version": "0.1.30",
3
+ "version": "0.1.31",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "description": "The runtime a Queek storefront theme is built on: hooks, stores, page renderer, navigation, shared blocks and locale strings.",
package/provider.tsx CHANGED
@@ -1,7 +1,7 @@
1
1
  'use client';
2
2
 
3
3
  import type { JSX } from 'react';
4
- import { createContext, useContext, useMemo, useRef, type ReactNode } from 'react';
4
+ import { createContext, useContext, useEffect, useMemo, useRef, type ReactNode } from 'react';
5
5
  import type { Menu } from './types/menu';
6
6
  import type { ReviewItem } from './types/block';
7
7
  import type { Post } from './types/page';
@@ -10,6 +10,8 @@ import type { StorefrontConfig, VendorProfile } from './types/vendor';
10
10
  import { getBrandCssVariables } from './utils/brand';
11
11
  import { parseLocaleCode } from './utils/locale';
12
12
  import { normalizeStoreLocales, type StoreLocale, type StoreLocaleInput } from './utils/locale-switch';
13
+ import { normalizeStoreMarkets, parseMarketId, setBrowserMarketId, type StoreMarket } from './utils/market';
14
+ import { reconcileMarketChoice } from './utils/market-choice';
13
15
  import {
14
16
  defaultThemeStrings,
15
17
  t as translateThemeStrings,
@@ -59,6 +61,10 @@ interface StorefrontContextValue {
59
61
  * `LanguageSwitcher` renders nothing. Optional so hand-built context values
60
62
  * keep compiling without it. */
61
63
  locales?: StoreLocale[];
64
+ /** The store's published markets (empty or omitted = the store sells in its own currency only: no picker, no `?market`). */
65
+ markets?: StoreMarket[];
66
+ /** The market the shopper chose, only when it is one of `markets`; null = the store's own currency. */
67
+ activeMarketId?: number | null;
62
68
  }
63
69
 
64
70
  /** The context behind {@link StorefrontProvider}. Read it through the hooks; use it directly only to test for a provider without throwing. */
@@ -88,6 +94,8 @@ export function StorefrontProvider({
88
94
  locale,
89
95
  strings,
90
96
  locales,
97
+ markets,
98
+ market,
91
99
  children,
92
100
  }: {
93
101
  vendor: VendorProfile;
@@ -122,6 +130,19 @@ export function StorefrontProvider({
122
130
  * owns it, like `basePath`.
123
131
  */
124
132
  locales?: readonly StoreLocaleInput[] | null;
133
+ /**
134
+ * The store's published markets, as `GET /client/store/markets` lists them,
135
+ * resolved by the host. Optional — absent or empty means no market choice:
136
+ * `MarketSwitcher` renders nothing and every request stays as before. Themes
137
+ * never set this; the host owns it.
138
+ */
139
+ markets?: readonly unknown[] | null;
140
+ /**
141
+ * The market id the shopper chose (the host reads it from the store's market
142
+ * cookie). Honoured only when it names one of `markets`; anything else is the
143
+ * store's own currency.
144
+ */
145
+ market?: number | string | null;
125
146
  children: ReactNode;
126
147
  }): JSX.Element {
127
148
  const resolvedBasePath = basePath ?? `/${vendor.slug ?? ''}`;
@@ -136,6 +157,18 @@ export function StorefrontProvider({
136
157
  [strings],
137
158
  );
138
159
  const resolvedLocales = useMemo(() => normalizeStoreLocales(locales), [locales]);
160
+ const resolvedMarkets = useMemo(() => normalizeStoreMarkets(markets), [markets]);
161
+ const marketsKnown = Array.isArray(markets);
162
+ const requestedMarket = parseMarketId(market);
163
+ const activeMarketId = resolvedMarkets.some((m) => m.id === requestedMarket) ? requestedMarket : null;
164
+ // Browser transports read the market per request. Idempotent and a no-op on the server.
165
+ setBrowserMarketId(activeMarketId);
166
+ const vendorSlug = vendor.slug ?? '';
167
+ const vendorId = vendor.id;
168
+ useEffect(() => {
169
+ // A cookie naming a market the store no longer publishes: drop it (and the lines priced under it) once.
170
+ reconcileMarketChoice(vendorSlug, vendorId, marketsKnown ? resolvedMarkets : null);
171
+ }, [vendorSlug, vendorId, resolvedMarkets, marketsKnown]);
139
172
  const value = useMemo(
140
173
  () => ({
141
174
  vendor,
@@ -147,8 +180,10 @@ export function StorefrontProvider({
147
180
  locale: resolvedLocale,
148
181
  strings: resolvedStrings,
149
182
  locales: resolvedLocales,
183
+ markets: resolvedMarkets,
184
+ activeMarketId,
150
185
  }),
151
- [config, menus, previewData, vendor, resolvedBasePath, pagesChrome, resolvedLocale, resolvedStrings, resolvedLocales],
186
+ [config, menus, previewData, vendor, resolvedBasePath, pagesChrome, resolvedLocale, resolvedStrings, resolvedLocales, resolvedMarkets, activeMarketId],
152
187
  );
153
188
  const brandRootRef = useRef<HTMLDivElement>(null);
154
189
 
package/sdk/client.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { getActivePlatform } from './platform';
2
+ import { getBrowserMarketId, isMarketPricedPath, withMarketQuery } from '../utils/market';
2
3
 
3
4
  const LOCAL_API_URL = 'http://127.0.0.1:8000/api/v1';
4
5
  const API_URL_FROM_ENV = process.env.QUEEK_API_URL ?? process.env.NEXT_PUBLIC_QUEEK_API_URL;
@@ -356,12 +357,16 @@ export function createBrowserClient(vendorSlug?: string, token?: string): {
356
357
  return headers;
357
358
  };
358
359
 
360
+ // The shopper's market, on priced paths only; no market leaves the query untouched.
361
+ const marketFor = (path: string): number | null => (isMarketPricedPath(path) ? getBrowserMarketId() : null);
362
+
359
363
  return {
360
364
  get: <T>(path: string, query?: RequestOptions['query']) =>
361
- request<T>(PUBLIC_API_BASE_URL, `/client/store${path}`, { query, timeoutMs: BROWSER_GET_TIMEOUT_MS }, buildHeaders()),
365
+ request<T>(PUBLIC_API_BASE_URL, `/client/store${path}`, { query: withMarketQuery(query, marketFor(path)), timeoutMs: BROWSER_GET_TIMEOUT_MS }, buildHeaders()),
362
366
  post: <T>(path: string, body?: unknown) =>
363
367
  request<T>(PUBLIC_API_BASE_URL, `/client/store${path}`, {
364
368
  method: 'POST',
369
+ query: withMarketQuery(undefined, marketFor(path)),
365
370
  body: body ? JSON.stringify(body) : undefined,
366
371
  timeoutMs: BROWSER_POST_TIMEOUT_MS,
367
372
  }, buildHeaders()),
@@ -3,6 +3,7 @@
3
3
  import { createQueekClient, type QueekClientInstance, type StorageAdapter } from '@usequeek/client-sdk';
4
4
  import { triggerReauth } from './error-handler';
5
5
  import { getActivePlatform } from './platform';
6
+ import { getBrowserMarketId, isMarketPricedPath, withMarketPath } from '../utils/market';
6
7
 
7
8
  // This file is 'use client' — every export here only ever runs in the browser.
8
9
  // ALWAYS same-origin-relative, on purpose: the host app's `next.config` rewrite
@@ -35,7 +36,8 @@ const localStorageAdapter: StorageAdapter = {
35
36
  * the rest of the site stays `storefront`. Reads the holder per request, so a
36
37
  * single cached client serves both platforms.
37
38
  */
38
- const platformFetch: typeof fetch = (input, init) => {
39
+ const platformFetch: typeof fetch = (rawInput, init) => {
40
+ const input = withActiveMarket(rawInput);
39
41
  if (init?.headers) {
40
42
  const headers = new Headers(init.headers);
41
43
  headers.set('X-Platform', getActivePlatform());
@@ -44,6 +46,20 @@ const platformFetch: typeof fetch = (input, init) => {
44
46
  return fetch(input, init).then(captureRequestId);
45
47
  };
46
48
 
49
+ /**
50
+ * The shopper's market rides every priced store call as `?market=<id>` (reads,
51
+ * cart writes, the quote and the order): the one place the SDK-backed client
52
+ * learns it, so no caller can forget it. No market chosen: the URL is untouched.
53
+ * The SDK always hands `fetch` a string URL; anything else passes through.
54
+ */
55
+ function withActiveMarket(input: RequestInfo | URL): RequestInfo | URL {
56
+ const marketId = getBrowserMarketId();
57
+ if (marketId === null || typeof input !== 'string' || !input.includes('/client/store/') || !isMarketPricedPath(input)) {
58
+ return input;
59
+ }
60
+ return withMarketPath(input, marketId);
61
+ }
62
+
47
63
  /**
48
64
  * Every API response carries a request id. The SDK's `request()` returns only
49
65
  * the parsed body, so this wrapper — the one place every SDK call's raw Response
@@ -1,6 +1,7 @@
1
- import { headers } from 'next/headers';
1
+ import { cookies, headers } from 'next/headers';
2
2
  import { resolveCustomDomainVendorSlug, resolveCustomDomainVendorSlugRemote, resolveSubdomainVendorSlug } from '../utils/vendor-host';
3
3
  import { LOCALE_CODE_HEADER, parseLocaleCode, withLocaleQuery, withLocaleTags } from '../utils/locale';
4
+ import { isMarketPricedPath, readMarketFromCookieString, withMarketQuery } from '../utils/market';
4
5
  import { API_BASE_URL, request, type RequestCachePolicy, type RequestOptions } from './client';
5
6
  import { getActivePlatform } from './platform';
6
7
 
@@ -190,7 +191,43 @@ export function withLocaleCachePolicy(
190
191
  return { revalidate: policy.revalidate, tags: withLocaleTags(policy.tags, locale) };
191
192
  }
192
193
 
193
- export function createServerStoreClient(vendorSlug: string, origin?: string): {
194
+ /**
195
+ * The market the shopper chose for this store (its cookie), for a server read.
196
+ * Never throws: outside a request scope there is no cookie, which reads as the
197
+ * store's own currency. `verify` (see {@link ServerStoreClientOptions}) lets the
198
+ * host confirm the id against the store's market list; without it only the id's
199
+ * shape is checked and the API answers in the store's currency for an id it does
200
+ * not offer, so a stale cookie can never price anything wrongly.
201
+ */
202
+ export async function readRequestMarket(vendorSlug: string, verify?: (marketId: number) => Promise<boolean>): Promise<number | null> {
203
+ let marketId: number | null;
204
+ try {
205
+ marketId = readMarketFromCookieString((await cookies()).toString(), vendorSlug);
206
+ } catch {
207
+ return null;
208
+ }
209
+
210
+ if (marketId === null || !verify) return marketId;
211
+
212
+ try {
213
+ return (await verify(marketId)) ? marketId : null;
214
+ } catch {
215
+ return null;
216
+ }
217
+ }
218
+
219
+ /** Options of {@link createServerStoreClient}. */
220
+ export interface ServerStoreClientOptions {
221
+ /**
222
+ * Decides, per request, whether the shopper's market cookie names a market the store really offers. A host that
223
+ * reads the store's market list passes it, so the server prices in a market only when the page and the browser
224
+ * will: a cookie the host cannot confirm (an unpublished market, a failed list read) reads as the store currency.
225
+ * Omitted: the cookie's shape is all that is checked and the API answers in the store currency for an unknown id.
226
+ */
227
+ verifyMarket?: (marketId: number) => Promise<boolean>;
228
+ }
229
+
230
+ export function createServerStoreClient(vendorSlug: string, origin?: string, options: ServerStoreClientOptions = {}): {
194
231
  get: <T>(path: string, query?: RequestOptions['query'], locale?: string) => Promise<T>;
195
232
  post: <T>(path: string, body?: unknown) => Promise<T>;
196
233
  } {
@@ -211,13 +248,17 @@ export function createServerStoreClient(vendorSlug: string, origin?: string): {
211
248
  // suffix on every cache tag).
212
249
  get: async <T>(path: string, query?: RequestOptions['query'], locale?: string) => {
213
250
  const code = await resolveRequestLocale(locale);
251
+ // A shopper in a market gets prices in its currency: `?market=<id>` on the priced reads, and those reads
252
+ // leave the shared data cache. The cache is shared by every visitor, its key is the URL, and a rate moves
253
+ // without any revalidation tag, so a market price is never stored there. No market: today's request.
254
+ const marketId = isMarketPricedPath(path) ? await readRequestMarket(vendorSlug, options.verifyMarket) : null;
214
255
  return request<T>(
215
256
  API_BASE_URL,
216
257
  `/client/store${path}`,
217
258
  {
218
- query: withLocaleQuery(query, code),
259
+ query: withMarketQuery(withLocaleQuery(query, code), marketId),
219
260
  timeoutMs: SSR_TIMEOUT_MS,
220
- cachePolicy: (await isPreviewRender())
261
+ cachePolicy: marketId !== null || (await isPreviewRender())
221
262
  ? null
222
263
  : withLocaleCachePolicy(resolveCachePolicy(vendorSlug, path, query), code),
223
264
  },
@@ -107,6 +107,34 @@ function propertiesSuffix(properties?: Record<string, unknown> | null): string {
107
107
  return `~p-${(fnv1a(json, 0x811c9dc5) + fnv1a(json, 0x9e3779b9)).slice(0, 12)}`;
108
108
  }
109
109
 
110
+ const CART_STORAGE_NAME = 'queek-storefront-cart';
111
+
112
+ /**
113
+ * Removes one shop's lines from the PERSISTED cart without touching the live
114
+ * store, for a page that is about to reload. A shopper who changes market gets
115
+ * every price in another currency, and a line keeps the unit price it was added
116
+ * at, so it must not survive into the new currency; the server cart still holds
117
+ * the lines and the reload adopts them re-priced. Changing the live store here
118
+ * would make the cart sync delete that server copy, so this writes storage only.
119
+ */
120
+ export function dropPersistedShopLines(shopId: string): void {
121
+ const storage = platformScopedStorage();
122
+
123
+ try {
124
+ const raw = storage.getItem(CART_STORAGE_NAME);
125
+ if (!raw) return;
126
+
127
+ const persisted = JSON.parse(raw) as { state?: { items?: CartItem[] } };
128
+ if (!Array.isArray(persisted.state?.items)) return;
129
+
130
+ persisted.state.items = persisted.state.items.filter((entry) => entry.shop_id !== shopId);
131
+ storage.setItem(CART_STORAGE_NAME, JSON.stringify(persisted));
132
+ } catch {
133
+ // Unreadable storage holds nothing worth keeping; the reload starts from the server cart.
134
+ storage.removeItem(CART_STORAGE_NAME);
135
+ }
136
+ }
137
+
110
138
  /**
111
139
  * The cart store. Prefer the `useCart()` and `useShopCart()` hooks; read this
112
140
  * directly only from non-React code (`useCartStore.getState()`). Lines persist
@@ -254,7 +282,7 @@ export const useCartStore = create<CartState>()(
254
282
  },
255
283
  }),
256
284
  {
257
- name: 'queek-storefront-cart',
285
+ name: CART_STORAGE_NAME,
258
286
  storage: createJSONStorage(platformScopedStorage),
259
287
  },
260
288
  ),
package/types/theme.ts CHANGED
@@ -389,6 +389,13 @@ export interface ThemeManifest {
389
389
  * it keeps the storefront's control for multi-language stores.
390
390
  */
391
391
  languageSwitcher?: 'theme';
392
+ /**
393
+ * Set to `'theme'` when the theme places the kit's `MarketSwitcher` itself.
394
+ * The storefront then does not also render its own floating market control.
395
+ * Optional — a manifest without it keeps the storefront's control, which
396
+ * shows only on a store with a published market.
397
+ */
398
+ marketSwitcher?: 'theme';
392
399
  }
393
400
 
394
401
  /**
@@ -0,0 +1,38 @@
1
+ import { dropPersistedShopLines } from '../stores/cart-store';
2
+ import { marketCookieWrite, readMarketFromCookieString, type StoreMarket } from './market';
3
+
4
+ /**
5
+ * Browser-only: records the shopper's market for this store and reloads.
6
+ *
7
+ * A market changes every price on the page, the cart and the checkout, and the
8
+ * server render reads the same cookie, so the one correct way to apply it is a
9
+ * full load: no price from the previous currency survives in a client cache,
10
+ * a store or an already rendered page. The store's cart lines are dropped from
11
+ * the persisted cart first, because a line keeps the unit price it was added at
12
+ * (see `dropPersistedShopLines`); the server cart re-prices them on the reload.
13
+ *
14
+ * `null` returns the shopper to the store's own currency.
15
+ */
16
+ export function chooseMarket(vendorSlug: string, vendorId: string, marketId: number | null): void {
17
+ if (typeof window === 'undefined') return;
18
+
19
+ document.cookie = marketCookieWrite(vendorSlug, marketId);
20
+ dropPersistedShopLines(vendorId);
21
+ window.location.reload();
22
+ }
23
+
24
+ /**
25
+ * Clears a choice the store no longer offers (its market was unpublished or
26
+ * deleted), once. Runs only when the host resolved the store's market list
27
+ * (a failed read passes none, and a shopper's choice is never dropped on a blip).
28
+ */
29
+ export function reconcileMarketChoice(vendorSlug: string, vendorId: string, published: readonly StoreMarket[] | null): void {
30
+ if (typeof window === 'undefined' || published === null || !vendorSlug) return;
31
+
32
+ const chosen = readMarketFromCookieString(document.cookie, vendorSlug);
33
+ if (chosen === null || published.some((market) => market.id === chosen)) return;
34
+
35
+ document.cookie = marketCookieWrite(vendorSlug, null);
36
+ dropPersistedShopLines(vendorId);
37
+ window.location.reload();
38
+ }
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Storefront market transport (markets.currency).
3
+ *
4
+ * A store may publish markets: a set of countries plus one currency. The shopper
5
+ * picks one explicitly (no geo switch), the API then answers prices in that
6
+ * currency when a read carries `?market=<id>`, and an order carries the rate pin
7
+ * the cart or quote issued (`market_pin` in the order body).
8
+ *
9
+ * The choice lives in a cookie, so the server render and the browser agree on
10
+ * it. It is per store: the cookie name carries the store slug, because
11
+ * path-based stores share one host. Like `utils/locale.ts` this module is pure
12
+ * (no `next/*`, no React) and every function returns its input untouched when no
13
+ * market is chosen, so a store without a published market behaves exactly as
14
+ * before.
15
+ */
16
+
17
+ /** One published market of the store, as `GET /client/store/markets` lists it. */
18
+ export interface StoreMarket {
19
+ /** The integer id a read sends back as `?market=`. */
20
+ id: number;
21
+ name: string;
22
+ /** ISO 3166-1 alpha-2 codes the market sells to. */
23
+ countries: string[];
24
+ /** ISO 4217 code prices are shown and charged in. */
25
+ currency: string;
26
+ }
27
+
28
+ import { getActivePlatform } from '../sdk/platform';
29
+
30
+ const MARKET_ID_MAX_LENGTH = 18;
31
+ const COOKIE_PREFIX = 'queek_market_';
32
+ export const MARKET_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 365;
33
+
34
+ /** The market id a request names, or null. Only short digit strings qualify, so nothing odd reaches the API or a cache key. */
35
+ export function parseMarketId(value: unknown): number | null {
36
+ const text = typeof value === 'number' && Number.isInteger(value) ? String(value) : value;
37
+ if (typeof text !== 'string' || text.length === 0 || text.length > MARKET_ID_MAX_LENGTH || !/^\d+$/.test(text)) {
38
+ return null;
39
+ }
40
+ const id = Number(text);
41
+ return Number.isSafeInteger(id) && id > 0 ? id : null;
42
+ }
43
+
44
+ /** Cookie holding the shopper's market for one store. Slug characters outside the cookie-name set become `_`. */
45
+ export function marketCookieName(vendorSlug: string): string {
46
+ return `${COOKIE_PREFIX}${vendorSlug.replace(/[^A-Za-z0-9_-]/g, '_')}`;
47
+ }
48
+
49
+ /** The market id in a `Cookie` header / `document.cookie` string for this store, or null. */
50
+ export function readMarketFromCookieString(cookieString: string | null | undefined, vendorSlug: string): number | null {
51
+ if (!cookieString) return null;
52
+ const name = marketCookieName(vendorSlug);
53
+ for (const part of cookieString.split(';')) {
54
+ const [key, ...rest] = part.trim().split('=');
55
+ if (key === name) return parseMarketId(rest.join('='));
56
+ }
57
+ return null;
58
+ }
59
+
60
+ /** The `Set-Cookie`-style value a browser write uses; `null` clears the choice. */
61
+ export function marketCookieWrite(vendorSlug: string, marketId: number | null): string {
62
+ const name = marketCookieName(vendorSlug);
63
+ return marketId === null
64
+ ? `${name}=; Path=/; Max-Age=0; SameSite=Lax`
65
+ : `${name}=${marketId}; Path=/; Max-Age=${MARKET_COOKIE_MAX_AGE_SECONDS}; SameSite=Lax`;
66
+ }
67
+
68
+ type QueryRecord = Record<string, string | number | boolean | string[] | null | undefined>;
69
+
70
+ /** Adds `?market=<id>` to a backend query. No market: the input is returned untouched (same reference). */
71
+ export function withMarketQuery<T extends QueryRecord>(
72
+ query: T | undefined,
73
+ marketId: number | null | undefined,
74
+ ): T | (T & { market: string }) | undefined {
75
+ const id = parseMarketId(marketId);
76
+ if (id === null) return query;
77
+ return { ...(query ?? ({} as T)), market: String(id) };
78
+ }
79
+
80
+ /** Appends `market=<id>` to a built URL or path. No market: the input is returned untouched. */
81
+ export function withMarketPath(path: string, marketId: number | null | undefined): string {
82
+ const id = parseMarketId(marketId);
83
+ if (id === null || /[?&]market=/.test(path)) return path;
84
+ const hash = path.indexOf('#');
85
+ const head = hash === -1 ? path : path.slice(0, hash);
86
+ const tail = hash === -1 ? '' : path.slice(hash);
87
+ return `${head}${head.includes('?') ? '&' : '?'}market=${id}${tail}`;
88
+ }
89
+
90
+ /**
91
+ * Whether a store read carries prices (or a price-dependent quote): the only
92
+ * calls that take `?market`. The same list decides which server reads leave the
93
+ * shared data cache for a shopper in a market.
94
+ */
95
+ export function isMarketPricedPath(path: string): boolean {
96
+ const clean = (path.split(/[?#]/)[0] ?? '').replace(/^(?:\/api\/v1)?(?:\/client\/store)?/, '');
97
+ // Anchored at the first segment: a page called "cart", a product's reviews or an order's pay link are not priced reads.
98
+ return (
99
+ /^\/products(?:\/[^/]+(?:\/related)?)?\/?$/.test(clean) ||
100
+ /^\/(?:collections|categories|promotions|search|shipping-zones|fulfillment|shipping|checkout|payment-methods|cart|wishlist-items)(?:\/|$)/.test(clean) ||
101
+ /^\/order\/checkout\/?$/.test(clean)
102
+ );
103
+ }
104
+
105
+ /**
106
+ * The market of the running browser page. `Provider` sets it from what the host
107
+ * validated; the browser transports read it per request. Server code never
108
+ * touches it (module state is shared between requests there). Markets are a
109
+ * storefront feature: the in-store QR channel never carries one.
110
+ */
111
+ let browserMarketId: number | null = null;
112
+
113
+ export function setBrowserMarketId(marketId: number | null): void {
114
+ if (typeof window === 'undefined') return;
115
+ browserMarketId = parseMarketId(marketId);
116
+ }
117
+
118
+ export function getBrowserMarketId(): number | null {
119
+ return typeof window === 'undefined' || getActivePlatform() !== 'storefront' ? null : browserMarketId;
120
+ }
121
+
122
+ /** Normalises the `store/markets` payload; anything malformed is dropped, so a bad row never reaches a picker. */
123
+ export function normalizeStoreMarkets(input: unknown): StoreMarket[] {
124
+ if (!Array.isArray(input)) return [];
125
+ const markets: StoreMarket[] = [];
126
+ for (const row of input as Array<Record<string, unknown> | null>) {
127
+ const id = parseMarketId(row?.id);
128
+ const currency = typeof row?.currency === 'string' ? row.currency.trim().toUpperCase() : '';
129
+ if (id === null || !/^[A-Z]{3}$/.test(currency) || typeof row?.name !== 'string' || row.name === '') continue;
130
+ markets.push({
131
+ id,
132
+ name: row.name,
133
+ countries: Array.isArray(row.countries) ? row.countries.filter((c): c is string => typeof c === 'string') : [],
134
+ currency,
135
+ });
136
+ }
137
+ return markets;
138
+ }
139
+
140
+ /** The refusal codes the market gates answer with, to branch on instead of a message. */
141
+ export const MARKET_ERROR_CODES = [
142
+ 'market_rate_changed',
143
+ 'market_unavailable',
144
+ 'market_payment_unavailable',
145
+ 'market_price_unusable',
146
+ 'market_method_unavailable',
147
+ 'market_delivery_unavailable',
148
+ 'market_cart_required',
149
+ // A market order older than markets.order_rate_ttl_hours: GET orders/{id}/pay answers 422, no link, order again.
150
+ 'market_rate_expired',
151
+ // 422 at the quote and the order (and cart `market.unavailable`): the market total is zero or below the provider minimum.
152
+ 'market_total_unusable',
153
+ ] as const;
154
+
155
+ export type MarketErrorCode = (typeof MARKET_ERROR_CODES)[number];
156
+
157
+ /** The market refusal an API failure carries, with its body data (`market` block, fresh `quote`), or null. */
158
+ export interface MarketRefusal {
159
+ code: MarketErrorCode;
160
+ status: number;
161
+ message: string;
162
+ /** `data.market`: the market block with a NEW pin on a 409 `market_rate_changed`; null on `market_unavailable`. */
163
+ market: { id: number; name: string; currency: string; pin: string } | null;
164
+ /** `data.quote`: the cart priced at the current rate, when the API could price it. */
165
+ quote: Record<string, unknown> | null;
166
+ }
167
+
168
+ export function asMarketRefusal(error: unknown): MarketRefusal | null {
169
+ const failure = error as { status?: unknown; code?: unknown; message?: unknown; details?: unknown; data?: unknown } | null;
170
+ if (!failure || typeof failure !== 'object') return null;
171
+
172
+ const code = MARKET_ERROR_CODES.find((candidate) => candidate === failure.code);
173
+ if (!code || typeof failure.status !== 'number') return null;
174
+
175
+ const body = (failure.details ?? failure.data ?? null) as { market?: unknown; quote?: unknown } | null;
176
+ const market = body?.market as { id?: unknown; name?: unknown; currency?: unknown; pin?: unknown } | null | undefined;
177
+ const marketId = parseMarketId(market?.id);
178
+
179
+ return {
180
+ code,
181
+ status: failure.status,
182
+ message: typeof failure.message === 'string' ? failure.message : '',
183
+ market:
184
+ marketId !== null && typeof market?.name === 'string' && typeof market?.currency === 'string' && typeof market?.pin === 'string'
185
+ ? { id: marketId, name: market.name, currency: market.currency, pin: market.pin }
186
+ : null,
187
+ quote: body?.quote && typeof body.quote === 'object' ? (body.quote as Record<string, unknown>) : null,
188
+ };
189
+ }