@ecomweb/storefront-kit 0.14.0 → 0.15.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 (90) 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 +39 -0
  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/response.js.map +1 -1
  16. package/dist/api/server-sdk.js +41 -0
  17. package/dist/api/server-sdk.js.map +1 -0
  18. package/dist/api/store-preview-header.js.map +1 -1
  19. package/dist/auth/context.js.map +1 -1
  20. package/dist/auth/sdk.js +15 -5
  21. package/dist/auth/sdk.js.map +1 -1
  22. package/dist/auth/session-refresh.js +7 -4
  23. package/dist/auth/session-refresh.js.map +1 -1
  24. package/dist/cart/api.js.map +1 -1
  25. package/dist/cart/server-context.js.map +1 -1
  26. package/dist/checkout/get-payment-state.js +4 -8
  27. package/dist/checkout/get-payment-state.js.map +1 -1
  28. package/dist/checkout/initiate-gateway-payment.js +5 -7
  29. package/dist/checkout/initiate-gateway-payment.js.map +1 -1
  30. package/dist/checkout/order-handoff.js.map +1 -1
  31. package/dist/checkout/payment-redirect.js.map +1 -1
  32. package/dist/checkout/use-checkout.js.map +1 -1
  33. package/dist/client-info.js +1 -1
  34. package/dist/config/public.js +2 -0
  35. package/dist/config/public.js.map +1 -1
  36. package/dist/config/schema.js +16 -4
  37. package/dist/config/schema.js.map +1 -1
  38. package/dist/config/secret-guard.js +20 -0
  39. package/dist/config/secret-guard.js.map +1 -0
  40. package/dist/config/server.js +15 -8
  41. package/dist/config/server.js.map +1 -1
  42. package/dist/config/version-check.js.map +1 -1
  43. package/dist/config.d.ts +22 -4
  44. package/dist/config.js +2 -0
  45. package/dist/config.js.map +1 -1
  46. package/dist/currency.js.map +1 -1
  47. package/dist/index.d.ts +331 -69
  48. package/dist/index.js.map +1 -1
  49. package/dist/logging.js.map +1 -1
  50. package/dist/middleware/create-storefront-middleware.js +14 -3
  51. package/dist/middleware/create-storefront-middleware.js.map +1 -1
  52. package/dist/middleware.d.ts +2 -2
  53. package/dist/middleware.js.map +1 -1
  54. package/dist/{mode-Lm9t4qzX.d.ts → mode-oVZCQxrc.d.ts} +1 -1
  55. package/dist/orders/api-client.js +3 -3
  56. package/dist/orders/api-client.js.map +1 -1
  57. package/dist/orders/bank-transfer.js +1 -1
  58. package/dist/orders/bank-transfer.js.map +1 -1
  59. package/dist/orders/shipment-tracking.js.map +1 -1
  60. package/dist/orders/use-order-status.js +2 -2
  61. package/dist/orders/use-order-status.js.map +1 -1
  62. package/dist/promotions/use-promotion-validation.js +2 -2
  63. package/dist/promotions/use-promotion-validation.js.map +1 -1
  64. package/dist/provider.js.map +1 -1
  65. package/dist/request/served-store.js +5 -0
  66. package/dist/request/served-store.js.map +1 -0
  67. package/dist/{schema-Dg0ZflMW.d.ts → schema-B3nAYiwT.d.ts} +5 -1
  68. package/dist/sdk.js +3 -3
  69. package/dist/sdk.js.map +1 -1
  70. package/dist/server/routes.js +16 -9
  71. package/dist/server/routes.js.map +1 -1
  72. package/dist/server.d.ts +46 -5
  73. package/dist/server.js +2 -0
  74. package/dist/server.js.map +1 -1
  75. package/dist/shipping/location-areas.js.map +1 -1
  76. package/dist/shipping/use-shipping-calculation.js +2 -2
  77. package/dist/shipping/use-shipping-calculation.js.map +1 -1
  78. package/dist/storage.js.map +1 -1
  79. package/dist/store/store-context.js.map +1 -1
  80. package/dist/store-scope/index.js.map +1 -1
  81. package/dist/stores/basic-settings.js.map +1 -1
  82. package/dist/stores/cached.js.map +1 -1
  83. package/dist/theme/define.js.map +1 -1
  84. package/dist/theme/index.js.map +1 -1
  85. package/dist/theme/settings-context.js.map +1 -1
  86. package/dist/theme/style.js.map +1 -1
  87. package/dist/theme.d.ts +33 -0
  88. package/package.json +6 -2
  89. package/dist/api/server-client.js +0 -162
  90. package/dist/api/server-client.js.map +0 -1
@@ -1,5 +1,6 @@
1
1
  import { publicNextUrl } from "../request/public-url.js";
