@ecomweb/storefront-kit 0.14.1 → 0.16.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 (69) hide show
  1. package/README.md +25 -1
  2. package/bin/check-client-bundle-lib.d.mts +16 -0
  3. package/bin/check-client-bundle-lib.mjs +58 -0
  4. package/bin/check-client-bundle.d.mts +11 -0
  5. package/bin/check-client-bundle.mjs +8 -0
  6. package/dist/api/client.js +52 -1
  7. package/dist/api/client.js.map +1 -1
  8. package/dist/api/index.js.map +1 -1
  9. package/dist/api/proxy-guard.js +29 -0
  10. package/dist/api/proxy-guard.js.map +1 -0
  11. package/dist/api/proxy-routes.js +126 -0
  12. package/dist/api/proxy-routes.js.map +1 -0
  13. package/dist/api/proxy.js +17 -4
  14. package/dist/api/proxy.js.map +1 -1
  15. package/dist/api/server-sdk.js +41 -0
  16. package/dist/api/server-sdk.js.map +1 -0
  17. package/dist/api/store-preview-header.js.map +1 -1
  18. package/dist/auth/sdk.js +21 -6
  19. package/dist/auth/sdk.js.map +1 -1
  20. package/dist/auth/session-refresh.js +7 -4
  21. package/dist/auth/session-refresh.js.map +1 -1
  22. package/dist/cart/api.js.map +1 -1
  23. package/dist/checkout/get-payment-state.js +4 -8
  24. package/dist/checkout/get-payment-state.js.map +1 -1
  25. package/dist/checkout/initiate-gateway-payment.js +5 -7
  26. package/dist/checkout/initiate-gateway-payment.js.map +1 -1
  27. package/dist/checkout/order-handoff.js.map +1 -1
  28. package/dist/checkout/payment-redirect.js.map +1 -1
  29. package/dist/client-info.js +1 -1
  30. package/dist/config/public.js +2 -0
  31. package/dist/config/public.js.map +1 -1
  32. package/dist/config/schema.js +16 -4
  33. package/dist/config/schema.js.map +1 -1
  34. package/dist/config/secret-guard.js +20 -0
  35. package/dist/config/secret-guard.js.map +1 -0
  36. package/dist/config/server.js +15 -8
  37. package/dist/config/server.js.map +1 -1
  38. package/dist/config.d.ts +14 -4
  39. package/dist/config.js +2 -0
  40. package/dist/config.js.map +1 -1
  41. package/dist/index.d.ts +27 -68
  42. package/dist/index.js.map +1 -1
  43. package/dist/middleware/create-storefront-middleware.js +14 -3
  44. package/dist/middleware/create-storefront-middleware.js.map +1 -1
  45. package/dist/middleware.d.ts +2 -2
  46. package/dist/{mode-DXo-EhTJ.d.ts → mode-oVZCQxrc.d.ts} +1 -1
  47. package/dist/orders/api-client.js +3 -3
  48. package/dist/orders/api-client.js.map +1 -1
  49. package/dist/orders/bank-transfer.js +1 -1
  50. package/dist/orders/bank-transfer.js.map +1 -1
  51. package/dist/orders/use-order-status.js +2 -2
  52. package/dist/orders/use-order-status.js.map +1 -1
  53. package/dist/promotions/use-promotion-validation.js +2 -2
  54. package/dist/promotions/use-promotion-validation.js.map +1 -1
  55. package/dist/request/served-store.js +5 -0
  56. package/dist/request/served-store.js.map +1 -0
  57. package/dist/{schema-DIF0CZNV.d.ts → schema-B3nAYiwT.d.ts} +1 -1
  58. package/dist/sdk.js +3 -3
  59. package/dist/sdk.js.map +1 -1
  60. package/dist/server/routes.js +16 -9
  61. package/dist/server/routes.js.map +1 -1
  62. package/dist/server.d.ts +38 -5
  63. package/dist/server.js +2 -0
  64. package/dist/server.js.map +1 -1
  65. package/dist/shipping/use-shipping-calculation.js +2 -2
  66. package/dist/shipping/use-shipping-calculation.js.map +1 -1
  67. package/package.json +6 -2
  68. package/dist/api/server-client.js +0 -162
  69. package/dist/api/server-client.js.map +0 -1
@@ -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 firstLivePreviewToken,\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 `/`; an expired one yields to the other. 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 firstLivePreviewToken(\n req.cookies.get(storePreviewCookieName(\"/\"))?.value,\n req.cookies.get(themePreviewCookieName(\"/\"))?.value\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,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;AAOlC,MAAM,+BAA+B;AAcrC,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,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gB;AAAA,QACrD,EAAE,QAAQ,SAAS,cAAc;AAAA,MACnC;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AAEd,YAAQ,MAAM,0BAA0B,KAAK;AAAA,EAC/C;AAEA,QAAM,UAAU,MAAM,oBAAoB,KAAK,UAAU,UAAU;AACnE,QAAM,WAAW,aAAa,KAAK;AAAA,IACjC,SAAS;AAAA,MACP,SAAS,yBAAyB,KAAK,MAAM,UAAU,OAAO;AAAA,IAChE;AAAA,EACF,CAAC;AAED,MAAI,gBAAgB,KAAK,UAAU,KAAK,gBAAgB,KAAK,UAAU;AACrE,aAAS,QAAQ,IAAI,gBAAgB,SAAS;AAChD,MAAI,SAAS;AACX,qBAAiB,UAAU,UAAU,SAAS,UAAU;AAAA,EAC1D;AACA,SAAO;AACT;AAYO,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","response"]}
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 { SERVED_STORE_HEADER } from \"../request/served-store\";\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 firstLivePreviewToken,\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 headers.delete(SERVED_STORE_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 `/`; an expired one yields to the other. 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 firstLivePreviewToken(\n req.cookies.get(storePreviewCookieName(\"/\"))?.value,\n req.cookies.get(themePreviewCookieName(\"/\"))?.value\n );\n}\n\n/**\n * Path-based dev access: only outside production, and only the host named\n * exactly `localhost`, `127.0.0.1` or `[::1]` (port ignored). A look-alike such\n * as `mylocalhostshop.com` is a store host, so a client cannot choose the\n * served store through the path there.\n */\nfunction isLocalDevelopmentHost(host: string): boolean {\n if (process.env.NODE_ENV === \"production\") return false;\n const hostname = host.startsWith(\"[\")\n ? host.slice(0, host.indexOf(\"]\") + 1)\n : host.split(\":\")[0];\n return [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(hostname.toLowerCase());\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 isLocalDevHost = isLocalDevelopmentHost(host);\n const hostIdentifiesStore =\n !isLocalDevHost &&\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 // A store host's own lookup decides (none if it failed). Only the local\n // dev host is path-based; anywhere else the path names no served store.\n isLocalDevHost\n ? storeRefFromPath(pathname)\n : hostIdentifiesStore\n ? hostStoreRef\n : null\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, storeRef),\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,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,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,MA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AAS,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","response"]}
@@ -1,6 +1,6 @@
1
1
  import { NextRequest, NextResponse } from 'next/server';
