@thorprovider/storefront 0.4.0-mvp.2 → 0.5.0

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 (129) hide show
  1. package/README.md +13 -13
  2. package/assets/templates/app/app/[[...slug]]/page.tsx +32 -1
  3. package/assets/templates/app/app/[[...slug]]/renderer.tsx +43 -12
  4. package/assets/templates/app/lib/__STOREFRONT__/account-boundary.client.tsx +76 -0
  5. package/assets/templates/app/lib/__STOREFRONT__/account-lifecycle.client.tsx +461 -0
  6. package/assets/templates/app/lib/__STOREFRONT__/account-mutation.client.ts +46 -0
  7. package/assets/templates/app/lib/__STOREFRONT__/account-private.core.ts +103 -0
  8. package/assets/templates/app/lib/__STOREFRONT__/account-reconcile.client.ts +465 -0
  9. package/assets/templates/app/lib/__STOREFRONT__/account-session.core.ts +177 -0
  10. package/assets/templates/app/lib/__STOREFRONT__/account-session.ts +44 -0
  11. package/assets/templates/app/lib/__STOREFRONT__/account-user.core.ts +65 -0
  12. package/assets/templates/app/lib/__STOREFRONT__/actions.ts +76 -27
  13. package/assets/templates/app/lib/__STOREFRONT__/catalog.ts +4 -4
  14. package/assets/templates/app/lib/__STOREFRONT__/commerce.ts +0 -10
  15. package/assets/templates/app/lib/__STOREFRONT__/composition.ts +1 -1
  16. package/assets/templates/app/lib/__STOREFRONT__/handlers.core.ts +3 -3
  17. package/assets/templates/app/lib/__STOREFRONT__/mappers.ts +17 -18
  18. package/assets/templates/app/lib/__STOREFRONT__/projection-ownership.client.tsx +209 -0
  19. package/assets/templates/app/lib/__STOREFRONT__/projection-ownership.ts +247 -0
  20. package/assets/templates/app/lib/__STOREFRONT__/registry.tsx +60 -29
  21. package/assets/templates/app/lib/__STOREFRONT__/schema.ts +83 -15
  22. package/assets/templates/app/lib/__STOREFRONT__/section-sources.ts +3 -5
  23. package/assets/templates/app/lib/__STOREFRONT__/shell/props.ts +1 -1
  24. package/assets/templates/app/lib/__STOREFRONT__/spec/index.ts +25 -0
  25. package/assets/templates/app/lib/__STOREFRONT__/state.core.ts +7 -10
  26. package/assets/templates/app/lib/__STOREFRONT__/views/sections/cta.client.tsx +1 -1
  27. package/assets/templates/app/lib/__STOREFRONT__/views/sections/faq.client.tsx +1 -1
  28. package/assets/templates/app/lib/__STOREFRONT__/views/sections/logoCloud.tsx +1 -1
  29. package/assets/templates/app/lib/__STOREFRONT__/views/sections/pricing.tsx +1 -1
  30. package/assets/templates/app/lib/__STOREFRONT__/views/sections/products.client.tsx +16 -16
  31. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.products.ts +1 -1
  32. package/assets/templates/app/lib/__STOREFRONT__/views/sections/statistics.tsx +1 -1
  33. package/assets/templates/app/lib/__STOREFRONT__/views/sections/testimonials.tsx +26 -19
  34. package/assets/templates/features/checkout/state.ts +0 -5
  35. package/assets/templates/features/customer-auth/handlers.ts +19 -23
  36. package/assets/templates/features/customer-auth/state.ts +21 -0
  37. package/assets/templates/views/account/index.tsx +19 -7
  38. package/assets/templates/views/account/registry.tsx +263 -155
  39. package/assets/templates/views/account/schema.ts +1 -1
  40. package/assets/templates/views/cart/data.ts +7 -7
  41. package/assets/templates/views/cart/registry.tsx +4 -3
  42. package/assets/templates/views/category/assembly/assembly.json +2 -2
  43. package/assets/templates/views/category/assembly/index.skeleton.tsx +11 -7
  44. package/assets/templates/views/category/assembly/registry.skeleton.tsx +9 -9
  45. package/assets/templates/views/category/assembly/slots/breadcrumb/Breadcrumb/binding.json +1 -1
  46. package/assets/templates/views/category/assembly/slots/filter/CategoryListing/catalog.part +5 -0
  47. package/assets/templates/views/category/assembly/slots/filter/{CategoryFilter2 → CategoryListing}/element.part +5 -3
  48. package/assets/templates/views/category/assembly/slots/filter/{CategoryFilter2 → CategoryListing}/registry.part +9 -5
  49. package/assets/templates/views/category/content.ts +2 -1
  50. package/assets/templates/views/category/index.tsx +19 -13
  51. package/assets/templates/views/category/props.ts +1 -1
  52. package/assets/templates/views/category/registry.tsx +19 -15
  53. package/assets/templates/views/category/schema.ts +48 -21
  54. package/assets/templates/views/checkout/content.ts +60 -0
  55. package/assets/templates/views/checkout/props.ts +4 -5
  56. package/assets/templates/views/checkout/registry.tsx +12 -10
  57. package/assets/templates/views/checkout/schema.ts +10 -16
  58. package/assets/templates/views/home/assembly/assembly.json +4 -4
  59. package/assets/templates/views/home/assembly/index.skeleton.tsx +2 -3
  60. package/assets/templates/views/home/assembly/registry.skeleton.tsx +4 -1
  61. package/assets/templates/views/home/assembly/slots/benefits/cards/binding.json +5 -0
  62. package/assets/templates/views/home/assembly/slots/benefits/cards/registry.part +17 -0
  63. package/assets/templates/views/home/assembly/slots/benefits/split/binding.json +5 -0
  64. package/assets/templates/views/home/assembly/slots/benefits/{Feature1 → split}/registry.part +6 -2
  65. package/assets/templates/views/home/assembly/slots/categories/CategoryGrid/binding.json +5 -0
  66. package/assets/templates/views/home/assembly/slots/categories/CategoryGrid/catalog.part +8 -0
  67. package/assets/templates/views/home/assembly/slots/categories/{ProductCategory2 → CategoryGrid}/element.part +1 -1
  68. package/assets/templates/views/home/assembly/slots/categories/CategoryGrid/registry.part +31 -0
  69. package/assets/templates/views/home/assembly/slots/hero/StorefrontHero/binding.json +5 -0
  70. package/assets/templates/views/home/assembly/slots/hero/StorefrontHero/catalog.part +4 -0
  71. package/assets/templates/views/home/assembly/slots/hero/{StorefrontHero1 → StorefrontHero}/registry.part +3 -1
  72. package/assets/templates/views/home/content.ts +22 -0
  73. package/assets/templates/views/home/index.tsx +11 -8
  74. package/assets/templates/views/home/props.ts +1 -0
  75. package/assets/templates/views/home/registry.tsx +39 -15
  76. package/assets/templates/views/home/schema.ts +141 -24
  77. package/assets/templates/views/product/data.ts +1 -1
  78. package/assets/templates/views/product/registry.tsx +10 -6
  79. package/assets/templates/views/product/schema.ts +36 -1
  80. package/examples/merchandising/category-led.json +1 -1
  81. package/examples/merchandising/collection-led.json +1 -1
  82. package/package.json +4 -5
  83. package/recipes/archetypes.json +39 -43
  84. package/recipes/catalog.json +212 -202
  85. package/recipes/catalog.mjs +10 -0
  86. package/recipes/catalog.schema.json +4 -0
  87. package/recipes/features.json +5 -5
  88. package/recipes/recipes.json +137 -43
  89. package/recipes/sections.json +4 -4
  90. package/recipes/validate.mjs +21 -4
  91. package/scripts/candidate.mjs +2 -2
  92. package/scripts/composers.mjs +2 -2
  93. package/scripts/file-classes.mjs +10 -0
  94. package/scripts/logical-controls.mjs +4 -4
  95. package/scripts/operation-registry.mjs +1 -1
  96. package/scripts/ownership-conflict.mjs +5 -2
  97. package/scripts/view-assembly.mjs +12 -4
  98. package/scripts/view-selection.mjs +1 -1
  99. package/skills/sf-view-gen/assets/recipes/archetypes.json +39 -43
  100. package/skills/sf-view-gen/assets/recipes/catalog.json +212 -202
  101. package/skills/sf-view-gen/assets/recipes/catalog.schema.json +4 -0
  102. package/skills/sf-view-gen/assets/recipes/features.json +5 -5
  103. package/skills/sf-view-gen/assets/recipes/recipes.json +137 -43
  104. package/skills/sf-view-gen/assets/recipes/sections.json +4 -4
  105. package/skills/sf-view-gen/assets/templates/views/sections/cta.client.tsx +1 -1
  106. package/skills/sf-view-gen/assets/templates/views/sections/faq.client.tsx +1 -1
  107. package/skills/sf-view-gen/assets/templates/views/sections/logoCloud.client.tsx +1 -1
  108. package/skills/sf-view-gen/assets/templates/views/sections/pricing.client.tsx +1 -1
  109. package/skills/sf-view-gen/assets/templates/views/sections/products.client.tsx +16 -16
  110. package/skills/sf-view-gen/assets/templates/views/sections/schema.products.ts +1 -1
  111. package/skills/sf-view-gen/assets/templates/views/sections/schema.testimonials.ts +21 -11
  112. package/skills/sf-view-gen/assets/templates/views/sections/statistics.client.tsx +1 -1
  113. package/skills/sf-view-gen/assets/templates/views/sections/testimonials.client.tsx +2 -8
  114. package/skills/sf-view-gen/scripts/catalog.mjs +10 -0
  115. package/skills/sf-view-gen/scripts/validate.mjs +21 -4
  116. package/assets/templates/views/category/assembly/slots/filter/CategoryFilter2/catalog.part +0 -5
  117. package/assets/templates/views/home/assembly/slots/benefits/Feature1/binding.json +0 -5
  118. package/assets/templates/views/home/assembly/slots/benefits/Feature2/binding.json +0 -5
  119. package/assets/templates/views/home/assembly/slots/benefits/Feature2/registry.part +0 -10
  120. package/assets/templates/views/home/assembly/slots/categories/ProductCategory2/binding.json +0 -5
  121. package/assets/templates/views/home/assembly/slots/categories/ProductCategory2/catalog.part +0 -4
  122. package/assets/templates/views/home/assembly/slots/categories/ProductCategory2/registry.part +0 -16
  123. package/assets/templates/views/home/assembly/slots/hero/StorefrontHero1/binding.json +0 -5
  124. package/assets/templates/views/home/assembly/slots/hero/StorefrontHero1/catalog.part +0 -4
  125. /package/assets/templates/views/home/assembly/slots/benefits/{Feature1 → cards}/catalog.part +0 -0
  126. /package/assets/templates/views/home/assembly/slots/benefits/{Feature1 → cards}/element.part +0 -0
  127. /package/assets/templates/views/home/assembly/slots/benefits/{Feature2 → split}/catalog.part +0 -0
  128. /package/assets/templates/views/home/assembly/slots/benefits/{Feature2 → split}/element.part +0 -0
  129. /package/assets/templates/views/home/assembly/slots/hero/{StorefrontHero1 → StorefrontHero}/element.part +0 -0
