@ecomweb/storefront-kit 0.6.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +28 -1
  2. package/dist/api/proxy.js +5 -1
  3. package/dist/api/proxy.js.map +1 -1
  4. package/dist/api/server-client.js +7 -4
  5. package/dist/api/server-client.js.map +1 -1
  6. package/dist/auth/cookies.js +51 -33
  7. package/dist/auth/cookies.js.map +1 -1
  8. package/dist/auth/error-copy.js +5 -1
  9. package/dist/auth/error-copy.js.map +1 -1
  10. package/dist/auth/route-handlers.js +2 -2
  11. package/dist/auth/route-handlers.js.map +1 -1
  12. package/dist/auth/session-refresh.js +11 -5
  13. package/dist/auth/session-refresh.js.map +1 -1
  14. package/dist/auth/session.js +8 -4
  15. package/dist/auth/session.js.map +1 -1
  16. package/dist/checkout/get-payment-state.js.map +1 -1
  17. package/dist/checkout/initiate-gateway-payment.js.map +1 -1
  18. package/dist/checkout/order-handoff.js +10 -1
  19. package/dist/checkout/order-handoff.js.map +1 -1
  20. package/dist/checkout/quote-changed.js +16 -0
  21. package/dist/checkout/quote-changed.js.map +1 -0
  22. package/dist/checkout/use-checkout.js +44 -7
  23. package/dist/checkout/use-checkout.js.map +1 -1
  24. package/dist/config/schema.js +12 -1
  25. package/dist/config/schema.js.map +1 -1
  26. package/dist/config/server.js +9 -2
  27. package/dist/config/server.js.map +1 -1
  28. package/dist/config.d.ts +3 -3
  29. package/dist/index.d.ts +167 -26
  30. package/dist/index.js +37 -1
  31. package/dist/index.js.map +1 -1
  32. package/dist/middleware/create-storefront-middleware.js +62 -26
  33. package/dist/middleware/create-storefront-middleware.js.map +1 -1
  34. package/dist/middleware.d.ts +2 -2
  35. package/dist/{mode-YNx2aOtQ.d.ts → mode-Lm9t4qzX.d.ts} +1 -1
  36. package/dist/orders/index.js +17 -1
  37. package/dist/orders/index.js.map +1 -1
  38. package/dist/orders/shipment-tracking.js +80 -0
  39. package/dist/orders/shipment-tracking.js.map +1 -0
  40. package/dist/promotions/use-promotion-validation.js +19 -16
  41. package/dist/promotions/use-promotion-validation.js.map +1 -1
  42. package/dist/{schema-Tc0qRs-Q.d.ts → schema-Dg0ZflMW.d.ts} +1 -0
  43. package/dist/server.d.ts +8 -2
  44. package/dist/server.js +2 -0
  45. package/dist/server.js.map +1 -1
  46. package/dist/shipping/format-shipping-option.js +28 -0
  47. package/dist/shipping/format-shipping-option.js.map +1 -1
  48. package/dist/shipping/messages.js +2 -0
  49. package/dist/shipping/messages.js.map +1 -1
  50. package/dist/shipping/option-id.js +7 -0
  51. package/dist/shipping/option-id.js.map +1 -0
  52. package/dist/shipping/shipping-calculation-reducer.js +61 -10
  53. package/dist/shipping/shipping-calculation-reducer.js.map +1 -1
  54. package/dist/shipping/use-shipping-calculation.js +38 -5
  55. package/dist/shipping/use-shipping-calculation.js.map +1 -1
  56. package/dist/stores/get-store-by-host.js +41 -6
  57. package/dist/stores/get-store-by-host.js.map +1 -1
  58. package/dist/stores/store-subdomain.js +25 -0
  59. package/dist/stores/store-subdomain.js.map +1 -0
  60. package/dist/stores/store-traffic.js +50 -0
  61. package/dist/stores/store-traffic.js.map +1 -0
  62. package/dist/stores/ttl-cache.js +34 -0
  63. package/dist/stores/ttl-cache.js.map +1 -0
  64. package/dist/theme/define.js.map +1 -1
  65. package/dist/theme/index.js.map +1 -1
  66. package/dist/theme/preview-bridge.js +33 -0
  67. package/dist/theme/preview-bridge.js.map +1 -0
  68. package/dist/theme/preview-cookie.js +13 -6
  69. package/dist/theme/preview-cookie.js.map +1 -1
  70. package/dist/theme/preview-host.js +7 -0
  71. package/dist/theme/preview-host.js.map +1 -0
  72. package/dist/theme/read-preview-host.js +10 -0
  73. package/dist/theme/read-preview-host.js.map +1 -0
  74. package/dist/theme/read-preview-token.js +5 -3
  75. package/dist/theme/read-preview-token.js.map +1 -1
  76. package/dist/theme/settings-context.js +14 -1
  77. package/dist/theme/settings-context.js.map +1 -1
  78. package/dist/theme.d.ts +65 -5
  79. package/package.json +2 -2
@@ -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} 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\";\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 (req.nextUrl.searchParams.has(THEME_PREVIEW_PARAM) || hasThemePreview(req))\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);\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 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\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();\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 let hostStoreRef: string | null = null;\n let hostResolved = false;\n\n let hostStoreSuspended = false;\n\n if (isMetadataFile && !hostIdentifiesStore) return NextResponse.next();\n\n if (hostIdentifiesStore) {\n try {\n const { storeRef, domain, isSubDomain, suspended, externalUrl } =\n await getStoreByHost(host);\n hostResolved = true;\n hostStoreRef = storeRef || null;\n hostStoreSuspended = suspended;\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();\n\n if (storeRef) {\n // If accessing via subdomain but custom domain exists, redirect to custom domain\n if (isSubDomain && domain && domain !== host) {\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();\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\n // A dashboard preview link: store its token in a cookie, then redirect to\n // the clean URL (themes spec §6.1).\n if (storeRef) {\n const preview = applyThemePreview(\n req,\n authCookiePath(storeRef, !!hostStoreRef)\n );\n if (preview) return preview;\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 = storeRef ? await refreshIfNearExpiry(req, storeRef) : 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 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 (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 if (hasThemePreview(req)) response.headers.set(\"x-robots-tag\", \"noindex\");\n\n if (rotated && storeRef) {\n // Same path the auth route handler writes with, from the same signal.\n writeAuthCookies(\n response,\n storeRef,\n rotated,\n authCookiePath(storeRef, !!hostStoreRef)\n );\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)) return NextResponse.next();\n\n const storeRef = publicConfig().storeRef as string;\n\n const preview = applyThemePreview(req, authCookiePath(storeRef, true));\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);\n const response = NextResponse.next({\n request: {\n headers: downstreamRequestHeaders(req, true, storeRef, rotated),\n },\n });\n\n if (hasThemePreview(req)) response.headers.set(\"x-robots-tag\", \"noindex\");\n if (rotated) {\n writeAuthCookies(\n response,\n storeRef,\n rotated,\n authCookiePath(storeRef, true)\n );\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, redirects, session refresh.\n * - single: redirects and session refresh only.\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,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;AAG/B,MAAM,iBAAiB;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAMA,MAAM,0BAA0B,CAAC,eAAe,cAAc;AAG9D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AAyB,KAAK,MAAM,UAAU,OAAO;AAAA,IAChE;AAAA,EACF,CAAC;AAED,MAAI,gBAAgB,GAAG,EAAG,UAAS,QAAQ,IAAI,gBAAgB,SAAS;AACxE,MAAI,SAAS;AACX;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA,eAAe,UAAU,IAAI;AAAA,IAC/B;AAAA,EACF;AACA,SAAO;AACT;AASO,SAAS,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} 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 { 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);\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 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);\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();\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 let hostStoreRef: string | null = null;\n let hostResolved = false;\n\n let hostStoreSuspended = false;\n // A theme's preview host (theme preview hosts): the theme's slug.\n let previewSlug: string | null = null;\n\n if (isMetadataFile && !hostIdentifiesStore) return NextResponse.next();\n\n if (hostIdentifiesStore) {\n try {\n const lookup = await getStoreByHost(host);\n const { storeRef, domain, isSubDomain, suspended, externalUrl } = lookup;\n hostResolved = true;\n hostStoreRef = storeRef || null;\n hostStoreSuspended = suspended;\n previewSlug = storeRef ? lookup.previewSlug : 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();\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();\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).\n const cookiePath = storeRef ? authCookiePath(storeRef, !!hostStoreRef) : null;\n if (storeRef && cookiePath) {\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\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 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 (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 if (previewSlug || (cookiePath && hasThemePreview(req, cookiePath))) {\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)) return NextResponse.next();\n\n const storeRef = publicConfig().storeRef as string;\n\n const cookiePath = authCookiePath(storeRef, true);\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))\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, redirects, session refresh.\n * - single: redirects and session refresh only.\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,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,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;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Y,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,6 +1,6 @@
1
1
  import { NextRequest, NextResponse } from 'next/server';