2
- import { S as StorefrontMode } from './mode-DXo-EhTJ.js';
3
- import './schema-DIF0CZNV.js';
2
+ import { S as StorefrontMode } from './mode-oVZCQxrc.js';
3
+ import './schema-B3nAYiwT.js';
4
4
  import 'zod';
5
5
 
6
6
  /**
@@ -1,4 +1,4 @@
1
- import { E as EnvSource } from './schema-DIF0CZNV.js';
1
+ import { E as EnvSource } from './schema-B3nAYiwT.js';
2
2
 
3
3
  /**
4
4
  * multi: the shared platform storefront, every store under /store/<ref> or
@@ -1,7 +1,7 @@
1
- import { createStoreSdk, sdk } from "../sdk.js";
1
+ import { createStoreSdk } from "../sdk.js";
2
2
  const publicOrdersApi = {
3
3
  async getPublicOrderStatus(storeRef, orderNumber, contactInfo) {
4
- const result = await sdk.orders.lookupGuest(storeRef, {
4
+ const result = await createStoreSdk(storeRef).orders.lookupGuest(storeRef, {
5
5
  order_number: orderNumber,
6
6
  customer_email: contactInfo.email,
7
7
  customer_phone: contactInfo.phone
@@ -12,7 +12,7 @@ const publicOrdersApi = {
12
12
  * `isAuth` comes from the caller's auth context — this module is not a
13
13
  * component and must not read context or an httpOnly cookie itself.
14
14
  *
15
- * When true the SDK posts to `/tenant/stores/:ref/customers/orders`, which
15
+ * When true the SDK posts to `/storefront/stores/:ref/customers/orders`, which
16
16
  * derives BOTH `customer_id` (ResolveCustomerInterceptor) and `user_id`
17
17
  * (JWT) server-side; the payload carries neither, and `CreateOrderDto` has no
18
18
  * such fields to carry them in. The request reaches that guarded route
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/orders/api-client.ts"],"sourcesContent":["import { createStoreSdk, sdk } from \"../sdk\";\nimport type { CreateOrderRequest, Order, OrderWithItems } from \"@ecomweb/sdk\";\n\nexport const publicOrdersApi = {\n async getPublicOrderStatus(\n storeRef: string,\n orderNumber: number,\n contactInfo: { email?: string; phone?: string }\n ): Promise<Order | null> {\n const result = await sdk.orders.lookupGuest(storeRef, {\n order_number: orderNumber,\n customer_email: contactInfo.email,\n customer_phone: contactInfo.phone,\n });\n return result;\n },\n\n /**\n * `isAuth` comes from the caller's auth context — this module is not a\n * component and must not read context or an httpOnly cookie itself.\n *\n * When true the SDK posts to `/tenant/stores/:ref/customers/orders`, which\n * derives BOTH `customer_id` (ResolveCustomerInterceptor) and `user_id`\n * (JWT) server-side; the payload carries neither, and `CreateOrderDto` has no\n * such fields to carry them in. The request reaches that guarded route\n * through the same-origin proxy, which attaches the bearer token.\n */\n async createStoreOrder(\n storeRef: string,\n data: Omit<CreateOrderRequest, \"store_id\">,\n isAuth: boolean\n ): Promise<OrderWithItems> {\n return createStoreSdk(storeRef).orders.create(\n storeRef,\n data as CreateOrderRequest,\n isAuth\n );\n },\n};\n\nexport type { CreateOrderRequest, CreateOrderItemRequest } from \"@ecomweb/sdk\";\n"],"mappings":"AAAA,SAAS,gBAAgB,WAAW;AAG7B,MAAM,kBAAkB;AAAA,EAC7B,MAAM,qBACJ,UACA,aACA,aACuB;AACvB,UAAM,SAAS,MAAM,IAAI,OAAO,YAAY,UAAU;AAAA,MACpD,cAAc;AAAA,MACd,gBAAgB,YAAY;AAAA,MAC5B,gBAAgB,YAAY;AAAA,IAC9B,CAAC;AACD,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,MAAM,iBACJ,UACA,MACA,QACyB;AACzB,WAAO,eAAe,QAAQ,EAAE,OAAO;AAAA,MACrC;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/orders/api-client.ts"],"sourcesContent":["import { createStoreSdk } from \"../sdk\";\nimport type { CreateOrderRequest, Order, OrderWithItems } from \"@ecomweb/sdk\";\n\nexport const publicOrdersApi = {\n async getPublicOrderStatus(\n storeRef: string,\n orderNumber: number,\n contactInfo: { email?: string; phone?: string }\n ): Promise<Order | null> {\n const result = await createStoreSdk(storeRef).orders.lookupGuest(storeRef, {\n order_number: orderNumber,\n customer_email: contactInfo.email,\n customer_phone: contactInfo.phone,\n });\n return result;\n },\n\n /**\n * `isAuth` comes from the caller's auth context — this module is not a\n * component and must not read context or an httpOnly cookie itself.\n *\n * When true the SDK posts to `/storefront/stores/:ref/customers/orders`, which\n * derives BOTH `customer_id` (ResolveCustomerInterceptor) and `user_id`\n * (JWT) server-side; the payload carries neither, and `CreateOrderDto` has no\n * such fields to carry them in. The request reaches that guarded route\n * through the same-origin proxy, which attaches the bearer token.\n */\n async createStoreOrder(\n storeRef: string,\n data: Omit<CreateOrderRequest, \"store_id\">,\n isAuth: boolean\n ): Promise<OrderWithItems> {\n return createStoreSdk(storeRef).orders.create(\n storeRef,\n data as CreateOrderRequest,\n isAuth\n );\n },\n};\n\nexport type { CreateOrderRequest, CreateOrderItemRequest } from \"@ecomweb/sdk\";\n"],"mappings":"AAAA,SAAS,sBAAsB;AAGxB,MAAM,kBAAkB;AAAA,EAC7B,MAAM,qBACJ,UACA,aACA,aACuB;AACvB,UAAM,SAAS,MAAM,eAAe,QAAQ,EAAE,OAAO,YAAY,UAAU;AAAA,MACzE,cAAc;AAAA,MACd,gBAAgB,YAAY;AAAA,MAC5B,gBAAgB,YAAY;AAAA,IAC9B,CAAC;AACD,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,MAAM,iBACJ,UACA,MACA,QACyB;AACzB,WAAO,eAAe,QAAQ,EAAE,OAAO;AAAA,MACrC;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -29,7 +29,7 @@ function useBankTransferDetails(enabled) {
29
29
  (async () => {
30
30
  try {
31
31
  const res = await publicApiClient.get(
32
- `/public/stores/${encodeURIComponent(storeRef)}/payment-methods`
32
+ `/storefront/stores/${encodeURIComponent(storeRef)}/payment-methods`
33
33
  );
34
34
  const picked = pickBankTransfer(unwrap(res));
35
35
  if (cancelled) return;
@@ -1 +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
+ {"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 `/storefront/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,sBAAsB,mBAAmB,QAAQ,CAAC;AAAA,QACpD;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":[]}
@@ -7,7 +7,7 @@ import {
7
7
  resolveInitialState,
8
8
  shouldPollForConfirmation
9
9
  } from "../checkout/success-state.js";
10
- import { sdk } from "../sdk.js";
10
+ import { createStoreSdk } from "../sdk.js";
11
11
  import { useStoreId } from "../store/store-context.js";
12
12
  import { useBankTransferDetails } from "./bank-transfer.js";
13
13
  const CANCELLED = new Error("order status: unmounted");
@@ -83,7 +83,7 @@ function useOrderLookup({
83
83
  try {
84
84
  setIsLoading(true);
85
85
  setError(null);
86
- const found = await sdk.orders.lookupGuest(storeRef, {
86
+ const found = await createStoreSdk(storeRef).orders.lookupGuest(storeRef, {
87
87
  order_code: orderCode,
88
88
  customer_email: email || void 0,
89
89
  customer_phone: phone || void 0
@@ -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 { 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);\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,O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import { 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 { createStoreSdk } 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 createStoreSdk(storeRef).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);\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,sBAAsB;AAC/B,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,YAAU,MAAM;AACd,QAAI,CAAC,UAAW;AAGhB,QAAI,CAAC,cAAe;AACpB,QAAI,CAAC,0BAA0B,KAAK,EAAG;AAEvC,QAAI,YAAY;AAChB,iBAAa,IAAI;AACjB,qBAAiB;AAAA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S,KAAK;AAAA,IAChB,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":[]}
@@ -1,4 +1,4 @@
1
- import { sdk } from "../sdk.js";
1
+ import { createStoreSdk } from "../sdk.js";
2
2
  import { useState, useCallback, useEffect, useRef } from "react";
3
3
  import { useNotify } from "../notices.js";
4
4
  class PromotionRejected extends Error {
@@ -25,7 +25,7 @@ function usePromotionValidation({
25
25
  setIsValidatingPromo(true);
26
26
  setPromoError("");
27
27
  try {
28
- const result = await sdk.promotions.validate(storeRef, {
28
+ const result = await createStoreSdk(storeRef).promotions.validate(storeRef, {
29
29
  code: codeToValidate.trim(),
30
30
  items: items.map((item) => ({
31
31
  product_id: item.productId,
@@ -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\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,SAAS,WAAW;AACpB,SAAS,UAAU,aAAa,WAAW,cAAc;AACzD,SAAS,iBAAiB;AAiB1B,MAAM,0BAA0B,MAAM;AAAC;AAEhC,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,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C,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":[]}
1
+ {"version":3,"sources":["../../src/promotions/use-promotion-validation.ts"],"sourcesContent":["import { createStoreSdk } 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 createStoreSdk(storeRef).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,SAAS,sBAAsB;AAC/B,SAAS,UAAU,aAAa,WAAW,cAAc;AACzD,SAAS,iBAAiB;AAiB1B,MAAM,0BAA0B,MAAM;AAAC;AAEhC,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,eAAe,QAAQ,EAAE,WAAW,SAAS,UAAU;AAAA,UAC1E,MA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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":[]}
@@ -0,0 +1,5 @@
1
+ const SERVED_STORE_HEADER = "x-ecomweb-served-store";
2
+ export {
3
+ SERVED_STORE_HEADER
4
+ };
5
+ //# sourceMappingURL=served-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/request/served-store.ts"],"sourcesContent":["/**\n * The store this request serves, stamped by the middleware (the host's store\n * on a store host, the path's store on localhost, the configured one in single\n * mode). The middleware always deletes any client copy first, so a server-side\n * reader can trust it. Absent when no store was resolved. No `server-only`:\n * the middleware imports it.\n */\nexport const SERVED_STORE_HEADER = \"x-ecomweb-served-store\";\n"],"mappings":"AAOO,MAAM,sBAAsB;","names":[]}
@@ -27,7 +27,7 @@ declare const publicConfigSchema: z.ZodObject<{
27
27
  }, z.core.$strip>;
28
28
  type PublicConfig = z.infer<typeof publicConfigSchema>;
29
29
  declare const serverConfigSchema: z.ZodObject<{
30
- platformApiKey: z.ZodString;
30
+ secretKey: z.ZodString;
31
31
  clientIpForwarderSecret: z.ZodOptional<z.ZodString>;
32
32
  appBaseUrl: z.ZodString;
33
33
  appEnv: z.ZodString;
package/dist/sdk.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createEcomwebSdk } from "@ecomweb/sdk";
1
+ import { createEcomwebProxiedSdk, createEcomwebSdk } from "@ecomweb/sdk";
2
2
  import { createStoreApiClient, publicApiClient } from "./api/client.js";
3
3
  import { KIT_CLIENT_TOKEN } from "./client-info.js";
4
4
  function requireStoreScopedSdk() {
@@ -21,9 +21,9 @@ const storeSdks = /* @__PURE__ */ new Map();
21
21
  function createStoreSdk(storeRef) {
22
22
  const cached = storeSdks.get(storeRef);
23
23
  if (cached) return cached;
24
- const created = createEcomwebSdk({
24
+ const created = createEcomwebProxiedSdk({
25
25
  publicHttp: publicApiClient,
26
- authHttp: createStoreApiClient(storeRef),
26
+ proxyHttp: createStoreApiClient(storeRef),
27
27
  clientInfo: KIT_CLIENT_TOKEN
28
28
  });
29
29
  storeSdks.set(storeRef, created);
package/dist/sdk.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sdk.ts"],"sourcesContent":["import { createEcomwebSdk } from \"@ecomweb/sdk\";\nimport type { ApiResponse, IHttpClient } from \"@ecomweb/sdk\";\nimport { createStoreApiClient, publicApiClient } from \"./api/client\";\nimport { KIT_CLIENT_TOKEN } from \"./client-info\";\n\n/**\n * The module-level `sdk` below has no store in scope, so it cannot build the\n * store-scoped proxy URL an authenticated call needs. Rather than let such a\n * call go out silently unauthenticated and 401 at the backend, its `authHttp`\n * fails here with an actionable message.\n */\nfunction requireStoreScopedSdk(): IHttpClient {\n const fail = async (): Promise<ApiResponse<never>> => ({\n success: false,\n error: {\n message:\n \"This endpoint requires a signed-in shopper. Use createStoreSdk(storeRef) instead of the module-level sdk.\",\n statusCode: 401,\n error: \"SDK_STORE_SCOPE_REQUIRED\",\n },\n });\n\n return { get: fail, post: fail, put: fail, patch: fail, delete: fail };\n}\n\n// ApiClient satisfies IHttpClient structurally at runtime; cast resolves the\n// AxiosRequestConfig vs RequestOptions type mismatch.\nexport const sdk = createEcomwebSdk({\n publicHttp: publicApiClient as any,\n authHttp: requireStoreScopedSdk(),\n clientInfo: KIT_CLIENT_TOKEN,\n});\n\nconst storeSdks = new Map<string, ReturnType<typeof createEcomwebSdk>>();\n\n/**\n * SDK bound to one store, whose authenticated modules (cart, orders, blog\n * comments, customers, addresses) go through the same-origin proxy route so the\n * httpOnly session cookie can be turned into a bearer token server-side.\n *\n * Memoised per store so the returned object is referentially stable and safe to\n * use in a React dependency array.\n */\nexport function createStoreSdk(storeRef: string) {\n const cached = storeSdks.get(storeRef);\n if (cached) return cached;\n\n const created = createEcomwebSdk({\n publicHttp: publicApiClient as any,\n authHttp: createStoreApiClient(storeRef) as any,\n clientInfo: KIT_CLIENT_TOKEN,\n });\n\n storeSdks.set(storeRef, created);\n return created;\n}\n"],"mappings":"AAAA,SAAS,wBAAwB;AAEjC,SAAS,sBAAsB,uBAAuB;AACtD,SAAS,wBAAwB;AAQjC,SAAS,wBAAqC;AAC5C,QAAM,OAAO,aAA0C;AAAA,IACrD,SAAS;AAAA,IACT,OAAO;AAAA,MACL,SACE;AAAA,MACF,YAAY;AAAA,MACZ,OAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO,EAAE,KAAK,MAAM,MAAM,MAAM,KAAK,MAAM,OAAO,MAAM,QAAQ,KAAK;AACvE;AAIO,MAAM,MAAM,iBAAiB;AAAA,EAClC,YAAY;AAAA,EACZ,UAAU,sBAAsB;AAAA,EAChC,YAAY;AACd,CAAC;AAED,MAAM,YAAY,oBAAI,IAAiD;AAUhE,SAAS,eAAe,UAAkB;AAC/C,QAAM,SAAS,UAAU,IAAI,QAAQ;AACrC,MAAI,OAAQ,QAAO;AAEnB,QAAM,UAAU,iBAAiB;AAAA,IAC/B,YAAY;AAAA,IACZ,UAAU,qBAAqB,QAAQ;AAAA,IACvC,YAAY;AAAA,EACd,CAAC;AAED,YAAU,IAAI,UAAU,OAAO;AAC/B,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/sdk.ts"],"sourcesContent":["import { createEcomwebProxiedSdk, createEcomwebSdk } from \"@ecomweb/sdk\";\nimport type {\n ApiResponse,\n EcomwebSdk,\n EcomwebServerSdk,\n IHttpClient,\n} from \"@ecomweb/sdk\";\nimport { createStoreApiClient, publicApiClient } from \"./api/client\";\nimport { KIT_CLIENT_TOKEN } from \"./client-info\";\n\n/**\n * The module-level `sdk` below has no store in scope, so it cannot build the\n * store-scoped proxy URL an authenticated call needs. Rather than let such a\n * call go out silently unauthenticated and 401 at the backend, its `authHttp`\n * fails here with an actionable message.\n */\nfunction requireStoreScopedSdk(): IHttpClient {\n const fail = async (): Promise<ApiResponse<never>> => ({\n success: false,\n error: {\n message:\n \"This endpoint requires a signed-in shopper. Use createStoreSdk(storeRef) instead of the module-level sdk.\",\n statusCode: 401,\n error: \"SDK_STORE_SCOPE_REQUIRED\",\n },\n });\n\n return { get: fail, post: fail, put: fail, patch: fail, delete: fail };\n}\n\n// ApiClient satisfies IHttpClient structurally at runtime; cast resolves the\n// AxiosRequestConfig vs RequestOptions type mismatch.\nexport const sdk: EcomwebSdk = createEcomwebSdk({\n publicHttp: publicApiClient as any,\n authHttp: requireStoreScopedSdk(),\n clientInfo: KIT_CLIENT_TOKEN,\n});\n\nconst storeSdks = new Map<string, EcomwebServerSdk>();\n\n/**\n * SDK bound to one store, for the browser. Public calls go straight to the\n * API with the publishable key; every private call (cart, orders, payments,\n * customers, addresses, shopper-side blog, review and metaobject calls, rate\n * calculation, promotion validation) goes to the same-origin proxy at\n * `/store/<ref>/api/backend` (`/api/backend` on a single-store site), which\n * adds the storefront secret key and turns the httpOnly session cookie into a\n * bearer token. The secret key never reaches the browser.\n *\n * Memoised per store so the returned object is referentially stable and safe to\n * use in a React dependency array.\n */\nexport function createStoreSdk(storeRef: string): EcomwebServerSdk {\n const cached = storeSdks.get(storeRef);\n if (cached) return cached;\n\n const created = createEcomwebProxiedSdk({\n publicHttp: publicApiClient as any,\n proxyHttp: createStoreApiClient(storeRef) as any,\n clientInfo: KIT_CLIENT_TOKEN,\n });\n\n storeSdks.set(storeRef, created);\n return created;\n}\n"],"mappings":"AAAA,SAAS,yBAAyB,wBAAwB;AAO1D,SAAS,sBAAsB,uBAAuB;AACtD,SAAS,wBAAwB;AAQjC,SAAS,wBAAqC;AAC5C,QAAM,OAAO,aAA0C;AAAA,IACrD,SAAS;AAAA,IACT,OAAO;AAAA,MACL,SACE;AAAA,MACF,YAAY;AAAA,MACZ,OAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO,EAAE,KAAK,MAAM,MAAM,MAAM,KAAK,MAAM,OAAO,MAAM,QAAQ,KAAK;AACvE;AAIO,MAAM,MAAkB,iBAAiB;AAAA,EAC9C,YAAY;AAAA,EACZ,UAAU,sBAAsB;AAAA,EAChC,YAAY;AACd,CAAC;AAED,MAAM,YAAY,oBAAI,IAA8B;AAc7C,SAAS,eAAe,UAAoC;AACjE,QAAM,SAAS,UAAU,IAAI,QAAQ;AACrC,MAAI,OAAQ,QAAO;AAEnB,QAAM,UAAU,wBAAwB;AAAA,IACtC,YAAY;AAAA,IACZ,WAAW,qBAAqB,QAAQ;AAAA,IACxC,YAAY;AAAA,EACd,CAAC;AAED,YAAU,IAAI,UAAU,OAAO;AAC/B,SAAO;AACT;","names":[]}
@@ -1,7 +1,11 @@
1
1
  import "server-only";
2
- import { NextResponse } from "next/server";
3
2
  import { redirect } from "next/navigation";
4
3
  import { handleBackendProxy } from "../api/proxy.js";
4
+ import {
5
+ isSameOriginRequest,
6
+ proxyNotFound,
7
+ servedStoreRef
8
+ } from "../api/proxy-guard.js";
5
9
  import { handleAuthRoute } from "../auth/route-handlers.js";
6
10
  import { getServerIdentity } from "../auth/session.js";
7
11
  import { resolveStoreRef } from "../store-scope/index.js";
@@ -12,18 +16,20 @@ async function storeRefFor(params) {
12
16
  }
13
17
  return resolveRootStoreRef();
14
18
  }
15
- function storeNotFound() {
16
- return NextResponse.json(
17
- { error: { message: "Store not found for host" } },
18
- { status: 404 }
19
- );
20
- }
21
19
  const segments = (v) => Array.isArray(v) ? v : v ? [v] : [];
20
+ function servesRouteStore(req, params) {
21
+ if (params.storeRef === void 0) return true;
22
+ return servedStoreRef(req) === params.storeRef;
23
+ }
22
24
  function createAuthRoutes() {
23
25
  const handle = async (req, { params }) => {
24
26
  const p = await params;
27
+ if (!servesRouteStore(req, p)) return proxyNotFound();
28
+ if (req.method !== "GET" && !isSameOriginRequest(req)) {
29
+ return proxyNotFound();
30
+ }
25
31
  const storeRef = await storeRefFor(p);
26
- if (!storeRef) return storeNotFound();
32
+ if (!storeRef) return proxyNotFound();
27
33
  return handleAuthRoute(req, storeRef, segments(p.route));
28
34
  };
29
35
  return { GET: handle, POST: handle };
@@ -31,8 +37,9 @@ function createAuthRoutes() {
31
37
  function createBackendProxy() {
32
38
  const handle = async (req, { params }) => {
33
39
  const p = await params;
40
+ if (!servesRouteStore(req, p)) return proxyNotFound();
34
41
  const storeRef = await storeRefFor(p);
35
- if (!storeRef) return storeNotFound();
42
+ if (!storeRef) return proxyNotFound();
36
43
  return handleBackendProxy(req, storeRef, segments(p.path));
37
44
  };
38
45
  return {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/server/routes.ts"],"sourcesContent":["import \"server-only\";\nimport { NextResponse, type NextRequest } from \"next/server\";\nimport { redirect } from \"next/navigation\";\nimport { handleBackendProxy } from \"../api/proxy\";\nimport { handleAuthRoute } from \"../auth/route-handlers\";\nimport { getServerIdentity } from \"../auth/session\";\nimport { resolveStoreRef } from \"../store-scope\";\nimport { resolveRootStoreRef } from \"../store-scope/root\";\n\ntype Params = Record<string, string | string[] | undefined>;\nexport type RouteContext = { params: Promise<Params> };\nexport type RouteHandler = (\n req: NextRequest,\n ctx: RouteContext\n) => Promise<Response>;\n\n/**\n * The store a route serves: the /store/<ref> segment when the route has one,\n * otherwise whatever the host (or, single-store, the config) names.\n */\nasync function storeRefFor(params: Params): Promise<string | null> {\n if (typeof params.storeRef === \"string\") {\n return resolveStoreRef(Promise.resolve({ storeRef: params.storeRef }));\n }\n return resolveRootStoreRef();\n}\n\nfunction storeNotFound(): Response {\n return NextResponse.json(\n { error: { message: \"Store not found for host\" } },\n { status: 404 }\n );\n}\n\nconst segments = (v: Params[string]): string[] =>\n Array.isArray(v) ? v : v ? [v] : [];\n\n/** `export const { GET, POST } = createAuthRoutes();` in api/auth/[...route]. */\nexport function createAuthRoutes(): { GET: RouteHandler; POST: RouteHandler } {\n const handle: RouteHandler = async (req, { params }) => {\n const p = await params;\n const storeRef = await storeRefFor(p);\n if (!storeRef) return storeNotFound();\n return handleAuthRoute(req, storeRef, segments(p.route));\n };\n return { GET: handle, POST: handle };\n}\n\n/**\n * `export const { GET, POST, PUT, PATCH, DELETE } = createBackendProxy();`\n * in api/backend/[...path].\n */\nexport function createBackendProxy(): Record<\n \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n RouteHandler\n> {\n const handle: RouteHandler = async (req, { params }) => {\n const p = await params;\n const storeRef = await storeRefFor(p);\n if (!storeRef) return storeNotFound();\n return handleBackendProxy(req, storeRef, segments(p.path));\n };\n return {\n GET: handle,\n POST: handle,\n PUT: handle,\n PATCH: handle,\n DELETE: handle,\n };\n}\n\nexport type CustomerIdentity = NonNullable<\n Awaited<ReturnType<typeof getServerIdentity>>\n>;\n\n/**\n * The signed-in customer, or a redirect to `redirectTo`. An anonymous\n * identity holds a valid token but no customer profile, so it redirects too.\n */\nexport async function requireSession(\n storeRef: string,\n redirectTo: string\n): Promise<CustomerIdentity> {\n const identity = await getServerIdentity(storeRef);\n if (!identity || identity.is_anonymous) redirect(redirectTo);\n return identity;\n}\n"],"mappings":"AAAA,OAAO;AACP,SAAS,oBAAsC;AAC/C,SAAS,gBAAgB;AACzB,SAAS,0BAA0B;AACnC,SAAS,uBAAuB;AAChC,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAS,2BAA2B;AAapC,eAAe,YAAY,QAAwC;AACjE,MAAI,OAAO,OAAO,aAAa,UAAU;AACvC,WAAO,gBAAgB,QAAQ,QAAQ,EAAE,UAAU,OAAO,SAAS,CAAC,CAAC;AAAA,EACvE;AACA,SAAO,oBAAoB;AAC7B;AAEA,SAAS,gBAA0B;AACjC,SAAO,aAAa;AAAA,IAClB,EAAE,OAAO,EAAE,SAAS,2BAA2B,EAAE;AAAA,IACjD,EAAE,QAAQ,IAAI;AAAA,EAChB;AACF;AAEA,MAAM,WAAW,CAAC,MAChB,MAAM,QAAQ,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC;AAG7B,SAAS,mBAA8D;AAC5E,QAAM,SAAuB,OAAO,KAAK,EAAE,OAAO,MAAM;AACtD,UAAM,IAAI,MAAM;AAChB,UAAM,WAAW,MAAM,YAAY,CAAC;AACpC,QAAI,CAAC,SAAU,QAAO,cAAc;AACpC,WAAO,gBAAgB,KAAK,UAAU,SAAS,EAAE,KAAK,CAAC;AAAA,EACzD;AACA,SAAO,EAAE,KAAK,QAAQ,MAAM,OAAO;AACrC;AAMO,SAAS,qBAGd;AACA,QAAM,SAAuB,OAAO,KAAK,EAAE,OAAO,MAAM;AACtD,UAAM,IAAI,MAAM;AAChB,UAAM,WAAW,MAAM,YAAY,CAAC;AACpC,QAAI,CAAC,SAAU,QAAO,cAAc;AACpC,WAAO,mBAAmB,KAAK,UAAU,SAAS,EAAE,IAAI,CAAC;AAAA,EAC3D;AACA,SAAO;AAAA,IACL,KAAK;AAAA,IACL,MAAM;AAAA,IACN,KAAK;AAAA,IACL,OAAO;AAAA,IACP,QAAQ;AAAA,EACV;AACF;AAUA,eAAsB,eACpB,UACA,YAC2B;AAC3B,QAAM,WAAW,MAAM,kBAAkB,QAAQ;AACjD,MAAI,CAAC,YAAY,SAAS,aAAc,UAAS,UAAU;AAC3D,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/server/routes.ts"],"sourcesContent":["import \"server-only\";\nimport type { NextRequest } from \"next/server\";\nimport { redirect } from \"next/navigation\";\nimport { handleBackendProxy } from \"../api/proxy\";\nimport {\n isSameOriginRequest,\n proxyNotFound,\n servedStoreRef,\n} from \"../api/proxy-guard\";\nimport { handleAuthRoute } from \"../auth/route-handlers\";\nimport { getServerIdentity } from \"../auth/session\";\nimport { resolveStoreRef } from \"../store-scope\";\nimport { resolveRootStoreRef } from \"../store-scope/root\";\n\ntype Params = Record<string, string | string[] | undefined>;\nexport type RouteContext = { params: Promise<Params> };\nexport type RouteHandler = (\n req: NextRequest,\n ctx: RouteContext\n) => Promise<Response>;\n\n/**\n * The store a route serves: the /store/<ref> segment when the route has one,\n * otherwise whatever the host (or, single-store, the config) names.\n */\nasync function storeRefFor(params: Params): Promise<string | null> {\n if (typeof params.storeRef === \"string\") {\n return resolveStoreRef(Promise.resolve({ storeRef: params.storeRef }));\n }\n return resolveRootStoreRef();\n}\n\nconst segments = (v: Params[string]): string[] =>\n Array.isArray(v) ? v : v ? [v] : [];\n\n/**\n * False when the route names a store (`/store/<ref>/...`) other than the one\n * the middleware stamped for this request, or when it stamped none. Routes\n * without the param take the store from the host or config instead.\n */\nfunction servesRouteStore(req: NextRequest, params: Params): boolean {\n if (params.storeRef === undefined) return true;\n return servedStoreRef(req) === params.storeRef;\n}\n\n/**\n * `export const { GET, POST } = createAuthRoutes();` in api/auth/[...route].\n * These routes sign every shopper-auth call with the storefront secret key,\n * so they answer 404 for a `/store/<ref>` other than the one this request\n * serves, and for any non-GET request that is not same-origin (GETs stay\n * open: Google's OAuth callback arrives cross-site).\n */\nexport function createAuthRoutes(): { GET: RouteHandler; POST: RouteHandler } {\n const handle: RouteHandler = async (req, { params }) => {\n const p = await params;\n if (!servesRouteStore(req, p)) return proxyNotFound();\n if (req.method !== \"GET\" && !isSameOriginRequest(req)) {\n return proxyNotFound();\n }\n const storeRef = await storeRefFor(p);\n if (!storeRef) return proxyNotFound();\n return handleAuthRoute(req, storeRef, segments(p.route));\n };\n return { GET: handle, POST: handle };\n}\n\n/**\n * `export const { GET, POST, PUT, PATCH, DELETE } = createBackendProxy();`\n * in api/backend/[...path]. It carries every private browser call under the\n * storefront secret key, so it forwards only same-origin calls to routes in\n * `PROXIED_STOREFRONT_ROUTES`, for the store this request serves, and answers\n * every other request 404 `NOT_FOUND`.\n */\nexport function createBackendProxy(): Record<\n \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n RouteHandler\n> {\n const handle: RouteHandler = async (req, { params }) => {\n const p = await params;\n if (!servesRouteStore(req, p)) return proxyNotFound();\n const storeRef = await storeRefFor(p);\n if (!storeRef) return proxyNotFound();\n return handleBackendProxy(req, storeRef, segments(p.path));\n };\n return {\n GET: handle,\n POST: handle,\n PUT: handle,\n PATCH: handle,\n DELETE: handle,\n };\n}\n\nexport type CustomerIdentity = NonNullable<\n Awaited<ReturnType<typeof getServerIdentity>>\n>;\n\n/**\n * The signed-in customer, or a redirect to `redirectTo`. An anonymous\n * identity holds a valid token but no customer profile, so it redirects too.\n */\nexport async function requireSession(\n storeRef: string,\n redirectTo: string\n): Promise<CustomerIdentity> {\n const identity = await getServerIdentity(storeRef);\n if (!identity || identity.is_anonymous) redirect(redirectTo);\n return identity;\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,gBAAgB;AACzB,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAS,2BAA2B;AAapC,eAAe,YAAY,QAAwC;AACjE,MAAI,OAAO,OAAO,aAAa,UAAU;AACvC,WAAO,gBAAgB,QAAQ,QAAQ,EAAE,UAAU,OAAO,SAAS,CAAC,CAAC;AAAA,EACvE;AACA,SAAO,oBAAoB;AAC7B;AAEA,MAAM,WAAW,CAAC,MAChB,MAAM,QAAQ,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC;AAOpC,SAAS,iBAAiB,KAAkB,QAAyB;AACnE,MAAI,OAAO,aAAa,OAAW,QAAO;AAC1C,SAAO,eAAe,GAAG,MAAM,OAAO;AACxC;AASO,SAAS,mBAA8D;AAC5E,QAAM,SAAuB,OAAO,KAAK,EAAE,OAAO,MAAM;AACtD,UAAM,IAAI,MAAM;AAChB,QAAI,CAAC,iBAAiB,KAAK,CAAC,EAAG,QAAO,cAAc;AACpD,QAAI,IAAI,WAAW,SAAS,CAAC,oBAAoB,GAAG,GAAG;AACrD,aAAO,cAAc;AAAA,IACvB;AACA,UAAM,WAAW,MAAM,YAAY,CAAC;AACpC,QAAI,CAAC,SAAU,QAAO,cAAc;AACpC,WAAO,gBAAgB,KAAK,UAAU,SAAS,EAAE,KAAK,CAAC;AAAA,EACzD;AACA,SAAO,EAAE,KAAK,QAAQ,MAAM,OAAO;AACrC;AASO,SAAS,qBAGd;AACA,QAAM,SAAuB,OAAO,KAAK,EAAE,OAAO,MAAM;AACtD,UAAM,IAAI,MAAM;AAChB,QAAI,CAAC,iBAAiB,KAAK,CAAC,EAAG,QAAO,cAAc;AACpD,UAAM,WAAW,MAAM,YAAY,CAAC;AACpC,QAAI,CAAC,SAAU,QAAO,cAAc;AACpC,WAAO,mBAAmB,KAAK,UAAU,SAAS,EAAE,IAAI,CAAC;AAAA,EAC3D;AACA,SAAO;AAAA,IACL,KAAK;AAAA,IACL,MAAM;AAAA,IACN,KAAK;AAAA,IACL,OAAO;AAAA,IACP,QAAQ;AAAA,EACV;AACF;AAUA,eAAsB,eACpB,UACA,YAC2B;AAC3B,QAAM,WAAW,MAAM,kBAAkB,QAAQ;AACjD,MAAI,CAAC,YAAY,SAAS,aAAc,UAAS,UAAU;AAC3D,SAAO;AACT;","names":[]}
package/dist/server.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { NextRequest } from 'next/server';
2
- import { CurrentIdentity } from '@ecomweb/sdk';
3
- import { E as EnvSource, S as ServerConfig } from './schema-DIF0CZNV.js';
2
+ import { CurrentIdentity, EcomwebServerSdk } from '@ecomweb/sdk';
3
+ export { EcomwebSdk, EcomwebServerSdk } from '@ecomweb/sdk';
4
+ import { E as EnvSource, S as ServerConfig } from './schema-B3nAYiwT.js';
4
5
  import 'zod';
5
6
 
6
7
  /**
@@ -27,14 +28,23 @@ type RouteContext = {
27
28
  params: Promise<Params>;
28
29
  };
29
30
  type RouteHandler = (req: NextRequest, ctx: RouteContext) => Promise<Response>;
30
- /** `export const { GET, POST } = createAuthRoutes();` in api/auth/[...route]. */
31
+ /**
32
+ * `export const { GET, POST } = createAuthRoutes();` in api/auth/[...route].
33
+ * These routes sign every shopper-auth call with the storefront secret key,
34
+ * so they answer 404 for a `/store/<ref>` other than the one this request
35
+ * serves, and for any non-GET request that is not same-origin (GETs stay
36
+ * open: Google's OAuth callback arrives cross-site).
37
+ */
31
38
  declare function createAuthRoutes(): {
32
39
  GET: RouteHandler;
33
40
  POST: RouteHandler;
34
41
  };
35
42
  /**
36
43
  * `export const { GET, POST, PUT, PATCH, DELETE } = createBackendProxy();`
37
- * in api/backend/[...path].
44
+ * in api/backend/[...path]. It carries every private browser call under the
45
+ * storefront secret key, so it forwards only same-origin calls to routes in
46
+ * `PROXIED_STOREFRONT_ROUTES`, for the store this request serves, and answers
47
+ * every other request 404 `NOT_FOUND`.
38
48
  */
39
49
  declare function createBackendProxy(): Record<"GET" | "POST" | "PUT" | "PATCH" | "DELETE", RouteHandler>;
40
50
  type CustomerIdentity = NonNullable<Awaited<ReturnType<typeof getServerIdentity>>>;
@@ -44,6 +54,29 @@ type CustomerIdentity = NonNullable<Awaited<ReturnType<typeof getServerIdentity>
44
54
  */
45
55
  declare function requireSession(storeRef: string, redirectTo: string): Promise<CustomerIdentity>;
46
56
 
57
+ /**
58
+ * The server SDK for the current request, signed with the storefront secret
59
+ * key, for private reads in server components and route handlers (for example
60
+ * a review invitation by token). The shopper's IP and the store preview token
61
+ * are taken from the request.
62
+ *
63
+ * Shopper-side methods (cart, orders, addresses and the like) do not work
64
+ * here: a server has no shopper session, so they reject with
65
+ * `SDK_SHOPPER_CALL_ON_SERVER`. Use `createStoreSdk(storeRef)` in the browser.
66
+ *
67
+ * @example
68
+ * ```ts
69
+ * import { getServerSdk } from "@ecomweb/storefront-kit/server";
70
+ *
71
+ * const sdk = await getServerSdk();
72
+ * const invitation = await sdk.reviews.getReviewInvitation(storeRef, token);
73
+ * ```
74
+ *
75
+ * @returns The server SDK for this request
76
+ * @throws Error when the storefront secret key is not set
77
+ */
78
+ declare function getServerSdk(): Promise<EcomwebServerSdk>;
79
+
47
80
  /** Parses the variables of the mode `env` selects (see resolveMode). */
48
81
  declare function parseServerConfig(env: EnvSource): ServerConfig;
49
82
  /**
@@ -109,4 +142,4 @@ declare function resolveComingSoonStore(): Promise<{
109
142
  name: string | null;
110
143
  } | null>;
111
144
 
112
- export { type CustomerIdentity, type RouteContext, type RouteHandler, createAuthRoutes, createBackendProxy, externalThemeRedirectFor, hasCustomerSession, parseServerConfig, readPreviewHostSlug, readStorePreviewToken, readThemePreviewToken, requireSession, resolveComingSoonStore, resolveRootStoreRef, serverConfig };
145
+ export { type CustomerIdentity, type RouteContext, type RouteHandler, createAuthRoutes, createBackendProxy, externalThemeRedirectFor, getServerSdk, hasCustomerSession, parseServerConfig, readPreviewHostSlug, readStorePreviewToken, readThemePreviewToken, requireSession, resolveComingSoonStore, resolveRootStoreRef, serverConfig };
package/dist/server.js CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  createBackendProxy,
5
5
  requireSession
6
6
  } from "./server/routes.js";
7
+ import { getServerSdk } from "./api/server-sdk.js";
7
8
  import { hasCustomerSession } from "./auth/session.js";
8
9
  import { parseServerConfig, serverConfig } from "./config/server.js";
9
10
  import { resolveRootStoreRef } from "./store-scope/root.js";
@@ -16,6 +17,7 @@ export {
16
17
  createAuthRoutes,
17
18
  createBackendProxy,
18
19
  externalThemeRedirectFor,
20
+ getServerSdk,
19
21
  hasCustomerSession,
20
22
  parseServerConfig,
21
23
  readPreviewHostSlug,