@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
@@ -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,
@@ -57,6 +64,7 @@ import {
57
64
  getProductDetailByHandle,
58
65
  loginCustomer,
59
66
  logoutCustomer,
67
+ updateCustomer as updateCustomerRuntime,
60
68
  reconcileCart,
61
69
  registerCustomer,
62
70
  removeCartLines,
@@ -89,6 +97,9 @@ import type {
89
97
  StorefrontOrderLineView,
90
98
  } from './state.core'
91
99
  import { assertBackendConfigured, getDataSource, getStoreContext, type StoreDataSource } from './store-context'
100
+ import { queryOrderHistoryPage } from '@thorprovider/blocks'
101
+ import type { OrderHistoryAdvancedRecord } from '@thorprovider/blocks'
102
+ import type { OrdersPage, OrdersQuery } from '@thorprovider/blocks/ports'
92
103
 
93
104
  // ---------------------------------------------------------------------------
94
105
  // Projections (serializable; the UI state holds these)
@@ -116,9 +127,24 @@ export const EMPTY_CART_STATE: CartStatePatch = {
116
127
  cartSelectedShippingOptionId: null,
117
128
  }
118
129
 
130
+ /**
131
+ * Request-scoped provider used by the host. A customer token produces a
132
+ * provider whose SDK carries that token; no token produces the guest provider.
133
+ */
134
+ export type HostCommerceProvider = ReturnType<typeof getCommerceClientWithToken>
135
+
136
+ export function getHostCommerceProvider(token: string | null): HostCommerceProvider {
137
+ return getCommerceClientWithToken(token)
138
+ }
139
+
119
140
  /** Result of a completion attempt. `unresolved` must never be blindly retried. */
120
141
  export type PlaceOrderResult =
121
- | { status: 'order'; order: StorefrontOrder; lines: StorefrontOrderLineView[] }
142
+ | {
143
+ status: 'order'
144
+ order: StorefrontOrder
145
+ lines: StorefrontOrderLineView[]
146
+ confirmation: StorefrontConfirmation
147
+ }
122
148
  | { status: 'error'; message: string; code?: string }
123
149
  | { status: 'cart-error'; message: string; code?: string }
124
150
  | { status: 'unresolved'; message: string; code?: string }
@@ -264,7 +290,12 @@ export function toCheckoutFieldErrors(errors: CheckoutFieldError[]): CheckoutFie
264
290
  /** Map the runtime's discriminated completion to the host result union. */
265
291
  export function toPlaceOrderResult(result: CartCompletionResult): PlaceOrderResult {
266
292
  if (result.type === 'order') {
267
- return { status: 'order', order: toStorefrontOrder(result.order), lines: toOrderLines(result.order) }
293
+ return {
294
+ status: 'order',
295
+ order: toStorefrontOrder(result.order),
296
+ lines: toOrderLines(result.order),
297
+ confirmation: toStorefrontConfirmation(result.order),
298
+ }
268
299
  }
269
300
  if (result.type === 'cart') {
270
301
  return { status: 'cart-error', message: result.error.message, code: result.error.code }
@@ -317,18 +348,31 @@ export function resolveProductCartTarget(
317
348
  export async function readCart(
318
349
  cartId: string,
319
350
  context: StoreContext = getStoreContext(),
351
+ provider?: HostCommerceProvider,
320
352
  ): Promise<CartStatePatch | undefined> {
321
353
  assertBackendConfigured()
322
- const cart = await getCartForContext(cartId, context)
354
+ const cart = await getCartForContext(cartId, context, provider)
323
355
  return cart ? toCartState(cart) : undefined
324
356
  }
325
357
 
358
+ /** The backend customer id of a cart, or undefined when the cart is missing. */
359
+ export async function loadCartCustomerId(
360
+ cartId: string,
361
+ context: StoreContext = getStoreContext(),
362
+ provider?: HostCommerceProvider,
363
+ ): Promise<string | null | undefined> {
364
+ assertBackendConfigured()
365
+ const cart = await getCartForContext(cartId, context, provider)
366
+ return cart ? (cart.customerId ?? null) : undefined
367
+ }
368
+
326
369
  export async function loadCheckoutCountries(
327
370
  cartId: string,
328
371
  context: StoreContext = getStoreContext(),
372
+ provider?: HostCommerceProvider,
329
373
  ): Promise<RegionCountry[]> {
330
374
  assertBackendConfigured()
331
- return getCheckoutCountries(cartId, context)
375
+ return getCheckoutCountries(cartId, context, provider)
332
376
  }
333
377
 
334
378
  /** Persist a billing address distinct from shipping, when the provider supports it. */
@@ -336,17 +380,19 @@ export async function saveBillingAddress(
336
380
  cartId: string,
337
381
  address: BillingAddressInput,
338
382
  context: StoreContext = getStoreContext(),
383
+ provider?: HostCommerceProvider,
339
384
  ): Promise<void> {
340
385
  assertBackendConfigured()
341
- return updateBillingAddress(cartId, address)
386
+ return updateBillingAddress(cartId, address, provider)
342
387
  }
343
388
 
344
389
  export async function loadShippingMethods(
345
390
  cartId: string,
346
391
  context: StoreContext = getStoreContext(),
392
+ provider?: HostCommerceProvider,
347
393
  ): Promise<ShippingMethod[]> {
348
394
  assertBackendConfigured()
349
- return getEligibleShippingMethods(cartId, context)
395
+ return getEligibleShippingMethods(cartId, context, provider)
350
396
  }
351
397
 
352
398
  /**
@@ -357,9 +403,10 @@ export async function loadShippingMethods(
357
403
  export async function loadCheckoutShippingGroups(
358
404
  cartId: string,
359
405
  context: StoreContext = getStoreContext(),
406
+ provider?: HostCommerceProvider,
360
407
  ): Promise<ShippingGroupQuote> {
361
408
  assertBackendConfigured()
362
- return getCheckoutShippingGroupsRuntime(cartId, context)
409
+ return getCheckoutShippingGroupsRuntime(cartId, context, provider)
363
410
  }
364
411
 
365
412
  /**
@@ -381,9 +428,10 @@ export function toDisplayPaymentMethods(methods: PaymentMethod[]): PaymentMethod
381
428
 
382
429
  export async function loadPaymentMethods(
383
430
  context: StoreContext = getStoreContext(),
431
+ provider?: HostCommerceProvider,
384
432
  ): Promise<PaymentMethod[]> {
385
433
  assertBackendConfigured()
386
- const methods = await getPaymentMethodsByRegion(context.regionId)
434
+ const methods = await getPaymentMethodsByRegion(context.regionId, provider)
387
435
  return toDisplayPaymentMethods(methods)
388
436
  }
389
437
 
@@ -391,12 +439,13 @@ export async function loadPaymentMethods(
391
439
  // Cart mutations (context-scoped)
392
440
  // ---------------------------------------------------------------------------
393
441
 
394
- /** Create a fresh backend guest cart in the store context region. */
442
+ /** Create a fresh backend cart in the store context region (guest or token-scoped). */
395
443
  export async function createGuestCart(
396
444
  context: StoreContext = getStoreContext(),
445
+ provider?: HostCommerceProvider,
397
446
  ): Promise<CartStatePatch> {
398
447
  assertBackendConfigured()
399
- const cart = await createCartForContext(context)
448
+ const cart = await createCartForContext(context, provider)
400
449
  return toCartState(cart)
401
450
  }
402
451
 
@@ -406,9 +455,15 @@ export async function addVariant(
406
455
  variantId: string,
407
456
  quantity: number,
408
457
  context: StoreContext = getStoreContext(),
458
+ provider?: HostCommerceProvider,
409
459
  ): Promise<CartStatePatch> {
410
460
  assertBackendConfigured()
411
- const cart = await addCartLines(cartId, [{ merchandiseId: variantId, quantity }], context)
461
+ const cart = await addCartLines(
462
+ cartId,
463
+ [{ merchandiseId: variantId, quantity }],
464
+ context,
465
+ provider,
466
+ )
412
467
  return toCartState(cart)
413
468
  }
414
469
 
@@ -419,9 +474,15 @@ export async function setLineQuantity(
419
474
  merchandiseId: string,
420
475
  quantity: number,
421
476
  context: StoreContext = getStoreContext(),
477
+ provider?: HostCommerceProvider,
422
478
  ): Promise<CartStatePatch> {
423
479
  assertBackendConfigured()
424
- const cart = await updateCartLines(cartId, [{ id: lineId, merchandiseId, quantity }], context)
480
+ const cart = await updateCartLines(
481
+ cartId,
482
+ [{ id: lineId, merchandiseId, quantity }],
483
+ context,
484
+ provider,
485
+ )
425
486
  return toCartState(cart)
426
487
  }
427
488
 
@@ -431,12 +492,13 @@ export async function applyLineDelta(
431
492
  lineId: string,
432
493
  delta: number,
433
494
  context: StoreContext = getStoreContext(),
495
+ provider?: HostCommerceProvider,
434
496
  ): Promise<CartStatePatch> {
435
497
  assertBackendConfigured()
436
- const current = await getCartForContext(cartId, context)
498
+ const current = await getCartForContext(cartId, context, provider)
437
499
  if (!current) throw new Error(`Cart not found: ${cartId}`)
438
500
  const update = toAbsoluteLineUpdate(current, lineId, delta)
439
- const cart = await updateCartLines(cartId, [update], context)
501
+ const cart = await updateCartLines(cartId, [update], context, provider)
440
502
  return toCartState(cart)
441
503
  }
442
504
 
@@ -445,9 +507,10 @@ export async function removeLine(
445
507
  cartId: string,
446
508
  lineId: string,
447
509
  context: StoreContext = getStoreContext(),
510
+ provider?: HostCommerceProvider,
448
511
  ): Promise<CartStatePatch> {
449
512
  assertBackendConfigured()
450
- const cart = await removeCartLines(cartId, [lineId], context)
513
+ const cart = await removeCartLines(cartId, [lineId], context, provider)
451
514
  return toCartState(cart)
452
515
  }
453
516
 
@@ -481,43 +544,60 @@ export async function saveShippingAddress(
481
544
  cartId: string,
482
545
  address: AddressInput,
483
546
  context: StoreContext = getStoreContext(),
547
+ provider?: HostCommerceProvider,
484
548
  ): Promise<CartStatePatch> {
485
549
  assertBackendConfigured()
486
- const current = await getCartForContext(cartId, context)
550
+ const current = await getCartForContext(cartId, context, provider)
487
551
  if (!current) throw new Error(`Cart not found before address update: ${cartId}`)
488
552
  try {
489
553
  // The runtime address validator treats province/phone as optional; the
490
554
  // address-setter input still declares them, so pass an empty string when the
491
555
  // 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
- })
556
+ await updateShippingAddress(
557
+ cartId,
558
+ {
559
+ email: address.email,
560
+ firstName: address.firstName,
561
+ lastName: address.lastName,
562
+ address1: address.address1,
563
+ address2: address.address2,
564
+ company: address.company,
565
+ city: address.city,
566
+ province: address.province ?? '',
567
+ postalCode: address.postalCode,
568
+ countryCode: address.countryCode,
569
+ phone: address.phone ?? '',
570
+ },
571
+ provider,
572
+ )
505
573
  } catch (error) {
506
574
  if (isUnsupportedAddressUpdate(error)) return toCartState(current)
507
575
  throw error
508
576
  }
509
- const cart = await getCartForContext(cartId, context)
577
+ const cart = await getCartForContext(cartId, context, provider)
510
578
  return toCartState(cart ?? current)
511
579
  }
512
580
 
581
+ /** Transfer a guest cart to the authenticated customer. */
582
+ export async function assignCartToCustomer(
583
+ cartId: string,
584
+ context: StoreContext = getStoreContext(),
585
+ provider?: HostCommerceProvider,
586
+ ): Promise<CartStatePatch> {
587
+ assertBackendConfigured()
588
+ const cart = await assignCartToCustomerRuntime(cartId, context, provider)
589
+ return toCartState(cart)
590
+ }
591
+
513
592
  /** Apply an eligible shipping method and return the recalculated cart. */
514
593
  export async function selectShipping(
515
594
  cartId: string,
516
595
  methodId: string,
517
596
  context: StoreContext = getStoreContext(),
597
+ provider?: HostCommerceProvider,
518
598
  ): Promise<CartStatePatch> {
519
599
  assertBackendConfigured()
520
- const cart = await selectShippingMethod(cartId, methodId, context)
600
+ const cart = await selectShippingMethod(cartId, methodId, context, provider)
521
601
  return toCartState(cart)
522
602
  }
523
603
 
@@ -530,28 +610,44 @@ export async function applyCheckoutShippingGroups(
530
610
  cartId: string,
531
611
  selections: ShippingGroupSelection[],
532
612
  context: StoreContext = getStoreContext(),
613
+ provider?: HostCommerceProvider,
533
614
  ): Promise<CartStatePatch> {
534
615
  assertBackendConfigured()
535
- const cart = await applyCheckoutShippingGroupsRuntime(cartId, selections, context)
616
+ const cart = await applyCheckoutShippingGroupsRuntime(cartId, selections, context, provider)
536
617
  return toCartState(cart)
537
618
  }
538
619
 
539
- /** Apply the single approved manual TEST payment provider (requires shipping). */
620
+ /**
621
+ * Start the shopper's selected payment method after shipping is final.
622
+ *
623
+ * Any provider listed by the backend is accepted here; the runtime validates
624
+ * that it exists, is enabled and does not still require setup. Provider-specific
625
+ * client confirmation (redirect, 3DS, wallet) remains a host surface.
626
+ */
540
627
  export async function applyPayment(
541
628
  cartId: string,
629
+ providerId: string,
542
630
  context: StoreContext = getStoreContext(),
543
- ): Promise<void> {
631
+ provider?: HostCommerceProvider,
632
+ ): Promise<PaymentMethod> {
544
633
  assertBackendConfigured()
545
- await applyManualTestPayment(cartId, context)
634
+ return applyPaymentMethodRuntime(cartId, providerId, context, provider)
546
635
  }
547
636
 
548
637
  /** Complete the cart exactly once, preserving the native discriminator. */
549
638
  export async function completeOrder(
550
639
  cartId: string,
551
640
  context: StoreContext = getStoreContext(),
641
+ customerToken?: string | null,
552
642
  ): Promise<PlaceOrderResult> {
553
643
  assertBackendConfigured()
554
- return toPlaceOrderResult(await completeCart(cartId, context))
644
+ // The host owns the auth cookie and threads the request's customer token
645
+ // into the completion so the backend attributes the order to the session
646
+ // customer (mock) or links it server-side (Medusa). A tokenless completion
647
+ // builds exactly the provider the previous token-blind default built.
648
+ return toPlaceOrderResult(
649
+ await completeCart(cartId, context, getCommerceClientWithToken(customerToken ?? null)),
650
+ )
555
651
  }
556
652
 
557
653
  /**
@@ -563,9 +659,12 @@ export async function completeOrder(
563
659
  export async function reconcileOrder(
564
660
  cartId: string,
565
661
  context: StoreContext = getStoreContext(),
662
+ customerToken?: string | null,
566
663
  ): Promise<PlaceOrderResult> {
567
664
  assertBackendConfigured()
568
- return toPlaceOrderResult(await reconcileCart(cartId, context))
665
+ return toPlaceOrderResult(
666
+ await reconcileCart(cartId, context, getCommerceClientWithToken(customerToken ?? null)),
667
+ )
569
668
  }
570
669
 
571
670
  // ---------------------------------------------------------------------------
@@ -602,6 +701,14 @@ export async function loadCustomerAddresses(token: string): Promise<Address[]> {
602
701
  return getCustomerAddresses(token)
603
702
  }
604
703
 
704
+ /** Update the authenticated customer's profile (name, phone, and email when supported). */
705
+ export async function updateCustomerProfile(
706
+ token: string,
707
+ data: UpdateCustomerData,
708
+ ): Promise<Customer> {
709
+ return updateCustomerRuntime(token, data)
710
+ }
711
+
605
712
  /** Validate a saved-address payload without the contact email. */
606
713
  export function validateCustomerAddress(
607
714
  input: unknown,
@@ -773,4 +880,205 @@ export async function loadOrdersPage(
773
880
  }
774
881
  }
775
882
 
883
+ // ---------------------------------------------------------------------------
884
+ // Advanced order-history boundary (account.orders default surface)
885
+ // ---------------------------------------------------------------------------
886
+ //
887
+ // The `OrderHistoryAdvanced` block owns its query lifecycle, so the host hands
888
+ // it a `OrdersPort` runner. The runner reads the same token-scoped customer
889
+ // history the canonical surface reads and maps it into the block's normalised
890
+ // `OrderRecord`: amounts cross as integer minor units (the block formats them),
891
+ // dates cross as `YYYY-MM-DD` (the block formats the long date), and a field the
892
+ // backend omits is omitted or reported as the neutral state, never invented.
893
+
894
+ /** Currency fraction digits, read from Intl (USD 2, JPY 0). */
895
+ function currencyFractionDigits(currency: string): number {
896
+ try {
897
+ return (
898
+ new Intl.NumberFormat('en', { style: 'currency', currency }).resolvedOptions()
899
+ .maximumFractionDigits ?? 2
900
+ )
901
+ } catch {
902
+ return 2
903
+ }
904
+ }
905
+
906
+ /** The backend decimal string as integer minor units, the block's money shape. */
907
+ export function toOrderHistoryMoney(money: Money): OrderHistoryAdvancedRecord['total'] {
908
+ const digits = currencyFractionDigits(money.currencyCode)
909
+ return {
910
+ amount: Math.round(Number(money.amount) * 10 ** digits),
911
+ currency: money.currencyCode,
912
+ }
913
+ }
914
+
915
+ /** The date part of an ISO timestamp; the block formats the long date itself. */
916
+ function toOrderHistoryDate(value: string): string {
917
+ return /^\d{4}-\d{2}-\d{2}T/.test(value) ? value.slice(0, 10) : value
918
+ }
919
+
920
+ function toOrderHistoryCommercial(
921
+ status: Order['status'],
922
+ ): OrderHistoryAdvancedRecord['commercial'] {
923
+ switch (status) {
924
+ case 'pending':
925
+ case 'processing':
926
+ case 'completed':
927
+ case 'cancelled':
928
+ return status
929
+ // A refunded order is finished; the refund field carries the refund itself
930
+ // and the block derives the buyer-facing `refunded` status from it.
931
+ case 'refunded':
932
+ return 'completed'
933
+ }
934
+ }
935
+
936
+ function toOrderHistoryPaymentStatus(
937
+ status: Order['paymentStatus'],
938
+ ): OrderHistoryAdvancedRecord['payment']['status'] {
939
+ switch (status) {
940
+ case 'pending':
941
+ return 'unpaid'
942
+ case 'authorized':
943
+ return 'authorized'
944
+ case 'paid':
945
+ case 'partially_refunded':
946
+ case 'refunded':
947
+ return 'paid'
948
+ }
949
+ }
950
+
951
+ function toOrderHistoryRefund(
952
+ status: Order['paymentStatus'],
953
+ ): OrderHistoryAdvancedRecord['refund'] {
954
+ if (status === 'refunded') return 'full'
955
+ if (status === 'partially_refunded') return 'partial'
956
+ return 'none'
957
+ }
958
+
959
+ function toOrderHistoryFulfilmentStatus(
960
+ status: Order['fulfillmentStatus'],
961
+ ): OrderHistoryAdvancedRecord['fulfilment']['status'] {
962
+ switch (status) {
963
+ case 'unfulfilled':
964
+ return 'unfulfilled'
965
+ case 'partially_fulfilled':
966
+ return 'partially_delivered'
967
+ case 'fulfilled':
968
+ case 'returned':
969
+ return 'delivered'
970
+ }
971
+ }
972
+
973
+ function toOrderHistoryDeliveryMode(
974
+ order: Order,
975
+ ): OrderHistoryAdvancedRecord['deliveryMode'] {
976
+ const modes: Array<'shipping' | 'pickup'> = []
977
+ for (const group of order.deliveryGroups ?? []) {
978
+ if (group.mode === 'shipping' || group.mode === 'pickup') modes.push(group.mode)
979
+ }
980
+ const declared = order.shippingMethod?.mode
981
+ if (declared === 'shipping' || declared === 'pickup') modes.push(declared)
982
+ if (modes.length === 0) return 'shipping'
983
+ const pickup = modes.includes('pickup')
984
+ const shipping = modes.includes('shipping')
985
+ return pickup && shipping ? 'mixed' : pickup ? 'pickup' : 'shipping'
986
+ }
987
+
988
+ export function toOrderHistoryItem(
989
+ item: Order['items'][number],
990
+ ): OrderHistoryAdvancedRecord['items'][number] {
991
+ const view: OrderHistoryAdvancedRecord['items'][number] = {
992
+ id: item.id,
993
+ name: item.title,
994
+ // The block requires a searchable line reference; the backend sku wins,
995
+ // then the variant identity, then the line id. Never a blank string.
996
+ sku: item.sku?.trim() || item.variantId || item.id,
997
+ quantity: item.quantity,
998
+ }
999
+ const variant = item.variantTitle?.trim()
1000
+ if (variant) view.variant = variant
1001
+ const image = normalizeImageUrl(item.image?.url)
1002
+ if (image !== undefined) view.image = image
1003
+ return view
1004
+ }
1005
+
1006
+ /** Map one backend order to the advanced block's normalised record. */
1007
+ export function toOrderHistoryRecord(order: Order): OrderHistoryAdvancedRecord {
1008
+ const items = order.items.map(toOrderHistoryItem)
1009
+ return {
1010
+ id: order.id,
1011
+ number: order.orderNumber,
1012
+ placedAt: toOrderHistoryDate(order.createdAt),
1013
+ updatedAt: toOrderHistoryDate(order.updatedAt),
1014
+ total: toOrderHistoryMoney(order.total),
1015
+ items,
1016
+ itemCount: items.reduce((sum, item) => sum + item.quantity, 0),
1017
+ commercial: toOrderHistoryCommercial(order.status),
1018
+ payment: { status: toOrderHistoryPaymentStatus(order.paymentStatus), creditTerms: false },
1019
+ refund: toOrderHistoryRefund(order.paymentStatus),
1020
+ // The order envelope carries no per-shipment records, so the host reports
1021
+ // the aggregate fulfilment status and no fabricated shipment list.
1022
+ fulfilment: {
1023
+ status: toOrderHistoryFulfilmentStatus(order.fulfillmentStatus),
1024
+ shipments: [],
1025
+ },
1026
+ deliveryMode: toOrderHistoryDeliveryMode(order),
1027
+ returns: order.fulfillmentStatus === 'returned' ? 'completed' : 'none',
1028
+ availableActions: ['view'],
1029
+ }
1030
+ }
1031
+
1032
+ // The query ids the block renders. Validated here because a Server Action is a
1033
+ // public endpoint, not only the block's own call site.
1034
+ const ORDER_HISTORY_QUICK = ['all', 'in-progress', 'completed', 'cancelled', 'attention'] as const
1035
+ const ORDER_HISTORY_SORTS = ['newest', 'oldest', 'total-desc', 'total-asc', 'updated'] as const
1036
+
1037
+ /** Guard a port query into the shape the block's engine accepts. */
1038
+ export function normalizeOrdersQuery(input: Partial<OrdersQuery> = {}): OrdersQuery {
1039
+ const page =
1040
+ Number.isInteger(input.page) && (input.page as number) > 0 ? (input.page as number) : 1
1041
+ const requestedSize = Number.isInteger(input.pageSize) ? (input.pageSize as number) : 10
1042
+ const pageSize = Math.min(50, Math.max(1, requestedSize))
1043
+ const quick = ORDER_HISTORY_QUICK.includes(input.quick as (typeof ORDER_HISTORY_QUICK)[number])
1044
+ ? (input.quick as OrdersQuery['quick'])
1045
+ : 'all'
1046
+ const sort = ORDER_HISTORY_SORTS.includes(input.sort as (typeof ORDER_HISTORY_SORTS)[number])
1047
+ ? (input.sort as OrdersQuery['sort'])
1048
+ : 'newest'
1049
+ const filters =
1050
+ input.filters !== null && typeof input.filters === 'object' && !Array.isArray(input.filters)
1051
+ ? input.filters
1052
+ : {}
1053
+ return {
1054
+ search: typeof input.search === 'string' ? input.search.slice(0, 200) : '',
1055
+ quick,
1056
+ filters,
1057
+ ...(input.date !== undefined && typeof input.date === 'object' ? { date: input.date } : {}),
1058
+ ...(input.amount !== undefined && typeof input.amount === 'object'
1059
+ ? { amount: input.amount }
1060
+ : {}),
1061
+ sort,
1062
+ page,
1063
+ pageSize,
1064
+ }
1065
+ }
1066
+
1067
+ /**
1068
+ * One bounded query window for the advanced order-history port. A missing token
1069
+ * yields the empty page without contacting the backend (an unauthenticated
1070
+ * caller has no history); it never fabricates an order. The runtime's
1071
+ * token-scoped `getCustomerOrders` serves both mock mode and Medusa.
1072
+ */
1073
+ export async function loadOrderHistoryPage(
1074
+ token: string | null,
1075
+ query: OrdersQuery,
1076
+ context: StoreContext = getStoreContext(),
1077
+ ): Promise<OrdersPage> {
1078
+ const normalized = normalizeOrdersQuery(query)
1079
+ if (!token) return queryOrderHistoryPage([], normalized)
1080
+ const orders = await getCustomerOrders(token, { salesChannelId: context.salesChannelId })
1081
+ return queryOrderHistoryPage(orders.map(toOrderHistoryRecord), normalized)
1082
+ }
1083
+
776
1084
  export type { Money }