@ecomweb/storefront-kit 0.11.0 → 0.12.1

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.
@@ -2,6 +2,9 @@ const GENERIC_ERROR_COPY = "\u0110\xE3 x\u1EA3y ra l\u1ED7i. Vui l\xF2ng th\u1EE
2
2
  const ERROR_COPY = {
3
3
  AUTH_INVALID_CREDENTIALS: "Email ho\u1EB7c m\u1EADt kh\u1EA9u kh\xF4ng \u0111\xFAng.",
4
4
  AUTH_ACCOUNT_LOCKED: "Qu\xE1 nhi\u1EC1u l\u1EA7n th\u1EED. Vui l\xF2ng th\u1EED l\u1EA1i sau 15 ph\xFAt.",
5
+ // The merchant marked this customer inactive. Sent only after the shopper
6
+ // proved the password, code or Google account.
7
+ AUTH_ACCOUNT_DISABLED: "T\xE0i kho\u1EA3n n\xE0y kh\xF4ng th\u1EC3 \u0111\u0103ng nh\u1EADp. Vui l\xF2ng li\xEAn h\u1EC7 c\u1EEDa h\xE0ng.",
5
8
  AUTH_EMAIL_NOT_VERIFIED: "Vui l\xF2ng x\xE1c th\u1EF1c email c\u1EE7a b\u1EA1n tr\u01B0\u1EDBc.",
6
9
  AUTH_METHOD_DISABLED: "Ph\u01B0\u01A1ng th\u1EE9c \u0111\u0103ng nh\u1EADp n\xE0y kh\xF4ng kh\u1EA3 d\u1EE5ng cho c\u1EEDa h\xE0ng n\xE0y.",
7
10
  AUTH_TOKEN_INVALID: "M\xE3 x\xE1c th\u1EF1c kh\xF4ng h\u1EE3p l\u1EC7 ho\u1EB7c \u0111\xE3 \u0111\u01B0\u1EE3c s\u1EED d\u1EE5ng.",
@@ -18,10 +21,12 @@ const ERROR_COPY = {
18
21
  ORDER_NOT_CANCELLABLE: "\u0110\u01A1n h\xE0ng n\xE0y kh\xF4ng th\u1EC3 hu\u1EF7 \u0111\u01B0\u1EE3c n\u1EEFa.",
19
22
  INSUFFICIENT_INVENTORY: "M\u1ED9t s\u1ED1 s\u1EA3n ph\u1EA9m kh\xF4ng \u0111\u1EE7 h\xE0ng.",
20
23
  ORDER_PROMOTION_NOT_APPLICABLE: "M\xE3 gi\u1EA3m gi\xE1 kh\xF4ng c\xF2n d\xF9ng \u0111\u01B0\u1EE3c cho \u0111\u01A1n n\xE0y n\xEAn \u0111\xE3 \u0111\u01B0\u1EE3c g\u1EE1. Vui l\xF2ng ki\u1EC3m tra l\u1EA1i t\u1ED5ng ti\u1EC1n r\u1ED3i \u0111\u1EB7t h\xE0ng.",
24
+ PROMOTION_USAGE_LIMIT_REACHED: "M\xE3 gi\u1EA3m gi\xE1 \u0111\xE3 h\u1EBFt l\u01B0\u1EE3t s\u1EED d\u1EE5ng n\xEAn \u0111\xE3 \u0111\u01B0\u1EE3c g\u1EE1. Vui l\xF2ng ki\u1EC3m tra l\u1EA1i t\u1ED5ng ti\u1EC1n r\u1ED3i \u0111\u1EB7t h\xE0ng.",
21
25
  SHIPPING_QUOTE_CHANGED: "Ph\xED v\u1EADn chuy\u1EC3n \u0111\xE3 thay \u0111\u1ED5i. Vui l\xF2ng ki\u1EC3m tra l\u1EA1i r\u1ED3i \u0111\u1EB7t h\xE0ng.",
22
26
  ORDER_SHIPPING_RATE_UNAVAILABLE: "Ph\u01B0\u01A1ng th\u1EE9c v\u1EADn chuy\u1EC3n \u0111\xE3 ch\u1ECDn kh\xF4ng c\xF2n kh\u1EA3 d\u1EE5ng. Vui l\xF2ng ch\u1ECDn l\u1EA1i.",
23
27
  ORDER_CANCEL_BLOCKED_BY_SHIPMENT: "\u0110\u01A1n \u0111\xE3 \u0111\u01B0\u1EE3c giao cho h\xE3ng v\u1EADn chuy\u1EC3n, kh\xF4ng th\u1EC3 hu\u1EF7. Vui l\xF2ng li\xEAn h\u1EC7 c\u1EEDa h\xE0ng.",
24
- STORE_COMING_SOON: "C\u1EEDa h\xE0ng ch\u01B0a m\u1EDF c\u1EEDa n\xEAn ch\u01B0a th\u1EC3 th\u1EF1c hi\u1EC7n thao t\xE1c n\xE0y."
28
+ STORE_COMING_SOON: "C\u1EEDa h\xE0ng ch\u01B0a m\u1EDF c\u1EEDa n\xEAn ch\u01B0a th\u1EC3 th\u1EF1c hi\u1EC7n thao t\xE1c n\xE0y.",
29
+ BLOG_COMMENTS_DISABLED: "C\u1EEDa h\xE0ng \u0111\xE3 t\u1EAFt b\xECnh lu\u1EADn cho blog."
25
30
  };
26
31
  const STATUS_COPY = {
27
32
  0: "Kh\xF4ng th\u1EC3 k\u1EBFt n\u1ED1i m\xE1y ch\u1EE7. Vui l\xF2ng ki\u1EC3m tra k\u1EBFt n\u1ED1i m\u1EA1ng.",
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/error-copy.ts"],"sourcesContent":["/**\n * Shopper-facing copy for backend errors.\n *\n * Project rule: backend exception messages are written in English and are\n * never shown to a shopper. The backend serialises every business error as\n * `{ code, message, details, timestamp }` (see `src/common/exceptions/` in the\n * api repo) and `code` is the stable identifier — this module is the single\n * place that turns one into Vietnamese.\n *\n * The fallback is always a generic Vietnamese sentence. Never fall back to the\n * backend's `message`.\n */\n\nexport const GENERIC_ERROR_COPY = \"Đã xảy ra lỗi. Vui lòng thử lại.\";\n\n/**\n * Keyed by the backend's stable `code`. Sources, read directly rather than\n * guessed:\n * - `AUTH_*` — `src/modules/customer-auth/domain/constants/auth.constants.ts`\n * (`AUTH_ERROR`).\n * - `ACCESS_DENIED` — `AuthorizationException.accessDenied()`, thrown by\n * `customer-addresses.controller.ts` on an address the caller does not own.\n * - `<RESOURCE>_NOT_FOUND` — `ResourceNotFoundException`, whose code is\n * `${resource.toUpperCase()}_NOT_FOUND`. `Address` and `Order` are the two\n * resources the storefront's authenticated routes can produce.\n * - `VALIDATION_FAILED` — `ValidationException`.\n * - `ORDER_NOT_CANCELLABLE` — `ORDER_ERROR.NOT_CANCELLABLE`\n * (`src/modules/orders/domain/constants/order-error.constants.ts`),\n * thrown by `OrderCancelCommandHandler` when a customer tries to cancel\n * an order outside pending/confirmed/processing.\n * - `INSUFFICIENT_INVENTORY`: `InsufficientInventoryException`\n * (`src/modules/inventory/domain/exceptions/`), thrown when an order asks\n * for more of a deny-policy variant than is available.\n * - `ORDER_PROMOTION_NOT_APPLICABLE`: `ORDER_ERROR.PROMOTION_NOT_APPLICABLE`,\n * thrown by `OrderComputationService.applyPromotionCode` when the applied\n * code can no longer be redeemed at placement (expired, used up, the cart\n * changed). `useCheckout` drops the code when it sees this.\n * - `SHIPPING_QUOTE_CHANGED` and `ORDER_SHIPPING_RATE_UNAVAILABLE`:\n * `SHIPPING_ERROR_CODES` in `@ecomweb/sdk`, returned by order creation\n * when the carrier's price moved since the quote (409, `details.options`\n * holds the new ones; `useCheckout` handles it as `quote_changed`) or the\n * chosen rate can no longer be quoted.\n * - `ORDER_CANCEL_BLOCKED_BY_SHIPMENT`: `ORDER_SHIPMENT_ERROR_CODES` in\n * `@ecomweb/sdk`, returned when a customer cancels an order whose carrier\n * shipment is already in progress.\n * - `STORE_COMING_SOON`: `src/modules/tenant/domain/services/store-access.ts`,\n * the 403 for a store its merchant has not opened yet (details\n * `{ name }`), applied by `StorefrontApiKeyGuard`. A preview token opens\n * only GET and HEAD, so in a preview every write gets it: customer\n * sign-in and sign-up, reviews, blog comments.\n */\nconst ERROR_COPY: Record<string, string> = {\n AUTH_INVALID_CREDENTIALS: \"Email hoặc mật khẩu không đúng.\",\n AUTH_ACCOUNT_LOCKED: \"Quá nhiều lần thử. Vui lòng thử lại sau 15 phút.\",\n AUTH_EMAIL_NOT_VERIFIED: \"Vui lòng xác thực email của bạn trước.\",\n AUTH_METHOD_DISABLED:\n \"Phương thức đăng nhập này không khả dụng cho cửa hàng này.\",\n AUTH_TOKEN_INVALID: \"Mã xác thực không hợp lệ hoặc đã được sử dụng.\",\n AUTH_TOKEN_EXPIRED: \"Mã xác thực đã hết hạn. Vui lòng yêu cầu mã mới.\",\n AUTH_SESSION_EXPIRED: \"Phiên đăng nhập đã hết hạn. Vui lòng đăng nhập lại.\",\n AUTH_WEAK_PASSWORD: \"Mật khẩu chưa đáp ứng yêu cầu của cửa hàng.\",\n AUTH_RATE_LIMITED: \"Quá nhiều yêu cầu. Vui lòng đợi một chút.\",\n AUTH_STORE_MISMATCH:\n \"Phiên đăng nhập không thuộc cửa hàng này. Vui lòng đăng nhập lại.\",\n AUTH_EMAIL_TAKEN: \"Email này đã được sử dụng.\",\n\n ACCESS_DENIED: \"Bạn không có quyền thực hiện thao tác này.\",\n VALIDATION_FAILED: \"Thông tin chưa hợp lệ. Vui lòng kiểm tra lại.\",\n ADDRESS_NOT_FOUND: \"Không tìm thấy địa chỉ này.\",\n ORDER_NOT_FOUND: \"Không tìm thấy đơn hàng này.\",\n ORDER_NOT_CANCELLABLE: \"Đơn hàng này không thể huỷ được nữa.\",\n INSUFFICIENT_INVENTORY: \"Một số sản phẩm không đủ hàng.\",\n ORDER_PROMOTION_NOT_APPLICABLE:\n \"Mã giảm giá không còn dùng được cho đơn này nên đã được gỡ. Vui lòng kiểm tra lại tổng tiền rồi đặt hàng.\",\n SHIPPING_QUOTE_CHANGED:\n \"Phí vận chuyển đã thay đổi. Vui lòng kiểm tra lại rồi đặt hàng.\",\n ORDER_SHIPPING_RATE_UNAVAILABLE:\n \"Phương thức vận chuyển đã chọn không còn khả dụng. Vui lòng chọn lại.\",\n ORDER_CANCEL_BLOCKED_BY_SHIPMENT:\n \"Đơn đã được giao cho hãng vận chuyển, không thể huỷ. Vui lòng liên hệ cửa hàng.\",\n STORE_COMING_SOON:\n \"Cửa hàng chưa mở cửa nên chưa thể thực hiện thao tác này.\",\n};\n\n/**\n * Nest's built-in `UnauthorizedException` / `ForbiddenException` (thrown by\n * `TenantUserAuthGuard`, `StorefrontApiKeyGuard` and the `@CurrentCustomer`\n * decorator) carry no `code` at all — only a status and English prose. Status\n * is the only stable signal there.\n */\nconst STATUS_COPY: Record<number, string> = {\n 0: \"Không thể kết nối máy chủ. Vui lòng kiểm tra kết nối mạng.\",\n 401: \"Phiên đăng nhập đã hết hạn. Vui lòng đăng nhập lại.\",\n 403: \"Bạn không có quyền thực hiện thao tác này.\",\n 404: \"Không tìm thấy dữ liệu yêu cầu.\",\n 429: \"Quá nhiều yêu cầu. Vui lòng đợi một chút.\",\n 500: \"Máy chủ đang gặp sự cố. Vui lòng thử lại sau.\",\n 502: \"Máy chủ đang gặp sự cố. Vui lòng thử lại sau.\",\n 503: \"Máy chủ đang bận. Vui lòng thử lại sau.\",\n 504: \"Máy chủ phản hồi quá lâu. Vui lòng thử lại.\",\n};\n\n/** Maps a backend error code to Vietnamese copy. */\nexport function errorCopy(\n code: string | null | undefined,\n fallback: string = GENERIC_ERROR_COPY\n): string {\n return (code && ERROR_COPY[code]) || fallback;\n}\n\n/**\n * The same mapping for a caught throwable. `ApiClientError` (thrown by the\n * SDK's `unwrap`) carries `code` and `statusCode`; `lib/auth/context.tsx`\n * surfaces `{ message, code }`. Anything else falls through to `fallback`.\n *\n * The caught value's own `message` is deliberately never used: it is either\n * the backend's English prose or an axios internal string.\n */\nexport function errorCopyFor(\n error: unknown,\n fallback: string = GENERIC_ERROR_COPY\n): string {\n if (!error || typeof error !== \"object\") return fallback;\n\n const { code, statusCode } = error as {\n code?: unknown;\n statusCode?: unknown;\n };\n\n if (typeof code === \"string\" && ERROR_COPY[code]) return ERROR_COPY[code];\n if (typeof statusCode === \"number\" && STATUS_COPY[statusCode]) {\n return STATUS_COPY[statusCode];\n }\n\n return fallback;\n}\n"],"mappings":"AAaO,MAAM,qBAAqB;AAsClC,MAAM,aAAqC;AAAA,EACzC,0BAA0B;AAAA,EAC1B,qBAAqB;AAAA,EACrB,yBAAyB;AAAA,EACzB,sBACE;AAAA,EACF,oBAAoB;AAAA,EACpB,oBAAoB;AAAA,EACpB,sBAAsB;AAAA,EACtB,oBAAoB;AAAA,EACpB,mBAAmB;AAAA,EACnB,qBACE;AAAA,EACF,kBAAkB;AAAA,EAElB,eAAe;AAAA,EACf,mBAAmB;AAAA,EACnB,mBAAmB;AAAA,EACnB,iBAAiB;AAAA,EACjB,uBAAuB;AAAA,EACvB,wBAAwB;AAAA,EACxB,gCACE;AAAA,EACF,wBACE;AAAA,EACF,iCACE;AAAA,EACF,kCACE;AAAA,EACF,mBACE;AACJ;AAQA,MAAM,cAAsC;AAAA,EAC1C,GAAG;AAAA,EACH,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACP;AAGO,SAAS,UACd,MACA,WAAmB,oBACX;AACR,SAAQ,QAAQ,WAAW,IAAI,KAAM;AACvC;AAUO,SAAS,aACd,OACA,WAAmB,oBACX;AACR,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAEhD,QAAM,EAAE,MAAM,WAAW,IAAI;AAK7B,MAAI,OAAO,SAAS,YAAY,WAAW,IAAI,EAAG,QAAO,WAAW,IAAI;AACxE,MAAI,OAAO,eAAe,YAAY,YAAY,UAAU,GAAG;AAC7D,WAAO,YAAY,UAAU;AAAA,EAC/B;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/error-copy.ts"],"sourcesContent":["/**\n * Shopper-facing copy for backend errors.\n *\n * Project rule: backend exception messages are written in English and are\n * never shown to a shopper. The backend serialises every business error as\n * `{ code, message, details, timestamp }` (see `src/common/exceptions/` in the\n * api repo) and `code` is the stable identifier — this module is the single\n * place that turns one into Vietnamese.\n *\n * The fallback is always a generic Vietnamese sentence. Never fall back to the\n * backend's `message`.\n */\n\nexport const GENERIC_ERROR_COPY = \"Đã xảy ra lỗi. Vui lòng thử lại.\";\n\n/**\n * Keyed by the backend's stable `code`. Sources, read directly rather than\n * guessed:\n * - `AUTH_*` — `src/modules/customer-auth/domain/constants/auth.constants.ts`\n * (`AUTH_ERROR`).\n * - `ACCESS_DENIED` — `AuthorizationException.accessDenied()`, thrown by\n * `customer-addresses.controller.ts` on an address the caller does not own.\n * - `<RESOURCE>_NOT_FOUND` — `ResourceNotFoundException`, whose code is\n * `${resource.toUpperCase()}_NOT_FOUND`. `Address` and `Order` are the two\n * resources the storefront's authenticated routes can produce.\n * - `VALIDATION_FAILED` — `ValidationException`.\n * - `ORDER_NOT_CANCELLABLE` — `ORDER_ERROR.NOT_CANCELLABLE`\n * (`src/modules/orders/domain/constants/order-error.constants.ts`),\n * thrown by `OrderCancelCommandHandler` when a customer tries to cancel\n * an order outside pending/confirmed/processing.\n * - `INSUFFICIENT_INVENTORY`: `InsufficientInventoryException`\n * (`src/modules/inventory/domain/exceptions/`), thrown when an order asks\n * for more of a deny-policy variant than is available.\n * - `ORDER_PROMOTION_NOT_APPLICABLE`: `ORDER_ERROR.PROMOTION_NOT_APPLICABLE`,\n * thrown by `OrderComputationService.applyPromotionCode` when the applied\n * code can no longer be redeemed at placement (expired, used up, the cart\n * changed). `useCheckout` drops the code when it sees this.\n * - `PROMOTION_USAGE_LIMIT_REACHED`: `promotion-usage.ts` in the API's\n * promotions module, when placing the order would pass the code's total\n * or per-customer usage limit. `useCheckout` drops the code too.\n * - `SHIPPING_QUOTE_CHANGED` and `ORDER_SHIPPING_RATE_UNAVAILABLE`:\n * `SHIPPING_ERROR_CODES` in `@ecomweb/sdk`, returned by order creation\n * when the carrier's price moved since the quote (409, `details.options`\n * holds the new ones; `useCheckout` handles it as `quote_changed`) or the\n * chosen rate can no longer be quoted.\n * - `ORDER_CANCEL_BLOCKED_BY_SHIPMENT`: `ORDER_SHIPMENT_ERROR_CODES` in\n * `@ecomweb/sdk`, returned when a customer cancels an order whose carrier\n * shipment is already in progress.\n * - `STORE_COMING_SOON`: `src/modules/tenant/domain/services/store-access.ts`,\n * the 403 for a store its merchant has not opened yet (details\n * `{ name }`), applied by `StorefrontApiKeyGuard`. A preview token opens\n * only GET and HEAD, so in a preview every write gets it: customer\n * sign-in and sign-up, reviews, blog comments.\n * - `BLOG_COMMENTS_DISABLED`: the 403 for a blog comment on a store whose\n * blog settings have comments turned off (`allow_comments`). The\n * storefront hides the form then, so this reaches a shopper only when the\n * setting changed while the post was open.\n */\nconst ERROR_COPY: Record<string, string> = {\n AUTH_INVALID_CREDENTIALS: \"Email hoặc mật khẩu không đúng.\",\n AUTH_ACCOUNT_LOCKED: \"Quá nhiều lần thử. Vui lòng thử lại sau 15 phút.\",\n // The merchant marked this customer inactive. Sent only after the shopper\n // proved the password, code or Google account.\n AUTH_ACCOUNT_DISABLED:\n \"Tài khoản này không thể đăng nhập. Vui lòng liên hệ cửa hàng.\",\n AUTH_EMAIL_NOT_VERIFIED: \"Vui lòng xác thực email của bạn trước.\",\n AUTH_METHOD_DISABLED:\n \"Phương thức đăng nhập này không khả dụng cho cửa hàng này.\",\n AUTH_TOKEN_INVALID: \"Mã xác thực không hợp lệ hoặc đã được sử dụng.\",\n AUTH_TOKEN_EXPIRED: \"Mã xác thực đã hết hạn. Vui lòng yêu cầu mã mới.\",\n AUTH_SESSION_EXPIRED: \"Phiên đăng nhập đã hết hạn. Vui lòng đăng nhập lại.\",\n AUTH_WEAK_PASSWORD: \"Mật khẩu chưa đáp ứng yêu cầu của cửa hàng.\",\n AUTH_RATE_LIMITED: \"Quá nhiều yêu cầu. Vui lòng đợi một chút.\",\n AUTH_STORE_MISMATCH:\n \"Phiên đăng nhập không thuộc cửa hàng này. Vui lòng đăng nhập lại.\",\n AUTH_EMAIL_TAKEN: \"Email này đã được sử dụng.\",\n\n ACCESS_DENIED: \"Bạn không có quyền thực hiện thao tác này.\",\n VALIDATION_FAILED: \"Thông tin chưa hợp lệ. Vui lòng kiểm tra lại.\",\n ADDRESS_NOT_FOUND: \"Không tìm thấy địa chỉ này.\",\n ORDER_NOT_FOUND: \"Không tìm thấy đơn hàng này.\",\n ORDER_NOT_CANCELLABLE: \"Đơn hàng này không thể huỷ được nữa.\",\n INSUFFICIENT_INVENTORY: \"Một số sản phẩm không đủ hàng.\",\n ORDER_PROMOTION_NOT_APPLICABLE:\n \"Mã giảm giá không còn dùng được cho đơn này nên đã được gỡ. Vui lòng kiểm tra lại tổng tiền rồi đặt hàng.\",\n PROMOTION_USAGE_LIMIT_REACHED:\n \"Mã giảm giá đã hết lượt sử dụng nên đã được gỡ. Vui lòng kiểm tra lại tổng tiền rồi đặt hàng.\",\n SHIPPING_QUOTE_CHANGED:\n \"Phí vận chuyển đã thay đổi. Vui lòng kiểm tra lại rồi đặt hàng.\",\n ORDER_SHIPPING_RATE_UNAVAILABLE:\n \"Phương thức vận chuyển đã chọn không còn khả dụng. Vui lòng chọn lại.\",\n ORDER_CANCEL_BLOCKED_BY_SHIPMENT:\n \"Đơn đã được giao cho hãng vận chuyển, không thể huỷ. Vui lòng liên hệ cửa hàng.\",\n STORE_COMING_SOON:\n \"Cửa hàng chưa mở cửa nên chưa thể thực hiện thao tác này.\",\n BLOG_COMMENTS_DISABLED: \"Cửa hàng đã tắt bình luận cho blog.\",\n};\n\n/**\n * Nest's built-in `UnauthorizedException` / `ForbiddenException` (thrown by\n * `TenantUserAuthGuard`, `StorefrontApiKeyGuard` and the `@CurrentCustomer`\n * decorator) carry no `code` at all — only a status and English prose. Status\n * is the only stable signal there.\n */\nconst STATUS_COPY: Record<number, string> = {\n 0: \"Không thể kết nối máy chủ. Vui lòng kiểm tra kết nối mạng.\",\n 401: \"Phiên đăng nhập đã hết hạn. Vui lòng đăng nhập lại.\",\n 403: \"Bạn không có quyền thực hiện thao tác này.\",\n 404: \"Không tìm thấy dữ liệu yêu cầu.\",\n 429: \"Quá nhiều yêu cầu. Vui lòng đợi một chút.\",\n 500: \"Máy chủ đang gặp sự cố. Vui lòng thử lại sau.\",\n 502: \"Máy chủ đang gặp sự cố. Vui lòng thử lại sau.\",\n 503: \"Máy chủ đang bận. Vui lòng thử lại sau.\",\n 504: \"Máy chủ phản hồi quá lâu. Vui lòng thử lại.\",\n};\n\n/** Maps a backend error code to Vietnamese copy. */\nexport function errorCopy(\n code: string | null | undefined,\n fallback: string = GENERIC_ERROR_COPY\n): string {\n return (code && ERROR_COPY[code]) || fallback;\n}\n\n/**\n * The same mapping for a caught throwable. `ApiClientError` (thrown by the\n * SDK's `unwrap`) carries `code` and `statusCode`; `lib/auth/context.tsx`\n * surfaces `{ message, code }`. Anything else falls through to `fallback`.\n *\n * The caught value's own `message` is deliberately never used: it is either\n * the backend's English prose or an axios internal string.\n */\nexport function errorCopyFor(\n error: unknown,\n fallback: string = GENERIC_ERROR_COPY\n): string {\n if (!error || typeof error !== \"object\") return fallback;\n\n const { code, statusCode } = error as {\n code?: unknown;\n statusCode?: unknown;\n };\n\n if (typeof code === \"string\" && ERROR_COPY[code]) return ERROR_COPY[code];\n if (typeof statusCode === \"number\" && STATUS_COPY[statusCode]) {\n return STATUS_COPY[statusCode];\n }\n\n return fallback;\n}\n"],"mappings":"AAaO,MAAM,qBAAqB;AA6ClC,MAAM,aAAqC;AAAA,EACzC,0BAA0B;AAAA,EAC1B,qBAAqB;AAAA;AAAA;AAAA,EAGrB,uBACE;AAAA,EACF,yBAAyB;AAAA,EACzB,sBACE;AAAA,EACF,oBAAoB;AAAA,EACpB,oBAAoB;AAAA,EACpB,sBAAsB;AAAA,EACtB,oBAAoB;AAAA,EACpB,mBAAmB;AAAA,EACnB,qBACE;AAAA,EACF,kBAAkB;AAAA,EAElB,eAAe;AAAA,EACf,mBAAmB;AAAA,EACnB,mBAAmB;AAAA,EACnB,iBAAiB;AAAA,EACjB,uBAAuB;AAAA,EACvB,wBAAwB;AAAA,EACxB,gCACE;AAAA,EACF,+BACE;AAAA,EACF,wBACE;AAAA,EACF,iCACE;AAAA,EACF,kCACE;AAAA,EACF,mBACE;AAAA,EACF,wBAAwB;AAC1B;AAQA,MAAM,cAAsC;AAAA,EAC1C,GAAG;AAAA,EACH,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACP;AAGO,SAAS,UACd,MACA,WAAmB,oBACX;AACR,SAAQ,QAAQ,WAAW,IAAI,KAAM;AACvC;AAUO,SAAS,aACd,OACA,WAAmB,oBACX;AACR,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAEhD,QAAM,EAAE,MAAM,WAAW,IAAI;AAK7B,MAAI,OAAO,SAAS,YAAY,WAAW,IAAI,EAAG,QAAO,WAAW,IAAI;AACxE,MAAI,OAAO,eAAe,YAAY,YAAY,UAAU,GAAG;AAC7D,WAAO,YAAY,UAAU;AAAA,EAC/B;AAEA,SAAO;AACT;","names":[]}
@@ -5,7 +5,8 @@ import {
5
5
  useContext,
6
6
  useReducer,
7
7
  useEffect,
8
- useCallback
8
+ useCallback,
9
+ useRef
9
10
  } from "react";
10
11
  import { useNotify } from "../notices.js";
11
12
  import { isBrowserStorePreview } from "../api/store-preview-header.js";
@@ -20,7 +21,10 @@ const cartReducer = (state, action) => {
20
21
  };
