@thorprovider/storefront 0.7.0 → 0.9.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 (151) 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 +621 -80
  9. package/assets/templates/app/lib/__STOREFRONT__/addresses-port.ts +107 -0
  10. package/assets/templates/app/lib/__STOREFRONT__/commerce.ts +346 -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__/order-detail-port.ts +26 -0
  14. package/assets/templates/app/lib/__STOREFRONT__/orders-port.ts +30 -0
  15. package/assets/templates/app/lib/__STOREFRONT__/ports.ts +18 -0
  16. package/assets/templates/app/lib/__STOREFRONT__/projection-ownership.client.tsx +4 -4
  17. package/assets/templates/app/lib/__STOREFRONT__/session.ts +24 -6
  18. package/assets/templates/app/lib/__STOREFRONT__/state.core.ts +21 -0
  19. package/assets/templates/app/lib/__STOREFRONT__/views/sections/address-book-advanced.client.tsx +29 -0
  20. package/assets/templates/app/lib/__STOREFRONT__/views/sections/checkout-commerce-v1.client.tsx +19 -0
  21. package/assets/templates/app/lib/__STOREFRONT__/views/sections/checkout-commerce-v1.tsx +16 -0
  22. package/assets/templates/app/lib/__STOREFRONT__/views/sections/customer-profile.client.tsx +27 -0
  23. package/assets/templates/app/lib/__STOREFRONT__/views/sections/index.ts +4 -1
  24. package/assets/templates/app/lib/__STOREFRONT__/views/sections/mega-menu-universal.client.tsx +19 -0
  25. package/assets/templates/app/lib/__STOREFRONT__/views/sections/mega-menu-universal.tsx +16 -0
  26. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.address-book-advanced.ts +437 -0
  27. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.checkout-commerce-v1.ts +398 -0
  28. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.customer-profile.ts +138 -0
  29. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.mega-menu-universal.ts +76 -0
  30. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.universal-banner.ts +217 -0
  31. package/assets/templates/app/lib/__STOREFRONT__/views/sections/universal-banner.client.tsx +24 -0
  32. package/assets/templates/app/lib/__STOREFRONT__/views/sections/universal-banner.tsx +16 -0
  33. package/assets/templates/features/checkout/handlers.ts +24 -4
  34. package/assets/templates/features/customer-addresses/handlers.ts +11 -0
  35. package/assets/templates/features/customer-addresses/state.ts +33 -0
  36. package/assets/templates/features/customer-auth/state.ts +10 -0
  37. package/assets/templates/features/customer-profile/handlers.ts +11 -0
  38. package/assets/templates/features/customer-profile/state.ts +18 -0
  39. package/assets/templates/views/account/address-book-advanced.defaults.ts +534 -0
  40. package/assets/templates/views/account/assembly/assembly.json +41 -0
  41. package/assets/templates/views/account/assembly/index.skeleton.tsx +229 -0
  42. package/assets/templates/views/account/assembly/registry.skeleton.tsx +1116 -0
  43. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/binding.json +5 -0
  44. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/catalog.part +4 -0
  45. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/element.part +5 -0
  46. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/registry.part +1 -0
  47. package/assets/templates/views/account/assembly/slots/addresses/cards/catalog.part +5 -0
  48. package/assets/templates/views/account/assembly/slots/addresses/cards/element.part +10 -0
  49. package/assets/templates/views/account/assembly/slots/addresses/cards/registry.part +1 -0
  50. package/assets/templates/views/account/assembly/slots/boot/AccountBoot/catalog.part +5 -0
  51. package/assets/templates/views/account/assembly/slots/boot/AccountBoot/element.part +5 -0
  52. package/assets/templates/views/account/assembly/slots/boot/AccountBoot/registry.part +1 -0
  53. package/assets/templates/views/account/assembly/slots/login/card/catalog.part +4 -0
  54. package/assets/templates/views/account/assembly/slots/login/card/element.part +13 -0
  55. package/assets/templates/views/account/assembly/slots/login/card/registry.part +1 -0
  56. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/catalog.part +5 -0
  57. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/element.part +5 -0
  58. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/registry.part +2 -0
  59. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/binding.json +5 -0
  60. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/catalog.part +5 -0
  61. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/element.part +5 -0
  62. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/registry.part +1 -0
  63. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/binding.json +5 -0
  64. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/catalog.part +4 -0
  65. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/element.part +5 -0
  66. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/registry.part +1 -0
  67. package/assets/templates/views/account/assembly/slots/profile/form/catalog.part +5 -0
  68. package/assets/templates/views/account/assembly/slots/profile/form/element.part +10 -0
  69. package/assets/templates/views/account/assembly/slots/profile/form/registry.part +1 -0
  70. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/catalog.part +4 -0
  71. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/element.part +13 -0
  72. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/registry.part +1 -0
  73. package/assets/templates/views/account/assembly/slots/summary/stack/catalog.part +5 -0
  74. package/assets/templates/views/account/assembly/slots/summary/stack/element.part +5 -0
  75. package/assets/templates/views/account/assembly/slots/summary/stack/registry.part +1 -0
  76. package/assets/templates/views/account/assembly/slots/summary/tabs/catalog.part +5 -0
  77. package/assets/templates/views/account/assembly/slots/summary/tabs/element.part +5 -0
  78. package/assets/templates/views/account/assembly/slots/summary/tabs/registry.part +1 -0
  79. package/assets/templates/views/account/content.ts +326 -0
  80. package/assets/templates/views/account/customer-profile.defaults.ts +136 -0
  81. package/assets/templates/views/account/index.tsx +218 -35
  82. package/assets/templates/views/account/order-detail.client.tsx +35 -0
  83. package/assets/templates/views/account/order-detail.defaults.ts +457 -0
  84. package/assets/templates/views/account/orders-advanced.client.tsx +166 -0
  85. package/assets/templates/views/account/orders-advanced.defaults.ts +230 -0
  86. package/assets/templates/views/account/registry.tsx +944 -369
  87. package/assets/templates/views/account/schema.ts +50 -0
  88. package/assets/templates/views/account/sections-data.ts +2 -0
  89. package/assets/templates/views/cart/content.ts +1 -0
  90. package/assets/templates/views/category/assembly/index.skeleton.tsx +1 -0
  91. package/assets/templates/views/category/assembly/slots/filter/CategoryListing/element.part +1 -0
  92. package/assets/templates/views/category/content.ts +2 -0
  93. package/assets/templates/views/category/index.tsx +2 -0
  94. package/assets/templates/views/category/sections-data.ts +2 -0
  95. package/assets/templates/views/checkout/checkout-commerce-hosted.tsx +1089 -0
  96. package/assets/templates/views/checkout/content.ts +51 -0
  97. package/assets/templates/views/checkout/index.tsx +1 -1
  98. package/assets/templates/views/checkout/props.ts +10 -2
  99. package/assets/templates/views/checkout/registry.tsx +104 -42
  100. package/assets/templates/views/checkout/schema.ts +76 -1
  101. package/assets/templates/views/home/assembly/assembly.json +22 -1
  102. package/assets/templates/views/home/assembly/index.skeleton.tsx +1 -0
  103. package/assets/templates/views/home/content.ts +2 -0
  104. package/assets/templates/views/home/index.tsx +1 -0
  105. package/assets/templates/views/home/sections-data.ts +2 -0
  106. package/assets/templates/views/product/content.ts +1 -0
  107. package/assets/templates/views/static/content.ts +1 -0
  108. package/bin/storefront.js +343 -13
  109. package/package.json +2 -1
  110. package/recipes/adapter-surface.json +158 -0
  111. package/recipes/archetypes.json +38 -3
  112. package/recipes/catalog.json +138 -1
  113. package/recipes/feature.schema.json +9 -0
  114. package/recipes/features.json +72 -1
  115. package/recipes/manifest.schema.json +5 -0
  116. package/recipes/recipe.schema.json +13 -1
  117. package/recipes/recipes.json +34 -5
  118. package/recipes/section.schema.json +112 -0
  119. package/recipes/sections.json +281 -4
  120. package/recipes/validate.mjs +83 -1
  121. package/scripts/adapter-surface.mjs +41 -0
  122. package/scripts/agent-blocks.mjs +700 -0
  123. package/scripts/block-validator.mjs +45 -0
  124. package/scripts/candidate.mjs +5 -4
  125. package/scripts/composers.mjs +7 -2
  126. package/scripts/default-sections.mjs +78 -0
  127. package/scripts/file-classes.mjs +14 -0
  128. package/scripts/generate-adapter-surface.mjs +148 -0
  129. package/scripts/operations.mjs +100 -0
  130. package/scripts/reconcile.mjs +67 -39
  131. package/scripts/section-configure.mjs +316 -0
  132. package/scripts/sync-assets.mjs +1 -0
  133. package/scripts/view-assembly.mjs +101 -14
  134. package/skills/sf-feature/SKILL.md +19 -0
  135. package/skills/sf-view-gen/SKILL.md +73 -7
  136. package/skills/sf-view-gen/assets/recipes/archetypes.json +38 -3
  137. package/skills/sf-view-gen/assets/recipes/catalog.json +138 -1
  138. package/skills/sf-view-gen/assets/recipes/features.json +72 -1
  139. package/skills/sf-view-gen/assets/recipes/recipes.json +34 -5
  140. package/skills/sf-view-gen/assets/recipes/section.schema.json +112 -0
  141. package/skills/sf-view-gen/assets/recipes/sections.json +281 -4
  142. package/skills/sf-view-gen/assets/templates/views/sections/checkout-commerce-v1.client.tsx +19 -0
  143. package/skills/sf-view-gen/assets/templates/views/sections/checkout-commerce-v1.tsx +16 -0
  144. package/skills/sf-view-gen/assets/templates/views/sections/mega-menu-universal.client.tsx +19 -0
  145. package/skills/sf-view-gen/assets/templates/views/sections/mega-menu-universal.tsx +16 -0
  146. package/skills/sf-view-gen/assets/templates/views/sections/schema.checkout-commerce-v1.ts +398 -0
  147. package/skills/sf-view-gen/assets/templates/views/sections/schema.mega-menu-universal.ts +76 -0
  148. package/skills/sf-view-gen/assets/templates/views/sections/schema.universal-banner.ts +217 -0
  149. package/skills/sf-view-gen/assets/templates/views/sections/universal-banner.client.tsx +24 -0
  150. package/skills/sf-view-gen/assets/templates/views/sections/universal-banner.tsx +16 -0
  151. package/skills/sf-view-gen/scripts/validate.mjs +83 -1
