@thorprovider/storefront 0.15.0 → 0.15.1

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/README.md CHANGED
@@ -196,10 +196,15 @@ scopes the store, `MEDUSA_REGION_ID` supplies currency, countries, and shipping,
196
196
 
197
197
  `THOR_DATA_SOURCE` selects the mode **explicitly** and is never inferred from a failure.
198
198
  `mock` renders labelled demo data and resolves a fixture store context in code (channel
199
- `mock-sales-channel`, region `mock-region-us`, currency `USD`), so no context variables
200
- are required. `medusa` uses the real backend: a missing provider or invalid config is a
201
- **visible error** — never a silent fallback to demo data. Run `storefront setup`, then
202
- restart `yarn dev`.
199
+ `mock-sales-channel`, region `mock-region-uy`, currency `UYU`, locale `es-UY`), so no
200
+ context variables are required. `medusa` uses the real backend: a missing provider or
201
+ invalid config is a **visible error** — never a silent fallback to demo data. Run
202
+ `storefront setup`, then restart `yarn dev`.
203
+
204
+ `THOR_STORE_LOCALE` (BCP-47, e.g. `es-UY`) is the store's single shopper locale: it
205
+ governs `<html lang>` and every monetary surface — cart, cart sheet, checkout summary
206
+ and order confirmation all format with it. Optional; unset or blank falls back to
207
+ `es-UY`, matching the mock Uruguay region.
203
208
 
204
209
  ### Feature capability gating
205
210
 
@@ -8,6 +8,7 @@ import { readCartStateForRender } from '@/lib/__STOREFRONT__/cart-state'
8
8
  import { readAccountSession } from '@/lib/__STOREFRONT__/account-session'
9
9
  import { toAccountInitialState } from '@/lib/__STOREFRONT__/account-session.core'
10
10
  import { mountedFeatureNames, backendCapabilities } from '@/lib/__STOREFRONT__/composition'
11
+ import { getStoreLocale } from '@/lib/__STOREFRONT__/store-context'
11
12
  import { StorefrontRenderer } from './renderer'
12
13
 
13
14
  export const { generateMetadata, generateStaticParams } = __STOREFRONT_CAMEL__App
