@ecomweb/storefront-kit 0.10.0 → 0.11.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.
- package/README.md +57 -2
- package/dist/api/client.js +32 -1
- package/dist/api/client.js.map +1 -1
- package/dist/api/proxy.js +29 -4
- package/dist/api/proxy.js.map +1 -1
- package/dist/api/store-preview-header.js +42 -0
- package/dist/api/store-preview-header.js.map +1 -0
- package/dist/auth/error-copy.js +2 -1
- package/dist/auth/error-copy.js.map +1 -1
- package/dist/auth/session-refresh.js +2 -0
- package/dist/auth/session-refresh.js.map +1 -1
- package/dist/cart/server-context.js +26 -0
- package/dist/cart/server-context.js.map +1 -1
- package/dist/checkout/use-checkout.js +9 -0
- package/dist/checkout/use-checkout.js.map +1 -1
- package/dist/index.d.ts +69 -3
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -1
- package/dist/middleware/create-storefront-middleware.js +58 -11
- package/dist/middleware/create-storefront-middleware.js.map +1 -1
- package/dist/middleware.d.ts +5 -2
- package/dist/provider.js +22 -0
- package/dist/provider.js.map +1 -1
- package/dist/redirects/lookup-redirect.js +2 -1
- package/dist/redirects/lookup-redirect.js.map +1 -1
- package/dist/server.d.ts +20 -1
- package/dist/server.js +4 -0
- package/dist/server.js.map +1 -1
- package/dist/stores/get-store-by-host.js +34 -7
- package/dist/stores/get-store-by-host.js.map +1 -1
- package/dist/stores/metadata.js +17 -0
- package/dist/stores/metadata.js.map +1 -1
- package/dist/stores/read-store-preview-token.js +10 -0
- package/dist/stores/read-store-preview-token.js.map +1 -0
- package/dist/stores/resolve-coming-soon.js +30 -0
- package/dist/stores/resolve-coming-soon.js.map +1 -0
- package/dist/stores/store-coming-soon.js +21 -0
- package/dist/stores/store-coming-soon.js.map +1 -0
- package/dist/stores/store-preview-cookie.js +64 -0
- package/dist/stores/store-preview-cookie.js.map +1 -0
- package/dist/stores/store-preview-guard.js +12 -0
- package/dist/stores/store-preview-guard.js.map +1 -0
- package/dist/stores/store-subdomain.js +10 -5
- package/dist/stores/store-subdomain.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/middleware/create-storefront-middleware.ts"],"sourcesContent":["import { publicNextUrl } from \"../request/public-url\";\nimport { REQUEST_PATH_HEADER } from \"../request/request-path\";\nimport {\n applyThemePreview,\n hasThemePreview,\n THEME_PREVIEW_PARAM,\n} from \"../theme/preview-cookie\";\nimport {\n externalStorefrontUrl,\n isSameHost,\n} from \"../theme/external-storefront\";\nimport { NextRequest, NextResponse } from \"next/server\";\nimport type { UrlRedirect } from \"@ecomweb/sdk\";\nimport { authCookiePath, writeAuthCookies } from \"../auth/cookies\";\nimport {\n downstreamRequestHeaders,\n refreshIfNearExpiry,\n} from \"../auth/session-refresh\";\nimport type { StorefrontMode } from \"../config/mode\";\nimport { publicConfig } from \"../config/public\";\nimport { lookupRedirect } from \"../redirects/lookup-redirect\";\nimport { multiTenantStorePath } from \"../store-scope\";\nimport { getStoreByHost } from \"../stores/get-store-by-host\";\nimport { getStoreSubdomain } from \"../stores/store-subdomain\";\nimport { recordStoreRequest } from \"../stores/store-traffic\";\nimport {\n PREVIEW_HOST_ROBOTS,\n THEME_PREVIEW_HOST_HEADER,\n} from \"../theme/preview-host\";\n\n/** Served from the app root in both modes; never rewritten or redirected. */\nconst METADATA_FILES = [\n \"/robots.txt\",\n \"/sitemap.xml\",\n \"/favicon.ico\",\n \"/manifest.json\",\n \"/manifest.webmanifest\",\n \"/icon\",\n \"/apple-icon\",\n];\n\n/**\n * Metadata files that follow the store to an external site: crawlers must\n * find the external site's robots.txt and sitemap, not ours.\n */\nconst EXTERNAL_METADATA_FILES = [\"/robots.txt\", \"/sitemap.xml\"];\n\n/** Rewrite target when a store's external URL still points at Ecomweb. */\nconst DOMAIN_NOT_CONNECTED_PATH = \"/domain-not-connected\";\n\n/**\n * The response for a store whose live theme is external, or null to serve\n * the request here (theme anatomy spec, \"Storefront\"):\n * - 302 to the external URL with the same path and query (307 for non-GET,\n * so the method survives); never 301, the merchant may switch back.\n * - never while previewing (`?preview_theme=` or the preview cookie): a\n * preview of an Ecomweb theme must render here.\n * - the external URL is this very host (the domain still points at Ecomweb):\n * a \"domain not connected\" page rather than a redirect loop (robots.txt\n * and the sitemap are still served here).\n * - no usable URL: null (fail open).\n */\nfunction externalThemeResponse(\n req: NextRequest,\n host: string,\n storeRef: string,\n externalUrl: string | null | undefined\n): NextResponse | null {\n if (!externalUrl) return null;\n if (\n req.nextUrl.searchParams.has(THEME_PREVIEW_PARAM) ||\n hasThemePreview(req, authCookiePath(storeRef, true))\n )\n return null;\n\n const pathname = req.nextUrl.pathname;\n const prefix = multiTenantStorePath(storeRef);\n const logicalPath =\n pathname === prefix || pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length) || \"/\"\n : pathname;\n const target = externalStorefrontUrl(\n externalUrl,\n logicalPath,\n req.nextUrl.search\n );\n if (!target) return null;\n\n if (isSameHost(host, target.hostname)) {\n // Our own robots.txt and sitemap still describe this host correctly.\n if (EXTERNAL_METADATA_FILES.includes(pathname)) return null;\n const url = req.nextUrl.clone();\n url.pathname = DOMAIN_NOT_CONNECTED_PATH;\n url.search = \"\";\n const res = NextResponse.rewrite(url);\n res.headers.set(\"x-robots-tag\", \"noindex\");\n return res;\n }\n\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\n}\n\n/**\n * The store a request belongs to, as far as the *path* can say.\n *\n * On localhost and on the platform apex there is no host→store mapping, but\n * the path is `/store/<storeRef>/…` — which is also how the auth cookies are\n * named. `params.storeRef` arrives URL-decoded downstream, so decode here too.\n */\nfunction storeRefFromPath(pathname: string): string | null {\n const match = /^\\/store\\/([^/]+)/.exec(pathname);\n if (!match) return null;\n try {\n return decodeURIComponent(match[1]) || null;\n } catch {\n return match[1];\n }\n}\n\n/**\n * Turns a stored redirect row into the 301/302 response for it.\n *\n * `pathPrefix` re-adds the `/store/<ref>` segment that direct path-based\n * access needs on the destination but a host-mapped request (whose\n * `destination_path` is already store-root-relative) does not.\n */\nfunction buildRedirectResponse(\n req: NextRequest,\n redirect: UrlRedirect,\n pathPrefix = \"\"\n): NextResponse {\n const redirectUrl = publicNextUrl(req);\n redirectUrl.pathname = `${pathPrefix}${redirect.destination_path}`;\n return NextResponse.redirect(redirectUrl, { status: redirect.redirect_type });\n}\n\n/**\n * `/store/<ref>/…` on the platform apex: never served here, sent to the\n * store's own subdomain instead.\n *\n * On the apex every store shares one origin, and a merchant's embedded\n * scripts run there. A cookie's Path is no boundary between pages of one\n * origin: store A's script could fetch `/store/B/api/…` with B's shopper\n * cookies attached, or frame `/store/B` and read it. Each store's subdomain\n * is its own origin. Localhost keeps path-based access (it is not the apex).\n *\n * 302 (307 for non-GET), not 301: the merchant may change the subdomain.\n * The subdomain then sends shoppers on to a custom domain when there is one.\n * No store, no subdomain, or the API unreachable: the 404 page.\n */\nasync function apexStoreResponse(\n req: NextRequest,\n storeRef: string,\n platformDomain: string\n): Promise<NextResponse> {\n let subdomain: string | null = null;\n try {\n subdomain = await getStoreSubdomain(storeRef);\n } catch (error) {\n console.error(\"Store lookup failed for apex path:\", storeRef, error);\n }\n\n if (!subdomain) {\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n url.search = \"\";\n return NextResponse.rewrite(url);\n }\n\n const prefix = multiTenantStorePath(storeRef);\n const pathname = req.nextUrl.pathname;\n const target = publicNextUrl(req);\n target.hostname = `${subdomain}.${platformDomain}`;\n target.port = \"\";\n target.pathname = pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length)\n : \"/\";\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\n}\n\nasync function multiTenant(req: NextRequest): Promise<NextResponse> {\n const host = req.headers.get(\"host\") || \"\";\n const pathname = req.nextUrl.pathname;\n\n // Skip metadata files - these are served from app root level - except the\n // ones that follow an external theme (checked once the store is known).\n const isMetadataFile = METADATA_FILES.includes(pathname);\n if (isMetadataFile && !EXTERNAL_METADATA_FILES.includes(pathname)) {\n return NextResponse.next();\n }\n\n // Store-by-host resolution and redirect lookup genuinely do not apply on\n // localhost or on the platform apex — but the token refresh below does, so\n // these only skip the host-specific work now, not the whole middleware.\n const platformDomain = publicConfig().platformDomainSuffix ?? \"ecomsite.app\";\n const hostIdentifiesStore =\n !host.includes(\"localhost\") &&\n !host.includes(\"127.0.0.1\") &&\n host !== platformDomain &&\n host !== `www.${platformDomain}`;\n\n const isPlatformApex =\n host === platformDomain || host === `www.${platformDomain}`;\n if (isPlatformApex) {\n const apexStoreRef = storeRefFromPath(pathname);\n if (apexStoreRef)\n return apexStoreResponse(req, apexStoreRef, platformDomain);\n }\n\n let hostStoreRef: string | null = null;\n let hostResolved = false;\n\n let hostStoreSuspended = false;\n // A theme's preview host (theme preview hosts): the theme's slug.\n let previewSlug: string | null = null;\n\n if (isMetadataFile && !hostIdentifiesStore) return NextResponse.next();\n\n if (hostIdentifiesStore) {\n try {\n const lookup = await getStoreByHost(host);\n const { storeRef, domain, isSubDomain, suspended, externalUrl } = lookup;\n hostResolved = true;\n hostStoreRef = storeRef || null;\n hostStoreSuspended = suspended;\n previewSlug = storeRef ? lookup.previewSlug : null;\n\n // Nothing on a preview host is for search engines.\n if (previewSlug && isMetadataFile) {\n return pathname === \"/robots.txt\"\n ? new NextResponse(PREVIEW_HOST_ROBOTS, {\n headers: { \"content-type\": \"text/plain\" },\n })\n : new NextResponse(null, { status: 404 });\n }\n\n if (storeRef) {\n // An external theme is live: the shopper belongs on that site. Before\n // the subdomain → custom domain redirect, which would only add a hop.\n const external = externalThemeResponse(\n req,\n host,\n storeRef,\n externalUrl\n );\n if (external) return external;\n }\n\n if (isMetadataFile) return NextResponse.next();\n\n if (storeRef) {\n // If accessing via subdomain but custom domain exists, redirect to\n // custom domain. Not a preview host: it is the theme's, not the store's.\n if (isSubDomain && domain && domain !== host && !previewSlug) {\n const url = publicNextUrl(req);\n url.hostname = domain;\n url.protocol = \"https:\";\n url.port = \"\"; // Remove port for custom domain\n return NextResponse.redirect(url, { status: 301 });\n }\n\n // Check for URL redirects BEFORE rewriting\n // Skip redirect check if path already starts with /store/ (internal rewrite)\n if (!pathname.startsWith(multiTenantStorePath(storeRef))) {\n const redirect = await lookupRedirect(storeRef, pathname);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect);\n }\n }\n }\n } catch (error) {\n console.debug(\"Middleware error:\", error);\n if (isMetadataFile) return NextResponse.next();\n // Fall through: no host mapping, but the refresh below still applies.\n hostResolved = false;\n hostStoreRef = null;\n }\n }\n\n // The host names the store on custom domains and subdomains; everywhere else\n // (localhost, the apex, direct /store/<ref>/… access) the path does.\n const storeRef = hostStoreRef ?? storeRefFromPath(pathname);\n if (storeRef) recordStoreRequest(storeRef);\n\n // A dashboard preview link: store its token in a cookie, then redirect to\n // the clean URL (themes spec §6.1).\n const cookiePath = storeRef ? authCookiePath(storeRef, !!hostStoreRef) : null;\n if (storeRef && cookiePath) {\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\n }\n\n // Direct /store/<ref>/… access never goes through the host-mapped branch\n // above, so it gets no redirect check there. `redirect_source_path` rows\n // are store-root-relative (e.g. \"/old\"), the same shape a host-mapped\n // request already checks against — strip the /store/<ref> prefix to\n // recover that shape, and re-add it on the destination.\n if (!hostStoreRef && storeRef) {\n const prefix = multiTenantStorePath(storeRef);\n if (pathname === prefix || pathname.startsWith(`${prefix}/`)) {\n try {\n const logicalPath = pathname.slice(prefix.length) || \"/\";\n const redirect = await lookupRedirect(storeRef, logicalPath);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect, prefix);\n }\n } catch (error) {\n // Fail open: lookupRedirect already catches internally and never\n // rejects, but this belongs to the caller's contract, not the\n // callee's — a future regression there must not take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n }\n }\n\n const rotated =\n storeRef && cookiePath\n ? await refreshIfNearExpiry(req, storeRef, cookiePath)\n : null;\n const downstream = downstreamRequestHeaders(\n req,\n !!hostStoreRef,\n storeRef,\n rotated\n );\n downstream.set(\n REQUEST_PATH_HEADER,\n `${req.nextUrl.pathname}${req.nextUrl.search}`\n );\n if (previewSlug) downstream.set(THEME_PREVIEW_HOST_HEADER, previewSlug);\n const init = { request: { headers: downstream } };\n\n let response: NextResponse;\n\n if (hostStoreRef) {\n const url = req.nextUrl.clone();\n // Only rewrite if the path doesn't already start with /store/\n if (!url.pathname.startsWith(multiTenantStorePath(hostStoreRef))) {\n url.pathname = multiTenantStorePath(hostStoreRef, url.pathname);\n }\n\n response = NextResponse.rewrite(url, init);\n // Add headers to indicate this is a domain-mapped store\n response.headers.set(\"x-store-domain\", \"true\");\n response.headers.set(\"x-store-ref\", hostStoreRef);\n } else if (hostStoreSuspended) {\n // A platform admin suspended this store. The 403 the backend returned\n // for a domain lookup carries no ref/id to route on (see\n // getStoreByHost), so this can't rewrite to `/store/<ref>` the way the\n // resolved-store branch above does — it goes to a platform-level page\n // instead of the not-found path below.\n const url = req.nextUrl.clone();\n url.pathname = \"/store-suspended\";\n response = NextResponse.rewrite(url, init);\n } else if (hostResolved) {\n // The host looked like a store host but resolved to nothing: 404.\n console.debug(\"Store not found for host:\", host);\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n response = NextResponse.rewrite(url, init);\n } else {\n response = NextResponse.next(init);\n }\n\n if (previewSlug || (cookiePath && hasThemePreview(req, cookiePath))) {\n response.headers.set(\"x-robots-tag\", \"noindex\");\n }\n\n if (rotated && storeRef && cookiePath) {\n // Same path the auth route handler writes with, from the same signal.\n writeAuthCookies(response, storeRef, rotated, cookiePath);\n }\n\n return response;\n}\n\n/**\n * Single-store middleware: the store is fixed by ECOMWEB_STORE_REF, so there\n * is no host lookup and no rewrite. It applies the store's URL redirects and\n * refreshes a near-expiry session. Requests are stamped host-mapped, so auth\n * cookies use Path=/ (see auth/cookies.ts).\n */\nasync function singleStore(req: NextRequest): Promise<NextResponse> {\n const pathname = req.nextUrl.pathname;\n if (METADATA_FILES.includes(pathname)) return NextResponse.next();\n\n const storeRef = publicConfig().storeRef as string;\n\n const cookiePath = authCookiePath(storeRef, true);\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\n\n try {\n const redirect = await lookupRedirect(storeRef, pathname);\n if (redirect) {\n const url = publicNextUrl(req);\n url.pathname = redirect.destination_path;\n return NextResponse.redirect(url, { status: redirect.redirect_type });\n }\n } catch (error) {\n // Fail open: a redirect lookup must never take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n\n const rotated = await refreshIfNearExpiry(req, storeRef, cookiePath);\n const response = NextResponse.next({\n request: {\n headers: downstreamRequestHeaders(req, true, storeRef, rotated),\n },\n });\n\n if (hasThemePreview(req, cookiePath))\n response.headers.set(\"x-robots-tag\", \"noindex\");\n if (rotated) {\n writeAuthCookies(response, storeRef, rotated, cookiePath);\n }\n return response;\n}\n\n/**\n * The storefront's proxy.ts (Next middleware).\n * - multi: host → store lookup, rewrites to /store/<ref>, suspended and\n * unknown stores, redirects, session refresh.\n * - single: redirects and session refresh only.\n * Without `mode`, the configured mode (ECOMWEB_MODE) decides per request.\n */\nexport function createStorefrontMiddleware(\n opts: { mode?: StorefrontMode } = {}\n): (req: NextRequest) => Promise<NextResponse> {\n return req =>\n (opts.mode ?? publicConfig().mode) === \"multi\"\n ? multiTenant(req)\n : singleStore(req);\n}\n\n/**\n * Next reads `config` from proxy.ts statically, so an app re-exports this as\n * `export const config = { matcher: [...] }` with the same literal.\n */\nexport const storefrontMiddlewareConfig = {\n matcher: [\n /*\n * Match all request paths except for the ones starting with:\n * - api (API routes)\n * - _next/static (static files)\n * - _next/image (image optimization files)\n * - _vercel (Vercel Analytics; off Vercel, a store page render per hit)\n * - favicon.ico (favicon file)\n */\n \"/((?!api|_next/static|_next/image|_vercel|favicon.ico).*)\",\n ],\n};\n"],"mappings":"AAAA,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC;AAAA,EAC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EhE,QAAM,WAAW,aAAa,EAAE;AAEhC,QAAM,aAAa,eAAe,UAAU,IAAI;AAChD,QAAM,UAAU,kBAAkB,KAAK,UAAU;AACjD,MAAI,QAAS,QAAO;AAEpB,MAAI;AACF,UAAM,WAAW,MAAM,eAAe,UAAU,QAAQ;AACxD,QAAI,UAAU;AACZ,YAAM,MAAM,cAAc,GAAG;AAC7B,UAAI,WAAW,SAAS;AACxB,aAAO,aAAa,SAAS,KAAK,EAAE,QAAQ,SAAS,cAAc,CAAC;AAAA,IACtE;AAAA,EACF,SAAS,OAAO;AAEd,YAAQ,MAAM,0BAA0B,KAAK;AAAA,EAC/C;AAEA,QAAM,UAAU,MAAM,oBAAoB,KAAK,UAAU,UAAU;AACnE,QAAM,WAAW,aAAa,KAAK;AAAA,IACjC,SAAS;AAAA,MACP,SAAS,yBAAyB,KAAK,MAAM,UAAU,OAAO;AAAA,IAChE;AAAA,EACF,CAAC;AAED,MAAI,gBAAgB,KAAK,UAAU;AACjC,aAAS,QAAQ,IAAI,gBAAgB,SAAS;AAChD,MAAI,SAAS;AACX,qBAAiB,UAAU,UAAU,SAAS,UAAU;AAAA,EAC1D;AACA,SAAO;AACT;AASO,SAAS,2BACd,OAAkC,CAAC,GACU;AAC7C,SAAO,UACJ,KAAK,QAAQ,aAAa,EAAE,UAAU,UACnC,YAAY,GAAG,IACf,YAAY,GAAG;AACvB;AAMO,MAAM,6BAA6B;AAAA,EACxC,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASP;AAAA,EACF;AACF;","names":["storeRef"]}
|
|
1
|
+
{"version":3,"sources":["../../src/middleware/create-storefront-middleware.ts"],"sourcesContent":["import { publicNextUrl } from \"../request/public-url\";\nimport { REQUEST_PATH_HEADER } from \"../request/request-path\";\nimport {\n applyThemePreview,\n hasThemePreview,\n THEME_PREVIEW_PARAM,\n themePreviewCookieName,\n} from \"../theme/preview-cookie\";\nimport {\n externalStorefrontUrl,\n isSameHost,\n} from \"../theme/external-storefront\";\nimport { NextRequest, NextResponse } from \"next/server\";\nimport type { UrlRedirect } from \"@ecomweb/sdk\";\nimport { authCookiePath, writeAuthCookies } from \"../auth/cookies\";\nimport {\n downstreamRequestHeaders,\n refreshIfNearExpiry,\n} from \"../auth/session-refresh\";\nimport type { StorefrontMode } from \"../config/mode\";\nimport { publicConfig } from \"../config/public\";\nimport { lookupRedirect } from \"../redirects/lookup-redirect\";\nimport { multiTenantStorePath } from \"../store-scope\";\nimport { getStoreByHost } from \"../stores/get-store-by-host\";\nimport { STORE_COMING_SOON_REDIRECT_PATH } from \"../stores/store-coming-soon\";\nimport {\n applyStorePreview,\n STORE_PREVIEW_PATH,\n STORE_PREVIEW_TOKEN_HEADER,\n storePreviewCookieName,\n} from \"../stores/store-preview-cookie\";\nimport { getStoreSubdomain } from \"../stores/store-subdomain\";\nimport { recordStoreRequest } from \"../stores/store-traffic\";\nimport {\n PREVIEW_HOST_ROBOTS,\n THEME_PREVIEW_HOST_HEADER,\n} from \"../theme/preview-host\";\n\n/** Served from the app root in both modes; never rewritten or redirected. */\nconst METADATA_FILES = [\n \"/robots.txt\",\n \"/sitemap.xml\",\n \"/favicon.ico\",\n \"/manifest.json\",\n \"/manifest.webmanifest\",\n \"/icon\",\n \"/apple-icon\",\n];\n\n/**\n * Metadata files that follow the store to an external site: crawlers must\n * find the external site's robots.txt and sitemap, not ours.\n */\nconst EXTERNAL_METADATA_FILES = [\"/robots.txt\", \"/sitemap.xml\"];\n\n/** Rewrite target when a store's external URL still points at Ecomweb. */\nconst DOMAIN_NOT_CONNECTED_PATH = \"/domain-not-connected\";\n\n/**\n * The response for a store whose live theme is external, or null to serve\n * the request here (theme anatomy spec, \"Storefront\"):\n * - 302 to the external URL with the same path and query (307 for non-GET,\n * so the method survives); never 301, the merchant may switch back.\n * - never while previewing (`?preview_theme=` or the preview cookie): a\n * preview of an Ecomweb theme must render here.\n * - the external URL is this very host (the domain still points at Ecomweb):\n * a \"domain not connected\" page rather than a redirect loop (robots.txt\n * and the sitemap are still served here).\n * - no usable URL: null (fail open).\n */\nfunction externalThemeResponse(\n req: NextRequest,\n host: string,\n storeRef: string,\n externalUrl: string | null | undefined\n): NextResponse | null {\n if (!externalUrl) return null;\n if (\n req.nextUrl.searchParams.has(THEME_PREVIEW_PARAM) ||\n hasThemePreview(req, authCookiePath(storeRef, true))\n )\n return null;\n\n const pathname = req.nextUrl.pathname;\n const prefix = multiTenantStorePath(storeRef);\n const logicalPath =\n pathname === prefix || pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length) || \"/\"\n : pathname;\n const target = externalStorefrontUrl(\n externalUrl,\n logicalPath,\n req.nextUrl.search\n );\n if (!target) return null;\n\n if (isSameHost(host, target.hostname)) {\n // Our own robots.txt and sitemap still describe this host correctly.\n if (EXTERNAL_METADATA_FILES.includes(pathname)) return null;\n const url = req.nextUrl.clone();\n url.pathname = DOMAIN_NOT_CONNECTED_PATH;\n url.search = \"\";\n const res = NextResponse.rewrite(url, withoutInternalHeaders(req));\n res.headers.set(\"x-robots-tag\", \"noindex\");\n return res;\n }\n\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\n}\n\n/**\n * The init for a response that lets the request through without the full\n * downstream headers (metadata files, the \"domain not connected\" and apex\n * 404 rewrites): the client's headers minus the middleware's internal ones.\n * With it, every request the matcher covers reaches the app with no client\n * copy of them, so a server-side reader can trust them there.\n */\nfunction withoutInternalHeaders(req: NextRequest): {\n request: { headers: Headers };\n} {\n const headers = new Headers(req.headers);\n headers.delete(THEME_PREVIEW_HOST_HEADER);\n headers.delete(STORE_PREVIEW_TOKEN_HEADER);\n return { request: { headers } };\n}\n\n/** True while the store preview cookie at `cookiePath` holds a token. */\nfunction hasStorePreview(req: NextRequest, cookiePath: string): boolean {\n return !!req.cookies.get(storePreviewCookieName(cookiePath))?.value;\n}\n\n/**\n * The preview token for the host lookup on a store host: the store preview\n * cookie, else the theme preview cookie (`?preview_theme=` on the store's own\n * host), both at `/`. Read from the cookies only, never through\n * `storePreviewTokenFrom`: that trusts `STORE_PREVIEW_TOKEN_HEADER`, and on\n * the middleware's incoming request that header is whatever the client sent.\n */\nfunction hostLookupPreviewToken(req: NextRequest): string | null {\n return (\n req.cookies.get(storePreviewCookieName(\"/\"))?.value ||\n req.cookies.get(themePreviewCookieName(\"/\"))?.value ||\n null\n );\n}\n\n/**\n * The store a request belongs to, as far as the *path* can say.\n *\n * On localhost and on the platform apex there is no host→store mapping, but\n * the path is `/store/<storeRef>/…` — which is also how the auth cookies are\n * named. `params.storeRef` arrives URL-decoded downstream, so decode here too.\n */\nfunction storeRefFromPath(pathname: string): string | null {\n const match = /^\\/store\\/([^/]+)/.exec(pathname);\n if (!match) return null;\n try {\n return decodeURIComponent(match[1]) || null;\n } catch {\n return match[1];\n }\n}\n\n/**\n * Turns a stored redirect row into the 301/302 response for it.\n *\n * `pathPrefix` re-adds the `/store/<ref>` segment that direct path-based\n * access needs on the destination but a host-mapped request (whose\n * `destination_path` is already store-root-relative) does not.\n */\nfunction buildRedirectResponse(\n req: NextRequest,\n redirect: UrlRedirect,\n pathPrefix = \"\"\n): NextResponse {\n const redirectUrl = publicNextUrl(req);\n redirectUrl.pathname = `${pathPrefix}${redirect.destination_path}`;\n return NextResponse.redirect(redirectUrl, { status: redirect.redirect_type });\n}\n\n/**\n * `/store/<ref>/…` on the platform apex: never served here, sent to the\n * store's own subdomain instead.\n *\n * On the apex every store shares one origin, and a merchant's embedded\n * scripts run there. A cookie's Path is no boundary between pages of one\n * origin: store A's script could fetch `/store/B/api/…` with B's shopper\n * cookies attached, or frame `/store/B` and read it. Each store's subdomain\n * is its own origin. Localhost keeps path-based access (it is not the apex).\n *\n * 302 (307 for non-GET), not 301: the merchant may change the subdomain.\n * The subdomain then sends shoppers on to a custom domain when there is one.\n * No store, no subdomain, or the API unreachable: the 404 page.\n */\nasync function apexStoreResponse(\n req: NextRequest,\n storeRef: string,\n platformDomain: string\n): Promise<NextResponse> {\n let subdomain: string | null = null;\n try {\n subdomain = await getStoreSubdomain(storeRef);\n } catch (error) {\n console.error(\"Store lookup failed for apex path:\", storeRef, error);\n }\n\n if (!subdomain) {\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n url.search = \"\";\n return NextResponse.rewrite(url, withoutInternalHeaders(req));\n }\n\n const prefix = multiTenantStorePath(storeRef);\n const pathname = req.nextUrl.pathname;\n const target = publicNextUrl(req);\n target.hostname = `${subdomain}.${platformDomain}`;\n target.port = \"\";\n target.pathname = pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length)\n : \"/\";\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\n}\n\nasync function multiTenant(req: NextRequest): Promise<NextResponse> {\n const host = req.headers.get(\"host\") || \"\";\n const pathname = req.nextUrl.pathname;\n\n // Skip metadata files - these are served from app root level - except the\n // ones that follow an external theme (checked once the store is known).\n const isMetadataFile = METADATA_FILES.includes(pathname);\n if (isMetadataFile && !EXTERNAL_METADATA_FILES.includes(pathname)) {\n return NextResponse.next(withoutInternalHeaders(req));\n }\n\n // Store-by-host resolution and redirect lookup genuinely do not apply on\n // localhost or on the platform apex — but the token refresh below does, so\n // these only skip the host-specific work now, not the whole middleware.\n const platformDomain = publicConfig().platformDomainSuffix ?? \"ecomsite.app\";\n const hostIdentifiesStore =\n !host.includes(\"localhost\") &&\n !host.includes(\"127.0.0.1\") &&\n host !== platformDomain &&\n host !== `www.${platformDomain}`;\n\n const isPlatformApex =\n host === platformDomain || host === `www.${platformDomain}`;\n if (isPlatformApex) {\n const apexStoreRef = storeRefFromPath(pathname);\n if (apexStoreRef)\n return apexStoreResponse(req, apexStoreRef, platformDomain);\n }\n\n // The dashboard's preview link on the store's own host. Before the lookup:\n // a coming soon store's host resolves to nothing until the cookie is set.\n if (hostIdentifiesStore && pathname === STORE_PREVIEW_PATH) {\n return applyStorePreview(req, \"/\", \"/\");\n }\n\n let hostStoreRef: string | null = null;\n let hostResolved = false;\n\n let hostStoreSuspended = false;\n let hostStoreComingSoon = false;\n // A theme's preview host (theme preview hosts): the theme's slug.\n let previewSlug: string | null = null;\n // A preview host's store preview token for a coming soon store (lookup).\n let storePreviewToken: string | null = null;\n\n if (isMetadataFile && !hostIdentifiesStore)\n return NextResponse.next(withoutInternalHeaders(req));\n\n if (hostIdentifiesStore) {\n try {\n // Without a token, the plain call: its answer is cached for the host.\n const previewToken = hostLookupPreviewToken(req);\n const lookup = previewToken\n ? await getStoreByHost(host, { previewToken })\n : await getStoreByHost(host);\n const { storeRef, domain, isSubDomain, suspended, externalUrl } = lookup;\n hostResolved = true;\n hostStoreRef = storeRef || null;\n hostStoreSuspended = suspended;\n hostStoreComingSoon = !storeRef && !!lookup.comingSoon;\n previewSlug = storeRef ? lookup.previewSlug : null;\n storePreviewToken = previewSlug ? lookup.storePreviewToken || null : null;\n\n // Nothing on a preview host is for search engines.\n if (previewSlug && isMetadataFile) {\n return pathname === \"/robots.txt\"\n ? new NextResponse(PREVIEW_HOST_ROBOTS, {\n headers: { \"content-type\": \"text/plain\" },\n })\n : new NextResponse(null, { status: 404 });\n }\n\n if (storeRef) {\n // An external theme is live: the shopper belongs on that site. Before\n // the subdomain → custom domain redirect, which would only add a hop.\n const external = externalThemeResponse(\n req,\n host,\n storeRef,\n externalUrl\n );\n if (external) return external;\n }\n\n if (isMetadataFile) return NextResponse.next(withoutInternalHeaders(req));\n\n if (storeRef) {\n // If accessing via subdomain but custom domain exists, redirect to\n // custom domain. Not a preview host: it is the theme's, not the store's.\n if (isSubDomain && domain && domain !== host && !previewSlug) {\n const url = publicNextUrl(req);\n url.hostname = domain;\n url.protocol = \"https:\";\n url.port = \"\"; // Remove port for custom domain\n return NextResponse.redirect(url, { status: 301 });\n }\n\n // Check for URL redirects BEFORE rewriting\n // Skip redirect check if path already starts with /store/ (internal rewrite)\n if (!pathname.startsWith(multiTenantStorePath(storeRef))) {\n const redirect = await lookupRedirect(storeRef, pathname);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect);\n }\n }\n }\n } catch (error) {\n console.debug(\"Middleware error:\", error);\n if (isMetadataFile) return NextResponse.next(withoutInternalHeaders(req));\n // Fall through: no host mapping, but the refresh below still applies.\n hostResolved = false;\n hostStoreRef = null;\n }\n }\n\n // The host names the store on custom domains and subdomains; everywhere else\n // (localhost, the apex, direct /store/<ref>/… access) the path does.\n const storeRef = hostStoreRef ?? storeRefFromPath(pathname);\n if (storeRef) recordStoreRequest(storeRef);\n\n // A dashboard preview link: store its token in a cookie, then redirect to\n // the clean URL (themes spec §6.1). A coming soon store's own host resolves\n // no store until a preview token comes with the lookup, so there the link\n // becomes the host's `/` cookie, the lookup's fallback token\n // (hostLookupPreviewToken).\n if (hostStoreComingSoon) {\n const preview = applyThemePreview(req, \"/\");\n if (preview) return preview;\n }\n const cookiePath = storeRef ? authCookiePath(storeRef, !!hostStoreRef) : null;\n if (storeRef && cookiePath) {\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\n // The store preview link on the shared path-based host (localhost; the\n // apex already sent /store/<ref>/… to the store's subdomain above). Not\n // on a store host, even one that resolved no store: it takes `/preview`.\n if (\n !hostIdentifiesStore &&\n pathname === multiTenantStorePath(storeRef, STORE_PREVIEW_PATH)\n ) {\n return applyStorePreview(req, cookiePath, multiTenantStorePath(storeRef));\n }\n }\n\n // Direct /store/<ref>/… access never goes through the host-mapped branch\n // above, so it gets no redirect check there. `redirect_source_path` rows\n // are store-root-relative (e.g. \"/old\"), the same shape a host-mapped\n // request already checks against — strip the /store/<ref> prefix to\n // recover that shape, and re-add it on the destination.\n if (!hostStoreRef && storeRef) {\n const prefix = multiTenantStorePath(storeRef);\n if (pathname === prefix || pathname.startsWith(`${prefix}/`)) {\n try {\n const logicalPath = pathname.slice(prefix.length) || \"/\";\n const redirect = await lookupRedirect(storeRef, logicalPath);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect, prefix);\n }\n } catch (error) {\n // Fail open: lookupRedirect already catches internally and never\n // rejects, but this belongs to the caller's contract, not the\n // callee's — a future regression there must not take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n }\n }\n\n const rotated =\n storeRef && cookiePath\n ? await refreshIfNearExpiry(req, storeRef, cookiePath)\n : null;\n const downstream = downstreamRequestHeaders(\n req,\n !!hostStoreRef,\n storeRef,\n rotated\n );\n downstream.set(\n REQUEST_PATH_HEADER,\n `${req.nextUrl.pathname}${req.nextUrl.search}`\n );\n if (previewSlug) downstream.set(THEME_PREVIEW_HOST_HEADER, previewSlug);\n // Set after downstreamRequestHeaders deleted any copy the client sent. On\n // every request to the preview host, the backend proxy's included.\n if (previewSlug && storePreviewToken)\n downstream.set(STORE_PREVIEW_TOKEN_HEADER, storePreviewToken);\n const init = { request: { headers: downstream } };\n\n let response: NextResponse;\n\n if (hostStoreRef) {\n const url = req.nextUrl.clone();\n // Only rewrite if the path doesn't already start with /store/\n if (!url.pathname.startsWith(multiTenantStorePath(hostStoreRef))) {\n url.pathname = multiTenantStorePath(hostStoreRef, url.pathname);\n }\n\n response = NextResponse.rewrite(url, init);\n // Add headers to indicate this is a domain-mapped store\n response.headers.set(\"x-store-domain\", \"true\");\n response.headers.set(\"x-store-ref\", hostStoreRef);\n } else if (hostStoreSuspended) {\n // A platform admin suspended this store. The 403 the backend returned\n // for a domain lookup carries no ref/id to route on (see\n // getStoreByHost), so this can't rewrite to `/store/<ref>` the way the\n // resolved-store branch above does — it goes to a platform-level page\n // instead of the not-found path below.\n const url = req.nextUrl.clone();\n url.pathname = \"/store-suspended\";\n response = NextResponse.rewrite(url, init);\n } else if (hostStoreComingSoon) {\n // The merchant has not opened the store, and the request carried no\n // valid preview token (an expired one lands here too). Like the\n // suspended branch, the 403 carries no ref, so a platform-level page.\n // Known limitation: on the shared path-based host (localhost) nothing\n // routes here; a store that turns coming soon mid-session sends the\n // browser to /coming-soon, which resolves no store there and 404s, as\n // the apex's /store/<ref> already does for these stores.\n const url = req.nextUrl.clone();\n url.pathname = STORE_COMING_SOON_REDIRECT_PATH;\n response = NextResponse.rewrite(url, init);\n response.headers.set(\"x-robots-tag\", \"noindex\");\n } else if (hostResolved) {\n // The host looked like a store host but resolved to nothing: 404.\n console.debug(\"Store not found for host:\", host);\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n response = NextResponse.rewrite(url, init);\n } else {\n response = NextResponse.next(init);\n }\n\n // A store preview cookie lives at `/` on a store host, even when the host\n // resolved no store (coming soon), else at the store's path.\n const storePreviewPath = hostIdentifiesStore ? \"/\" : cookiePath;\n if (\n previewSlug ||\n (cookiePath && hasThemePreview(req, cookiePath)) ||\n (storePreviewPath && hasStorePreview(req, storePreviewPath))\n ) {\n response.headers.set(\"x-robots-tag\", \"noindex\");\n }\n\n if (rotated && storeRef && cookiePath) {\n // Same path the auth route handler writes with, from the same signal.\n writeAuthCookies(response, storeRef, rotated, cookiePath);\n }\n\n return response;\n}\n\n/**\n * Single-store middleware: the store is fixed by ECOMWEB_STORE_REF, so there\n * is no host lookup and no rewrite. It applies the store's URL redirects and\n * refreshes a near-expiry session. Requests are stamped host-mapped, so auth\n * cookies use Path=/ (see auth/cookies.ts).\n */\nasync function singleStore(req: NextRequest): Promise<NextResponse> {\n const pathname = req.nextUrl.pathname;\n if (METADATA_FILES.includes(pathname))\n return NextResponse.next(withoutInternalHeaders(req));\n\n const storeRef = publicConfig().storeRef as string;\n\n const cookiePath = authCookiePath(storeRef, true);\n if (pathname === STORE_PREVIEW_PATH)\n return applyStorePreview(req, cookiePath, \"/\");\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\n\n try {\n const redirect = await lookupRedirect(storeRef, pathname);\n if (redirect) {\n const url = publicNextUrl(req);\n url.pathname = redirect.destination_path;\n return NextResponse.redirect(url, { status: redirect.redirect_type });\n }\n } catch (error) {\n // Fail open: a redirect lookup must never take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n\n const rotated = await refreshIfNearExpiry(req, storeRef, cookiePath);\n const response = NextResponse.next({\n request: {\n headers: downstreamRequestHeaders(req, true, storeRef, rotated),\n },\n });\n\n if (hasThemePreview(req, cookiePath) || hasStorePreview(req, cookiePath))\n response.headers.set(\"x-robots-tag\", \"noindex\");\n if (rotated) {\n writeAuthCookies(response, storeRef, rotated, cookiePath);\n }\n return response;\n}\n\n/**\n * The storefront's proxy.ts (Next middleware).\n * - multi: host → store lookup, rewrites to /store/<ref>, suspended and\n * unknown stores, coming soon stores (rewritten to /coming-soon, noindex),\n * redirects, session refresh. The store preview link (`/preview?token=`\n * on a store host, `/store/<ref>/preview?token=` on localhost) becomes a\n * cookie before the lookup, and the lookup carries that token.\n * - single: the `/preview?token=` link, redirects and session refresh.\n * Without `mode`, the configured mode (ECOMWEB_MODE) decides per request.\n */\nexport function createStorefrontMiddleware(\n opts: { mode?: StorefrontMode } = {}\n): (req: NextRequest) => Promise<NextResponse> {\n return req =>\n (opts.mode ?? publicConfig().mode) === \"multi\"\n ? multiTenant(req)\n : singleStore(req);\n}\n\n/**\n * Next reads `config` from proxy.ts statically, so an app re-exports this as\n * `export const config = { matcher: [...] }` with the same literal.\n */\nexport const storefrontMiddlewareConfig = {\n matcher: [\n /*\n * Match all request paths except for the ones starting with:\n * - api (API routes)\n * - _next/static (static files)\n * - _next/image (image optimization files)\n * - _vercel (Vercel Analytics; off Vercel, a store page render per hit)\n * - favicon.ico (favicon file)\n */\n \"/((?!api|_next/static|_next/image|_vercel|favicon.ico).*)\",\n ],\n};\n"],"mappings":"AAAA,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAsB,oBAAoB;AAE1C,SAAS,gBAAgB,wBAAwB;AACjD;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,4BAA4B;AACrC,SA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,QAAM,WAAW,aAAa,EAAE;AAEhC,QAAM,aAAa,eAAe,UAAU,IAAI;AAChD,MAAI,aAAa;AACf,WAAO,kBAAkB,KAAK,YAAY,GAAG;AAC/C,QAAM,UAAU,kBAAkB,KAAK,UAAU;AACjD,MAAI,QAAS,QAAO;AAEpB,MAAI;AACF,UAAM,WAAW,MAAM,eAAe,UAAU,QAAQ;AACxD,QAAI,UAAU;AACZ,YAAM,MAAM,cAAc,GAAG;AAC7B,UAAI,WAAW,SAAS;AACxB,aAAO,aAAa,SAAS,KAAK,EAAE,QAAQ,SAAS,cAAc,CAAC;AAAA,IACtE;AAAA,EACF,SAAS,OAAO;AAEd,YAAQ,MAAM,0BAA0B,KAAK;AAAA,EAC/C;AAEA,QAAM,UAAU,MAAM,oBAAoB,KAAK,UAAU,UAAU;AACnE,QAAM,WAAW,aAAa,KAAK;AAAA,IACjC,SAAS;AAAA,MACP,SAAS,yBAAyB,KAAK,MAAM,UAAU,OAAO;AAAA,IAChE;AAAA,EACF,CAAC;AAED,MAAI,gBAAgB,KAAK,UAAU,KAAK,gBAAgB,KAAK,UAAU;AACrE,aAAS,QAAQ,IAAI,gBAAgB,SAAS;AAChD,MAAI,SAAS;AACX,qBAAiB,UAAU,UAAU,SAAS,UAAU;AAAA,EAC1D;AACA,SAAO;AACT;AAYO,SAAS,2BACd,OAAkC,CAAC,GACU;AAC7C,SAAO,UACJ,KAAK,QAAQ,aAAa,EAAE,UAAU,UACnC,YAAY,GAAG,IACf,YAAY,GAAG;AACvB;AAMO,MAAM,6BAA6B;AAAA,EACxC,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASP;AAAA,EACF;AACF;","names":["storeRef"]}
|
package/dist/middleware.d.ts
CHANGED
|
@@ -6,8 +6,11 @@ import 'zod';
|
|
|
6
6
|
/**
|
|
7
7
|
* The storefront's proxy.ts (Next middleware).
|
|
8
8
|
* - multi: host → store lookup, rewrites to /store/<ref>, suspended and
|
|
9
|
-
* unknown stores,
|
|
10
|
-
*
|
|
9
|
+
* unknown stores, coming soon stores (rewritten to /coming-soon, noindex),
|
|
10
|
+
* redirects, session refresh. The store preview link (`/preview?token=`
|
|
11
|
+
* on a store host, `/store/<ref>/preview?token=` on localhost) becomes a
|
|
12
|
+
* cookie before the lookup, and the lookup carries that token.
|
|
13
|
+
* - single: the `/preview?token=` link, redirects and session refresh.
|
|
11
14
|
* Without `mode`, the configured mode (ECOMWEB_MODE) decides per request.
|
|
12
15
|
*/
|
|
13
16
|
declare function createStorefrontMiddleware(opts?: {
|
package/dist/provider.js
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { jsx } from "react/jsx-runtime";
|
|
3
|
+
import { useEffect, useRef } from "react";
|
|
3
4
|
import { AuthProvider, useAuth } from "./auth/context.js";
|
|
4
5
|
import { CartProvider } from "./cart/server-context.js";
|
|
5
6
|
import { NoticeProvider } from "./notices.js";
|
|
6
7
|
import { StoreProvider } from "./store/store-context.js";
|
|
8
|
+
import {
|
|
9
|
+
setBrowserStorePreviewToken,
|
|
10
|
+
setStorePreviewRenewer
|
|
11
|
+
} from "./api/store-preview-header.js";
|
|
12
|
+
const STORE_PREVIEW_RENEW_MS = 30 * 60 * 1e3;
|
|
7
13
|
function IdentityCart({
|
|
8
14
|
storeRef,
|
|
9
15
|
children
|
|
@@ -15,8 +21,24 @@ function StorefrontKitProvider({
|
|
|
15
21
|
store,
|
|
16
22
|
storeRef,
|
|
17
23
|
onNotice,
|
|
24
|
+
storePreviewToken,
|
|
25
|
+
onStorePreviewRenew,
|
|
18
26
|
children
|
|
19
27
|
}) {
|
|
28
|
+
setBrowserStorePreviewToken(storePreviewToken ?? null);
|
|
29
|
+
const renewRef = useRef(onStorePreviewRenew);
|
|
30
|
+
renewRef.current = onStorePreviewRenew;
|
|
31
|
+
const renews = !!storePreviewToken && !!onStorePreviewRenew;
|
|
32
|
+
useEffect(() => {
|
|
33
|
+
if (!renews) return;
|
|
34
|
+
const renew = () => renewRef.current?.();
|
|
35
|
+
setStorePreviewRenewer(renew);
|
|
36
|
+
const timer = setInterval(renew, STORE_PREVIEW_RENEW_MS);
|
|
37
|
+
return () => {
|
|
38
|
+
clearInterval(timer);
|
|
39
|
+
setStorePreviewRenewer(null);
|
|
40
|
+
};
|
|
41
|
+
}, [renews]);
|
|
20
42
|
return /* @__PURE__ */ jsx(StoreProvider, { store, children: /* @__PURE__ */ jsx(NoticeProvider, { onNotice, children: /* @__PURE__ */ jsx(AuthProvider, { children: /* @__PURE__ */ jsx(IdentityCart, { storeRef: storeRef ?? store.ref, children }) }) }) });
|
|
21
43
|
}
|
|
22
44
|
export {
|
package/dist/provider.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/provider.tsx"],"sourcesContent":["\"use client\";\n\nimport type
|
|
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,7 +1,8 @@
|
|
|
1
1
|
import { sdk } from "../sdk.js";
|
|
2
|
+
import { SKIP_STORE_PREVIEW } from "../stores/store-preview-cookie.js";
|
|
2
3
|
async function lookupRedirect(storeId, path) {
|
|
3
4
|
try {
|
|
4
|
-
return await sdk.redirects.lookup(storeId, path);
|
|
5
|
+
return await sdk.redirects.lookup(storeId, path, SKIP_STORE_PREVIEW);
|
|
5
6
|
} catch (error) {
|
|
6
7
|
console.error("Error looking up redirect:", error);
|
|
7
8
|
return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/redirects/lookup-redirect.ts"],"sourcesContent":["import type { UrlRedirect } from \"@ecomweb/sdk\";\nimport { sdk } from \"../sdk\";\n\n/**\n * Lookup URL redirect for a given store and path\n * Used by middleware to check if a path should be redirected\n */\nexport async function lookupRedirect(\n storeId: string,\n path: string\n): Promise<UrlRedirect | null> {\n try {\n return await sdk.redirects.lookup(storeId, path);\n } catch (error) {\n console.error(\"Error looking up redirect:\", error);\n return null;\n }\n}\n"],"mappings":"AACA,SAAS,WAAW;
|
|
1
|
+
{"version":3,"sources":["../../src/redirects/lookup-redirect.ts"],"sourcesContent":["import type { UrlRedirect } from \"@ecomweb/sdk\";\nimport { sdk } from \"../sdk\";\nimport { SKIP_STORE_PREVIEW } from \"../stores/store-preview-cookie\";\n\n/**\n * Lookup URL redirect for a given store and path\n * Used by middleware to check if a path should be redirected\n */\nexport async function lookupRedirect(\n storeId: string,\n path: string\n): Promise<UrlRedirect | null> {\n try {\n // The middleware's own call: `next/headers` there is its raw incoming\n // request, so the ambient preview token must not ride along.\n return await sdk.redirects.lookup(storeId, path, SKIP_STORE_PREVIEW);\n } catch (error) {\n console.error(\"Error looking up redirect:\", error);\n return null;\n }\n}\n"],"mappings":"AACA,SAAS,WAAW;AACpB,SAAS,0BAA0B;AAMnC,eAAsB,eACpB,SACA,MAC6B;AAC7B,MAAI;AAGF,WAAO,MAAM,IAAI,UAAU,OAAO,SAAS,MAAM,kBAAkB;AAAA,EACrE,SAAS,OAAO;AACd,YAAQ,MAAM,8BAA8B,KAAK;AACjD,WAAO;AAAA,EACT;AACF;","names":[]}
|
package/dist/server.d.ts
CHANGED
|
@@ -58,6 +58,14 @@ declare function resolveRootStoreRef(): Promise<string | null>;
|
|
|
58
58
|
/** The open theme preview's token, if any (server components only). */
|
|
59
59
|
declare function readThemePreviewToken(): Promise<string | null>;
|
|
60
60
|
|
|
61
|
+
/**
|
|
62
|
+
* The token this request sends as `X-Store-Preview` (server components
|
|
63
|
+
* only): a preview host's token the middleware stamped, else the store
|
|
64
|
+
* preview cookie, else the theme preview cookie. The layout passes it to
|
|
65
|
+
* `StorefrontKitProvider` while the store is coming soon.
|
|
66
|
+
*/
|
|
67
|
+
declare function readStorePreviewToken(): Promise<string | null>;
|
|
68
|
+
|
|
61
69
|
/**
|
|
62
70
|
* The theme preview host's slug when this request came in on one (server
|
|
63
71
|
* components only); the middleware sets it, never the client.
|
|
@@ -82,4 +90,15 @@ declare function externalThemeRedirectFor(request: {
|
|
|
82
90
|
external_url?: string | null;
|
|
83
91
|
} | null | undefined, previewOpen: boolean): string | null;
|
|
84
92
|
|
|
85
|
-
|
|
93
|
+
/**
|
|
94
|
+
* Whether the store this request belongs to is coming soon, and its name
|
|
95
|
+
* (null when the API gave none). Null when the store is not coming soon.
|
|
96
|
+
*
|
|
97
|
+
* The name only ever comes from the API lookup, never from the request, so
|
|
98
|
+
* the /coming-soon page cannot be made to show text a visitor chose.
|
|
99
|
+
*/
|
|
100
|
+
declare function resolveComingSoonStore(): Promise<{
|
|
101
|
+
name: string | null;
|
|
102
|
+
} | null>;
|
|
103
|
+
|
|
104
|
+
export { type CustomerIdentity, type RouteContext, type RouteHandler, createAuthRoutes, createBackendProxy, externalThemeRedirectFor, hasCustomerSession, parseServerConfig, readPreviewHostSlug, readStorePreviewToken, readThemePreviewToken, requireSession, resolveComingSoonStore, resolveRootStoreRef, serverConfig };
|
package/dist/server.js
CHANGED
|
@@ -8,8 +8,10 @@ import { hasCustomerSession } from "./auth/session.js";
|
|
|
8
8
|
import { parseServerConfig, serverConfig } from "./config/server.js";
|
|
9
9
|
import { resolveRootStoreRef } from "./store-scope/root.js";
|
|
10
10
|
import { readThemePreviewToken } from "./theme/read-preview-token.js";
|
|
11
|
+
import { readStorePreviewToken } from "./stores/read-store-preview-token.js";
|
|
11
12
|
import { readPreviewHostSlug } from "./theme/read-preview-host.js";
|
|
12
13
|
import { externalThemeRedirectFor } from "./theme/external-storefront.js";
|
|
14
|
+
import { resolveComingSoonStore } from "./stores/resolve-coming-soon.js";
|
|
13
15
|
export {
|
|
14
16
|
createAuthRoutes,
|
|
15
17
|
createBackendProxy,
|
|
@@ -17,8 +19,10 @@ export {
|
|
|
17
19
|
hasCustomerSession,
|
|
18
20
|
parseServerConfig,
|
|
19
21
|
readPreviewHostSlug,
|
|
22
|
+
readStorePreviewToken,
|
|
20
23
|
readThemePreviewToken,
|
|
21
24
|
requireSession,
|
|
25
|
+
resolveComingSoonStore,
|
|
22
26
|
resolveRootStoreRef,
|
|
23
27
|
serverConfig
|
|
24
28
|
};
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["// @ecomweb/storefront-kit/server: server-only handlers and helpers.\nimport \"server-only\";\n\nexport {\n createAuthRoutes,\n createBackendProxy,\n requireSession,\n} from \"./server/routes\";\nexport type {\n CustomerIdentity,\n RouteContext,\n RouteHandler,\n} from \"./server/routes\";\nexport { hasCustomerSession } from \"./auth/session\";\nexport { parseServerConfig, serverConfig } from \"./config/server\";\nexport { resolveRootStoreRef } from \"./store-scope/root\";\nexport { readThemePreviewToken } from \"./theme/read-preview-token\";\nexport { readPreviewHostSlug } from \"./theme/read-preview-host\";\nexport { externalThemeRedirectFor } from \"./theme/external-storefront\";\n"],"mappings":"AACA,OAAO;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,0BAA0B;AACnC,SAAS,mBAAmB,oBAAoB;AAChD,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS,gCAAgC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["// @ecomweb/storefront-kit/server: server-only handlers and helpers.\nimport \"server-only\";\n\nexport {\n createAuthRoutes,\n createBackendProxy,\n requireSession,\n} from \"./server/routes\";\nexport type {\n CustomerIdentity,\n RouteContext,\n RouteHandler,\n} from \"./server/routes\";\nexport { hasCustomerSession } from \"./auth/session\";\nexport { parseServerConfig, serverConfig } from \"./config/server\";\nexport { resolveRootStoreRef } from \"./store-scope/root\";\nexport { readThemePreviewToken } from \"./theme/read-preview-token\";\nexport { readStorePreviewToken } from \"./stores/read-store-preview-token\";\nexport { readPreviewHostSlug } from \"./theme/read-preview-host\";\nexport { externalThemeRedirectFor } from \"./theme/external-storefront\";\nexport { resolveComingSoonStore } from \"./stores/resolve-coming-soon\";\n"],"mappings":"AACA,OAAO;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,0BAA0B;AACnC,SAAS,mBAAmB,oBAAoB;AAChD,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AACtC,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS,gCAAgC;AACzC,SAAS,8BAA8B;","names":[]}
|
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
import { sdk } from "../sdk.js";
|
|
2
2
|
import { isStoreSuspendedError } from "./store-suspension.js";
|
|
3
|
+
import {
|
|
4
|
+
comingSoonStoreNameOf,
|
|
5
|
+
isStoreComingSoonError
|
|
6
|
+
} from "./store-coming-soon.js";
|
|
7
|
+
import {
|
|
8
|
+
SKIP_STORE_PREVIEW,
|
|
9
|
+
STORE_PREVIEW_HEADER
|
|
10
|
+
} from "./store-preview-cookie.js";
|
|
3
11
|
import { publicConfig } from "../config.js";
|
|
4
12
|
import { TtlCache } from "./ttl-cache.js";
|
|
5
13
|
const FOUND_TTL_MS = 3e4;
|
|
@@ -15,7 +23,7 @@ function platformSubdomain(hostname, platformDomain) {
|
|
|
15
23
|
const label = hostname.slice(0, -suffix.length);
|
|
16
24
|
return label && !label.includes(".") ? label : null;
|
|
17
25
|
}
|
|
18
|
-
async function getStoreByHost(host) {
|
|
26
|
+
async function getStoreByHost(host, options) {
|
|
19
27
|
if (host.includes("localhost") || host.includes("127.0.0.1")) {
|
|
20
28
|
return {
|
|
21
29
|
storeRef: null,
|
|
@@ -23,17 +31,26 @@ async function getStoreByHost(host) {
|
|
|
23
31
|
isSubDomain: false,
|
|
24
32
|
suspended: false,
|
|
25
33
|
externalUrl: null,
|
|
26
|
-
previewSlug: null
|
|
34
|
+
previewSlug: null,
|
|
35
|
+
comingSoon: false,
|
|
36
|
+
comingSoonName: null,
|
|
37
|
+
storePreviewToken: null
|
|
27
38
|
};
|
|
28
39
|
}
|
|
40
|
+
const previewToken = options?.previewToken || null;
|
|
29
41
|
const key = host.toLowerCase();
|
|
30
|
-
|
|
31
|
-
|
|
42
|
+
if (!previewToken) {
|
|
43
|
+
const cached = byHost.get(key);
|
|
44
|
+
if (cached) return cached;
|
|
45
|
+
}
|
|
32
46
|
let storeRef = null;
|
|
33
47
|
let domain = null;
|
|
34
48
|
let suspended = false;
|
|
35
49
|
let externalUrl = null;
|
|
36
50
|
let previewSlug = null;
|
|
51
|
+
let comingSoon = false;
|
|
52
|
+
let comingSoonName = null;
|
|
53
|
+
let storePreviewToken = null;
|
|
37
54
|
let failed = false;
|
|
38
55
|
const hostname = key.split(":")[0];
|
|
39
56
|
const platformDomain = (publicConfig().platformDomainSuffix ?? "ecomsite.app").toLowerCase();
|
|
@@ -41,16 +58,23 @@ async function getStoreByHost(host) {
|
|
|
41
58
|
const isSubDomain = subdomain !== null;
|
|
42
59
|
try {
|
|
43
60
|
const lookupValue = subdomain ?? host;
|
|
44
|
-
const foundStore = await sdk.stores.getByDomain(
|
|
61
|
+
const foundStore = await sdk.stores.getByDomain(
|
|
62
|
+
lookupValue,
|
|
63
|
+
previewToken ? { headers: { [STORE_PREVIEW_HEADER]: previewToken } } : SKIP_STORE_PREVIEW
|
|
64
|
+
);
|
|
45
65
|
if (foundStore?.ref) {
|
|
46
66
|
storeRef = foundStore.ref;
|
|
47
67
|
domain = foundStore.config?.custom_domain || null;
|
|
48
68
|
externalUrl = foundStore.storefront_url || null;
|
|
49
69
|
previewSlug = foundStore.preview_slug || null;
|
|
70
|
+
storePreviewToken = previewSlug ? foundStore.store_preview_token || null : null;
|
|
50
71
|
}
|
|
51
72
|
} catch (error) {
|
|
52
73
|
if (isStoreSuspendedError(error)) {
|
|
53
74
|
suspended = true;
|
|
75
|
+
} else if (isStoreComingSoonError(error)) {
|
|
76
|
+
comingSoon = true;
|
|
77
|
+
comingSoonName = comingSoonStoreNameOf(error);
|
|
54
78
|
} else {
|
|
55
79
|
failed = true;
|
|
56
80
|
console.error("Store not found for host:", host);
|
|
@@ -62,9 +86,12 @@ async function getStoreByHost(host) {
|
|
|
62
86
|
isSubDomain,
|
|
63
87
|
suspended,
|
|
64
88
|
externalUrl,
|
|
65
|
-
previewSlug
|
|
89
|
+
previewSlug,
|
|
90
|
+
comingSoon,
|
|
91
|
+
comingSoonName,
|
|
92
|
+
storePreviewToken
|
|
66
93
|
};
|
|
67
|
-
if (!failed) {
|
|
94
|
+
if (!failed && !previewToken) {
|
|
68
95
|
byHost.set(key, result, storeRef ? FOUND_TTL_MS : NOT_FOUND_TTL_MS);
|
|
69
96
|
}
|
|
70
97
|
return result;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/stores/get-store-by-host.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { isStoreSuspendedError } from \"./store-suspension\";\nimport { publicConfig } from \"../config\";\nimport { TtlCache } from \"./ttl-cache\";\n\ntype StoreByHost = Awaited<ReturnType<typeof getStoreByHost>>;\n\n/**\n * How long a lookup is reused in this process. A merchant's change (custom\n * domain, external theme, suspension) reaches shoppers within this window on\n * top of the API's own Redis cache. Misses and suspensions expire sooner so\n * a new or re-enabled store shows up quickly. A failed lookup (API down) is\n * never cached: it would turn a blip into a run of 404s.\n */\nconst FOUND_TTL_MS = 30_000;\nconst NOT_FOUND_TTL_MS = 10_000;\nconst MAX_HOSTS = 10_000;\n\nconst byHost = new TtlCache<StoreByHost>(MAX_HOSTS);\n\n/** Tests only: forget every cached lookup. */\nexport function clearStoreByHostCache(): void {\n byHost.clear();\n}\n\n/**\n * The store's subdomain label when `hostname` is `<label>.<platformDomain>`\n * (a single label, so `www.shop.<platform>` and `shop.evil<platform>` are\n * not subdomains), else null.\n */\nfunction platformSubdomain(\n hostname: string,\n platformDomain: string\n): string | null {\n const suffix = `.${platformDomain}`;\n if (!hostname.endsWith(suffix)) return null;\n const label = hostname.slice(0, -suffix.length);\n return label && !label.includes(\".\") ? label : null;\n}\n\n/**\n * Get store ref and domain info from host\n * Used by middleware and API routes to determine which store is being accessed\n */\nexport async function getStoreByHost(host: string): Promise<{\n storeRef: string | null;\n domain: string | null;\n isSubDomain: boolean;\n // True when the backend identified a store for this host but rejected it\n // with STORE_SUSPENDED. There is no `ref` to route on in that case — the\n // 403 response carries no store-identifying payload — so the caller must\n // handle this without a storeRef (see proxy.ts, which rewrites to a\n // platform-level suspended page rather than `/store/<ref>`).\n suspended: boolean;\n // The live theme's URL when it is external (`storefront_url`), else null.\n // Null too when the API predates external themes.\n externalUrl: string | null;\n // A theme's preview host, p-<slug> (theme preview hosts): its slug.\n previewSlug: string | null;\n}> {\n if (host.includes(\"localhost\") || host.includes(\"127.0.0.1\")) {\n return {\n storeRef: null,\n domain: null,\n isSubDomain: false,\n suspended: false,\n externalUrl: null,\n previewSlug: null,\n };\n }\n\n const key = host.toLowerCase();\n const cached = byHost.get(key);\n
|
|
1
|
+
{"version":3,"sources":["../../src/stores/get-store-by-host.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { isStoreSuspendedError } from \"./store-suspension\";\nimport {\n comingSoonStoreNameOf,\n isStoreComingSoonError,\n} from \"./store-coming-soon\";\nimport {\n SKIP_STORE_PREVIEW,\n STORE_PREVIEW_HEADER,\n} from \"./store-preview-cookie\";\nimport { publicConfig } from \"../config\";\nimport { TtlCache } from \"./ttl-cache\";\n\ntype StoreByHost = Awaited<ReturnType<typeof getStoreByHost>>;\n\n/**\n * How long a lookup is reused in this process. A merchant's change (custom\n * domain, external theme, suspension) reaches shoppers within this window on\n * top of the API's own Redis cache. Misses and suspensions expire sooner so\n * a new or re-enabled store shows up quickly. A failed lookup (API down) is\n * never cached: it would turn a blip into a run of 404s. Neither is a lookup\n * made with a preview token: its answer is that previewer's, not the public's.\n */\nconst FOUND_TTL_MS = 30_000;\nconst NOT_FOUND_TTL_MS = 10_000;\nconst MAX_HOSTS = 10_000;\n\nconst byHost = new TtlCache<StoreByHost>(MAX_HOSTS);\n\n/** Tests only: forget every cached lookup. */\nexport function clearStoreByHostCache(): void {\n byHost.clear();\n}\n\n/**\n * The store's subdomain label when `hostname` is `<label>.<platformDomain>`\n * (a single label, so `www.shop.<platform>` and `shop.evil<platform>` are\n * not subdomains), else null.\n */\nfunction platformSubdomain(\n hostname: string,\n platformDomain: string\n): string | null {\n const suffix = `.${platformDomain}`;\n if (!hostname.endsWith(suffix)) return null;\n const label = hostname.slice(0, -suffix.length);\n return label && !label.includes(\".\") ? label : null;\n}\n\n/**\n * Get store ref and domain info from host\n * Used by middleware and API routes to determine which store is being accessed\n *\n * With `previewToken` (a store or theme preview token), the token is sent as\n * `X-Store-Preview`, which opens a coming soon store, and the cache is\n * neither read nor written. Without one the lookup is the public answer for\n * the host: it is cached, and it carries `SKIP_STORE_PREVIEW` so the API\n * client never attaches the request's ambient preview token to it.\n */\nexport async function getStoreByHost(\n host: string,\n options?: { previewToken?: string | null }\n): Promise<{\n storeRef: string | null;\n domain: string | null;\n isSubDomain: boolean;\n // True when the backend identified a store for this host but rejected it\n // with STORE_SUSPENDED. There is no `ref` to route on in that case — the\n // 403 response carries no store-identifying payload — so the caller must\n // handle this without a storeRef (see proxy.ts, which rewrites to a\n // platform-level suspended page rather than `/store/<ref>`).\n suspended: boolean;\n // The live theme's URL when it is external (`storefront_url`), else null.\n // Null too when the API predates external themes.\n externalUrl: string | null;\n // A theme's preview host, p-<slug> (theme preview hosts): its slug.\n previewSlug: string | null;\n // True when the backend identified a store for this host but rejected it\n // with STORE_COMING_SOON: the merchant has not opened it yet. Like\n // `suspended`, there is no `ref` to route on, because the 403 carries only\n // `details.name`; the caller handles it without a storeRef (proxy.ts\n // rewrites to the platform-level coming soon page). A lookup with a valid\n // preview token gets the store instead.\n comingSoon: boolean;\n // The store's name from that 403's `details.name`, else null.\n comingSoonName: string | null;\n // On a theme's preview host only (previewSlug set): the API's short-lived\n // store preview token for a coming soon store, sent as X-Store-Preview in\n // place of the cookie on that host. Null everywhere else. It is cached\n // with the lookup, because the p-<slug> host is itself the capability, and\n // 30 s is far inside the token's 1 h.\n storePreviewToken: string | null;\n}> {\n if (host.includes(\"localhost\") || host.includes(\"127.0.0.1\")) {\n return {\n storeRef: null,\n domain: null,\n isSubDomain: false,\n suspended: false,\n externalUrl: null,\n previewSlug: null,\n comingSoon: false,\n comingSoonName: null,\n storePreviewToken: null,\n };\n }\n\n const previewToken = options?.previewToken || null;\n const key = host.toLowerCase();\n if (!previewToken) {\n const cached = byHost.get(key);\n if (cached) return cached;\n }\n\n let storeRef: string | null = null;\n let domain: string | null = null;\n let suspended = false;\n let externalUrl: string | null = null;\n let previewSlug: string | null = null;\n let comingSoon = false;\n let comingSoonName: string | null = null;\n let storePreviewToken: string | null = null;\n\n let failed = false;\n\n const hostname = key.split(\":\")[0]!;\n const platformDomain = (\n publicConfig().platformDomainSuffix ?? \"ecomsite.app\"\n ).toLowerCase();\n const subdomain = platformSubdomain(hostname, platformDomain);\n const isSubDomain = subdomain !== null;\n\n try {\n const lookupValue = subdomain ?? host;\n const foundStore = await sdk.stores.getByDomain(\n lookupValue,\n previewToken\n ? { headers: { [STORE_PREVIEW_HEADER]: previewToken } }\n : SKIP_STORE_PREVIEW\n );\n\n if (foundStore?.ref) {\n storeRef = foundStore.ref;\n domain = foundStore.config?.custom_domain || null;\n externalUrl = foundStore.storefront_url || null;\n previewSlug = foundStore.preview_slug || null;\n // Never taken from a non-preview host.\n storePreviewToken = previewSlug\n ? foundStore.store_preview_token || null\n : null;\n }\n } catch (error) {\n if (isStoreSuspendedError(error)) {\n suspended = true;\n } else if (isStoreComingSoonError(error)) {\n comingSoon = true;\n comingSoonName = comingSoonStoreNameOf(error);\n } else {\n failed = true;\n console.error(\"Store not found for host:\", host);\n }\n }\n\n const result = {\n storeRef,\n domain,\n isSubDomain,\n suspended,\n externalUrl,\n previewSlug,\n comingSoon,\n comingSoonName,\n storePreviewToken,\n };\n if (!failed && !previewToken) {\n byHost.set(key, result, storeRef ? FOUND_TTL_MS : NOT_FOUND_TTL_MS);\n }\n return result;\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB;AAYzB,MAAM,eAAe;AACrB,MAAM,mBAAmB;AACzB,MAAM,YAAY;AAElB,MAAM,SAAS,IAAI,SAAsB,SAAS;AAG3C,SAAS,wBAA8B;AAC5C,SAAO,MAAM;AACf;AAOA,SAAS,kBACP,UACA,gBACe;AACf,QAAM,SAAS,IAAI,cAAc;AACjC,MAAI,CAAC,SAAS,SAAS,MAAM,EAAG,QAAO;AACvC,QAAM,QAAQ,SAAS,MAAM,GAAG,CAAC,OAAO,MAAM;AAC9C,SAAO,SAAS,CAAC,MAAM,SAAS,GAAG,IAAI,QAAQ;AACjD;AAYA,eAAsB,eACpB,MACA,SA+BC;AACD,MAAI,KAAK,SAAS,WAAW,KAAK,KAAK,SAAS,WAAW,GAAG;AAC5D,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,aAAa;AAAA,MACb,WAAW;AAAA,MACX,aAAa;AAAA,MACb,aAAa;AAAA,MACb,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AA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACA,MAAI,CAAC,UAAU,CAAC,cAAc;AAC5B,WAAO,IAAI,KAAK,QAAQ,WAAW,eAAe,gBAAgB;AAAA,EACpE;AACA,SAAO;AACT;","names":[]}
|
package/dist/stores/metadata.js
CHANGED
|
@@ -1,19 +1,36 @@
|
|
|
1
|
+
import {
|
|
2
|
+
comingSoonStoreNameOf,
|
|
3
|
+
isStoreComingSoonError
|
|
4
|
+
} from "./store-coming-soon.js";
|
|
1
5
|
import { isStoreSuspendedError } from "./store-suspension.js";
|
|
6
|
+
const COMING_SOON_STORE_DESCRIPTION = "C\u1EEDa h\xE0ng \u0111ang chu\u1EA9n b\u1ECB v\xE0 s\u1EBD s\u1EDBm m\u1EDF c\u1EEDa.";
|
|
2
7
|
const SUSPENDED_STORE_METADATA = {
|
|
3
8
|
title: "Store suspended",
|
|
4
9
|
description: "This store is temporarily unavailable. If you are the store owner, contact support.",
|
|
5
10
|
robots: "noindex, nofollow"
|
|
6
11
|
};
|
|
12
|
+
function comingSoonStoreMetadata(name) {
|
|
13
|
+
return {
|
|
14
|
+
title: name ? `${name} s\u1EAFp ra m\u1EAFt` : "S\u1EAFp ra m\u1EAFt",
|
|
15
|
+
description: COMING_SOON_STORE_DESCRIPTION,
|
|
16
|
+
robots: "noindex, nofollow"
|
|
17
|
+
};
|
|
18
|
+
}
|
|
7
19
|
async function withSuspendedStoreMetadataFallback(fn) {
|
|
8
20
|
try {
|
|
9
21
|
return await fn();
|
|
10
22
|
} catch (error) {
|
|
11
23
|
if (isStoreSuspendedError(error)) return SUSPENDED_STORE_METADATA;
|
|
24
|
+
if (isStoreComingSoonError(error)) {
|
|
25
|
+
return comingSoonStoreMetadata(comingSoonStoreNameOf(error));
|
|
26
|
+
}
|
|
12
27
|
throw error;
|
|
13
28
|
}
|
|
14
29
|
}
|
|
15
30
|
export {
|
|
31
|
+
COMING_SOON_STORE_DESCRIPTION,
|
|
16
32
|
SUSPENDED_STORE_METADATA,
|
|
33
|
+
comingSoonStoreMetadata,
|
|
17
34
|
withSuspendedStoreMetadataFallback
|
|
18
35
|
};
|
|
19
36
|
//# sourceMappingURL=metadata.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/stores/metadata.ts"],"sourcesContent":["import type { Metadata } from \"next\";\nimport { isStoreSuspendedError } from \"./store-suspension\";\n\n/**\n * The metadata Next.js shows for a store's suspended pages. Never includes\n * `platform_suspension_reason` -- it's internal, written by an admin for\n * other admins.\n */\nexport const SUSPENDED_STORE_METADATA: Metadata = {\n title: \"Store suspended\",\n description:\n \"This store is temporarily unavailable. If you are the store owner, contact support.\",\n robots: \"noindex, nofollow\",\n};\n\n/**\n * Wraps a leaf page's `generateMetadata` body so a STORE_SUSPENDED lookup\n * doesn't crash the whole route.\n *\n * Next.js resolves every matched segment's `generateMetadata` unconditionally\n * to build <head> -- this happens independently of whatever the parent\n * `StoreLayout` eventually renders (it can skip rendering `children` for a\n * suspended store, but that doesn't stop Next from having already awaited\n * this segment's own `generateMetadata`). So each page that calls\n * `getCachedStore` in its own `generateMetadata` needs this, not just the\n * layout's.\n */\nexport async function withSuspendedStoreMetadataFallback(\n fn: () => Promise<Metadata>\n): Promise<Metadata> {\n try {\n return await fn();\n } catch (error) {\n if (isStoreSuspendedError(error)) return SUSPENDED_STORE_METADATA;\n throw error;\n }\n}\n"],"mappings":"AACA,SAAS,6BAA6B;
|
|
1
|
+
{"version":3,"sources":["../../src/stores/metadata.ts"],"sourcesContent":["import type { Metadata } from \"next\";\nimport {\n comingSoonStoreNameOf,\n isStoreComingSoonError,\n} from \"./store-coming-soon\";\nimport { isStoreSuspendedError } from \"./store-suspension\";\n\n/** Shared copy: the coming soon metadata description and the coming soon page. */\nexport const COMING_SOON_STORE_DESCRIPTION =\n \"Cửa hàng đang chuẩn bị và sẽ sớm mở cửa.\";\n\n/**\n * The metadata Next.js shows for a store's suspended pages. Never includes\n * `platform_suspension_reason` -- it's internal, written by an admin for\n * other admins.\n */\nexport const SUSPENDED_STORE_METADATA: Metadata = {\n title: \"Store suspended\",\n description:\n \"This store is temporarily unavailable. If you are the store owner, contact support.\",\n robots: \"noindex, nofollow\",\n};\n\n/**\n * The metadata for a store the merchant has not opened yet. `name` comes from\n * the coming soon error's details and may be missing.\n */\nexport function comingSoonStoreMetadata(name: string | null): Metadata {\n return {\n title: name ? `${name} sắp ra mắt` : \"Sắp ra mắt\",\n description: COMING_SOON_STORE_DESCRIPTION,\n robots: \"noindex, nofollow\",\n };\n}\n\n/**\n * Wraps a leaf page's `generateMetadata` body so a STORE_SUSPENDED lookup\n * doesn't crash the whole route. A STORE_COMING_SOON lookup gets\n * `comingSoonStoreMetadata` the same way.\n *\n * Next.js resolves every matched segment's `generateMetadata` unconditionally\n * to build <head> -- this happens independently of whatever the parent\n * `StoreLayout` eventually renders (it can skip rendering `children` for a\n * suspended store, but that doesn't stop Next from having already awaited\n * this segment's own `generateMetadata`). So each page that calls\n * `getCachedStore` in its own `generateMetadata` needs this, not just the\n * layout's.\n */\nexport async function withSuspendedStoreMetadataFallback(\n fn: () => Promise<Metadata>\n): Promise<Metadata> {\n try {\n return await fn();\n } catch (error) {\n if (isStoreSuspendedError(error)) return SUSPENDED_STORE_METADATA;\n if (isStoreComingSoonError(error)) {\n return comingSoonStoreMetadata(comingSoonStoreNameOf(error));\n }\n throw error;\n }\n}\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,6BAA6B;AAG/B,MAAM,gCACX;AAOK,MAAM,2BAAqC;AAAA,EAChD,OAAO;AAAA,EACP,aACE;AAAA,EACF,QAAQ;AACV;AAMO,SAAS,wBAAwB,MAA+B;AACrE,SAAO;AAAA,IACL,OAAO,OAAO,GAAG,IAAI,0BAAgB;AAAA,IACrC,aAAa;AAAA,IACb,QAAQ;AAAA,EACV;AACF;AAeA,eAAsB,mCACpB,IACmB;AACnB,MAAI;AACF,WAAO,MAAM,GAAG;AAAA,EAClB,SAAS,OAAO;AACd,QAAI,sBAAsB,KAAK,EAAG,QAAO;AACzC,QAAI,uBAAuB,KAAK,GAAG;AACjC,aAAO,wBAAwB,sBAAsB,KAAK,CAAC;AAAA,IAC7D;AACA,UAAM;AAAA,EACR;AACF;","names":[]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { cookies, headers } from "next/headers";
|
|
3
|
+
import { storePreviewTokenFrom } from "./store-preview-cookie.js";
|
|
4
|
+
async function readStorePreviewToken() {
|
|
5
|
+
return storePreviewTokenFrom(await cookies(), { headers: await headers() });
|
|
6
|
+
}
|
|
7
|
+
export {
|
|
8
|
+
readStorePreviewToken
|
|
9
|
+
};
|
|
10
|
+
//# sourceMappingURL=read-store-preview-token.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/stores/read-store-preview-token.ts"],"sourcesContent":["import \"server-only\";\nimport { cookies, headers } from \"next/headers\";\nimport { storePreviewTokenFrom } from \"./store-preview-cookie\";\n\n/**\n * The token this request sends as `X-Store-Preview` (server components\n * only): a preview host's token the middleware stamped, else the store\n * preview cookie, else the theme preview cookie. The layout passes it to\n * `StorefrontKitProvider` while the store is coming soon.\n */\nexport async function readStorePreviewToken(): Promise<string | null> {\n return storePreviewTokenFrom(await cookies(), { headers: await headers() });\n}\n"],"mappings":"AAAA,OAAO;AACP,SAAS,SAAS,eAAe;AACjC,SAAS,6BAA6B;AAQtC,eAAsB,wBAAgD;AACpE,SAAO,sBAAsB,MAAM,QAAQ,GAAG,EAAE,SAAS,MAAM,QAAQ,EAAE,CAAC;AAC5E;","names":[]}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { headers } from "next/headers";
|
|
3
|
+
import { publicConfig } from "../config/public.js";
|
|
4
|
+
import { getCachedStore } from "./cached.js";
|
|
5
|
+
import { getStoreByHost } from "./get-store-by-host.js";
|
|
6
|
+
import {
|
|
7
|
+
comingSoonStoreNameOf,
|
|
8
|
+
isStoreComingSoonError
|
|
9
|
+
} from "./store-coming-soon.js";
|
|
10
|
+
async function resolveComingSoonStore() {
|
|
11
|
+
const config = publicConfig();
|
|
12
|
+
if (config.mode === "single") {
|
|
13
|
+
try {
|
|
14
|
+
await getCachedStore(config.storeRef);
|
|
15
|
+
return null;
|
|
16
|
+
} catch (error) {
|
|
17
|
+
if (isStoreComingSoonError(error)) {
|
|
18
|
+
return { name: comingSoonStoreNameOf(error) };
|
|
19
|
+
}
|
|
20
|
+
throw error;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
const host = (await headers()).get("host") ?? "";
|
|
24
|
+
const lookup = await getStoreByHost(host);
|
|
25
|
+
return lookup.comingSoon ? { name: lookup.comingSoonName } : null;
|
|
26
|
+
}
|
|
27
|
+
export {
|
|
28
|
+
resolveComingSoonStore
|
|
29
|
+
};
|
|
30
|
+
//# sourceMappingURL=resolve-coming-soon.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/stores/resolve-coming-soon.ts"],"sourcesContent":["import \"server-only\";\nimport { headers } from \"next/headers\";\nimport { publicConfig } from \"../config/public\";\nimport { getCachedStore } from \"./cached\";\nimport { getStoreByHost } from \"./get-store-by-host\";\nimport {\n comingSoonStoreNameOf,\n isStoreComingSoonError,\n} from \"./store-coming-soon\";\n\n/**\n * Whether the store this request belongs to is coming soon, and its name\n * (null when the API gave none). Null when the store is not coming soon.\n *\n * The name only ever comes from the API lookup, never from the request, so\n * the /coming-soon page cannot be made to show text a visitor chose.\n */\nexport async function resolveComingSoonStore(): Promise<{\n name: string | null;\n} | null> {\n const config = publicConfig();\n if (config.mode === \"single\") {\n try {\n await getCachedStore(config.storeRef as string);\n return null;\n } catch (error) {\n if (isStoreComingSoonError(error)) {\n return { name: comingSoonStoreNameOf(error) };\n }\n throw error;\n }\n }\n const host = (await headers()).get(\"host\") ?? \"\";\n const lookup = await getStoreByHost(host);\n return lookup.comingSoon ? { name: lookup.comingSoonName } : null;\n}\n"],"mappings":"AAAA,OAAO;AACP,SAAS,eAAe;AACxB,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AASP,eAAsB,yBAEZ;AACR,QAAM,SAAS,aAAa;AAC5B,MAAI,OAAO,SAAS,UAAU;AAC5B,QAAI;AACF,YAAM,eAAe,OAAO,QAAkB;AAC9C,aAAO;AAAA,IACT,SAAS,OAAO;AACd,UAAI,uBAAuB,KAAK,GAAG;AACjC,eAAO,EAAE,MAAM,sBAAsB,KAAK,EAAE;AAAA,MAC9C;AACA,YAAM;AAAA,IACR;AAAA,EACF;AACA,QAAM,QAAQ,MAAM,QAAQ,GAAG,IAAI,MAAM,KAAK;AAC9C,QAAM,SAAS,MAAM,eAAe,IAAI;AACxC,SAAO,OAAO,aAAa,EAAE,MAAM,OAAO,eAAe,IAAI;AAC/D;","names":[]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { ApiClientError } from "@ecomweb/sdk";
|
|
2
|
+
function isStoreComingSoonError(error) {
|
|
3
|
+
return error instanceof ApiClientError && error.code === "STORE_COMING_SOON";
|
|
4
|
+
}
|
|
5
|
+
function comingSoonStoreNameOf(error) {
|
|
6
|
+
if (!isStoreComingSoonError(error)) return null;
|
|
7
|
+
const details = error.details;
|
|
8
|
+
const name = typeof details === "object" && details !== null ? details.name : void 0;
|
|
9
|
+
return typeof name === "string" && name.length > 0 ? name : null;
|
|
10
|
+
}
|
|
11
|
+
const STORE_COMING_SOON_REDIRECT_PATH = "/coming-soon";
|
|
12
|
+
function isStoreComingSoonResponseBody(data) {
|
|
13
|
+
return typeof data === "object" && data !== null && data.code === "STORE_COMING_SOON";
|
|
14
|
+
}
|
|
15
|
+
export {
|
|
16
|
+
STORE_COMING_SOON_REDIRECT_PATH,
|
|
17
|
+
comingSoonStoreNameOf,
|
|
18
|
+
isStoreComingSoonError,
|
|
19
|
+
isStoreComingSoonResponseBody
|
|
20
|
+
};
|
|
21
|
+
//# sourceMappingURL=store-coming-soon.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/stores/store-coming-soon.ts"],"sourcesContent":["import { ApiClientError } from \"@ecomweb/sdk\";\n\n/**\n * True when `error` is the backend's signal that the merchant has not opened\n * this store yet (`STORE_COMING_SOON`, 403, details `{ name }`). Unlike\n * `STORE_SUSPENDED`, this is a merchant-controlled state, and the API lifts\n * it for a request carrying a valid `X-Store-Preview` token.\n *\n * Both `getCachedStore` and `getStoreByHost` surface it as an\n * `ApiClientError`, so this is the one place that decides \"was that coming\n * soon\" for both entry points.\n */\nexport function isStoreComingSoonError(error: unknown): boolean {\n return error instanceof ApiClientError && error.code === \"STORE_COMING_SOON\";\n}\n\n/**\n * The store name the API puts in a coming soon error's `details`, or null\n * when the error is not coming soon or carries no usable name.\n */\nexport function comingSoonStoreNameOf(error: unknown): string | null {\n if (!isStoreComingSoonError(error)) return null;\n const details = (error as ApiClientError).details;\n const name =\n typeof details === \"object\" && details !== null\n ? (details as { name?: unknown }).name\n : undefined;\n return typeof name === \"string\" && name.length > 0 ? name : null;\n}\n\n/**\n * Where the axios interceptor (lib/api/client.ts) sends the browser when a\n * client-side call discovers mid-session that the store is coming soon.\n */\nexport const STORE_COMING_SOON_REDIRECT_PATH = \"/coming-soon\";\n\n/**\n * True when a raw HTTP error body (`{ code, message, details, timestamp }`)\n * is a STORE_COMING_SOON response. The raw-body twin of\n * `isStoreComingSoonError`, for the axios interceptor, which sees the error\n * before the SDK constructs an `ApiClientError`. Internal to the kit.\n */\nexport function isStoreComingSoonResponseBody(data: unknown): boolean {\n return (\n typeof data === \"object\" &&\n data !== null &&\n (data as { code?: unknown }).code === \"STORE_COMING_SOON\"\n );\n}\n"],"mappings":"AAAA,SAAS,sBAAsB;AAYxB,SAAS,uBAAuB,OAAyB;AAC9D,SAAO,iBAAiB,kBAAkB,MAAM,SAAS;AAC3D;AAMO,SAAS,sBAAsB,OAA+B;AACnE,MAAI,CAAC,uBAAuB,KAAK,EAAG,QAAO;AAC3C,QAAM,UAAW,MAAyB;AAC1C,QAAM,OACJ,OAAO,YAAY,YAAY,YAAY,OACtC,QAA+B,OAChC;AACN,SAAO,OAAO,SAAS,YAAY,KAAK,SAAS,IAAI,OAAO;AAC9D;AAMO,MAAM,kCAAkC;AAQxC,SAAS,8BAA8B,MAAwB;AACpE,SACE,OAAO,SAAS,YAChB,SAAS,QACR,KAA4B,SAAS;AAE1C;","names":[]}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { NextResponse } from "next/server";
|
|
2
|
+
import {
|
|
3
|
+
hostOnlyCookieName,
|
|
4
|
+
isHostMappedRequest,
|
|
5
|
+
secureCookies
|
|
6
|
+
} from "../auth/cookies.js";
|
|
7
|
+
import { publicNextUrl } from "../request/public-url.js";
|
|
8
|
+
import {
|
|
9
|
+
THEME_PREVIEW_COOKIE,
|
|
10
|
+
themePreviewCookieName
|
|
11
|
+
} from "../theme/preview-cookie.js";
|
|
12
|
+
const STORE_PREVIEW_COOKIE = "ecw_store_preview";
|
|
13
|
+
const STORE_PREVIEW_PATH = "/preview";
|
|
14
|
+
const STORE_PREVIEW_PARAM = "token";
|
|
15
|
+
const STORE_PREVIEW_HEADER = "x-store-preview";
|
|
16
|
+
const STORE_PREVIEW_TOKEN_HEADER = "x-ecomweb-store-preview-token";
|
|
17
|
+
const MAX_TOKEN_LENGTH = 2048;
|
|
18
|
+
const MAX_AGE_SECONDS = 24 * 60 * 60;
|
|
19
|
+
function storePreviewCookieName(cookiePath) {
|
|
20
|
+
return hostOnlyCookieName(STORE_PREVIEW_COOKIE, cookiePath);
|
|
21
|
+
}
|
|
22
|
+
function applyStorePreview(req, cookiePath, storeRoot) {
|
|
23
|
+
const token = req.nextUrl.searchParams.get(STORE_PREVIEW_PARAM) ?? "";
|
|
24
|
+
const url = publicNextUrl(req);
|
|
25
|
+
url.pathname = storeRoot;
|
|
26
|
+
url.search = "";
|
|
27
|
+
const res = NextResponse.redirect(url, 307);
|
|
28
|
+
const valid = token.length > 0 && token.length <= MAX_TOKEN_LENGTH;
|
|
29
|
+
res.cookies.set(storePreviewCookieName(cookiePath), valid ? token : "", {
|
|
30
|
+
httpOnly: true,
|
|
31
|
+
secure: secureCookies(),
|
|
32
|
+
sameSite: "lax",
|
|
33
|
+
path: cookiePath,
|
|
34
|
+
maxAge: valid ? MAX_AGE_SECONDS : 0
|
|
35
|
+
});
|
|
36
|
+
return res;
|
|
37
|
+
}
|
|
38
|
+
function storePreviewTokenFrom(jar, request) {
|
|
39
|
+
const stamped = request.headers.get(STORE_PREVIEW_TOKEN_HEADER);
|
|
40
|
+
if (stamped) return stamped;
|
|
41
|
+
const hostMapped = isHostMappedRequest(request);
|
|
42
|
+
const storeCookie = hostMapped ? storePreviewCookieName("/") : STORE_PREVIEW_COOKIE;
|
|
43
|
+
const themeCookie = hostMapped ? themePreviewCookieName("/") : THEME_PREVIEW_COOKIE;
|
|
44
|
+
return jar.get(storeCookie)?.value || jar.get(themeCookie)?.value || null;
|
|
45
|
+
}
|
|
46
|
+
const SKIP_STORE_PREVIEW = Object.freeze({
|
|
47
|
+
skipStorePreview: true
|
|
48
|
+
});
|
|
49
|
+
function skipsStorePreview(options) {
|
|
50
|
+
return options?.skipStorePreview === true;
|
|
51
|
+
}
|
|
52
|
+
export {
|
|
53
|
+
SKIP_STORE_PREVIEW,
|
|
54
|
+
STORE_PREVIEW_COOKIE,
|
|
55
|
+
STORE_PREVIEW_HEADER,
|
|
56
|
+
STORE_PREVIEW_PARAM,
|
|
57
|
+
STORE_PREVIEW_PATH,
|
|
58
|
+
STORE_PREVIEW_TOKEN_HEADER,
|
|
59
|
+
applyStorePreview,
|
|
60
|
+
skipsStorePreview,
|
|
61
|
+
storePreviewCookieName,
|
|
62
|
+
storePreviewTokenFrom
|
|
63
|
+
};
|
|
64
|
+
//# sourceMappingURL=store-preview-cookie.js.map
|