@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
@@ -33,18 +33,25 @@ import type {
33
33
  ShippingGroupSelection,
34
34
  ShippingMethod,
35
35
  StoreContext,
36
+ UpdateCustomerData,
36
37
  } from '@thorprovider/types'
38
+ import {
39
+ toStorefrontConfirmation,
40
+ type StorefrontConfirmation,
41
+ } from './confirmation.core'
37
42
  import {
38
43
  addCartLines,
39
44
  applyCheckoutShippingGroups as applyCheckoutShippingGroupsRuntime,
40
- applyManualTestPayment,
45
+ applyPaymentMethod as applyPaymentMethodRuntime,
41
46
  APPROVED_MANUAL_TEST_PROVIDER_ID,
47
+ assignCartToCustomer as assignCartToCustomerRuntime,
42
48
  completeCart,
43
49
  createCartForContext,
44
50
  createCustomerAddress as createCustomerAddressRuntime,
45
51
  deleteCustomerAddress as deleteCustomerAddressRuntime,
46
52
  getCartForContext,
47
53
  getCheckoutCountries,
54
+ getCommerceClientWithToken,
48
55
  getCheckoutShippingGroups as getCheckoutShippingGroupsRuntime,
49
56
  getCurrentCustomer,
50
57
  getCustomerAddresses,
@@ -52,11 +59,13 @@ import {
52
59
  getGeoCities,
53
60
  getGeoProvinces,
54
61
  getCustomerOrdersPage,
62
+ getCustomerOrderDetail,
55
63
  getEligibleShippingMethods,
56
64
  getPaymentMethodsByRegion,
57
65
  getProductDetailByHandle,
58
66
  loginCustomer,
59
67
  logoutCustomer,
68
+ updateCustomer as updateCustomerRuntime,
60
69
  reconcileCart,
61
70
  registerCustomer,
62
71
  removeCartLines,
@@ -89,6 +98,12 @@ import type {
89
98
  StorefrontOrderLineView,
90
99
  } from './state.core'
91
100
  import { assertBackendConfigured, getDataSource, getStoreContext, type StoreDataSource } from './store-context'
101
+ // The query engine is imported through its server-safe subpath: the package
102
+ // root is a client entry (`'use client'`), so a Server Action cannot call a
103
+ // function exported from it (React refuses a client function on the server).
104
+ import { queryOrderHistoryPage } from '@thorprovider/blocks/order-history-engine'
105
+ import type { OrderHistoryAdvancedRecord } from '@thorprovider/blocks'
106
+ import type { OrdersPage, OrdersQuery } from '@thorprovider/blocks/ports'
92
107
 
93
108
  // ---------------------------------------------------------------------------
94
109
  // Projections (serializable; the UI state holds these)
@@ -116,9 +131,24 @@ export const EMPTY_CART_STATE: CartStatePatch = {
116
131
  cartSelectedShippingOptionId: null,
117
132
  }
118
133
 
134
+ /**
135
+ * Request-scoped provider used by the host. A customer token produces a
136
+ * provider whose SDK carries that token; no token produces the guest provider.
137
+ */
138
+ export type HostCommerceProvider = ReturnType<typeof getCommerceClientWithToken>
139
+
140
+ export function getHostCommerceProvider(token: string | null): HostCommerceProvider {
141
+ return getCommerceClientWithToken(token)
142
+ }
143
+
119
144
  /** Result of a completion attempt. `unresolved` must never be blindly retried. */
120
145
  export type PlaceOrderResult =
121
- | { status: 'order'; order: StorefrontOrder; lines: StorefrontOrderLineView[] }
146
+ | {
147
+ status: 'order'
148
+ order: StorefrontOrder
149
+ lines: StorefrontOrderLineView[]
150
+ confirmation: StorefrontConfirmation
151
+ }
122
152
  | { status: 'error'; message: string; code?: string }
123
153
  | { status: 'cart-error'; message: string; code?: string }
124
154
  | { status: 'unresolved'; message: string; code?: string }
@@ -264,7 +294,12 @@ export function toCheckoutFieldErrors(errors: CheckoutFieldError[]): CheckoutFie
264
294
  /** Map the runtime's discriminated completion to the host result union. */
265
295
  export function toPlaceOrderResult(result: CartCompletionResult): PlaceOrderResult {
266
296
  if (result.type === 'order') {
267
- return { status: 'order', order: toStorefrontOrder(result.order), lines: toOrderLines(result.order) }
297
+ return {
298
+ status: 'order',
299
+ order: toStorefrontOrder(result.order),
300
+ lines: toOrderLines(result.order),
301
+ confirmation: toStorefrontConfirmation(result.order),
302
+ }
268
303
  }
269
304
  if (result.type === 'cart') {
270
305
  return { status: 'cart-error', message: result.error.message, code: result.error.code }
@@ -317,18 +352,31 @@ export function resolveProductCartTarget(
317
352
  export async function readCart(
318
353
  cartId: string,
319
354
  context: StoreContext = getStoreContext(),
355
+ provider?: HostCommerceProvider,
320
356
  ): Promise<CartStatePatch | undefined> {
321
357
  assertBackendConfigured()
322
- const cart = await getCartForContext(cartId, context)
358
+ const cart = await getCartForContext(cartId, context, provider)
323
359
  return cart ? toCartState(cart) : undefined
324
360
  }
325
361
 
362
+ /** The backend customer id of a cart, or undefined when the cart is missing. */
363
+ export async function loadCartCustomerId(
364
+ cartId: string,
365
+ context: StoreContext = getStoreContext(),
366
+ provider?: HostCommerceProvider,
367
+ ): Promise<string | null | undefined> {
368
+ assertBackendConfigured()
369
+ const cart = await getCartForContext(cartId, context, provider)
370
+ return cart ? (cart.customerId ?? null) : undefined
371
+ }
372
+
326
373
  export async function loadCheckoutCountries(
327
374
  cartId: string,
328
375
  context: StoreContext = getStoreContext(),
376
+ provider?: HostCommerceProvider,
329
377
  ): Promise<RegionCountry[]> {
330
378
  assertBackendConfigured()
331
- return getCheckoutCountries(cartId, context)
379
+ return getCheckoutCountries(cartId, context, provider)
332
380
  }
333
381
 
334
382
  /** Persist a billing address distinct from shipping, when the provider supports it. */
@@ -336,17 +384,19 @@ export async function saveBillingAddress(
336
384
  cartId: string,
337
385
  address: BillingAddressInput,
338
386
  context: StoreContext = getStoreContext(),
387
+ provider?: HostCommerceProvider,
339
388
  ): Promise<void> {
340
389
  assertBackendConfigured()
341
- return updateBillingAddress(cartId, address)
390
+ return updateBillingAddress(cartId, address, provider)
342
391
  }
343
392
 
344
393
  export async function loadShippingMethods(
345
394
  cartId: string,
346
395
  context: StoreContext = getStoreContext(),
396
+ provider?: HostCommerceProvider,
347
397
  ): Promise<ShippingMethod[]> {
348
398
  assertBackendConfigured()
349
- return getEligibleShippingMethods(cartId, context)
399
+ return getEligibleShippingMethods(cartId, context, provider)
350
400
  }
351
401
 
352
402
  /**
@@ -357,9 +407,10 @@ export async function loadShippingMethods(
357
407
  export async function loadCheckoutShippingGroups(
358
408
  cartId: string,
359
409
  context: StoreContext = getStoreContext(),
410
+ provider?: HostCommerceProvider,
360
411
  ): Promise<ShippingGroupQuote> {
361
412
  assertBackendConfigured()
362
- return getCheckoutShippingGroupsRuntime(cartId, context)
413
+ return getCheckoutShippingGroupsRuntime(cartId, context, provider)
363
414
  }
364
415
 
365
416
  /**
@@ -381,9 +432,10 @@ export function toDisplayPaymentMethods(methods: PaymentMethod[]): PaymentMethod
381
432
 
382
433
  export async function loadPaymentMethods(
383
434
  context: StoreContext = getStoreContext(),
435
+ provider?: HostCommerceProvider,
384
436
  ): Promise<PaymentMethod[]> {
385
437
  assertBackendConfigured()
386
- const methods = await getPaymentMethodsByRegion(context.regionId)
438
+ const methods = await getPaymentMethodsByRegion(context.regionId, provider)
387
439
  return toDisplayPaymentMethods(methods)
388
440
  }
389
441
 
@@ -391,12 +443,13 @@ export async function loadPaymentMethods(
391
443
  // Cart mutations (context-scoped)
392
444
  // ---------------------------------------------------------------------------
393
445
 
394
- /** Create a fresh backend guest cart in the store context region. */
446
+ /** Create a fresh backend cart in the store context region (guest or token-scoped). */
395
447
  export async function createGuestCart(
396
448
  context: StoreContext = getStoreContext(),
449
+ provider?: HostCommerceProvider,
397
450
  ): Promise<CartStatePatch> {
398
451
  assertBackendConfigured()
399
- const cart = await createCartForContext(context)
452
+ const cart = await createCartForContext(context, provider)
400
453
  return toCartState(cart)
401
454
  }
402
455
 
@@ -406,9 +459,15 @@ export async function addVariant(
406
459
  variantId: string,
407
460
  quantity: number,
408
461
  context: StoreContext = getStoreContext(),
462
+ provider?: HostCommerceProvider,
409
463
  ): Promise<CartStatePatch> {
410
464
  assertBackendConfigured()
411
- const cart = await addCartLines(cartId, [{ merchandiseId: variantId, quantity }], context)
465
+ const cart = await addCartLines(
466
+ cartId,
467
+ [{ merchandiseId: variantId, quantity }],
468
+ context,
469
+ provider,
470
+ )
412
471
  return toCartState(cart)
413
472
  }
414
473
 
@@ -419,9 +478,15 @@ export async function setLineQuantity(
419
478
  merchandiseId: string,
420
479
  quantity: number,
421
480
  context: StoreContext = getStoreContext(),
481
+ provider?: HostCommerceProvider,
422
482
  ): Promise<CartStatePatch> {
423
483
  assertBackendConfigured()
424
- const cart = await updateCartLines(cartId, [{ id: lineId, merchandiseId, quantity }], context)
484
+ const cart = await updateCartLines(
485
+ cartId,
486
+ [{ id: lineId, merchandiseId, quantity }],
487
+ context,
488
+ provider,
489
+ )
425
490
  return toCartState(cart)
426
491
  }
427
492
 
@@ -431,12 +496,13 @@ export async function applyLineDelta(
431
496
  lineId: string,
432
497
  delta: number,
433
498
  context: StoreContext = getStoreContext(),
499
+ provider?: HostCommerceProvider,
434
500
  ): Promise<CartStatePatch> {
435
501
  assertBackendConfigured()
436
- const current = await getCartForContext(cartId, context)
502
+ const current = await getCartForContext(cartId, context, provider)
437
503
  if (!current) throw new Error(`Cart not found: ${cartId}`)
438
504
  const update = toAbsoluteLineUpdate(current, lineId, delta)
439
- const cart = await updateCartLines(cartId, [update], context)
505
+ const cart = await updateCartLines(cartId, [update], context, provider)
440
506
  return toCartState(cart)
441
507
  }
442
508
 
@@ -445,9 +511,10 @@ export async function removeLine(
445
511
  cartId: string,
446
512
  lineId: string,
447
513
  context: StoreContext = getStoreContext(),
514
+ provider?: HostCommerceProvider,
448
515
  ): Promise<CartStatePatch> {
449
516
  assertBackendConfigured()
450
- const cart = await removeCartLines(cartId, [lineId], context)
517
+ const cart = await removeCartLines(cartId, [lineId], context, provider)
451
518
  return toCartState(cart)
452
519
  }
453
520
 
@@ -481,43 +548,60 @@ export async function saveShippingAddress(
481
548
  cartId: string,
482
549
  address: AddressInput,
483
550
  context: StoreContext = getStoreContext(),
551
+ provider?: HostCommerceProvider,
484
552
  ): Promise<CartStatePatch> {
485
553
  assertBackendConfigured()
486
- const current = await getCartForContext(cartId, context)
554
+ const current = await getCartForContext(cartId, context, provider)
487
555
  if (!current) throw new Error(`Cart not found before address update: ${cartId}`)
488
556
  try {
489
557
  // The runtime address validator treats province/phone as optional; the
490
558
  // address-setter input still declares them, so pass an empty string when the
491
559
  // shopper did not supply one rather than failing the type contract.
492
- await updateShippingAddress(cartId, {
493
- email: address.email,
494
- firstName: address.firstName,
495
- lastName: address.lastName,
496
- address1: address.address1,
497
- address2: address.address2,
498
- company: address.company,
499
- city: address.city,
500
- province: address.province ?? '',
501
- postalCode: address.postalCode,
502
- countryCode: address.countryCode,
503
- phone: address.phone ?? '',
504
- })
560
+ await updateShippingAddress(
561
+ cartId,
562
+ {
563
+ email: address.email,
564
+ firstName: address.firstName,
565
+ lastName: address.lastName,
566
+ address1: address.address1,
567
+ address2: address.address2,
568
+ company: address.company,
569
+ city: address.city,
570
+ province: address.province ?? '',
571
+ postalCode: address.postalCode,
572
+ countryCode: address.countryCode,
573
+ phone: address.phone ?? '',
574
+ },
575
+ provider,
576
+ )
505
577
  } catch (error) {
506
578
  if (isUnsupportedAddressUpdate(error)) return toCartState(current)
507
579
  throw error
508
580
  }
509
- const cart = await getCartForContext(cartId, context)
581
+ const cart = await getCartForContext(cartId, context, provider)
510
582
  return toCartState(cart ?? current)
511
583
  }
512
584
 
585
+ /** Transfer a guest cart to the authenticated customer. */
586
+ export async function assignCartToCustomer(
587
+ cartId: string,
588
+ context: StoreContext = getStoreContext(),
589
+ provider?: HostCommerceProvider,
590
+ ): Promise<CartStatePatch> {
591
+ assertBackendConfigured()
592
+ const cart = await assignCartToCustomerRuntime(cartId, context, provider)
593
+ return toCartState(cart)
594
+ }
595
+
513
596
  /** Apply an eligible shipping method and return the recalculated cart. */
514
597
  export async function selectShipping(
515
598
  cartId: string,
516
599
  methodId: string,
517
600
  context: StoreContext = getStoreContext(),
601
+ provider?: HostCommerceProvider,
518
602
  ): Promise<CartStatePatch> {
519
603
  assertBackendConfigured()
520
- const cart = await selectShippingMethod(cartId, methodId, context)
604
+ const cart = await selectShippingMethod(cartId, methodId, context, provider)
521
605
  return toCartState(cart)
522
606
  }
523
607
 
@@ -530,28 +614,44 @@ export async function applyCheckoutShippingGroups(
530
614
  cartId: string,
531
615
  selections: ShippingGroupSelection[],
532
616
  context: StoreContext = getStoreContext(),
617
+ provider?: HostCommerceProvider,
533
618
  ): Promise<CartStatePatch> {
534
619
  assertBackendConfigured()
535
- const cart = await applyCheckoutShippingGroupsRuntime(cartId, selections, context)
620
+ const cart = await applyCheckoutShippingGroupsRuntime(cartId, selections, context, provider)
536
621
  return toCartState(cart)
537
622
  }
538
623
 
539
- /** Apply the single approved manual TEST payment provider (requires shipping). */
624
+ /**
625
+ * Start the shopper's selected payment method after shipping is final.
626
+ *
627
+ * Any provider listed by the backend is accepted here; the runtime validates
628
+ * that it exists, is enabled and does not still require setup. Provider-specific
629
+ * client confirmation (redirect, 3DS, wallet) remains a host surface.
630
+ */
540
631
  export async function applyPayment(
541
632
  cartId: string,
633
+ providerId: string,
542
634
  context: StoreContext = getStoreContext(),
543
- ): Promise<void> {
635
+ provider?: HostCommerceProvider,
636
+ ): Promise<PaymentMethod> {
544
637
  assertBackendConfigured()
545
- await applyManualTestPayment(cartId, context)
638
+ return applyPaymentMethodRuntime(cartId, providerId, context, provider)
546
639
  }
547
640
 
548
641
  /** Complete the cart exactly once, preserving the native discriminator. */
549
642
  export async function completeOrder(
550
643
  cartId: string,
551
644
  context: StoreContext = getStoreContext(),
645
+ customerToken?: string | null,
552
646
  ): Promise<PlaceOrderResult> {
553
647
  assertBackendConfigured()
554
- return toPlaceOrderResult(await completeCart(cartId, context))
648
+ // The host owns the auth cookie and threads the request's customer token
649
+ // into the completion so the backend attributes the order to the session
650
+ // customer (mock) or links it server-side (Medusa). A tokenless completion
651
+ // builds exactly the provider the previous token-blind default built.
652
+ return toPlaceOrderResult(
653
+ await completeCart(cartId, context, getCommerceClientWithToken(customerToken ?? null)),
654
+ )
555
655
  }
556
656
 
557
657
  /**
@@ -563,9 +663,12 @@ export async function completeOrder(
563
663
  export async function reconcileOrder(
564
664
  cartId: string,
565
665
  context: StoreContext = getStoreContext(),
666
+ customerToken?: string | null,
566
667
  ): Promise<PlaceOrderResult> {
567
668
  assertBackendConfigured()
568
- return toPlaceOrderResult(await reconcileCart(cartId, context))
669
+ return toPlaceOrderResult(
670
+ await reconcileCart(cartId, context, getCommerceClientWithToken(customerToken ?? null)),
671
+ )
569
672
  }
570
673
 
571
674
  // ---------------------------------------------------------------------------
@@ -602,6 +705,14 @@ export async function loadCustomerAddresses(token: string): Promise<Address[]> {
602
705
  return getCustomerAddresses(token)
603
706
  }
604
707
 
708
+ /** Update the authenticated customer's profile (name, phone, and email when supported). */
709
+ export async function updateCustomerProfile(
710
+ token: string,
711
+ data: UpdateCustomerData,
712
+ ): Promise<Customer> {
713
+ return updateCustomerRuntime(token, data)
714
+ }
715
+
605
716
  /** Validate a saved-address payload without the contact email. */
606
717
  export function validateCustomerAddress(
607
718
  input: unknown,
@@ -773,4 +884,332 @@ export async function loadOrdersPage(
773
884
  }
774
885
  }
775
886
 
887
+ // ---------------------------------------------------------------------------
888
+ // Advanced order-history boundary (account.orders default surface)
889
+ // ---------------------------------------------------------------------------
890
+ //
891
+ // The `OrderHistoryAdvanced` block owns its query lifecycle, so the host hands
892
+ // it a `OrdersPort` runner. The runner reads the same token-scoped customer
893
+ // history the canonical surface reads and maps it into the block's normalised
894
+ // `OrderRecord`: amounts cross as integer minor units (the block formats them),
895
+ // dates cross as `YYYY-MM-DD` (the block formats the long date), and a field the
896
+ // backend omits is omitted or reported as the neutral state, never invented.
897
+
898
+ /** Currency fraction digits, read from Intl (USD 2, JPY 0). */
899
+ function currencyFractionDigits(currency: string): number {
900
+ try {
901
+ return (
902
+ new Intl.NumberFormat('en', { style: 'currency', currency }).resolvedOptions()
903
+ .maximumFractionDigits ?? 2
904
+ )
905
+ } catch {
906
+ return 2
907
+ }
908
+ }
909
+
910
+ /** The backend decimal string as integer minor units, the block's money shape. */
911
+ export function toOrderHistoryMoney(money: Money): OrderHistoryAdvancedRecord['total'] {
912
+ const digits = currencyFractionDigits(money.currencyCode)
913
+ return {
914
+ amount: Math.round(Number(money.amount) * 10 ** digits),
915
+ currency: money.currencyCode,
916
+ }
917
+ }
918
+
919
+ /** The date part of an ISO timestamp; the block formats the long date itself. */
920
+ function toOrderHistoryDate(value: string): string {
921
+ return /^\d{4}-\d{2}-\d{2}T/.test(value) ? value.slice(0, 10) : value
922
+ }
923
+
924
+ function toOrderHistoryCommercial(
925
+ status: Order['status'],
926
+ ): OrderHistoryAdvancedRecord['commercial'] {
927
+ switch (status) {
928
+ case 'pending':
929
+ case 'processing':
930
+ case 'completed':
931
+ case 'cancelled':
932
+ return status
933
+ // A refunded order is finished; the refund field carries the refund itself
934
+ // and the block derives the buyer-facing `refunded` status from it.
935
+ case 'refunded':
936
+ return 'completed'
937
+ }
938
+ }
939
+
940
+ function toOrderHistoryPaymentStatus(
941
+ status: Order['paymentStatus'],
942
+ ): OrderHistoryAdvancedRecord['payment']['status'] {
943
+ switch (status) {
944
+ case 'pending':
945
+ return 'unpaid'
946
+ case 'authorized':
947
+ return 'authorized'
948
+ case 'paid':
949
+ case 'partially_refunded':
950
+ case 'refunded':
951
+ return 'paid'
952
+ }
953
+ }
954
+
955
+ function toOrderHistoryRefund(
956
+ status: Order['paymentStatus'],
957
+ ): OrderHistoryAdvancedRecord['refund'] {
958
+ if (status === 'refunded') return 'full'
959
+ if (status === 'partially_refunded') return 'partial'
960
+ return 'none'
961
+ }
962
+
963
+ function toOrderHistoryFulfilmentStatus(
964
+ status: Order['fulfillmentStatus'],
965
+ ): OrderHistoryAdvancedRecord['fulfilment']['status'] {
966
+ switch (status) {
967
+ case 'unfulfilled':
968
+ return 'unfulfilled'
969
+ case 'partially_fulfilled':
970
+ return 'partially_delivered'
971
+ case 'fulfilled':
972
+ case 'returned':
973
+ return 'delivered'
974
+ }
975
+ }
976
+
977
+ type OrderHistoryFulfilmentStage =
978
+ | 'shipped'
979
+ | 'delayed'
980
+ | 'ready_for_pickup'
981
+ | 'partially_delivered'
982
+
983
+ type OrderHistoryLifecycleHint = {
984
+ fulfilment?: OrderHistoryFulfilmentStage
985
+ returns?: OrderHistoryAdvancedRecord['returns']
986
+ payment?: 'partially_paid'
987
+ creditTerms?: boolean
988
+ partiallyCancelled?: boolean
989
+ }
990
+
991
+ const FULFILMENT_STAGES: readonly string[] = [
992
+ 'shipped',
993
+ 'delayed',
994
+ 'ready_for_pickup',
995
+ 'partially_delivered',
996
+ ]
997
+ const RETURN_STAGES: readonly string[] = ['none', 'requested', 'in_progress', 'completed']
998
+
999
+ /**
1000
+ * Optional lifecycle detail the universal order envelope cannot express yet
1001
+ * (a delayed shipment, an open return, a partial payment). A backend or a demo
1002
+ * fixture may publish it under `metadata.orderHistory`; the mapper validates
1003
+ * every value and falls back to the truthful aggregate status otherwise.
1004
+ */
1005
+ function readOrderHistoryHint(order: Order): OrderHistoryLifecycleHint {
1006
+ const raw = order.metadata?.orderHistory
1007
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}
1008
+ const candidate = raw as Record<string, unknown>
1009
+ const hint: OrderHistoryLifecycleHint = {}
1010
+ if (typeof candidate.fulfilment === 'string' && FULFILMENT_STAGES.includes(candidate.fulfilment)) {
1011
+ hint.fulfilment = candidate.fulfilment as OrderHistoryFulfilmentStage
1012
+ }
1013
+ if (typeof candidate.returns === 'string' && RETURN_STAGES.includes(candidate.returns)) {
1014
+ hint.returns = candidate.returns as OrderHistoryAdvancedRecord['returns']
1015
+ }
1016
+ if (candidate.payment === 'partially_paid') hint.payment = 'partially_paid'
1017
+ if (typeof candidate.creditTerms === 'boolean') hint.creditTerms = candidate.creditTerms
1018
+ if (typeof candidate.partiallyCancelled === 'boolean') {
1019
+ hint.partiallyCancelled = candidate.partiallyCancelled
1020
+ }
1021
+ return hint
1022
+ }
1023
+
1024
+ /**
1025
+ * The action menu is a function of the order's truthful state: a delivered
1026
+ * order can be repeated, returned or invoiced; an open one can be cancelled or
1027
+ * paid. Capabilities still gate what the store offers, and the block intersects
1028
+ * both lists before rendering an action.
1029
+ */
1030
+ function deriveOrderHistoryActions(input: {
1031
+ commercial: OrderHistoryAdvancedRecord['commercial']
1032
+ paymentStatus: OrderHistoryAdvancedRecord['payment']['status']
1033
+ fulfilmentStatus: OrderHistoryAdvancedRecord['fulfilment']['status']
1034
+ returns: OrderHistoryAdvancedRecord['returns']
1035
+ }): OrderHistoryAdvancedRecord['availableActions'] {
1036
+ const actions: OrderHistoryAdvancedRecord['availableActions'] = ['view']
1037
+ switch (input.commercial) {
1038
+ case 'completed':
1039
+ actions.push('reorder', 'invoice')
1040
+ break
1041
+ case 'cancelled':
1042
+ actions.push('invoice')
1043
+ break
1044
+ case 'processing':
1045
+ if (input.paymentStatus === 'paid') actions.push('invoice')
1046
+ if (input.fulfilmentStatus === 'unfulfilled') actions.push('cancel')
1047
+ break
1048
+ case 'pending':
1049
+ actions.push('cancel')
1050
+ break
1051
+ }
1052
+ if (input.paymentStatus === 'unpaid' || input.paymentStatus === 'partially_paid') {
1053
+ actions.push('pay-balance')
1054
+ }
1055
+ if (
1056
+ input.fulfilmentStatus === 'shipped' ||
1057
+ input.fulfilmentStatus === 'partially_delivered' ||
1058
+ input.fulfilmentStatus === 'ready_for_pickup' ||
1059
+ input.fulfilmentStatus === 'delayed'
1060
+ ) {
1061
+ actions.push('track')
1062
+ }
1063
+ if (input.fulfilmentStatus === 'delivered' && input.returns === 'none') {
1064
+ actions.push('return', 'exchange')
1065
+ }
1066
+ if (input.returns === 'requested' || input.returns === 'in_progress') actions.push('problem')
1067
+ actions.push('support')
1068
+ return actions
1069
+ }
1070
+
1071
+ function toOrderHistoryDeliveryMode(
1072
+ order: Order,
1073
+ ): OrderHistoryAdvancedRecord['deliveryMode'] {
1074
+ const modes: Array<'shipping' | 'pickup'> = []
1075
+ for (const group of order.deliveryGroups ?? []) {
1076
+ if (group.mode === 'shipping' || group.mode === 'pickup') modes.push(group.mode)
1077
+ }
1078
+ const declared = order.shippingMethod?.mode
1079
+ if (declared === 'shipping' || declared === 'pickup') modes.push(declared)
1080
+ if (modes.length === 0) return 'shipping'
1081
+ const pickup = modes.includes('pickup')
1082
+ const shipping = modes.includes('shipping')
1083
+ return pickup && shipping ? 'mixed' : pickup ? 'pickup' : 'shipping'
1084
+ }
1085
+
1086
+ export function toOrderHistoryItem(
1087
+ item: Order['items'][number],
1088
+ ): OrderHistoryAdvancedRecord['items'][number] {
1089
+ const view: OrderHistoryAdvancedRecord['items'][number] = {
1090
+ id: item.id,
1091
+ name: item.title,
1092
+ // The block requires a searchable line reference; the backend sku wins,
1093
+ // then the variant identity, then the line id. Never a blank string.
1094
+ sku: item.sku?.trim() || item.variantId || item.id,
1095
+ quantity: item.quantity,
1096
+ }
1097
+ const variant = item.variantTitle?.trim()
1098
+ if (variant) view.variant = variant
1099
+ const image = normalizeImageUrl(item.image?.url)
1100
+ if (image !== undefined) view.image = image
1101
+ return view
1102
+ }
1103
+
1104
+ /** Map one backend order to the advanced block's normalised record. */
1105
+ export function toOrderHistoryRecord(order: Order): OrderHistoryAdvancedRecord {
1106
+ const hint = readOrderHistoryHint(order)
1107
+ const items = order.items.map(toOrderHistoryItem)
1108
+ const commercial = toOrderHistoryCommercial(order.status)
1109
+ const paymentStatus = hint.payment ?? toOrderHistoryPaymentStatus(order.paymentStatus)
1110
+ const fulfilmentStatus =
1111
+ hint.fulfilment ?? toOrderHistoryFulfilmentStatus(order.fulfillmentStatus)
1112
+ const returns =
1113
+ hint.returns ?? (order.fulfillmentStatus === 'returned' ? 'completed' : 'none')
1114
+ const record: OrderHistoryAdvancedRecord = {
1115
+ id: order.id,
1116
+ number: order.orderNumber,
1117
+ placedAt: toOrderHistoryDate(order.createdAt),
1118
+ updatedAt: toOrderHistoryDate(order.updatedAt),
1119
+ total: toOrderHistoryMoney(order.total),
1120
+ items,
1121
+ itemCount: items.reduce((sum, item) => sum + item.quantity, 0),
1122
+ commercial,
1123
+ payment: { status: paymentStatus, creditTerms: hint.creditTerms ?? false },
1124
+ refund: toOrderHistoryRefund(order.paymentStatus),
1125
+ // The order envelope carries no per-shipment records, so the host reports
1126
+ // the aggregate fulfilment status and no fabricated shipment list.
1127
+ fulfilment: {
1128
+ status: fulfilmentStatus,
1129
+ shipments: [],
1130
+ },
1131
+ deliveryMode: toOrderHistoryDeliveryMode(order),
1132
+ returns,
1133
+ availableActions: deriveOrderHistoryActions({
1134
+ commercial,
1135
+ paymentStatus,
1136
+ fulfilmentStatus,
1137
+ returns,
1138
+ }),
1139
+ }
1140
+ if (hint.partiallyCancelled) record.partiallyCancelled = true
1141
+ return record
1142
+ }
1143
+
1144
+ // The query ids the block renders. Validated here because a Server Action is a
1145
+ // public endpoint, not only the block's own call site.
1146
+ const ORDER_HISTORY_QUICK = ['all', 'in-progress', 'completed', 'cancelled', 'attention'] as const
1147
+ const ORDER_HISTORY_SORTS = ['newest', 'oldest', 'total-desc', 'total-asc', 'updated'] as const
1148
+
1149
+ /** Guard a port query into the shape the block's engine accepts. */
1150
+ export function normalizeOrdersQuery(input: Partial<OrdersQuery> = {}): OrdersQuery {
1151
+ const page =
1152
+ Number.isInteger(input.page) && (input.page as number) > 0 ? (input.page as number) : 1
1153
+ const requestedSize = Number.isInteger(input.pageSize) ? (input.pageSize as number) : 10
1154
+ const pageSize = Math.min(50, Math.max(1, requestedSize))
1155
+ const quick = ORDER_HISTORY_QUICK.includes(input.quick as (typeof ORDER_HISTORY_QUICK)[number])
1156
+ ? (input.quick as OrdersQuery['quick'])
1157
+ : 'all'
1158
+ const sort = ORDER_HISTORY_SORTS.includes(input.sort as (typeof ORDER_HISTORY_SORTS)[number])
1159
+ ? (input.sort as OrdersQuery['sort'])
1160
+ : 'newest'
1161
+ const filters =
1162
+ input.filters !== null && typeof input.filters === 'object' && !Array.isArray(input.filters)
1163
+ ? input.filters
1164
+ : {}
1165
+ return {
1166
+ search: typeof input.search === 'string' ? input.search.slice(0, 200) : '',
1167
+ quick,
1168
+ filters,
1169
+ ...(input.date !== undefined && typeof input.date === 'object' ? { date: input.date } : {}),
1170
+ ...(input.amount !== undefined && typeof input.amount === 'object'
1171
+ ? { amount: input.amount }
1172
+ : {}),
1173
+ sort,
1174
+ page,
1175
+ pageSize,
1176
+ }
1177
+ }
1178
+
1179
+ /**
1180
+ * One bounded query window for the advanced order-history port. A missing token
1181
+ * yields the empty page without contacting the backend (an unauthenticated
1182
+ * caller has no history); it never fabricates an order. The runtime's
1183
+ * token-scoped `getCustomerOrders` serves both mock mode and Medusa.
1184
+ */
1185
+ export async function loadOrderHistoryPage(
1186
+ token: string | null,
1187
+ query: OrdersQuery,
1188
+ context: StoreContext = getStoreContext(),
1189
+ ): Promise<OrdersPage> {
1190
+ const normalized = normalizeOrdersQuery(query)
1191
+ if (!token) return queryOrderHistoryPage([], normalized)
1192
+ const orders = await getCustomerOrders(token, { salesChannelId: context.salesChannelId })
1193
+ return queryOrderHistoryPage(orders.map(toOrderHistoryRecord), normalized)
1194
+ }
1195
+
1196
+ /**
1197
+ * Resolve ONE order for the authenticated customer. It is a separate,
1198
+ * ownership-scoped read: the provider resolves the token to a customer and the
1199
+ * order must belong to that customer and the store's channel. In mock mode the
1200
+ * bundled provider serves the same seeded order store as the history; a live
1201
+ * provider that has not shipped the detail endpoint fails closed, and the
1202
+ * detail is never assembled from the list payload.
1203
+ */
1204
+ export async function loadCustomerOrderDetail(
1205
+ token: string | null,
1206
+ id: string,
1207
+ context: StoreContext = getStoreContext(),
1208
+ ): Promise<Order> {
1209
+ return getCustomerOrderDetail(
1210
+ { token, id, salesChannelId: context.salesChannelId },
1211
+ getCommerceClientWithToken,
1212
+ )
1213
+ }
1214
+
776
1215
  export type { Money }