@thorprovider/storefront 0.7.0 → 0.10.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 (164) hide show
  1. package/README.md +22 -2
  2. package/assets/templates/AGENTS.md +14 -2
  3. package/assets/templates/app/app/[[...slug]]/page.tsx +9 -2
  4. package/assets/templates/app/lib/__STOREFRONT__/account-address.ts +129 -0
  5. package/assets/templates/app/lib/__STOREFRONT__/account-lifecycle.client.tsx +2 -2
  6. package/assets/templates/app/lib/__STOREFRONT__/account-private.core.ts +143 -0
  7. package/assets/templates/app/lib/__STOREFRONT__/account-profile.ts +220 -0
  8. package/assets/templates/app/lib/__STOREFRONT__/actions.ts +677 -80
  9. package/assets/templates/app/lib/__STOREFRONT__/addresses-port.ts +107 -0
  10. package/assets/templates/app/lib/__STOREFRONT__/commerce.ts +477 -38
  11. package/assets/templates/app/lib/__STOREFRONT__/confirmation.core.ts +240 -0
  12. package/assets/templates/app/lib/__STOREFRONT__/customer-profile-port.ts +103 -0
  13. package/assets/templates/app/lib/__STOREFRONT__/fulfillment-evidence-port.ts +31 -0
  14. package/assets/templates/app/lib/__STOREFRONT__/handlers.core.ts +21 -4
  15. package/assets/templates/app/lib/__STOREFRONT__/mappers.ts +6 -2
  16. package/assets/templates/app/lib/__STOREFRONT__/order-detail-mapper.ts +642 -0
  17. package/assets/templates/app/lib/__STOREFRONT__/order-detail-port.ts +25 -0
  18. package/assets/templates/app/lib/__STOREFRONT__/orders-port.ts +30 -0
  19. package/assets/templates/app/lib/__STOREFRONT__/ports.ts +28 -0
  20. package/assets/templates/app/lib/__STOREFRONT__/projection-ownership.client.tsx +4 -4
  21. package/assets/templates/app/lib/__STOREFRONT__/session.ts +24 -6
  22. package/assets/templates/app/lib/__STOREFRONT__/state.core.ts +21 -0
  23. package/assets/templates/app/lib/__STOREFRONT__/views/sections/address-book-advanced.client.tsx +29 -0
  24. package/assets/templates/app/lib/__STOREFRONT__/views/sections/checkout-commerce-v1.client.tsx +19 -0
  25. package/assets/templates/app/lib/__STOREFRONT__/views/sections/checkout-commerce-v1.tsx +16 -0
  26. package/assets/templates/app/lib/__STOREFRONT__/views/sections/customer-profile.client.tsx +27 -0
  27. package/assets/templates/app/lib/__STOREFRONT__/views/sections/index.ts +4 -1
  28. package/assets/templates/app/lib/__STOREFRONT__/views/sections/mega-menu-universal.client.tsx +19 -0
  29. package/assets/templates/app/lib/__STOREFRONT__/views/sections/mega-menu-universal.tsx +16 -0
  30. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.address-book-advanced.ts +437 -0
  31. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.checkout-commerce-v1.ts +398 -0
  32. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.customer-profile.ts +138 -0
  33. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.mega-menu-universal.ts +76 -0
  34. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.universal-banner.ts +217 -0
  35. package/assets/templates/app/lib/__STOREFRONT__/views/sections/universal-banner.client.tsx +24 -0
  36. package/assets/templates/app/lib/__STOREFRONT__/views/sections/universal-banner.tsx +16 -0
  37. package/assets/templates/features/checkout/handlers.ts +24 -4
  38. package/assets/templates/features/customer-addresses/handlers.ts +11 -0
  39. package/assets/templates/features/customer-addresses/state.ts +33 -0
  40. package/assets/templates/features/customer-auth/state.ts +10 -0
  41. package/assets/templates/features/customer-profile/handlers.ts +11 -0
  42. package/assets/templates/features/customer-profile/state.ts +18 -0
  43. package/assets/templates/views/account/address-book-advanced.defaults.ts +534 -0
  44. package/assets/templates/views/account/assembly/assembly.json +36 -0
  45. package/assets/templates/views/account/assembly/index.skeleton.tsx +277 -0
  46. package/assets/templates/views/account/assembly/registry.skeleton.tsx +1057 -0
  47. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/binding.json +5 -0
  48. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/catalog.part +4 -0
  49. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/element.part +5 -0
  50. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/registry.part +1 -0
  51. package/assets/templates/views/account/assembly/slots/addresses/cards/catalog.part +5 -0
  52. package/assets/templates/views/account/assembly/slots/addresses/cards/element.part +10 -0
  53. package/assets/templates/views/account/assembly/slots/addresses/cards/registry.part +1 -0
  54. package/assets/templates/views/account/assembly/slots/login/card/catalog.part +4 -0
  55. package/assets/templates/views/account/assembly/slots/login/card/element.part +13 -0
  56. package/assets/templates/views/account/assembly/slots/login/card/registry.part +1 -0
  57. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/catalog.part +5 -0
  58. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/element.part +5 -0
  59. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/registry.part +2 -0
  60. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/binding.json +5 -0
  61. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/catalog.part +5 -0
  62. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/element.part +5 -0
  63. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/registry.part +1 -0
  64. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/binding.json +5 -0
  65. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/catalog.part +4 -0
  66. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/element.part +5 -0
  67. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/registry.part +1 -0
  68. package/assets/templates/views/account/assembly/slots/profile/form/catalog.part +5 -0
  69. package/assets/templates/views/account/assembly/slots/profile/form/element.part +10 -0
  70. package/assets/templates/views/account/assembly/slots/profile/form/registry.part +1 -0
  71. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/catalog.part +4 -0
  72. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/element.part +13 -0
  73. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/registry.part +1 -0
  74. package/assets/templates/views/account/assembly/slots/summary/stack/catalog.part +5 -0
  75. package/assets/templates/views/account/assembly/slots/summary/stack/element.part +5 -0
  76. package/assets/templates/views/account/assembly/slots/summary/stack/registry.part +1 -0
  77. package/assets/templates/views/account/assembly/slots/summary/tabs/catalog.part +5 -0
  78. package/assets/templates/views/account/assembly/slots/summary/tabs/element.part +5 -0
  79. package/assets/templates/views/account/assembly/slots/summary/tabs/registry.part +1 -0
  80. package/assets/templates/views/account/content.ts +326 -0
  81. package/assets/templates/views/account/customer-profile.defaults.ts +136 -0
  82. package/assets/templates/views/account/fulfillment-evidence.client.tsx +34 -0
  83. package/assets/templates/views/account/fulfillment-evidence.defaults.ts +145 -0
  84. package/assets/templates/views/account/fulfillment-evidence.schema.ts +15 -0
  85. package/assets/templates/views/account/index.tsx +259 -38
  86. package/assets/templates/views/account/order-detail.client.tsx +35 -0
  87. package/assets/templates/views/account/order-detail.defaults.ts +457 -0
  88. package/assets/templates/views/account/orders-advanced.client.tsx +77 -0
  89. package/assets/templates/views/account/orders-advanced.defaults.ts +230 -0
  90. package/assets/templates/views/account/registry.tsx +935 -420
  91. package/assets/templates/views/account/schema.ts +50 -0
  92. package/assets/templates/views/account/sections-data.ts +2 -0
  93. package/assets/templates/views/cart/content.ts +1 -0
  94. package/assets/templates/views/category/assembly/index.skeleton.tsx +1 -0
  95. package/assets/templates/views/category/assembly/slots/filter/CategoryListing/element.part +1 -0
  96. package/assets/templates/views/category/content.ts +2 -0
  97. package/assets/templates/views/category/index.tsx +2 -0
  98. package/assets/templates/views/category/sections-data.ts +2 -0
  99. package/assets/templates/views/checkout/checkout-commerce-hosted.tsx +1089 -0
  100. package/assets/templates/views/checkout/content.ts +51 -0
  101. package/assets/templates/views/checkout/index.tsx +1 -1
  102. package/assets/templates/views/checkout/props.ts +10 -2
  103. package/assets/templates/views/checkout/registry.tsx +104 -42
  104. package/assets/templates/views/checkout/schema.ts +76 -1
  105. package/assets/templates/views/home/assembly/assembly.json +23 -2
  106. package/assets/templates/views/home/assembly/index.skeleton.tsx +4 -1
  107. package/assets/templates/views/home/assembly/registry.skeleton.tsx +1 -0
  108. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/binding.json +5 -0
  109. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/catalog.part +4 -0
  110. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/element.part +4 -0
  111. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/registry.part +10 -0
  112. package/assets/templates/views/home/content.ts +247 -1
  113. package/assets/templates/views/home/data.ts +10 -1
  114. package/assets/templates/views/home/index.tsx +8 -6
  115. package/assets/templates/views/home/props.ts +7 -1
  116. package/assets/templates/views/home/registry.tsx +11 -28
  117. package/assets/templates/views/home/schema.ts +163 -0
  118. package/assets/templates/views/home/sections-data.ts +2 -0
  119. package/assets/templates/views/product/content.ts +1 -0
  120. package/assets/templates/views/static/content.ts +1 -0
  121. package/bin/storefront.js +356 -27
  122. package/package.json +2 -1
  123. package/recipes/adapter-surface.json +159 -0
  124. package/recipes/archetypes.json +43 -4
  125. package/recipes/catalog.json +147 -2
  126. package/recipes/feature.schema.json +9 -0
  127. package/recipes/features.json +72 -1
  128. package/recipes/manifest.schema.json +5 -0
  129. package/recipes/recipe.schema.json +13 -1
  130. package/recipes/recipes.json +37 -7
  131. package/recipes/section.schema.json +112 -0
  132. package/recipes/sections.json +281 -4
  133. package/recipes/validate.mjs +83 -1
  134. package/scripts/adapter-surface.mjs +41 -0
  135. package/scripts/agent-blocks.mjs +700 -0
  136. package/scripts/block-validator.mjs +45 -0
  137. package/scripts/candidate.mjs +56 -14
  138. package/scripts/composers.mjs +7 -2
  139. package/scripts/default-sections.mjs +78 -0
  140. package/scripts/file-classes.mjs +18 -0
  141. package/scripts/generate-adapter-surface.mjs +148 -0
  142. package/scripts/operations.mjs +100 -0
  143. package/scripts/reconcile.mjs +67 -39
  144. package/scripts/section-configure.mjs +316 -0
  145. package/scripts/sync-assets.mjs +1 -0
  146. package/scripts/view-assembly.mjs +101 -14
  147. package/skills/sf-feature/SKILL.md +19 -0
  148. package/skills/sf-view-gen/SKILL.md +73 -7
  149. package/skills/sf-view-gen/assets/recipes/archetypes.json +43 -4
  150. package/skills/sf-view-gen/assets/recipes/catalog.json +147 -2
  151. package/skills/sf-view-gen/assets/recipes/features.json +72 -1
  152. package/skills/sf-view-gen/assets/recipes/recipes.json +37 -7
  153. package/skills/sf-view-gen/assets/recipes/section.schema.json +112 -0
  154. package/skills/sf-view-gen/assets/recipes/sections.json +281 -4
  155. package/skills/sf-view-gen/assets/templates/views/sections/checkout-commerce-v1.client.tsx +19 -0
  156. package/skills/sf-view-gen/assets/templates/views/sections/checkout-commerce-v1.tsx +16 -0
  157. package/skills/sf-view-gen/assets/templates/views/sections/mega-menu-universal.client.tsx +19 -0
  158. package/skills/sf-view-gen/assets/templates/views/sections/mega-menu-universal.tsx +16 -0
  159. package/skills/sf-view-gen/assets/templates/views/sections/schema.checkout-commerce-v1.ts +398 -0
  160. package/skills/sf-view-gen/assets/templates/views/sections/schema.mega-menu-universal.ts +76 -0
  161. package/skills/sf-view-gen/assets/templates/views/sections/schema.universal-banner.ts +217 -0
  162. package/skills/sf-view-gen/assets/templates/views/sections/universal-banner.client.tsx +24 -0
  163. package/skills/sf-view-gen/assets/templates/views/sections/universal-banner.tsx +16 -0
  164. package/skills/sf-view-gen/scripts/validate.mjs +83 -1
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  title: "@thorprovider/storefront"
3
3
  purpose: "Deterministic storefront scaffolder and installable skill suite for Thor Commerce"