2
- import { S as StorefrontMode } from './mode-YNx2aOtQ.js';
3
- import './schema-Tc0qRs-Q.js';
2
+ import { S as StorefrontMode } from './mode-Lm9t4qzX.js';
3
+ import './schema-Dg0ZflMW.js';
4
4
  import 'zod';
5
5
 
6
6
  /**
@@ -1,4 +1,4 @@
1
- import { E as EnvSource } from './schema-Tc0qRs-Q.js';
1
+ import { E as EnvSource } from './schema-Dg0ZflMW.js';
2
2
 
3
3
  /**
4
4
  * multi: the shared platform storefront, every store under /store/<ref> or
@@ -1,6 +1,22 @@
1
1
  export * from "./types.js";
2
2
  import { publicOrdersApi } from "./api-client.js";
3
+ import {
4
+ SHIPMENT_STATUS_LABELS,
5
+ TRACKING_MESSAGES,
6
+ canCustomerCancel,
7
+ deriveShipmentTracking,
8
+ isCarrierShipment,
9
+ isHandedToCarrier,
10
+ shipmentEventLabel
11
+ } from "./shipment-tracking.js";
3
12
  export {
4
- publicOrdersApi
13
+ SHIPMENT_STATUS_LABELS,
14
+ TRACKING_MESSAGES,
15
+ canCustomerCancel,
16
+ deriveShipmentTracking,
17
+ isCarrierShipment,
18
+ isHandedToCarrier,
19
+ publicOrdersApi,
20
+ shipmentEventLabel
5
21
  };
6
22
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/orders/index.ts"],"sourcesContent":["// Orders API - Pure API Client Architecture\n// Store-based objects pattern - All operations are store-scoped\n// All operations use backend API exclusively - no direct database calls\n// Supabase used only for auth and storage\n\n// Types (sourced from consolidated interface as single source of truth)\nexport * from \"./types\";\n\n// API Clients (store-scoped operations)\nexport { publicOrdersApi } from \"./api-client\";\n"],"mappings":"AAMA,cAAc;AAGd,SAAS,uBAAuB;","names":[]}
1
+ {"version":3,"sources":["../../src/orders/index.ts"],"sourcesContent":["// Orders API - Pure API Client Architecture\n// Store-based objects pattern - All operations are store-scoped\n// All operations use backend API exclusively - no direct database calls\n// Supabase used only for auth and storage\n\n// Types (sourced from consolidated interface as single source of truth)\nexport * from \"./types\";\n\n// API Clients (store-scoped operations)\nexport { publicOrdersApi } from \"./api-client\";\n\n// Shipment tracking view and customer cancel rule\nexport {\n SHIPMENT_STATUS_LABELS,\n TRACKING_MESSAGES,\n canCustomerCancel,\n deriveShipmentTracking,\n isCarrierShipment,\n isHandedToCarrier,\n shipmentEventLabel,\n} from \"./shipment-tracking\";\nexport type { ShipmentTrackingView } from \"./shipment-tracking\";\n"],"mappings":"AAMA,cAAc;AAGd,SAAS,uBAAuB;AAGhC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;","names":[]}
@@ -0,0 +1,80 @@
1
+ const SHIPMENT_STATUS_LABELS = {
2
+ booked: "\u0110\xE3 t\u1EA1o v\u1EADn \u0111\u01A1n",
3
+ picked_up: "\u0110\xE3 l\u1EA5y h\xE0ng",
4
+ in_transit: "\u0110ang v\u1EADn chuy\u1EC3n",
5
+ out_for_delivery: "\u0110ang giao h\xE0ng",
6
+ delivered: "\u0110\xE3 giao",
7
+ failed: "Giao h\xE0ng th\u1EA5t b\u1EA1i",
8
+ returned: "\u0110\xE3 ho\xE0n h\xE0ng",
9
+ cancelled: "\u0110\xE3 h\u1EE7y"
10
+ };
11
+ const TRACKING_MESSAGES = {
12
+ title: "V\u1EADn chuy\u1EC3n",
13
+ trackingNumber: "M\xE3 v\u1EADn \u0111\u01A1n",
14
+ trackLink: "Theo d\xF5i \u0111\u01A1n h\xE0ng",
15
+ handedToCarrier: "\u0110\u01A1n \u0111\xE3 \u0111\u01B0\u1EE3c giao cho h\xE3ng v\u1EADn chuy\u1EC3n",
16
+ noEvents: "Ch\u01B0a c\xF3 c\u1EADp nh\u1EADt t\u1EEB h\xE3ng v\u1EADn chuy\u1EC3n",
17
+ eventFallback: "C\u1EADp nh\u1EADt v\u1EADn chuy\u1EC3n"
18
+ };
19
+ const CANCELLABLE_STATUSES = ["pending", "confirmed", "processing"];
20
+ const ENDED_STATUSES = ["cancelled", "failed", "returned"];
21
+ function httpLinkOrNull(link) {
22
+ return link && /^https?:\/\//i.test(link.trim()) ? link.trim() : null;
23
+ }
24
+ function labelOrNull(status) {
25
+ if (!status) return null;
26
+ return Object.prototype.hasOwnProperty.call(SHIPMENT_STATUS_LABELS, status) ? SHIPMENT_STATUS_LABELS[status] : null;
27
+ }
28
+ function deriveShipmentTracking(order) {
29
+ const shipment = order.shipment;
30
+ if (shipment === null) return null;
31
+ if (shipment) {
32
+ return {
33
+ carrierName: shipment.carrier_name ?? null,
34
+ carrierLogoUrl: httpLinkOrNull(shipment.carrier_logo_url),
35
+ serviceName: shipment.service_name ?? null,
36
+ trackingNumber: shipment.tracking_number ?? null,
37
+ trackLink: httpLinkOrNull(shipment.track_link),
38
+ statusLabel: labelOrNull(shipment.status),
39
+ events: shipment.events ?? []
40
+ };
41
+ }
42
+ if (order.shipping_carrier || order.tracking_number) {
43
+ return {
44
+ carrierName: order.shipping_carrier ?? null,
45
+ carrierLogoUrl: null,
46
+ serviceName: null,
47
+ trackingNumber: order.tracking_number ?? null,
48
+ trackLink: null,
49
+ statusLabel: null,
50
+ events: []
51
+ };
52
+ }
53
+ return null;
54
+ }
55
+ function canCustomerCancel(order) {
56
+ if (typeof order.can_cancel === "boolean") return order.can_cancel;
57
+ return CANCELLABLE_STATUSES.includes(order.order_status);
58
+ }
59
+ function isHandedToCarrier(order) {
60
+ const status = order.shipment?.status;
61
+ return !!status && !ENDED_STATUSES.includes(status);
62
+ }
63
+ function isCarrierShipment(order) {
64
+ return order.shipment?.status != null;
65
+ }
66
+ function shipmentEventLabel(event) {
67
+ const label = event.label?.trim();
68
+ if (label) return label;
69
+ return labelOrNull(event.status) ?? TRACKING_MESSAGES.eventFallback;
70
+ }
71
+ export {
72
+ SHIPMENT_STATUS_LABELS,
73
+ TRACKING_MESSAGES,
74
+ canCustomerCancel,
75
+ deriveShipmentTracking,
76
+ isCarrierShipment,
77
+ isHandedToCarrier,
78
+ shipmentEventLabel
79
+ };
80
+ //# sourceMappingURL=shipment-tracking.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/orders/shipment-tracking.ts"],"sourcesContent":["import type { Order, OrderShipmentSummary, ShipmentStatus } from \"@ecomweb/sdk\";\n\n/** The API's SHIPMENT_STATUS_LABEL_VI, copied exactly so badge and events agree. */\nexport const SHIPMENT_STATUS_LABELS: Record<ShipmentStatus, string> = {\n booked: \"Đã tạo vận đơn\",\n picked_up: \"Đã lấy hàng\",\n in_transit: \"Đang vận chuyển\",\n out_for_delivery: \"Đang giao hàng\",\n delivered: \"Đã giao\",\n failed: \"Giao hàng thất bại\",\n returned: \"Đã hoàn hàng\",\n cancelled: \"Đã hủy\",\n};\n\nexport const TRACKING_MESSAGES = {\n title: \"Vận chuyển\",\n trackingNumber: \"Mã vận đơn\",\n trackLink: \"Theo dõi đơn hàng\",\n handedToCarrier: \"Đơn đã được giao cho hãng vận chuyển\",\n noEvents: \"Chưa có cập nhật từ hãng vận chuyển\",\n eventFallback: \"Cập nhật vận chuyển\",\n} as const;\n\nexport interface ShipmentTrackingView {\n carrierName: string | null;\n carrierLogoUrl: string | null;\n serviceName: string | null;\n trackingNumber: string | null;\n trackLink: string | null;\n statusLabel: string | null;\n events: OrderShipmentSummary[\"events\"];\n}\n\nconst CANCELLABLE_STATUSES = [\"pending\", \"confirmed\", \"processing\"];\nconst ENDED_STATUSES: string[] = [\"cancelled\", \"failed\", \"returned\"];\n\nfunction httpLinkOrNull(link: string | null | undefined): string | null {\n return link && /^https?:\\/\\//i.test(link.trim()) ? link.trim() : null;\n}\n\nfunction labelOrNull(status: string | null | undefined): string | null {\n if (!status) return null;\n return Object.prototype.hasOwnProperty.call(SHIPMENT_STATUS_LABELS, status)\n ? SHIPMENT_STATUS_LABELS[status as ShipmentStatus]\n : null;\n}\n\nexport function deriveShipmentTracking(\n order: Order,\n): ShipmentTrackingView | null {\n const shipment = order.shipment;\n // An explicit `shipment: null` means the API decided there is nothing to show\n // (e.g. a cancelled waybill); the order's own fields are only a fallback for\n // an older API that does not send `shipment` at all.\n if (shipment === null) return null;\n if (shipment) {\n return {\n carrierName: shipment.carrier_name ?? null,\n carrierLogoUrl: httpLinkOrNull(shipment.carrier_logo_url),\n serviceName: shipment.service_name ?? null,\n trackingNumber: shipment.tracking_number ?? null,\n trackLink: httpLinkOrNull(shipment.track_link),\n statusLabel: labelOrNull(shipment.status),\n events: shipment.events ?? [],\n };\n }\n if (order.shipping_carrier || order.tracking_number) {\n return {\n carrierName: order.shipping_carrier ?? null,\n carrierLogoUrl: null,\n serviceName: null,\n trackingNumber: order.tracking_number ?? null,\n trackLink: null,\n statusLabel: null,\n events: [],\n };\n }\n return null;\n}\n\nexport function canCustomerCancel(order: Order): boolean {\n if (typeof order.can_cancel === \"boolean\") return order.can_cancel;\n return CANCELLABLE_STATUSES.includes(order.order_status);\n}\n\nexport function isHandedToCarrier(order: Order): boolean {\n const status = order.shipment?.status;\n return !!status && !ENDED_STATUSES.includes(status);\n}\n\n/**\n * True only for a carrier-booked shipment. The API also sends `order.shipment`\n * for a manual shipment (carrier and tracking number typed by the merchant),\n * with `status: null` and no events; that one has no carrier timeline to show.\n */\nexport function isCarrierShipment(order: Order): boolean {\n return order.shipment?.status != null;\n}\n\n/**\n * The text of one tracking event. A blank label falls back to the event's own\n * status label when it carries a known one, else to neutral copy -- never the\n * shipment's current status, which is not what that event reported.\n */\nexport function shipmentEventLabel(event: {\n label?: string | null;\n status?: string | null;\n}): string {\n const label = event.label?.trim();\n if (label) return label;\n return labelOrNull(event.status) ?? TRACKING_MESSAGES.eventFallback;\n}\n"],"mappings":"AAGO,MAAM,yBAAyD;AAAA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AAAA,EACF;AACA,SAAO;AACT;AAEO,SAAS,kBAAkB,OAAuB;AACvD,MAAI,OAAO,MAAM,eAAe,UAAW,QAAO,MAAM;AACxD,SAAO,qBAAqB,SAAS,MAAM,YAAY;AACzD;AAEO,SAAS,kBAAkB,OAAuB;AACvD,QAAM,SAAS,MAAM,UAAU;AAC/B,SAAO,CAAC,CAAC,UAAU,CAAC,eAAe,SAAS,MAAM;AACpD;AAOO,SAAS,kBAAkB,OAAuB;AACvD,SAAO,MAAM,UAAU,UAAU;AACnC;AAOO,SAAS,mBAAmB,OAGxB;AACT,QAAM,QAAQ,MAAM,OAAO,KAAK;AAChC,MAAI,MAAO,QAAO;AAClB,SAAO,YAAY,MAAM,MAAM,KAAK,kBAAkB;AACxD;","names":[]}
@@ -1,6 +1,8 @@
1
1
  import { sdk } from "../sdk.js";