21
22
  case "LOAD_CART": {
22
23
  const cart = action.payload;
23
- const items = cart.items.map((item) => ({
24
+ const inAddedOrder = [...cart.items].sort(
25
+ (a, b) => Date.parse(a.created_at) - Date.parse(b.created_at)
26
+ );
27
+ const items = inAddedOrder.map((item) => ({
24
28
  id: item.id,
25
29
  productId: item.product_id,
26
30
  variantId: item.variant_id ?? void 0,
@@ -101,6 +105,7 @@ function CartProvider({
101
105
  if (cart) {
102
106
  dispatch({ type: "LOAD_CART", payload: cart });
103
107
  } else {
108
+ dispatch({ type: "CLEAR_CART" });
104
109
  dispatch({ type: "SET_LOADING", payload: false });
105
110
  }
106
111
  } catch (error) {
@@ -108,9 +113,45 @@ function CartProvider({
108
113
  dispatch({ type: "SET_LOADING", payload: false });
109
114
  }
110
115
  }, [storeRef, isAuth]);
116
+ const movingGuestCart = useRef(null);
117
+ const moveGuestCartToAccount = useCallback(() => {
118
+ if (!movingGuestCart.current) {
119
+ movingGuestCart.current = (async () => {
120
+ try {
121
+ const guestCart = await cartApiService.getCart(storeRef, false);
122
+ for (const item of guestCart?.items ?? []) {
123
+ try {
124
+ await cartApiService.addToCart(
125
+ storeRef,
126
+ {
127
+ product_id: item.product_id,
128
+ variant_id: item.variant_id ?? void 0,
129
+ quantity: item.quantity
130
+ },
131
+ true
132
+ );
133
+ await cartApiService.removeFromCart(storeRef, item.id, false);
134
+ } catch (error) {
135
+ console.error("Could not move a guest cart line:", error);
136
+ }
137
+ }
138
+ } catch (error) {
139
+ console.error("Could not read the guest cart:", error);
140
+ } finally {
141
+ movingGuestCart.current = null;
142
+ }
143
+ })();
144
+ }
145
+ return movingGuestCart.current;
146
+ }, [storeRef]);
111
147
  useEffect(() => {
112
- loadCart();
113
- }, [loadCart]);
148
+ if (!storeRef || !isAuth || isBrowserStorePreview()) {
149
+ loadCart();
150
+ return;
151
+ }
152
+ dispatch({ type: "SET_LOADING", payload: true });
153
+ moveGuestCartToAccount().then(loadCart);
154
+ }, [storeRef, isAuth, loadCart, moveGuestCartToAccount]);
114
155
  const addItem = async (item) => {
115
156
  if (isBrowserStorePreview()) {
116
157
  notify(STORE_PREVIEW_READ_ONLY_NOTICE);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cart/server-context.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n createContext,\n useContext,\n useReducer,\n useEffect,\n useCallback,\n type ReactNode,\n} from \"react\";\nimport { useNotify } from \"../notices\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { STORE_PREVIEW_READ_ONLY_NOTICE } from \"../stores/store-preview-guard\";\nimport { CartItem } from \"./types\";\nimport { cartApiService, CartApiResponse, CartApiItem } from \"./api\";\n\ninterface CartState {\n items: CartItem[];\n total: number;\n subtotal: number;\n originalSubtotal: number;\n discountAmount: number;\n shippingFee: number;\n itemCount: number;\n isLoading: boolean;\n cartId?: string;\n sessionId?: string;\n}\n\ntype CartAction =\n | { type: \"SET_LOADING\"; payload: boolean }\n | { type: \"LOAD_CART\"; payload: CartApiResponse }\n | { type: \"SET_SESSION_ID\"; payload: string }\n | { type: \"CLEAR_CART\" };\n\nconst cartReducer = (state: CartState, action: CartAction): CartState => {\n switch (action.type) {\n case \"SET_LOADING\":\n return {\n ...state,\n isLoading: action.payload,\n };\n\n case \"LOAD_CART\": {\n const cart = action.payload;\n const items: CartItem[] = cart.items.map((item: CartApiItem) => ({\n id: item.id,\n productId: item.product_id,\n variantId: item.variant_id ?? undefined,\n name: item.product_name,\n price: item.price,\n originalPrice: item.original_price,\n image: item.product_image,\n quantity: item.quantity,\n variantName: item.variant_name,\n variantOptions: item.variant_options,\n promotions: item.promotions,\n bestPromotion: item.best_promotion,\n }));\n\n return {\n ...state,\n items,\n total: cart.total,\n subtotal: cart.subtotal,\n originalSubtotal: cart.original_subtotal,\n discountAmount: cart.discount_amount,\n shippingFee: cart.shipping_fee,\n itemCount: cart.item_count,\n cartId: cart.id,\n isLoading: false,\n };\n }\n\n case \"SET_SESSION_ID\":\n return {\n ...state,\n sessionId: action.payload,\n };\n\n case \"CLEAR_CART\":\n return {\n ...state,\n items: [],\n total: 0,\n subtotal: 0,\n originalSubtotal: 0,\n discountAmount: 0,\n shippingFee: 0,\n itemCount: 0,\n cartId: undefined,\n };\n\n default:\n return state;\n }\n};\n\ninterface CartContextType extends CartState {\n addItem: (\n item: Omit<CartItem, \"quantity\"> & { quantity?: number }\n ) => Promise<void>;\n removeItem: (id: string) => Promise<void>;\n updateQuantity: (id: string, quantity: number) => Promise<void>;\n /** Pass false to skip the \"cart cleared\" notice (e.g. after checkout). */\n clearCart: (notifyCleared?: boolean) => Promise<void>;\n refreshCart: () => Promise<void>;\n mergeCarts: (userId: string) => Promise<void>;\n reorderItems: (\n items: { product_id: number; variant_id?: number; quantity: number }[]\n ) => Promise<{ added: number; total: number }>;\n}\n\nconst CartContext = createContext<CartContextType | undefined>(undefined);\n\ninterface CartProviderProps {\n children: ReactNode;\n storeRef: string;\n userId?: string;\n}\n\nexport function CartProvider({\n children,\n storeRef,\n userId,\n}: CartProviderProps) {\n // A signed-in shopper gets the identity-scoped cart; everyone else gets the\n // session-id cart. `userId` comes from the auth context one level up\n // (StoreCartProvider) — this module can never read the httpOnly cookie itself.\n const isAuth = !!userId;\n const notify = useNotify();\n const [state, dispatch] = useReducer(cartReducer, {\n items: [],\n total: 0,\n subtotal: 0,\n originalSubtotal: 0,\n discountAmount: 0,\n shippingFee: 0,\n itemCount: 0,\n isLoading: true, // Start with loading true to show loading state on initial render\n });\n\n // Generate session ID for anonymous users\n useEffect(() => {\n if (!userId && !state.sessionId) {\n const sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n dispatch({ type: \"SET_SESSION_ID\", payload: sessionId });\n }\n }, [userId, state.sessionId]);\n\n // Load cart from server\n const loadCart = useCallback(async () => {\n if (!storeRef) return;\n\n dispatch({ type: \"SET_LOADING\", payload: true });\n try {\n const cart = await cartApiService.getCart(storeRef, isAuth);\n\n if (cart) {\n dispatch({ type: \"LOAD_CART\", payload: cart });\n } else {\n dispatch({ type: \"SET_LOADING\", payload: false });\n }\n } catch (error) {\n console.error(\"Failed to load cart:\", error);\n dispatch({ type: \"SET_LOADING\", payload: false });\n }\n }, [storeRef, isAuth]);\n\n // Load cart on mount and when dependencies change\n useEffect(() => {\n loadCart();\n }, [loadCart]);\n\n const addItem = async (\n item: Omit<CartItem, \"quantity\"> & { quantity?: number }\n ) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.productId,\n variant_id: item.variantId,\n quantity: item.quantity || 1,\n },\n isAuth\n );\n\n // Refresh cart after adding item\n await loadCart();\n\n notify({\n kind: \"success\",\n code: \"cart.item_added\",\n title: \"Đã thêm vào giỏ hàng\",\n description: `${item.name} đã được thêm vào giỏ hàng của bạn`,\n data: { productName: item.name },\n });\n } catch (error) {\n console.error(\"Failed to add item to cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.add_failed\",\n title: \"Lỗi\",\n description: \"Không thể thêm sản phẩm vào giỏ hàng\",\n });\n }\n };\n\n /**\n * Add every line of a past order back to the cart.\n *\n * Deliberately not a loop over addItem: that notifies per item and swallows\n * its errors, so a reorder would fire one notice per line and the caller\n * could never report a shortfall. This refreshes once and returns counts.\n */\n const reorderItems = async (\n items: { product_id: number; variant_id?: number; quantity: number }[]\n ): Promise<{ added: number; total: number }> => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return { added: 0, total: items.length };\n }\n if (!storeRef) return { added: 0, total: items.length };\n\n let added = 0;\n for (const item of items) {\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.product_id,\n variant_id: item.variant_id,\n quantity: item.quantity,\n },\n isAuth\n );\n added += 1;\n } catch (error) {\n // Product deleted, out of stock, or repriced since purchase. Skip it —\n // the caller reports the shortfall rather than failing the reorder.\n console.error(\"Reorder skipped an item:\", error);\n }\n }\n\n await loadCart();\n return { added, total: items.length };\n };\n\n const removeItem = async (id: string) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n const item = state.items.find(item => item.id === id);\n\n try {\n await cartApiService.removeFromCart(storeRef, id, isAuth);\n\n // Refresh cart after removing item\n await loadCart();\n\n if (item) {\n notify({\n kind: \"success\",\n code: \"cart.item_removed\",\n title: \"Đã xóa khỏi giỏ hàng\",\n description: `${item.name} đã được xóa khỏi giỏ hàng`,\n data: { productName: item.name },\n });\n }\n } catch (error) {\n console.error(\"Failed to remove item from cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.remove_failed\",\n title: \"Lỗi\",\n description: \"Không thể xóa sản phẩm khỏi giỏ hàng\",\n });\n }\n };\n\n const updateQuantity = async (id: string, quantity: number) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.updateCartItem(storeRef, id, { quantity }, isAuth);\n\n // Refresh cart after updating quantity\n await loadCart();\n } catch (error) {\n console.error(\"Failed to update item quantity:\", error);\n notify({\n kind: \"error\",\n code: \"cart.update_failed\",\n title: \"Lỗi\",\n description: \"Không thể cập nhật số lượng sản phẩm\",\n });\n }\n };\n\n const clearCart = async (notifyCleared: boolean = true) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.clearCart(storeRef, isAuth);\n\n dispatch({ type: \"CLEAR_CART\" });\n\n if (notifyCleared) {\n notify({\n kind: \"success\",\n code: \"cart.cleared\",\n title: \"Đã xóa giỏ hàng\",\n description: \"Tất cả sản phẩm đã được xóa khỏi giỏ hàng\",\n });\n }\n } catch (error) {\n console.error(\"Failed to clear cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.clear_failed\",\n title: \"Lỗi\",\n description: \"Không thể xóa giỏ hàng\",\n });\n }\n };\n\n const refreshCart = async () => {\n await loadCart();\n };\n\n const mergeCarts = async (_userId: string) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef || !state.sessionId) return;\n\n try {\n await cartApiService.mergeCarts(storeRef);\n\n // Refresh cart after merging\n await loadCart();\n\n notify({\n kind: \"success\",\n code: \"cart.merged\",\n title: \"Đã đồng bộ giỏ hàng\",\n description: \"Giỏ hàng đã được đồng bộ với tài khoản của bạn\",\n });\n } catch (error) {\n console.error(\"Failed to merge carts:\", error);\n notify({\n kind: \"error\",\n code: \"cart.merge_failed\",\n title: \"Lỗi\",\n description: \"Không thể đồng bộ giỏ hàng\",\n });\n }\n };\n\n return (\n <CartContext.Provider\n value={{\n ...state,\n addItem,\n removeItem,\n updateQuantity,\n clearCart,\n refreshCart,\n mergeCarts,\n reorderItems,\n }}\n >\n {children}\n </CartContext.Provider>\n );\n}\n\nexport function useCart() {\n const context = useContext(CartContext);\n if (context === undefined) {\n throw new Error(\"useCart must be used within a CartProvider\");\n }\n return context;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/B,UAAI,eAAe;AACjB,eAAO;AAAA,UACL,MAAM;AAAA,UACN,MAAM;AAAA,UACN,OAAO;AAAA,UACP,aAAa;AAAA,QACf,CAAC;AAAA,MACH;AAAA,IACF,SAAS,OAAO;AACd,cAAQ,MAAM,yBAAyB,KAAK;AAC5C,aAAO;AAAA,QACL,MAAM;AAAA,QACN,MAAM;AAAA,QACN,OAAO;AAAA,QACP,aAAa;AAAA,MACf,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,cAAc,YAAY;AAC9B,UAAM,SAAS;AAAA,EACjB;AAEA,QAAM,aAAa,OAAO,YAAoB;AAC5C,QAAI,sBAAsB,GAAG;AAC3B,aAAO,8BAA8B;AACrC;AAAA,IACF;AACA,QAAI,CAAC,YAAY,CAAC,MAAM,UAAW;AAEnC,QAAI;AACF,YAAM,eAAe,WAAW,QAAQ;AAGxC,YAAM,SAAS;AAEf,aAAO;AAAA,QACL,MAAM;AAAA,QACN,MAAM;AAAA,QACN,OAAO;AAAA,QACP,aAAa;AAAA,MACf,CAAC;AAAA,IACH,SAAS,OAAO;AACd,cAAQ,MAAM,0BAA0B,KAAK;AAC7C,aAAO;AAAA,QACL,MAAM;AAAA,QACN,MAAM;AAAA,QACN,OAAO;AAAA,QACP,aAAa;AAAA,MACf,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SACE;AAAA,IAAC,YAAY;AAAA,IAAZ;AAAA,MACC,OAAO;AAAA,QACL,GAAG;AAAA,QACH;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;AAEO,SAAS,UAAU;AACxB,QAAM,UAAU,WAAW,WAAW;AACtC,MAAI,YAAY,QAAW;AACzB,UAAM,IAAI,MAAM,4CAA4C;AAAA,EAC9D;AACA,SAAO;AACT;","names":["item"]}
1
+ {"version":3,"sources":["../../src/cart/server-context.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n createContext,\n useContext,\n useReducer,\n useEffect,\n useCallback,\n useRef,\n type ReactNode,\n} from \"react\";\nimport { useNotify } from \"../notices\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { STORE_PREVIEW_READ_ONLY_NOTICE } from \"../stores/store-preview-guard\";\nimport { CartItem } from \"./types\";\nimport { cartApiService, CartApiResponse, CartApiItem } from \"./api\";\n\ninterface CartState {\n items: CartItem[];\n total: number;\n subtotal: number;\n originalSubtotal: number;\n discountAmount: number;\n shippingFee: number;\n itemCount: number;\n isLoading: boolean;\n cartId?: string;\n sessionId?: string;\n}\n\ntype CartAction =\n | { type: \"SET_LOADING\"; payload: boolean }\n | { type: \"LOAD_CART\"; payload: CartApiResponse }\n | { type: \"SET_SESSION_ID\"; payload: string }\n | { type: \"CLEAR_CART\" };\n\nconst cartReducer = (state: CartState, action: CartAction): CartState => {\n switch (action.type) {\n case \"SET_LOADING\":\n return {\n ...state,\n isLoading: action.payload,\n };\n\n case \"LOAD_CART\": {\n const cart = action.payload;\n // The API returns lines in no fixed order, and an updated line moves.\n // Without this, the row under the shopper's finger swaps mid-tap.\n const inAddedOrder = [...cart.items].sort(\n (a, b) => Date.parse(a.created_at) - Date.parse(b.created_at)\n );\n const items: CartItem[] = inAddedOrder.map((item: CartApiItem) => ({\n id: item.id,\n productId: item.product_id,\n variantId: item.variant_id ?? undefined,\n name: item.product_name,\n price: item.price,\n originalPrice: item.original_price,\n image: item.product_image,\n quantity: item.quantity,\n variantName: item.variant_name,\n variantOptions: item.variant_options,\n promotions: item.promotions,\n bestPromotion: item.best_promotion,\n }));\n\n return {\n ...state,\n items,\n total: cart.total,\n subtotal: cart.subtotal,\n originalSubtotal: cart.original_subtotal,\n discountAmount: cart.discount_amount,\n shippingFee: cart.shipping_fee,\n itemCount: cart.item_count,\n cartId: cart.id,\n isLoading: false,\n };\n }\n\n case \"SET_SESSION_ID\":\n return {\n ...state,\n sessionId: action.payload,\n };\n\n case \"CLEAR_CART\":\n return {\n ...state,\n items: [],\n total: 0,\n subtotal: 0,\n originalSubtotal: 0,\n discountAmount: 0,\n shippingFee: 0,\n itemCount: 0,\n cartId: undefined,\n };\n\n default:\n return state;\n }\n};\n\ninterface CartContextType extends CartState {\n addItem: (\n item: Omit<CartItem, \"quantity\"> & { quantity?: number }\n ) => Promise<void>;\n removeItem: (id: string) => Promise<void>;\n updateQuantity: (id: string, quantity: number) => Promise<void>;\n /** Pass false to skip the \"cart cleared\" notice (e.g. after checkout). */\n clearCart: (notifyCleared?: boolean) => Promise<void>;\n refreshCart: () => Promise<void>;\n mergeCarts: (userId: string) => Promise<void>;\n reorderItems: (\n items: { product_id: number; variant_id?: number; quantity: number }[]\n ) => Promise<{ added: number; total: number }>;\n}\n\nconst CartContext = createContext<CartContextType | undefined>(undefined);\n\ninterface CartProviderProps {\n children: ReactNode;\n storeRef: string;\n userId?: string;\n}\n\nexport function CartProvider({\n children,\n storeRef,\n userId,\n}: CartProviderProps) {\n // A signed-in shopper gets the identity-scoped cart; everyone else gets the\n // session-id cart. `userId` comes from the auth context one level up\n // (StoreCartProvider) — this module can never read the httpOnly cookie itself.\n const isAuth = !!userId;\n const notify = useNotify();\n const [state, dispatch] = useReducer(cartReducer, {\n items: [],\n total: 0,\n subtotal: 0,\n originalSubtotal: 0,\n discountAmount: 0,\n shippingFee: 0,\n itemCount: 0,\n isLoading: true, // Start with loading true to show loading state on initial render\n });\n\n // Generate session ID for anonymous users\n useEffect(() => {\n if (!userId && !state.sessionId) {\n const sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n dispatch({ type: \"SET_SESSION_ID\", payload: sessionId });\n }\n }, [userId, state.sessionId]);\n\n // Load cart from server\n const loadCart = useCallback(async () => {\n if (!storeRef) return;\n\n dispatch({ type: \"SET_LOADING\", payload: true });\n try {\n const cart = await cartApiService.getCart(storeRef, isAuth);\n\n if (cart) {\n dispatch({ type: \"LOAD_CART\", payload: cart });\n } else {\n // No cart for this identity. Keeping the state would show the\n // previous identity's items (guest before sign-in, account after\n // sign-out) as if they could be bought.\n dispatch({ type: \"CLEAR_CART\" });\n dispatch({ type: \"SET_LOADING\", payload: false });\n }\n } catch (error) {\n console.error(\"Failed to load cart:\", error);\n dispatch({ type: \"SET_LOADING\", payload: false });\n }\n }, [storeRef, isAuth]);\n\n // Shared while running: the provider's effect can fire twice for one sign-in.\n const movingGuestCart = useRef<Promise<void> | null>(null);\n\n /**\n * Signing in switches to the account's cart, so without this whatever the\n * shopper added as a guest disappears, even on checkout's own \"sign in and\n * come back\" link. Each line is added before it is removed, and a line that\n * cannot be added stays in the guest cart, so nothing is lost on a failure.\n */\n const moveGuestCartToAccount = useCallback(() => {\n if (!movingGuestCart.current) {\n movingGuestCart.current = (async () => {\n try {\n const guestCart = await cartApiService.getCart(storeRef, false);\n for (const item of guestCart?.items ?? []) {\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.product_id,\n variant_id: item.variant_id ?? undefined,\n quantity: item.quantity,\n },\n true\n );\n await cartApiService.removeFromCart(storeRef, item.id, false);\n } catch (error) {\n console.error(\"Could not move a guest cart line:\", error);\n }\n }\n } catch (error) {\n console.error(\"Could not read the guest cart:\", error);\n } finally {\n movingGuestCart.current = null;\n }\n })();\n }\n return movingGuestCart.current;\n }, [storeRef]);\n\n // Load cart on mount and when dependencies change\n useEffect(() => {\n if (!storeRef || !isAuth || isBrowserStorePreview()) {\n loadCart();\n return;\n }\n dispatch({ type: \"SET_LOADING\", payload: true });\n moveGuestCartToAccount().then(loadCart);\n }, [storeRef, isAuth, loadCart, moveGuestCartToAccount]);\n\n const addItem = async (\n item: Omit<CartItem, \"quantity\"> & { quantity?: number }\n ) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.productId,\n variant_id: item.variantId,\n quantity: item.quantity || 1,\n },\n isAuth\n );\n\n // Refresh cart after adding item\n await loadCart();\n\n notify({\n kind: \"success\",\n code: \"cart.item_added\",\n title: \"Đã thêm vào giỏ hàng\",\n description: `${item.name} đã được thêm vào giỏ hàng của bạn`,\n data: { productName: item.name },\n });\n } catch (error) {\n console.error(\"Failed to add item to cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.add_failed\",\n title: \"Lỗi\",\n description: \"Không thể thêm sản phẩm vào giỏ hàng\",\n });\n }\n };\n\n /**\n * Add every line of a past order back to the cart.\n *\n * Deliberately not a loop over addItem: that notifies per item and swallows\n * its errors, so a reorder would fire one notice per line and the caller\n * could never report a shortfall. This refreshes once and returns counts.\n */\n const reorderItems = async (\n items: { product_id: number; variant_id?: number; quantity: number }[]\n ): Promise<{ added: number; total: number }> => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return { added: 0, total: items.length };\n }\n if (!storeRef) return { added: 0, total: items.length };\n\n let added = 0;\n for (const item of items) {\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.product_id,\n variant_id: item.variant_id,\n quantity: item.quantity,\n },\n isAuth\n );\n added += 1;\n } catch (error) {\n // Product deleted, out of stock, or repriced since purchase. Skip it —\n // the caller reports the shortfall rather than failing the reorder.\n console.error(\"Reorder skipped an item:\", error);\n }\n }\n\n await loadCart();\n return { added, total: items.length };\n };\n\n const removeItem = async (id: string) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n const item = state.items.find(item => item.id === id);\n\n try {\n await cartApiService.removeFromCart(storeRef, id, isAuth);\n\n // Refresh cart after removing item\n await loadCart();\n\n if (item) {\n notify({\n kind: \"success\",\n code: \"cart.item_removed\",\n title: \"Đã xóa khỏi giỏ hàng\",\n description: `${item.name} đã được xóa khỏi giỏ hàng`,\n data: { productName: item.name },\n });\n }\n } catch (error) {\n console.error(\"Failed to remove item from cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.remove_failed\",\n title: \"Lỗi\",\n description: \"Không thể xóa sản phẩm khỏi giỏ hàng\",\n });\n }\n };\n\n const updateQuantity = async (id: string, quantity: number) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.updateCartItem(storeRef, id, { quantity }, isAuth);\n\n // Refresh cart after updating quantity\n await loadCart();\n } catch (error) {\n console.error(\"Failed to update item quantity:\", error);\n notify({\n kind: \"error\",\n code: \"cart.update_failed\",\n title: \"Lỗi\",\n description: \"Không thể cập nhật số lượng sản phẩm\",\n });\n }\n };\n\n const clearCart = async (notifyCleared: boolean = true) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.clearCart(storeRef, isAuth);\n\n dispatch({ type: \"CLEAR_CART\" });\n\n if (notifyCleared) {\n notify({\n kind: \"success\",\n code: \"cart.cleared\",\n title: \"Đã xóa giỏ hàng\",\n description: \"Tất cả sản phẩm đã được xóa khỏi giỏ hàng\",\n });\n }\n } catch (error) {\n console.error(\"Failed to clear cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.clear_failed\",\n title: \"Lỗi\",\n description: \"Không thể xóa giỏ hàng\",\n });\n }\n };\n\n const refreshCart = async () => {\n await loadCart();\n };\n\n const mergeCarts = async (_userId: string) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef || !state.sessionId) return;\n\n try {\n await cartApiService.mergeCarts(storeRef);\n\n // Refresh cart after merging\n await loadCart();\n\n notify({\n kind: \"success\",\n code: \"cart.merged\",\n title: \"Đã đồng bộ giỏ hàng\",\n description: \"Giỏ hàng đã được đồng bộ với tài khoản của bạn\",\n });\n } catch (error) {\n console.error(\"Failed to merge carts:\", error);\n notify({\n kind: \"error\",\n code: \"cart.merge_failed\",\n title: \"Lỗi\",\n description: \"Không thể đồng bộ giỏ hàng\",\n });\n }\n };\n\n return (\n <CartContext.Provider\n value={{\n ...state,\n addItem,\n removeItem,\n updateQuantity,\n clearCart,\n refreshCart,\n mergeCarts,\n reorderItems,\n }}\n >\n {children}\n </CartContext.Provider>\n );\n}\n\nexport function useCart() {\n const context = useContext(CartContext);\n if (context === undefined) {\n throw new Error(\"useCart must be used within a CartProvider\");\n }\n return context;\n}\n"],"mappings":";AAkbI;AAhbJ;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,iBAAiB;AAC1B,SAAS,6BAA6B;AACtC,SAAS,sCAAsC;AAE/C,SAAS,sBAAoD;AAqB7D,MAAM,cAAc,CAAC,OAAkB,WAAkC;AACvE,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK;AACH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,WAAW,OAAO;AAAA,MACpB;AAAA,IAEF,KAAK,aAAa;AAChB,YAAM,OAAO,OAAO;AAGpB,YAAM,eAAe,CAAC,GAAG,KAAK,KAAK,EAAE;AAAA,QACnC,CAAC,GAAG,MAAM,KAAK,MAAM,EAAE,UAAU,IAAI,KAAK,MAAM,EAAE,UAAU;AAAA,MAC9D;AACA,YAAM,QAAoB,aAAa,IAAI,CAAC,UAAuB;AAAA,QACjE,IAAI,KAAK;AAAA,QACT,WAAW,KAAK;AAAA,QAChB,WAAW,KAAK,cAAc;AAAA,QAC9B,MAAM,KAAK;AAAA,QACX,OAAO,KAAK;AAAA,QACZ,eAAe,KAAK;AAAA,QACpB,OAAO,KAAK;AAAA,QACZ,UAAU,KAAK;AAAA,QACf,aAAa,KAAK;AAAA,QAClB,gBAAgB,KAAK;AAAA,QACrB,YAAY,KAAK;AAAA,QACjB,eAAe,KAAK;AAAA,MACtB,EAAE;AAEF,aAAO;AAAA,QACL,GAAG;AAAA,QACH;AAAA,QACA,OAAO,KAAK;AAAA,QACZ,UAAU,KAAK;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AM,4CAA4C;AAAA,EAC9D;AACA,SAAO;AACT;","names":["item"]}
@@ -216,7 +216,7 @@ function useCheckout({
216
216
  return { kind: "quote_changed" };
217
217
  }
218
218
  const code = error && typeof error === "object" && "code" in error ? error.code : void 0;
219
- if (code === "ORDER_PROMOTION_NOT_APPLICABLE") {
219
+ if (code === "ORDER_PROMOTION_NOT_APPLICABLE" || code === "PROMOTION_USAGE_LIMIT_REACHED") {
220
220
  promotionState.removePromoCode();
221
221
  }
222
222
  if (code === SHIPPING_ERROR_CODES.RATE_UNAVAILABLE || code === SHIPPING_ERROR_CODES.QUOTE_CHANGED) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/checkout/use-checkout.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport {\n SHIPPING_ERROR_CODES,\n type PaymentMethod,\n type StorePaymentMethod,\n} from \"@ecomweb/sdk\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { useAuth } from \"../auth/context\";\nimport { useCart } from \"../cart/server-context\";\nimport { useNotify } from \"../notices\";\nimport { publicOrdersApi } from \"../orders/api-client\";\nimport { usePromotionValidation } from \"../promotions/use-promotion-validation\";\nimport { sdk } from \"../sdk\";\nimport { useShippingCalculation } from \"../shipping/use-shipping-calculation\";\nimport { useStoreData } from \"../store/store-context\";\nimport { STORE_PREVIEW_READ_ONLY_MESSAGE } from \"../stores/store-preview-guard\";\nimport { initiateGatewayPayment } from \"./initiate-gateway-payment\";\nimport { writeOrderHandoff, type OrderHandoffSummary } from \"./order-handoff\";\nimport {\n getPaymentRedirectIntent,\n type PaymentMethodWithProviderCode,\n} from \"./payment-redirect\";\nimport { startGatewayRedirect } from \"./start-gateway-redirect\";\nimport { quoteChangedOptionsFrom } from \"./quote-changed\";\nimport { insufficientItemsFrom, stockIssuesByLine } from \"./stock-issues\";\nimport { getPaymentMethod } from \"./utils\";\n\n/** What the shopper entered; the app owns the form and its validation. */\nexport interface PlaceOrderInput {\n fullName: string;\n phone: string;\n email?: string;\n street: string;\n /** Province code, as quoted for shipping. */\n province: string;\n /** Ward code, as quoted for shipping. */\n ward: string;\n notes?: string;\n /** A `payment_method` code from `paymentMethods`. */\n paymentMethod: string;\n /**\n * What the thank-you page shows of the order; stored with the handoff in\n * this browser only, never sent to the API.\n */\n summary?: OrderHandoffSummary;\n}\n\nexport interface PlacedOrder {\n order_code: string;\n total: number | string | null;\n}\n\n/**\n * - redirect: the shopper is being sent to the payment provider.\n * - redirect_failed: the order exists but the provider hand-off did not\n * start; offer retryPaymentRedirect(). Further placeOrder calls return\n * this again instead of creating a second order.\n * - success: an offline-payment order; show its confirmation.\n * - stock_issues: nothing was placed; `issues` is copy keyed by cart line id.\n * - error: nothing was placed. `code` is the API's error code when it sent\n * one; pass it to `errorCopy`. On ORDER_PROMOTION_NOT_APPLICABLE the applied\n * code has already been removed, so the shopper sees the real total before\n * placing again.\n * - quote_changed: nothing was placed; the shipping options were replaced with\n * the API's new prices and the selection kept where possible; show\n * `SHIPPING_MESSAGES.quoteChanged` and let the shopper place again.\n * - busy: an earlier placeOrder is still running; this call did nothing.\n */\nexport type PlaceOrderResult =\n | { kind: \"redirect\" }\n | { kind: \"redirect_failed\"; orderCode: string }\n | { kind: \"success\"; order: PlacedOrder }\n | { kind: \"stock_issues\"; issues: Record<string, string> }\n | { kind: \"error\"; message: string; code?: string }\n | { kind: \"quote_changed\" }\n | { kind: \"busy\" };\n\nexport interface UseCheckoutOptions {\n /** The address fields shipping is quoted against (codes, may be empty). */\n province: string;\n ward: string;\n /**\n * Ask the API for carrier-quoted shipping options too. Off by default;\n * passed to `useShippingCalculation`.\n */\n includeCarrierOptions?: boolean;\n /** Leaves for the payment provider; defaults to a full-page navigation. */\n navigateToGateway?: (url: string) => void;\n}\n\nconst defaultNavigateToGateway = (url: string) => {\n window.location.href = url;\n};\n\n/**\n * Checkout without the UI: payment methods, shipping quotes, promotions,\n * totals, placing the order and the payment-provider hand-off. The app\n * renders the form and decides what to show for each PlaceOrderResult.\n */\nexport function useCheckout({\n province,\n ward,\n includeCarrierOptions = false,\n navigateToGateway = defaultNavigateToGateway,\n}: UseCheckoutOptions) {\n const store = useStoreData();\n const notify = useNotify();\n const {\n items,\n total,\n subtotal,\n originalSubtotal,\n discountAmount,\n clearCart,\n cartId,\n isLoading: isCartLoading,\n } = useCart();\n const { user, isAnonymous } = useAuth();\n\n const [paymentMethods, setPaymentMethods] = useState<StorePaymentMethod[]>(\n []\n );\n const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(true);\n const [savedAddressId, setSavedAddressId] = useState<number | undefined>(\n undefined\n );\n const [isSubmitting, setIsSubmitting] = useState(false);\n // Set only when the order was placed but the gateway redirect failed to\n // start. The order already exists, so the cart is deliberately left\n // intact until a redirect actually commits — this is what lets the shopper\n // retry payment without resubmitting the order.\n const [redirectError, setRedirectError] = useState<{\n order_code: string;\n provider_code: string;\n } | null>(null);\n const [isRetryingRedirect, setIsRetryingRedirect] = useState(false);\n // Set synchronously, unlike isSubmitting: a double-click lands before the\n // re-render that would disable the button.\n const inFlight = useRef(false);\n // Copy keyed by cart line id when the API rejects the order for short\n // stock. Cleared on the next submit.\n const [stockIssues, setStockIssues] = useState<Record<string, string>>({});\n\n const totalWeight = items.reduce(\n (sum, item) =>\n sum + ((item as { weight_gr?: number }).weight_gr || 500) * item.quantity,\n 0\n );\n\n const shippingQuote = useShippingCalculation({\n storeRef: store.ref,\n city: province,\n ward,\n subtotal,\n totalWeight,\n itemsCount: items.length,\n includeCarrierOptions,\n });\n\n const promotionState = usePromotionValidation({\n storeRef: store.ref,\n items: items.map(item => ({\n productId: item.productId,\n variantId: item.variantId ?? null,\n quantity: item.quantity,\n price: item.price,\n })),\n subtotal,\n shippingFee: shippingQuote.shippingFee,\n });\n\n useEffect(() => {\n const load = async () => {\n try {\n setIsLoadingPaymentMethods(true);\n setPaymentMethods(await sdk.paymentMethods.getEnabled(store.ref));\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to load payment methods:\", error);\n notify({\n kind: \"error\",\n code: \"checkout.payment_methods_failed\",\n title: \"Không thể tải phương thức thanh toán\",\n description: \"Vui lòng thử lại sau\",\n });\n } finally {\n setIsLoadingPaymentMethods(false);\n }\n };\n load();\n }, [store.ref, notify]);\n\n const redirectTo = useCallback(\n (target: { order_code: string; provider_code: string }) =>\n startGatewayRedirect({\n initiate: () => initiateGatewayPayment(store.ref, target),\n clearCart: () => clearCart(false),\n navigate: navigateToGateway,\n }),\n [store.ref, clearCart, navigateToGateway]\n );\n\n const placeOrder = async (\n input: PlaceOrderInput\n ): Promise<PlaceOrderResult> => {\n // The order from a failed hand-off still exists and the cart is kept for\n // it; placing again would create a second order for the same cart.\n if (redirectError) {\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n }\n if (inFlight.current) {\n return { kind: \"busy\" };\n }\n // A preview is read-only: the API would refuse the order anyway.\n if (isBrowserStorePreview()) {\n return {\n kind: \"error\",\n message: STORE_PREVIEW_READ_ONLY_MESSAGE,\n code: \"STORE_COMING_SOON\",\n };\n }\n inFlight.current = true;\n setIsSubmitting(true);\n setStockIssues({});\n // The quote this attempt is made against. A reply that lands after the\n // shopper changed the address must not overwrite the newer options.\n const quoteRequestId = shippingQuote.currentRequestId();\n\n try {\n const shippingOption = shippingQuote.selectedOption;\n const orderData = {\n cart_id: cartId || undefined,\n customer_name: input.fullName,\n customer_phone: input.phone,\n customer_email: input.email || \"\",\n // Money fields are deliberately not sent: the API recomputes subtotal,\n // shipping, discounts and total from the catalog and its own rules,\n // and ignores anything supplied here.\n shipping_street: input.street,\n shipping_city: input.province,\n shipping_ward: input.ward,\n payment_method: getPaymentMethod(input.paymentMethod) as PaymentMethod,\n // The shopper's choice of rate is real input; the API prices it and\n // rejects a rate_id that isn't one it just quoted for this address\n // and cart. useShippingCalculation clears the selection the moment an\n // input it was quoted against changes, so this is either nothing\n // (omitted, the API picks) or an option from the matching quote.\n // A carrier option also names its service and the amount the shopper\n // saw; after a quote_changed that is the replaced amount, so the\n // retry confirms the new price.\n ...(shippingOption && {\n shipping_rate_id: shippingOption.rate_id,\n ...(shippingOption.carrier_service_id && {\n shipping_service_id: shippingOption.carrier_service_id,\n shipping_quoted_amount: shippingOption.amount,\n }),\n }),\n notes: input.notes || undefined,\n promotion_id: promotionState.appliedPromotion?.id || undefined,\n ...(savedAddressId && { customer_address_id: savedAddressId }),\n items: items.map(item => ({\n product_id: item.productId,\n variant_id: item.variantId,\n variant_name: item.variantName,\n product_name: item.name,\n product_image: item.image,\n quantity: item.quantity,\n // No price/total: the API resolves the unit price from the catalog.\n })),\n };\n\n // A signed-in (non-anonymous) shopper's order goes to the authenticated\n // route so the backend links it to their customer record; guests and\n // anonymous identities keep the public route.\n const order = await publicOrdersApi.createStoreOrder(\n store.ref,\n orderData,\n !!user && !isAnonymous\n );\n\n // The order now exists no matter what happens below. A gateway-backed\n // method (non-null provider_code) must send the shopper to the provider\n // to pay; offline methods land on the success screen.\n const method = paymentMethods.find(\n m => m.payment_method === input.paymentMethod\n ) as PaymentMethodWithProviderCode | undefined;\n const intent = getPaymentRedirectIntent(method, order.order_code);\n\n if (intent) {\n try {\n await redirectTo(intent);\n return { kind: \"redirect\" };\n } catch (initiateError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to initiate gateway payment:\", initiateError);\n setRedirectError(intent);\n return { kind: \"redirect_failed\", orderCode: intent.order_code };\n }\n }\n\n // The handoff carries what the success screen cannot ask the API for:\n // the amount to transfer (see order-handoff.ts).\n writeOrderHandoff({\n order_code: order.order_code,\n payment_method: input.paymentMethod,\n provider_code: method?.provider_code ?? null,\n total: Number(order.total ?? 0),\n currency_code:\n (order as { currency_code?: string }).currency_code ?? \"VND\",\n summary: input.summary ?? null,\n });\n clearCart(false);\n return {\n kind: \"success\",\n order: { order_code: order.order_code, total: order.total ?? null },\n };\n } catch (error) {\n const shortItems = insufficientItemsFrom(error);\n if (shortItems) {\n const issues = stockIssuesByLine(items, shortItems);\n setStockIssues(issues);\n return { kind: \"stock_issues\", issues };\n }\n // The carrier's price moved since the shopper saw it. Show the new\n // options (selection kept where possible) and let them place again.\n const changed = quoteChangedOptionsFrom(error);\n if (changed) {\n shippingQuote.replaceOptions(\n changed,\n shippingQuote.selectedOptionId,\n quoteRequestId\n );\n return { kind: \"quote_changed\" };\n }\n const code =\n error && typeof error === \"object\" && \"code\" in error\n ? (error as { code?: unknown }).code\n : undefined;\n // The API refused the order rather than drop the discount the shopper\n // was shown. Keeping the code would fail every retry the same way.\n if (code === \"ORDER_PROMOTION_NOT_APPLICABLE\") {\n promotionState.removePromoCode();\n }\n // The carrier could not price the chosen option, or reported a changed\n // quote we cannot use: refresh the options so the shopper can pick\n // again instead of being stuck on a stale list.\n if (\n code === SHIPPING_ERROR_CODES.RATE_UNAVAILABLE ||\n code === SHIPPING_ERROR_CODES.QUOTE_CHANGED\n ) {\n shippingQuote.retryCalculation();\n }\n return {\n kind: \"error\",\n message: error instanceof Error ? error.message : String(error),\n ...(typeof code === \"string\" && { code }),\n };\n } finally {\n inFlight.current = false;\n setIsSubmitting(false);\n }\n };\n\n // The order already exists — this only re-attempts starting the gateway\n // charge, never re-submits the order.\n const retryPaymentRedirect =\n useCallback(async (): Promise<PlaceOrderResult> => {\n if (!redirectError) return { kind: \"error\", message: \"No order to pay\" };\n setIsRetryingRedirect(true);\n try {\n await redirectTo(redirectError);\n return { kind: \"redirect\" };\n } catch (retryError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to retry gateway payment redirect:\", retryError);\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n } finally {\n setIsRetryingRedirect(false);\n }\n }, [redirectError, redirectTo]);\n\n return {\n items,\n isCartLoading,\n paymentMethods,\n isLoadingPaymentMethods,\n shipping: {\n fee: shippingQuote.shippingFee,\n options: shippingQuote.shippingOptions,\n selectedRate: shippingQuote.selectedShippingRate,\n isCalculating: shippingQuote.isCalculatingShipping,\n hasCalculated: shippingQuote.hasCalculatedShipping,\n calculationFailed: shippingQuote.calculationFailed,\n /** @deprecated Use selectOption. */\n selectRate: shippingQuote.handleShippingRateSelect,\n selectedOptionId: shippingQuote.selectedOptionId,\n selectedOption: shippingQuote.selectedOption,\n selectOption: shippingQuote.handleShippingOptionSelect,\n retry: shippingQuote.retryCalculation,\n },\n promotion: {\n code: promotionState.promoCode,\n setCode: promotionState.setPromoCode,\n applied: promotionState.appliedPromotion,\n shippingDiscount: promotionState.shippingDiscount,\n isValidating: promotionState.isValidatingPromo,\n error: promotionState.promoError,\n validate: promotionState.validatePromoCode,\n remove: promotionState.removePromoCode,\n applySuggestion: promotionState.applyPromotionFromSuggestion,\n },\n // shippingDiscount comes from the API's promotion validation — the same\n // number the server applies when the order is placed.\n totals: {\n subtotal,\n originalSubtotal,\n discount: discountAmount,\n cartTotal: total,\n shipping: shippingQuote.shippingFee,\n shippingDiscount: promotionState.shippingDiscount,\n total:\n total + shippingQuote.shippingFee - promotionState.shippingDiscount,\n },\n savedAddressId,\n selectSavedAddress: setSavedAddressId,\n stockIssues,\n isSubmitting,\n redirectError,\n isRetryingRedirect,\n placeOrder,\n retryPaymentRedirect,\n };\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AACzD;AAAA,EACE;AAAA,OAGK;AACP,SAAS,6BAA6B;AACtC,SAAS,eAAe;AACxB,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AACvC,SAAS,WAAW;AACpB,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAC7B,SAAS,uCAAuC;AAChD,SAAS,8BAA8B;AACvC,SAAS,yBAAmD;AAC5D;AAAA,EACE;AAAA,OAEK;AACP,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC,SAAS,uBAAuB,yBAAyB;AACzD,SAAS,wBAAwB;AAiEjC,MAAM,2BAA2B,CAAC,QAAgB;AAChD,SAAO,SAAS,OAAO;AACzB;AAOO,SAAS,YAAY;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nB,cAAQ,MAAM,6CAA6C,UAAU;AACrE,aAAO,EAAE,MAAM,mBAAmB,WAAW,cAAc,WAAW;AAAA,IACxE,UAAE;AACA,4BAAsB,KAAK;AAAA,IAC7B;AAAA,EACF,GAAG,CAAC,eAAe,UAAU,CAAC;AAEhC,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,UAAU;AAAA,MACR,KAAK,cAAc;AAAA,MACnB,SAAS,cAAc;AAAA,MACvB,cAAc,cAAc;AAAA,MAC5B,eAAe,cAAc;AAAA,MAC7B,eAAe,cAAc;AAAA,MAC7B,mBAAmB,cAAc;AAAA;AAAA,MAEjC,YAAY,cAAc;AAAA,MAC1B,kBAAkB,cAAc;AAAA,MAChC,gBAAgB,cAAc;AAAA,MAC9B,cAAc,cAAc;AAAA,MAC5B,OAAO,cAAc;AAAA,IACvB;AAAA,IACA,WAAW;AAAA,MACT,MAAM,eAAe;AAAA,MACrB,SAAS,eAAe;AAAA,MACxB,SAAS,eAAe;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,cAAc,eAAe;AAAA,MAC7B,OAAO,eAAe;AAAA,MACtB,UAAU,eAAe;AAAA,MACzB,QAAQ,eAAe;AAAA,MACvB,iBAAiB,eAAe;AAAA,IAClC;AAAA;AAAA;AAAA,IAGA,QAAQ;AAAA,MACN;AAAA,MACA;AAAA,MACA,UAAU;AAAA,MACV,WAAW;AAAA,MACX,UAAU,cAAc;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,OACE,QAAQ,cAAc,cAAc,eAAe;AAAA,IACvD;AAAA,IACA;AAAA,IACA,oBAAoB;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/checkout/use-checkout.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport {\n SHIPPING_ERROR_CODES,\n type PaymentMethod,\n type StorePaymentMethod,\n} from \"@ecomweb/sdk\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { useAuth } from \"../auth/context\";\nimport { useCart } from \"../cart/server-context\";\nimport { useNotify } from \"../notices\";\nimport { publicOrdersApi } from \"../orders/api-client\";\nimport { usePromotionValidation } from \"../promotions/use-promotion-validation\";\nimport { sdk } from \"../sdk\";\nimport { useShippingCalculation } from \"../shipping/use-shipping-calculation\";\nimport { useStoreData } from \"../store/store-context\";\nimport { STORE_PREVIEW_READ_ONLY_MESSAGE } from \"../stores/store-preview-guard\";\nimport { initiateGatewayPayment } from \"./initiate-gateway-payment\";\nimport { writeOrderHandoff, type OrderHandoffSummary } from \"./order-handoff\";\nimport {\n getPaymentRedirectIntent,\n type PaymentMethodWithProviderCode,\n} from \"./payment-redirect\";\nimport { startGatewayRedirect } from \"./start-gateway-redirect\";\nimport { quoteChangedOptionsFrom } from \"./quote-changed\";\nimport { insufficientItemsFrom, stockIssuesByLine } from \"./stock-issues\";\nimport { getPaymentMethod } from \"./utils\";\n\n/** What the shopper entered; the app owns the form and its validation. */\nexport interface PlaceOrderInput {\n fullName: string;\n phone: string;\n email?: string;\n street: string;\n /** Province code, as quoted for shipping. */\n province: string;\n /** Ward code, as quoted for shipping. */\n ward: string;\n notes?: string;\n /** A `payment_method` code from `paymentMethods`. */\n paymentMethod: string;\n /**\n * What the thank-you page shows of the order; stored with the handoff in\n * this browser only, never sent to the API.\n */\n summary?: OrderHandoffSummary;\n}\n\nexport interface PlacedOrder {\n order_code: string;\n total: number | string | null;\n}\n\n/**\n * - redirect: the shopper is being sent to the payment provider.\n * - redirect_failed: the order exists but the provider hand-off did not\n * start; offer retryPaymentRedirect(). Further placeOrder calls return\n * this again instead of creating a second order.\n * - success: an offline-payment order; show its confirmation.\n * - stock_issues: nothing was placed; `issues` is copy keyed by cart line id.\n * - error: nothing was placed. `code` is the API's error code when it sent\n * one; pass it to `errorCopy`. On ORDER_PROMOTION_NOT_APPLICABLE the applied\n * code has already been removed, so the shopper sees the real total before\n * placing again.\n * - quote_changed: nothing was placed; the shipping options were replaced with\n * the API's new prices and the selection kept where possible; show\n * `SHIPPING_MESSAGES.quoteChanged` and let the shopper place again.\n * - busy: an earlier placeOrder is still running; this call did nothing.\n */\nexport type PlaceOrderResult =\n | { kind: \"redirect\" }\n | { kind: \"redirect_failed\"; orderCode: string }\n | { kind: \"success\"; order: PlacedOrder }\n | { kind: \"stock_issues\"; issues: Record<string, string> }\n | { kind: \"error\"; message: string; code?: string }\n | { kind: \"quote_changed\" }\n | { kind: \"busy\" };\n\nexport interface UseCheckoutOptions {\n /** The address fields shipping is quoted against (codes, may be empty). */\n province: string;\n ward: string;\n /**\n * Ask the API for carrier-quoted shipping options too. Off by default;\n * passed to `useShippingCalculation`.\n */\n includeCarrierOptions?: boolean;\n /** Leaves for the payment provider; defaults to a full-page navigation. */\n navigateToGateway?: (url: string) => void;\n}\n\nconst defaultNavigateToGateway = (url: string) => {\n window.location.href = url;\n};\n\n/**\n * Checkout without the UI: payment methods, shipping quotes, promotions,\n * totals, placing the order and the payment-provider hand-off. The app\n * renders the form and decides what to show for each PlaceOrderResult.\n */\nexport function useCheckout({\n province,\n ward,\n includeCarrierOptions = false,\n navigateToGateway = defaultNavigateToGateway,\n}: UseCheckoutOptions) {\n const store = useStoreData();\n const notify = useNotify();\n const {\n items,\n total,\n subtotal,\n originalSubtotal,\n discountAmount,\n clearCart,\n cartId,\n isLoading: isCartLoading,\n } = useCart();\n const { user, isAnonymous } = useAuth();\n\n const [paymentMethods, setPaymentMethods] = useState<StorePaymentMethod[]>(\n []\n );\n const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(true);\n const [savedAddressId, setSavedAddressId] = useState<number | undefined>(\n undefined\n );\n const [isSubmitting, setIsSubmitting] = useState(false);\n // Set only when the order was placed but the gateway redirect failed to\n // start. The order already exists, so the cart is deliberately left\n // intact until a redirect actually commits — this is what lets the shopper\n // retry payment without resubmitting the order.\n const [redirectError, setRedirectError] = useState<{\n order_code: string;\n provider_code: string;\n } | null>(null);\n const [isRetryingRedirect, setIsRetryingRedirect] = useState(false);\n // Set synchronously, unlike isSubmitting: a double-click lands before the\n // re-render that would disable the button.\n const inFlight = useRef(false);\n // Copy keyed by cart line id when the API rejects the order for short\n // stock. Cleared on the next submit.\n const [stockIssues, setStockIssues] = useState<Record<string, string>>({});\n\n const totalWeight = items.reduce(\n (sum, item) =>\n sum + ((item as { weight_gr?: number }).weight_gr || 500) * item.quantity,\n 0\n );\n\n const shippingQuote = useShippingCalculation({\n storeRef: store.ref,\n city: province,\n ward,\n subtotal,\n totalWeight,\n itemsCount: items.length,\n includeCarrierOptions,\n });\n\n const promotionState = usePromotionValidation({\n storeRef: store.ref,\n items: items.map(item => ({\n productId: item.productId,\n variantId: item.variantId ?? null,\n quantity: item.quantity,\n price: item.price,\n })),\n subtotal,\n shippingFee: shippingQuote.shippingFee,\n });\n\n useEffect(() => {\n const load = async () => {\n try {\n setIsLoadingPaymentMethods(true);\n setPaymentMethods(await sdk.paymentMethods.getEnabled(store.ref));\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to load payment methods:\", error);\n notify({\n kind: \"error\",\n code: \"checkout.payment_methods_failed\",\n title: \"Không thể tải phương thức thanh toán\",\n description: \"Vui lòng thử lại sau\",\n });\n } finally {\n setIsLoadingPaymentMethods(false);\n }\n };\n load();\n }, [store.ref, notify]);\n\n const redirectTo = useCallback(\n (target: { order_code: string; provider_code: string }) =>\n startGatewayRedirect({\n initiate: () => initiateGatewayPayment(store.ref, target),\n clearCart: () => clearCart(false),\n navigate: navigateToGateway,\n }),\n [store.ref, clearCart, navigateToGateway]\n );\n\n const placeOrder = async (\n input: PlaceOrderInput\n ): Promise<PlaceOrderResult> => {\n // The order from a failed hand-off still exists and the cart is kept for\n // it; placing again would create a second order for the same cart.\n if (redirectError) {\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n }\n if (inFlight.current) {\n return { kind: \"busy\" };\n }\n // A preview is read-only: the API would refuse the order anyway.\n if (isBrowserStorePreview()) {\n return {\n kind: \"error\",\n message: STORE_PREVIEW_READ_ONLY_MESSAGE,\n code: \"STORE_COMING_SOON\",\n };\n }\n inFlight.current = true;\n setIsSubmitting(true);\n setStockIssues({});\n // The quote this attempt is made against. A reply that lands after the\n // shopper changed the address must not overwrite the newer options.\n const quoteRequestId = shippingQuote.currentRequestId();\n\n try {\n const shippingOption = shippingQuote.selectedOption;\n const orderData = {\n cart_id: cartId || undefined,\n customer_name: input.fullName,\n customer_phone: input.phone,\n customer_email: input.email || \"\",\n // Money fields are deliberately not sent: the API recomputes subtotal,\n // shipping, discounts and total from the catalog and its own rules,\n // and ignores anything supplied here.\n shipping_street: input.street,\n shipping_city: input.province,\n shipping_ward: input.ward,\n payment_method: getPaymentMethod(input.paymentMethod) as PaymentMethod,\n // The shopper's choice of rate is real input; the API prices it and\n // rejects a rate_id that isn't one it just quoted for this address\n // and cart. useShippingCalculation clears the selection the moment an\n // input it was quoted against changes, so this is either nothing\n // (omitted, the API picks) or an option from the matching quote.\n // A carrier option also names its service and the amount the shopper\n // saw; after a quote_changed that is the replaced amount, so the\n // retry confirms the new price.\n ...(shippingOption && {\n shipping_rate_id: shippingOption.rate_id,\n ...(shippingOption.carrier_service_id && {\n shipping_service_id: shippingOption.carrier_service_id,\n shipping_quoted_amount: shippingOption.amount,\n }),\n }),\n notes: input.notes || undefined,\n promotion_id: promotionState.appliedPromotion?.id || undefined,\n ...(savedAddressId && { customer_address_id: savedAddressId }),\n items: items.map(item => ({\n product_id: item.productId,\n variant_id: item.variantId,\n variant_name: item.variantName,\n product_name: item.name,\n product_image: item.image,\n quantity: item.quantity,\n // No price/total: the API resolves the unit price from the catalog.\n })),\n };\n\n // A signed-in (non-anonymous) shopper's order goes to the authenticated\n // route so the backend links it to their customer record; guests and\n // anonymous identities keep the public route.\n const order = await publicOrdersApi.createStoreOrder(\n store.ref,\n orderData,\n !!user && !isAnonymous\n );\n\n // The order now exists no matter what happens below. A gateway-backed\n // method (non-null provider_code) must send the shopper to the provider\n // to pay; offline methods land on the success screen.\n const method = paymentMethods.find(\n m => m.payment_method === input.paymentMethod\n ) as PaymentMethodWithProviderCode | undefined;\n const intent = getPaymentRedirectIntent(method, order.order_code);\n\n if (intent) {\n try {\n await redirectTo(intent);\n return { kind: \"redirect\" };\n } catch (initiateError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to initiate gateway payment:\", initiateError);\n setRedirectError(intent);\n return { kind: \"redirect_failed\", orderCode: intent.order_code };\n }\n }\n\n // The handoff carries what the success screen cannot ask the API for:\n // the amount to transfer (see order-handoff.ts).\n writeOrderHandoff({\n order_code: order.order_code,\n payment_method: input.paymentMethod,\n provider_code: method?.provider_code ?? null,\n total: Number(order.total ?? 0),\n currency_code:\n (order as { currency_code?: string }).currency_code ?? \"VND\",\n summary: input.summary ?? null,\n });\n clearCart(false);\n return {\n kind: \"success\",\n order: { order_code: order.order_code, total: order.total ?? null },\n };\n } catch (error) {\n const shortItems = insufficientItemsFrom(error);\n if (shortItems) {\n const issues = stockIssuesByLine(items, shortItems);\n setStockIssues(issues);\n return { kind: \"stock_issues\", issues };\n }\n // The carrier's price moved since the shopper saw it. Show the new\n // options (selection kept where possible) and let them place again.\n const changed = quoteChangedOptionsFrom(error);\n if (changed) {\n shippingQuote.replaceOptions(\n changed,\n shippingQuote.selectedOptionId,\n quoteRequestId\n );\n return { kind: \"quote_changed\" };\n }\n const code =\n error && typeof error === \"object\" && \"code\" in error\n ? (error as { code?: unknown }).code\n : undefined;\n // The API refused the order rather than drop the discount the shopper\n // was shown (or the code is used up). Keeping the code would fail every\n // retry the same way.\n if (\n code === \"ORDER_PROMOTION_NOT_APPLICABLE\" ||\n code === \"PROMOTION_USAGE_LIMIT_REACHED\"\n ) {\n promotionState.removePromoCode();\n }\n // The carrier could not price the chosen option, or reported a changed\n // quote we cannot use: refresh the options so the shopper can pick\n // again instead of being stuck on a stale list.\n if (\n code === SHIPPING_ERROR_CODES.RATE_UNAVAILABLE ||\n code === SHIPPING_ERROR_CODES.QUOTE_CHANGED\n ) {\n shippingQuote.retryCalculation();\n }\n return {\n kind: \"error\",\n message: error instanceof Error ? error.message : String(error),\n ...(typeof code === \"string\" && { code }),\n };\n } finally {\n inFlight.current = false;\n setIsSubmitting(false);\n }\n };\n\n // The order already exists — this only re-attempts starting the gateway\n // charge, never re-submits the order.\n const retryPaymentRedirect =\n useCallback(async (): Promise<PlaceOrderResult> => {\n if (!redirectError) return { kind: \"error\", message: \"No order to pay\" };\n setIsRetryingRedirect(true);\n try {\n await redirectTo(redirectError);\n return { kind: \"redirect\" };\n } catch (retryError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to retry gateway payment redirect:\", retryError);\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n } finally {\n setIsRetryingRedirect(false);\n }\n }, [redirectError, redirectTo]);\n\n return {\n items,\n isCartLoading,\n paymentMethods,\n isLoadingPaymentMethods,\n shipping: {\n fee: shippingQuote.shippingFee,\n options: shippingQuote.shippingOptions,\n selectedRate: shippingQuote.selectedShippingRate,\n isCalculating: shippingQuote.isCalculatingShipping,\n hasCalculated: shippingQuote.hasCalculatedShipping,\n calculationFailed: shippingQuote.calculationFailed,\n /** @deprecated Use selectOption. */\n selectRate: shippingQuote.handleShippingRateSelect,\n selectedOptionId: shippingQuote.selectedOptionId,\n selectedOption: shippingQuote.selectedOption,\n selectOption: shippingQuote.handleShippingOptionSelect,\n retry: shippingQuote.retryCalculation,\n },\n promotion: {\n code: promotionState.promoCode,\n setCode: promotionState.setPromoCode,\n applied: promotionState.appliedPromotion,\n shippingDiscount: promotionState.shippingDiscount,\n isValidating: promotionState.isValidatingPromo,\n error: promotionState.promoError,\n validate: promotionState.validatePromoCode,\n remove: promotionState.removePromoCode,\n applySuggestion: promotionState.applyPromotionFromSuggestion,\n },\n // shippingDiscount comes from the API's promotion validation — the same\n // number the server applies when the order is placed.\n totals: {\n subtotal,\n originalSubtotal,\n discount: discountAmount,\n cartTotal: total,\n shipping: shippingQuote.shippingFee,\n shippingDiscount: promotionState.shippingDiscount,\n total:\n total + shippingQuote.shippingFee - promotionState.shippingDiscount,\n },\n savedAddressId,\n selectSavedAddress: setSavedAddressId,\n stockIssues,\n isSubmitting,\n redirectError,\n isRetryingRedirect,\n placeOrder,\n retryPaymentRedirect,\n };\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AACzD;AAAA,EACE;AAAA,OAGK;AACP,SAAS,6BAA6B;AACtC,SAAS,eAAe;AACxB,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AACvC,SAAS,WAAW;AACpB,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAC7B,SAAS,uCAAuC;AAChD,SAAS,8BAA8B;AACvC,SAAS,yBAAmD;AAC5D;AAAA,EACE;AAAA,OAEK;AACP,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC,SAAS,uBAAuB,yBAAyB;AACzD,SAAS,wBAAwB;AAiEjC,MAAM,2BAA2B,CAAC,QAAgB;AAChD,SAAO,SAAS,OAAO;AACzB;AAOO,SAAS,YAAY;AAAA,EAC1B;AAAA,EACA;AAAA,EACA,wBAAwB;AAAA,EACxB,oBAAoB;AACtB,GAAuB;AACrB,QAAM,QAAQ,aAAa;AAC3B,QAAM,SAAS,UAAU;AACzB,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW;AAAA,EACb,IAAI,QAAQ;AACZ,QAAM,EAAE,MAAM,YAAY,IAAI,QAAQ;AAEtC,QAAM,CAAC,gBAAgB,iBAAiB,IAAI;AAAA,IAC1C,CAAC;AAAA,EACH;AACA,QAAM,CAAC,yBAAyB,0BAA0B,IAAI,SAAS,IAAI;AAC3E,QAAM,CAAC,gBAAgB,iBAAiB,IAAI;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MAChC,gBAAgB,cAAc;AAAA,MAC9B,cAAc,cAAc;AAAA,MAC5B,OAAO,cAAc;AAAA,IACvB;AAAA,IACA,WAAW;AAAA,MACT,MAAM,eAAe;AAAA,MACrB,SAAS,eAAe;AAAA,MACxB,SAAS,eAAe;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,cAAc,eAAe;AAAA,MAC7B,OAAO,eAAe;AAAA,MACtB,UAAU,eAAe;AAAA,MACzB,QAAQ,eAAe;AAAA,MACvB,iBAAiB,eAAe;AAAA,IAClC;AAAA;AAAA;AAAA,IAGA,QAAQ;AAAA,MACN;AAAA,MACA;AAAA,MACA,UAAU;AAAA,MACV,WAAW;AAAA,MACX,UAAU,cAAc;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,OACE,QAAQ,cAAc,cAAc,eAAe;AAAA,IACvD;AAAA,IACA;AAAA,IACA,oBAAoB;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
package/dist/index.d.ts CHANGED
@@ -270,6 +270,48 @@ declare function useCheckout({ province, ward, includeCarrierOptions, navigateTo
270
270
  retryPaymentRedirect: () => Promise<PlaceOrderResult>;
271
271
  };
272
272
 
273
+ /** The bank_transfer slice of the public payment-methods projection. */
274
+ interface BankAccountView {
275
+ id: number;
276
+ bank_name: string;
277
+ bank_code: string;
278
+ account_number: string;
279
+ account_holder: string;
280
+ }
281
+ /** What a shopper needs to pay a bank transfer order. */
282
+ interface BankTransferDetails {
283
+ accounts: BankAccountView[];
284
+ /** The merchant's transfer instruction, if they wrote one. */
285
+ note: string | null;
286
+ isLoading: boolean;
287
+ }
288
+ /**
289
+ * Whether an order page should tell the shopper how to pay by transfer: a
290
+ * bank_transfer order the merchant has not marked paid yet, and that is
291
+ * still live. Order pages read this from the order itself, so they work for
292
+ * any order, long after the checkout handoff has expired.
293
+ */
294
+ declare function shouldShowBankTransferDetails(order: {
295
+ payment_method?: string | null;
296
+ payment_status?: string | null;
297
+ order_status?: string | null;
298
+ } | null | undefined): boolean;
299
+ /**
300
+ * The bank_transfer method's accounts and instruction out of the public
301
+ * payment-methods response. A store without the method, or a malformed
302
+ * response, yields no accounts.
303
+ */
304
+ declare function pickBankTransfer(methods: unknown): {
305
+ accounts: BankAccountView[];
306
+ note: string | null;
307
+ };
308
+ /**
309
+ * The store's bank accounts and transfer instruction, fetched from the
310
+ * public payment-methods endpoint while `enabled`. Used by the order-success
311
+ * page and by the order lookup and account order pages.
312
+ */
313
+ declare function useBankTransferDetails(enabled: boolean): BankTransferDetails;
314
+
273
315
  /**
274
316
  * Which success screen an order gets.
275
317
  *
@@ -306,14 +348,6 @@ declare function resolveInitialState(order_code: string | null, handoff: OrderHa
306
348
  */
307
349
  declare function shouldPollForConfirmation(state: PaymentConfirmationState): boolean;
308
350
 
309
- /** The bank_transfer slice of the public payment-methods projection. */
310
- interface BankAccountView {
311
- id: number;
312
- bank_name: string;
313
- bank_code: string;
314
- account_number: string;
315
- account_holder: string;
316
- }
317
351
  /**
318
352
  * What the shopper should be told about a just-placed order (the
319
353
  * order-success page, which is also the payment gateway's return URL).
@@ -1234,4 +1268,4 @@ declare function getLogLevel(): LogLevel;
1234
1268
  declare function shouldLog(currentLevel: LogLevel, messageLevel: LogLevel): boolean;
1235
1269
  declare function applyConsoleFilter(level?: LogLevel): void;
1236
1270
 
1237
- export { type BankAccountView, COMING_SOON_STORE_DESCRIPTION, DEFAULT_REDIRECT, type Notice, type NoticeHandler, type NoticeKind, ORDER_PROGRESS_STEPS, type OrderHandoff, type OrderHandoffSummary, type OrderSuccessInfo, type PaymentConfirmationState, type PlaceOrderInput, type PlaceOrderResult, type PlacedOrder, RichText, type RichTextProps, SHIPMENT_STATUS_LABELS, SHIPPING_MESSAGES, STATUS_OPTIONS, STOCK_ISSUE_TOAST_DESCRIPTION, STORE_COMING_SOON_REDIRECT_PATH, STORE_PREVIEW_READ_ONLY_MESSAGE, SUSPENDED_STORE_METADATA, type ShipmentTrackingView, type ShippingOptionDisplay, StorefrontKitProvider, type StorefrontKitProviderProps, type SupportedCurrency, THEME_PREVIEW_FRAME_ATTR, THEME_PREVIEW_MESSAGE, TRACKING_MESSAGES, ThemePreviewBridge, ThemeSettingsProvider, ThemeStyle, type UseCheckoutOptions, applyConsoleFilter, buildStoreUrl, canCustomerCancel, comingSoonStoreMetadata, comingSoonStoreNameOf, createStoreSdk, deriveOrderProgress, deriveShipmentTracking, describeShippingOption, errorCopy, errorCopyFor, findProvinceByCodeOrName, findWardByCodeOrName, formatNumber, formatPrice, formatPriceRange, formatPriceWithoutSymbol, formatShippingAmount, formatShippingEstimate, getCachedStore, getDefaultLocale, getLogLevel, getMetaobject, getMetaobjects, getPasswordPolicyHints, getPaymentState, getPromotionDescription, isCarrierShipment, isHandedToCarrier, isStoreComingSoonError, isStoreSuspendedError, loadWards, metafield, metaobjectField, money, optionIdOf, pollPaymentState, publicApiClient, quoteChangedOptionsFrom, readBasicSettings, readOrderHandoff, refFromPathname, resolveAssetSrc, resolveInitialState, resolveLegalHref, resolveStoreRef, resolveTransformedImageUrl, resolveTransformedProductImageUrl, resolveTransformedStoreLogoUrl, safeRedirectPath, sdk, searchTextFor, shipmentEventLabel, shouldLog, shouldPollForConfirmation, storeApiPath, storePath, themeStyleCss, unwrap, unwrapOrNull, useAuth, useCart, useCheckout, useNotify, useOptionalStoreId, useOptionalThemeId, useOptionalThemeKey, useOrderLookup, useOrderStatus, useProvinces, usePublicAuthConfig, useStore, useStoreCurrency, useStoreData, useStoreId, useStoreLocale, useThemeId, useThemeSettings, useWards, validatePasswordAgainstPolicy, withSuspendedStoreMetadataFallback };
1271
+ export { type BankAccountView, type BankTransferDetails, COMING_SOON_STORE_DESCRIPTION, DEFAULT_REDIRECT, type Notice, type NoticeHandler, type NoticeKind, ORDER_PROGRESS_STEPS, type OrderHandoff, type OrderHandoffSummary, type OrderSuccessInfo, type PaymentConfirmationState, type PlaceOrderInput, type PlaceOrderResult, type PlacedOrder, RichText, type RichTextProps, SHIPMENT_STATUS_LABELS, SHIPPING_MESSAGES, STATUS_OPTIONS, STOCK_ISSUE_TOAST_DESCRIPTION, STORE_COMING_SOON_REDIRECT_PATH, STORE_PREVIEW_READ_ONLY_MESSAGE, SUSPENDED_STORE_METADATA, type ShipmentTrackingView, type ShippingOptionDisplay, StorefrontKitProvider, type StorefrontKitProviderProps, type SupportedCurrency, THEME_PREVIEW_FRAME_ATTR, THEME_PREVIEW_MESSAGE, TRACKING_MESSAGES, ThemePreviewBridge, ThemeSettingsProvider, ThemeStyle, type UseCheckoutOptions, applyConsoleFilter, buildStoreUrl, canCustomerCancel, comingSoonStoreMetadata, comingSoonStoreNameOf, createStoreSdk, deriveOrderProgress, deriveShipmentTracking, describeShippingOption, errorCopy, errorCopyFor, findProvinceByCodeOrName, findWardByCodeOrName, formatNumber, formatPrice, formatPriceRange, formatPriceWithoutSymbol, formatShippingAmount, formatShippingEstimate, getCachedStore, getDefaultLocale, getLogLevel, getMetaobject, getMetaobjects, getPasswordPolicyHints, getPaymentState, getPromotionDescription, isCarrierShipment, isHandedToCarrier, isStoreComingSoonError, isStoreSuspendedError, loadWards, metafield, metaobjectField, money, optionIdOf, pickBankTransfer, pollPaymentState, publicApiClient, quoteChangedOptionsFrom, readBasicSettings, readOrderHandoff, refFromPathname, resolveAssetSrc, resolveInitialState, resolveLegalHref, resolveStoreRef, resolveTransformedImageUrl, resolveTransformedProductImageUrl, resolveTransformedStoreLogoUrl, safeRedirectPath, sdk, searchTextFor, shipmentEventLabel, shouldLog, shouldPollForConfirmation, shouldShowBankTransferDetails, storeApiPath, storePath, themeStyleCss, unwrap, unwrapOrNull, useAuth, useBankTransferDetails, useCart, useCheckout, useNotify, useOptionalStoreId, useOptionalThemeId, useOptionalThemeKey, useOrderLookup, useOrderStatus, useProvinces, usePublicAuthConfig, useStore, useStoreCurrency, useStoreData, useStoreId, useStoreLocale, useThemeId, useThemeSettings, useWards, validatePasswordAgainstPolicy, withSuspendedStoreMetadataFallback };
package/dist/index.js CHANGED
@@ -2,6 +2,11 @@ import { StorefrontKitProvider } from "./provider.js";
2
2
  import { useNotify } from "./notices.js";
3
3
  import { useCheckout } from "./checkout/use-checkout.js";
4
4
  import { useOrderLookup, useOrderStatus } from "./orders/use-order-status.js";
5
+ import {
6
+ pickBankTransfer,
7
+ shouldShowBankTransferDetails,
8
+ useBankTransferDetails
9
+ } from "./orders/bank-transfer.js";
5
10
  import {
6
11
  useOptionalStoreId,
7
12
  useStore,
@@ -169,6 +174,7 @@ export {
169
174
  metaobjectField,
170
175
  money,
171
176
  optionIdOf,
177
+ pickBankTransfer,
172
178
  pollPaymentState,
173
179
  publicApiClient,
174
180
  quoteChangedOptionsFrom,
@@ -188,12 +194,14 @@ export {
188
194
  shipmentEventLabel,
189
195
  shouldLog,
190
196
  shouldPollForConfirmation,
197
+ shouldShowBankTransferDetails,
191
198
  storeApiPath,
192
199
  storePath,
193
200
  themeStyleCss,
194
201
  unwrap,
195
202
  unwrapOrNull,
196
203
  useAuth,
204
+ useBankTransferDetails,
197
205
  useCart,
198
206
  useCheckout,
199
207
  useNotify,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["// @ecomweb/storefront-kit: client-safe hooks, providers and helpers.\nexport { StorefrontKitProvider } from \"./provider\";\nexport type { StorefrontKitProviderProps } from \"./provider\";\nexport { useNotify } from \"./notices\";\nexport { useCheckout } from \"./checkout/use-checkout\";\nexport { useOrderLookup, useOrderStatus } from \"./orders/use-order-status\";\nexport type { BankAccountView } from \"./orders/use-order-status\";\nexport type {\n PlacedOrder,\n PlaceOrderInput,\n PlaceOrderResult,\n UseCheckoutOptions,\n} from \"./checkout/use-checkout\";\nexport type { Notice, NoticeHandler, NoticeKind } from \"./notices\";\nexport {\n useOptionalStoreId,\n useStore,\n useStoreCurrency,\n useStoreData,\n useStoreId,\n useStoreLocale,\n} from \"./store/store-context\";\nexport { usePublicAuthConfig } from \"./auth/use-public-auth-config\";\nexport { publicApiClient } from \"./api/client\";\nexport { unwrap, unwrapOrNull } from \"./api/response\";\nexport { useAuth } from \"./auth/context\";\nexport { errorCopy, errorCopyFor } from \"./auth/error-copy\";\nexport {\n getPasswordPolicyHints,\n validatePasswordAgainstPolicy,\n} from \"./auth/password-policy\";\nexport { DEFAULT_REDIRECT, safeRedirectPath } from \"./auth/safe-redirect\";\nexport { useCart } from \"./cart/server-context\";\nexport { getPaymentState } from \"./checkout/get-payment-state\";\nexport { readOrderHandoff } from \"./checkout/order-handoff\";\nexport type {\n OrderHandoff,\n OrderHandoffSummary,\n} from \"./checkout/order-handoff\";\nexport { pollPaymentState } from \"./checkout/payment-state-poll\";\nexport { quoteChangedOptionsFrom } from \"./checkout/quote-changed\";\nexport { optionIdOf } from \"./shipping/option-id\";\nexport { STOCK_ISSUE_TOAST_DESCRIPTION } from \"./checkout/stock-issues\";\nexport {\n resolveInitialState,\n shouldPollForConfirmation,\n} from \"./checkout/success-state\";\nexport type { PaymentConfirmationState } from \"./checkout/success-state\";\nexport type { OrderSuccessInfo } from \"./checkout/types\";\nexport {\n formatNumber,\n formatPrice,\n formatPriceRange,\n formatPriceWithoutSymbol,\n getDefaultLocale,\n money,\n} from \"./currency\";\nexport type { SupportedCurrency } from \"./currency\";\nexport {\n ORDER_PROGRESS_STEPS,\n deriveOrderProgress,\n} from \"./orders/derive-progress\";\nexport { STATUS_OPTIONS } from \"./orders/types\";\nexport {\n SHIPMENT_STATUS_LABELS,\n TRACKING_MESSAGES,\n canCustomerCancel,\n deriveShipmentTracking,\n isCarrierShipment,\n isHandedToCarrier,\n shipmentEventLabel,\n} from \"./orders/shipment-tracking\";\nexport type { ShipmentTrackingView } from \"./orders/shipment-tracking\";\nexport { getPromotionDescription } from \"./promotions/utils\";\nexport { createStoreSdk, sdk } from \"./sdk\";\nexport {\n formatShippingAmount,\n describeShippingOption,\n type ShippingOptionDisplay,\n} from \"./shipping/format-shipping-option\";\nexport {\n loadWards,\n searchTextFor,\n useProvinces,\n useWards,\n} from \"./shipping/location-areas\";\nexport { SHIPPING_MESSAGES, formatShippingEstimate } from \"./shipping/messages\";\nexport {\n findProvinceByCodeOrName,\n findWardByCodeOrName,\n} from \"./shipping/utils\";\nexport {\n resolveAssetSrc,\n resolveTransformedImageUrl,\n resolveTransformedProductImageUrl,\n resolveTransformedStoreLogoUrl,\n} from \"./storage\";\nexport { resolveStoreRef, storeApiPath, storePath } from \"./store-scope\";\nexport { buildStoreUrl } from \"./store-scope/store-url\";\nexport { readBasicSettings, resolveLegalHref } from \"./stores/basic-settings\";\nexport { defineSchema, defineTheme } from \"./theme/define\";\nexport type {\n AnyThemeDefinition,\n BlogIndexSlotProps,\n BlogPostSlotProps,\n CollectionPageSlotProps,\n CollectionSearchParams,\n ContentPageSlotProps,\n NotFoundProps,\n ProductCardProps,\n ProductPageSlotProps,\n ThemeClientComponents,\n HomePageSlotProps,\n LayoutSlotProps,\n ThemeComponents,\n ThemeDefinition,\n ThemeInfo,\n ThemeSlot,\n ThemeSlotName,\n ThemeSlotProps,\n} from \"./theme/define\";\nexport {\n ThemeSettingsProvider,\n useOptionalThemeId,\n useOptionalThemeKey,\n useThemeId,\n useThemeSettings,\n} from \"./theme/settings-context\";\nexport { metafield, metaobjectField } from \"./metafields/readers\";\nexport { getMetaobject, getMetaobjects } from \"./metafields/metaobjects\";\nexport { RichText } from \"./metafields/rich-text\";\nexport type { RichTextProps } from \"./metafields/rich-text\";\nexport { ThemeStyle, themeStyleCss } from \"./theme/style\";\nexport {\n THEME_PREVIEW_FRAME_ATTR,\n THEME_PREVIEW_MESSAGE,\n ThemePreviewBridge,\n} from \"./theme/preview-bridge\";\nexport { getCachedStore } from \"./stores/cached\";\nexport {\n COMING_SOON_STORE_DESCRIPTION,\n comingSoonStoreMetadata,\n SUSPENDED_STORE_METADATA,\n withSuspendedStoreMetadataFallback,\n} from \"./stores/metadata\";\nexport { refFromPathname } from \"./stores/store-path\";\nexport { STORE_PREVIEW_READ_ONLY_MESSAGE } from \"./stores/store-preview-guard\";\nexport { isStoreSuspendedError } from \"./stores/store-suspension\";\nexport {\n comingSoonStoreNameOf,\n isStoreComingSoonError,\n STORE_COMING_SOON_REDIRECT_PATH,\n} from \"./stores/store-coming-soon\";\nexport { applyConsoleFilter, getLogLevel, shouldLog } from \"./logging\";\n"],"mappings":"AACA,SAAS,6BAA6B;AAEtC,SAAS,iBAAiB;AAC1B,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB,sBAAsB;AAS/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAChC,SAAS,QAAQ,oBAAoB;AACrC,SAAS,eAAe;AACxB,SAAS,WAAW,oBAAoB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,kBAAkB,wBAAwB;AACnD,SAAS,eAAe;AACxB,SAAS,uBAAuB;AAChC,SAAS,wBAAwB;AAKjC,SAAS,wBAAwB;AACjC,SAAS,+BAA+B;AACxC,SAAS,kBAAkB;AAC3B,SAAS,qCAAqC;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,+BAA+B;AACxC,SAAS,gBAAgB,WAAW;AACpC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB,8BAA8B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB,cAAc,iBAAiB;AACzD,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB,wBAAwB;AACpD,SAAS,cAAc,mBAAmB;AAqB1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,WAAW,uBAAuB;AAC3C,SAAS,eAAe,sBAAsB;AAC9C,SAAS,gBAAgB;AAEzB,SAAS,YAAY,qBAAqB;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,uCAAuC;AAChD,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB,aAAa,iBAAiB;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["// @ecomweb/storefront-kit: client-safe hooks, providers and helpers.\nexport { StorefrontKitProvider } from \"./provider\";\nexport type { StorefrontKitProviderProps } from \"./provider\";\nexport { useNotify } from \"./notices\";\nexport { useCheckout } from \"./checkout/use-checkout\";\nexport { useOrderLookup, useOrderStatus } from \"./orders/use-order-status\";\nexport {\n pickBankTransfer,\n shouldShowBankTransferDetails,\n useBankTransferDetails,\n} from \"./orders/bank-transfer\";\nexport type {\n BankAccountView,\n BankTransferDetails,\n} from \"./orders/bank-transfer\";\nexport type {\n PlacedOrder,\n PlaceOrderInput,\n PlaceOrderResult,\n UseCheckoutOptions,\n} from \"./checkout/use-checkout\";\nexport type { Notice, NoticeHandler, NoticeKind } from \"./notices\";\nexport {\n useOptionalStoreId,\n useStore,\n useStoreCurrency,\n useStoreData,\n useStoreId,\n useStoreLocale,\n} from \"./store/store-context\";\nexport { usePublicAuthConfig } from \"./auth/use-public-auth-config\";\nexport { publicApiClient } from \"./api/client\";\nexport { unwrap, unwrapOrNull } from \"./api/response\";\nexport { useAuth } from \"./auth/context\";\nexport { errorCopy, errorCopyFor } from \"./auth/error-copy\";\nexport {\n getPasswordPolicyHints,\n validatePasswordAgainstPolicy,\n} from \"./auth/password-policy\";\nexport { DEFAULT_REDIRECT, safeRedirectPath } from \"./auth/safe-redirect\";\nexport { useCart } from \"./cart/server-context\";\nexport { getPaymentState } from \"./checkout/get-payment-state\";\nexport { readOrderHandoff } from \"./checkout/order-handoff\";\nexport type {\n OrderHandoff,\n OrderHandoffSummary,\n} from \"./checkout/order-handoff\";\nexport { pollPaymentState } from \"./checkout/payment-state-poll\";\nexport { quoteChangedOptionsFrom } from \"./checkout/quote-changed\";\nexport { optionIdOf } from \"./shipping/option-id\";\nexport { STOCK_ISSUE_TOAST_DESCRIPTION } from \"./checkout/stock-issues\";\nexport {\n resolveInitialState,\n shouldPollForConfirmation,\n} from \"./checkout/success-state\";\nexport type { PaymentConfirmationState } from \"./checkout/success-state\";\nexport type { OrderSuccessInfo } from \"./checkout/types\";\nexport {\n formatNumber,\n formatPrice,\n formatPriceRange,\n formatPriceWithoutSymbol,\n getDefaultLocale,\n money,\n} from \"./currency\";\nexport type { SupportedCurrency } from \"./currency\";\nexport {\n ORDER_PROGRESS_STEPS,\n deriveOrderProgress,\n} from \"./orders/derive-progress\";\nexport { STATUS_OPTIONS } from \"./orders/types\";\nexport {\n SHIPMENT_STATUS_LABELS,\n TRACKING_MESSAGES,\n canCustomerCancel,\n deriveShipmentTracking,\n isCarrierShipment,\n isHandedToCarrier,\n shipmentEventLabel,\n} from \"./orders/shipment-tracking\";\nexport type { ShipmentTrackingView } from \"./orders/shipment-tracking\";\nexport { getPromotionDescription } from \"./promotions/utils\";\nexport { createStoreSdk, sdk } from \"./sdk\";\nexport {\n formatShippingAmount,\n describeShippingOption,\n type ShippingOptionDisplay,\n} from \"./shipping/format-shipping-option\";\nexport {\n loadWards,\n searchTextFor,\n useProvinces,\n useWards,\n} from \"./shipping/location-areas\";\nexport { SHIPPING_MESSAGES, formatShippingEstimate } from \"./shipping/messages\";\nexport {\n findProvinceByCodeOrName,\n findWardByCodeOrName,\n} from \"./shipping/utils\";\nexport {\n resolveAssetSrc,\n resolveTransformedImageUrl,\n resolveTransformedProductImageUrl,\n resolveTransformedStoreLogoUrl,\n} from \"./storage\";\nexport { resolveStoreRef, storeApiPath, storePath } from \"./store-scope\";\nexport { buildStoreUrl } from \"./store-scope/store-url\";\nexport { readBasicSettings, resolveLegalHref } from \"./stores/basic-settings\";\nexport { defineSchema, defineTheme } from \"./theme/define\";\nexport type {\n AnyThemeDefinition,\n BlogIndexSlotProps,\n BlogPostSlotProps,\n CollectionPageSlotProps,\n CollectionSearchParams,\n ContentPageSlotProps,\n NotFoundProps,\n ProductCardProps,\n ProductPageSlotProps,\n ThemeClientComponents,\n HomePageSlotProps,\n LayoutSlotProps,\n ThemeComponents,\n ThemeDefinition,\n ThemeInfo,\n ThemeSlot,\n ThemeSlotName,\n ThemeSlotProps,\n} from \"./theme/define\";\nexport {\n ThemeSettingsProvider,\n useOptionalThemeId,\n useOptionalThemeKey,\n useThemeId,\n useThemeSettings,\n} from \"./theme/settings-context\";\nexport { metafield, metaobjectField } from \"./metafields/readers\";\nexport { getMetaobject, getMetaobjects } from \"./metafields/metaobjects\";\nexport { RichText } from \"./metafields/rich-text\";\nexport type { RichTextProps } from \"./metafields/rich-text\";\nexport { ThemeStyle, themeStyleCss } from \"./theme/style\";\nexport {\n THEME_PREVIEW_FRAME_ATTR,\n THEME_PREVIEW_MESSAGE,\n ThemePreviewBridge,\n} from \"./theme/preview-bridge\";\nexport { getCachedStore } from \"./stores/cached\";\nexport {\n COMING_SOON_STORE_DESCRIPTION,\n comingSoonStoreMetadata,\n SUSPENDED_STORE_METADATA,\n withSuspendedStoreMetadataFallback,\n} from \"./stores/metadata\";\nexport { refFromPathname } from \"./stores/store-path\";\nexport { STORE_PREVIEW_READ_ONLY_MESSAGE } from \"./stores/store-preview-guard\";\nexport { isStoreSuspendedError } from \"./stores/store-suspension\";\nexport {\n comingSoonStoreNameOf,\n isStoreComingSoonError,\n STORE_COMING_SOON_REDIRECT_PATH,\n} from \"./stores/store-coming-soon\";\nexport { applyConsoleFilter, getLogLevel, shouldLog } from \"./logging\";\n"],"mappings":"AACA,SAAS,6BAA6B;AAEtC,SAAS,iBAAiB;AAC1B,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB,sBAAsB;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAYP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAChC,SAAS,QAAQ,oBAAoB;AACrC,SAAS,eAAe;AACxB,SAAS,WAAW,oBAAoB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,kBAAkB,wBAAwB;AACnD,SAAS,eAAe;AACxB,SAAS,uBAAuB;AAChC,SAAS,wBAAwB;AAKjC,SAAS,wBAAwB;AACjC,SAAS,+BAA+B;AACxC,SAAS,kBAAkB;AAC3B,SAAS,qCAAqC;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,+BAA+B;AACxC,SAAS,gBAAgB,WAAW;AACpC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB,8BAA8B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB,cAAc,iBAAiB;AACzD,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB,wBAAwB;AACpD,SAAS,cAAc,mBAAmB;AAqB1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,WAAW,uBAAuB;AAC3C,SAAS,eAAe,sBAAsB;AAC9C,SAAS,gBAAgB;AAEzB,SAAS,YAAY,qBAAqB;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,uCAAuC;AAChD,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB,aAAa,iBAAiB;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/metafields/rich-text.tsx"],"sourcesContent":["import {\n createElement,\n Fragment,\n type ReactElement,\n type ReactNode,\n} from \"react\";\nimport type { RichTextRoot } from \"@ecomweb/sdk\";\n\n/**\n * The engine's link rule (spec 5.3), re-checked at render: the tree was\n * validated on write, but a row written before a validation fix, or edited\n * in the database, must still never become a script URL here. At least as\n * strict as the SDK engine. Commas are legal in http(s) URLs; only the\n * mailto pattern refuses them.\n */\nconst MAX_URL_LENGTH = 2048;\nconst UNSAFE_URL_CHARS = /[\\u0000-\\u001f\\u007f-\\u009f\"<>`\\\\]|\\s/;\nconst MAILTO = /^mailto:[^\\s@?&#,]+@[^\\s@?&#,]+$/i;\n\nexport interface RichTextHref {\n href: string;\n /** http(s) links; they get rel=\"noopener noreferrer\". */\n external: boolean;\n}\n\nexport function richTextHref(url: unknown): RichTextHref | null {\n if (\n typeof url !== \"string\" ||\n url.length === 0 ||\n url.length > MAX_URL_LENGTH ||\n UNSAFE_URL_CHARS.test(url)\n ) {\n return null;\n }\n if (MAILTO.test(url)) return { href: url, external: false };\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return null;\n }\n return parsed.protocol === \"http:\" || parsed.protocol === \"https:\"\n ? { href: url, external: true }\n : null;\n}\n\ntype Node = Record<string, unknown>;\n\nconst isNode = (value: unknown): value is Node =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst childrenOf = (node: Node): unknown[] =>\n Array.isArray(node.children) ? node.children : [];\n\nconst HEADINGS: Record<number, \"h1\" | \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"h6\"> = {\n 1: \"h1\",\n 2: \"h2\",\n 3: \"h3\",\n 4: \"h4\",\n 5: \"h5\",\n 6: \"h6\",\n};\n\n/** Only the listed keys of a node are ever read; nothing is spread into props. */\nfunction renderText(node: Node, key: number): ReactNode {\n if (typeof node.value !== \"string\") return null;\n let out: ReactNode = node.value;\n if (node.italic === true) out = <em>{out}</em>;\n if (node.bold === true) out = <strong>{out}</strong>;\n return <Fragment key={key}>{out}</Fragment>;\n}\n\nfunction renderInline(node: unknown, key: number): ReactNode {\n if (!isNode(node)) return null;\n if (node.type === \"text\") return renderText(node, key);\n if (node.type !== \"link\") return null;\n const text = childrenOf(node).map((child, index) =>\n isNode(child) && child.type === \"text\" ? renderText(child, index) : null\n );\n const link = richTextHref(node.url);\n if (!link) return <Fragment key={key}>{text}</Fragment>;\n const title =\n typeof node.title === \"string\" && node.title !== \"\"\n ? node.title\n : undefined;\n return (\n <a\n key={key}\n href={link.href}\n rel={link.external ? \"noopener noreferrer\" : undefined}\n title={title}\n >\n {text}\n </a>\n );\n}\n\nconst inlines = (node: Node): ReactNode[] => childrenOf(node).map(renderInline);\n\nfunction renderBlock(node: unknown, key: number): ReactNode {\n if (!isNode(node)) return null;\n switch (node.type) {\n case \"paragraph\":\n return <p key={key}>{inlines(node)}</p>;\n case \"heading\": {\n const level = node.level;\n const tag =\n typeof level === \"number\" &&\n Object.prototype.hasOwnProperty.call(HEADINGS, level)\n ? HEADINGS[level]\n : \"p\";\n return createElement(tag, { key }, inlines(node));\n }\n case \"list\": {\n const items = childrenOf(node).map((item, index) =>\n isNode(item) && item.type === \"list-item\" ? (\n <li key={index}>{inlines(item)}</li>\n ) : null\n );\n return node.listType === \"ordered\" ? (\n <ol key={key}>{items}</ol>\n ) : (\n <ul key={key}>{items}</ul>\n );\n }\n default:\n return null;\n }\n}\n\nexport interface RichTextProps {\n /** A rich_text metafield value, e.g. `metafield<RichTextRoot>(product, \"custom.care_guide\")`. */\n value: RichTextRoot | null | undefined;\n}\n\n/**\n * Renders a rich-text metafield as React elements: headings, paragraphs,\n * lists, bold, italic and links. Unknown nodes are skipped. Text is always a\n * text child, so nothing a merchant or shopper typed is ever parsed as\n * markup. Returns bare elements with no wrapper; style them from the parent.\n */\nexport function RichText({ value }: RichTextProps): ReactElement | null {\n if (!isNode(value) || value.type !== \"root\") return null;\n return <>{childrenOf(value).map(renderBlock)}</>;\n}\n"],"mappings":"AAmEkC,SA4EzB,UA5EyB;AAnElC;AAAA,EACE;AAAA,EACA,YAAAA;AAAA,OAGK;AAUP,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AACzB,MAAM,SAAS;AAQR,SAAS,aAAa,KAAmC;AAC9D,MACE,OAAO,QAAQ,YACf,IAAI,WAAW,KACf,IAAI,SAAS,kBACb,iBAAiB,KAAK,GAAG,GACzB;AACA,WAAO;AAAA,EACT;AACA,MAAI,OAAO,KAAK,GAAG,EAAG,QAAO,EAAE,MAAM,KAAK,UAAU,MAAM;AAC1D,MAAI;AACJ,MAAI;AACF,aAAS,IAAI,IAAI,GAAG;AAAA,EACtB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,SAAO,OAAO,aAAa,WAAW,OAAO,aAAa,WACtD,EAAE,MAAM,KAAK,UAAU,KAAK,IAC5B;AACN;AAIA,MAAM,SAAS,CAAC,UACd,OAAO,UAAU,YAAY,UAAU,QAAQ,C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,CAAC,OAAO,IAAI,EAAG,QAAO;AAC1B,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK;AACH,aAAO,oBAAC,OAAa,kBAAQ,IAAI,KAAlB,GAAoB;AAAA,IACrC,KAAK,WAAW;AACd,YAAM,QAAQ,KAAK;AACnB,YAAM,MACJ,OAAO,UAAU,YACjB,OAAO,UAAU,eAAe,KAAK,UAAU,KAAK,IAChD,SAAS,KAAK,IACd;AACN,aAAO,cAAc,KAAK,EAAE,IAAI,GAAG,QAAQ,IAAI,CAAC;AAAA,IAClD;AAAA,IACA,KAAK,QAAQ;AACX,YAAM,QAAQ,WAAW,IAAI,EAAE;AAAA,QAAI,CAAC,MAAM,UACxC,OAAO,IAAI,KAAK,KAAK,SAAS,cAC5B,oBAAC,QAAgB,kBAAQ,IAAI,KAApB,KAAsB,IAC7B;AAAA,MACN;AACA,aAAO,KAAK,aAAa,YACvB,oBAAC,QAAc,mBAAN,GAAY,IAErB,oBAAC,QAAc,mBAAN,GAAY;AAAA,IAEzB;AAAA,IACA;AACE,aAAO;AAAA,EACX;AACF;AAaO,SAAS,SAAS,EAAE,MAAM,GAAuC;AACtE,MAAI,CAAC,OAAO,KAAK,KAAK,MAAM,SAAS,OAAQ,QAAO;AACpD,SAAO,gCAAG,qBAAW,KAAK,EAAE,IAAI,WAAW,GAAE;AAC/C;","names":["Fragment"]}
1
+ {"version":3,"sources":["../../src/metafields/rich-text.tsx"],"sourcesContent":["import {\n createElement,\n Fragment,\n type ReactElement,\n type ReactNode,\n} from \"react\";\nimport type { RichTextRoot } from \"@ecomweb/sdk\";\n\n/**\n * The engine's link rule (spec 5.3), re-checked at render: the tree was\n * validated on write, but a row written before a validation fix, or edited\n * in the database, must still never become a script URL here. At least as\n * strict as the SDK engine. Commas are legal in http(s) URLs; only the\n * mailto pattern refuses them.\n */\nconst MAX_URL_LENGTH = 2048;\n// eslint-disable-next-line no-control-regex -- matching control characters is the point: they are rejected in URLs\nconst UNSAFE_URL_CHARS = /[\\u0000-\\u001f\\u007f-\\u009f\"<>`\\\\]|\\s/;\nconst MAILTO = /^mailto:[^\\s@?&#,]+@[^\\s@?&#,]+$/i;\n\nexport interface RichTextHref {\n href: string;\n /** http(s) links; they get rel=\"noopener noreferrer\". */\n external: boolean;\n}\n\nexport function richTextHref(url: unknown): RichTextHref | null {\n if (\n typeof url !== \"string\" ||\n url.length === 0 ||\n url.length > MAX_URL_LENGTH ||\n UNSAFE_URL_CHARS.test(url)\n ) {\n return null;\n }\n if (MAILTO.test(url)) return { href: url, external: false };\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n return null;\n }\n return parsed.protocol === \"http:\" || parsed.protocol === \"https:\"\n ? { href: url, external: true }\n : null;\n}\n\ntype Node = Record<string, unknown>;\n\nconst isNode = (value: unknown): value is Node =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst childrenOf = (node: Node): unknown[] =>\n Array.isArray(node.children) ? node.children : [];\n\nconst HEADINGS: Record<number, \"h1\" | \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"h6\"> = {\n 1: \"h1\",\n 2: \"h2\",\n 3: \"h3\",\n 4: \"h4\",\n 5: \"h5\",\n 6: \"h6\",\n};\n\n/** Only the listed keys of a node are ever read; nothing is spread into props. */\nfunction renderText(node: Node, key: number): ReactNode {\n if (typeof node.value !== \"string\") return null;\n let out: ReactNode = node.value;\n if (node.italic === true) out = <em>{out}</em>;\n if (node.bold === true) out = <strong>{out}</strong>;\n return <Fragment key={key}>{out}</Fragment>;\n}\n\nfunction renderInline(node: unknown, key: number): ReactNode {\n if (!isNode(node)) return null;\n if (node.type === \"text\") return renderText(node, key);\n if (node.type !== \"link\") return null;\n const text = childrenOf(node).map((child, index) =>\n isNode(child) && child.type === \"text\" ? renderText(child, index) : null\n );\n const link = richTextHref(node.url);\n if (!link) return <Fragment key={key}>{text}</Fragment>;\n const title =\n typeof node.title === \"string\" && node.title !== \"\"\n ? node.title\n : undefined;\n return (\n <a\n key={key}\n href={link.href}\n rel={link.external ? \"noopener noreferrer\" : undefined}\n title={title}\n >\n {text}\n </a>\n );\n}\n\nconst inlines = (node: Node): ReactNode[] => childrenOf(node).map(renderInline);\n\nfunction renderBlock(node: unknown, key: number): ReactNode {\n if (!isNode(node)) return null;\n switch (node.type) {\n case \"paragraph\":\n return <p key={key}>{inlines(node)}</p>;\n case \"heading\": {\n const level = node.level;\n const tag =\n typeof level === \"number\" &&\n Object.prototype.hasOwnProperty.call(HEADINGS, level)\n ? HEADINGS[level]\n : \"p\";\n return createElement(tag, { key }, inlines(node));\n }\n case \"list\": {\n const items = childrenOf(node).map((item, index) =>\n isNode(item) && item.type === \"list-item\" ? (\n <li key={index}>{inlines(item)}</li>\n ) : null\n );\n return node.listType === \"ordered\" ? (\n <ol key={key}>{items}</ol>\n ) : (\n <ul key={key}>{items}</ul>\n );\n }\n default:\n return null;\n }\n}\n\nexport interface RichTextProps {\n /** A rich_text metafield value, e.g. `metafield<RichTextRoot>(product, \"custom.care_guide\")`. */\n value: RichTextRoot | null | undefined;\n}\n\n/**\n * Renders a rich-text metafield as React elements: headings, paragraphs,\n * lists, bold, italic and links. Unknown nodes are skipped. Text is always a\n * text child, so nothing a merchant or shopper typed is ever parsed as\n * markup. Returns bare elements with no wrapper; style them from the parent.\n */\nexport function RichText({ value }: RichTextProps): ReactElement | null {\n if (!isNode(value) || value.type !== \"root\") return null;\n return <>{childrenOf(value).map(renderBlock)}</>;\n}\n"],"mappings":"AAoEkC,SA4EzB,UA5EyB;AApElC;AAAA,EACE;AAAA,EACA,YAAAA;AAAA,OAGK;AAUP,MAAM,iBAAiB;AAEvB,MAAM,mBAAmB;AACzB,MAAM,SAAS;AAQR,SAAS,aAAa,KAAmC;AAC9D,MACE,OAAO,QAAQ,YACf,IAAI,WAAW,KACf,IAAI,SAAS,kBACb,iBAAiB,KAAK,GAAG,GACzB;AACA,WAAO;AAAA,EACT;AACA,MAAI,OAAO,KAAK,GAAG,EAAG,QAAO,EAAE,MAAM,KAAK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ATH = "/domain-not-connected";
47
+ const CUSTOM_DOMAIN_REDIRECT_CACHE = "public, max-age=3600";
47
48
  function externalThemeResponse(req, host, storeRef, externalUrl) {
48
49
  if (!externalUrl) return null;
49
50
  if (req.nextUrl.searchParams.has(THEME_PREVIEW_PARAM) || hasThemePreview(req, authCookiePath(storeRef, true)))
@@ -90,10 +91,19 @@ function storeRefFromPath(pathname) {
90
91
  return match[1];
91
92
  }
92
93
  }
94
+ function redirectDestinationUrl(req, destination, pathPrefix = "") {
95
+ const url = publicNextUrl(req);
96
+ const parsed = new URL(destination, "http://destination.invalid");
97
+ url.pathname = `${pathPrefix}${parsed.pathname}`;
98
+ if (parsed.search) url.search = parsed.search;
99
+ if (parsed.hash) url.hash = parsed.hash;
100
+ return url;
101
+ }
93
102
  function buildRedirectResponse(req, redirect, pathPrefix = "") {
94
- const redirectUrl = publicNextUrl(req);
95
- redirectUrl.pathname = `${pathPrefix}${redirect.destination_path}`;
96
- return NextResponse.redirect(redirectUrl, { status: redirect.redirect_type });
103
+ return NextResponse.redirect(
104
+ redirectDestinationUrl(req, redirect.destination_path, pathPrefix),
105
+ { status: redirect.redirect_type }
106
+ );
97
107
  }
98
108
  async function apexStoreResponse(req, storeRef, platformDomain) {
99
109
  let subdomain = null;
@@ -175,7 +185,9 @@ async function multiTenant(req) {
175
185
  url.hostname = domain;
176
186
  url.protocol = "https:";
177
187
  url.port = "";
178
- return NextResponse.redirect(url, { status: 301 });
188
+ const response2 = NextResponse.redirect(url, { status: 301 });
189
+ response2.headers.set("Cache-Control", CUSTOM_DOMAIN_REDIRECT_CACHE);
190
+ return response2;
179
191
  }
180
192
  if (!pathname.startsWith(multiTenantStorePath(storeRef2))) {
181
193
  const redirect = await lookupRedirect(storeRef2, pathname);
@@ -282,9 +294,10 @@ async function singleStore(req) {
282
294
  try {
283
295
  const redirect = await lookupRedirect(storeRef, pathname);
284
296
  if (redirect) {
285
- const url = publicNextUrl(req);
286
- url.pathname = redirect.destination_path;
287
- return NextResponse.redirect(url, { status: redirect.redirect_type });
297
+ return NextResponse.redirect(
298
+ redirectDestinationUrl(req, redirect.destination_path),
299
+ { status: redirect.redirect_type }
300
+ );
288
301
  }
289
302
  } catch (error) {
290
303
  console.debug("Redirect lookup error:", error);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/middleware/create-storefront-middleware.ts"],"sourcesContent":["import { publicNextUrl } from \"../request/public-url\";\nimport { REQUEST_PATH_HEADER } from \"../request/request-path\";\nimport {\n applyThemePreview,\n hasThemePreview,\n THEME_PREVIEW_PARAM,\n themePreviewCookieName,\n} from \"../theme/preview-cookie\";\nimport {\n externalStorefrontUrl,\n isSameHost,\n} from \"../theme/external-storefront\";\nimport { NextRequest, NextResponse } from \"next/server\";\nimport type { UrlRedirect } from \"@ecomweb/sdk\";\nimport { authCookiePath, writeAuthCookies } from \"../auth/cookies\";\nimport {\n downstreamRequestHeaders,\n refreshIfNearExpiry,\n} from \"../auth/session-refresh\";\nimport type { StorefrontMode } from \"../config/mode\";\nimport { publicConfig } from \"../config/public\";\nimport { lookupRedirect } from \"../redirects/lookup-redirect\";\nimport { multiTenantStorePath } from \"../store-scope\";\nimport { getStoreByHost } from \"../stores/get-store-by-host\";\nimport { STORE_COMING_SOON_REDIRECT_PATH } from \"../stores/store-coming-soon\";\nimport {\n applyStorePreview,\n STORE_PREVIEW_PATH,\n STORE_PREVIEW_TOKEN_HEADER,\n storePreviewCookieName,\n} from \"../stores/store-preview-cookie\";\nimport { getStoreSubdomain } from \"../stores/store-subdomain\";\nimport { recordStoreRequest } from \"../stores/store-traffic\";\nimport {\n PREVIEW_HOST_ROBOTS,\n THEME_PREVIEW_HOST_HEADER,\n} from \"../theme/preview-host\";\n\n/** Served from the app root in both modes; never rewritten or redirected. */\nconst METADATA_FILES = [\n \"/robots.txt\",\n \"/sitemap.xml\",\n \"/favicon.ico\",\n \"/manifest.json\",\n \"/manifest.webmanifest\",\n \"/icon\",\n \"/apple-icon\",\n];\n\n/**\n * Metadata files that follow the store to an external site: crawlers must\n * find the external site's robots.txt and sitemap, not ours.\n */\nconst EXTERNAL_METADATA_FILES = [\"/robots.txt\", \"/sitemap.xml\"];\n\n/** Rewrite target when a store's external URL still points at Ecomweb. */\nconst DOMAIN_NOT_CONNECTED_PATH = \"/domain-not-connected\";\n\n/**\n * The response for a store whose live theme is external, or null to serve\n * the request here (theme anatomy spec, \"Storefront\"):\n * - 302 to the external URL with the same path and query (307 for non-GET,\n * so the method survives); never 301, the merchant may switch back.\n * - never while previewing (`?preview_theme=` or the preview cookie): a\n * preview of an Ecomweb theme must render here.\n * - the external URL is this very host (the domain still points at Ecomweb):\n * a \"domain not connected\" page rather than a redirect loop (robots.txt\n * and the sitemap are still served here).\n * - no usable URL: null (fail open).\n */\nfunction externalThemeResponse(\n req: NextRequest,\n host: string,\n storeRef: string,\n externalUrl: string | null | undefined\n): NextResponse | null {\n if (!externalUrl) return null;\n if (\n req.nextUrl.searchParams.has(THEME_PREVIEW_PARAM) ||\n hasThemePreview(req, authCookiePath(storeRef, true))\n )\n return null;\n\n const pathname = req.nextUrl.pathname;\n const prefix = multiTenantStorePath(storeRef);\n const logicalPath =\n pathname === prefix || pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length) || \"/\"\n : pathname;\n const target = externalStorefrontUrl(\n externalUrl,\n logicalPath,\n req.nextUrl.search\n );\n if (!target) return null;\n\n if (isSameHost(host, target.hostname)) {\n // Our own robots.txt and sitemap still describe this host correctly.\n if (EXTERNAL_METADATA_FILES.includes(pathname)) return null;\n const url = req.nextUrl.clone();\n url.pathname = DOMAIN_NOT_CONNECTED_PATH;\n url.search = \"\";\n const res = NextResponse.rewrite(url, withoutInternalHeaders(req));\n res.headers.set(\"x-robots-tag\", \"noindex\");\n return res;\n }\n\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\n}\n\n/**\n * The init for a response that lets the request through without the full\n * downstream headers (metadata files, the \"domain not connected\" and apex\n * 404 rewrites): the client's headers minus the middleware's internal ones.\n * With it, every request the matcher covers reaches the app with no client\n * copy of them, so a server-side reader can trust them there.\n */\nfunction withoutInternalHeaders(req: NextRequest): {\n request: { headers: Headers };\n} {\n const headers = new Headers(req.headers);\n headers.delete(THEME_PREVIEW_HOST_HEADER);\n headers.delete(STORE_PREVIEW_TOKEN_HEADER);\n return { request: { headers } };\n}\n\n/** True while the store preview cookie at `cookiePath` holds a token. */\nfunction hasStorePreview(req: NextRequest, cookiePath: string): boolean {\n return !!req.cookies.get(storePreviewCookieName(cookiePath))?.value;\n}\n\n/**\n * The preview token for the host lookup on a store host: the store preview\n * cookie, else the theme preview cookie (`?preview_theme=` on the store's own\n * host), both at `/`. Read from the cookies only, never through\n * `storePreviewTokenFrom`: that trusts `STORE_PREVIEW_TOKEN_HEADER`, and on\n * the middleware's incoming request that header is whatever the client sent.\n */\nfunction hostLookupPreviewToken(req: NextRequest): string | null {\n return (\n req.cookies.get(storePreviewCookieName(\"/\"))?.value ||\n req.cookies.get(themePreviewCookieName(\"/\"))?.value ||\n null\n );\n}\n\n/**\n * The store a request belongs to, as far as the *path* can say.\n *\n * On localhost and on the platform apex there is no host→store mapping, but\n * the path is `/store/<storeRef>/…` — which is also how the auth cookies are\n * named. `params.storeRef` arrives URL-decoded downstream, so decode here too.\n */\nfunction storeRefFromPath(pathname: string): string | null {\n const match = /^\\/store\\/([^/]+)/.exec(pathname);\n if (!match) return null;\n try {\n return decodeURIComponent(match[1]) || null;\n } catch {\n return match[1];\n }\n}\n\n/**\n * Turns a stored redirect row into the 301/302 response for it.\n *\n * `pathPrefix` re-adds the `/store/<ref>` segment that direct path-based\n * access needs on the destination but a host-mapped request (whose\n * `destination_path` is already store-root-relative) does not.\n */\nfunction buildRedirectResponse(\n req: NextRequest,\n redirect: UrlRedirect,\n pathPrefix = \"\"\n): NextResponse {\n const redirectUrl = publicNextUrl(req);\n redirectUrl.pathname = `${pathPrefix}${redirect.destination_path}`;\n return NextResponse.redirect(redirectUrl, { status: redirect.redirect_type });\n}\n\n/**\n * `/store/<ref>/…` on the platform apex: never served here, sent to the\n * store's own subdomain instead.\n *\n * On the apex every store shares one origin, and a merchant's embedded\n * scripts run there. A cookie's Path is no boundary between pages of one\n * origin: store A's script could fetch `/store/B/api/…` with B's shopper\n * cookies attached, or frame `/store/B` and read it. Each store's subdomain\n * is its own origin. Localhost keeps path-based access (it is not the apex).\n *\n * 302 (307 for non-GET), not 301: the merchant may change the subdomain.\n * The subdomain then sends shoppers on to a custom domain when there is one.\n * No store, no subdomain, or the API unreachable: the 404 page.\n */\nasync function apexStoreResponse(\n req: NextRequest,\n storeRef: string,\n platformDomain: string\n): Promise<NextResponse> {\n let subdomain: string | null = null;\n try {\n subdomain = await getStoreSubdomain(storeRef);\n } catch (error) {\n console.error(\"Store lookup failed for apex path:\", storeRef, error);\n }\n\n if (!subdomain) {\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n url.search = \"\";\n return NextResponse.rewrite(url, withoutInternalHeaders(req));\n }\n\n const prefix = multiTenantStorePath(storeRef);\n const pathname = req.nextUrl.pathname;\n const target = publicNextUrl(req);\n target.hostname = `${subdomain}.${platformDomain}`;\n target.port = \"\";\n target.pathname = pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length)\n : \"/\";\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\n}\n\nasync function multiTenant(req: NextRequest): Promise<NextResponse> {\n const host = req.headers.get(\"host\") || \"\";\n const pathname = req.nextUrl.pathname;\n\n // Skip metadata files - these are served from app root level - except the\n // ones that follow an external theme (checked once the store is known).\n const isMetadataFile = METADATA_FILES.includes(pathname);\n if (isMetadataFile && !EXTERNAL_METADATA_FILES.includes(pathname)) {\n return NextResponse.next(withoutInternalHeaders(req));\n }\n\n // Store-by-host resolution and redirect lookup genuinely do not apply on\n // localhost or on the platform apex — but the token refresh below does, so\n // these only skip the host-specific work now, not the whole middleware.\n const platformDomain = publicConfig().platformDomainSuffix ?? \"ecomsite.app\";\n const hostIdentifiesStore =\n !host.includes(\"localhost\") &&\n !host.includes(\"127.0.0.1\") &&\n host !== platformDomain &&\n host !== `www.${platformDomain}`;\n\n const isPlatformApex =\n host === platformDomain || host === `www.${platformDomain}`;\n if (isPlatformApex) {\n const apexStoreRef = storeRefFromPath(pathname);\n if (apexStoreRef)\n return apexStoreResponse(req, apexStoreRef, platformDomain);\n }\n\n // The dashboard's preview link on the store's own host. Before the lookup:\n // a coming soon store's host resolves to nothing until the cookie is set.\n if (hostIdentifiesStore && pathname === STORE_PREVIEW_PATH) {\n return applyStorePreview(req, \"/\", \"/\");\n }\n\n let hostStoreRef: string | null = null;\n let hostResolved = false;\n\n let hostStoreSuspended = false;\n let hostStoreComingSoon = false;\n // A theme's preview host (theme preview hosts): the theme's slug.\n let previewSlug: string | null = null;\n // A preview host's store preview token for a coming soon store (lookup).\n let storePreviewToken: string | null = null;\n\n if (isMetadataFile && !hostIdentifiesStore)\n return NextResponse.next(withoutInternalHeaders(req));\n\n if (hostIdentifiesStore) {\n try {\n // Without a token, the plain call: its answer is cached for the host.\n const previewToken = hostLookupPreviewToken(req);\n const lookup = previewToken\n ? await getStoreByHost(host, { previewToken })\n : await getStoreByHost(host);\n const { storeRef, domain, isSubDomain, suspended, externalUrl } = lookup;\n hostResolved = true;\n hostStoreRef = storeRef || null;\n hostStoreSuspended = suspended;\n hostStoreComingSoon = !storeRef && !!lookup.comingSoon;\n previewSlug = storeRef ? lookup.previewSlug : null;\n storePreviewToken = previewSlug ? lookup.storePreviewToken || null : null;\n\n // Nothing on a preview host is for search engines.\n if (previewSlug && isMetadataFile) {\n return pathname === \"/robots.txt\"\n ? new NextResponse(PREVIEW_HOST_ROBOTS, {\n headers: { \"content-type\": \"text/plain\" },\n })\n : new NextResponse(null, { status: 404 });\n }\n\n if (storeRef) {\n // An external theme is live: the shopper belongs on that site. Before\n // the subdomain → custom domain redirect, which would only add a hop.\n const external = externalThemeResponse(\n req,\n host,\n storeRef,\n externalUrl\n );\n if (external) return external;\n }\n\n if (isMetadataFile) return NextResponse.next(withoutInternalHeaders(req));\n\n if (storeRef) {\n // If accessing via subdomain but custom domain exists, redirect to\n // custom domain. Not a preview host: it is the theme's, not the store's.\n if (isSubDomain && domain && domain !== host && !previewSlug) {\n const url = publicNextUrl(req);\n url.hostname = domain;\n url.protocol = \"https:\";\n url.port = \"\"; // Remove port for custom domain\n return NextResponse.redirect(url, { status: 301 });\n }\n\n // Check for URL redirects BEFORE rewriting\n // Skip redirect check if path already starts with /store/ (internal rewrite)\n if (!pathname.startsWith(multiTenantStorePath(storeRef))) {\n const redirect = await lookupRedirect(storeRef, pathname);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect);\n }\n }\n }\n } catch (error) {\n console.debug(\"Middleware error:\", error);\n if (isMetadataFile) return NextResponse.next(withoutInternalHeaders(req));\n // Fall through: no host mapping, but the refresh below still applies.\n hostResolved = false;\n hostStoreRef = null;\n }\n }\n\n // The host names the store on custom domains and subdomains; everywhere else\n // (localhost, the apex, direct /store/<ref>/… access) the path does.\n const storeRef = hostStoreRef ?? storeRefFromPath(pathname);\n if (storeRef) recordStoreRequest(storeRef);\n\n // A dashboard preview link: store its token in a cookie, then redirect to\n // the clean URL (themes spec §6.1). A coming soon store's own host resolves\n // no store until a preview token comes with the lookup, so there the link\n // becomes the host's `/` cookie, the lookup's fallback token\n // (hostLookupPreviewToken).\n if (hostStoreComingSoon) {\n const preview = applyThemePreview(req, \"/\");\n if (preview) return preview;\n }\n const cookiePath = storeRef ? authCookiePath(storeRef, !!hostStoreRef) : null;\n if (storeRef && cookiePath) {\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\n // The store preview link on the shared path-based host (localhost; the\n // apex already sent /store/<ref>/… to the store's subdomain above). Not\n // on a store host, even one that resolved no store: it takes `/preview`.\n if (\n !hostIdentifiesStore &&\n pathname === multiTenantStorePath(storeRef, STORE_PREVIEW_PATH)\n ) {\n return applyStorePreview(req, cookiePath, multiTenantStorePath(storeRef));\n }\n }\n\n // Direct /store/<ref>/… access never goes through the host-mapped branch\n // above, so it gets no redirect check there. `redirect_source_path` rows\n // are store-root-relative (e.g. \"/old\"), the same shape a host-mapped\n // request already checks against — strip the /store/<ref> prefix to\n // recover that shape, and re-add it on the destination.\n if (!hostStoreRef && storeRef) {\n const prefix = multiTenantStorePath(storeRef);\n if (pathname === prefix || pathname.startsWith(`${prefix}/`)) {\n try {\n const logicalPath = pathname.slice(prefix.length) || \"/\";\n const redirect = await lookupRedirect(storeRef, logicalPath);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect, prefix);\n }\n } catch (error) {\n // Fail open: lookupRedirect already catches internally and never\n // rejects, but this belongs to the caller's contract, not the\n // callee's — a future regression there must not take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n }\n }\n\n const rotated =\n storeRef && cookiePath\n ? await refreshIfNearExpiry(req, storeRef, cookiePath)\n : null;\n const downstream = downstreamRequestHeaders(\n req,\n !!hostStoreRef,\n storeRef,\n rotated\n );\n downstream.set(\n REQUEST_PATH_HEADER,\n `${req.nextUrl.pathname}${req.nextUrl.search}`\n );\n if (previewSlug) downstream.set(THEME_PREVIEW_HOST_HEADER, previewSlug);\n // Set after downstreamRequestHeaders deleted any copy the client sent. On\n // every request to the preview host, the backend proxy's included.\n if (previewSlug && storePreviewToken)\n downstream.set(STORE_PREVIEW_TOKEN_HEADER, storePreviewToken);\n const init = { request: { headers: downstream } };\n\n let response: NextResponse;\n\n if (hostStoreRef) {\n const url = req.nextUrl.clone();\n // Only rewrite if the path doesn't already start with /store/\n if (!url.pathname.startsWith(multiTenantStorePath(hostStoreRef))) {\n url.pathname = multiTenantStorePath(hostStoreRef, url.pathname);\n }\n\n response = NextResponse.rewrite(url, init);\n // Add headers to indicate this is a domain-mapped store\n response.headers.set(\"x-store-domain\", \"true\");\n response.headers.set(\"x-store-ref\", hostStoreRef);\n } else if (hostStoreSuspended) {\n // A platform admin suspended this store. The 403 the backend returned\n // for a domain lookup carries no ref/id to route on (see\n // getStoreByHost), so this can't rewrite to `/store/<ref>` the way the\n // resolved-store branch above does — it goes to a platform-level page\n // instead of the not-found path below.\n const url = req.nextUrl.clone();\n url.pathname = \"/store-suspended\";\n response = NextResponse.rewrite(url, init);\n } else if (hostStoreComingSoon) {\n // The merchant has not opened the store, and the request carried no\n // valid preview token (an expired one lands here too). Like the\n // suspended branch, the 403 carries no ref, so a platform-level page.\n // Known limitation: on the shared path-based host (localhost) nothing\n // routes here; a store that turns coming soon mid-session sends the\n // browser to /coming-soon, which resolves no store there and 404s, as\n // the apex's /store/<ref> already does for these stores.\n const url = req.nextUrl.clone();\n url.pathname = STORE_COMING_SOON_REDIRECT_PATH;\n response = NextResponse.rewrite(url, init);\n response.headers.set(\"x-robots-tag\", \"noindex\");\n } else if (hostResolved) {\n // The host looked like a store host but resolved to nothing: 404.\n console.debug(\"Store not found for host:\", host);\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n response = NextResponse.rewrite(url, init);\n } else {\n response = NextResponse.next(init);\n }\n\n // A store preview cookie lives at `/` on a store host, even when the host\n // resolved no store (coming soon), else at the store's path.\n const storePreviewPath = hostIdentifiesStore ? \"/\" : cookiePath;\n if (\n previewSlug ||\n (cookiePath && hasThemePreview(req, cookiePath)) ||\n (storePreviewPath && hasStorePreview(req, storePreviewPath))\n ) {\n response.headers.set(\"x-robots-tag\", \"noindex\");\n }\n\n if (rotated && storeRef && cookiePath) {\n // Same path the auth route handler writes with, from the same signal.\n writeAuthCookies(response, storeRef, rotated, cookiePath);\n }\n\n return response;\n}\n\n/**\n * Single-store middleware: the store is fixed by ECOMWEB_STORE_REF, so there\n * is no host lookup and no rewrite. It applies the store's URL redirects and\n * refreshes a near-expiry session. Requests are stamped host-mapped, so auth\n * cookies use Path=/ (see auth/cookies.ts).\n */\nasync function singleStore(req: NextRequest): Promise<NextResponse> {\n const pathname = req.nextUrl.pathname;\n if (METADATA_FILES.includes(pathname))\n return NextResponse.next(withoutInternalHeaders(req));\n\n const storeRef = publicConfig().storeRef as string;\n\n const cookiePath = authCookiePath(storeRef, true);\n if (pathname === STORE_PREVIEW_PATH)\n return applyStorePreview(req, cookiePath, \"/\");\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\n\n try {\n const redirect = await lookupRedirect(storeRef, pathname);\n if (redirect) {\n const url = publicNextUrl(req);\n url.pathname = redirect.destination_path;\n return NextResponse.redirect(url, { status: redirect.redirect_type });\n }\n } catch (error) {\n // Fail open: a redirect lookup must never take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n\n const rotated = await refreshIfNearExpiry(req, storeRef, cookiePath);\n const response = NextResponse.next({\n request: {\n headers: downstreamRequestHeaders(req, true, storeRef, rotated),\n },\n });\n\n if (hasThemePreview(req, cookiePath) || hasStorePreview(req, cookiePath))\n response.headers.set(\"x-robots-tag\", \"noindex\");\n if (rotated) {\n writeAuthCookies(response, storeRef, rotated, cookiePath);\n }\n return response;\n}\n\n/**\n * The storefront's proxy.ts (Next middleware).\n * - multi: host → store lookup, rewrites to /store/<ref>, suspended and\n * unknown stores, coming soon stores (rewritten to /coming-soon, noindex),\n * redirects, session refresh. The store preview link (`/preview?token=`\n * on a store host, `/store/<ref>/preview?token=` on localhost) becomes a\n * cookie before the lookup, and the lookup carries that token.\n * - single: the `/preview?token=` link, redirects and session refresh.\n * Without `mode`, the configured mode (ECOMWEB_MODE) decides per request.\n */\nexport function createStorefrontMiddleware(\n opts: { mode?: StorefrontMode } = {}\n): (req: NextRequest) => Promise<NextResponse> {\n return req =>\n (opts.mode ?? publicConfig().mode) === \"multi\"\n ? multiTenant(req)\n : singleStore(req);\n}\n\n/**\n * Next reads `config` from proxy.ts statically, so an app re-exports this as\n * `export const config = { matcher: [...] }` with the same literal.\n */\nexport const storefrontMiddlewareConfig = {\n matcher: [\n /*\n * Match all request paths except for the ones starting with:\n * - api (API routes)\n * - _next/static (static files)\n * - _next/image (image optimization files)\n * - _vercel (Vercel Analytics; off Vercel, a store page render per hit)\n * - favicon.ico (favicon file)\n */\n \"/((?!api|_next/static|_next/image|_vercel|favicon.ico).*)\",\n ],\n};\n"],"mappings":"AAAA,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAsB,oBAAoB;AAE1C,SAAS,gBAAgB,wBAAwB;AACjD;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,4BAA4B;AACrC,SAAS,sBAAsB;AAC/B,SAAS,uCAAuC;AAChD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP,MAAM,iBAAiB;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAMA,MAAM,0BAA0B,CAAC,eAAe,cAAc;AAG9D,MAAM,4BAA4B;AAclC,SAAS,sBACP,KACA,MACA,UACA,aACqB;AACrB,MAAI,CAAC,YAAa,QAAO;AACzB,MACE,IAAI,QAAQ,aAAa,IAAI,mBAAmB,KAChD,gBAAgB,KAAK,eAAe,UAAU,IAAI,CAAC;AAEnD,WAAO;AAET,QAAM,WAAW,IAAI,QAAQ;AAC7B,QAAM,SAAS,qBAAqB,QAAQ;AAC5C,QAAM,cACJ,aAAa,UAAU,SAAS,WAAW,GAAG,MAAM,GAAG,IACnD,SAAS,MAAM,OAAO,MAAM,KAAK,MACjC;AACN,QAAM,SAAS;AAAA,IACb;AAAA,IACA;AAAA,IACA,IAAI,QAAQ;AAAA,EACd;AACA,MAAI,CAAC,OAAQ,QAAO;AAEpB,MAAI,WAAW,MAAM,OAAO,QAAQ,GAAG;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S,2BACd,OAAkC,CAAC,GACU;AAC7C,SAAO,UACJ,KAAK,QAAQ,aAAa,EAAE,UAAU,UACnC,YAAY,GAAG,IACf,YAAY,GAAG;AACvB;AAMO,MAAM,6BAA6B;AAAA,EACxC,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASP;AAAA,EACF;AACF;","names":["storeRef"]}
1
+ {"version":3,"sources":["../../src/middleware/create-storefront-middleware.ts"],"sourcesContent":["import { publicNextUrl } from \"../request/public-url\";\nimport { REQUEST_PATH_HEADER } from \"../request/request-path\";\nimport {\n applyThemePreview,\n hasThemePreview,\n THEME_PREVIEW_PARAM,\n themePreviewCookieName,\n} from \"../theme/preview-cookie\";\nimport {\n externalStorefrontUrl,\n isSameHost,\n} from \"../theme/external-storefront\";\nimport { NextRequest, NextResponse } from \"next/server\";\nimport type { UrlRedirect } from \"@ecomweb/sdk\";\nimport { authCookiePath, writeAuthCookies } from \"../auth/cookies\";\nimport {\n downstreamRequestHeaders,\n refreshIfNearExpiry,\n} from \"../auth/session-refresh\";\nimport type { StorefrontMode } from \"../config/mode\";\nimport { publicConfig } from \"../config/public\";\nimport { lookupRedirect } from \"../redirects/lookup-redirect\";\nimport { multiTenantStorePath } from \"../store-scope\";\nimport { getStoreByHost } from \"../stores/get-store-by-host\";\nimport { STORE_COMING_SOON_REDIRECT_PATH } from \"../stores/store-coming-soon\";\nimport {\n applyStorePreview,\n STORE_PREVIEW_PATH,\n STORE_PREVIEW_TOKEN_HEADER,\n storePreviewCookieName,\n} from \"../stores/store-preview-cookie\";\nimport { getStoreSubdomain } from \"../stores/store-subdomain\";\nimport { recordStoreRequest } from \"../stores/store-traffic\";\nimport {\n PREVIEW_HOST_ROBOTS,\n THEME_PREVIEW_HOST_HEADER,\n} from \"../theme/preview-host\";\n\n/** Served from the app root in both modes; never rewritten or redirected. */\nconst METADATA_FILES = [\n \"/robots.txt\",\n \"/sitemap.xml\",\n \"/favicon.ico\",\n \"/manifest.json\",\n \"/manifest.webmanifest\",\n \"/icon\",\n \"/apple-icon\",\n];\n\n/**\n * Metadata files that follow the store to an external site: crawlers must\n * find the external site's robots.txt and sitemap, not ours.\n */\nconst EXTERNAL_METADATA_FILES = [\"/robots.txt\", \"/sitemap.xml\"];\n\n/** Rewrite target when a store's external URL still points at Ecomweb. */\nconst DOMAIN_NOT_CONNECTED_PATH = \"/domain-not-connected\";\n\n/**\n * Cache-Control on the subdomain → custom domain 301. An hour keeps the 301\n * for search engines and caps how long browsers follow it after the merchant\n * removes the domain.\n */\nconst CUSTOM_DOMAIN_REDIRECT_CACHE = \"public, max-age=3600\";\n\n/**\n * The response for a store whose live theme is external, or null to serve\n * the request here (theme anatomy spec, \"Storefront\"):\n * - 302 to the external URL with the same path and query (307 for non-GET,\n * so the method survives); never 301, the merchant may switch back.\n * - never while previewing (`?preview_theme=` or the preview cookie): a\n * preview of an Ecomweb theme must render here.\n * - the external URL is this very host (the domain still points at Ecomweb):\n * a \"domain not connected\" page rather than a redirect loop (robots.txt\n * and the sitemap are still served here).\n * - no usable URL: null (fail open).\n */\nfunction externalThemeResponse(\n req: NextRequest,\n host: string,\n storeRef: string,\n externalUrl: string | null | undefined\n): NextResponse | null {\n if (!externalUrl) return null;\n if (\n req.nextUrl.searchParams.has(THEME_PREVIEW_PARAM) ||\n hasThemePreview(req, authCookiePath(storeRef, true))\n )\n return null;\n\n const pathname = req.nextUrl.pathname;\n const prefix = multiTenantStorePath(storeRef);\n const logicalPath =\n pathname === prefix || pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length) || \"/\"\n : pathname;\n const target = externalStorefrontUrl(\n externalUrl,\n logicalPath,\n req.nextUrl.search\n );\n if (!target) return null;\n\n if (isSameHost(host, target.hostname)) {\n // Our own robots.txt and sitemap still describe this host correctly.\n if (EXTERNAL_METADATA_FILES.includes(pathname)) return null;\n const url = req.nextUrl.clone();\n url.pathname = DOMAIN_NOT_CONNECTED_PATH;\n url.search = \"\";\n const res = NextResponse.rewrite(url, withoutInternalHeaders(req));\n res.headers.set(\"x-robots-tag\", \"noindex\");\n return res;\n }\n\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\n}\n\n/**\n * The init for a response that lets the request through without the full\n * downstream headers (metadata files, the \"domain not connected\" and apex\n * 404 rewrites): the client's headers minus the middleware's internal ones.\n * With it, every request the matcher covers reaches the app with no client\n * copy of them, so a server-side reader can trust them there.\n */\nfunction withoutInternalHeaders(req: NextRequest): {\n request: { headers: Headers };\n} {\n const headers = new Headers(req.headers);\n headers.delete(THEME_PREVIEW_HOST_HEADER);\n headers.delete(STORE_PREVIEW_TOKEN_HEADER);\n return { request: { headers } };\n}\n\n/** True while the store preview cookie at `cookiePath` holds a token. */\nfunction hasStorePreview(req: NextRequest, cookiePath: string): boolean {\n return !!req.cookies.get(storePreviewCookieName(cookiePath))?.value;\n}\n\n/**\n * The preview token for the host lookup on a store host: the store preview\n * cookie, else the theme preview cookie (`?preview_theme=` on the store's own\n * host), both at `/`. Read from the cookies only, never through\n * `storePreviewTokenFrom`: that trusts `STORE_PREVIEW_TOKEN_HEADER`, and on\n * the middleware's incoming request that header is whatever the client sent.\n */\nfunction hostLookupPreviewToken(req: NextRequest): string | null {\n return (\n req.cookies.get(storePreviewCookieName(\"/\"))?.value ||\n req.cookies.get(themePreviewCookieName(\"/\"))?.value ||\n null\n );\n}\n\n/**\n * The store a request belongs to, as far as the *path* can say.\n *\n * On localhost and on the platform apex there is no host→store mapping, but\n * the path is `/store/<storeRef>/…` — which is also how the auth cookies are\n * named. `params.storeRef` arrives URL-decoded downstream, so decode here too.\n */\nfunction storeRefFromPath(pathname: string): string | null {\n const match = /^\\/store\\/([^/]+)/.exec(pathname);\n if (!match) return null;\n try {\n return decodeURIComponent(match[1]) || null;\n } catch {\n return match[1];\n }\n}\n\n/**\n * Where a stored redirect sends this request, on this request's own host.\n *\n * The destination is parsed as a URL rather than assigned to `pathname`,\n * which would percent-encode its `?` and lose the query. A destination with\n * a query (or fragment) keeps its own; one without carries the request's\n * query over, as before. Only the destination's path, query and fragment are\n * used, so the redirect never leaves the store's host.\n */\nfunction redirectDestinationUrl(\n req: NextRequest,\n destination: string,\n pathPrefix = \"\"\n) {\n const url = publicNextUrl(req);\n const parsed = new URL(destination, \"http://destination.invalid\");\n url.pathname = `${pathPrefix}${parsed.pathname}`;\n if (parsed.search) url.search = parsed.search;\n if (parsed.hash) url.hash = parsed.hash;\n return url;\n}\n\n/**\n * Turns a stored redirect row into the 301/302 response for it.\n *\n * `pathPrefix` re-adds the `/store/<ref>` segment that direct path-based\n * access needs on the destination but a host-mapped request (whose\n * `destination_path` is already store-root-relative) does not.\n */\nfunction buildRedirectResponse(\n req: NextRequest,\n redirect: UrlRedirect,\n pathPrefix = \"\"\n): NextResponse {\n return NextResponse.redirect(\n redirectDestinationUrl(req, redirect.destination_path, pathPrefix),\n { status: redirect.redirect_type }\n );\n}\n\n/**\n * `/store/<ref>/…` on the platform apex: never served here, sent to the\n * store's own subdomain instead.\n *\n * On the apex every store shares one origin, and a merchant's embedded\n * scripts run there. A cookie's Path is no boundary between pages of one\n * origin: store A's script could fetch `/store/B/api/…` with B's shopper\n * cookies attached, or frame `/store/B` and read it. Each store's subdomain\n * is its own origin. Localhost keeps path-based access (it is not the apex).\n *\n * 302 (307 for non-GET), not 301: the merchant may change the subdomain.\n * The subdomain then sends shoppers on to a custom domain when there is one.\n * No store, no subdomain, or the API unreachable: the 404 page.\n */\nasync function apexStoreResponse(\n req: NextRequest,\n storeRef: string,\n platformDomain: string\n): Promise<NextResponse> {\n let subdomain: string | null = null;\n try {\n subdomain = await getStoreSubdomain(storeRef);\n } catch (error) {\n console.error(\"Store lookup failed for apex path:\", storeRef, error);\n }\n\n if (!subdomain) {\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n url.search = \"\";\n return NextResponse.rewrite(url, withoutInternalHeaders(req));\n }\n\n const prefix = multiTenantStorePath(storeRef);\n const pathname = req.nextUrl.pathname;\n const target = publicNextUrl(req);\n target.hostname = `${subdomain}.${platformDomain}`;\n target.port = \"\";\n target.pathname = pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length)\n : \"/\";\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\n}\n\nasync function multiTenant(req: NextRequest): Promise<NextResponse> {\n const host = req.headers.get(\"host\") || \"\";\n const pathname = req.nextUrl.pathname;\n\n // Skip metadata files - these are served from app root level - except the\n // ones that follow an external theme (checked once the store is known).\n const isMetadataFile = METADATA_FILES.includes(pathname);\n if (isMetadataFile && !EXTERNAL_METADATA_FILES.includes(pathname)) {\n return NextResponse.next(withoutInternalHeaders(req));\n }\n\n // Store-by-host resolution and redirect lookup genuinely do not apply on\n // localhost or on the platform apex — but the token refresh below does, so\n // these only skip the host-specific work now, not the whole middleware.\n const platformDomain = publicConfig().platformDomainSuffix ?? \"ecomsite.app\";\n const hostIdentifiesStore =\n !host.includes(\"localhost\") &&\n !host.includes(\"127.0.0.1\") &&\n host !== platformDomain &&\n host !== `www.${platformDomain}`;\n\n const isPlatformApex =\n host === platformDomain || host === `www.${platformDomain}`;\n if (isPlatformApex) {\n const apexStoreRef = storeRefFromPath(pathname);\n if (apexStoreRef)\n return apexStoreResponse(req, apexStoreRef, platformDomain);\n }\n\n // The dashboard's preview link on the store's own host. Before the lookup:\n // a coming soon store's host resolves to nothing until the cookie is set.\n if (hostIdentifiesStore && pathname === STORE_PREVIEW_PATH) {\n return applyStorePreview(req, \"/\", \"/\");\n }\n\n let hostStoreRef: string | null = null;\n let hostResolved = false;\n\n let hostStoreSuspended = false;\n let hostStoreComingSoon = false;\n // A theme's preview host (theme preview hosts): the theme's slug.\n let previewSlug: string | null = null;\n // A preview host's store preview token for a coming soon store (lookup).\n let storePreviewToken: string | null = null;\n\n if (isMetadataFile && !hostIdentifiesStore)\n return NextResponse.next(withoutInternalHeaders(req));\n\n if (hostIdentifiesStore) {\n try {\n // Without a token, the plain call: its answer is cached for the host.\n const previewToken = hostLookupPreviewToken(req);\n const lookup = previewToken\n ? await getStoreByHost(host, { previewToken })\n : await getStoreByHost(host);\n const { storeRef, domain, isSubDomain, suspended, externalUrl } = lookup;\n hostResolved = true;\n hostStoreRef = storeRef || null;\n hostStoreSuspended = suspended;\n hostStoreComingSoon = !storeRef && !!lookup.comingSoon;\n previewSlug = storeRef ? lookup.previewSlug : null;\n storePreviewToken = previewSlug ? lookup.storePreviewToken || null : null;\n\n // Nothing on a preview host is for search engines.\n if (previewSlug && isMetadataFile) {\n return pathname === \"/robots.txt\"\n ? new NextResponse(PREVIEW_HOST_ROBOTS, {\n headers: { \"content-type\": \"text/plain\" },\n })\n : new NextResponse(null, { status: 404 });\n }\n\n if (storeRef) {\n // An external theme is live: the shopper belongs on that site. Before\n // the subdomain → custom domain redirect, which would only add a hop.\n const external = externalThemeResponse(\n req,\n host,\n storeRef,\n externalUrl\n );\n if (external) return external;\n }\n\n if (isMetadataFile) return NextResponse.next(withoutInternalHeaders(req));\n\n if (storeRef) {\n // If accessing via subdomain but custom domain exists, redirect to\n // custom domain. Not a preview host: it is the theme's, not the store's.\n if (isSubDomain && domain && domain !== host && !previewSlug) {\n const url = publicNextUrl(req);\n url.hostname = domain;\n url.protocol = \"https:\";\n url.port = \"\"; // Remove port for custom domain\n const response = NextResponse.redirect(url, { status: 301 });\n // Browsers keep an uncached 301 forever: if the merchant removes a\n // broken domain, shoppers would never come back to the subdomain.\n response.headers.set(\"Cache-Control\", CUSTOM_DOMAIN_REDIRECT_CACHE);\n return response;\n }\n\n // Check for URL redirects BEFORE rewriting\n // Skip redirect check if path already starts with /store/ (internal rewrite)\n if (!pathname.startsWith(multiTenantStorePath(storeRef))) {\n const redirect = await lookupRedirect(storeRef, pathname);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect);\n }\n }\n }\n } catch (error) {\n console.debug(\"Middleware error:\", error);\n if (isMetadataFile) return NextResponse.next(withoutInternalHeaders(req));\n // Fall through: no host mapping, but the refresh below still applies.\n hostResolved = false;\n hostStoreRef = null;\n }\n }\n\n // The host names the store on custom domains and subdomains; everywhere else\n // (localhost, the apex, direct /store/<ref>/… access) the path does.\n const storeRef = hostStoreRef ?? storeRefFromPath(pathname);\n if (storeRef) recordStoreRequest(storeRef);\n\n // A dashboard preview link: store its token in a cookie, then redirect to\n // the clean URL (themes spec §6.1). A coming soon store's own host resolves\n // no store until a preview token comes with the lookup, so there the link\n // becomes the host's `/` cookie, the lookup's fallback token\n // (hostLookupPreviewToken).\n if (hostStoreComingSoon) {\n const preview = applyThemePreview(req, \"/\");\n if (preview) return preview;\n }\n const cookiePath = storeRef ? authCookiePath(storeRef, !!hostStoreRef) : null;\n if (storeRef && cookiePath) {\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\n // The store preview link on the shared path-based host (localhost; the\n // apex already sent /store/<ref>/… to the store's subdomain above). Not\n // on a store host, even one that resolved no store: it takes `/preview`.\n if (\n !hostIdentifiesStore &&\n pathname === multiTenantStorePath(storeRef, STORE_PREVIEW_PATH)\n ) {\n return applyStorePreview(req, cookiePath, multiTenantStorePath(storeRef));\n }\n }\n\n // Direct /store/<ref>/… access never goes through the host-mapped branch\n // above, so it gets no redirect check there. `redirect_source_path` rows\n // are store-root-relative (e.g. \"/old\"), the same shape a host-mapped\n // request already checks against — strip the /store/<ref> prefix to\n // recover that shape, and re-add it on the destination.\n if (!hostStoreRef && storeRef) {\n const prefix = multiTenantStorePath(storeRef);\n if (pathname === prefix || pathname.startsWith(`${prefix}/`)) {\n try {\n const logicalPath = pathname.slice(prefix.length) || \"/\";\n const redirect = await lookupRedirect(storeRef, logicalPath);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect, prefix);\n }\n } catch (error) {\n // Fail open: lookupRedirect already catches internally and never\n // rejects, but this belongs to the caller's contract, not the\n // callee's — a future regression there must not take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n }\n }\n\n const rotated =\n storeRef && cookiePath\n ? await refreshIfNearExpiry(req, storeRef, cookiePath)\n : null;\n const downstream = downstreamRequestHeaders(\n req,\n !!hostStoreRef,\n storeRef,\n rotated\n );\n downstream.set(\n REQUEST_PATH_HEADER,\n `${req.nextUrl.pathname}${req.nextUrl.search}`\n );\n if (previewSlug) downstream.set(THEME_PREVIEW_HOST_HEADER, previewSlug);\n // Set after downstreamRequestHeaders deleted any copy the client sent. On\n // every request to the preview host, the backend proxy's included.\n if (previewSlug && storePreviewToken)\n downstream.set(STORE_PREVIEW_TOKEN_HEADER, storePreviewToken);\n const init = { request: { headers: downstream } };\n\n let response: NextResponse;\n\n if (hostStoreRef) {\n const url = req.nextUrl.clone();\n // Only rewrite if the path doesn't already start with /store/\n if (!url.pathname.startsWith(multiTenantStorePath(hostStoreRef))) {\n url.pathname = multiTenantStorePath(hostStoreRef, url.pathname);\n }\n\n response = NextResponse.rewrite(url, init);\n // Add headers to indicate this is a domain-mapped store\n response.headers.set(\"x-store-domain\", \"true\");\n response.headers.set(\"x-store-ref\", hostStoreRef);\n } else if (hostStoreSuspended) {\n // A platform admin suspended this store. The 403 the backend returned\n // for a domain lookup carries no ref/id to route on (see\n // getStoreByHost), so this can't rewrite to `/store/<ref>` the way the\n // resolved-store branch above does — it goes to a platform-level page\n // instead of the not-found path below.\n const url = req.nextUrl.clone();\n url.pathname = \"/store-suspended\";\n response = NextResponse.rewrite(url, init);\n } else if (hostStoreComingSoon) {\n // The merchant has not opened the store, and the request carried no\n // valid preview token (an expired one lands here too). Like the\n // suspended branch, the 403 carries no ref, so a platform-level page.\n // Known limitation: on the shared path-based host (localhost) nothing\n // routes here; a store that turns coming soon mid-session sends the\n // browser to /coming-soon, which resolves no store there and 404s, as\n // the apex's /store/<ref> already does for these stores.\n const url = req.nextUrl.clone();\n url.pathname = STORE_COMING_SOON_REDIRECT_PATH;\n response = NextResponse.rewrite(url, init);\n response.headers.set(\"x-robots-tag\", \"noindex\");\n } else if (hostResolved) {\n // The host looked like a store host but resolved to nothing: 404.\n console.debug(\"Store not found for host:\", host);\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n response = NextResponse.rewrite(url, init);\n } else {\n response = NextResponse.next(init);\n }\n\n // A store preview cookie lives at `/` on a store host, even when the host\n // resolved no store (coming soon), else at the store's path.\n const storePreviewPath = hostIdentifiesStore ? \"/\" : cookiePath;\n if (\n previewSlug ||\n (cookiePath && hasThemePreview(req, cookiePath)) ||\n (storePreviewPath && hasStorePreview(req, storePreviewPath))\n ) {\n response.headers.set(\"x-robots-tag\", \"noindex\");\n }\n\n if (rotated && storeRef && cookiePath) {\n // Same path the auth route handler writes with, from the same signal.\n writeAuthCookies(response, storeRef, rotated, cookiePath);\n }\n\n return response;\n}\n\n/**\n * Single-store middleware: the store is fixed by ECOMWEB_STORE_REF, so there\n * is no host lookup and no rewrite. It applies the store's URL redirects and\n * refreshes a near-expiry session. Requests are stamped host-mapped, so auth\n * cookies use Path=/ (see auth/cookies.ts).\n */\nasync function singleStore(req: NextRequest): Promise<NextResponse> {\n const pathname = req.nextUrl.pathname;\n if (METADATA_FILES.includes(pathname))\n return NextResponse.next(withoutInternalHeaders(req));\n\n const storeRef = publicConfig().storeRef as string;\n\n const cookiePath = authCookiePath(storeRef, true);\n if (pathname === STORE_PREVIEW_PATH)\n return applyStorePreview(req, cookiePath, \"/\");\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\n\n try {\n const redirect = await lookupRedirect(storeRef, pathname);\n if (redirect) {\n return NextResponse.redirect(\n redirectDestinationUrl(req, redirect.destination_path),\n { status: redirect.redirect_type }\n );\n }\n } catch (error) {\n // Fail open: a redirect lookup must never take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n\n const rotated = await refreshIfNearExpiry(req, storeRef, cookiePath);\n const response = NextResponse.next({\n request: {\n headers: downstreamRequestHeaders(req, true, storeRef, rotated),\n },\n });\n\n if (hasThemePreview(req, cookiePath) || hasStorePreview(req, cookiePath))\n response.headers.set(\"x-robots-tag\", \"noindex\");\n if (rotated) {\n writeAuthCookies(response, storeRef, rotated, cookiePath);\n }\n return response;\n}\n\n/**\n * The storefront's proxy.ts (Next middleware).\n * - multi: host → store lookup, rewrites to /store/<ref>, suspended and\n * unknown stores, coming soon stores (rewritten to /coming-soon, noindex),\n * redirects, session refresh. The store preview link (`/preview?token=`\n * on a store host, `/store/<ref>/preview?token=` on localhost) becomes a\n * cookie before the lookup, and the lookup carries that token.\n * - single: the `/preview?token=` link, redirects and session refresh.\n * Without `mode`, the configured mode (ECOMWEB_MODE) decides per request.\n */\nexport function createStorefrontMiddleware(\n opts: { mode?: StorefrontMode } = {}\n): (req: NextRequest) => Promise<NextResponse> {\n return req =>\n (opts.mode ?? publicConfig().mode) === \"multi\"\n ? multiTenant(req)\n : singleStore(req);\n}\n\n/**\n * Next reads `config` from proxy.ts statically, so an app re-exports this as\n * `export const config = { matcher: [...] }` with the same literal.\n */\nexport const storefrontMiddlewareConfig = {\n matcher: [\n /*\n * Match all request paths except for the ones starting with:\n * - api (API routes)\n * - _next/static (static files)\n * - _next/image (image optimization files)\n * - _vercel (Vercel Analytics; off Vercel, a store page render per hit)\n * - favicon.ico (favicon file)\n */\n \"/((?!api|_next/static|_next/image|_vercel|favicon.ico).*)\",\n ],\n};\n"],"mappings":"AAAA,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAsB,oBAAoB;AAE1C,SAAS,gBAAgB,wBAAwB;AACjD;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,4BAA4B;AACrC,SAAS,sBAAsB;AAC/B,SAAS,uCAAuC;AAChD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AAC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AACF;","names":["storeRef","response"]}
@@ -0,0 +1,58 @@
1
+ "use client";
2
+ import { useEffect, useState } from "react";
3
+ import { publicApiClient } from "../api/client.js";
4
+ import { unwrap } from "../api/response.js";
5
+ import { useStoreId } from "../store/store-context.js";
6
+ function shouldShowBankTransferDetails(order) {
7
+ if (!order) return false;
8
+ return order.payment_method === "bank_transfer" && order.payment_status === "pending" && order.order_status !== "cancelled";
9
+ }
10
+ function pickBankTransfer(methods) {
11
+ const list = Array.isArray(methods) ? methods : [];
12
+ const transfer = list.find((m) => m?.payment_method === "bank_transfer");
13
+ return {
14
+ accounts: Array.isArray(transfer?.bank_accounts) ? transfer.bank_accounts : [],
15
+ // transfer_instruction, not description: description is the
16
+ // choose-a-method text shown at checkout.
17
+ note: transfer?.transfer_instruction || null
18
+ };
19
+ }
20
+ function useBankTransferDetails(enabled) {
21
+ const storeRef = useStoreId();
22
+ const [accounts, setAccounts] = useState([]);
23
+ const [note, setNote] = useState(null);
24
+ const [isLoading, setIsLoading] = useState(false);
25
+ useEffect(() => {
26
+ if (!enabled || !storeRef) return;
27
+ let cancelled = false;
28
+ setIsLoading(true);
29
+ (async () => {
30
+ try {
31
+ const res = await publicApiClient.get(
32
+ `/public/stores/${encodeURIComponent(storeRef)}/payment-methods`
33
+ );
34
+ const picked = pickBankTransfer(unwrap(res));
35
+ if (cancelled) return;
36
+ setAccounts(picked.accounts);
37
+ setNote(picked.note);
38
+ } catch {
39
+ if (!cancelled) {
40
+ setAccounts([]);
41
+ setNote(null);
42
+ }
43
+ } finally {
44
+ if (!cancelled) setIsLoading(false);
45
+ }
46
+ })();
47
+ return () => {
48
+ cancelled = true;
49
+ };
50
+ }, [enabled, storeRef]);
51
+ return { accounts, note, isLoading };
52
+ }
53
+ export {
54
+ pickBankTransfer,
55
+ shouldShowBankTransferDetails,
56
+ useBankTransferDetails
57
+ };
58
+ //# sourceMappingURL=bank-transfer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/orders/bank-transfer.ts"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\nimport { useStoreId } from \"../store/store-context\";\n\n/** The bank_transfer slice of the public payment-methods projection. */\nexport interface BankAccountView {\n id: number;\n bank_name: string;\n bank_code: string;\n account_number: string;\n account_holder: string;\n}\n\ninterface PublicPaymentMethod {\n payment_method: string;\n transfer_instruction?: string | null;\n bank_accounts?: BankAccountView[];\n}\n\n/** What a shopper needs to pay a bank transfer order. */\nexport interface BankTransferDetails {\n accounts: BankAccountView[];\n /** The merchant's transfer instruction, if they wrote one. */\n note: string | null;\n isLoading: boolean;\n}\n\n/**\n * Whether an order page should tell the shopper how to pay by transfer: a\n * bank_transfer order the merchant has not marked paid yet, and that is\n * still live. Order pages read this from the order itself, so they work for\n * any order, long after the checkout handoff has expired.\n */\nexport function shouldShowBankTransferDetails(\n order:\n | {\n payment_method?: string | null;\n payment_status?: string | null;\n order_status?: string | null;\n }\n | null\n | undefined\n): boolean {\n if (!order) return false;\n return (\n order.payment_method === \"bank_transfer\" &&\n order.payment_status === \"pending\" &&\n order.order_status !== \"cancelled\"\n );\n}\n\n/**\n * The bank_transfer method's accounts and instruction out of the public\n * payment-methods response. A store without the method, or a malformed\n * response, yields no accounts.\n */\nexport function pickBankTransfer(methods: unknown): {\n accounts: BankAccountView[];\n note: string | null;\n} {\n const list = Array.isArray(methods) ? (methods as PublicPaymentMethod[]) : [];\n const transfer = list.find(m => m?.payment_method === \"bank_transfer\");\n return {\n accounts: Array.isArray(transfer?.bank_accounts)\n ? transfer.bank_accounts\n : [],\n // transfer_instruction, not description: description is the\n // choose-a-method text shown at checkout.\n note: transfer?.transfer_instruction || null,\n };\n}\n\n/**\n * The store's bank accounts and transfer instruction, fetched from the\n * public payment-methods endpoint while `enabled`. Used by the order-success\n * page and by the order lookup and account order pages.\n */\nexport function useBankTransferDetails(enabled: boolean): BankTransferDetails {\n const storeRef = useStoreId();\n const [accounts, setAccounts] = useState<BankAccountView[]>([]);\n const [note, setNote] = useState<string | null>(null);\n const [isLoading, setIsLoading] = useState(false);\n\n useEffect(() => {\n if (!enabled || !storeRef) return;\n let cancelled = false;\n setIsLoading(true);\n (async () => {\n try {\n const res = await publicApiClient.get<PublicPaymentMethod[]>(\n `/public/stores/${encodeURIComponent(storeRef)}/payment-methods`\n );\n const picked = pickBankTransfer(unwrap(res));\n if (cancelled) return;\n setAccounts(picked.accounts);\n setNote(picked.note);\n } catch {\n // The order exists either way; no accounts renders a \"contact the\n // shop\" fallback rather than an error.\n if (!cancelled) {\n setAccounts([]);\n setNote(null);\n }\n } finally {\n if (!cancelled) setIsLoading(false);\n }\n })();\n return () => {\n cancelled = true;\n };\n }, [enabled, storeRef]);\n\n return { accounts, note, isLoading };\n}\n"],"mappings":";AAEA,SAAS,WAAW,gBAAgB;AACpC,SAAS,uBAAuB;AAChC,SAAS,cAAc;AACvB,SAAS,kBAAkB;AA+BpB,SAAS,8BACd,OAQS;AACT,MAAI,CAAC,MAAO,QAAO;AACnB,SACE,MAAM,mBAAmB,mBACzB,MAAM,mBAAmB,aACzB,MAAM,iBAAiB;AAE3B;AAOO,SAAS,iBAAiB,SAG/B;AACA,QAAM,OAAO,MAAM,QAAQ,OAAO,IAAK,UAAoC,CAAC;AAC5E,QAAM,WAAW,KAAK,KAAK,OAAK,GAAG,mBAAmB,eAAe;AACrE,SAAO;AAAA,IACL,UAAU,MAAM,QAAQ,UAAU,aAAa,IAC3C,SAAS,gBACT,CAAC;AAAA;AAAA;AAAA,IAGL,MAAM,UAAU,wBAAwB;AAAA,EAC1C;AACF;AAOO,SAAS,uBAAuB,SAAuC;AAC5E,QAAM,WAAW,WAAW;AAC5B,QAAM,CAAC,UAAU,WAAW,IAAI,SAA4B,CAAC,CAAC;AAC9D,QAAM,CAAC,MAAM,OAAO,IAAI,SAAwB,IAAI;AACpD,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAEhD,YAAU,MAAM;AACd,QAAI,CAAC,WAAW,CAAC,SAAU;AAC3B,QAAI,YAAY;AAChB,iBAAa,IAAI;AACjB,KAAC,YAAY;AACX,UAAI;AACF,cAAM,MAAM,MAAM,gBAAgB;AAAA,UAChC,kBAAkB,mBAAmB,QAAQ,CAAC;AAAA,QAChD;AACA,cAAM,SAAS,iBAAiB,OAAO,GAAG,CAAC;AAC3C,YAAI,UAAW;AACf,oBAAY,OAAO,QAAQ;AAC3B,gBAAQ,OAAO,IAAI;AAAA,MACrB,QAAQ;AAGN,YAAI,CAAC,WAAW;AACd,sBAAY,CAAC,CAAC;AACd,kBAAQ,IAAI;AAAA,QACd;AAAA,MACF,UAAE;AACA,YAAI,CAAC,UAAW,cAAa,KAAK;AAAA,MACpC;AAAA,IACF,GAAG;AACH,WAAO,MAAM;AACX,kBAAY;AAAA,IACd;AAAA,EACF,GAAG,CAAC,SAAS,QAAQ,CAAC;AAEtB,SAAO,EAAE,UAAU,MAAM,UAAU;AACrC;","names":[]}
@@ -1,7 +1,5 @@
1
1
  "use client";
2
2
  import { useCallback, useEffect, useState } from "react";
3
- import { publicApiClient } from "../api/client.js";
4
- import { unwrap } from "../api/response.js";
5
3
  import { getPaymentState } from "../checkout/get-payment-state.js";
6
4
  import { readOrderHandoff } from "../checkout/order-handoff.js";
7
5
  import { pollPaymentState } from "../checkout/payment-state-poll.js";
@@ -11,6 +9,7 @@ import {
11
9
  } from "../checkout/success-state.js";
12
10
  import { sdk } from "../sdk.js";
13
11
  import { useStoreId } from "../store/store-context.js";
12
+ import { useBankTransferDetails } from "./bank-transfer.js";
14
13
  const CANCELLED = new Error("order status: unmounted");
15
14
  const timeoutWait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
16
15
  function useOrderStatus({
@@ -24,37 +23,13 @@ function useOrderStatus({
24
23
  () => resolveInitialState(orderCode, null)
25
24
  );
26
25
  const [isPolling, setIsPolling] = useState(false);
27
- const [bankAccounts, setBankAccounts] = useState([]);
28
- const [transferNote, setTransferNote] = useState(null);
29
26
  useEffect(() => {
30
27
  const stored = readOrderHandoff(orderCode);
31
28
  setHandoff(stored);
32
29
  setState(resolveInitialState(orderCode, stored));
33
30
  setHandoffLoaded(true);
34
31
  }, [orderCode]);
35
- useEffect(() => {
36
- if (state !== "awaiting-transfer" || !storeRef) return;
37
- let cancelled = false;
38
- (async () => {
39
- try {
40
- const res = await publicApiClient.get(
41
- `/public/stores/${encodeURIComponent(storeRef)}/payment-methods`
42
- );
43
- const methods = unwrap(res);
44
- const transfer = (Array.isArray(methods) ? methods : []).find(
45
- (m) => m.payment_method === "bank_transfer"
46
- );
47
- if (cancelled) return;
48
- setBankAccounts(transfer?.bank_accounts ?? []);
49
- setTransferNote(transfer?.transfer_instruction ?? null);
50
- } catch {
51
- if (!cancelled) setBankAccounts([]);
52
- }
53
- })();
54
- return () => {
55
- cancelled = true;
56
- };
57
- }, [state, storeRef]);
32
+ const bankTransfer = useBankTransferDetails(state === "awaiting-transfer");
58
33
  useEffect(() => {
59
34
  if (!orderCode) return;
60
35
  if (!handoffLoaded) return;
@@ -87,7 +62,7 @@ function useOrderStatus({
87
62
  return {
88
63
  handoff,
89
64
  payment: { state, isPolling },
90
- bankTransfer: { accounts: bankAccounts, note: transferNote }
65
+ bankTransfer: { accounts: bankTransfer.accounts, note: bankTransfer.note }
91
66
  };
92
67
  }
93
68
  function useOrderLookup({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/orders/use-order-status.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useState } from \"react\";\nimport type { OrderWithItems } from \"@ecomweb/sdk\";\nimport { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\nimport { getPaymentState } from \"../checkout/get-payment-state\";\nimport { readOrderHandoff, type OrderHandoff } from \"../checkout/order-handoff\";\nimport { pollPaymentState } from \"../checkout/payment-state-poll\";\nimport {\n resolveInitialState,\n shouldPollForConfirmation,\n type PaymentConfirmationState,\n} from \"../checkout/success-state\";\nimport { sdk } from \"../sdk\";\nimport { useStoreId } from \"../store/store-context\";\n\n/** The bank_transfer slice of the public payment-methods projection. */\nexport interface BankAccountView {\n id: number;\n bank_name: string;\n bank_code: string;\n account_number: string;\n account_holder: string;\n}\n\ninterface PublicPaymentMethod {\n payment_method: string;\n transfer_instruction?: string | null;\n bank_accounts?: BankAccountView[];\n}\n\nconst CANCELLED = new Error(\"order status: unmounted\");\n\nconst timeoutWait = (ms: number) =>\n new Promise<void>(resolve => setTimeout(resolve, ms));\n\n/**\n * What the shopper should be told about a just-placed order (the\n * order-success page, which is also the payment gateway's return URL).\n *\n * Arriving back from a gateway proves nothing about the payment: the\n * provider's server-to-server callback usually lands later, so a gateway\n * order polls the API until it is paid or failed. Offline orders read the\n * checkout's handoff and never poll. See checkout/success-state.ts.\n */\nexport function useOrderStatus({\n orderCode,\n wait = timeoutWait,\n}: {\n orderCode: string | null;\n /** Delay between polls; injectable for tests. */\n wait?: (ms: number) => Promise<void>;\n}) {\n const storeRef = useStoreId();\n // Read in an effect, not a useState initialiser: storage does not exist\n // during the server render, and seeding state from it would make the first\n // client render disagree with the server's.\n const [handoff, setHandoff] = useState<OrderHandoff | null>(null);\n const [handoffLoaded, setHandoffLoaded] = useState(false);\n const [state, setState] = useState<PaymentConfirmationState>(() =>\n resolveInitialState(orderCode, null)\n );\n const [isPolling, setIsPolling] = useState(false);\n const [bankAccounts, setBankAccounts] = useState<BankAccountView[]>([]);\n const [transferNote, setTransferNote] = useState<string | null>(null);\n\n useEffect(() => {\n const stored = readOrderHandoff(orderCode);\n setHandoff(stored);\n setState(resolveInitialState(orderCode, stored));\n setHandoffLoaded(true);\n }, [orderCode]);\n\n // A bank transfer order needs the merchant's accounts and transfer\n // instruction, which travel on the public payment-methods endpoint.\n useEffect(() => {\n if (state !== \"awaiting-transfer\" || !storeRef) return;\n let cancelled = false;\n (async () => {\n try {\n const res = await publicApiClient.get<PublicPaymentMethod[]>(\n `/public/stores/${encodeURIComponent(storeRef)}/payment-methods`\n );\n const methods = unwrap(res) as unknown as PublicPaymentMethod[];\n const transfer = (Array.isArray(methods) ? methods : []).find(\n m => m.payment_method === \"bank_transfer\"\n );\n if (cancelled) return;\n setBankAccounts(transfer?.bank_accounts ?? []);\n // transfer_instruction, not description: description is the\n // choose-a-method text shown at checkout.\n setTransferNote(transfer?.transfer_instruction ?? null);\n } catch {\n // The order is placed either way; no accounts renders a \"contact the\n // shop\" fallback rather than an error.\n if (!cancelled) setBankAccounts([]);\n }\n })();\n return () => {\n cancelled = true;\n };\n }, [state, storeRef]);\n\n useEffect(() => {\n if (!orderCode) return; // no gateway return in play, nothing to poll\n // Until the handoff is read every order looks like \"confirming\"; an\n // offline one would start a poll with no callback coming.\n if (!handoffLoaded) return;\n if (!shouldPollForConfirmation(state)) return;\n\n let cancelled = false;\n setIsPolling(true);\n pollPaymentState({\n poll: () => getPaymentState(storeRef, orderCode),\n // Rejecting once unmounted ends the poll loop, not just its result.\n wait: async ms => {\n if (cancelled) throw CANCELLED;\n await wait(ms);\n if (cancelled) throw CANCELLED;\n },\n }).then(\n outcome => {\n if (cancelled) return;\n // \"pending\" (attempts exhausted, or every attempt errored) is\n // \"still-confirming\", never \"failed\": only the API says failed.\n setState(\n outcome.status === \"paid\"\n ? \"paid\"\n : outcome.status === \"failed\"\n ? \"failed\"\n : \"still-confirming\"\n );\n setIsPolling(false);\n },\n () => {}\n );\n\n return () => {\n cancelled = true;\n };\n // state is read once to decide whether to start; re-running on every\n // transition would restart the poll it just resolved.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [orderCode, storeRef, handoffLoaded]);\n\n return {\n handoff,\n payment: { state, isPolling },\n bankTransfer: { accounts: bankAccounts, note: transferNote },\n };\n}\n\n/**\n * A guest's order, looked up by its code plus the email or phone it was\n * placed with (the view-order page).\n */\nexport function useOrderLookup({\n orderCode,\n email,\n phone,\n}: {\n orderCode: string | null;\n email?: string | null;\n phone?: string | null;\n}) {\n const storeRef = useStoreId();\n const [order, setOrder] = useState<OrderWithItems | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n const fetchOrder = useCallback(async () => {\n if (!orderCode || (!email && !phone)) {\n setError(\"Thiếu thông tin cần thiết để tra cứu đơn hàng\");\n setIsLoading(false);\n return;\n }\n try {\n setIsLoading(true);\n setError(null);\n const found = await sdk.orders.lookupGuest(storeRef, {\n order_code: orderCode,\n customer_email: email || undefined,\n customer_phone: phone || undefined,\n });\n if (!found) {\n setError(\"Không tìm thấy đơn hàng với thông tin đã cung cấp\");\n return;\n }\n setOrder(found as unknown as OrderWithItems);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\"Error fetching order:\", err);\n setError(\"Có lỗi xảy ra khi tra cứu đơn hàng\");\n } finally {\n setIsLoading(false);\n }\n }, [storeRef, orderCode, email, phone]);\n\n useEffect(() => {\n fetchOrder();\n }, [fetchOrder]);\n\n return { order, isLoading, error, retry: fetchOrder };\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,gBAAgB;AAEjD,SAAS,uBAAuB;AAChC,SAAS,cAAc;AACvB,SAAS,uBAAuB;AAChC,SAAS,wBAA2C;AACpD,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,WAAW;AACpB,SAAS,kBAAkB;AAiB3B,MAAM,YAAY,IAAI,MAAM,yBAAyB;AAErD,MAAM,cAAc,CAAC,OACnB,IAAI,QAAc,aAAW,WAAW,SAAS,EAAE,CAAC;AAW/C,SAAS,eAAe;AAAA,EAC7B;AAAA,EACA,OAAO;AACT,GAIG;AACD,QAAM,WAAW,WAAW;AAI5B,QAAM,CAAC,SAAS,UAAU,IAAI,SAA8B,IAAI;AAChE,QAAM,CAAC,eAAe,gBAAgB,IAAI,SAAS,KAAK;AACxD,QAAM,CAAC,OAAO,QAAQ,IAAI;AAAA,IAAmC,MAC3D,oBAAoB,WAAW,IAAI;AAAA,EACrC;AACA,QAAM,CAAC,WAAW,YAAY,IAAI,SA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AAAA,EACb,GAAG,CAAC,UAAU,CAAC;AAEf,SAAO,EAAE,OAAO,WAAW,OAAO,OAAO,WAAW;AACtD;","names":[]}
1
+ {"version":3,"sources":["../../src/orders/use-order-status.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useState } from \"react\";\nimport type { OrderWithItems } from \"@ecomweb/sdk\";\nimport { getPaymentState } from \"../checkout/get-payment-state\";\nimport { readOrderHandoff, type OrderHandoff } from \"../checkout/order-handoff\";\nimport { pollPaymentState } from \"../checkout/payment-state-poll\";\nimport {\n resolveInitialState,\n shouldPollForConfirmation,\n type PaymentConfirmationState,\n} from \"../checkout/success-state\";\nimport { sdk } from \"../sdk\";\nimport { useStoreId } from \"../store/store-context\";\nimport { useBankTransferDetails } from \"./bank-transfer\";\n\nexport type { BankAccountView } from \"./bank-transfer\";\n\nconst CANCELLED = new Error(\"order status: unmounted\");\n\nconst timeoutWait = (ms: number) =>\n new Promise<void>(resolve => setTimeout(resolve, ms));\n\n/**\n * What the shopper should be told about a just-placed order (the\n * order-success page, which is also the payment gateway's return URL).\n *\n * Arriving back from a gateway proves nothing about the payment: the\n * provider's server-to-server callback usually lands later, so a gateway\n * order polls the API until it is paid or failed. Offline orders read the\n * checkout's handoff and never poll. See checkout/success-state.ts.\n */\nexport function useOrderStatus({\n orderCode,\n wait = timeoutWait,\n}: {\n orderCode: string | null;\n /** Delay between polls; injectable for tests. */\n wait?: (ms: number) => Promise<void>;\n}) {\n const storeRef = useStoreId();\n // Read in an effect, not a useState initialiser: storage does not exist\n // during the server render, and seeding state from it would make the first\n // client render disagree with the server's.\n const [handoff, setHandoff] = useState<OrderHandoff | null>(null);\n const [handoffLoaded, setHandoffLoaded] = useState(false);\n const [state, setState] = useState<PaymentConfirmationState>(() =>\n resolveInitialState(orderCode, null)\n );\n const [isPolling, setIsPolling] = useState(false);\n\n useEffect(() => {\n const stored = readOrderHandoff(orderCode);\n setHandoff(stored);\n setState(resolveInitialState(orderCode, stored));\n setHandoffLoaded(true);\n }, [orderCode]);\n\n // A bank transfer order needs the merchant's accounts and transfer\n // instruction, which travel on the public payment-methods endpoint.\n const bankTransfer = useBankTransferDetails(state === \"awaiting-transfer\");\n\n useEffect(() => {\n if (!orderCode) return; // no gateway return in play, nothing to poll\n // Until the handoff is read every order looks like \"confirming\"; an\n // offline one would start a poll with no callback coming.\n if (!handoffLoaded) return;\n if (!shouldPollForConfirmation(state)) return;\n\n let cancelled = false;\n setIsPolling(true);\n pollPaymentState({\n poll: () => getPaymentState(storeRef, orderCode),\n // Rejecting once unmounted ends the poll loop, not just its result.\n wait: async ms => {\n if (cancelled) throw CANCELLED;\n await wait(ms);\n if (cancelled) throw CANCELLED;\n },\n }).then(\n outcome => {\n if (cancelled) return;\n // \"pending\" (attempts exhausted, or every attempt errored) is\n // \"still-confirming\", never \"failed\": only the API says failed.\n setState(\n outcome.status === \"paid\"\n ? \"paid\"\n : outcome.status === \"failed\"\n ? \"failed\"\n : \"still-confirming\"\n );\n setIsPolling(false);\n },\n () => {}\n );\n\n return () => {\n cancelled = true;\n };\n // state is read once to decide whether to start; re-running on every\n // transition would restart the poll it just resolved.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [orderCode, storeRef, handoffLoaded]);\n\n return {\n handoff,\n payment: { state, isPolling },\n bankTransfer: { accounts: bankTransfer.accounts, note: bankTransfer.note },\n };\n}\n\n/**\n * A guest's order, looked up by its code plus the email or phone it was\n * placed with (the view-order page).\n */\nexport function useOrderLookup({\n orderCode,\n email,\n phone,\n}: {\n orderCode: string | null;\n email?: string | null;\n phone?: string | null;\n}) {\n const storeRef = useStoreId();\n const [order, setOrder] = useState<OrderWithItems | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n const fetchOrder = useCallback(async () => {\n if (!orderCode || (!email && !phone)) {\n setError(\"Thiếu thông tin cần thiết để tra cứu đơn hàng\");\n setIsLoading(false);\n return;\n }\n try {\n setIsLoading(true);\n setError(null);\n const found = await sdk.orders.lookupGuest(storeRef, {\n order_code: orderCode,\n customer_email: email || undefined,\n customer_phone: phone || undefined,\n });\n if (!found) {\n setError(\"Không tìm thấy đơn hàng với thông tin đã cung cấp\");\n return;\n }\n setOrder(found as unknown as OrderWithItems);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\"Error fetching order:\", err);\n setError(\"Có lỗi xảy ra khi tra cứu đơn hàng\");\n } finally {\n setIsLoading(false);\n }\n }, [storeRef, orderCode, email, phone]);\n\n useEffect(() => {\n fetchOrder();\n }, [fetchOrder]);\n\n return { order, isLoading, error, retry: fetchOrder };\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,gBAAgB;AAEjD,SAAS,uBAAuB;AAChC,SAAS,wBAA2C;AACpD,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,WAAW;AACpB,SAAS,kBAAkB;AAC3B,SAAS,8BAA8B;AAIvC,MAAM,YAAY,IAAI,MAAM,yBAAyB;AAErD,MAAM,cAAc,CAAC,OACnB,IAAI,QAAc,aAAW,WAAW,SAAS,EAAE,CAAC;AAW/C,SAAS,eAAe;AAAA,EAC7B;AAAA,EACA,OAAO;AACT,GAIG;AACD,QAAM,WAAW,WAAW;AAI5B,QAAM,CAAC,SAAS,UAAU,IAAI,SAA8B,IAAI;AAChE,QAAM,CAAC,eAAe,gBAAgB,IAAI,SAAS,KAAK;AACxD,QAAM,CAAC,OAAO,QAAQ,IAAI;AAAA,IAAmC,MAC3D,oBAAoB,WAAW,IAAI;AAAA,EACrC;AACA,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAEhD,YAAU,MAAM;AACd,UAAM,SAAS,iBAAiB,SAAS;AACzC,eAAW,MAAM;AACjB,aAAS,oBAAoB,WAAW,MAAM,CAAC;AAC/C,qBAAiB,IAAI;AAAA,EACvB,GAAG,CAAC,SAAS,CAAC;AAId,QAAM,eAAe,uBAAuB,UAAU,mBAAmB;AAEzE,YA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AAA,QACZ,gBAAgB,SAAS;AAAA,QACzB,gBAAgB,SAAS;AAAA,MAC3B,CAAC;AACD,UAAI,CAAC,OAAO;AACV,iBAAS,gGAAmD;AAC5D;AAAA,MACF;AACA,eAAS,KAAkC;AAAA,IAC7C,SAAS,KAAK;AAEZ,cAAQ,MAAM,yBAAyB,GAAG;AAC1C,eAAS,mEAAoC;AAAA,IAC/C,UAAE;AACA,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF,GAAG,CAAC,UAAU,WAAW,OAAO,KAAK,CAAC;AAEtC,YAAU,MAAM;AACd,eAAW;AAAA,EACb,GAAG,CAAC,UAAU,CAAC;AAEf,SAAO,EAAE,OAAO,WAAW,OAAO,OAAO,WAAW;AACtD;","names":[]}
@@ -5,6 +5,7 @@ function buildStoreUrl(store, path) {
5
5
  if (!path) return config.appUrl;
6
6
  return `${config.appUrl}/${path.replace(/^\/+/, "")}`;
7
7
  }
8
+ const subpath = (path ?? "").replace(/^\/+/, "");
8
9
  const isLocal = config.appBaseUrlFlag === "local";
9
10
  let subdomain = "";
10
11
  let custom_domain = "";
@@ -25,19 +26,19 @@ function buildStoreUrl(store, path) {
25
26
  if (isLocal) {
26
27
  const origin = typeof window === "undefined" && process.env.APP_BASE_URL?.trim() || "http://localhost:3002";
27
28
  const baseUrl2 = `${origin}/store/${store_ref}`;
28
- return path ? `${baseUrl2}/${path}` : baseUrl2;
29
+ return subpath ? `${baseUrl2}/${subpath}` : baseUrl2;
29
30
  }
30
31
  if (custom_domain) {
31
32
  const baseUrl2 = `https://${custom_domain}`;
32
- return path ? `${baseUrl2}/${path}` : baseUrl2;
33
+ return subpath ? `${baseUrl2}/${subpath}` : baseUrl2;
33
34
  }
34
35
  if (subdomain) {
35
36
  const platformDomain = config.platformDomainSuffix ?? "ecomsite.app";
36
37
  const baseUrl2 = `https://${subdomain}.${platformDomain}`;
37
- return path ? `${baseUrl2}/${path}` : baseUrl2;
38
+ return subpath ? `${baseUrl2}/${subpath}` : baseUrl2;
38
39
  }
39
40
  const baseUrl = `/store/${store_ref}`;
40
- return path ? `${baseUrl}/${path}` : baseUrl;
41
+ return subpath ? `${baseUrl}/${subpath}` : baseUrl;
41
42
  }
42
43
  export {
43
44
  buildStoreUrl
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/store-scope/store-url.ts"],"sourcesContent":["import type { StoreConfig, StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { publicConfig } from \"../config/public\";\n\n/**\n * Build store URL based on environment and store configuration\n * @param store - Store object with subdomain and custom_domain\n * @param path - Optional path to append to the store URL\n * @returns Complete store URL\n *\n * @example\n * // Local development\n * buildStoreUrl({ id: 1, subdomain: 'mystore', custom_domain: null })\n * // Returns: 'http://localhost:3000/store/1'\n *\n * // Production with subdomain\n * buildStoreUrl({ id: 1, subdomain: 'mystore', custom_domain: null })\n * // Returns: 'https://mystore.{NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX}'\n *\n * // Production with custom domain\n * buildStoreUrl({ id: 1, subdomain: 'mystore', custom_domain: 'mystore.com' })\n * // Returns: 'https://mystore.com'\n *\n * // With path\n * buildStoreUrl({ id: 1, subdomain: 'mystore', custom_domain: null }, 'about')\n * // Returns: 'https://mystore.{NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX}/about'\n */\nexport function buildStoreUrl(\n store:\n | { ref: string; subdomain: string | null; custom_domain: string | null }\n | StoreConfig\n | StoreConfigurationInfo,\n path?: string\n): string {\n const config = publicConfig();\n // Single-store: an absolute URL on this site; `store` is ignored.\n if (config.mode === \"single\") {\n if (!path) return config.appUrl;\n return `${config.appUrl}/${path.replace(/^\\/+/, \"\")}`;\n }\n\n const isLocal = config.appBaseUrlFlag === \"local\";\n let subdomain = \"\";\n let custom_domain = \"\";\n let store_ref = \"\";\n\n if (\"ref\" in store && \"subdomain\" in store && \"custom_domain\" in store) {\n subdomain = store.subdomain || \"\";\n custom_domain = store.custom_domain || \"\";\n store_ref = (store as any).ref || \"\";\n } else if (\"config\" in store && store.config) {\n subdomain = store.config.subdomain || \"\";\n custom_domain = store.config.custom_domain || \"\";\n store_ref = (store as any).ref || \"\";\n } else if (\"subdomain\" in store && \"custom_domain\" in store) {\n subdomain = store.subdomain || \"\";\n custom_domain = store.custom_domain || \"\";\n store_ref = (store as any).ref || \"\";\n }\n\n if (isLocal) {\n // Server-only var, so the browser always gets the dev default (as before).\n const origin =\n (typeof window === \"undefined\" && process.env.APP_BASE_URL?.trim()) ||\n \"http://localhost:3002\";\n const baseUrl = `${origin}/store/${store_ref}`;\n return path ? `${baseUrl}/${path}` : baseUrl;\n }\n\n if (custom_domain) {\n const baseUrl = `https://${custom_domain}`;\n return path ? `${baseUrl}/${path}` : baseUrl;\n }\n\n if (subdomain) {\n const platformDomain = config.platformDomainSuffix ?? \"ecomsite.app\";\n const baseUrl = `https://${subdomain}.${platformDomain}`;\n return path ? `${baseUrl}/${path}` : baseUrl;\n }\n\n // Fallback: use store ref format\n const baseUrl = `/store/${store_ref}`;\n return path ? `${baseUrl}/${path}` : baseUrl;\n}\n"],"mappings":"AACA,SAAS,oBAAoB;AAyBtB,SAAS,cACd,OAIA,MACQ;AACR,QAAM,SAAS,aAAa;AAE5B,MAAI,OAAO,SAAS,UAAU;AAC5B,QAAI,CAAC,KAAM,QAAO,OAAO;AACzB,WAAO,GAAG,OAAO,MAAM,IAAI,KAAK,QAAQ,QAAQ,EAAE,CAAC;AAAA,EACrD;AAEA,QAAM,UAAU,OAAO,mBAAmB;AAC1C,MAAI,YAAY;AAChB,MAAI,gBAAgB;AACpB,MAAI,YAAY;AAEhB,MAAI,SAAS,SAAS,eAAe,SAAS,mBAAmB,OAAO;AACtE,gBAAY,MAAM,aAAa;AAC/B,oBAAgB,MAAM,iBAAiB;AACvC,gBAAa,MAAc,OAAO;AAAA,EACpC,WAAW,YAAY,SAAS,MAAM,QAAQ;AAC5C,gBAAY,MAAM,OAAO,aAAa;AACtC,oBAAgB,MAAM,OAAO,iBAAiB;AAC9C,gBAAa,MAAc,OAAO;AAAA,EACpC,WAAW,eAAe,SAAS,mBAAmB,OAAO;AAC3D,gBAAY,MAAM,aAAa;AAC/B,oBAAgB,MAAM,iBAAiB;AACvC,gBAAa,MAAc,OAAO;AAAA,EACpC;AAEA,MAAI,SAAS;AAEX,UAAM,SACH,OAAO,WAAW,eAAe,QAAQ,IAAI,cAAc,KAAK,KACjE;AACF,UAAMA,WAAU,GAAG,MAAM,UAAU,SAAS;AAC5C,WAAO,OAAO,GAAGA,QAAO,IAAI,IAAI,KAAKA;AAAA,EACvC;AAEA,MAAI,eAAe;AACjB,UAAMA,WAAU,WAAW,aAAa;AACxC,WAAO,OAAO,GAAGA,QAAO,IAAI,IAAI,KAAKA;AAAA,EACvC;AAEA,MAAI,WAAW;AACb,UAAM,iBAAiB,OAAO,wBAAwB;AACtD,UAAMA,WAAU,WAAW,SAAS,IAAI,cAAc;AACtD,WAAO,OAAO,GAAGA,QAAO,IAAI,IAAI,KAAKA;AAAA,EACvC;AAGA,QAAM,UAAU,UAAU,SAAS;AACnC,SAAO,OAAO,GAAG,OAAO,IAAI,IAAI,KAAK;AACvC;","names":["baseUrl"]}
1
+ {"version":3,"sources":["../../src/store-scope/store-url.ts"],"sourcesContent":["import type { StoreConfig, StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { publicConfig } from \"../config/public\";\n\n/**\n * Build store URL based on environment and store configuration\n * @param store - Store object with subdomain and custom_domain\n * @param path - Optional path to append to the store URL\n * @returns Complete store URL\n *\n * @example\n * // Local development\n * buildStoreUrl({ id: 1, subdomain: 'mystore', custom_domain: null })\n * // Returns: 'http://localhost:3000/store/1'\n *\n * // Production with subdomain\n * buildStoreUrl({ id: 1, subdomain: 'mystore', custom_domain: null })\n * // Returns: 'https://mystore.{NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX}'\n *\n * // Production with custom domain\n * buildStoreUrl({ id: 1, subdomain: 'mystore', custom_domain: 'mystore.com' })\n * // Returns: 'https://mystore.com'\n *\n * // With path\n * buildStoreUrl({ id: 1, subdomain: 'mystore', custom_domain: null }, 'about')\n * // Returns: 'https://mystore.{NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX}/about'\n */\nexport function buildStoreUrl(\n store:\n | { ref: string; subdomain: string | null; custom_domain: string | null }\n | StoreConfig\n | StoreConfigurationInfo,\n path?: string\n): string {\n const config = publicConfig();\n // Single-store: an absolute URL on this site; `store` is ignored.\n if (config.mode === \"single\") {\n if (!path) return config.appUrl;\n return `${config.appUrl}/${path.replace(/^\\/+/, \"\")}`;\n }\n\n // Callers pass both \"login\" and \"/login\"; the base never ends in a slash.\n const subpath = (path ?? \"\").replace(/^\\/+/, \"\");\n\n const isLocal = config.appBaseUrlFlag === \"local\";\n let subdomain = \"\";\n let custom_domain = \"\";\n let store_ref = \"\";\n\n if (\"ref\" in store && \"subdomain\" in store && \"custom_domain\" in store) {\n subdomain = store.subdomain || \"\";\n custom_domain = store.custom_domain || \"\";\n store_ref = (store as any).ref || \"\";\n } else if (\"config\" in store && store.config) {\n subdomain = store.config.subdomain || \"\";\n custom_domain = store.config.custom_domain || \"\";\n store_ref = (store as any).ref || \"\";\n } else if (\"subdomain\" in store && \"custom_domain\" in store) {\n subdomain = store.subdomain || \"\";\n custom_domain = store.custom_domain || \"\";\n store_ref = (store as any).ref || \"\";\n }\n\n if (isLocal) {\n // Server-only var, so the browser always gets the dev default (as before).\n const origin =\n (typeof window === \"undefined\" && process.env.APP_BASE_URL?.trim()) ||\n \"http://localhost:3002\";\n const baseUrl = `${origin}/store/${store_ref}`;\n return subpath ? `${baseUrl}/${subpath}` : baseUrl;\n }\n\n if (custom_domain) {\n const baseUrl = `https://${custom_domain}`;\n return subpath ? `${baseUrl}/${subpath}` : baseUrl;\n }\n\n if (subdomain) {\n const platformDomain = config.platformDomainSuffix ?? \"ecomsite.app\";\n const baseUrl = `https://${subdomain}.${platformDomain}`;\n return subpath ? `${baseUrl}/${subpath}` : baseUrl;\n }\n\n // Fallback: use store ref format\n const baseUrl =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,cAAc;AACtD,WAAO,UAAU,GAAGA,QAAO,IAAI,OAAO,KAAKA;AAAA,EAC7C;AAGA,QAAM,UAAU,UAAU,SAAS;AACnC,SAAO,UAAU,GAAG,OAAO,IAAI,OAAO,KAAK;AAC7C;","names":["baseUrl"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/stores/cached.ts"],"sourcesContent":["import type { StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { sdk } from \"../sdk\";\nimport { cache } from \"react\";\n\nconst getCachedStoreInternal = cache(\n async (storeRef: string): Promise<StoreConfigurationInfo | null> => {\n return sdk.stores.getById(storeRef, {\n includeConfig: true,\n includeSettings: true,\n includeEmbeddedScripts: true,\n });\n }\n);\n\nexport const getCachedStore = cache(\n async (\n storeRef: string,\n options?: {\n includeConfig?: boolean;\n includeSettings?: boolean;\n includeBlogSettings?: boolean;\n }\n ): Promise<StoreConfigurationInfo | null> => {\n return getCachedStoreInternal(storeRef);\n }\n);\n"],"mappings":"AACA,SAAS,WAAW;AACpB,SAAS,aAAa;AAEtB,MAAM,yBAAyB;AAAA,EAC7B,OAAO,aAA6D;AAClE,WAAO,IAAI,OAAO,QAAQ,UAAU;AAAA,MAClC,eAAe;AAAA,MACf,iBAAiB;AAAA,MACjB,wBAAwB;AAAA,IAC1B,CAAC;AAAA,EACH;AACF;AAEO,MAAM,iBAAiB;AAAA,EAC5B,OACE,UACA,YAK2C;AAC3C,WAAO,uBAAuB,QAAQ;AAAA,EACxC;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/stores/cached.ts"],"sourcesContent":["import type { StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { sdk } from \"../sdk\";\nimport { cache } from \"react\";\n\nconst getCachedStoreInternal = cache(\n async (storeRef: string): Promise<StoreConfigurationInfo | null> => {\n return sdk.stores.getById(storeRef, {\n includeConfig: true,\n includeSettings: true,\n includeEmbeddedScripts: true,\n });\n }\n);\n\nexport const getCachedStore = cache(\n async (\n storeRef: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- public signature (in etc/index.api.md); accepted for compatibility, the full config is always fetched\n options?: {\n includeConfig?: boolean;\n includeSettings?: boolean;\n includeBlogSettings?: boolean;\n }\n ): Promise<StoreConfigurationInfo | null> => {\n return getCachedStoreInternal(storeRef);\n }\n);\n"],"mappings":"AACA,SAAS,WAAW;AACpB,SAAS,aAAa;AAEtB,MAAM,yBAAyB;AAAA,EAC7B,OAAO,aAA6D;AAClE,WAAO,IAAI,OAAO,QAAQ,UAAU;AAAA,MAClC,eAAe;AAAA,MACf,iBAAiB;AAAA,MACjB,wBAAwB;AAAA,IAC1B,CAAC;AAAA,EACH;AACF;AAEO,MAAM,iBAAiB;AAAA,EAC5B,OACE,UAEA,YAK2C;AAC3C,WAAO,uBAAuB,QAAQ;AAAA,EACxC;AACF;","names":[]}
@@ -64,7 +64,7 @@ async function getStoreByHost(host, options) {
64
64
  );
65
65
  if (foundStore?.ref) {
66
66
  storeRef = foundStore.ref;
67
- domain = foundStore.config?.custom_domain || null;
67
+ domain = foundStore.config?.verified === true ? foundStore.config.custom_domain || null : null;
68
68
  externalUrl = foundStore.storefront_url || null;
69
69
  previewSlug = foundStore.preview_slug || null;
70
70
  storePreviewToken = previewSlug ? foundStore.store_preview_token || null : null;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/stores/get-store-by-host.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { isStoreSuspendedError } from \"./store-suspension\";\nimport {\n comingSoonStoreNameOf,\n isStoreComingSoonError,\n} from \"./store-coming-soon\";\nimport {\n SKIP_STORE_PREVIEW,\n STORE_PREVIEW_HEADER,\n} from \"./store-preview-cookie\";\nimport { publicConfig } from \"../config\";\nimport { TtlCache } from \"./ttl-cache\";\n\ntype StoreByHost = Awaited<ReturnType<typeof getStoreByHost>>;\n\n/**\n * How long a lookup is reused in this process. A merchant's change (custom\n * domain, external theme, suspension) reaches shoppers within this window on\n * top of the API's own Redis cache. Misses and suspensions expire sooner so\n * a new or re-enabled store shows up quickly. A failed lookup (API down) is\n * never cached: it would turn a blip into a run of 404s. Neither is a lookup\n * made with a preview token: its answer is that previewer's, not the public's.\n */\nconst FOUND_TTL_MS = 30_000;\nconst NOT_FOUND_TTL_MS = 10_000;\nconst MAX_HOSTS = 10_000;\n\nconst byHost = new TtlCache<StoreByHost>(MAX_HOSTS);\n\n/** Tests only: forget every cached lookup. */\nexport function clearStoreByHostCache(): void {\n byHost.clear();\n}\n\n/**\n * The store's subdomain label when `hostname` is `<label>.<platformDomain>`\n * (a single label, so `www.shop.<platform>` and `shop.evil<platform>` are\n * not subdomains), else null.\n */\nfunction platformSubdomain(\n hostname: string,\n platformDomain: string\n): string | null {\n const suffix = `.${platformDomain}`;\n if (!hostname.endsWith(suffix)) return null;\n const label = hostname.slice(0, -suffix.length);\n return label && !label.includes(\".\") ? label : null;\n}\n\n/**\n * Get store ref and domain info from host\n * Used by middleware and API routes to determine which store is being accessed\n *\n * With `previewToken` (a store or theme preview token), the token is sent as\n * `X-Store-Preview`, which opens a coming soon store, and the cache is\n * neither read nor written. Without one the lookup is the public answer for\n * the host: it is cached, and it carries `SKIP_STORE_PREVIEW` so the API\n * client never attaches the request's ambient preview token to it.\n */\nexport async function getStoreByHost(\n host: string,\n options?: { previewToken?: string | null }\n): Promise<{\n storeRef: string | null;\n domain: string | null;\n isSubDomain: boolean;\n // True when the backend identified a store for this host but rejected it\n // with STORE_SUSPENDED. There is no `ref` to route on in that case — the\n // 403 response carries no store-identifying payload — so the caller must\n // handle this without a storeRef (see proxy.ts, which rewrites to a\n // platform-level suspended page rather than `/store/<ref>`).\n suspended: boolean;\n // The live theme's URL when it is external (`storefront_url`), else null.\n // Null too when the API predates external themes.\n externalUrl: string | null;\n // A theme's preview host, p-<slug> (theme preview hosts): its slug.\n previewSlug: string | null;\n // True when the backend identified a store for this host but rejected it\n // with STORE_COMING_SOON: the merchant has not opened it yet. Like\n // `suspended`, there is no `ref` to route on, because the 403 carries only\n // `details.name`; the caller handles it without a storeRef (proxy.ts\n // rewrites to the platform-level coming soon page). A lookup with a valid\n // preview token gets the store instead.\n comingSoon: boolean;\n // The store's name from that 403's `details.name`, else null.\n comingSoonName: string | null;\n // On a theme's preview host only (previewSlug set): the API's short-lived\n // store preview token for a coming soon store, sent as X-Store-Preview in\n // place of the cookie on that host. Null everywhere else. It is cached\n // with the lookup, because the p-<slug> host is itself the capability, and\n // 30 s is far inside the token's 1 h.\n storePreviewToken: string | null;\n}> {\n if (host.includes(\"localhost\") || host.includes(\"127.0.0.1\")) {\n return {\n storeRef: null,\n domain: null,\n isSubDomain: false,\n suspended: false,\n externalUrl: null,\n previewSlug: null,\n comingSoon: false,\n comingSoonName: null,\n storePreviewToken: null,\n };\n }\n\n const previewToken = options?.previewToken || null;\n const key = host.toLowerCase();\n if (!previewToken) {\n const cached = byHost.get(key);\n if (cached) return cached;\n }\n\n let storeRef: string | null = null;\n let domain: string | null = null;\n let suspended = false;\n let externalUrl: string | null = null;\n let previewSlug: string | null = null;\n let comingSoon = false;\n let comingSoonName: string | null = null;\n let storePreviewToken: string | null = null;\n\n let failed = false;\n\n const hostname = key.split(\":\")[0]!;\n const platformDomain = (\n publicConfig().platformDomainSuffix ?? \"ecomsite.app\"\n ).toLowerCase();\n const subdomain = platformSubdomain(hostname, platformDomain);\n const isSubDomain = subdomain !== null;\n\n try {\n const lookupValue = subdomain ?? host;\n const foundStore = await sdk.stores.getByDomain(\n lookupValue,\n previewToken\n ? { headers: { [STORE_PREVIEW_HEADER]: previewToken } }\n : SKIP_STORE_PREVIEW\n );\n\n if (foundStore?.ref) {\n storeRef = foundStore.ref;\n domain = foundStore.config?.custom_domain || null;\n externalUrl = foundStore.storefront_url || null;\n previewSlug = foundStore.preview_slug || null;\n // Never taken from a non-preview host.\n storePreviewToken = previewSlug\n ? foundStore.store_preview_token || null\n : null;\n }\n } catch (error) {\n if (isStoreSuspendedError(error)) {\n suspended = true;\n } else if (isStoreComingSoonError(error)) {\n comingSoon = true;\n comingSoonName = comingSoonStoreNameOf(error);\n } else {\n failed = true;\n console.error(\"Store not found for host:\", host);\n }\n }\n\n const result = {\n storeRef,\n domain,\n isSubDomain,\n suspended,\n externalUrl,\n previewSlug,\n comingSoon,\n comingSoonName,\n storePreviewToken,\n };\n if (!failed && !previewToken) {\n byHost.set(key, result, storeRef ? FOUND_TTL_MS : NOT_FOUND_TTL_MS);\n }\n return result;\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB;AAYzB,MAAM,eAAe;AACrB,MAAM,mBAAmB;AACzB,MAAM,YAAY;AAElB,MAAM,SAAS,IAAI,SAAsB,SAAS;AAG3C,SAAS,wBAA8B;AAC5C,SAAO,MAAM;AACf;AAOA,SAAS,kBACP,UACA,gBACe;AACf,QAAM,SAAS,IAAI,cAAc;AACjC,MAAI,CAAC,SAAS,SAAS,MAAM,EAAG,QAAO;AACvC,QAAM,QAAQ,SAAS,MAAM,GAAG,CAAC,OAAO,MAAM;AAC9C,SAAO,SAAS,CAAC,MAAM,SAAS,GAAG,IAAI,QAAQ;AACjD;AAYA,eAAsB,eACpB,MACA,SA+BC;AACD,MAAI,KAAK,SAAS,WAAW,KAAK,KAAK,SAAS,WAAW,GAAG;AAC5D,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,aAAa;AAAA,MACb,WAAW;AAAA,MACX,aAAa;AAAA,MACb,aAAa;AAAA,MACb,YAAY;AAAA,MACZ,gBAAgB;AAAA,MAChB,mBAAmB;AAAA,IACrB;AAAA,EACF;AAEA,QAAM,eAAe,SAAS,gBAAgB;AAC9C,QAAM,MAAM,KAAK,YAAY;AAC7B,MAAI,CAAC,cAAc;AACjB,UAAM,SAAS,OAAO,IAAI,GAAG;AAC7B,QAAI,OAAQ,QAAO;AAAA,EAC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sdk } from \"../sdk\";\nimport { isStoreSuspendedError } from \"./store-suspension\";\nimport {\n comingSoonStoreNameOf,\n isStoreComingSoonError,\n} from \"./store-coming-soon\";\nimport {\n SKIP_STORE_PREVIEW,\n STORE_PREVIEW_HEADER,\n} from \"./store-preview-cookie\";\nimport { publicConfig } from \"../config\";\nimport { TtlCache } from \"./ttl-cache\";\n\ntype StoreByHost = Awaited<ReturnType<typeof getStoreByHost>>;\n\n/**\n * How long a lookup is reused in this process. A merchant's change (custom\n * domain, external theme, suspension) reaches shoppers within this window on\n * top of the API's own Redis cache. Misses and suspensions expire sooner so\n * a new or re-enabled store shows up quickly. A failed lookup (API down) is\n * never cached: it would turn a blip into a run of 404s. Neither is a lookup\n * made with a preview token: its answer is that previewer's, not the public's.\n */\nconst FOUND_TTL_MS = 30_000;\nconst NOT_FOUND_TTL_MS = 10_000;\nconst MAX_HOSTS = 10_000;\n\nconst byHost = new TtlCache<StoreByHost>(MAX_HOSTS);\n\n/** Tests only: forget every cached lookup. */\nexport function clearStoreByHostCache(): void {\n byHost.clear();\n}\n\n/**\n * The store's subdomain label when `hostname` is `<label>.<platformDomain>`\n * (a single label, so `www.shop.<platform>` and `shop.evil<platform>` are\n * not subdomains), else null.\n */\nfunction platformSubdomain(\n hostname: string,\n platformDomain: string\n): string | null {\n const suffix = `.${platformDomain}`;\n if (!hostname.endsWith(suffix)) return null;\n const label = hostname.slice(0, -suffix.length);\n return label && !label.includes(\".\") ? label : null;\n}\n\n/**\n * Get store ref and domain info from host\n * Used by middleware and API routes to determine which store is being accessed\n *\n * With `previewToken` (a store or theme preview token), the token is sent as\n * `X-Store-Preview`, which opens a coming soon store, and the cache is\n * neither read nor written. Without one the lookup is the public answer for\n * the host: it is cached, and it carries `SKIP_STORE_PREVIEW` so the API\n * client never attaches the request's ambient preview token to it.\n */\nexport async function getStoreByHost(\n host: string,\n options?: { previewToken?: string | null }\n): Promise<{\n storeRef: string | null;\n domain: string | null;\n isSubDomain: boolean;\n // True when the backend identified a store for this host but rejected it\n // with STORE_SUSPENDED. There is no `ref` to route on in that case — the\n // 403 response carries no store-identifying payload — so the caller must\n // handle this without a storeRef (see proxy.ts, which rewrites to a\n // platform-level suspended page rather than `/store/<ref>`).\n suspended: boolean;\n // The live theme's URL when it is external (`storefront_url`), else null.\n // Null too when the API predates external themes.\n externalUrl: string | null;\n // A theme's preview host, p-<slug> (theme preview hosts): its slug.\n previewSlug: string | null;\n // True when the backend identified a store for this host but rejected it\n // with STORE_COMING_SOON: the merchant has not opened it yet. Like\n // `suspended`, there is no `ref` to route on, because the 403 carries only\n // `details.name`; the caller handles it without a storeRef (proxy.ts\n // rewrites to the platform-level coming soon page). A lookup with a valid\n // preview token gets the store instead.\n comingSoon: boolean;\n // The store's name from that 403's `details.name`, else null.\n comingSoonName: string | null;\n // On a theme's preview host only (previewSlug set): the API's short-lived\n // store preview token for a coming soon store, sent as X-Store-Preview in\n // place of the cookie on that host. Null everywhere else. It is cached\n // with the lookup, because the p-<slug> host is itself the capability, and\n // 30 s is far inside the token's 1 h.\n storePreviewToken: string | null;\n}> {\n if (host.includes(\"localhost\") || host.includes(\"127.0.0.1\")) {\n return {\n storeRef: null,\n domain: null,\n isSubDomain: false,\n suspended: false,\n externalUrl: null,\n previewSlug: null,\n comingSoon: false,\n comingSoonName: null,\n storePreviewToken: null,\n };\n }\n\n const previewToken = options?.previewToken || null;\n const key = host.toLowerCase();\n if (!previewToken) {\n const cached = byHost.get(key);\n if (cached) return cached;\n }\n\n let storeRef: string | null = null;\n let domain: string | null = null;\n let suspended = false;\n let externalUrl: string | null = null;\n let previewSlug: string | null = null;\n let comingSoon = false;\n let comingSoonName: string | null = null;\n let storePreviewToken: string | null = null;\n\n let failed = false;\n\n const hostname = key.split(\":\")[0]!;\n const platformDomain = (\n publicConfig().platformDomainSuffix ?? \"ecomsite.app\"\n ).toLowerCase();\n const subdomain = platformSubdomain(hostname, platformDomain);\n const isSubDomain = subdomain !== null;\n\n try {\n const lookupValue = subdomain ?? host;\n const foundStore = await sdk.stores.getByDomain(\n lookupValue,\n previewToken\n ? { headers: { [STORE_PREVIEW_HEADER]: previewToken } }\n : SKIP_STORE_PREVIEW\n );\n\n if (foundStore?.ref) {\n storeRef = foundStore.ref;\n // Only a verified custom domain: the subdomain redirects to `domain`,\n // and before DNS works that would take the store offline.\n domain =\n foundStore.config?.verified === true\n ? foundStore.config.custom_domain || null\n : null;\n externalUrl = foundStore.storefront_url || null;\n previewSlug = foundStore.preview_slug || null;\n // Never taken from a non-preview host.\n storePreviewToken = previewSlug\n ? foundStore.store_preview_token || null\n : null;\n }\n } catch (error) {\n if (isStoreSuspendedError(error)) {\n suspended = true;\n } else if (isStoreComingSoonError(error)) {\n comingSoon = true;\n comingSoonName = comingSoonStoreNameOf(error);\n } else {\n failed = true;\n console.error(\"Store not found for host:\", host);\n }\n }\n\n const result = {\n storeRef,\n domain,\n isSubDomain,\n suspended,\n externalUrl,\n previewSlug,\n comingSoon,\n comingSoonName,\n storePreviewToken,\n };\n if (!failed && !previewToken) {\n byHost.set(key, result, storeRef ? FOUND_TTL_MS : NOT_FOUND_TTL_MS);\n }\n return result;\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB;AAYzB,MAAM,eAAe;AACrB,MAAM,mBAAmB;AACzB,MAAM,YAAY;AAElB,MAAM,SAAS,IAAI,SAAsB,SAAS;AAG3C,SAAS,wBAA8B;AAC5C,SAAO,MAAM;AACf;AAOA,SAAS,kBACP,UACA,gBACe;AACf,QAAM,SAAS,IAAI,cAAc;AACjC,MAAI,CAAC,SAAS,SAAS,MAAM,EAAG,QAAO;AACvC,QAAM,QAAQ,SAAS,MAAM,GAAG,CAAC,OAAO,MAAM;AAC9C,SAAO,SAAS,CAAC,MAAM,SAAS,GAAG,IAAI,QAAQ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;AAChC,kBAAY;AAAA,IACd,WAAW,uBAAuB,KAAK,GAAG;AACxC,mBAAa;AACb,uBAAiB,sBAAsB,KAAK;AAAA,IAC9C,OAAO;AACL,eAAS;AACT,cAAQ,MAAM,6BAA6B,IAAI;AAAA,IACjD;AAAA,EACF;AAEA,QAAM,SAAS;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACA,MAAI,CAAC,UAAU,CAAC,cAAc;AAC5B,WAAO,IAAI,KAAK,QAAQ,WAAW,eAAe,gBAAgB;AAAA,EACpE;AACA,SAAO;AACT;","names":[]}
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@ecomweb/storefront-kit",
3
- "version": "0.11.0",
3
+ "version": "0.12.1",
4
4
  "description": "Headless storefront logic for ecomweb: auth, cart, checkout, API proxy",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "sideEffects": false,
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "https://github.com/travistech20/ecomweb-storefront.git",
10
+ "url": "https://github.com/ecomwebai/ecomweb-storefront.git",
11
11
  "directory": "packages/storefront-kit"
12
12
  },
13
13
  "main": "./dist/index.js",
@@ -47,7 +47,7 @@
47
47
  "currency.js": "^2.0.4",
48
48
  "server-only": "^0.0.1",
49
49
  "zod": "^4.1.12",
50
- "@ecomweb/sdk": "^0.11.0"
50
+ "@ecomweb/sdk": "^0.12.1"
51
51
  },
52
52
  "peerDependencies": {
53
53
  "next": ">=16",