4
- lastReviewed: "2026-10-14"
4
+ lastReviewed: "2026-11-08"
5
5
  ---
6
6
 
7
7
  # @thorprovider/storefront
@@ -193,6 +193,24 @@ are required. `medusa` uses the real backend: a missing provider or invalid conf
193
193
  **visible error** — never a silent fallback to demo data. Run `storefront setup`, then
194
194
  restart `yarn dev`.
195
195
 
196
+ ### Feature capability gating
197
+
198
+ `setup` also probes `GET /store/thor/capabilities` and records the enabled flags on
199
+ `storefront.config.json` (`capabilities`). A feature that declares
200
+ `backendCapabilities` — for example an account address book needing `manageAddresses`
201
+ — installs only when the configured backend advertises every one of them:
202
+
203
+ ```bash
204
+ storefront feature add customer-addresses # refused when the backend lacks manageAddresses
205
+ ```
206
+
207
+ A failed probe records no list (unknown), so capability-gated features stay
208
+ uninstallable until `storefront setup` succeeds again. `storefront doctor` re-probes and
209
+ reports an installed feature whose capability the backend no longer advertises. Features
210
+ also declare `requires` (a module needs its host feature) and `adapter.needs` (callables
211
+ checked against the adapter/commerce surface), and a held feature is inspectable with
212
+ `storefront features --json` but never installable.
213
+
196
214
  The guest flow is backend-authoritative end to end: the signed host cookie binds a