2
2
  import { useState, useCallback, useEffect, useRef } from "react";
3
3
  import { useNotify } from "../notices.js";
4
+ class PromotionRejected extends Error {
5
+ }
4
6
  function usePromotionValidation({
5
7
  storeRef,
6
8
  items,
@@ -23,22 +25,21 @@ function usePromotionValidation({
23
25
  setIsValidatingPromo(true);
24
26
  setPromoError("");
25
27
  try {
26
- const result = await sdk.promotions.validate(
27
- storeRef,
28
- {
29
- code: codeToValidate.trim(),
30
- items: items.map((item) => ({
31
- product_id: item.productId,
32
- variant_id: item.variantId ?? void 0,
33
- quantity: item.quantity,
34
- price: item.price
35
- })),
36
- subtotal,
37
- shipping_fee: shippingFee
38
- }
39
- );
28
+ const result = await sdk.promotions.validate(storeRef, {
29
+ code: codeToValidate.trim(),
30
+ items: items.map((item) => ({
31
+ product_id: item.productId,
32
+ variant_id: item.variantId ?? void 0,
33
+ quantity: item.quantity,
34
+ price: item.price
35
+ })),
36
+ subtotal,
37
+ shipping_fee: shippingFee
38
+ });
40
39
  if (!result.success) {
41
- throw new Error(result.message || "M\xE3 khuy\u1EBFn m\xE3i kh\xF4ng h\u1EE3p l\u1EC7");
40
+ throw new PromotionRejected(
41
+ result.message || "M\xE3 khuy\u1EBFn m\xE3i kh\xF4ng h\u1EE3p l\u1EC7"
42
+ );
42
43
  }
43
44
  const promotionWithCode = {
44
45
  ...result.promotion,
@@ -53,7 +54,9 @@ function usePromotionValidation({
53
54
  description: `${result.promotion?.name || ""} \u0111\xE3 \u0111\u01B0\u1EE3c \xE1p d\u1EE5ng`
54
55
  });
55
56
  } catch (error) {
56
- console.error("Failed to validate promotion code:", error);
57
+ if (!(error instanceof PromotionRejected)) {
58
+ console.error("Failed to validate promotion code:", error);
59
+ }
57
60
  setPromoError(
58
61
  error instanceof Error ? error.message : "M\xE3 khuy\u1EBFn m\xE3i kh\xF4ng h\u1EE3p l\u1EC7"
59
62
  );
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/promotions/use-promotion-validation.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { useState, useCallback, useEffect, useRef } from \"react\";\nimport { useNotify } from \"../notices\";\n\ninterface CartItem {\n productId: number;\n variantId: number | null;\n quantity: number;\n price: number;\n}\n\ninterface UsePromotionValidationProps {\n storeRef: string;\n items: CartItem[];\n subtotal: number;\n shippingFee: number;\n}\n\nexport function usePromotionValidation({\n storeRef,\n items,\n subtotal,\n shippingFee,\n}: UsePromotionValidationProps) {\n const [promoCode, setPromoCode] = useState<string>(\"\");\n const [appliedPromotion, setAppliedPromotion] = useState<any>(null);\n // Computed by the API against the shipping fee we sent; the same number the\n // server uses when the order is placed, so we never derive it ourselves.\n const [shippingDiscount, setShippingDiscount] = useState<number>(0);\n const [isValidatingPromo, setIsValidatingPromo] = useState(false);\n const [promoError, setPromoError] = useState<string>(\"\");\n const notify = useNotify();\n\n // Validate promotion code with specific code\n const validatePromoCodeWithCode = useCallback(\n async (code?: string) => {\n const codeToValidate = code || promoCode;\n\n if (!codeToValidate.trim()) {\n setPromoError(\"Vui lòng nhập mã khuyến mãi\");\n return;\n }\n\n setIsValidatingPromo(true);\n setPromoError(\"\");\n\n try {\n const result = await sdk.promotions.validate(\n storeRef,\n {\n code: codeToValidate.trim(),\n items: items.map(item => ({\n product_id: item.productId,\n variant_id: item.variantId ?? undefined,\n quantity: item.quantity,\n price: item.price,\n })),\n subtotal: subtotal,\n shipping_fee: shippingFee,\n }\n );\n\n if (!result.success) {\n throw new Error(result.message || \"Mã khuyến mãi không hợp lệ\");\n }\n\n // Add code to promotion object for tracking\n const promotionWithCode = {\n ...result.promotion,\n code: codeToValidate.trim(),\n };\n setAppliedPromotion(promotionWithCode);\n setShippingDiscount(result.shipping_discount ?? 0);\n notify({\n kind: \"success\",\n code: \"promotion.applied\",\n title: \"Áp dụng mã khuyến mãi thành công\",\n description: `${result.promotion?.name || \"\"} đã được áp dụng`,\n });\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to validate promotion code:\", error);\n setPromoError(\n error instanceof Error ? error.message : \"Mã khuyến mãi không hợp lệ\"\n );\n setAppliedPromotion(null);\n setShippingDiscount(0);\n } finally {\n setIsValidatingPromo(false);\n }\n },\n [storeRef, items, subtotal, shippingFee, promoCode, notify]\n );\n\n // The server computes the shipping discount against the shipping fee we sent\n // it, so the number goes stale the moment the fee changes (new address, new\n // method). Re-ask rather than recomputing locally — a local recomputation is\n // exactly the duplicated money logic this hook exists to avoid.\n const revalidateRef = useRef(validatePromoCodeWithCode);\n revalidateRef.current = validatePromoCodeWithCode;\n\n useEffect(() => {\n const code = appliedPromotion?.code;\n if (!code) return;\n void revalidateRef.current(code);\n // Intentionally keyed on the fee alone: including the callback would\n // re-run this on every render, and including appliedPromotion would loop\n // on the state this very effect writes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [shippingFee]);\n\n // Validate promotion code\n const validatePromoCode = useCallback(async () => {\n await validatePromoCodeWithCode();\n }, [validatePromoCodeWithCode]);\n\n // Remove applied promotion\n const removePromoCode = useCallback(() => {\n setPromoCode(\"\");\n setAppliedPromotion(null);\n setShippingDiscount(0);\n setPromoError(\"\");\n }, []);\n\n // Apply promotion from suggestion\n const applyPromotionFromSuggestion = useCallback(\n async (code: string) => {\n setPromoCode(code);\n // Use the code directly instead of relying on state\n await validatePromoCodeWithCode(code);\n },\n [validatePromoCodeWithCode]\n );\n\n return {\n promoCode,\n appliedPromotion,\n shippingDiscount,\n isValidatingPromo,\n promoError,\n setPromoCode,\n validatePromoCode,\n removePromoCode,\n applyPromotionFromSuggestion,\n };\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,UAAU,aAAa,WAAW,cAAc;AACzD,SAAS,iBAAiB;AAgBnB,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAgC;AAC9B,QAAM,CAAC,WAAW,YAAY,IAAI,SAAiB,EAAE;AACrD,QAAM,CAAC,kBAAkB,mBAAmB,IAAI,SAAc,IAAI;AAGlE,QAAM,CAAC,kBAAkB,mBAAmB,IAAI,SAAiB,CAAC;AAClE,QAAM,CAAC,mBAAmB,oBAAoB,IAAI,SAAS,KAAK;AAChE,QAAM,CAAC,YAAY,aAAa,IAAI,SAAiB,EAAE;AACvD,QAAM,SAAS,UAAU;AAGzB,QAAM,4BAA4B;AAAA,IAChC,OAAO,SAAkB;AACvB,YAAM,iBAAiB,QAAQ;AAE/B,UAAI,CAAC,eAAe,KAAK,GAAG;AAC1B,sBAAc,gDAA6B;AAC3C;AAAA,MACF;AAEA,2BAAqB,IAAI;AACzB,oBAAc,EAAE;AAEhB,UAAI;AACF,cAAM,SAAS,MAAM,IAAI,WAAW;AAAA,UAClC;AAAA,UACA;AAAA,YACE,MAAM,eAAe,KAAK;AAAA,YAC1B,OAAO,MAAM,IAAI,WAAS;AAAA,cACxB,YAAY,KAAK;AAAA,cACjB,YAAY,KAAK,aAAa;AAAA,cAC9B,UAAU,KAAK;AAAA,cACf,OAAO,KAAK;AAAA,YACd,EAAE;AAAA,YACF;AAAA,YACA,cAAc;AAAA,UAChB;AAAA,QACF;AAEA,YAAI,CAAC,OAAO,SAAS;AACnB,gBAAM,IAAI,M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,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/promotions/use-promotion-validation.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { useState, useCallback, useEffect, useRef } from \"react\";\nimport { useNotify } from \"../notices\";\n\ninterface CartItem {\n productId: number;\n variantId: number | null;\n quantity: number;\n price: number;\n}\n\ninterface UsePromotionValidationProps {\n storeRef: string;\n items: CartItem[];\n subtotal: number;\n shippingFee: number;\n}\n\n/** The API answered: this code does not apply (unknown, expired, not eligible). */\nclass PromotionRejected extends Error {}\n\nexport function usePromotionValidation({\n storeRef,\n items,\n subtotal,\n shippingFee,\n}: UsePromotionValidationProps) {\n const [promoCode, setPromoCode] = useState<string>(\"\");\n const [appliedPromotion, setAppliedPromotion] = useState<any>(null);\n // Computed by the API against the shipping fee we sent; the same number the\n // server uses when the order is placed, so we never derive it ourselves.\n const [shippingDiscount, setShippingDiscount] = useState<number>(0);\n const [isValidatingPromo, setIsValidatingPromo] = useState(false);\n const [promoError, setPromoError] = useState<string>(\"\");\n const notify = useNotify();\n\n // Validate promotion code with specific code\n const validatePromoCodeWithCode = useCallback(\n async (code?: string) => {\n const codeToValidate = code || promoCode;\n\n if (!codeToValidate.trim()) {\n setPromoError(\"Vui lòng nhập mã khuyến mãi\");\n return;\n }\n\n setIsValidatingPromo(true);\n setPromoError(\"\");\n\n try {\n const result = await sdk.promotions.validate(storeRef, {\n code: codeToValidate.trim(),\n items: items.map(item => ({\n product_id: item.productId,\n variant_id: item.variantId ?? undefined,\n quantity: item.quantity,\n price: item.price,\n })),\n subtotal: subtotal,\n shipping_fee: shippingFee,\n });\n\n if (!result.success) {\n throw new PromotionRejected(\n result.message || \"Mã khuyến mãi không hợp lệ\"\n );\n }\n\n // Add code to promotion object for tracking\n const promotionWithCode = {\n ...result.promotion,\n code: codeToValidate.trim(),\n };\n setAppliedPromotion(promotionWithCode);\n setShippingDiscount(result.shipping_discount ?? 0);\n notify({\n kind: \"success\",\n code: \"promotion.applied\",\n title: \"Áp dụng mã khuyến mãi thành công\",\n description: `${result.promotion?.name || \"\"} đã được áp dụng`,\n });\n } catch (error) {\n // A rejected code is an ordinary answer, shown to the shopper; only\n // unexpected failures (network, server) are worth logging.\n if (!(error instanceof PromotionRejected)) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to validate promotion code:\", error);\n }\n setPromoError(\n error instanceof Error ? error.message : \"Mã khuyến mãi không hợp lệ\"\n );\n setAppliedPromotion(null);\n setShippingDiscount(0);\n } finally {\n setIsValidatingPromo(false);\n }\n },\n [storeRef, items, subtotal, shippingFee, promoCode, notify]\n );\n\n // The server computes the shipping discount against the shipping fee we sent\n // it, so the number goes stale the moment the fee changes (new address, new\n // method). Re-ask rather than recomputing locally — a local recomputation is\n // exactly the duplicated money logic this hook exists to avoid.\n const revalidateRef = useRef(validatePromoCodeWithCode);\n revalidateRef.current = validatePromoCodeWithCode;\n\n useEffect(() => {\n const code = appliedPromotion?.code;\n if (!code) return;\n void revalidateRef.current(code);\n // Intentionally keyed on the fee alone: including the callback would\n // re-run this on every render, and including appliedPromotion would loop\n // on the state this very effect writes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [shippingFee]);\n\n // Validate promotion code\n const validatePromoCode = useCallback(async () => {\n await validatePromoCodeWithCode();\n }, [validatePromoCodeWithCode]);\n\n // Remove applied promotion\n const removePromoCode = useCallback(() => {\n setPromoCode(\"\");\n setAppliedPromotion(null);\n setShippingDiscount(0);\n setPromoError(\"\");\n }, []);\n\n // Apply promotion from suggestion\n const applyPromotionFromSuggestion = useCallback(\n async (code: string) => {\n setPromoCode(code);\n // Use the code directly instead of relying on state\n await validatePromoCodeWithCode(code);\n },\n [validatePromoCodeWithCode]\n );\n\n return {\n promoCode,\n appliedPromotion,\n shippingDiscount,\n isValidatingPromo,\n promoError,\n setPromoCode,\n validatePromoCode,\n removePromoCode,\n applyPromotionFromSuggestion,\n };\n}\n"],"mappings":"AAAA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AM;AAAA,UACN,OAAO;AAAA,UACP,aAAa,GAAG,OAAO,WAAW,QAAQ,EAAE;AAAA,QAC9C,CAAC;AAAA,MACH,SAAS,OAAO;AAGd,YAAI,EAAE,iBAAiB,oBAAoB;AAEzC,kBAAQ,MAAM,sCAAsC,KAAK;AAAA,QAC3D;AACA;AAAA,UACE,iBAAiB,QAAQ,MAAM,UAAU;AAAA,QAC3C;AACA,4BAAoB,IAAI;AACxB,4BAAoB,CAAC;AAAA,MACvB,UAAE;AACA,6BAAqB,KAAK;AAAA,MAC5B;AAAA,IACF;AAAA,IACA,CAAC,UAAU,OAAO,UAAU,aAAa,WAAW,MAAM;AAAA,EAC5D;AAMA,QAAM,gBAAgB,OAAO,yBAAyB;AACtD,gBAAc,UAAU;AAExB,YAAU,MAAM;AACd,UAAM,OAAO,kBAAkB;AAC/B,QAAI,CAAC,KAAM;AACX,SAAK,cAAc,QAAQ,IAAI;AAAA,EAKjC,GAAG,CAAC,WAAW,CAAC;AAGhB,QAAM,oBAAoB,YAAY,YAAY;AAChD,UAAM,0BAA0B;AAAA,EAClC,GAAG,CAAC,yBAAyB,CAAC;AAG9B,QAAM,kBAAkB,YAAY,MAAM;AACxC,iBAAa,EAAE;AACf,wBAAoB,IAAI;AACxB,wBAAoB,CAAC;AACrB,kBAAc,EAAE;AAAA,EAClB,GAAG,CAAC,CAAC;AAGL,QAAM,+BAA+B;AAAA,IACnC,OAAO,SAAiB;AACtB,mBAAa,IAAI;AAEjB,YAAM,0BAA0B,IAAI;AAAA,IACtC;AAAA,IACA,CAAC,yBAAyB;AAAA,EAC5B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
@@ -43,6 +43,7 @@ declare const serverConfigSchema: z.ZodObject<{
43
43
  "x-forwarded-for": "x-forwarded-for";
44
44
  "cf-connecting-ip": "cf-connecting-ip";
45
45
  }>;
46
+ storeTrafficLogPerMinute: z.ZodNumber;
46
47
  }, z.core.$strip>;
47
48
  type ServerConfig = z.infer<typeof serverConfigSchema>;
48
49
  declare class ConfigError extends Error {
package/dist/server.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { NextRequest } from 'next/server';
2
2
  import { CurrentIdentity } from '@ecomweb/sdk';
3
- import { E as EnvSource, S as ServerConfig } from './schema-Tc0qRs-Q.js';
3
+ import { E as EnvSource, S as ServerConfig } from './schema-Dg0ZflMW.js';
4
4
  import 'zod';
5
5
 
6
6
  /**
@@ -58,6 +58,12 @@ declare function resolveRootStoreRef(): Promise<string | null>;
58
58
  /** The open theme preview's token, if any (server components only). */
59
59
  declare function readThemePreviewToken(): Promise<string | null>;
60
60
 
61
+ /**
62
+ * The theme preview host's slug when this request came in on one (server
63
+ * components only); the middleware sets it, never the client.
64
+ */
65
+ declare function readPreviewHostSlug(): Promise<string | null>;
66
+
61
67
  /**
62
68
  * Where the store layout sends a request when the published theme is
63
69
  * external, else null: the backstop for path-based access
@@ -76,4 +82,4 @@ declare function externalThemeRedirectFor(request: {
76
82
  external_url?: string | null;
77
83
  } | null | undefined, previewOpen: boolean): string | null;
78
84
 
79
- export { type CustomerIdentity, type RouteContext, type RouteHandler, createAuthRoutes, createBackendProxy, externalThemeRedirectFor, hasCustomerSession, parseServerConfig, readThemePreviewToken, requireSession, resolveRootStoreRef, serverConfig };
85
+ export { type CustomerIdentity, type RouteContext, type RouteHandler, createAuthRoutes, createBackendProxy, externalThemeRedirectFor, hasCustomerSession, parseServerConfig, readPreviewHostSlug, readThemePreviewToken, requireSession, resolveRootStoreRef, serverConfig };
package/dist/server.js CHANGED
@@ -8,6 +8,7 @@ import { hasCustomerSession } from "./auth/session.js";
8
8
  import { parseServerConfig, serverConfig } from "./config/server.js";
9
9
  import { resolveRootStoreRef } from "./store-scope/root.js";
10
10
  import { readThemePreviewToken } from "./theme/read-preview-token.js";
11
+ import { readPreviewHostSlug } from "./theme/read-preview-host.js";
11
12
  import { externalThemeRedirectFor } from "./theme/external-storefront.js";
12
13
  export {
13
14
  createAuthRoutes,
@@ -15,6 +16,7 @@ export {
15
16
  externalThemeRedirectFor,
16
17
  hasCustomerSession,
17
18
  parseServerConfig,
19
+ readPreviewHostSlug,
18
20
  readThemePreviewToken,
19
21
  requireSession,
20
22
  resolveRootStoreRef,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server.ts"],"sourcesContent":["// @ecomweb/storefront-kit/server: server-only handlers and helpers.\nimport \"server-only\";\n\nexport {\n createAuthRoutes,\n createBackendProxy,\n requireSession,\n} from \"./server/routes\";\nexport type {\n CustomerIdentity,\n RouteContext,\n RouteHandler,\n} from \"./server/routes\";\nexport { hasCustomerSession } from \"./auth/session\";\nexport { parseServerConfig, serverConfig } from \"./config/server\";\nexport { resolveRootStoreRef } from \"./store-scope/root\";\nexport { readThemePreviewToken } from \"./theme/read-preview-token\";\nexport { externalThemeRedirectFor } from \"./theme/external-storefront\";\n"],"mappings":"AACA,OAAO;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,0BAA0B;AACnC,SAAS,mBAAmB,oBAAoB;AAChD,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AACtC,SAAS,gCAAgC;","names":[]}
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["// @ecomweb/storefront-kit/server: server-only handlers and helpers.\nimport \"server-only\";\n\nexport {\n createAuthRoutes,\n createBackendProxy,\n requireSession,\n} from \"./server/routes\";\nexport type {\n CustomerIdentity,\n RouteContext,\n RouteHandler,\n} from \"./server/routes\";\nexport { hasCustomerSession } from \"./auth/session\";\nexport { parseServerConfig, serverConfig } from \"./config/server\";\nexport { resolveRootStoreRef } from \"./store-scope/root\";\nexport { readThemePreviewToken } from \"./theme/read-preview-token\";\nexport { readPreviewHostSlug } from \"./theme/read-preview-host\";\nexport { externalThemeRedirectFor } from \"./theme/external-storefront\";\n"],"mappings":"AACA,OAAO;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,0BAA0B;AACnC,SAAS,mBAAmB,oBAAoB;AAChD,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS,gCAAgC;","names":[]}
@@ -1,11 +1,39 @@
1
1
  import { formatPrice } from "../currency.js";
2
+ import { formatShippingEstimate } from "./messages.js";
2
3
  function isFreeShippingRate(amount) {
3
4
  return amount === 0;
4
5
  }
5
6
  function formatShippingAmount(amount, freeLabel, locale, currency) {
6
7
  return isFreeShippingRate(amount) ? freeLabel : formatPrice(amount, locale, currency);
7
8
  }
9
+ function safeHttpUrl(url) {
10
+ if (!url) return null;
11
+ try {
12
+ const { protocol } = new URL(url);
13
+ return protocol === "http:" || protocol === "https:" ? url : null;
14
+ } catch {
15
+ return null;
16
+ }
17
+ }
18
+ function describeShippingOption(option) {
19
+ let eta = null;
20
+ if (option.estimated_label) {
21
+ eta = option.estimated_label;
22
+ } else if (option.estimated_days_min != null) {
23
+ eta = formatShippingEstimate(
24
+ option.estimated_days_min,
25
+ option.estimated_days_max ?? option.estimated_days_min
26
+ );
27
+ }
28
+ return {
29
+ title: option.display_name,
30
+ carrierName: option.carrier_name ? [option.carrier_name, option.carrier_service_name].filter(Boolean).join(" \xB7 ") : null,
31
+ carrierLogoUrl: safeHttpUrl(option.carrier_logo_url),
32
+ eta
33
+ };
34
+ }
8
35
  export {
36
+ describeShippingOption,
9
37
  formatShippingAmount,
10
38
  isFreeShippingRate
11
39
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/shipping/format-shipping-option.ts"],"sourcesContent":["import { formatPrice, type SupportedCurrency } from \"../currency\";\n\n/**\n * A free shipping rate is a VALUE comparison (amount === 0), not a rate\n * type the API tags for us. There is no \"FREE\" rate_type in the shipping\n * vocabulary on purpose — see @ecomweb/sdk's shipping types.\n */\nexport function isFreeShippingRate(amount: number): boolean {\n return amount === 0;\n}\n\n/**\n * Renders a shipping option's price for display: the free label when the\n * rate is free, the house money format otherwise.\n *\n * `freeLabel` is passed in (see lib/shipping/messages.ts) rather than\n * hardcoded here, so this stays a pure, generic function reachable from a\n * plain vitest spec.\n */\nexport function formatShippingAmount(\n amount: number,\n freeLabel: string,\n locale: string,\n currency: SupportedCurrency | string\n): string {\n return isFreeShippingRate(amount)\n ? freeLabel\n : formatPrice(amount, locale, currency);\n}\n"],"mappings":"AAAA,SAAS,mBAA2C;AAO7C,SAAS,mBAAmB,QAAyB;AAC1D,SAAO,WAAW;AACpB;AAUO,SAAS,qBACd,QACA,WACA,QACA,UACQ;AACR,SAAO,mBAAmB,MAAM,IAC5B,YACA,YAAY,QAAQ,QAAQ,QAAQ;AAC1C;","names":[]}
1
+ {"version":3,"sources":["../../src/shipping/format-shipping-option.ts"],"sourcesContent":["import type { ShippingOption } from \"@ecomweb/sdk\";\nimport { formatPrice, type SupportedCurrency } from \"../currency\";\nimport { formatShippingEstimate } from \"./messages\";\n\n/**\n * A free shipping rate is a VALUE comparison (amount === 0), not a rate\n * type the API tags for us. There is no \"FREE\" rate_type in the shipping\n * vocabulary on purpose — see @ecomweb/sdk's shipping types.\n */\nexport function isFreeShippingRate(amount: number): boolean {\n return amount === 0;\n}\n\n/**\n * Renders a shipping option's price for display: the free label when the\n * rate is free, the house money format otherwise.\n *\n * `freeLabel` is passed in (see lib/shipping/messages.ts) rather than\n * hardcoded here, so this stays a pure, generic function reachable from a\n * plain vitest spec.\n */\nexport function formatShippingAmount(\n amount: number,\n freeLabel: string,\n locale: string,\n currency: SupportedCurrency | string\n): string {\n return isFreeShippingRate(amount)\n ? freeLabel\n : formatPrice(amount, locale, currency);\n}\n\nexport interface ShippingOptionDisplay {\n title: string;\n carrierName: string | null;\n carrierLogoUrl: string | null;\n eta: string | null;\n}\n\n/** Carrier-provided URLs are untrusted: only http(s) may reach an <img src>. */\nfunction safeHttpUrl(url: string | null | undefined): string | null {\n if (!url) return null;\n try {\n const { protocol } = new URL(url);\n return protocol === \"http:\" || protocol === \"https:\" ? url : null;\n } catch {\n return null;\n }\n}\n\n/**\n * What an option row shows: title, carrier (when carrier-quoted) and an ETA.\n * The carrier's own label wins over the fixed-rate day range. The carrier\n * line names the service too: one carrier can offer several at one price.\n */\nexport function describeShippingOption(\n option: ShippingOption\n): ShippingOptionDisplay {\n let eta: string | null = null;\n if (option.estimated_label) {\n eta = option.estimated_label;\n } else if (option.estimated_days_min != null) {\n eta = formatShippingEstimate(\n option.estimated_days_min,\n option.estimated_days_max ?? option.estimated_days_min\n );\n }\n return {\n title: option.display_name,\n carrierName: option.carrier_name\n ? [option.carrier_name, option.carrier_service_name]\n .filter(Boolean)\n .join(\" · \")\n : null,\n carrierLogoUrl: safeHttpUrl(option.carrier_logo_url),\n eta,\n };\n}\n"],"mappings":"AACA,SAAS,mBAA2C;AACpD,SAAS,8BAA8B;AAOhC,SAAS,mBAAmB,QAAyB;AAC1D,SAAO,WAAW;AACpB;AAUO,SAAS,qBACd,QACA,WACA,QACA,UACQ;AACR,SAAO,mBAAmB,MAAM,IAC5B,YACA,YAAY,QAAQ,QAAQ,QAAQ;AAC1C;AAUA,SAAS,YAAY,KAA+C;AAClE,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,EAAE,SAAS,IAAI,IAAI,IAAI,GAAG;AAChC,WAAO,aAAa,WAAW,aAAa,WAAW,MAAM;AAAA,EAC/D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAOO,SAAS,uBACd,QACuB;AACvB,MAAI,MAAqB;AACzB,MAAI,OAAO,iBAAiB;AAC1B,UAAM,OAAO;AAAA,EACf,WAAW,OAAO,sBAAsB,MAAM;AAC5C,UAAM;AAAA,MACJ,OAAO;AAAA,MACP,OAAO,sBAAsB,OAAO;AAAA,IACtC;AAAA,EACF;AACA,SAAO;AAAA,IACL,OAAO,OAAO;AAAA,IACd,aAAa,OAAO,eAChB,CAAC,OAAO,cAAc,OAAO,oBAAoB,EAC9C,OAAO,OAAO,EACd,KAAK,QAAK,IACb;AAAA,IACJ,gBAAgB,YAAY,OAAO,gBAAgB;AAAA,IACnD;AAAA,EACF;AACF;","names":[]}
@@ -7,6 +7,8 @@ const SHIPPING_MESSAGES = Object.freeze({
7
7
  failedHint: "K\u1EBFt n\u1ED1i c\xF3 th\u1EC3 \u0111ang gi\xE1n \u0111o\u1EA1n. Vui l\xF2ng th\u1EED l\u1EA1i.",
8
8
  retry: "Th\u1EED l\u1EA1i",
9
9
  free: "Mi\u1EC5n ph\xED",
10
+ quoteChanged: "Ph\xED v\u1EADn chuy\u1EC3n \u0111\xE3 thay \u0111\u1ED5i",
11
+ quoteChangedHint: "Vui l\xF2ng ki\u1EC3m tra l\u1EA1i ph\xED v\u1EADn chuy\u1EC3n m\u1EDBi r\u1ED3i \u0111\u1EB7t h\xE0ng.",
10
12
  estimate: "D\u1EF1 ki\u1EBFn giao: {min} \u0111\u1EBFn {max} ng\xE0y"
11
13
  });
12
14
  function formatShippingEstimate(min, max) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/shipping/messages.ts"],"sourcesContent":["/**\n * Checkout shipping strings, extracted from the components that used to\n * hardcode them inline. This is NOT an i18n layer -- the storefront has no\n * i18n infrastructure (no next-intl, no locale routing, no message\n * catalog), and bootstrapping one is out of scope for a shipping-vocabulary\n * change. This just gets every shipping string into one place so a real\n * i18n task can source from here later instead of hunting through JSX.\n *\n * `estimate` is a template: interpolate `{min}` and `{max}` yourself.\n */\nexport const SHIPPING_MESSAGES = Object.freeze({\n title: \"Phương thức vận chuyển\",\n prompt: \"Vui lòng nhập địa chỉ giao hàng để xem phương thức vận chuyển\",\n empty: \"Không có phương thức vận chuyển phù hợp\",\n emptyHint:\n \"Vui lòng kiểm tra lại địa chỉ giao hàng hoặc liên hệ với cửa hàng.\",\n failed: \"Không thể tính phí vận chuyển\",\n failedHint: \"Kết nối có thể đang gián đoạn. Vui lòng thử lại.\",\n retry: \"Thử lại\",\n free: \"Miễn phí\",\n estimate: \"Dự kiến giao: {min} đến {max} ngày\",\n});\n\n/** Fills in the `{min}`/`{max}` placeholders in `SHIPPING_MESSAGES.estimate`. */\nexport function formatShippingEstimate(min: number, max: number): string {\n return SHIPPING_MESSAGES.estimate\n .replace(\"{min}\", String(min))\n .replace(\"{max}\", String(max));\n}\n"],"mappings":"AAUO,MAAM,oBAAoB,OAAO,OAAO;AAAA,EAC7C,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,WACE;AAAA,EACF,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,MAAM;AAAA,EACN,UAAU;AACZ,CAAC;AAGM,SAAS,uBAAuB,KAAa,KAAqB;AACvE,SAAO,kBAAkB,SACtB,QAAQ,SAAS,OAAO,GAAG,CAAC,EAC5B,QAAQ,SAAS,OAAO,GAAG,CAAC;AACjC;","names":[]}
1
+ {"version":3,"sources":["../../src/shipping/messages.ts"],"sourcesContent":["/**\n * Checkout shipping strings, extracted from the components that used to\n * hardcode them inline. This is NOT an i18n layer -- the storefront has no\n * i18n infrastructure (no next-intl, no locale routing, no message\n * catalog), and bootstrapping one is out of scope for a shipping-vocabulary\n * change. This just gets every shipping string into one place so a real\n * i18n task can source from here later instead of hunting through JSX.\n *\n * `estimate` is a template: interpolate `{min}` and `{max}` yourself.\n */\nexport const SHIPPING_MESSAGES = Object.freeze({\n title: \"Phương thức vận chuyển\",\n prompt: \"Vui lòng nhập địa chỉ giao hàng để xem phương thức vận chuyển\",\n empty: \"Không có phương thức vận chuyển phù hợp\",\n emptyHint:\n \"Vui lòng kiểm tra lại địa chỉ giao hàng hoặc liên hệ với cửa hàng.\",\n failed: \"Không thể tính phí vận chuyển\",\n failedHint: \"Kết nối có thể đang gián đoạn. Vui lòng thử lại.\",\n retry: \"Thử lại\",\n free: \"Miễn phí\",\n quoteChanged: \"Phí vận chuyển đã thay đổi\",\n quoteChangedHint: \"Vui lòng kiểm tra lại phí vận chuyển mới rồi đặt hàng.\",\n estimate: \"Dự kiến giao: {min} đến {max} ngày\",\n});\n\n/** Fills in the `{min}`/`{max}` placeholders in `SHIPPING_MESSAGES.estimate`. */\nexport function formatShippingEstimate(min: number, max: number): string {\n return SHIPPING_MESSAGES.estimate\n .replace(\"{min}\", String(min))\n .replace(\"{max}\", String(max));\n}\n"],"mappings":"AAUO,MAAM,oBAAoB,OAAO,OAAO;AAAA,EAC7C,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,WACE;AAAA,EACF,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,MAAM;AAAA,EACN,cAAc;AAAA,EACd,kBAAkB;AAAA,EAClB,UAAU;AACZ,CAAC;AAGM,SAAS,uBAAuB,KAAa,KAAqB;AACvE,SAAO,kBAAkB,SACtB,QAAQ,SAAS,OAAO,GAAG,CAAC,EAC5B,QAAQ,SAAS,OAAO,GAAG,CAAC;AACjC;","names":[]}
@@ -0,0 +1,7 @@
1
+ function optionIdOf(option) {
2
+ return option.option_id ?? String(option.rate_id);
3
+ }
4
+ export {
5
+ optionIdOf
6
+ };
7
+ //# sourceMappingURL=option-id.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/shipping/option-id.ts"],"sourcesContent":["import type { ShippingOption } from \"@ecomweb/sdk\";\n\n/**\n * The stable identity of a shipping option. Carrier-backed rates can offer\n * several options under one `rate_id`, so the API sends `option_id`; older\n * APIs don't, and `rate_id` alone is unique there.\n */\nexport function optionIdOf(option: ShippingOption): string {\n return option.option_id ?? String(option.rate_id);\n}\n"],"mappings":"AAOO,SAAS,WAAW,QAAgC;AACzD,SAAO,OAAO,aAAa,OAAO,OAAO,OAAO;AAClD;","names":[]}
@@ -1,12 +1,26 @@
1
+ import { optionIdOf } from "./option-id.js";
1
2
  const initialShippingCalculationState = {
2
3
  shippingFee: 0,
3
4
  isCalculatingShipping: false,
4
5
  hasCalculatedShipping: false,
5
6
  shippingOptions: [],
6
7
  selectedShippingRate: null,
8
+ selectedOptionId: null,
7
9
  requestId: 0,
8
10
  calculationFailed: false
9
11
  };
12
+ function selectFrom(options, preferId) {
13
+ const preferred = preferId === null ? void 0 : options.find((option) => optionIdOf(option) === preferId);
14
+ const chosen = preferred ?? options.reduce(
15
+ (best, option) => !best || option.amount < best.amount ? option : best,
16
+ null
17
+ );
18
+ return chosen ? {
19
+ optionId: optionIdOf(chosen),
20
+ rateId: chosen.rate_id,
21
+ fee: chosen.amount
22
+ } : { optionId: null, rateId: null, fee: 0 };
23
+ }
10
24
  function shippingCalculationReducer(state, action) {
11
25
  switch (action.type) {
12
26
  case "RESET":
@@ -24,18 +38,44 @@ function shippingCalculationReducer(state, action) {
24
38
  case "CALCULATION_SUCCEEDED": {
25
39
  if (action.requestId !== state.requestId) return state;
26
40
  const { options } = action;
27
- const first = options.length > 0 ? options[0] : null;
41
+ const picked = selectFrom(options, null);
28
42
  return {
29
43
  ...state,
30
44
  shippingOptions: options,
31
45
  hasCalculatedShipping: true,
32
46
  isCalculatingShipping: false,
33
- // Auto-select the first option. This also revalidates the
47
+ // Auto-select the cheapest option. This also revalidates the
34
48
  // selection on every successful recalculation: it is always
35
- // replaced with a rate_id guaranteed to belong to THIS response,
36
- // so a stale rate from an earlier quote can never linger.
37
- selectedShippingRate: first ? first.rate_id : null,
38
- shippingFee: first ? first.amount : 0,
49
+ // replaced with an option guaranteed to belong to THIS response,
50
+ // so a stale selection from an earlier quote can never linger.
51
+ selectedOptionId: picked.optionId,
52
+ selectedShippingRate: picked.rateId,
53
+ shippingFee: picked.fee,
54
+ calculationFailed: false
55
+ };
56
+ }
57
+ case "QUOTE_REPLACED": {
58
+ if (action.requestId !== state.requestId) return state;
59
+ const incoming = new Map(action.options.map((o) => [optionIdOf(o), o]));
60
+ const merged = state.shippingOptions.map(
61
+ (o) => incoming.get(optionIdOf(o)) ?? o
62
+ );
63
+ const known = new Set(state.shippingOptions.map(optionIdOf));
64
+ for (const o of action.options) {
65
+ if (!known.has(optionIdOf(o))) {
66
+ known.add(optionIdOf(o));
67
+ merged.push(o);
68
+ }
69
+ }
70
+ const picked = selectFrom(merged, action.preferOptionId);
71
+ return {
72
+ ...state,
73
+ shippingOptions: merged,
74
+ hasCalculatedShipping: true,
75
+ isCalculatingShipping: false,
76
+ selectedOptionId: picked.optionId,
77
+ selectedShippingRate: picked.rateId,
78
+ shippingFee: picked.fee,
39
79
  calculationFailed: false
40
80
  };
41
81
  }
@@ -46,10 +86,23 @@ function shippingCalculationReducer(state, action) {
46
86
  shippingFee: 0,
47
87
  shippingOptions: [],
48
88
  selectedShippingRate: null,
89
+ selectedOptionId: null,
49
90
  hasCalculatedShipping: false,
50
91
  isCalculatingShipping: false,
51
92
  calculationFailed: true
52
93
  };
94
+ case "OPTION_SELECTED": {
95
+ const option = state.shippingOptions.find(
96
+ (opt) => optionIdOf(opt) === action.optionId
97
+ );
98
+ if (!option) return state;
99
+ return {
100
+ ...state,
101
+ selectedOptionId: optionIdOf(option),
102
+ selectedShippingRate: option.rate_id,
103
+ shippingFee: option.amount
104
+ };
105
+ }
53
106
  case "RATE_SELECTED": {
54
107
  const option = state.shippingOptions.find(
55
108
  (opt) => opt.rate_id === action.rateId
@@ -57,10 +110,8 @@ function shippingCalculationReducer(state, action) {
57
110
  return {
58
111
  ...state,
59
112
  selectedShippingRate: action.rateId,
60
- // Preserves the previous fee if the id doesn't match a known
61
- // option -- shouldn't happen in practice (the UI only ever
62
- // dispatches a rate_id it just rendered from shippingOptions),
63
- // kept explicit rather than silently coercing the fee to 0.
113
+ selectedOptionId: option ? optionIdOf(option) : state.selectedOptionId,
114
+ // Preserves the previous fee if the id doesn't match a known option.
64
115
  shippingFee: option ? option.amount : state.shippingFee
65
116
  };
66
117
  }