@@ -0,0 +1,65 @@
1
+ // Generated by Thor Commerce storefront (template: assets/templates/app/lib/__STOREFRONT__/account-user.core.ts)
2
+ //
3
+ // Pure, framework-free mapper from the allowlisted account identity
4
+ // (`./account-session.core`) to the navbar block's `StoreUser` shape.
5
+ //
6
+ // The navbar account menu renders `@thorprovider/blocks`' `StoreUser`
7
+ // (`{ name, email, avatar?, initials }`), which differs from the allowlisted
8
+ // identity (`{ id, email, firstName|null, lastName|null }`). The mapping lives
9
+ // in this DERIVED module — regenerated by the CLI — rather than in the
10
+ // user-owned `mappers.ts` (seeded once, never rewritten by `reconcile`, so a new
11
+ // required export there would break older storefronts on upgrade).
12
+ //
13
+ // No Next.js/React, no I/O, no env: the same identity always maps to the same
14
+ // user, and the block dependency is `import type` only (erased at build).
15
+
16
+ import type { StoreUser } from '@thorprovider/blocks'
17
+ import type { AccountIdentity } from './account-session.core'
18
+
19
+ /** Trim a nullable name, collapsing `null`/`undefined`/whitespace to `''`. */
20
+ function namePart(value: string | null | undefined): string {
21
+ return value?.trim() ?? ''
22
+ }
23
+
24
+ /** The email local-part: text before the first `@` (empty when there is none). */
25
+ function emailLocalPart(email: string): string {
26
+ const at = email.indexOf('@')
27
+ return (at === -1 ? email : email.slice(0, at)).trim()
28
+ }
29
+
30
+ /**
31
+ * Deterministic uppercase initials for the display name. When both name parts
32
+ * are present, the first character of each; otherwise the first two characters
33
+ * of the resolved name (the single name part, or the email local-part).
34
+ * `toUpperCase` (not `toLocaleUpperCase`) keeps the rule locale-independent.
35
+ */
36
+ function initialsOf(firstName: string, lastName: string, displayName: string): string {
37
+ if (firstName !== '' && lastName !== '') {
38
+ return (firstName[0] + lastName[0]).toUpperCase()
39
+ }
40
+ return displayName.slice(0, 2).toUpperCase()
41
+ }
42
+
43
+ /**
44
+ * Map one allowlisted account identity to the navbar `StoreUser`, or `null`
45
+ * when there is no authenticated identity (so the account menu is not
46
+ * rendered). `name` joins the trimmed names with a single space and falls back
47
+ * to the email local-part when both are absent; `avatar` is always absent, so
48
+ * the block renders its initials fallback instead of an empty image source.
49
+ */
50
+ export function accountStoreUser(identity: AccountIdentity | null): StoreUser | null {
51
+ if (!identity) return null
52
+
53
+ const firstName = namePart(identity.firstName)
54
+ const lastName = namePart(identity.lastName)
55
+ const joined = [firstName, lastName].filter((part) => part !== '').join(' ')
56
+ // Never an empty name while an email exists: the local-part is the documented
57
+ // fallback, and the full email covers a degenerate local-part-less address.
58
+ const displayName = joined !== '' ? joined : emailLocalPart(identity.email) || identity.email
59
+
60
+ return {
61
+ name: displayName,
62
+ email: identity.email,
63
+ initials: initialsOf(firstName, lastName, displayName),
64
+ }
65
+ }
@@ -27,11 +27,10 @@ import {
27
27
  createGuestCart,
28
28
  endSession,
29
29
  loadCheckoutCountries,
30
- loadCustomer,
31
30
  loadOrders,
32
31
  loadOrdersPage,
33
32
  loadPaymentMethods,
34
- loadProductDetailById,
33
+ loadProductDetail,
35
34
  loadShippingMethods,
36
35
  readCart,
37
36
  reconcileOrder,
@@ -48,6 +47,8 @@ import {
48
47
  type CartStatePatch,
49
48
  type PlaceOrderResult,
50
49
  } from './commerce'
50
+ import { readAccountSession } from './account-session'
51
+ import { accountIdentitySchema, type AccountIdentity } from './account-session.core'
51
52
  import { getStoreContext } from './store-context'
52
53
  import {
53
54
  bindHostSessionCart,
@@ -81,9 +82,26 @@ type CheckoutActionResult =
81
82
  }
82
83
  | { ok: false; error: string; fieldErrors?: CheckoutFieldErrors }
83
84
 
84
- /** Structured result for an auth action that may carry the current customer. */
85
+ /**
86
+ * Structured result for a login/register auth action. It carries ONLY the
87
+ * allowlisted display identity (id/email/names) — never a token or customer
88
+ * metadata — so the client can project it into shared account state directly.
89
+ * An identity that fails the display allowlist is a failure, never a claimed
90
+ * authenticated state.
91
+ */
85
92
  type AuthActionResult =
86
- | { ok: true; customer: Customer | null }
93
+ | { ok: true; customer: AccountIdentity | null }
94
+ | { ok: false; error: string }
95
+
96
+ /**
97
+ * Structured result for the reader-backed current-customer load. It carries
98
+ * only the allowlisted display identity — never a token or customer metadata.
99
+ * `AccountIdentity` is a structural subset of `Customer` (whose other fields
100
+ * are optional), so this stays assignable wherever the legacy auth result is
101
+ * consumed.
102
+ */
103
+ type AccountActionResult =
104
+ | { ok: true; customer: AccountIdentity | null }
87
105
  | { ok: false; error: string }
88
106
 
89
107
  /** Structured result for logout; the authoritative cookie clear is the outcome. */
@@ -116,6 +134,20 @@ function toError(error: unknown, fallback: string): string {
116
134
  return error instanceof Error && error.message.trim() !== '' ? error.message : fallback
117
135
  }
118
136
 
137
+ /**
138
+ * Allowlist a backend customer to the serializable display identity before it
139
+ * crosses the Server Action boundary. Returns `null` for a confirmed anonymous
140
+ * result, the parsed identity for a valid customer, and `undefined` for a
141
+ * response that fails the allowlist (for example a missing id/email) so the
142
+ * caller reports a failure instead of storing an unrestricted customer object
143
+ * (design D1: only id/email/names may enter client state; no token/metadata).
144
+ */
145
+ function toDisplayIdentity(customer: Customer | null): AccountIdentity | null | undefined {
146
+ if (!customer) return null
147
+ const parsed = accountIdentitySchema.safeParse(customer)
148
+ return parsed.success ? parsed.data : undefined
149
+ }
150
+
119
151
  /**
120
152
  * Resolve the active cart id, creating and binding a new backend cart when the
121
153
  * session has none or its cart was completed. A new cart after a completed one
@@ -161,24 +193,26 @@ export async function addToCartAction(input: {
161
193
  }
162
194
 
163
195
  /**
164
- * Add a product's FIRST purchasable variant by backend product id — the
165
- * product-card shortcut. The variant is resolved server-side from the backend
166
- * detail (card data carries no variant ids); a product with no purchasable
167
- * variant returns a truthful error and adds nothing. The product detail remains
168
- * the explicit-selection surface (change storefront-card-add-to-cart).
196
+ * Add a product's FIRST purchasable variant by the public product handle the
197
+ * card presents — the product-card shortcut. The variant is resolved server-side
198
+ * from the backend detail (card data carries no variant ids); a product with no
199
+ * purchasable variant returns a truthful error and adds nothing. The product
200
+ * detail remains the explicit-selection surface (change
201
+ * storefront-card-add-to-cart-handle-resolution).
169
202
  */
170
- export async function addToCartByProductAction(input: {
171
- productId: string
203
+ export async function addToCartByHandleAction(input: {
204
+ productHandle: string
172
205
  quantity?: number
173
206
  }): Promise<CartActionResult> {
174
207
  try {
175
- const productId = typeof input?.productId === 'string' ? input.productId : ''
176
- if (productId === '') return { ok: false, error: 'Producto no válido.' }
208
+ const productHandle =
209
+ typeof input?.productHandle === 'string' ? input.productHandle : ''
210
+ if (productHandle === '') return { ok: false, error: 'Producto no válido.' }
177
211
  const quantity =
178
212
  Number.isFinite(input?.quantity) && (input.quantity as number) > 0
179
213
  ? Math.floor(input.quantity as number)
180
214
  : 1
181
- const detail = await loadProductDetailById(productId)
215
+ const { detail } = await loadProductDetail(productHandle)
182
216
  const target = resolveProductCartTarget(detail)
183
217
  if (!target.ok) return { ok: false, error: target.error }
184
218
  const { cartId, context } = await ensureActiveCartId()
@@ -472,8 +506,13 @@ export async function loginAction(input: {
472
506
  if (outcome.requiresAction) {
473
507
  return { ok: false, error: 'Se requiere un paso adicional para iniciar sesión.' }
474
508
  }
509
+ const identity = toDisplayIdentity(outcome.customer)
510
+ if (identity === undefined) {
511
+ logServerError('loginAction', new Error('customer failed the display allowlist'))
512
+ return { ok: false, error: 'No se pudo verificar la cuenta.' }
513
+ }
475
514
  if (outcome.token) await writeAuthToken(context, outcome.token)
476
- return { ok: true, customer: outcome.customer }
515
+ return { ok: true, customer: identity }
477
516
  } catch (error) {
478
517
  logServerError('loginAction', error)
479
518
  return { ok: false, error: toError(error, 'No se pudo iniciar sesión.') }
@@ -513,8 +552,13 @@ export async function registerAction(input: {
513
552
  if (outcome.requiresAction) {
514
553
  return { ok: false, error: 'Se requiere un paso adicional para iniciar sesión.' }
515
554
  }
555
+ const identity = toDisplayIdentity(outcome.customer)
556
+ if (identity === undefined) {
557
+ logServerError('registerAction', new Error('customer failed the display allowlist'))
558
+ return { ok: false, error: 'No se pudo verificar la cuenta.' }
559
+ }
516
560
  if (outcome.token) await writeAuthToken(context, outcome.token)
517
- return { ok: true, customer: outcome.customer }
561
+ return { ok: true, customer: identity }
518
562
  } catch (error) {
519
563
  logServerError('registerAction', error)
520
564
  return { ok: false, error: toError(error, 'No se pudo crear la cuenta.') }
@@ -541,17 +585,22 @@ export async function logoutAction(): Promise<LogoutActionResult> {
541
585
  }
542
586
  }
543
587
 
544
- /** Resolve the current customer from the verified auth cookie, or null. */
545
- export async function loadAccountAction(): Promise<AuthActionResult> {
546
- try {
547
- const context = getStoreContext()
548
- const token = await readAuthToken(context)
549
- const customer = await loadCustomer(token)
550
- return { ok: true, customer: customer ?? null }
551
- } catch (error) {
552
- logServerError('loadAccountAction', error)
553
- return { ok: false, error: toError(error, 'No se pudo cargar la cuenta.') }
554
- }
588
+ /**
589
+ * Resolve the current customer from the verified auth cookie, or null. It
590
+ * reuses the shared host session reader so the account action and the server
591
+ * render agree on cookie/customer resolution. The result carries only the
592
+ * allowlisted display identity (id/email/names), never metadata or a token, and
593
+ * an operational failure stays a retryable error rather than a fake sign-out.
594
+ */
595
+ export async function loadAccountAction(): Promise<AccountActionResult> {
596
+ const outcome = await readAccountSession()
597
+ if (outcome.status === 'authenticated') return { ok: true, customer: outcome.identity }
598
+ if (outcome.status === 'anonymous') return { ok: true, customer: null }
599
+ // Keep the sanitized detail in the server log; the shopper sees the
600
+ // established Spanish wording. An outage stays a retryable error, never a
601
+ // claim that the session ended.
602
+ logServerError('loadAccountAction', outcome.error)
603
+ return { ok: false, error: 'No se pudo cargar la cuenta.' }
555
604
  }
556
605
 
557
606
  // ---------------------------------------------------------------------------
@@ -12,7 +12,7 @@ import {
12
12
  footerPropsSchema,
13
13
  mobileBottomNavPropsSchema,
14
14
  navbarPropsSchema,
15
- productCardPropsSchema,
15
+ productGridPropsSchema,
16
16
  skipToContentPropsSchema,
17
17
  storefrontNavbarPropsSchema,
18
18
  } from './schema'
@@ -49,9 +49,9 @@ const baseComponents = {
49
49
  props: bannerPropsSchema,
50
50
  description: 'Announcement banner above the header.',
51
51
  },
52
- ProductCard: {
53
- props: productCardPropsSchema,
54
- description: 'Grid of product cards.',
52
+ ProductGrid: {
53
+ props: productGridPropsSchema,
54
+ description: 'Product grid listing, rendered as a grid of product cells.',
55
55
  },
56
56
  Footer: {
57
57
  props: footerPropsSchema,
@@ -42,7 +42,6 @@ import {
42
42
  getCustomerOrdersPage,
43
43
  getEligibleShippingMethods,
44
44
  getPaymentMethodsByRegion,
45
- getProductDetailById,
46
45
  getProductDetailByHandle,
47
46
  loginCustomer,
48
47
  logoutCustomer,
@@ -266,15 +265,6 @@ export async function loadProductDetail(handle: string): Promise<CatalogDetailRe
266
265
  return { detail, source }
267
266
  }
268
267
 
269
- /** Directed product-detail lookup by backend id, priced in the store context region. */
270
- export async function loadProductDetailById(
271
- productId: string,
272
- ): Promise<CatalogProductDetail | undefined> {
273
- const context = getStoreContext()
274
- assertBackendConfigured()
275
- return getProductDetailById(productId, context)
276
- }
277
-
278
268
  /** The resolved add-to-cart target for a product-card shortcut. */
279
269
  export type ProductCartTarget =
280
270
  | { ok: true; variantId: string }
@@ -3,7 +3,7 @@
3
3
  // Installed manifest catalog features, in stable order, with their persisted
4
4
  // config. This is the generation seam the catalog URL boundary consumes to
5
5
  // reject parameters owned by a feature that is not installed, and the seam the
6
- // single controlled CategoryFilter2 reads to select its control
6
+ // single controlled CategoryListing reads to select its control
7
7
  // visibility/config from the installed manifest only.
8
8
 
9
9
  import type { CatalogFeatureName } from '@thorprovider/runtime/contracts'
@@ -15,7 +15,7 @@ import { useActions, useStateStore } from '@json-render/react'
15
15
  import { useNextApp } from '@json-render/next'
16
16
  import {
17
17
  addToCartAction,
18
- addToCartByProductAction,
18
+ addToCartByHandleAction,
19
19
  applyQuantityDeltaAction,
20
20
  ensureCartAction,
21
21
  loadCartStateAction,
@@ -94,11 +94,11 @@ export function useCoreHandlers() {
94
94
  addClickedToCart: () => {
95
95
  // Product-card shortcut: add the clicked product's first purchasable
96
96
  // variant. The backend variant id is resolved server-side from the
97
- // product id (the card carries no variant ids).
97
+ // public handle the card carries for navigation.
98
98
  const product = get('/lastClicked') as ClickedProduct | null
99
99
  if (!product?.id) return
100
100
  begin()
101
- void addToCartByProductAction({ productId: String(product.id) })
101
+ void addToCartByHandleAction({ productHandle: String(product.id) })
102
102
  .then((result) => {
103
103
  if (result.ok) {
104
104
  applyCart(result.cart)
@@ -3,7 +3,7 @@
3
3
  // Kept out of the views so a view module stays a pure server spec; mappers are
4
4
  // data-only and imported where the loader builds block props.
5
5
 
6
- import type { CardProduct, FeaturedProduct, ProductCategory2Category, StoreCategory } from '@thorprovider/blocks'
6
+ import type { CardProduct, FeaturedProduct, ProductCategoryItem, StoreCategory } from '@thorprovider/blocks'
7
7
 
8
8
  export const CATEGORY_IMAGE_FALLBACK =
9
9
  "data:image/svg+xml;charset=utf-8," +
@@ -11,33 +11,32 @@ export const CATEGORY_IMAGE_FALLBACK =
11
11
  `<svg xmlns='http://www.w3.org/2000/svg' width='600' height='480'><rect width='100%' height='100%' fill='#e2e8f0'/><g fill='none' stroke='#94a3b8' stroke-width='12' stroke-linecap='round'><path d='M120 240h360M300 120v240'/><path d='M200 180h50M200 240h50M200 300h50'/><path d='M350 180h50M350 240h50M350 300h50'/></g></svg>`,
12
12
  )
13
13
 
14
- /** CardProduct → FeaturedProduct (storefront-hero), with defaults for the fields
15
- * the card canon does not carry. The hero block requires every featured field
16
- * (including `colors`) to be defined at render time. */
14
+ /** CardProduct → FeaturedProduct (canonical StorefrontHero). Only fields the
15
+ * backend really carries are forwarded: the block renders honest omission for
16
+ * every host-supplied evidence field (brand, rating, reviews, stock, colors). */
17
17
  export function toFeaturedProduct(card: CardProduct): FeaturedProduct {
18
18
  return {
19
19
  id: String(card.id),
20
20
  name: card.title,
21
- brand: '',
22
21
  price: card.price,
23
- originalPrice: card.originalPrice ?? card.price,
24
- rating: 0,
25
- reviewCount: 0,
26
- inStock: true,
27
- isNew: false,
28
- isOnSale: Boolean(card.originalPrice),
22
+ // Only a real compare-at price is forwarded: the block renders a discount
23
+ // treatment solely from an `originalPrice > price` pair, and never from a
24
+ // fabricated one. Popularity/review/stock fields are omitted — the block
25
+ // renders nothing for them instead of claiming `rating: 0` or `inStock`.
26
+ originalPrice: card.originalPrice,
29
27
  image: card.image ?? '',
30
- colors: [],
28
+ tag: card.badge,
31
29
  }
32
30
  }
33
31
 
34
32
  /** StoreCategory (what @thorprovider/runtime/commerce's getCatalog returns) →
35
- * ProductCategory2Category (block), with fallbacks for description and image.
36
- * The runtime projection keeps only label/href and carries no product count, so
37
- * `itemCount` is unknown here: it is OMITTED (the block then renders no count)
38
- * rather than fabricated as `0`. A genuine `0` supplied by a richer source is
39
- * preserved because `itemCount` is optional, not defaulted. */
40
- export function toCategoryCard(category: StoreCategory): ProductCategory2Category {
33
+ * ProductCategoryItem (block). The runtime projection keeps only label/href and
34
+ * carries no product count, so `itemCount` is unknown here: it is OMITTED (the
35
+ * block then renders no count) rather than fabricated as `0`. A genuine `0`
36
+ * supplied by a richer source is preserved because `itemCount` is optional.
37
+ * `image` seeds the storefront's editorial category imagery — the brand overlay
38
+ * rekeys it by backend handle; the block also supplies a neutral placeholder. */
39
+ export function toCategoryCard(category: StoreCategory): ProductCategoryItem {
41
40
  return {
42
41
  id: category.label,
43
42
  handle: category.href,
@@ -0,0 +1,209 @@
1
+ 'use client'
2
+
3
+ // Generated by Thor Commerce storefront (template: assets/templates/app/lib/__STOREFRONT__/projection-ownership.client.tsx)
4
+ //
5
+ // React binding for the projection-ownership ledger. The renderer creates one
6
+ // ledger per tab and provides it here; account mutation/reconciliation code
7
+ // (tasks 3.x) reads the SAME instance through `useProjectionOwnership` so a
8
+ // successful mutation claims the account slice and the renderer stops a later,
9
+ // older server projection from overwriting it. No global mutable and no token.
10
+ //
11
+ // `useAccountOwnership` is the atomic account-ownership helper: claiming the
12
+ // overlay and writing `/account*` in one call keeps the two in lockstep (a
13
+ // divergence would make the overlay mask a different store value). It MUST be
14
+ // called from a client component rendered inside the storefront renderer — a
15
+ // React hook cannot run in a Server Action. Server Actions return data; the
16
+ // client handler awaits the action and then calls `claimAccount(result)` or
17
+ // `claimResolved(result, guard)`.
18
+ //
19
+ // INVARIANT (Important-D): an older server snapshot never overwrites a newer
20
+ // result. The ledger orders CLAIMS, so any authoritative result you display —
21
+ // login/register/logout, or a cross-tab re-resolution (4.x) — MUST be claimed
22
+ // via `claimResolved(result, guard)` (generation guard + claim, atomic). Never
23
+ // display a result and then release to the server: `releaseAccount` /
24
+ // `reconcileAccount` carry no age evidence, so an arbitrary delayed
25
+ // `router.refresh()`/RSC projection could overwrite it. `reconcileAccount` is
26
+ // only an explicit transfer that accepts the NEXT server refresh.
27
+ //
28
+ // IDENTITY-CHANGE INVALIDATION (task 3.3): `claimAccount` also clears the
29
+ // identity-dependent account-PRIVATE order slice whenever the identity key
30
+ // changes, ATOMICALLY with the trio write and only after a `claimResolved`
31
+ // guard. Because every authoritative identity change (login/register/logout,
32
+ // retry/reconcile re-resolution, shell/4.2 claim) flows through `claimAccount`,
33
+ // the private reset happens AT the trigger even when the `/account` panel is
34
+ // unmounted and no effect can run. Same-identity claims are a no-op and the
35
+ // guest cart is never touched (`clearAccountPrivateOrders`).
36
+
37
+ import { createContext, useContext, useMemo, useRef, type ReactNode } from 'react'
38
+ import { useStateStore } from '@json-render/react'
39
+ import type { AccountIdentity, AccountResolution } from './account-session.core'
40
+ import { accountIdentityKey, clearAccountPrivateOrders } from './account-private.core'
41
+ import {
42
+ ACCOUNT_OWNED_KEYS,
43
+ createProjectionOwnership,
44
+ type OwnershipToken,
45
+ type ProjectionOwnership,
46
+ } from './projection-ownership'
47
+
48
+ const ProjectionOwnershipContext = createContext<ProjectionOwnership | null>(null)
49
+
50
+ /**
51
+ * Provide the per-tab ownership ledger. Passing `ownership` is for composition
52
+ * and tests; in the renderer an internal instance is created once and kept for
53
+ * the mounted lifetime of the tab.
54
+ */
55
+ export function ProjectionOwnershipProvider({
56
+ ownership,
57
+ children,
58
+ }: {
59
+ ownership?: ProjectionOwnership
60
+ children: ReactNode
61
+ }) {
62
+ const ref = useRef<ProjectionOwnership | null>(null)
63
+ if (ref.current === null) ref.current = ownership ?? createProjectionOwnership()
64
+ return (
65
+ <ProjectionOwnershipContext.Provider value={ref.current}>
66
+ {children}
67
+ </ProjectionOwnershipContext.Provider>
68
+ )
69
+ }
70
+
71
+ /** Access the tab's ownership ledger. Throws outside the storefront renderer. */
72
+ export function useProjectionOwnership(): ProjectionOwnership {
73
+ const ownership = useContext(ProjectionOwnershipContext)
74
+ if (!ownership) {
75
+ throw new Error('useProjectionOwnership must be used within the storefront renderer')
76
+ }
77
+ return ownership
78
+ }
79
+
80
+ /** The allowlisted account values a mutation claims and writes together. */
81
+ export interface AccountClaimValues {
82
+ accountCustomer: AccountIdentity | null
83
+ accountAuthenticated: boolean
84
+ accountResolution: AccountResolution
85
+ }
86
+
87
+ /** Atomic account ownership: claim the overlay and write the store in one call. */
88
+ export interface AccountOwnership {
89
+ /**
90
+ * Claim the account slice and write `/account*` with the same values. When the
91
+ * identity key changes, the identity-dependent private order slice is cleared
92
+ * in the SAME call (atomic with the trio write); a same-identity claim is a
93
+ * no-op and the guest cart is never touched.
94
+ */
95
+ claimAccount(values: AccountClaimValues): OwnershipToken
96
+ /**
97
+ * Apply an authoritative action/reconciliation result ATOMICALLY with its
98
+ * generation guard. When `guard` is no longer current (a newer mutation or
99
+ * reconciliation already superseded it), the stale result is discarded and
100
+ * null is returned; otherwise the result is claimed (overlay + store write) so
101
+ * it wins over any later-arriving OLDER server projection, and the new token is
102
+ * returned. This is the REQUIRED path for any authoritative result you display
103
+ * (login/register/logout, cross-tab re-resolution in 4.x). Never display a
104
+ * result and then release to the server: `release`/`reconcileAccount` carry no
105
+ * age evidence, so an arbitrary delayed router projection could overwrite it.
106
+ */
107
+ claimResolved(values: AccountClaimValues, guard?: OwnershipToken | null): OwnershipToken | null
108
+ /** Return the account slice to the server when `token` is still current. */
109
+ releaseAccount(token: OwnershipToken): void
110
+ /**
111
+ * Explicit transfer of the account slice to the NEXT server projection (e.g. a
112
+ * `router.refresh()` whose ordering the framework/app guarantees). Use it ONLY
113
+ * when the authoritative values will arrive through that refresh — NOT for a
114
+ * cross-tab/action result you display (`claimResolved` is that path). Releases
115
+ * whether the slice was seeded or claimed, so a tab that only mounted still
116
+ * adopts the next refresh.
117
+ */
118
+ reconcileAccount(): void
119
+ /** True while `token` is still the current account claim. */
120
+ isCurrent(token: OwnershipToken): boolean
121
+ /**
122
+ * Acquire the per-tab auth-mutation gate shared by every consumer in this
123
+ * renderer (the global mount, the account forms, a future nav sign-out).
124
+ * Returns false when another auth mutation/reconciliation is already in
125
+ * flight, so two consumers cannot issue concurrent auth requests. The gate is
126
+ * per-tab ledger state — never a module global.
127
+ */
128
+ acquireAuthMutation(): boolean
129
+ /** Release the per-tab auth-mutation gate (the acquirer only). */
130
+ releaseAuthMutation(): void
131
+ /** True while an auth mutation/reconciliation holds the gate. */
132
+ isAuthMutationPending(): boolean
133
+ }
134
+
135
+ /**
136
+ * The atomic account-ownership helper. Call it from a client component inside
137
+ * the renderer (for example the account registry) — a React hook cannot run in a
138
+ * Server Action. Server Actions return data; the client handler awaits the
139
+ * action and then calls `claimAccount`/`claimResolved`.
140
+ *
141
+ * Invariant: an older server snapshot never overwrites a newer result. The
142
+ * ledger orders CLAIMS (a claim wins until release), so any authoritative result
143
+ * you display must be claimed — `claimResolved(result, guard)` — never released
144
+ * to the server after display. `reconcileAccount`/`releaseAccount` only hand the
145
+ * slice to the next server projection.
146
+ */
147
+ export function useAccountOwnership(): AccountOwnership {
148
+ const ownership = useProjectionOwnership()
149
+ const { set, getSnapshot } = useStateStore()
150
+ return useMemo(() => {
151
+ const claimAccount = (values: AccountClaimValues): OwnershipToken => {
152
+ // Normalize once so the overlay and the store cannot diverge (Minor-A).
153
+ const accountCustomer = values.accountCustomer ?? null
154
+ const accountAuthenticated = values.accountAuthenticated === true
155
+ // Identity-change invalidation, ATOMIC with the trio write and
156
+ // generation-safe (this only runs after a guard check in `claimResolved`):
157
+ // when the authorized customer changes — logout, customer switch,
158
+ // expiry/invalidation, or unavailable — clear the identity-dependent
159
+ // private order slice in the SAME call, so the reset happens AT the
160
+ // trigger even when the `/account` panel is unmounted and no effect can
161
+ // run. The prior key is read from the LIVE store (not a render closure),
162
+ // so it is correct regardless of which route is mounted. A same-identity
163
+ // claim (a re-resolution, or `beginMutation`'s snapshot claim) is a no-op,
164
+ // and `clearAccountPrivateOrders` never writes a guest cart key.
165
+ const priorKey = accountIdentityKey(
166
+ (getSnapshot().accountCustomer ?? null) as { id?: string | null } | null,
167
+ )
168
+ const nextKey = accountIdentityKey(accountCustomer)
169
+ const token = ownership.claim(ACCOUNT_OWNED_KEYS, {
170
+ accountCustomer,
171
+ accountAuthenticated,
172
+ accountResolution: values.accountResolution,
173
+ })
174
+ // Clear BEFORE writing the new identity so no reader ever observes the
175
+ // new identity alongside the previous customer's private rows.
176
+ if (priorKey !== nextKey) clearAccountPrivateOrders(set)
177
+ set('/accountCustomer', accountCustomer)
178
+ set('/accountAuthenticated', accountAuthenticated)
179
+ set('/accountResolution', values.accountResolution)
180
+ return token
181
+ }
182
+ return {
183
+ claimAccount,
184
+ claimResolved(values, guard = null) {
185
+ if (guard && !ownership.isCurrent(guard)) return null
186
+ return claimAccount(values)
187
+ },
188
+ releaseAccount(token) {
189
+ ownership.release(token)
190
+ },
191
+ reconcileAccount() {
192
+ const token = ownership.currentToken(ACCOUNT_OWNED_KEYS)
193
+ if (token) ownership.release(token)
194
+ },
195
+ isCurrent(token) {
196
+ return ownership.isCurrent(token)
197
+ },
198
+ acquireAuthMutation() {
199
+ return ownership.acquireMutationGate()
200
+ },
201
+ releaseAuthMutation() {
202
+ ownership.releaseMutationGate()
203
+ },
204
+ isAuthMutationPending() {
205
+ return ownership.isMutationGateHeld()
206
+ },
207
+ }
208
+ }, [ownership, set])
209
+ }