@@ -59,6 +60,11 @@ export default async function Page({
59
60
  const initialState = {
60
61
  ...(data.initialState ?? {}),
61
62
  navCategories,
63
+ // The shopper locale is resolved server-side (env-backed) and seeded for
64
+ // every route so the client registries build the same money formatter the
65
+ // shell's `<html lang>` uses. `getStoreLocale` never throws, so a
66
+ // misconfigured context still renders its visible cart/config error.
67
+ storeLocale: getStoreLocale(),
62
68
  ...cartState,
63
69
  ...accountState,
64
70
  }
@@ -5,7 +5,7 @@ import { Geist } from 'next/font/google'
5
5
  import { ThemeProvider } from 'next-themes'
6
6
  import { StorefrontProvider } from '@thorprovider/runtime/host-glue/providers'
7
7
  import { registry } from '@/lib/__STOREFRONT__/registry'
8
- import { getSiteUrl } from '@/lib/__STOREFRONT__/store-context'
8
+ import { getSiteUrl, getStoreLocale } from '@/lib/__STOREFRONT__/store-context'
9
9
  import './globals.css'
10
10
 
11
11
  const geist = Geist({
@@ -32,7 +32,7 @@ export default function RootLayout({
32
32
  children,
33
33
  }: Readonly<{ children: React.ReactNode }>) {
34
34
  return (
35
- <html lang="es" className={geist.variable} suppressHydrationWarning>
35
+ <html lang={getStoreLocale()} className={geist.variable} suppressHydrationWarning>
36
36
  <body className="font-sans antialiased">
37
37
  <ThemeProvider attribute="class" defaultTheme="__STOREFRONT_MODE__" enableSystem>
38
38
  <StorefrontProvider registry={registry}>
@@ -99,7 +99,7 @@ import type {
99
99
  StorefrontOrder,
100
100
  StorefrontOrderLineView,
101
101
  } from './state.core'
102
- import { assertBackendConfigured, getDataSource, getStoreContext, type StoreDataSource } from './store-context'
102
+ import { assertBackendConfigured, getDataSource, getStoreContext, getStoreLocale, type StoreDataSource } from './store-context'
103
103
  // The query engine is imported through its server-safe subpath: the package
104
104
  // root is a client entry (`'use client'`), so a Server Action cannot call a
105
105
  // function exported from it (React refuses a client function on the server).
@@ -294,14 +294,21 @@ export function toCheckoutFieldErrors(errors: CheckoutFieldError[]): CheckoutFie
294
294
  return grouped
295
295
  }
296
296
 
297
- /** Map the runtime's discriminated completion to the host result union. */
298
- export function toPlaceOrderResult(result: CartCompletionResult): PlaceOrderResult {
297
+ /**
298
+ * Map the runtime's discriminated completion to the host result union. The
299
+ * confirmation carries the store's shopper locale; callers may pass it
300
+ * explicitly, otherwise it resolves from the host environment (server-side).
301
+ */
302
+ export function toPlaceOrderResult(
303
+ result: CartCompletionResult,
304
+ locale: string = getStoreLocale(),
305
+ ): PlaceOrderResult {
299
306
  if (result.type === 'order') {
300
307
  return {
301
308
  status: 'order',
302
309
  order: toStorefrontOrder(result.order),
303
310
  lines: toOrderLines(result.order),
304
- confirmation: toStorefrontConfirmation(result.order),
311
+ confirmation: toStorefrontConfirmation(result.order, locale),
305
312
  ...(result.paymentSummary ? { paymentSummary: result.paymentSummary } : {}),
306
313
  }
307
314
  }
@@ -122,8 +122,11 @@ function normalizeImageUrl(url: string | null | undefined): string | undefined {
122
122
  * Build the designer confirmation from the host-confirmed order. The order is
123
123
  * the single source: addresses, delivery method, payment label and totals are
124
124
  * only included when the backend reports them; the view omits what is absent.
125
+ * The caller supplies the store's shopper locale so the confirmation formats
126
+ * money identically to the cart and checkout (design D4) — never a hardcoded
127
+ * presentation locale.
125
128
  */
126
- export function toStorefrontConfirmation(order: Order): StorefrontConfirmation {
129
+ export function toStorefrontConfirmation(order: Order, locale: string): StorefrontConfirmation {
127
130
  const shippingAddress = order.shippingAddress
128
131
  const recipient = shippingAddress
129
132
  ? `${shippingAddress.firstName} ${shippingAddress.lastName}`.trim()
@@ -267,9 +270,9 @@ export function toStorefrontConfirmation(order: Order): StorefrontConfirmation {
267
270
  billingDetail: billing ? addressDetail(billing) : '',
268
271
  customerName,
269
272
  customerEmail: order.email,
270
- // The storefront's money presentation uses the design's en-US dollar
271
- // format; copy stays in the store language.
272
- locale: 'en-US',
273
+ // The store's shopper locale, supplied by the host from the store context;
274
+ // copy stays in the store language.
275
+ locale,
273
276
  currencyCode: order.total.currencyCode,
274
277
  }
275
278
  }
@@ -25,6 +25,7 @@ import { isAvailableMoney } from '@thorprovider/blocks/contracts'
25
25
  import type { Money } from '@thorprovider/types'
26
26
  import { catalog } from './catalog'
27
27
  import type { CartLineState, CartTotalsState } from './state'
28
+ import { createStoreMoneyFormatter, DEFAULT_STORE_LOCALE } from './store-context'
28
29
  import { useStorefrontHandlers } from './handlers'
29
30
  import { cartViewAvailable, checkoutAvailable, mountedFeatureNames } from './composition'
30
31
  import { accountStoreUser } from './account-user.core'
@@ -165,6 +166,14 @@ const baseComponents = {
165
166
  ) as AccountResolution | 'unresolved'
166
167
  const cart = (state.cart ?? []) as CartLineState[]
167
168
  const totals = state.cartTotals as CartTotalsState | null
169
+ // One money formatter for the whole shell, built from the shopper locale
170
+ // the catch-all host seeded (the same locale as `<html lang>`). The navbar
171
+ // forwards it to the cart sheet, so every chrome money surface agrees.
172
+ const storeLocale =
173
+ typeof state.storeLocale === 'string' && state.storeLocale.trim() !== ''
174
+ ? state.storeLocale
175
+ : DEFAULT_STORE_LOCALE
176
+ const formatMoney = createStoreMoneyFormatter(storeLocale)
168
177
  const cartError = typeof state.cartError === 'string' ? state.cartError : undefined
169
178
  const readError = typeof state.cartReadError === 'string' ? state.cartReadError : undefined
170
179
  const errorLabel = cartError ?? readError
@@ -215,6 +224,7 @@ const baseComponents = {
215
224
  showSearch={parsed.showSearch ?? false}
216
225
  items={toNavCartItems(cart)}
217
226
  subtotal={totals?.subtotal}
227
+ formatMoney={formatMoney}
218
228
  // One shared lateral: visibility is driven by the shared `cartOpen`
219
229
  // state (a successful add opens it; navigation dismisses it). The
220
230
  // canonical line amounts and lifecycle states come from the same cart
@@ -14,6 +14,7 @@ import type {
14
14
  ProductDetailProduct,
15
15
  } from '@thorprovider/blocks'
16
16
  import type { Money, PaymentMethod } from '@thorprovider/types'
17
+ import { DEFAULT_STORE_LOCALE } from './store-context'
17
18
 
18
19
  /** Real review, rendered only when the backend supplies it. */
19
20
  export interface ProductReview {
@@ -208,6 +209,12 @@ export interface StorefrontCoreState {
208
209
  dataNoticeDismissed: boolean
209
210
  /** Explicit data source; `'mock'` is always labelled as demo data. */
210
211
  dataSource: 'mock' | 'medusa'
212
+ /**
213
+ * The store's shopper locale (BCP-47). Seeded by the catch-all host from the
214
+ * store context so every client surface formats money with the same locale
215
+ * the server rendered `<html lang>` with; the default matches the scaffold.
216
+ */
217
+ storeLocale: string
211
218
  /** Visible real-mode failure; null when the data loaded. */
212
219
  dataError: string | null
213
220
  cartOpen: boolean
@@ -269,6 +276,7 @@ export const storefrontCoreState: StorefrontCoreState = {
269
276
  bannerDismissed: false,
270
277
  dataNoticeDismissed: false,
271
278
  dataSource: 'mock',
279
+ storeLocale: DEFAULT_STORE_LOCALE,
272
280
  dataError: null,
273
281
  cartOpen: false,
274
282
  cart: [],
@@ -5,8 +5,11 @@
5
5
  // any commerce call, so an incomplete or invalid configuration fails visibly
6
6
  // instead of silently falling back to demo data.
7
7
  //
8
- // Boundary: this module is server-only and reads no Next.js or React API. It
9
- // owns the environment contract; the commerce bridge owns the backend calls.
8
+ // Boundary: the environment-reading functions are server-only and read no
9
+ // Next.js or React API. This module owns the environment contract; the
10
+ // commerce bridge owns the backend calls. The pure exports (locale default,
11
+ // `createStoreMoneyFormatter`) carry no env reads and are safe in the client
12
+ // registries, which receive the resolved locale through the seeded state.
10
13
  //
11
14
  // The values are the multitenancy seam: a future tenancy layer varies
12
15
  // storeId/channel/region/currency without redefining the commerce shapes. In
@@ -14,7 +17,7 @@
14
17
  // environment; mock mode resolves a labelled fixture context so the store runs
15
18
  // with no environment configured at all.
16
19
 
17
- import type { StoreContext } from '@thorprovider/types'
20
+ import type { Money, StoreContext } from '@thorprovider/types'
18
21
  import { storeContextSchema } from '@thorprovider/runtime/contracts'
19
22
 
20
23
  /** Data source selected explicitly by the host; never inferred from a failure. */
@@ -44,6 +47,66 @@ export const DATA_SOURCE_ENV = 'THOR_DATA_SOURCE'
44
47
  */
45
48
  export const SITE_URL_ENV = 'THOR_SITE_URL'
46
49
 
50
+ /**
51
+ * Host environment variable with the shopper locale (BCP-47, e.g. `es-UY`).
52
+ * One locale governs `<html lang>` and every monetary surface. Optional: when
53
+ * unset or blank the store falls back to `DEFAULT_STORE_LOCALE`.
54
+ */
55
+ export const LOCALE_ENV = 'THOR_STORE_LOCALE'
56
+
57
+ /**
58
+ * The scaffold's default shopper locale: the generated starter is a Spanish
59
+ * shop for a Uruguayan merchant, matching the mock Uruguay region (design D4).
60
+ */
61
+ export const DEFAULT_STORE_LOCALE = 'es-UY'
62
+
63
+ /**
64
+ * The store's shopper locale (BCP-47). Pure env read with a safe default; it
65
+ * never throws, so a missing override degrades to the scaffold default instead
66
+ * of failing the render.
67
+ */
68
+ export function getStoreLocale(): string {
69
+ const value = process.env[LOCALE_ENV]?.trim()
70
+ return value ? value : DEFAULT_STORE_LOCALE
71
+ }
72
+
73
+ /**
74
+ * The generated store's context: the shared validated `StoreContext` plus the
75
+ * shopper locale. The locale is a presentation concern owned by the host, so
76
+ * it extends the shared commerce shape here rather than in the backend
77
+ * contract.
78
+ */
79
+ export interface StorefrontStoreContext extends StoreContext {
80
+ /** BCP-47 shopper locale governing the document language and money. */
81
+ locale: string
82
+ }
83
+
84
+ /**
85
+ * Build the store's single money formatter from a locale. Pure and total, so
86
+ * the client registries can build the identical formatter from the locale the
87
+ * server seeded into the state store; `formatStoreMoney` below is the
88
+ * server-side convenience that resolves the locale itself. The currency always
89
+ * comes from the `Money` value — never hardcoded.
90
+ */
91
+ export function createStoreMoneyFormatter(locale: string): (value: Money) => string {
92
+ return (value) =>
93
+ new Intl.NumberFormat(locale, {
94
+ style: 'currency',
95
+ currency: value.currencyCode,
96
+ }).format(Number(value.amount))
97
+ }
98
+
99
+ /**
100
+ * Format a `Money` with the store's shopper locale. Server-side surfaces use
101
+ * this directly; client surfaces receive the same rendering through
102
+ * `createStoreMoneyFormatter(state.storeLocale)`. Callers gate availability
103
+ * first (the blocks' `formatMoney` safety gate) — this helper formats the
104
+ * canonical `Money` it is given.
105
+ */
106
+ export function formatStoreMoney(value: Money): string {
107
+ return createStoreMoneyFormatter(getStoreContext().locale)(value)
108
+ }
109
+
47
110
  /**
48
111
  * Visible configuration failure. Thrown before commerce so a missing or invalid
49
112
  * store context surfaces as an error instead of fictional data.
@@ -94,15 +157,17 @@ export function getSiteUrl(): string | undefined {
94
157
 
95
158
  /**
96
159
  * Fixture context resolved in mock mode. It satisfies `storeContextSchema` and
97
- * mirrors the values the bundled mock provider serves, so a store with no
98
- * environment configured still has a valid context to render and operate its
99
- * cart against. It is a labelled fixture, never a real backend identity.
160
+ * mirrors the values the bundled mock provider serves — the Uruguay region in
161
+ * UYU with the `es-UY` shopper locale — so a store with no environment
162
+ * configured still has a valid context whose country and currency agree with
163
+ * the commerce data. It is a labelled fixture, never a real backend identity.
100
164
  */
101
- export const MOCK_STORE_CONTEXT: StoreContext = {
165
+ export const MOCK_STORE_CONTEXT: StorefrontStoreContext = {
102
166
  storeId: 'mock-store',
103
167
  salesChannelId: 'mock-sales-channel',
104
- regionId: 'mock-region-us',
105
- currencyCode: 'USD',
168
+ regionId: 'mock-region-uy',
169
+ currencyCode: 'UYU',
170
+ locale: DEFAULT_STORE_LOCALE,
106
171
  }
107
172
 
108
173
  function requireEnv(name: string): string {
@@ -118,15 +183,16 @@ function requireEnv(name: string): string {
118
183
  /**
119
184
  * Resolve and validate the single-store context.
120
185
  *
121
- * Mock mode returns the labelled fixture context and reads no environment
122
- * variables, so a created store runs with no configuration. Real mode resolves
123
- * the four variables from the host environment and validates them through the
124
- * shared runtime schema, so an invalid context is rejected before any commerce
125
- * call. Throws `StoreConfigError` naming the missing variable — never a secret
126
- * value.
186
+ * Mock mode returns the labelled fixture context and reads none of the four
187
+ * backend variables, so a created store runs with no configuration; only the
188
+ * optional shopper-locale override (`THOR_STORE_LOCALE`) is honoured. Real mode
189
+ * resolves the four variables from the host environment and validates them
190
+ * through the shared runtime schema, so an invalid context is rejected before
191
+ * any commerce call. The shopper locale is attached in both modes. Throws
192
+ * `StoreConfigError` naming the missing variable — never a secret value.
127
193
  */
128
- export function getStoreContext(): StoreContext {
129
- if (!isRealMode()) return MOCK_STORE_CONTEXT
194
+ export function getStoreContext(): StorefrontStoreContext {
195
+ if (!isRealMode()) return { ...MOCK_STORE_CONTEXT, locale: getStoreLocale() }
130
196
  const candidate = {
131
197
  storeId: requireEnv(STORE_CONTEXT_ENV.storeId),
132
198
  salesChannelId: requireEnv(STORE_CONTEXT_ENV.salesChannelId),
@@ -140,7 +206,7 @@ export function getStoreContext(): StoreContext {
140
206
  .join('; ')
141
207
  throw new StoreConfigError(`Invalid store context: ${issues}`)
142
208
  }
143
- return parsed.data
209
+ return { ...parsed.data, locale: getStoreLocale() }
144
210
  }
145
211
 
146
212
  /**
@@ -11,6 +11,7 @@ import ShoppingCart from '@thorprovider/blocks/blocks/e-commerce/shopping-carts/
11
11
  import { isAvailableMoney } from '@thorprovider/blocks/contracts'
12
12
  import { useStateStore } from '@json-render/react'
13
13
  import { checkoutAvailable } from '../../composition'
14
+ import { createStoreMoneyFormatter, DEFAULT_STORE_LOCALE } from '../../store-context'
14
15
  import type { ViewRegistry } from '../types'
15
16
  import { toCartViewItems } from './data'
16
17
  import { cartViewPropsSchema } from './schema'
@@ -20,6 +21,13 @@ export const registry: ViewRegistry = {
20
21
  const { state, set } = useStateStore()
21
22
  const parsed = cartViewPropsSchema.parse(props)
22
23
  const cart = parsed.items
24
+ // The same store-locale formatter the shell chrome uses, so the cart page
25
+ // and the cart sheet render one Money identically (design D4).
26
+ const storeLocale =
27
+ typeof state.storeLocale === 'string' && state.storeLocale.trim() !== ''
28
+ ? state.storeLocale
29
+ : DEFAULT_STORE_LOCALE
30
+ const formatMoney = createStoreMoneyFormatter(storeLocale)
23
31
  const cartError = typeof state.cartError === 'string' ? state.cartError : undefined
24
32
  const readError = typeof state.cartReadError === 'string' ? state.cartReadError : undefined
25
33
  const isPending = state.cartPending === true
@@ -55,6 +63,7 @@ export const registry: ViewRegistry = {
55
63
  items={toCartViewItems(cart)}
56
64
  promotions={[]}
57
65
  totals={parsed.totals ?? undefined}
66
+ formatMoney={formatMoney}
58
67
  totalsState={totalsState}
59
68
  totalsErrorLabel={errorLabel}
60
69
  titleLabel={parsed.titleLabel}
@@ -58,6 +58,8 @@ export type HostedCheckoutState = {
58
58
  checkoutShippingState: CheckoutReadState;
59
59
  checkoutPaymentState: CheckoutReadState;
60
60
  checkoutFieldErrors?: Record<string, unknown>;
61
+ /** The store's shopper locale, seeded by the catch-all host (design D4). */
62
+ storeLocale: string;
61
63
  };
62
64
 
63
65
  type HostedSetter = (path: string, value: unknown) => void;
@@ -655,7 +657,9 @@ export function toHostedCheckoutModel(
655
657
 
656
658
  return {
657
659
  labels: copyFor(props),
658
- locale: 'es-ES',
660
+ // One store locale for every money surface: the checkout summary formats
661
+ // with the same locale as the cart and `<html lang>` (design D4).
662
+ locale: state.storeLocale,
659
663
  currencyCode,
660
664
  countries: (props.shippingLocations?.countries ?? [])
661
665
  .filter((country) => country.value.trim() !== '' && country.label.trim() !== '')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thorprovider/storefront",
3
- "version": "0.15.0",
3
+ "version": "0.15.1",
4
4
  "description": "Deterministic storefront scaffolder and installable OpenCode skill suite for Thor Commerce (Next.js, @thorprovider/blocks, @thorprovider/adapters, Medusa)",
5
5
  "type": "module",
6
6
  "bin": "bin/storefront.js",
@@ -48,7 +48,7 @@ export const CANDIDATE_TOOLSET = Object.freeze({
48
48
  }),
49
49
  local: Object.freeze({
50
50
  '@thorprovider/blocks': '4.8.0',
51
- '@thorprovider/adapters': '5.8.0',
51
+ '@thorprovider/adapters': '5.8.1',
52
52
  '@thorprovider/runtime': '0.10.0',
53
53
  '@thorprovider/types': '7.8.0',
54
54
  }),
@@ -29,6 +29,11 @@ export function envExample(name) {
29
29
  'THOR_DATA_SOURCE=mock',
30
30
  '# Store identity (written by create; required only in real mode).',
31
31
  `THOR_STORE_ID=${name}`,
32
+ '# Shopper locale (BCP-47): governs <html lang> and every money surface',
33
+ '# (cart, cart sheet, checkout summary, order confirmation). Optional —',
34
+ '# unset or blank falls back to es-UY, the scaffold default that matches',
35
+ '# the mock Uruguay region (UYU).',
36
+ 'THOR_STORE_LOCALE=es-UY',
32
37
  '# Demo imagery base (mock mode only). The starter ships local product,',
33
38
  '# category and banner shots under public/images; drop this to fall back to',
34
39
  '# the generated SVG placeholders.',