@@ -15,7 +15,7 @@
15
15
  // blindly retried; reconciliation uses the active cart id when no completed
16
16
  // receipt cookie exists yet.
17
17
 
18
- import type { AccountOrderView, CartLineState } from './state.core'
18
+ import type { AccountAddressView, AccountOrderView, CartLineState } from './state.core'
19
19
  import type {
20
20
  Address,
21
21
  CheckoutAddressOption,
@@ -32,12 +32,14 @@ import type {
32
32
  CheckoutSavedAddress,
33
33
  CheckoutShippingGroup,
34
34
  } from '@thorprovider/blocks'
35
+ import type { OrdersPage, OrdersQuery } from '@thorprovider/blocks/ports'
35
36
  import {
36
37
  EMPTY_CART_STATE,
37
38
  addVariant,
38
39
  applyCheckoutShippingGroups,
39
40
  applyLineDelta,
40
41
  applyPayment,
42
+ assignCartToCustomer,
41
43
  authenticate,
42
44
  completeOrder,
43
45
  createGuestCart,
@@ -45,11 +47,13 @@ import {
45
47
  deleteCustomerAddress,
46
48
  endSession,
47
49
  loadCheckoutCountries,
50
+ loadCartCustomerId,
48
51
  loadCheckoutShippingGroups,
49
52
  loadCustomer,
50
53
  loadCustomerAddresses,
51
54
  loadGeoCities,
52
55
  loadGeoProvinces,
56
+ loadOrderHistoryPage,
53
57
  loadOrders,
54
58
  loadOrdersPage,
55
59
  loadPaymentMethods,
@@ -67,15 +71,18 @@ import {
67
71
  toCheckoutFieldErrors,
68
72
  toCheckoutShippingGroups,
69
73
  updateCustomerAddress,
74
+ updateCustomerProfile,
75
+ getHostCommerceProvider,
70
76
  validateAddress,
71
77
  validateCustomerAddress,
72
78
  type AddressInput,
73
79
  type CartStatePatch,
80
+ type HostCommerceProvider,
74
81
  type PlaceOrderResult,
75
82
  } from './commerce'
76
83
  import { readAccountSession } from './account-session'
77
84
  import { accountIdentitySchema, type AccountIdentity } from './account-session.core'
78
- import { getStoreContext } from './store-context'
85
+ import { getDataSource, getStoreContext } from './store-context'
79
86
  import {
80
87
  bindHostSessionCart,
81
88
  clearAuthToken,
@@ -84,6 +91,7 @@ import {
84
91
  readHostSession,
85
92
  writeAuthToken,
86
93
  } from './session'
94
+ import type { AccountProfileMetadataPatch, AccountProfilePayload } from './account-profile'
87
95
 
88
96
  // A `'use server'` module may export ONLY async functions. Next/Turbopack's
89
97
  // server-actions transform registers every export as a runtime server
@@ -127,10 +135,22 @@ type CheckoutActionResult =
127
135
  ok: false
128
136
  error: string
129
137
  fieldErrors?: Record<string, unknown>
138
+ /** Stable machine code for a failure the UI must treat specially. */
139
+ code?: string
130
140
  /** Set by a failed grouped apply so the UI can distinguish unsupported. */
131
141
  shippingState?: CheckoutShippingState
132
142
  }
133
143
 
144
+ /** Raised when a checkout action requires an authenticated customer. */
145
+ class CheckoutAuthError extends Error {
146
+ readonly code = 'AUTH_REQUIRED'
147
+
148
+ constructor() {
149
+ super('Inicia sesión para continuar con el checkout.')
150
+ this.name = 'CheckoutAuthError'
151
+ }
152
+ }
153
+
134
154
  /**
135
155
  * Structured result for a login/register auth action. It carries ONLY the
136
156
  * allowlisted display identity (id/email/names) — never a token or customer
@@ -166,6 +186,11 @@ type OrdersPageActionResult =
166
186
  | { ok: true; orders: AccountOrderView[]; count: number; limit: number; offset: number }
167
187
  | { ok: false; error: string }
168
188
 
189
+ /** Structured result for one advanced order-history port query. */
190
+ type OrdersQueryPageActionResult =
191
+ | { ok: true; page: OrdersPage }
192
+ | { ok: false; error: string }
193
+
169
194
  /** Basic email shape check; a boundary guard, not a full RFC validation. */
170
195
  const EMAIL_PATTERN = /\S+@\S+\.\S+/
171
196
 
@@ -203,6 +228,17 @@ function toError(error: unknown, fallback: string): string {
203
228
  return error instanceof Error && error.message.trim() !== '' ? error.message : fallback
204
229
  }
205
230
 
231
+ /** Preserve the auth code so the checkout boot can send the shopper to login. */
232
+ function toCheckoutActionError(
233
+ error: unknown,
234
+ fallback: string,
235
+ ): { ok: false; error: string; code?: string } {
236
+ if (error instanceof CheckoutAuthError) {
237
+ return { ok: false, error: error.message, code: error.code }
238
+ }
239
+ return { ok: false, error: toError(error, fallback) }
240
+ }
241
+
206
242
  /**
207
243
  * Allowlist a backend customer to the serializable display identity before it
208
244
  * crosses the Server Action boundary. Returns `null` for a confirmed anonymous
@@ -217,30 +253,122 @@ function toDisplayIdentity(customer: Customer | null): AccountIdentity | null |
217
253
  return parsed.success ? parsed.data : undefined
218
254
  }
219
255
 
256
+ type ActiveCartContext = {
257
+ cartId: string
258
+ context: ReturnType<typeof getStoreContext>
259
+ token: string | null
260
+ provider: HostCommerceProvider
261
+ customerId: string | null
262
+ }
263
+
264
+ /** Read the authenticated customer without letting an expired token break a cart. */
265
+ async function resolveHostCustomer(token: string | null) {
266
+ if (!token) return null
267
+ try {
268
+ return await loadCustomer(token)
269
+ } catch (error) {
270
+ logServerError('resolveHostCustomer', error)
271
+ return null
272
+ }
273
+ }
274
+
220
275
  /**
221
- * Resolve the active cart id, creating and binding a new backend cart when the
222
- * session has none or its cart was completed. A new cart after a completed one
223
- * keeps the SAME shopper and preserves the prior receipt cart id, so the
224
- * receipt proof cookie is never lost.
276
+ * Resolve the active cart for the current session.
277
+ *
278
+ * When a customer token is present the provider carries it, so a newly created
279
+ * cart belongs to the customer. If the session holds a guest cart, the cart is
280
+ * transferred to the authenticated customer before reuse; a cart that already
281
+ * belongs to a different customer is never reassigned — a new cart is created
282
+ * instead. `requireAuth` is used by checkout actions and fails closed.
225
283
  */
226
- async function ensureActiveCartId(): Promise<{ cartId: string; context: ReturnType<typeof getStoreContext> }> {
284
+ async function ensureActiveCartId(
285
+ options: { requireAuth?: boolean } = {},
286
+ ): Promise<ActiveCartContext> {
227
287
  const context = getStoreContext()
288
+ const token = await readAuthToken(context)
289
+ const customer = await resolveHostCustomer(token)
290
+
291
+ // Real mode requires an authenticated customer. Mock mode is an explicit,
292
+ // labelled fixture with no auth surface, so it keeps the demo checkout usable.
293
+ const authRequired = options.requireAuth === true && getDataSource() === 'medusa'
294
+ if (authRequired && !customer) throw new CheckoutAuthError()
295
+
296
+ const provider = getHostCommerceProvider(customer ? token : null)
228
297
  const session = await readHostSession(context)
298
+
229
299
  if (session?.cartId) {
230
- const existing = await readCart(session.cartId, context)
231
- if (existing && !existing.cartCompleted) return { cartId: session.cartId, context }
300
+ try {
301
+ const existing = await readCart(session.cartId, context, provider)
302
+ if (existing && !existing.cartCompleted) {
303
+ if (!customer) {
304
+ return {
305
+ cartId: session.cartId,
306
+ context,
307
+ token,
308
+ provider,
309
+ customerId: null,
310
+ }
311
+ }
312
+
313
+ const owner = await loadCartCustomerId(session.cartId, context, provider)
314
+ if (owner === customer.id) {
315
+ return {
316
+ cartId: session.cartId,
317
+ context,
318
+ token,
319
+ provider,
320
+ customerId: customer.id,
321
+ }
322
+ }
323
+
324
+ if (owner === null) {
325
+ const linked = await assignCartToCustomer(session.cartId, context, provider)
326
+ if (linked.cartId) {
327
+ await bindHostSessionCart(context, linked.cartId)
328
+ return {
329
+ cartId: linked.cartId,
330
+ context,
331
+ token,
332
+ provider,
333
+ customerId: customer.id,
334
+ }
335
+ }
336
+ }
337
+ }
338
+ } catch (error) {
339
+ // A stale, foreign-channel or otherwise unreadable cart is replaced.
340
+ logServerError('ensureActiveCartId', error)
341
+ }
232
342
  }
233
- const created = await createGuestCart(context)
343
+
344
+ const created = await createGuestCart(context, provider)
234
345
  if (!created.cartId) throw new Error('Cart creation returned no id')
346
+
347
+ if (customer) {
348
+ try {
349
+ await assignCartToCustomer(created.cartId, context, provider)
350
+ } catch (error) {
351
+ // The authenticated create normally links the customer; a transfer failure
352
+ // is logged and the backend ownership check remains authoritative.
353
+ logServerError('assignCartToCustomer', error)
354
+ }
355
+ }
356
+
235
357
  await bindHostSessionCart(context, created.cartId)
236
- return { cartId: created.cartId, context }
358
+ return {
359
+ cartId: created.cartId,
360
+ context,
361
+ token,
362
+ provider,
363
+ customerId: customer?.id ?? null,
364
+ }
237
365
  }
238
366
 
239
367
  /** Ensure a guest cart exists and return its authoritative snapshot. */
240
368
  export async function ensureCartAction(): Promise<CartActionResult> {
241
369
  try {
242
- const { cartId, context } = await ensureActiveCartId()
243
- return { ok: true, cart: (await readCart(cartId, context)) ?? EMPTY_CART_STATE }
370
+ const { cartId, context, provider } = await ensureActiveCartId()
371
+ return { ok: true, cart: (await readCart(cartId, context, provider)) ?? EMPTY_CART_STATE }
244
372
  } catch (error) {
245
373
  return { ok: false, error: toError(error, 'No se pudo iniciar el carrito.') }
246
374
  }
@@ -254,8 +382,11 @@ export async function addToCartAction(input: {
254
382
  try {
255
383
  if (!input?.variantId) return { ok: false, error: 'Selecciona una variante antes de agregar.' }
256
384
  const quantity = Number.isFinite(input.quantity) && input.quantity > 0 ? Math.floor(input.quantity) : 1
257
- const { cartId, context } = await ensureActiveCartId()
258
- return { ok: true, cart: await addVariant(cartId, input.variantId, quantity, context) }
385
+ const { cartId, context, provider } = await ensureActiveCartId()
386
+ return {
387
+ ok: true,
388
+ cart: await addVariant(cartId, input.variantId, quantity, context, provider),
389
+ }
259
390
  } catch (error) {
260
391
  return { ok: false, error: toError(error, 'No se pudo agregar el producto.') }
261
392
  }
@@ -284,8 +415,11 @@ export async function addToCartByHandleAction(input: {
284
415
  const { detail } = await loadProductDetail(productHandle)
285
416
  const target = resolveProductCartTarget(detail)
286
417
  if (!target.ok) return { ok: false, error: target.error }
287
- const { cartId, context } = await ensureActiveCartId()
288
- return { ok: true, cart: await addVariant(cartId, target.variantId, quantity, context) }
418
+ const { cartId, context, provider } = await ensureActiveCartId()
419
+ return {
420
+ ok: true,
421
+ cart: await addVariant(cartId, target.variantId, quantity, context, provider),
422
+ }
289
423
  } catch (error) {
290
424
  return { ok: false, error: toError(error, 'No se pudo agregar el producto.') }
291
425
  }
@@ -299,10 +433,17 @@ export async function setLineQuantityAction(input: {
299
433
  }): Promise<CartActionResult> {
300
434
  try {
301
435
  const quantity = Math.max(1, Math.floor(input.quantity))
302
- const { cartId, context } = await ensureActiveCartId()
436
+ const { cartId, context, provider } = await ensureActiveCartId()
303
437
  return {
304
438
  ok: true,
305
- cart: await setLineQuantity(cartId, input.lineId, input.merchandiseId, quantity, context),
439
+ cart: await setLineQuantity(
440
+ cartId,
441
+ input.lineId,
442
+ input.merchandiseId,
443
+ quantity,
444
+ context,
445
+ provider,
446
+ ),
306
447
  }
307
448
  } catch (error) {
308
449
  return { ok: false, error: toError(error, 'No se pudo actualizar la cantidad.') }
@@ -319,8 +460,11 @@ export async function applyQuantityDeltaAction(input: {
319
460
  delta: number
320
461
  }): Promise<CartActionResult> {
321
462
  try {
322
- const { cartId, context } = await ensureActiveCartId()
323
- return { ok: true, cart: await applyLineDelta(cartId, input.lineId, input.delta, context) }
463
+ const { cartId, context, provider } = await ensureActiveCartId()
464
+ return {
465
+ ok: true,
466
+ cart: await applyLineDelta(cartId, input.lineId, input.delta, context, provider),
467
+ }
324
468
  } catch (error) {
325
469
  return { ok: false, error: toError(error, 'No se pudo actualizar la cantidad.') }
326
470
  }
@@ -329,8 +473,8 @@ export async function applyQuantityDeltaAction(input: {
329
473
  /** Remove a backend cart line by its line-item id. */
330
474
  export async function removeLineAction(input: { lineId: string }): Promise<CartActionResult> {
331
475
  try {
332
- const { cartId, context } = await ensureActiveCartId()
333
- return { ok: true, cart: await removeLine(cartId, input.lineId, context) }
476
+ const { cartId, context, provider } = await ensureActiveCartId()
477
+ return { ok: true, cart: await removeLine(cartId, input.lineId, context, provider) }
334
478
  } catch (error) {
335
479
  return { ok: false, error: toError(error, 'No se pudo quitar el producto.') }
336
480
  }
@@ -415,9 +559,10 @@ async function loadMappedShippingGroups(
415
559
  cartLines: CartLineState[],
416
560
  previous: CheckoutShippingGroup[] | undefined,
417
561
  context: ReturnType<typeof getStoreContext>,
562
+ provider?: HostCommerceProvider,
418
563
  ): Promise<CheckoutShippingGroupsLoad> {
419
564
  try {
420
- const quote = await loadCheckoutShippingGroups(cartId, context)
565
+ const quote = await loadCheckoutShippingGroups(cartId, context, provider)
421
566
  const mapped = toCheckoutShippingGroups(quote, cartLines, previous)
422
567
  return { groups: mapped.groups, productsByGroup: mapped.productsByGroup }
423
568
  } catch (error) {
@@ -449,8 +594,8 @@ export async function syncCheckoutAddressAction(
449
594
  values: Record<string, unknown>,
450
595
  ): Promise<CheckoutActionResult> {
451
596
  try {
452
- const { cartId, context } = await ensureActiveCartId()
453
- const countries = await loadCheckoutCountries(cartId, context)
597
+ const { cartId, context, provider } = await ensureActiveCartId({ requireAuth: true })
598
+ const countries = await loadCheckoutCountries(cartId, context, provider)
454
599
  const validation = validateAddress(toAddressInput(values), countries)
455
600
  if (!validation.success) {
456
601
  return {
@@ -459,8 +604,14 @@ export async function syncCheckoutAddressAction(
459
604
  fieldErrors: toCheckoutFieldErrors(validation.errors),
460
605
  }
461
606
  }
462
- const cart = await saveShippingAddress(cartId, validation.address, context)
463
- const shipping = await loadMappedShippingGroups(cartId, cart.cart, undefined, context)
607
+ const cart = await saveShippingAddress(cartId, validation.address, context, provider)
608
+ const shipping = await loadMappedShippingGroups(
609
+ cartId,
610
+ cart.cart,
611
+ undefined,
612
+ context,
613
+ provider,
614
+ )
464
615
  return {
465
616
  ok: true,
466
617
  cart,
@@ -471,7 +622,7 @@ export async function syncCheckoutAddressAction(
471
622
  : {}),
472
623
  }
473
624
  } catch (error) {
474
- return { ok: false, error: toError(error, 'No se pudo validar la dirección.') }
625
+ return toCheckoutActionError(error, 'No se pudo validar la dirección.')
475
626
  }
476
627
  }
477
628
 
@@ -484,11 +635,11 @@ export async function selectShippingMethodAction(input: {
484
635
  methodId: string
485
636
  }): Promise<CheckoutActionResult> {
486
637
  try {
487
- const { cartId, context } = await ensureActiveCartId()
488
- const cart = await selectShipping(cartId, input.methodId, context)
638
+ const { cartId, context, provider } = await ensureActiveCartId({ requireAuth: true })
639
+ const cart = await selectShipping(cartId, input.methodId, context, provider)
489
640
  return { ok: true, cart }
490
641
  } catch (error) {
491
- return { ok: false, error: toError(error, 'No se pudo seleccionar el envío.') }
642
+ return toCheckoutActionError(error, 'No se pudo seleccionar el envío.')
492
643
  }
493
644
  }
494
645
 
@@ -506,10 +657,18 @@ export async function applyCheckoutShippingGroupsAction(input: {
506
657
  if (!Array.isArray(input?.shippingGroups)) {
507
658
  return { ok: false, error: 'No se recibieron opciones de envío.' }
508
659
  }
509
- const { cartId, context } = await ensureActiveCartId()
510
- const cart = await applyCheckoutShippingGroups(cartId, input.shippingGroups, context)
660
+ const { cartId, context, provider } = await ensureActiveCartId({ requireAuth: true })
661
+ const cart = await applyCheckoutShippingGroups(
662
+ cartId,
663
+ input.shippingGroups,
664
+ context,
665
+ provider,
666
+ )
511
667
  return { ok: true, cart }
512
668
  } catch (error) {
669
+ if (error instanceof CheckoutAuthError) {
670
+ return { ok: false, error: error.message, code: error.code }
671
+ }
513
672
  // Same boundary policy as the quote path: the provider/backend detail is
514
673
  // logged server-side and the shopper gets one fixed, user-safe message. An
515
674
  // unsupported provider is `unavailable` (retrying cannot help).
@@ -536,11 +695,11 @@ export async function loadCheckoutAction(
536
695
  input: { previousShippingGroups?: CheckoutShippingGroup[] } = {},
537
696
  ): Promise<CheckoutActionResult> {
538
697
  try {
539
- const { cartId, context } = await ensureActiveCartId()
698
+ const { cartId, context, provider } = await ensureActiveCartId({ requireAuth: true })
540
699
  const [regionCountries, paymentMethods, cart] = await Promise.all([
541
- loadCheckoutCountries(cartId, context),
542
- loadPaymentMethods(context),
543
- readCart(cartId, context),
700
+ loadCheckoutCountries(cartId, context, provider),
701
+ loadPaymentMethods(context, provider),
702
+ readCart(cartId, context, provider),
544
703
  ])
545
704
  const patch = cart ?? EMPTY_CART_STATE
546
705
  const shipping = await loadMappedShippingGroups(
@@ -548,6 +707,7 @@ export async function loadCheckoutAction(
548
707
  patch.cart,
549
708
  input?.previousShippingGroups,
550
709
  context,
710
+ provider,
551
711
  )
552
712
  return {
553
713
  ok: true,
@@ -561,7 +721,7 @@ export async function loadCheckoutAction(
561
721
  : {}),
562
722
  }
563
723
  } catch (error) {
564
- return { ok: false, error: toError(error, 'No se pudo cargar el checkout.') }
724
+ return toCheckoutActionError(error, 'No se pudo cargar el checkout.')
565
725
  }
566
726
  }
567
727
 
@@ -572,7 +732,7 @@ type CheckoutPrefillPayload = ReturnType<typeof prefillCheckoutFromCustomer> & {
572
732
 
573
733
  type CheckoutPrefillActionResult =
574
734
  | ({ ok: true } & CheckoutPrefillPayload)
575
- | { ok: false; error: string }
735
+ | { ok: false; error: string; code?: string }
576
736
 
577
737
  type CheckoutLocationsActionResult =
578
738
  | { ok: true; options: CheckoutAddressOption[] }
@@ -584,7 +744,7 @@ type CheckoutSavedAddressActionResult =
584
744
  savedAddresses: CheckoutSavedAddress[]
585
745
  savedAddressId?: string
586
746
  }
587
- | { ok: false; error: string; fieldErrors?: Record<string, unknown> }
747
+ | { ok: false; error: string; code?: string; fieldErrors?: Record<string, unknown> }
588
748
 
589
749
  function toSavedAddress(address: Address, index: number): CheckoutSavedAddress {
590
750
  const optional = (value: string | undefined): string | undefined => {
@@ -642,8 +802,8 @@ export async function createCheckoutAddressAction(
642
802
  return { ok: false, error: 'Inicia sesión para guardar direcciones.' }
643
803
  }
644
804
 
645
- const { cartId } = await ensureActiveCartId()
646
- const countries = await loadCheckoutCountries(cartId, context)
805
+ const { cartId, provider } = await ensureActiveCartId({ requireAuth: true })
806
+ const countries = await loadCheckoutCountries(cartId, context, provider)
647
807
  const validation = validateCustomerAddress(address, countries)
648
808
  if (!validation.success) {
649
809
  return {
@@ -667,10 +827,7 @@ export async function createCheckoutAddressAction(
667
827
  }
668
828
  } catch (error) {
669
829
  logServerError('createCheckoutAddressAction', error)
670
- return {
671
- ok: false,
672
- error: toError(error, 'No se pudo guardar la dirección.'),
673
- }
830
+ return toCheckoutActionError(error, 'No se pudo guardar la dirección.')
674
831
  }
675
832
  }
676
833
 
@@ -686,8 +843,8 @@ export async function updateCheckoutAddressAction(input: {
686
843
  return { ok: false, error: 'Inicia sesión para actualizar direcciones.' }
687
844
  }
688
845
 
689
- const { cartId } = await ensureActiveCartId()
690
- const countries = await loadCheckoutCountries(cartId, context)
846
+ const { cartId, provider } = await ensureActiveCartId({ requireAuth: true })
847
+ const countries = await loadCheckoutCountries(cartId, context, provider)
691
848
  const validation = validateCustomerAddress(input.address, countries)
692
849
  if (!validation.success) {
693
850
  return {
@@ -703,10 +860,7 @@ export async function updateCheckoutAddressAction(input: {
703
860
  return { ok: true, savedAddresses, savedAddressId: input.id }
704
861
  } catch (error) {
705
862
  logServerError('updateCheckoutAddressAction', error)
706
- return {
707
- ok: false,
708
- error: toError(error, 'No se pudo actualizar la dirección.'),
709
- }
863
+ return toCheckoutActionError(error, 'No se pudo actualizar la dirección.')
710
864
  }
711
865
  }
712
866
 
@@ -727,10 +881,7 @@ export async function deleteCheckoutAddressAction(input: {
727
881
  return { ok: true, savedAddresses, savedAddressId: input.id }
728
882
  } catch (error) {
729
883
  logServerError('deleteCheckoutAddressAction', error)
730
- return {
731
- ok: false,
732
- error: toError(error, 'No se pudo eliminar la dirección.'),
733
- }
884
+ return toCheckoutActionError(error, 'No se pudo eliminar la dirección.')
734
885
  }
735
886
  }
736
887
 
@@ -749,8 +900,8 @@ export async function loadCheckoutPrefillAction(
749
900
  } = {},
750
901
  ): Promise<CheckoutPrefillActionResult> {
751
902
  try {
752
- const { cartId, context } = await ensureActiveCartId()
753
- const regionCountries = await loadCheckoutCountries(cartId, context)
903
+ const { cartId, context, provider, token } = await ensureActiveCartId({ requireAuth: true })
904
+ const regionCountries = await loadCheckoutCountries(cartId, context, provider)
754
905
  const countries = regionCountries.map((country) => ({
755
906
  value: country.code,
756
907
  label: country.name,
@@ -772,7 +923,6 @@ export async function loadCheckoutPrefillAction(
772
923
  sameAsShipping: input.sameAsShipping,
773
924
  }
774
925
 
775
- const token = await readAuthToken(context)
776
926
  if (!token) {
777
927
  const result = prefillCheckoutFromCustomer({
778
928
  cart: cartInput,
@@ -819,10 +969,7 @@ export async function loadCheckoutPrefillAction(
819
969
  return { ok: true, ...result, shippingLocations, billingLocations }
820
970
  }
821
971
  } catch (error) {
822
- return {
823
- ok: false,
824
- error: toError(error, 'No se pudo cargar la información del cliente.'),
825
- }
972
+ return toCheckoutActionError(error, 'No se pudo cargar la información del cliente.')
826
973
  }
827
974
  }
828
975
 
@@ -876,8 +1023,8 @@ export async function syncCheckoutAddressStructuredAction(input: {
876
1023
  previousShippingGroups?: CheckoutShippingGroup[]
877
1024
  }): Promise<CheckoutActionResult> {
878
1025
  try {
879
- const { cartId, context } = await ensureActiveCartId()
880
- const countries = await loadCheckoutCountries(cartId, context)
1026
+ const { cartId, context, provider } = await ensureActiveCartId({ requireAuth: true })
1027
+ const countries = await loadCheckoutCountries(cartId, context, provider)
881
1028
  const validation = validateAddress(
882
1029
  {
883
1030
  email: input.contact.email,
@@ -902,7 +1049,7 @@ export async function syncCheckoutAddressStructuredAction(input: {
902
1049
  }
903
1050
  }
904
1051
 
905
- const cart = await saveShippingAddress(cartId, validation.address, context)
1052
+ const cart = await saveShippingAddress(cartId, validation.address, context, provider)
906
1053
  if (!input.sameAsShipping && input.billingAddress) {
907
1054
  await saveBillingAddress(
908
1055
  cartId,
@@ -919,6 +1066,7 @@ export async function syncCheckoutAddressStructuredAction(input: {
919
1066
  phone: input.billingAddress.phone ?? '',
920
1067
  },
921
1068
  context,
1069
+ provider,
922
1070
  )
923
1071
  }
924
1072
 
@@ -927,6 +1075,7 @@ export async function syncCheckoutAddressStructuredAction(input: {
927
1075
  cart.cart,
928
1076
  input.previousShippingGroups,
929
1077
  context,
1078
+ provider,
930
1079
  )
931
1080
  return {
932
1081
  ok: true,
@@ -938,7 +1087,7 @@ export async function syncCheckoutAddressStructuredAction(input: {
938
1087
  : {}),
939
1088
  }
940
1089
  } catch (error) {
941
- return { ok: false, error: toError(error, 'No se pudo validar la dirección.') }
1090
+ return toCheckoutActionError(error, 'No se pudo validar la dirección.')
942
1091
  }
943
1092
  }
944
1093
 
@@ -976,15 +1125,30 @@ async function clearConfirmedSession(
976
1125
  * a committed order as a retryable failure.
977
1126
  */
978
1127
  export async function placeOrderAction(
979
- input: { shippingGroups?: ShippingGroupSelection[] } = {},
1128
+ input: { shippingGroups?: ShippingGroupSelection[]; paymentMethodId?: string } = {},
980
1129
  ): Promise<PlaceOrderResult> {
981
1130
  try {
982
- const context = getStoreContext()
983
- const session = await readHostSession(context)
984
- if (!session?.cartId) {
985
- return { status: 'error', message: 'No hay un carrito activo.' }
1131
+ const { cartId, context, provider, customerId } = await ensureActiveCartId({
1132
+ requireAuth: true,
1133
+ })
1134
+ if (!customerId && getDataSource() === 'medusa') {
1135
+ return {
1136
+ status: 'error',
1137
+ message: 'Inicia sesión para completar el pedido.',
1138
+ code: 'AUTH_REQUIRED',
1139
+ }
986
1140
  }
987
- const cartId = session.cartId
1141
+
1142
+ const paymentMethodId =
1143
+ typeof input.paymentMethodId === 'string' ? input.paymentMethodId.trim() : ''
1144
+ if (!paymentMethodId) {
1145
+ return {
1146
+ status: 'error',
1147
+ message: 'Selecciona un método de pago antes de confirmar.',
1148
+ code: 'PAYMENT_METHOD_REQUIRED',
1149
+ }
1150
+ }
1151
+
988
1152
  const shippingGroups = input?.shippingGroups
989
1153
  if (shippingGroups) {
990
1154
  // An explicitly empty selection set means the delivery step was not
@@ -999,7 +1163,7 @@ export async function placeOrderAction(
999
1163
  }
1000
1164
  }
1001
1165
  try {
1002
- await applyCheckoutShippingGroups(cartId, shippingGroups, context)
1166
+ await applyCheckoutShippingGroups(cartId, shippingGroups, context, provider)
1003
1167
  } catch (error) {
1004
1168
  // Logged server-side only; the shopper gets a fixed recoverable message.
1005
1169
  logServerError('applyCheckoutShippingGroups', error)
@@ -1011,12 +1175,20 @@ export async function placeOrderAction(
1011
1175
  }
1012
1176
  }
1013
1177
  try {
1014
- await applyPayment(cartId, context)
1178
+ await applyPayment(cartId, paymentMethodId, context, provider)
1015
1179
  } catch (error) {
1016
1180
  logServerError('applyPayment', error)
1017
- return { status: 'error', message: toError(error, 'No se pudo iniciar el pago.') }
1181
+ return {
1182
+ status: 'error',
1183
+ message: toError(error, 'No se pudo iniciar el pago.'),
1184
+ code: 'PAYMENT_METHOD_REJECTED',
1185
+ }
1018
1186
  }
1019
- const result = await completeOrder(cartId, context)
1187
+ // Thread the request's customer token (design D11) so an authenticated
1188
+ // checkout is attributed to the session customer; guests complete the same
1189
+ // tokenless provider as before.
1190
+ const customerToken = await readAuthToken(context)
1191
+ const result = await completeOrder(cartId, context, customerToken)
1020
1192
  if (result.status !== 'order') return result
1021
1193
  if (!(await clearConfirmedSession(context, cartId))) {
1022
1194
  return {
@@ -1027,6 +1199,9 @@ export async function placeOrderAction(
1027
1199
  }
1028
1200
  return result
1029
1201
  } catch (error) {
1202
+ if (error instanceof CheckoutAuthError) {
1203
+ return { status: 'error', message: error.message, code: error.code }
1204
+ }
1030
1205
  // An unexpected failure during completion is ambiguous: never a blind retry.
1031
1206
  logServerError('placeOrderAction', error)
1032
1207
  return {
@@ -1047,10 +1222,22 @@ export async function placeOrderAction(
1047
1222
  export async function reconcileReceiptAction(): Promise<PlaceOrderResult> {
1048
1223
  try {
1049
1224
  const context = getStoreContext()
1225
+ const token = await readAuthToken(context)
1226
+ if (!token && getDataSource() === 'medusa') {
1227
+ return {
1228
+ status: 'error',
1229
+ message: 'Inicia sesión para recuperar el comprobante.',
1230
+ code: 'AUTH_REQUIRED',
1231
+ }
1232
+ }
1233
+ const provider = getHostCommerceProvider(token)
1050
1234
  const session = await readHostSession(context)
1051
1235
  if (!session) {
1052
1236
  return { status: 'unresolved', message: 'No hay un comprobante autorizado para esta sesión.' }
1053
1237
  }
1238
+ // Same threading as the completion (design D11): the reconcile completes
1239
+ // under the session customer when one is signed in.
1240
+ const customerToken = await readAuthToken(context)
1054
1241
 
1055
1242
  // An active cart is reconciled first: the runtime does a single GET and
1056
1243
  // only POSTs complete when the backend committed. A cart the backend did
@@ -1059,7 +1246,7 @@ export async function reconcileReceiptAction(): Promise<PlaceOrderResult> {
1059
1246
  // The active cart is only cleared when it is the committed cart; a new cart
1060
1247
  // started after an earlier order is preserved by the session core.
1061
1248
  if (session.cartId) {
1062
- const result = await reconcileOrder(session.cartId, context)
1249
+ const result = await reconcileOrder(session.cartId, context, customerToken)
1063
1250
  if (result.status === 'order') {
1064
1251
  await clearConfirmedSession(context, session.cartId)
1065
1252
  return result
@@ -1074,7 +1261,7 @@ export async function reconcileReceiptAction(): Promise<PlaceOrderResult> {
1074
1261
  if (!candidate) {
1075
1262
  return { status: 'unresolved', message: 'No hay un comprobante autorizado para esta sesión.' }
1076
1263
  }
1077
- const result = await reconcileOrder(candidate, context)
1264
+ const result = await reconcileOrder(candidate, context, customerToken)
1078
1265
  if (result.status === 'order') {
1079
1266
  await clearConfirmedSession(context, candidate)
1080
1267
  return result
@@ -1277,3 +1464,357 @@ export async function loadOrdersPageAction(input?: {
1277
1464
  return { ok: false, error: toError(error, 'No se pudieron cargar tus pedidos.') }
1278
1465
  }
1279
1466
  }
1467
+
1468
+ /**
1469
+ * One query window for the advanced order-history port. The block owns its
1470
+ * filtering, sorting and pagination UI; this action is the request-scoped read
1471
+ * behind `OrdersPort.list`, the same token-scoped history the canonical surface
1472
+ * reads. It touches ONLY the auth cookie — never the guest session cookie or the
1473
+ * cart — and no token is logged or returned. A missing token resolves to the
1474
+ * empty page without contacting the backend.
1475
+ */
1476
+ export async function listOrdersQueryPageAction(
1477
+ query: OrdersQuery,
1478
+ ): Promise<OrdersQueryPageActionResult> {
1479
+ const context = getStoreContext()
1480
+ const token = await readAuthToken(context)
1481
+ try {
1482
+ const page = await loadOrderHistoryPage(token, query, context)
1483
+ return { ok: true, page }
1484
+ } catch (error) {
1485
+ logServerError('listOrdersQueryPageAction', error)
1486
+ return { ok: false, error: toError(error, 'No se pudieron cargar tus pedidos.') }
1487
+ }
1488
+ }
1489
+
1490
+ // ---------------------------------------------------------------------------
1491
+ // Account modules (change: storefront-customer-view, task 4.4)
1492
+ // ---------------------------------------------------------------------------
1493
+ //
1494
+ // Profile and address-book mutations are account-scoped: they use ONLY the auth
1495
+ // cookie, never the guest cart, and never require a checkout region. Every action
1496
+ // returns an allowlisted, serializable result and never a token.
1497
+
1498
+ type AccountProfileResult =
1499
+ | { ok: true; customer: Pick<Customer, 'id' | 'email' | 'firstName' | 'lastName'> }
1500
+ | { ok: false; error: string; fieldErrors?: Record<string, string> }
1501
+
1502
+ type AccountAddressesResult =
1503
+ | { ok: true; addresses: AccountAddressView[] }
1504
+ | { ok: false; error: string }
1505
+
1506
+ type AccountAddressMutationResult =
1507
+ | { ok: true; addresses: AccountAddressView[] }
1508
+ | { ok: false; error: string; fieldErrors?: Record<string, string> }
1509
+
1510
+ interface AccountAddressInput {
1511
+ firstName: string
1512
+ lastName: string
1513
+ address1: string
1514
+ address2?: string
1515
+ city: string
1516
+ province?: string
1517
+ postalCode?: string
1518
+ countryCode: string
1519
+ phone?: string
1520
+ label?: string
1521
+ }
1522
+
1523
+ function optionalText(value: string | undefined): string | undefined {
1524
+ const trimmed = value?.trim()
1525
+ return trimmed ? value : undefined
1526
+ }
1527
+
1528
+ function toAccountAddress(address: Address, index: number): AccountAddressView {
1529
+ return {
1530
+ id: address.id ?? `account-address-${index}`,
1531
+ firstName: address.firstName,
1532
+ lastName: address.lastName,
1533
+ ...(optionalText(address.address1) ? { address1: address.address1 } : {}),
1534
+ ...(optionalText(address.address2) ? { address2: address.address2 } : {}),
1535
+ city: address.city,
1536
+ ...(optionalText(address.province) ? { province: address.province } : {}),
1537
+ ...(optionalText(address.postalCode) ? { postalCode: address.postalCode } : {}),
1538
+ countryCode: address.countryCode,
1539
+ ...(optionalText(address.phone) ? { phone: address.phone } : {}),
1540
+ ...(optionalText(address.label) ? { label: address.label } : {}),
1541
+ ...(address.isDefaultShipping ? { isDefaultShipping: true } : {}),
1542
+ ...(address.isDefaultBilling ? { isDefaultBilling: true } : {}),
1543
+ }
1544
+ }
1545
+
1546
+ async function readAccountToken(): Promise<string | null> {
1547
+ return readAuthToken(getStoreContext())
1548
+ }
1549
+
1550
+ /**
1551
+ * Update the authenticated customer's profile. Only the fields the caller
1552
+ * supplies are sent; the returned identity is allowlisted to the same keys the
1553
+ * session projection exposes.
1554
+ */
1555
+ export async function updateAccountProfileAction(input: {
1556
+ firstName?: string
1557
+ lastName?: string
1558
+ phone?: string
1559
+ email?: string
1560
+ /** Namespaced profile metadata to merge; never replaces unrelated metadata. */
1561
+ profile?: AccountProfileMetadataPatch
1562
+ }): Promise<AccountProfileResult> {
1563
+ const token = await readAccountToken()
1564
+ if (!token) return { ok: false, error: 'Inicia sesión para actualizar tu perfil.' }
1565
+
1566
+ const fieldErrors: Record<string, string> = {}
1567
+ const firstName = input.firstName?.trim()
1568
+ const lastName = input.lastName?.trim()
1569
+ const email = input.email?.trim()
1570
+ if (!firstName) fieldErrors.firstName = 'El nombre es obligatorio.'
1571
+ if (!lastName) fieldErrors.lastName = 'Los apellidos son obligatorios.'
1572
+ if (email !== undefined && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
1573
+ fieldErrors.email = 'El correo no es válido.'
1574
+ }
1575
+ if (Object.keys(fieldErrors).length > 0) {
1576
+ return { ok: false, error: 'Revisa los datos antes de guardar.', fieldErrors }
1577
+ }
1578
+
1579
+ try {
1580
+ let metadata: Record<string, unknown> | undefined
1581
+ if (input.profile) {
1582
+ const current = await loadCustomer(token)
1583
+ const base = current && isRecord(current.metadata) ? current.metadata : {}
1584
+ const profile = isRecord(base.profile) ? base.profile : {}
1585
+ metadata = { ...base, profile: mergeProfileMetadata(profile, input.profile) }
1586
+ }
1587
+
1588
+ const customer = await updateCustomerProfile(token, {
1589
+ ...(firstName ? { firstName } : {}),
1590
+ ...(lastName ? { lastName } : {}),
1591
+ ...(input.phone !== undefined ? { phone: optionalText(input.phone) ?? '' } : {}),
1592
+ ...(email !== undefined ? { email } : {}),
1593
+ ...(metadata ? { metadata } : {}),
1594
+ })
1595
+ return {
1596
+ ok: true,
1597
+ customer: {
1598
+ id: customer.id,
1599
+ email: customer.email,
1600
+ firstName: customer.firstName,
1601
+ lastName: customer.lastName,
1602
+ },
1603
+ }
1604
+ } catch (error) {
1605
+ logServerError('updateAccountProfileAction', error)
1606
+ return { ok: false, error: toError(error, 'No se pudo guardar tu perfil.') }
1607
+ }
1608
+ }
1609
+
1610
+ function isRecord(value: unknown): value is Record<string, unknown> {
1611
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
1612
+ }
1613
+
1614
+ /** Merge the profile namespace without dropping unrelated metadata keys. */
1615
+ function mergeProfileMetadata(
1616
+ current: Record<string, unknown>,
1617
+ patch: AccountProfileMetadataPatch,
1618
+ ): Record<string, unknown> {
1619
+ return {
1620
+ ...current,
1621
+ ...patch,
1622
+ ...(patch.person
1623
+ ? { person: { ...(isRecord(current.person) ? current.person : {}), ...patch.person } }
1624
+ : {}),
1625
+ ...(patch.preferences
1626
+ ? {
1627
+ preferences: {
1628
+ ...(isRecord(current.preferences) ? current.preferences : {}),
1629
+ ...patch.preferences,
1630
+ },
1631
+ }
1632
+ : {}),
1633
+ ...(patch.professional
1634
+ ? {
1635
+ professional: {
1636
+ ...(isRecord(current.professional) ? current.professional : {}),
1637
+ ...patch.professional,
1638
+ },
1639
+ }
1640
+ : {}),
1641
+ ...(patch.customFields ? { customFields: patch.customFields } : {}),
1642
+ }
1643
+ }
1644
+
1645
+ type AccountProfileLoadResult =
1646
+ | { ok: true; profile: AccountProfilePayload }
1647
+ | { ok: false; error: string }
1648
+
1649
+ /**
1650
+ * Load the authenticated customer's full profile. Only the profile namespace
1651
+ * of `metadata` is returned; unrelated backend metadata never reaches the
1652
+ * client.
1653
+ */
1654
+ export async function loadAccountProfileAction(): Promise<AccountProfileLoadResult> {
1655
+ const token = await readAccountToken()
1656
+ if (!token) return { ok: false, error: 'Inicia sesión para ver tu perfil.' }
1657
+
1658
+ try {
1659
+ const customer = await loadCustomer(token)
1660
+ if (!customer) return { ok: false, error: 'Inicia sesión para ver tu perfil.' }
1661
+ const metadata = isRecord(customer.metadata) ? customer.metadata : {}
1662
+ const profile = isRecord(metadata.profile)
1663
+ ? (metadata.profile as AccountProfilePayload['metadata'])
1664
+ : undefined
1665
+ return {
1666
+ ok: true,
1667
+ profile: {
1668
+ id: customer.id,
1669
+ email: customer.email,
1670
+ firstName: customer.firstName,
1671
+ lastName: customer.lastName,
1672
+ ...(customer.phone ? { phone: customer.phone } : {}),
1673
+ ...(profile ? { metadata: profile } : {}),
1674
+ },
1675
+ }
1676
+ } catch (error) {
1677
+ logServerError('loadAccountProfileAction', error)
1678
+ return { ok: false, error: toError(error, 'No se pudo cargar tu perfil.') }
1679
+ }
1680
+ }
1681
+
1682
+ /** Persist the profile-only metadata namespace without touching identity fields. */
1683
+ export async function updateAccountProfileMetadataAction(
1684
+ patch: AccountProfileMetadataPatch,
1685
+ ): Promise<{ ok: true } | { ok: false; error: string }> {
1686
+ const token = await readAccountToken()
1687
+ if (!token) return { ok: false, error: 'Inicia sesión para actualizar tu perfil.' }
1688
+
1689
+ try {
1690
+ const customer = await loadCustomer(token)
1691
+ if (!customer) return { ok: false, error: 'Inicia sesión para actualizar tu perfil.' }
1692
+ const metadata = isRecord(customer.metadata) ? customer.metadata : {}
1693
+ const current = isRecord(metadata.profile) ? metadata.profile : {}
1694
+ await updateCustomerProfile(token, {
1695
+ metadata: { ...metadata, profile: mergeProfileMetadata(current, patch) },
1696
+ })
1697
+ return { ok: true }
1698
+ } catch (error) {
1699
+ logServerError('updateAccountProfileMetadataAction', error)
1700
+ return { ok: false, error: toError(error, 'No se pudo guardar tu perfil.') }
1701
+ }
1702
+ }
1703
+
1704
+ /** Load the authenticated customer's address book. */
1705
+ export async function loadAccountAddressesAction(): Promise<AccountAddressesResult> {
1706
+ const token = await readAccountToken()
1707
+ if (!token) return { ok: true, addresses: [] }
1708
+ try {
1709
+ const addresses = await loadCustomerAddresses(token)
1710
+ return { ok: true, addresses: addresses.map(toAccountAddress) }
1711
+ } catch (error) {
1712
+ logServerError('loadAccountAddressesAction', error)
1713
+ return { ok: false, error: toError(error, 'No se pudieron cargar tus direcciones.') }
1714
+ }
1715
+ }
1716
+
1717
+ function validateAccountAddress(input: AccountAddressInput): Record<string, string> {
1718
+ const errors: Record<string, string> = {}
1719
+ if (!input.firstName?.trim()) errors.firstName = 'El nombre es obligatorio.'
1720
+ if (!input.lastName?.trim()) errors.lastName = 'Los apellidos son obligatorios.'
1721
+ if (!input.address1?.trim()) errors.address1 = 'La dirección es obligatoria.'
1722
+ if (!input.city?.trim()) errors.city = 'La ciudad es obligatoria.'
1723
+ if (!/^[A-Za-z]{2}$/.test(input.countryCode?.trim() ?? '')) {
1724
+ errors.countryCode = 'Usa un código de país ISO de dos letras.'
1725
+ }
1726
+ return errors
1727
+ }
1728
+
1729
+ function toAddressData(input: AccountAddressInput): CreateAddressData {
1730
+ return {
1731
+ firstName: input.firstName,
1732
+ lastName: input.lastName,
1733
+ address1: input.address1,
1734
+ address2: optionalText(input.address2),
1735
+ city: input.city,
1736
+ province: optionalText(input.province),
1737
+ postalCode: optionalText(input.postalCode),
1738
+ countryCode: input.countryCode.toUpperCase(),
1739
+ phone: optionalText(input.phone),
1740
+ label: optionalText(input.label),
1741
+ }
1742
+ }
1743
+
1744
+ async function refreshAccountAddresses(token: string): Promise<AccountAddressView[]> {
1745
+ const addresses = await loadCustomerAddresses(token)
1746
+ return addresses.map(toAccountAddress)
1747
+ }
1748
+
1749
+ /** Create an address in the authenticated customer's address book. */
1750
+ export async function createAccountAddressAction(
1751
+ input: AccountAddressInput,
1752
+ ): Promise<AccountAddressMutationResult> {
1753
+ const token = await readAccountToken()
1754
+ if (!token) return { ok: false, error: 'Inicia sesión para guardar direcciones.' }
1755
+ const fieldErrors = validateAccountAddress(input)
1756
+ if (Object.keys(fieldErrors).length > 0) {
1757
+ return { ok: false, error: 'Revisa la dirección antes de guardarla.', fieldErrors }
1758
+ }
1759
+ try {
1760
+ await createCustomerAddress(token, toAddressData(input))
1761
+ return { ok: true, addresses: await refreshAccountAddresses(token) }
1762
+ } catch (error) {
1763
+ logServerError('createAccountAddressAction', error)
1764
+ return { ok: false, error: toError(error, 'No se pudo guardar la dirección.') }
1765
+ }
1766
+ }
1767
+
1768
+ /** Update a saved address; omitted optional values are preserved by the adapter. */
1769
+ export async function updateAccountAddressAction(
1770
+ input: AccountAddressInput & { id: string },
1771
+ ): Promise<AccountAddressMutationResult> {
1772
+ const token = await readAccountToken()
1773
+ if (!token) return { ok: false, error: 'Inicia sesión para guardar direcciones.' }
1774
+ const fieldErrors = validateAccountAddress(input)
1775
+ if (Object.keys(fieldErrors).length > 0) {
1776
+ return { ok: false, error: 'Revisa la dirección antes de guardarla.', fieldErrors }
1777
+ }
1778
+ try {
1779
+ await updateCustomerAddress(token, input.id, toAddressData(input))
1780
+ return { ok: true, addresses: await refreshAccountAddresses(token) }
1781
+ } catch (error) {
1782
+ logServerError('updateAccountAddressAction', error)
1783
+ return { ok: false, error: toError(error, 'No se pudo guardar la dirección.') }
1784
+ }
1785
+ }
1786
+
1787
+ /** Delete a saved address; the backend enforces ownership. */
1788
+ export async function deleteAccountAddressAction(input: {
1789
+ id: string
1790
+ }): Promise<AccountAddressMutationResult> {
1791
+ const token = await readAccountToken()
1792
+ if (!token) return { ok: false, error: 'Inicia sesión para eliminar direcciones.' }
1793
+ try {
1794
+ await deleteCustomerAddress(token, input.id)
1795
+ return { ok: true, addresses: await refreshAccountAddresses(token) }
1796
+ } catch (error) {
1797
+ logServerError('deleteAccountAddressAction', error)
1798
+ return { ok: false, error: toError(error, 'No se pudo eliminar la dirección.') }
1799
+ }
1800
+ }
1801
+
1802
+ /** Mark an address as the default shipping or billing address. */
1803
+ export async function setDefaultAccountAddressAction(input: {
1804
+ id: string
1805
+ kind: 'shipping' | 'billing'
1806
+ }): Promise<AccountAddressMutationResult> {
1807
+ const token = await readAccountToken()
1808
+ if (!token) return { ok: false, error: 'Inicia sesión para actualizar direcciones.' }
1809
+ try {
1810
+ await updateCustomerAddress(
1811
+ token,
1812
+ input.id,
1813
+ input.kind === 'shipping' ? { isDefaultShipping: true } : { isDefaultBilling: true },
1814
+ )
1815
+ return { ok: true, addresses: await refreshAccountAddresses(token) }
1816
+ } catch (error) {
1817
+ logServerError('setDefaultAccountAddressAction', error)
1818
+ return { ok: false, error: toError(error, 'No se pudo actualizar la dirección.') }
1819
+ }
1820
+ }