197
215
  persistent backend cart; the PDP adds the explicitly selected variant; the cart and
198
216
  checkout render the backend's totals; checkout applies the one approved manual TEST
@@ -298,7 +316,9 @@ held post-MVP and rejected before any write. `create` seeds `home` and `cart`;
298
316
  data-bound `products` sections: see [Product sections](docs/product-sections.md).
299
317
 
300
318
  **Cart lifecycle and checkout independence.** The cart review is a normal view, not a shell element: `view add cart` installs it, `view remove cart` drops it (which also hides the lateral's "View cart" action and leaves `/cart` unrouted; the navbar icon still opens the compact lateral). `sync` never silently adds it to an existing store — upgrading is an explicit `view add cart`.
301
- Cart and checkout are independent: review works without checkout (its action is hidden), and adding `checkout` never adds the cart view. The CLI derives `cartViewAvailable`/`checkoutAvailable` from the installed views/features into `composition.ts`, which the generated wiring reads.
319
+ Cart and checkout are independent: review works without checkout (its action is hidden), and adding `checkout` never adds the cart view. Installing `checkout` mounts the host-driven designer entry on its feature-owned `/checkout`; host cart/totals, grouped delivery, payment, and confirmation remain host-owned, with no demo simulation. See [Host-driven checkout](../blocks/docs/design-integration.md#host-driven-checkout). The CLI derives `cartViewAvailable`/`checkoutAvailable` from installed views/features into `composition.ts`.
320
+
321
+ **Checkout v1 scope:** the checkout data path works only for our own sales channels. Dropshipper sales channels require setting a custom price when adding items to the cart (custom pricing), which the current cart path does not support yet.
302
322
 
303
323
  **Account lifecycle (customer-auth).** The `customer-auth` feature owns the `/account` route, the request-scoped session read, cross-tab/foreground reconciliation, and the navbar account chrome, toggled together by `storefront feature add|remove customer-auth`; the account chrome follows the scaffold's user-owned/derived split.
304
324
  See [Account lifecycle](docs/account-lifecycle.md) — the single canonical source — for the reader, the shared client lifecycle, the real panel scope, and sync behaviour.
@@ -62,12 +62,24 @@ See the `storefront-workflow` skill for the full model and the ownership classes
62
62
 
63
63
  ## Router — intent → skill → CLI
64
64
 
65
- The user states the intent in natural language; load the skill and delegate the
66
- write to the CLI. Never edit a derived file to achieve the intent.
65
+ The user describes the outcome in natural language; the agent loads the owning
66
+ skill and chooses the commands. For editorial blocks, the user never chooses
67
+ commands or block names. Never edit a derived file to achieve the intent.
68
+
69
+ Route navigation/header requests to the shell/view procedure in `sf-view-gen`,
70
+ product listings to the owning product view/feature procedure (`sf-view-gen` or
71
+ `sf-feature`), checkout requests to the checkout feature in `sf-feature`, and
72
+ account requests to the account feature in `sf-feature`. These are not editorial
73
+ block requests; do not select an editorial section for them. The checkout feature
74
+ owns the hosted `/checkout` route; explain the host-driven checkout surface and
75
+ its backend-owned grouped delivery and designer confirmation. Discuss or
76
+ customize only user-owned checkout files under the declared ownership rules; do
77
+ not edit generated checkout files or serialize transactional state/actions.
67
78
 
68
79
  | Intent | Load skill | Delegate to CLI |
69
80
  |---|---|---|
70
81
  | Add or remove a view; compose a view's sections | `sf-view-gen` | `storefront views --json`, then `storefront view add\|remove …`; sections via `plan` → `apply` |
82
+ | Choose or configure an editorial block by intent | `sf-view-gen` | `storefront blocks list\|show --json`, `storefront section configure …`, then `storefront sync` and `storefront doctor` |
71
83
  | Customize the theme: colors, radius, fonts, presets; identity/SEO | `sf-theme-gen` | `storefront theme` — `--brand orange`, `--primary <color>`, `--accent <color>`, `--radius <length>`, `--font-sans google:Inter`, `--set light.primary=#f97316`, `--preset <ref>`, `--import <src>`, `--export <file>`, `--mode light\|dark\|system`. Visual values live in `app/globals.css`; the mode in `storefront.config.json`. Inspect with `storefront theme --inspect`. The bounded external surface stays editable by hand |
72
84
  | Add or remove a feature (e.g. `checkout`) | `sf-feature` | `storefront features --json`, then `storefront feature add\|remove …` |
73
85
  | Connect or re-point the Medusa backend; change region, sales channel, or publishable key | `sf-setup` | `storefront setup --backend-url … --publishable-key … --sales-channel-id … --region-id …` |
@@ -7,7 +7,7 @@ import { __STOREFRONT_CAMEL__App } from '@/lib/__STOREFRONT__/runtime'
7
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
- import { mountedFeatureNames } from '@/lib/__STOREFRONT__/composition'
10
+ import { mountedFeatureNames, backendCapabilities } from '@/lib/__STOREFRONT__/composition'
11
11
  import { StorefrontRenderer } from './renderer'
12
12
 
13
13
  export const { generateMetadata, generateStaticParams } = __STOREFRONT_CAMEL__App
@@ -46,7 +46,14 @@ export default async function Page({
46
46
  // cache, so concurrent requests and store contexts stay isolated); only the
47
47
  // allowlisted display identity enters the initial state, never a token.
48
48
  const accountState = mountedFeatureNames.includes('customer-auth')
49
- ? toAccountInitialState(await readAccountSession())
49
+ ? {
50
+ ...toAccountInitialState(await readAccountSession()),
51
+ // The profile email control is emitted only when the backend advertises
52
+ // email changes; the view reads this flag instead of importing the
53
+ // composition module directly.
54
+ accountEmailEditable:
55
+ Array.isArray(backendCapabilities) && backendCapabilities.includes('updateEmail'),
56
+ }
50
57
  : {}
51
58
 
52
59
  const initialState = {
@@ -0,0 +1,129 @@
1
+ // Generated by Thor Commerce storefront (template: assets/templates/app/lib/__STOREFRONT__/account-address.ts)
2
+ //
3
+ // Pure mapping between the backend address view and the address-book block's
4
+ // host port. No React, no Next.js, no transport: the Server Actions supply the
5
+ // saved addresses and this module maps them into the delivery's own shapes.
6
+ //
7
+ // The backend exposes personal addresses only, so every mapped address is
8
+ // `owner: 'personal'`, `scope: 'customer'`. Validation and logistics coverage
9
+ // are not provided by the backend and stay `unverified` / `unknown`.
10
+
11
+ import type {
12
+ AddressBookPort,
13
+ AddressDraft,
14
+ AddressListResult,
15
+ AddressPermissions,
16
+ AddressQuery,
17
+ CommerceAddress,
18
+ } from '@thorprovider/blocks/ports'
19
+
20
+ import type { AccountAddressView } from './state.core'
21
+
22
+ /** The host enforces ownership; every declared action is available to the buyer. */
23
+ export const ADDRESS_PERMISSIONS: AddressPermissions = {
24
+ view: true,
25
+ create: true,
26
+ edit: true,
27
+ delete: true,
28
+ setDefault: true,
29
+ useInCheckout: true,
30
+ }
31
+
32
+ /** The backend address view has no timestamp; expose an optional extension. */
33
+ export type AccountAddressViewWithTimestamp = AccountAddressView & { updatedAt?: string }
34
+
35
+ /** Map one saved backend address into the delivery's commerce shape. */
36
+ export function toCommerceAddress(view: AccountAddressViewWithTimestamp): CommerceAddress {
37
+ const updatedAt = typeof view.updatedAt === 'string' ? view.updatedAt : ''
38
+ return {
39
+ id: view.id,
40
+ owner: 'personal',
41
+ scope: 'customer',
42
+ ...(view.label ? { customLabel: view.label } : {}),
43
+ recipient: {
44
+ firstName: view.firstName,
45
+ lastName: view.lastName,
46
+ ...(view.phone ? { phone: view.phone } : {}),
47
+ },
48
+ postal: {
49
+ countryCode: view.countryCode,
50
+ line1: view.address1 ?? '',
51
+ ...(view.address2 ? { line2: view.address2 } : {}),
52
+ city: view.city,
53
+ region: view.province ?? '',
54
+ ...(view.postalCode ? { postalCode: view.postalCode } : {}),
55
+ },
56
+ defaults: {
57
+ shipping: view.isDefaultShipping === true,
58
+ billing: view.isDefaultBilling === true,
59
+ },
60
+ validation: 'unverified',
61
+ coverage: 'unknown',
62
+ updatedAt,
63
+ }
64
+ }
65
+
66
+ /** The list result the block consumes. Filtering and sorting stay client-side. */
67
+ export function toAddressListResult(
68
+ views: AccountAddressViewWithTimestamp[],
69
+ query?: AddressQuery,
70
+ ): AddressListResult {
71
+ const items = views.map(toCommerceAddress)
72
+ return {
73
+ items,
74
+ total: items.length,
75
+ page: query?.page ?? 1,
76
+ pageSize: query?.pageSize ?? 10,
77
+ hasMore: false,
78
+ permissions: ADDRESS_PERMISSIONS,
79
+ serverQuery: false,
80
+ }
81
+ }
82
+
83
+ /** Map the delivery's draft onto the host action's input. */
84
+ export function toAddressInput(draft: AddressDraft): {
85
+ firstName: string
86
+ lastName: string
87
+ address1: string
88
+ address2?: string
89
+ city: string
90
+ province?: string
91
+ postalCode?: string
92
+ countryCode: string
93
+ phone?: string
94
+ label?: string
95
+ } {
96
+ return {
97
+ firstName: draft.recipient.firstName,
98
+ lastName: draft.recipient.lastName,
99
+ address1: draft.postal.line1,
100
+ ...(draft.postal.line2 ? { address2: draft.postal.line2 } : {}),
101
+ city: draft.postal.city,
102
+ ...(draft.postal.region ? { province: draft.postal.region } : {}),
103
+ ...(draft.postal.postalCode ? { postalCode: draft.postal.postalCode } : {}),
104
+ countryCode: draft.postal.countryCode,
105
+ ...(draft.recipient.phone ? { phone: draft.recipient.phone } : {}),
106
+ ...(draft.customLabel ?? draft.labelId
107
+ ? { label: draft.customLabel ?? draft.labelId }
108
+ : {}),
109
+ }
110
+ }
111
+
112
+ /** Find the address a just-completed create produced. */
113
+ export function findCreatedAddress(
114
+ views: AccountAddressView[],
115
+ draft: AddressDraft,
116
+ ): AccountAddressView | undefined {
117
+ const matches = views.filter(
118
+ (view) =>
119
+ view.firstName === draft.recipient.firstName &&
120
+ view.lastName === draft.recipient.lastName &&
121
+ (view.address1 ?? '') === draft.postal.line1 &&
122
+ view.city === draft.postal.city &&
123
+ view.countryCode === draft.postal.countryCode,
124
+ )
125
+ return matches[matches.length - 1] ?? views[views.length - 1]
126
+ }
127
+
128
+ /** The optional checks the backend does not implement. */
129
+ export type AddressBookChecks = Pick<AddressBookPort, 'checkValidation' | 'checkCoverage'>
@@ -55,7 +55,7 @@ import {
55
55
  type AccountProjection,
56
56
  type AccountResolution,
57
57
  } from './account-session.core'
58
- import { accountIdentityKey, clearAccountPrivateOrders } from './account-private.core'
58
+ import { accountIdentityKey, clearAccountPrivateState } from './account-private.core'
59
59
  import { loadAccountAction, loginAction, logoutAction, registerAction } from './actions'
60
60
  import { emitAuthMutation, subscribeAuthMutations, type AuthMutationKind } from './account-mutation.client'
61
61
  import { createAuthReconcileReceiver, publishAuthInvalidation } from './account-reconcile.client'
@@ -194,7 +194,7 @@ export function useAccountLifecycle(): AccountLifecycle {
194
194
  // `/account` panel unmounted). Exposed for a shell/4.2 path that wants to drop
195
195
  // private UI before it re-resolves. The guest cart keys are never written.
196
196
  const invalidatePrivateState = useCallback(() => {
197
- clearAccountPrivateOrders(set)
197
+ clearAccountPrivateState(set)
198
198
  }, [set])
199
199
 
200
200
  // Read the LIVE projection from the store (not the render snapshot) so a guard
@@ -74,6 +74,56 @@ export function emptyAccountPrivateOrderState(
74
74
  }
75
75
  }
76
76
 
77
+ /**
78
+ * The identity-dependent account-PRIVATE module keys (profile + address book).
79
+ * Cleared with the order slice on an identity change; the flag keys
80
+ * (`accountProfileAvailable`, `accountAddressesAvailable`) are install-time
81
+ * presence, never private data, and are not in this list.
82
+ */
83
+ export const ACCOUNT_PRIVATE_MODULE_KEYS = [
84
+ 'accountProfilePending',
85
+ 'accountProfileError',
86
+ 'accountAddresses',
87
+ 'accountAddressesPending',
88
+ 'accountAddressesError',
89
+ 'accountAddressFormOpen',
90
+ 'accountAddressEditingId',
91
+ 'accountAddressMutationPending',
92
+ 'accountAddressMutationError',
93
+ 'accountAddressFieldErrors',
94
+ ] as const
95
+
96
+ export type AccountPrivateModuleKey = (typeof ACCOUNT_PRIVATE_MODULE_KEYS)[number]
97
+
98
+ export interface AccountPrivateModuleState {
99
+ accountProfilePending: boolean
100
+ accountProfileError: string | null
101
+ accountAddresses: unknown[]
102
+ accountAddressesPending: boolean
103
+ accountAddressesError: string | null
104
+ accountAddressFormOpen: boolean
105
+ accountAddressEditingId: string | null
106
+ accountAddressMutationPending: boolean
107
+ accountAddressMutationError: string | null
108
+ accountAddressFieldErrors: Record<string, string>
109
+ }
110
+
111
+ /** The reset value of every private module key. */
112
+ export function emptyAccountPrivateModuleState(): AccountPrivateModuleState {
113
+ return {
114
+ accountProfilePending: false,
115
+ accountProfileError: null,
116
+ accountAddresses: [],
117
+ accountAddressesPending: false,
118
+ accountAddressesError: null,
119
+ accountAddressFormOpen: false,
120
+ accountAddressEditingId: null,
121
+ accountAddressMutationPending: false,
122
+ accountAddressMutationError: null,
123
+ accountAddressFieldErrors: {},
124
+ }
125
+ }
126
+
77
127
  /**
78
128
  * The stable identity key for the private slice. An authenticated shopper keys
79
129
  * by the customer id; a resolved-anonymous, unavailable, or unresolved session
@@ -86,6 +136,74 @@ export function accountIdentityKey(identity: { id?: string | null } | null | und
86
136
  : 'anonymous'
87
137
  }
88
138
 
139
+ /**
140
+ * Whether an installed account module is visible in the current shape. In the
141
+ * stacked shape every module renders; in the tabbed shape only the active one.
142
+ * Kept pure so the view registry and a test share one decision.
143
+ */
144
+ export function isAccountModuleVisible(
145
+ shape: string | null | undefined,
146
+ activeTab: string | null | undefined,
147
+ moduleId: string,
148
+ ): boolean {
149
+ return shape !== 'tabs' || activeTab === moduleId
150
+ }
151
+
152
+ /** One profile field the account view declares to the canonical ProfileForm. */
153
+ export interface AccountProfileFieldView {
154
+ name: string
155
+ label: string
156
+ value: string
157
+ type?: 'text' | 'tel' | 'email'
158
+ required?: boolean
159
+ autoComplete?: string
160
+ }
161
+
162
+ /**
163
+ * Build the profile fields from the resolved customer. The email field exists
164
+ * only when the backend advertises email changes; a read-only email control is
165
+ * never emitted (the spec omits the control instead of showing an inert one).
166
+ */
167
+ export function buildAccountProfileFields(
168
+ customer: { email: string; firstName: string | null; lastName: string | null; phone?: string | null },
169
+ emailEditable: boolean,
170
+ ): AccountProfileFieldView[] {
171
+ const fields: AccountProfileFieldView[] = [
172
+ {
173
+ name: 'firstName',
174
+ label: 'Nombre',
175
+ value: customer.firstName ?? '',
176
+ required: true,
177
+ autoComplete: 'given-name',
178
+ },
179
+ {
180
+ name: 'lastName',
181
+ label: 'Apellidos',
182
+ value: customer.lastName ?? '',
183
+ required: true,
184
+ autoComplete: 'family-name',
185
+ },
186
+ {
187
+ name: 'phone',
188
+ label: 'Teléfono',
189
+ value: customer.phone ?? '',
190
+ type: 'tel',
191
+ autoComplete: 'tel',
192
+ },
193
+ ]
194
+ if (emailEditable) {
195
+ fields.unshift({
196
+ name: 'email',
197
+ label: 'Correo electrónico',
198
+ value: customer.email,
199
+ type: 'email',
200
+ required: true,
201
+ autoComplete: 'email',
202
+ })
203
+ }
204
+ return fields
205
+ }
206
+
89
207
  /**
90
208
  * Clear the identity-dependent private order state through a json-render-style
91
209
  * setter. Writes exactly `ACCOUNT_PRIVATE_ORDER_KEYS`; it never writes a guest
@@ -101,3 +219,28 @@ export function clearAccountPrivateOrders(
101
219
  set(`/${key}`, reset[key])
102
220
  }
103
221
  }
222
+
223
+ /** Clear the private module slice (profile mutation state and address book). */
224
+ export function clearAccountPrivateModules(
225
+ set: (path: string, value: unknown) => void,
226
+ ): void {
227
+ const reset = emptyAccountPrivateModuleState()
228
+ for (const key of ACCOUNT_PRIVATE_MODULE_KEYS) {
229
+ set(`/${key}`, reset[key])
230
+ }
231
+ }
232
+
233
+ /**
234
+ * Clear every identity-dependent private key in one call: the order slice and
235
+ * the module slice. The guest cart and the install-time presence flags are never
236
+ * touched. This is the clear the account claim write path uses, so an identity
237
+ * change cannot leave a previous customer's addresses or profile mutation state
238
+ * behind even when the module panel is unmounted.
239
+ */
240
+ export function clearAccountPrivateState(
241
+ set: (path: string, value: unknown) => void,
242
+ pageSize: number = ACCOUNT_ORDERS_DEFAULT_PAGE_SIZE,
243
+ ): void {
244
+ clearAccountPrivateOrders(set, pageSize)
245
+ clearAccountPrivateModules(set)
246
+ }
@@ -0,0 +1,220 @@
1
+ // Generated by Thor Commerce storefront (template: assets/templates/app/lib/__STOREFRONT__/account-profile.ts)
2
+ //
3
+ // Pure mapping between the backend customer and the customer-profile block's
4
+ // host port. No React, no Next.js, no transport: the Server Action supplies the
5
+ // customer payload and this module turns it into the delivery's own snapshot.
6
+ //
7
+ // Preferences, professional data and store-defined fields have no first-class
8
+ // backend column, so they live under `customer.metadata.profile`. The mapper
9
+ // reads only that namespace; it never projects arbitrary metadata to the client.
10
+
11
+ import type {
12
+ CustomerPreferences,
13
+ CustomerProfessional,
14
+ CustomerProfileField,
15
+ CustomerProfileOptions,
16
+ CustomerProfileSnapshot,
17
+ PhoneCountry,
18
+ ProfileDraft,
19
+ } from '@thorprovider/blocks/ports'
20
+
21
+ /** The profile-only slice of `customer.metadata`. */
22
+ export type AccountProfileMetadata = {
23
+ accountType?: 'individual' | 'business'
24
+ person?: {
25
+ middleName?: string
26
+ preferredName?: string
27
+ birthDate?: string
28
+ avatarUrl?: string
29
+ }
30
+ preferences?: CustomerPreferences
31
+ professional?: CustomerProfessional
32
+ customFields?: CustomerProfileField[]
33
+ }
34
+
35
+ export type AccountProfileMetadataPatch = Partial<AccountProfileMetadata>
36
+
37
+ /** The allowlisted customer payload the load action returns to the client. */
38
+ export type AccountProfilePayload = {
39
+ id: string
40
+ email: string
41
+ firstName: string | null
42
+ lastName: string | null
43
+ phone?: string | null
44
+ metadata?: AccountProfileMetadata
45
+ }
46
+
47
+ /**
48
+ * Store-supported profile options. This is host configuration, not demo data:
49
+ * the block can only offer values the store declares here.
50
+ */
51
+ export const PROFILE_OPTIONS: CustomerProfileOptions = {
52
+ languages: [
53
+ { value: 'es', label: 'Español' },
54
+ { value: 'en', label: 'English' },
55
+ { value: 'pt', label: 'Português' },
56
+ ],
57
+ currencies: [
58
+ { value: 'EUR', label: 'Euro (EUR)' },
59
+ { value: 'USD', label: 'Dólar estadounidense (USD)' },
60
+ { value: 'MXN', label: 'Peso mexicano (MXN)' },
61
+ ],
62
+ timezones: [
63
+ { value: 'Europe/Madrid', label: 'Madrid (UTC+1)' },
64
+ { value: 'Europe/Lisbon', label: 'Lisboa (UTC+0)' },
65
+ { value: 'America/Mexico_City', label: 'Ciudad de México (UTC−6)' },
66
+ ],
67
+ phoneCountries: [
68
+ { code: 'ES', dial: '+34', minDigits: 9, maxDigits: 9, label: 'España' },
69
+ { code: 'MX', dial: '+52', minDigits: 10, maxDigits: 10, label: 'México' },
70
+ { code: 'US', dial: '+1', minDigits: 10, maxDigits: 10, label: 'Estados Unidos' },
71
+ { code: 'CU', dial: '+53', minDigits: 8, maxDigits: 8, label: 'Cuba' },
72
+ { code: 'PT', dial: '+351', minDigits: 9, maxDigits: 9, label: 'Portugal' },
73
+ ],
74
+ }
75
+
76
+ function digits(value: string): string {
77
+ return value.replace(/\D/g, '')
78
+ }
79
+
80
+ /**
81
+ * Split a stored phone number into the delivery's country + national parts.
82
+ * A leading `+` resolves the longest matching dial code; a bare number falls
83
+ * back to the store's first declared country.
84
+ */
85
+ export function parsePhoneNumber(
86
+ value: string | null | undefined,
87
+ countries: PhoneCountry[] = PROFILE_OPTIONS.phoneCountries,
88
+ ): { countryCode: string; nationalNumber: string } | undefined {
89
+ const raw = value?.trim()
90
+ if (!raw) return undefined
91
+ const normalized = raw.replace(/[\s().-]/g, '')
92
+ if (normalized.startsWith('+')) {
93
+ const match = [...countries]
94
+ .sort((a, b) => b.dial.length - a.dial.length)
95
+ .find((country) => normalized.startsWith(country.dial))
96
+ if (match) {
97
+ return {
98
+ countryCode: match.code,
99
+ nationalNumber: digits(normalized.slice(match.dial.length)),
100
+ }
101
+ }
102
+ }
103
+ return {
104
+ countryCode: countries[0]?.code ?? '',
105
+ nationalNumber: digits(normalized),
106
+ }
107
+ }
108
+
109
+ /** Render the delivery's country + national parts as the backend phone string. */
110
+ export function formatPhoneNumber(
111
+ countryCode: string,
112
+ nationalNumber: string,
113
+ countries: PhoneCountry[] = PROFILE_OPTIONS.phoneCountries,
114
+ ): string | undefined {
115
+ const national = digits(nationalNumber)
116
+ if (!national) return undefined
117
+ const country = countries.find((candidate) => candidate.code === countryCode)
118
+ return country ? `${country.dial}${national}` : national
119
+ }
120
+
121
+ /** The customer payload plus the profile namespace, as the block's snapshot. */
122
+ export function toCustomerProfileSnapshot(
123
+ payload: AccountProfilePayload,
124
+ options: CustomerProfileOptions = PROFILE_OPTIONS,
125
+ ): CustomerProfileSnapshot {
126
+ const metadata = payload.metadata
127
+ const person = metadata?.person
128
+ const parsedPhone = parsePhoneNumber(payload.phone, options.phoneCountries)
129
+
130
+ return {
131
+ person: {
132
+ id: payload.id,
133
+ firstName: payload.firstName ?? '',
134
+ lastName: payload.lastName ?? '',
135
+ ...(person?.middleName ? { middleName: person.middleName } : {}),
136
+ ...(person?.preferredName ? { preferredName: person.preferredName } : {}),
137
+ ...(person?.birthDate ? { birthDate: person.birthDate } : {}),
138
+ ...(person?.avatarUrl ? { avatarUrl: person.avatarUrl } : {}),
139
+ email: { value: payload.email, verification: 'unverified' },
140
+ ...(parsedPhone
141
+ ? {
142
+ phone: {
143
+ countryCode: parsedPhone.countryCode,
144
+ nationalNumber: parsedPhone.nationalNumber,
145
+ verification: 'unverified' as const,
146
+ },
147
+ }
148
+ : {}),
149
+ },
150
+ accountType: metadata?.accountType ?? 'individual',
151
+ ...(metadata?.preferences ? { preferences: metadata.preferences } : {}),
152
+ ...(metadata?.professional ? { professional: metadata.professional } : {}),
153
+ customFields: metadata?.customFields ?? [],
154
+ options,
155
+ }
156
+ }
157
+
158
+ function text(draft: ProfileDraft, key: string): string {
159
+ const value = draft[key]
160
+ return typeof value === 'string' ? value.trim() : ''
161
+ }
162
+
163
+ function optional(value: string): string | undefined {
164
+ return value ? value : undefined
165
+ }
166
+
167
+ export function personalMetadataFromDraft(draft: ProfileDraft): AccountProfileMetadataPatch['person'] {
168
+ return {
169
+ middleName: optional(text(draft, 'middleName')),
170
+ preferredName: optional(text(draft, 'preferredName')),
171
+ birthDate: optional(text(draft, 'birthDate')),
172
+ }
173
+ }
174
+
175
+ export function preferencesFromDraft(draft: ProfileDraft): CustomerPreferences {
176
+ return {
177
+ language: optional(text(draft, 'language')),
178
+ currency: optional(text(draft, 'currency')),
179
+ timezone: optional(text(draft, 'timezone')),
180
+ marketingEmail: draft.marketingEmail === true,
181
+ marketingSms: draft.marketingSms === true,
182
+ commercial: draft.commercial === true,
183
+ }
184
+ }
185
+
186
+ export function professionalFromDraft(draft: ProfileDraft): CustomerProfessional {
187
+ return {
188
+ jobTitle: optional(text(draft, 'jobTitle')),
189
+ department: optional(text(draft, 'department')),
190
+ workPhone: optional(text(draft, 'workPhone')),
191
+ memberships: [],
192
+ }
193
+ }
194
+
195
+ /** Map one custom-field draft value to the field's declared type. */
196
+ export function customFieldValue(
197
+ field: CustomerProfileField,
198
+ value: string | boolean,
199
+ ): string | number | boolean | undefined {
200
+ if (field.type === 'boolean') return value === true
201
+ const raw = typeof value === 'string' ? value.trim() : ''
202
+ if (!raw) return undefined
203
+ if (field.type === 'number') {
204
+ const parsed = Number(raw)
205
+ return Number.isFinite(parsed) ? parsed : undefined
206
+ }
207
+ return raw
208
+ }
209
+
210
+ /** Apply the `custom:<key>` draft entries to the current field definitions. */
211
+ export function customFieldsFromDraft(
212
+ fields: CustomerProfileField[],
213
+ draft: ProfileDraft,
214
+ ): CustomerProfileField[] {
215
+ return fields.map((field) => {
216
+ const key = `custom:${field.key}`
217
+ if (!(key in draft)) return field
218
+ return { ...field, value: customFieldValue(field, draft[key]) }
219
+ })
220
+ }