2
2
  import { REQUEST_PATH_HEADER } from "../request/request-path.js";
3
+ import { SERVED_STORE_HEADER } from "../request/served-store.js";
3
4
  import {
4
5
  applyThemePreview,
5
6
  hasThemePreview,
@@ -75,6 +76,7 @@ function withoutInternalHeaders(req) {
75
76
  const headers = new Headers(req.headers);
76
77
  headers.delete(THEME_PREVIEW_HOST_HEADER);
77
78
  headers.delete(STORE_PREVIEW_TOKEN_HEADER);
79
+ headers.delete(SERVED_STORE_HEADER);
78
80
  return { request: { headers } };
79
81
  }
80
82
  function hasStorePreview(req, cookiePath) {
@@ -86,6 +88,11 @@ function hostLookupPreviewToken(req) {
86
88
  req.cookies.get(themePreviewCookieName("/"))?.value
87
89
  );
88
90
  }
91
+ function isLocalDevelopmentHost(host) {
92
+ if (process.env.NODE_ENV === "production") return false;
93
+ const hostname = host.startsWith("[") ? host.slice(0, host.indexOf("]") + 1) : host.split(":")[0];
94
+ return ["localhost", "127.0.0.1", "[::1]"].includes(hostname.toLowerCase());
95
+ }
89
96
  function storeRefFromPath(pathname) {
90
97
  const match = /^\/store\/([^/]+)/.exec(pathname);
91
98
  if (!match) return null;
@@ -139,7 +146,8 @@ async function multiTenant(req) {
139
146
  return NextResponse.next(withoutInternalHeaders(req));
140
147
  }
141
148
  const platformDomain = publicConfig().platformDomainSuffix ?? "ecomsite.app";
142
- const hostIdentifiesStore = !host.includes("localhost") && !host.includes("127.0.0.1") && host !== platformDomain && host !== `www.${platformDomain}`;
149
+ const isLocalDevHost = isLocalDevelopmentHost(host);
150
+ const hostIdentifiesStore = !isLocalDevHost && host !== platformDomain && host !== `www.${platformDomain}`;
143
151
  const isPlatformApex = host === platformDomain || host === `www.${platformDomain}`;
144
152
  if (isPlatformApex) {
145
153
  const apexStoreRef = storeRefFromPath(pathname);
@@ -240,7 +248,10 @@ async function multiTenant(req) {
240
248
  req,
241
249
  !!hostStoreRef,
242
250
  storeRef,
243
- rotated
251
+ rotated,
252
+ // A store host's own lookup decides (none if it failed). Only the local
253
+ // dev host is path-based; anywhere else the path names no served store.
254
+ isLocalDevHost ? storeRefFromPath(pathname) : hostIdentifiesStore ? hostStoreRef : null
244
255
  );
245
256
  downstream.set(
246
257
  REQUEST_PATH_HEADER,
@@ -309,7 +320,7 @@ async function singleStore(req) {
309
320
  const rotated = await refreshIfNearExpiry(req, storeRef, cookiePath);
310
321
  const response = NextResponse.next({
311
322
  request: {
312
- headers: downstreamRequestHeaders(req, true, storeRef, rotated)
323
+ headers: downstreamRequestHeaders(req, true, storeRef, rotated, storeRef)
313
324
  }
314
325
  });
315
326
  if (hasThemePreview(req, cookiePath) || hasStorePreview(req, cookiePath))
@@ -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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AK;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,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,eA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A,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-Lm9t4qzX.js';
3
- import './schema-Dg0ZflMW.js';
2
+ import { S as StorefrontMode } from './mode-oVZCQxrc.js';
3
+ import './schema-B3nAYiwT.js';
4
4
  import 'zod';
5
5
 
6
6
  /**
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/middleware.ts"],"sourcesContent":["// @ecomweb/storefront-kit/middleware: the storefront's proxy.ts.\nexport {\n createStorefrontMiddleware,\n storefrontMiddlewareConfig,\n} from \"./middleware/create-storefront-middleware\";\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,OACK;","names":[]}
1
+ {"version":3,"sources":["../src/middleware.ts"],"sourcesContent":["/**\n * The storefront's request middleware (`proxy.ts`): store routing and the\n * checks that run before a page renders.\n *\n * Import from `@ecomweb/storefront-kit/middleware` in the storefront's\n * `proxy.ts` (or `middleware.ts`).\n *\n * @packageDocumentation\n */\nexport {\n createStorefrontMiddleware,\n storefrontMiddlewareConfig,\n} from \"./middleware/create-storefront-middleware\";\n"],"mappings":"AASA;AAAA,EACE;AAAA,EACA;AAAA,OACK;","names":[]}
@@ -1,4 +1,4 @@
1
- import { E as EnvSource } from './schema-Dg0ZflMW.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,kBA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,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":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/orders/shipment-tracking.ts"],"sourcesContent":["import type { Order, OrderShipmentSummary, ShipmentStatus } from \"@ecomweb/sdk\";\n\n/** The API's SHIPMENT_STATUS_LABEL_VI, copied exactly so badge and events agree. */\nexport const SHIPMENT_STATUS_LABELS: Record<ShipmentStatus, string> = {\n booked: \"Đã tạo vận đơn\",\n picked_up: \"Đã lấy hàng\",\n in_transit: \"Đang vận chuyển\",\n out_for_delivery: \"Đang giao hàng\",\n delivered: \"Đã giao\",\n failed: \"Giao hàng thất bại\",\n returned: \"Đã hoàn hàng\",\n cancelled: \"Đã hủy\",\n};\n\nexport const TRACKING_MESSAGES = {\n title: \"Vận chuyển\",\n trackingNumber: \"Mã vận đơn\",\n trackLink: \"Theo dõi đơn hàng\",\n handedToCarrier: \"Đơn đã được giao cho hãng vận chuyển\",\n noEvents: \"Chưa có cập nhật từ hãng vận chuyển\",\n eventFallback: \"Cập nhật vận chuyển\",\n} as const;\n\nexport interface ShipmentTrackingView {\n carrierName: string | null;\n carrierLogoUrl: string | null;\n serviceName: string | null;\n trackingNumber: string | null;\n trackLink: string | null;\n statusLabel: string | null;\n events: OrderShipmentSummary[\"events\"];\n}\n\nconst CANCELLABLE_STATUSES = [\"pending\", \"confirmed\", \"processing\"];\nconst ENDED_STATUSES: string[] = [\"cancelled\", \"failed\", \"returned\"];\n\nfunction httpLinkOrNull(link: string | null | undefined): string | null {\n return link && /^https?:\\/\\//i.test(link.trim()) ? link.trim() : null;\n}\n\nfunction labelOrNull(status: string | null | undefined): string | null {\n if (!status) return null;\n return Object.prototype.hasOwnProperty.call(SHIPMENT_STATUS_LABELS, status)\n ? SHIPMENT_STATUS_LABELS[status as ShipmentStatus]\n : null;\n}\n\nexport function deriveShipmentTracking(\n order: Order,\n): ShipmentTrackingView | null {\n const shipment = order.shipment;\n // An explicit `shipment: null` means the API decided there is nothing to show\n // (e.g. a cancelled waybill); the order's own fields are only a fallback for\n // an older API that does not send `shipment` at all.\n if (shipment === null) return null;\n if (shipment) {\n return {\n carrierName: shipment.carrier_name ?? null,\n carrierLogoUrl: httpLinkOrNull(shipment.carrier_logo_url),\n serviceName: shipment.service_name ?? null,\n trackingNumber: shipment.tracking_number ?? null,\n trackLink: httpLinkOrNull(shipment.track_link),\n statusLabel: labelOrNull(shipment.status),\n events: shipment.events ?? [],\n };\n }\n if (order.shipping_carrier || order.tracking_number) {\n return {\n carrierName: order.shipping_carrier ?? null,\n carrierLogoUrl: null,\n serviceName: null,\n trackingNumber: order.tracking_number ?? null,\n trackLink: null,\n statusLabel: null,\n events: [],\n };\n }\n return null;\n}\n\nexport function canCustomerCancel(order: Order): boolean {\n if (typeof order.can_cancel === \"boolean\") return order.can_cancel;\n return CANCELLABLE_STATUSES.includes(order.order_status);\n}\n\nexport function isHandedToCarrier(order: Order): boolean {\n const status = order.shipment?.status;\n return !!status && !ENDED_STATUSES.includes(status);\n}\n\n/**\n * True only for a carrier-booked shipment. The API also sends `order.shipment`\n * for a manual shipment (carrier and tracking number typed by the merchant),\n * with `status: null` and no events; that one has no carrier timeline to show.\n */\nexport function isCarrierShipment(order: Order): boolean {\n return order.shipment?.status != null;\n}\n\n/**\n * The text of one tracking event. A blank label falls back to the event's own\n * status label when it carries a known one, else to neutral copy -- never the\n * shipment's current status, which is not what that event reported.\n */\nexport function shipmentEventLabel(event: {\n label?: string | null;\n status?: string | null;\n}): string {\n const label = event.label?.trim();\n if (label) return label;\n return labelOrNull(event.status) ?? TRACKING_MESSAGES.eventFallback;\n}\n"],"mappings":"AAGO,MAAM,yBAAyD;AAAA,EACpE,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,kBAAkB;AAAA,EAClB,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,WAAW;AACb;AAEO,MAAM,oBAAoB;AAAA,EAC/B,OAAO;AAAA,EACP,gBAAgB;AAAA,EAChB,WAAW;AAAA,EACX,iBAAiB;AAAA,EACjB,UAAU;AAAA,EACV,eAAe;AACjB;AAYA,MAAM,uBAAuB,CAAC,WAAW,aAAa,YAAY;AAClE,MAAM,iBAA2B,CAAC,aAAa,UAAU,UAAU;AAEnE,SAAS,eAAe,MAAgD;AACtE,SAAO,QAAQ,gBAAgB,KAAK,KAAK,KAAK,CAAC,IAAI,KAAK,KAAK,IAAI;AACnE;AAEA,SAAS,YAAY,QAAkD;AACrE,MAAI,CAAC,OAAQ,QAAO;AACpB,SAAO,OAAO,UAAU,eAAe,KAAK,wBAAwB,MAAM,IACtE,uBAAuB,MAAwB,IAC/C;AACN;AAEO,SAAS,uBACd,OAC6B;AAC7B,QAAM,WAAW,MAAM;AAIvB,MAAI,aAAa,KAAM,QAAO;AAC9B,MAAI,UAAU;AACZ,WAAO;AAAA,MACL,aAAa,SAAS,gBAAgB;AAAA,MACtC,gBAAgB,eAAe,SAAS,gBAAgB;AAAA,MACxD,aAAa,SAAS,gBAAgB;AAAA,MACtC,gBAAgB,SAAS,mBAAmB;AAAA,MAC5C,WAAW,eAAe,SAAS,UAAU;AAAA,MAC7C,aAAa,YAAY,SAAS,MAAM;AAAA,MACxC,QAAQ,SAAS,UAAU,CAAC;AAAA,IAC9B;AAAA,EACF;AACA,MAAI,MAAM,oBAAoB,MAAM,iBAAiB;AACnD,WAAO;AAAA,MACL,aAAa,MAAM,oBAAoB;AAAA,MACvC,gBAAgB;AAAA,MAChB,aAAa;AAAA,MACb,gBAAgB,MAAM,mBAAmB;AAAA,MACzC,WAAW;AAAA,MACX,aAAa;AAAA,MACb,QAAQ,CAAC;AAAA,IACX;AAAA,EACF;AACA,SAAO;AACT;AAEO,SAAS,kBAAkB,OAAuB;AACvD,MAAI,OAAO,MAAM,eAAe,UAAW,QAAO,MAAM;AACxD,SAAO,qBAAqB,SAAS,MAAM,YAAY;AACzD;AAEO,SAAS,kBAAkB,OAAuB;AACvD,QAAM,SAAS,MAAM,UAAU;AAC/B,SAAO,CAAC,CAAC,UAAU,CAAC,eAAe,SAAS,MAAM;AACpD;AAOO,SAAS,kBAAkB,OAAuB;AACvD,SAAO,MAAM,UAAU,UAAU;AACnC;AAOO,SAAS,mBAAmB,OAGxB;AACT,QAAM,QAAQ,MAAM,OAAO,KAAK;AAChC,MAAI,MAAO,QAAO;AAClB,SAAO,YAAY,MAAM,MAAM,KAAK,kBAAkB;AACxD;","names":[]}
1
+ {"version":3,"sources":["../../src/orders/shipment-tracking.ts"],"sourcesContent":["import type { Order, OrderShipmentSummary, ShipmentStatus } from \"@ecomweb/sdk\";\n\n/** The API's SHIPMENT_STATUS_LABEL_VI, copied exactly so badge and events agree. */\nexport const SHIPMENT_STATUS_LABELS: Record<ShipmentStatus, string> = {\n booked: \"Đã tạo vận đơn\",\n picked_up: \"Đã lấy hàng\",\n in_transit: \"Đang vận chuyển\",\n out_for_delivery: \"Đang giao hàng\",\n delivered: \"Đã giao\",\n failed: \"Giao hàng thất bại\",\n returned: \"Đã hoàn hàng\",\n cancelled: \"Đã hủy\",\n};\n\nexport const TRACKING_MESSAGES = {\n title: \"Vận chuyển\",\n trackingNumber: \"Mã vận đơn\",\n trackLink: \"Theo dõi đơn hàng\",\n handedToCarrier: \"Đơn đã được giao cho hãng vận chuyển\",\n noEvents: \"Chưa có cập nhật từ hãng vận chuyển\",\n eventFallback: \"Cập nhật vận chuyển\",\n} as const;\n\nexport interface ShipmentTrackingView {\n carrierName: string | null;\n carrierLogoUrl: string | null;\n serviceName: string | null;\n trackingNumber: string | null;\n trackLink: string | null;\n statusLabel: string | null;\n events: OrderShipmentSummary[\"events\"];\n}\n\nconst CANCELLABLE_STATUSES = [\"pending\", \"confirmed\", \"processing\"];\nconst ENDED_STATUSES: string[] = [\"cancelled\", \"failed\", \"returned\"];\n\nfunction httpLinkOrNull(link: string | null | undefined): string | null {\n return link && /^https?:\\/\\//i.test(link.trim()) ? link.trim() : null;\n}\n\nfunction labelOrNull(status: string | null | undefined): string | null {\n if (!status) return null;\n return Object.prototype.hasOwnProperty.call(SHIPMENT_STATUS_LABELS, status)\n ? SHIPMENT_STATUS_LABELS[status as ShipmentStatus]\n : null;\n}\n\n/**\n * Builds the shipment details to show for an order: carrier, tracking number,\n * tracking link, status and events. Uses the order's `shipment` when the API\n * sends one and falls back to the order's carrier and tracking fields for an\n * older API.\n *\n * @param order - The order to read.\n * @returns The shipment view, or `null` when there is nothing to show.\n */\nexport function deriveShipmentTracking(\n order: Order,\n): ShipmentTrackingView | null {\n const shipment = order.shipment;\n // An explicit `shipment: null` means the API decided there is nothing to show\n // (e.g. a cancelled waybill); the order's own fields are only a fallback for\n // an older API that does not send `shipment` at all.\n if (shipment === null) return null;\n if (shipment) {\n return {\n carrierName: shipment.carrier_name ?? null,\n carrierLogoUrl: httpLinkOrNull(shipment.carrier_logo_url),\n serviceName: shipment.service_name ?? null,\n trackingNumber: shipment.tracking_number ?? null,\n trackLink: httpLinkOrNull(shipment.track_link),\n statusLabel: labelOrNull(shipment.status),\n events: shipment.events ?? [],\n };\n }\n if (order.shipping_carrier || order.tracking_number) {\n return {\n carrierName: order.shipping_carrier ?? null,\n carrierLogoUrl: null,\n serviceName: null,\n trackingNumber: order.tracking_number ?? null,\n trackLink: null,\n statusLabel: null,\n events: [],\n };\n }\n return null;\n}\n\n/**\n * Tells whether the shopper may still cancel the order. Follows the API's\n * `can_cancel` flag when present, else the order status.\n *\n * @param order - The order to check.\n * @returns `true` when the order can be cancelled.\n */\nexport function canCustomerCancel(order: Order): boolean {\n if (typeof order.can_cancel === \"boolean\") return order.can_cancel;\n return CANCELLABLE_STATUSES.includes(order.order_status);\n}\n\n/**\n * Tells whether the order's shipment has been handed to a carrier and is not\n * cancelled, failed or returned.\n *\n * @param order - The order to check.\n * @returns `true` while the shipment is with a carrier.\n */\nexport function isHandedToCarrier(order: Order): boolean {\n const status = order.shipment?.status;\n return !!status && !ENDED_STATUSES.includes(status);\n}\n\n/**\n * True only for a carrier-booked shipment. The API also sends `order.shipment`\n * for a manual shipment (carrier and tracking number typed by the merchant),\n * with `status: null` and no events; that one has no carrier timeline to show.\n */\nexport function isCarrierShipment(order: Order): boolean {\n return order.shipment?.status != null;\n}\n\n/**\n * The text of one tracking event. A blank label falls back to the event's own\n * status label when it carries a known one, else to neutral copy -- never the\n * shipment's current status, which is not what that event reported.\n */\nexport function shipmentEventLabel(event: {\n label?: string | null;\n status?: string | null;\n}): string {\n const label = event.label?.trim();\n if (label) return label;\n return labelOrNull(event.status) ?? TRACKING_MESSAGES.eventFallback;\n}\n"],"mappings":"AAGO,MAAM,yBAAyD;AAAA,EACpE,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,kBAAkB;AAAA,EAClB,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,WAAW;AACb;AAEO,MAAM,oBAAoB;AAAA,EAC/B,OAAO;AAAA,EACP,gBAAgB;AAAA,EAChB,WAAW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C,CAAC,UAAU,CAAC,eAAe,SAAS,MAAM;AACpD;AAOO,SAAS,kBAAkB,OAAuB;AACvD,SAAO,MAAM,UAAU,UAAU;AACnC;AAOO,SAAS,mBAAmB,OAGxB;AACT,QAAM,QAAQ,MAAM,OAAO,KAAK;AAChC,MAAI,MAAO,QAAO;AAClB,SAAO,YAAY,MAAM,MAAM,KAAK,kBAAkB;AACxD;","names":[]}
@@ -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,OAEK;AACP,SAAS,WAAW;AACpB,SAAS,kBAAkB;AAC3B,SAAS,8BAA8B;AAIvC,MAAM,YAAY,IAAI,MAAM,yBAAyB;AAErD,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A,IACA,SAAS,EAAE,OAAO,UAAU;AAAA,IAC5B,cAAc,EAAE,UAAU,aAAa,UAAU,MAAM,aAAa,KAAK;AAAA,EAC3E;AACF;AAMO,SAAS,eAAe;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AACF,GAIG;AACD,QAAM,WAAW,WAAW;AAC5B,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAgC,IAAI;AAC9D,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,IAAI;AAC/C,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAwB,IAAI;AAEtD,QAAM,aAAa,YAAY,YAAY;AACzC,QAAI,CAAC,aAAc,CAAC,SAAS,CAAC,OAAQ;AACpC,eAAS,6FAA+C;AACxD,mBAAa,KAAK;AAClB;AAAA,IACF;AACA,QAAI;AACF,mBAAa,IAAI;AACjB,eAAS,IAAI;AACb,YAAM,QAAQ,MAAM,IAAI,OAAO,YAAY,UAAU;AAAA,QACnD,YAAY;AAAA,QACZ,gBAAgB,SAAS;AAAA,QACzB,gBAAgB,SAAS;AAAA,MAC3B,CAAC;AACD,UAAI,CAAC,OAAO;AACV,iBAAS,gGAAmD;AAC5D;AAAA,MACF;AACA,eAAS,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
+ {"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 { 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,MACf,MAAM,MAAM,gBAAgB,UAAU,SAAS;AAAA;AAAA,MAE/C,MAAM,OAAM,OAAM;AAChB,YAAI,UAAW,OAAM;AACrB,cAA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ACA,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,gDAA6B;AAC3C;AAAA,MACF;AAEA,2BAAqB,IAAI;AACzB,oBAAc,EAAE;AAEhB,UAAI;AACF,cAAM,SAAS,MAAM,IAAI,W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G9B,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,MAAM,eAAe,KAAK;AAAA,UAC1B,OAAO,MAAM,IAAI,WAAS;AAAA,YACxB,YAAY,KAAK;AAAA,YACjB,YAAY,KAAK,aAAa;AA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AGL,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 +1 @@
1
- {"version":3,"sources":["../src/provider.tsx"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useRef, type ReactNode } from \"react\";\nimport type { StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { AuthProvider, useAuth } from \"./auth/context\";\nimport { CartProvider } from \"./cart/server-context\";\nimport { NoticeProvider, type NoticeHandler } from \"./notices\";\nimport { StoreProvider } from \"./store/store-context\";\nimport {\n setBrowserStorePreviewToken,\n setStorePreviewRenewer,\n} from \"./api/store-preview-header\";\n\n/**\n * How often a preview host's preview token is renewed: half of its 1 h, so\n * a long editor session never sends an expired one.\n */\nconst STORE_PREVIEW_RENEW_MS = 30 * 60 * 1000;\n\nexport interface StorefrontKitProviderProps {\n store: StoreConfigurationInfo;\n /** The ref the cart is scoped to; defaults to `store.ref`. */\n storeRef?: string;\n /** Receives the kit's notices (item added, request failed, …). */\n onNotice?: NoticeHandler;\n /**\n * The store preview token the browser's kit clients send as\n * `X-Store-Preview` (`readStorePreviewToken()` on the server). The layout\n * passes it only while the store is coming soon, else null.\n *\n * Why the browser gets it: the preview cookie stays httpOnly, but without\n * the token the client-side fetches on the home, collection and product\n * pages would get the API's 403 during a preview. It is one of three\n * tokens: the store preview cookie's (the dashboard's preview link), a\n * theme preview host's (`p-<slug>`, from the host lookup), or the theme\n * preview cookie's (`?preview_theme=` on the store's own host). Each is\n * read-only (the API opens GET and HEAD only) and bound to one store.\n * Merchant scripts are off during a store preview, so they never see it.\n */\n storePreviewToken?: string | null;\n /**\n * Fetches a fresh `storePreviewToken`, such as by re-rendering the layout.\n * The app passes it only on a theme preview host, whose token lasts 1 h:\n * the layout does not re-render on client navigation, so the first\n * render's token would run out in a long editor session. While both are\n * set, the kit calls it every 30 minutes, and when a read is refused with\n * `STORE_COMING_SOON` (at most once a minute). A link preview's 24 h\n * cookie is not renewed.\n */\n onStorePreviewRenew?: () => void;\n children: ReactNode;\n}\n\nfunction IdentityCart({\n storeRef,\n children,\n}: {\n storeRef: string;\n children: ReactNode;\n}) {\n const { user } = useAuth();\n return (\n <CartProvider storeRef={storeRef} userId={user?.id}>\n {children}\n </CartProvider>\n );\n}\n\n/**\n * The kit's providers in their required order: auth reads the store, and the\n * cart reads the signed-in identity from auth.\n */\nexport function StorefrontKitProvider({\n store,\n storeRef,\n onNotice,\n storePreviewToken,\n onStorePreviewRenew,\n children,\n}: StorefrontKitProviderProps) {\n // In the render body, not an effect: React renders this before any child\n // effect runs, so the first client fetch already carries the token. A\n // render without one clears it; until then it stays set (store-preview-\n // header.ts). A no-op on the server.\n setBrowserStorePreviewToken(storePreviewToken ?? null);\n\n // The latest callback, so an app that passes a new function on every\n // render does not restart the 30 minute timer each time.\n const renewRef = useRef(onStorePreviewRenew);\n renewRef.current = onStorePreviewRenew;\n const renews = !!storePreviewToken && !!onStorePreviewRenew;\n useEffect(() => {\n if (!renews) return;\n const renew = () => renewRef.current?.();\n setStorePreviewRenewer(renew);\n const timer = setInterval(renew, STORE_PREVIEW_RENEW_MS);\n return () => {\n clearInterval(timer);\n setStorePreviewRenewer(null);\n };\n }, [renews]);\n\n return (\n <StoreProvider store={store}>\n <NoticeProvider onNotice={onNotice}>\n <AuthProvider>\n <IdentityCart storeRef={storeRef ?? store.ref}>\n {children}\n </IdentityCart>\n </AuthProvider>\n </NoticeProvider>\n </StoreProvider>\n );\n}\n"],"mappings":";AA8DI;AA5DJ,SAAS,WAAW,cAA8B;AAElD,SAAS,cAAc,eAAe;AACtC,SAAS,oBAAoB;AAC7B,SAAS,sBAA0C;AACnD,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAMP,MAAM,yBAAyB,KAAK,KAAK;AAoCzC,SAAS,aAAa;AAAA,EACpB;AAAA,EACA;AACF,GAGG;AACD,QAAM,EAAE,KAAK,IAAI,QAAQ;AACzB,SACE,oBAAC,gBAAa,UAAoB,QAAQ,MAAM,IAC7C,UACH;AAEJ;AAMO,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA+B;AAK7B,8BAA4B,qBAAqB,IAAI;AAIrD,QAAM,WAAW,OAAO,mBAAmB;AAC3C,WAAS,UAAU;AACnB,QAAM,SAAS,CAAC,CAAC,qBAAqB,CAAC,CAAC;AACxC,YAAU,MAAM;AACd,QAAI,CAAC,OAAQ;AACb,UAAM,QAAQ,MAAM,SAAS,UAAU;AACvC,2BAAuB,KAAK;AAC5B,UAAM,QAAQ,YAAY,OAAO,sBAAsB;AACvD,WAAO,MAAM;AACX,oBAAc,KAAK;AACnB,6BAAuB,IAAI;AAAA,IAC7B;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AAEX,SACE,oBAAC,iBAAc,OACb,8BAAC,kBAAe,UACd,8BAAC,gBACC,8BAAC,gBAAa,UAAU,YAAY,MAAM,KACvC,UACH,GACF,GACF,GACF;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../src/provider.tsx"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useRef, type ReactNode } from \"react\";\nimport type { StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { AuthProvider, useAuth } from \"./auth/context\";\nimport { CartProvider } from \"./cart/server-context\";\nimport { NoticeProvider, type NoticeHandler } from \"./notices\";\nimport { StoreProvider } from \"./store/store-context\";\nimport {\n setBrowserStorePreviewToken,\n setStorePreviewRenewer,\n} from \"./api/store-preview-header\";\n\n/**\n * How often a preview host's preview token is renewed: half of its 1 h, so\n * a long editor session never sends an expired one.\n */\nconst STORE_PREVIEW_RENEW_MS = 30 * 60 * 1000;\n\n/** Props of {@link StorefrontKitProvider}. */\nexport interface StorefrontKitProviderProps {\n store: StoreConfigurationInfo;\n /** The ref the cart is scoped to; defaults to `store.ref`. */\n storeRef?: string;\n /** Receives the kit's notices (item added, request failed, …). */\n onNotice?: NoticeHandler;\n /**\n * The store preview token the browser's kit clients send as\n * `X-Store-Preview` (`readStorePreviewToken()` on the server). The layout\n * passes it only while the store is coming soon, else null.\n *\n * Why the browser gets it: the preview cookie stays httpOnly, but without\n * the token the client-side fetches on the home, collection and product\n * pages would get the API's 403 during a preview. It is one of three\n * tokens: the store preview cookie's (the dashboard's preview link), a\n * theme preview host's (`p-<slug>`, from the host lookup), or the theme\n * preview cookie's (`?preview_theme=` on the store's own host). Each is\n * read-only (the API opens GET and HEAD only) and bound to one store.\n * Merchant scripts are off during a store preview, so they never see it.\n */\n storePreviewToken?: string | null;\n /**\n * Fetches a fresh `storePreviewToken`, such as by re-rendering the layout.\n * The app passes it only on a theme preview host, whose token lasts 1 h:\n * the layout does not re-render on client navigation, so the first\n * render's token would run out in a long editor session. While both are\n * set, the kit calls it every 30 minutes, and when a read is refused with\n * `STORE_COMING_SOON` (at most once a minute). A link preview's 24 h\n * cookie is not renewed.\n */\n onStorePreviewRenew?: () => void;\n children: ReactNode;\n}\n\nfunction IdentityCart({\n storeRef,\n children,\n}: {\n storeRef: string;\n children: ReactNode;\n}) {\n const { user } = useAuth();\n return (\n <CartProvider storeRef={storeRef} userId={user?.id}>\n {children}\n </CartProvider>\n );\n}\n\n/**\n * The kit's providers in their required order: auth reads the store, and the\n * cart reads the signed-in identity from auth.\n */\nexport function StorefrontKitProvider({\n store,\n storeRef,\n onNotice,\n storePreviewToken,\n onStorePreviewRenew,\n children,\n}: StorefrontKitProviderProps) {\n // In the render body, not an effect: React renders this before any child\n // effect runs, so the first client fetch already carries the token. A\n // render without one clears it; until then it stays set (store-preview-\n // header.ts). A no-op on the server.\n setBrowserStorePreviewToken(storePreviewToken ?? null);\n\n // The latest callback, so an app that passes a new function on every\n // render does not restart the 30 minute timer each time.\n const renewRef = useRef(onStorePreviewRenew);\n renewRef.current = onStorePreviewRenew;\n const renews = !!storePreviewToken && !!onStorePreviewRenew;\n useEffect(() => {\n if (!renews) return;\n const renew = () => renewRef.current?.();\n setStorePreviewRenewer(renew);\n const timer = setInterval(renew, STORE_PREVIEW_RENEW_MS);\n return () => {\n clearInterval(timer);\n setStorePreviewRenewer(null);\n };\n }, [renews]);\n\n return (\n <StoreProvider store={store}>\n <NoticeProvider onNotice={onNotice}>\n <AuthProvider>\n <IdentityCart storeRef={storeRef ?? store.ref}>\n {children}\n </IdentityCart>\n </AuthProvider>\n </NoticeProvider>\n </StoreProvider>\n );\n}\n"],"mappings":";AA+DI;AA7DJ,SAAS,WAAW,cAA8B;AAElD,SAAS,cAAc,eAAe;AACtC,SAAS,oBAAoB;AAC7B,SAAS,sBAA0C;AACnD,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAMP,MAAM,yBAAyB,KAAK,KAAK;AAqCzC,SAAS,aAAa;AAAA,EACpB;AAAA,EACA;AACF,GAGG;AACD,QAAM,EAAE,KAAK,IAAI,QAAQ;AACzB,SACE,oBAAC,gBAAa,UAAoB,QAAQ,MAAM,IAC7C,UACH;AAEJ;AAMO,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA+B;AAK7B,8BAA4B,qBAAqB,IAAI;AAIrD,QAAM,WAAW,OAAO,mBAAmB;AAC3C,WAAS,UAAU;AACnB,QAAM,SAAS,CAAC,CAAC,qBAAqB,CAAC,CAAC;AACxC,YAAU,MAAM;AACd,QAAI,CAAC,OAAQ;AACb,UAAM,QAAQ,MAAM,SAAS,UAAU;AACvC,2BAAuB,KAAK;AAC5B,UAAM,QAAQ,YAAY,OAAO,sBAAsB;AACvD,WAAO,MAAM;AACX,oBAAc,KAAK;AACnB,6BAAuB,IAAI;AAAA,IAC7B;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AAEX,SACE,oBAAC,iBAAc,OACb,8BAAC,kBAAe,UACd,8BAAC,gBACC,8BAAC,gBAAa,UAAU,YAAY,MAAM,KACvC,UACH,GACF,GACF,GACF;AAEJ;","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;
@@ -46,6 +46,10 @@ declare const serverConfigSchema: z.ZodObject<{
46
46
  storeTrafficLogPerMinute: z.ZodNumber;
47
47
  }, z.core.$strip>;
48
48
  type ServerConfig = z.infer<typeof serverConfigSchema>;
49
+ /**
50
+ * Thrown when the storefront's environment variables are missing or invalid.
51
+ * The message names the variable behind every bad field.
52
+ */
49
53
  declare class ConfigError extends Error {
50
54
  constructor(message: string);
51
55
  }
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":[]}