@kotao/storefront 0.2.7 → 0.2.9
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/dist/{chunk-DTKLAOKR.js → chunk-PHEKJDFW.js} +3 -3
- package/dist/chunk-PHEKJDFW.js.map +1 -0
- package/dist/{chunk-RFM27BKZ.js → chunk-S4HW5NH7.js} +6 -2
- package/dist/chunk-S4HW5NH7.js.map +1 -0
- package/dist/{client-CwOPPpFF.d.ts → client-D-M3Y1ul.d.ts} +2 -0
- package/dist/{createCartHandler-7DdKB-GF.d.ts → createCartHandler-DJEZW4o2.d.ts} +1 -1
- package/dist/events-react.d.ts +1 -1
- package/dist/events-react.js +20 -9
- package/dist/events-react.js.map +1 -1
- package/dist/events.d.ts +3 -3
- package/dist/index.d.ts +9 -9
- package/dist/index.js +4 -4
- package/dist/react-router.d.ts +5 -5
- package/dist/react-router.js +2 -2
- package/dist/react.d.ts +3 -3
- package/dist/react.js +119 -3
- package/dist/react.js.map +1 -1
- package/dist/{routing-Bz3Cg0BW.d.ts → routing-BYc6JReb.d.ts} +6 -3
- package/dist/{shop-CnrnSAJw.d.ts → shop-keSWbFKV.d.ts} +3 -2
- package/dist/{types-DZX8ScsJ.d.ts → types-C4yXcret.d.ts} +2 -1
- package/package.json +2 -2
- package/dist/chunk-DTKLAOKR.js.map +0 -1
- package/dist/chunk-RFM27BKZ.js.map +0 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { S as StoredThemeSettings } from './fetch-Bq_cc8_G.js';
|
|
2
2
|
import { C as CacheStrategy, K as KotaoCache, S as StorefrontClient, b as StorefrontCacheInput } from './client-D51WdvYR.js';
|
|
3
|
-
import { C as CartHandler } from './createCartHandler-
|
|
4
|
-
import { E as EventsClient } from './client-
|
|
5
|
-
import { H as HydrogenSession } from './types-
|
|
3
|
+
import { C as CartHandler } from './createCartHandler-DJEZW4o2.js';
|
|
4
|
+
import { E as EventsClient } from './client-D-M3Y1ul.js';
|
|
5
|
+
import { H as HydrogenSession } from './types-C4yXcret.js';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* Typed customer-account shapes for the `@kotao/storefront` SDK surface (#91). The names/signatures
|
|
@@ -165,6 +165,9 @@ interface Geo {
|
|
|
165
165
|
colo: string | null;
|
|
166
166
|
botScore: number | null;
|
|
167
167
|
clientIp: string | null;
|
|
168
|
+
/** Approximate IP geolocation from the trusted gateway, never browser GPS. */
|
|
169
|
+
latitude?: number;
|
|
170
|
+
longitude?: number;
|
|
168
171
|
}
|
|
169
172
|
/** Gateway side (#81): produce the two header values for a geo payload. */
|
|
170
173
|
declare function signGeo(geo: Geo, key: string): Promise<{
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { j as CartFormAction } from './types-
|
|
1
|
+
import { j as CartFormAction } from './types-C4yXcret.js';
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
3
|
|
|
4
4
|
interface CartFormProps {
|
|
@@ -166,6 +166,7 @@ interface PixelTransportOptions {
|
|
|
166
166
|
/** Same-origin carve-out endpoint (default '/api/storefront/pixel') — never cross-origin. */
|
|
167
167
|
readonly endpoint?: string;
|
|
168
168
|
readonly batchSize?: number;
|
|
169
|
+
readonly flushAfterMs?: number;
|
|
169
170
|
/**
|
|
170
171
|
* The actual network send. Required + injected: the browser sender (`sendBeacon`/keepalive `fetch`)
|
|
171
172
|
* is DOM-specific and lives in the React layer, keeping this batching core framework-agnostic and
|
|
@@ -179,7 +180,7 @@ interface PixelTransport {
|
|
|
179
180
|
}
|
|
180
181
|
/**
|
|
181
182
|
* Batches pixel events and POSTs them to the same-origin carve-out. Flushes on `batchSize` or an
|
|
182
|
-
* explicit `flush()` (the provider flushes on page-hide). The endpoint is same-origin so themes need
|
|
183
|
+
* explicit `flush()` (the provider flushes on page-hide), or after one second. The endpoint is same-origin so themes need
|
|
183
184
|
* no CORS and no token is exposed in the browser.
|
|
184
185
|
*/
|
|
185
186
|
declare function createPixelTransport(options: PixelTransportOptions): PixelTransport;
|
|
@@ -85,7 +85,8 @@ interface CartDiscountAllocation {
|
|
|
85
85
|
interface CartCost {
|
|
86
86
|
readonly subtotalAmount: Money;
|
|
87
87
|
readonly totalAmount: Money;
|
|
88
|
-
|
|
88
|
+
/** Null when destination taxes have not been configured. */
|
|
89
|
+
readonly totalTaxAmount: Money | null;
|
|
89
90
|
readonly discountTotal: Money;
|
|
90
91
|
readonly taxLines: readonly CartTaxLine[];
|
|
91
92
|
readonly discountAllocations: readonly CartDiscountAllocation[];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kotao/storefront",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.9",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"description": "Kotao Storefronts theme SDK — framework-agnostic server runtime, React Router 8 binding, and authenticated source-authoritative React/Hydrogen editor bridge (ADR-0003/ADR-0047). Leaf package (ADR-0006).",
|
|
@@ -72,7 +72,7 @@
|
|
|
72
72
|
"LICENSE"
|
|
73
73
|
],
|
|
74
74
|
"dependencies": {
|
|
75
|
-
"@kotao/storefront-contracts": "^0.2.
|
|
75
|
+
"@kotao/storefront-contracts": "^0.2.4"
|
|
76
76
|
},
|
|
77
77
|
"peerDependencies": {
|
|
78
78
|
"react": "^18.2.0 || ^19.0.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cache/cache.ts","../src/cart/cookie.ts","../src/customer-account/session.ts","../src/checkout/consent.ts","../src/checkout/checkout-url.ts","../src/checkout/design-tokens.ts","../src/cart/queries.ts","../src/cart/createCartHandler.ts","../src/customer-account/types.ts","../src/customer-account/client.ts","../src/geo/geo.ts","../src/localization/cookie.ts","../src/localization/routing.ts","../src/storefront-client/client.ts","../src/with-cache/with-cache.ts","../src/context/context.ts"],"names":["value","mutation","SAME_ORIGIN_PATH"],"mappings":";;;;;;;;AAUA,IAAM,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,MAAA,OAAO,EAAA;AAAA,IACT,CAAA;AAAA,IACA,MAAA,GAAiB;AACf,MAAA,SAAA,GAAY,KAAA;AACZ,MAAA,OAAO,EAAA;AAAA,IACT;AAAA,GACF;AACF","file":"chunk-DTKLAOKR.js","sourcesContent":["export interface CacheStrategy {\n readonly mode: 'none' | 'short' | 'long' | 'custom'\n /** seconds the value is considered fresh */\n readonly maxAge: number\n /** extra seconds the stale value may be served while revalidating */\n readonly staleWhileRevalidate: number\n /** extra seconds the last value may be served only when revalidation fails */\n readonly staleIfError?: number\n}\n\nconst DEFAULT_STALE_IF_ERROR_SECONDS = 300\n\nexport const CacheNone = (): CacheStrategy => ({\n mode: 'none',\n maxAge: 0,\n staleWhileRevalidate: 0,\n staleIfError: 0,\n})\n\nexport const CacheShort = (o?: Partial<Omit<CacheStrategy, 'mode'>>): CacheStrategy => ({\n mode: 'short',\n maxAge: o?.maxAge ?? 1,\n staleWhileRevalidate: o?.staleWhileRevalidate ?? 9,\n staleIfError: o?.staleIfError ?? DEFAULT_STALE_IF_ERROR_SECONDS,\n})\n\nexport const CacheLong = (o?: Partial<Omit<CacheStrategy, 'mode'>>): CacheStrategy => ({\n mode: 'long',\n maxAge: o?.maxAge ?? 3600,\n staleWhileRevalidate: o?.staleWhileRevalidate ?? 82_800,\n staleIfError: o?.staleIfError ?? DEFAULT_STALE_IF_ERROR_SECONDS,\n})\n\nexport const CacheCustom = (s: Omit<CacheStrategy, 'mode'>): CacheStrategy => ({\n mode: 'custom',\n staleIfError: DEFAULT_STALE_IF_ERROR_SECONDS,\n ...s,\n})\n\n/** Hydrogen-parity storefront sub-request default: fresh 1s, serveable up to ~1 day. */\nexport const StorefrontDefaultCache = (): CacheStrategy => ({\n mode: 'custom',\n maxAge: 1,\n staleWhileRevalidate: 86_399,\n staleIfError: DEFAULT_STALE_IF_ERROR_SECONDS,\n})\n\nexport function generateCacheControlHeader(strategy: CacheStrategy): string {\n if (strategy.mode === 'none') return 'no-store'\n const staleIfError = strategy.staleIfError ?? 0\n const staleIfErrorDirective = staleIfError > 0 ? `, stale-if-error=${String(staleIfError)}` : ''\n return `public, max-age=${String(strategy.maxAge)}, stale-while-revalidate=${String(strategy.staleWhileRevalidate)}${staleIfErrorDirective}`\n}\n\nexport interface KotaoCache {\n run<T>(\n key: string,\n strategy: CacheStrategy,\n fn: () => Promise<T>,\n onStaleIfError?: (fallback: StaleIfErrorFallback) => void,\n ): Promise<T>\n readonly raw: StorefrontCacheInput\n}\n\nexport type StorefrontCacheRequest = Request | string | URL\n\nexport interface StorefrontCacheQueryOptions {\n readonly cacheName?: string\n readonly ignoreMethod?: boolean\n readonly ignoreSearch?: boolean\n readonly ignoreVary?: boolean\n}\n\n/** Worker-compatible Cache input required by the storefront cache implementation. */\nexport interface StorefrontCacheInput {\n delete(request: StorefrontCacheRequest, options?: StorefrontCacheQueryOptions): Promise<boolean>\n match(\n request: StorefrontCacheRequest,\n options?: StorefrontCacheQueryOptions,\n ): Promise<Response | undefined>\n put(request: StorefrontCacheRequest, response: Response): Promise<void>\n}\n\n/** Full standard Cache surface retained by the public storefront client. */\nexport interface StorefrontCache extends StorefrontCacheInput {\n add(request: StorefrontCacheRequest): Promise<void>\n addAll(requests: StorefrontCacheRequest[]): Promise<void>\n keys(\n request?: StorefrontCacheRequest,\n options?: StorefrontCacheQueryOptions,\n ): Promise<readonly Request[]>\n matchAll(\n request?: StorefrontCacheRequest,\n options?: StorefrontCacheQueryOptions,\n ): Promise<readonly Response[]>\n}\n\nexport interface StaleIfErrorFallback {\n readonly ageSeconds: number\n readonly error: unknown\n}\n\ninterface Stored<T> {\n value: T\n /** ms epoch at write time */\n storedAt: number\n}\n\nconst requestFor = (key: string): Request =>\n new Request(`https://kotao.cache/${encodeURIComponent(key)}`)\n\n/**\n * Stale-while-revalidate cache over an injected Cache (WFP untrusted mode disables\n * `caches.default`; each user Worker gets an isolated `caches.open(...)`). `now` is injectable\n * for deterministic tests and to sidestep workerd's intra-request frozen clock — only\n * cross-request age is ever compared, which `Date.now()` reports correctly.\n */\nexport function createCache(opts: {\n cache: StorefrontCacheInput\n waitUntil: (p: Promise<unknown>) => void\n now?: () => number\n}): KotaoCache {\n const now = opts.now ?? ((): number => Date.now())\n const cache = opts.cache\n\n const read = async <T>(key: string): Promise<Stored<T> | null> => {\n const res = await cache.match(requestFor(key))\n if (!res) return null\n try {\n return (await res.json()) as Stored<T>\n } catch {\n return null\n }\n }\n\n const write = async <T>(key: string, value: T, strategy: CacheStrategy): Promise<void> => {\n const body: Stored<T> = { value, storedAt: now() }\n const ttl = strategy.maxAge + strategy.staleWhileRevalidate + (strategy.staleIfError ?? 0)\n await cache.put(\n requestFor(key),\n new Response(JSON.stringify(body), {\n headers: { 'content-type': 'application/json', 'cache-control': `max-age=${String(ttl)}` },\n }),\n )\n }\n\n return {\n raw: cache,\n async run<T>(\n key: string,\n strategy: CacheStrategy,\n fn: () => Promise<T>,\n onStaleIfError?: (fallback: StaleIfErrorFallback) => void,\n ): Promise<T> {\n if (strategy.mode === 'none') return fn()\n\n const stored = await read<T>(key)\n if (stored) {\n const ageSec = (now() - stored.storedAt) / 1000\n if (ageSec <= strategy.maxAge) return stored.value\n if (ageSec <= strategy.maxAge + strategy.staleWhileRevalidate) {\n opts.waitUntil(\n (async (): Promise<void> => {\n const fresh = await fn()\n await write(key, fresh, strategy)\n })().catch(() => undefined),\n )\n return stored.value\n }\n\n if (\n ageSec <=\n strategy.maxAge + strategy.staleWhileRevalidate + (strategy.staleIfError ?? 0)\n ) {\n try {\n const value = await fn()\n opts.waitUntil(write(key, value, strategy))\n return value\n } catch (error) {\n try {\n onStaleIfError?.({ ageSeconds: ageSec, error })\n } catch {\n // Observability must never turn a safe stale fallback into a render failure.\n }\n return stored.value\n }\n }\n }\n\n const value = await fn()\n opts.waitUntil(write(key, value, strategy))\n return value\n },\n }\n}\n","export const CART_ID_COOKIE = 'kotao_cart'\n\nconst CART_MAX_AGE = 60 * 60 * 24 * 30\n\nexport function readCartIdCookie(cookieHeader: string | null | undefined): string | null {\n if (cookieHeader == null || cookieHeader === '') return null\n const match = cookieHeader\n .split(';')\n .map((part) => part.trim())\n .find((part) => part.startsWith(`${CART_ID_COOKIE}=`))\n if (match === undefined) return null\n try {\n const value = decodeURIComponent(match.slice(CART_ID_COOKIE.length + 1))\n return value === '' ? null : value\n } catch {\n return null\n }\n}\n\nexport function buildCartIdCookie(cartId: string): string {\n return `${CART_ID_COOKIE}=${encodeURIComponent(cartId)}; Path=/; Max-Age=${CART_MAX_AGE}; SameSite=Lax; Secure; HttpOnly`\n}\n\nexport function clearCartIdCookie(): string {\n return `${CART_ID_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax; Secure; HttpOnly`\n}\n","/**\n * Per-shop customer session cookie (#91). Sessions are scoped to the shop's custom hostname and MUST\n * NOT be shared across shops or up to `.kotao.com` (ADR-0004, design §\"Checkout handoff\") — cross-shop\n * session bleed is the footgun this module exists to prevent. The cookie name + attributes are defined\n * here once so every reader/writer (theme runtime, proxy callback) agrees on the shape.\n */\n\nexport const CUSTOMER_SESSION_COOKIE = 'kotao_customer_session'\nexport const DEFAULT_SESSION_MAX_AGE = 60 * 60 * 24 * 30 // 30 days\nexport const HOSTED_CUSTOMER_SESSION_COOKIE = '__Host-kotao_customer_session'\nexport const HOSTED_CUSTOMER_CSRF_COOKIE = '__Host-kotao_customer_csrf'\nexport const HOSTED_CUSTOMER_CSRF_HEADER = 'x-kotao-csrf-token'\nexport const MAX_HOSTED_SESSION_MAX_AGE = 60 * 60 * 24 * 365 // 365 days\nexport const DEFAULT_HOSTED_SESSION_MAX_AGE = MAX_HOSTED_SESSION_MAX_AGE\nexport const MAX_LEGACY_CUSTOMER_SESSION_TOKEN_LENGTH = 4096\n\nexport interface SessionCookieAttrs {\n /**\n * The shop's custom hostname. `Domain` is pinned to it host-scoped (no leading dot), so the cookie\n * matches only this shop's host — never another shop and never the `.kotao.com` platform apex.\n */\n readonly hostname: string\n readonly maxAgeSeconds?: number\n}\n\nexport interface HostedSessionCookieAttrs {\n readonly maxAgeSeconds?: number\n}\n\nexport interface LegacySessionReadOptions {\n /** The caller must opt in only while the one-time legacy exchange is enabled. */\n readonly allowLegacy: boolean\n}\n\n/**\n * A leading dot, empty, or trailing-dot (FQDN form, e.g. `shop.example.com.`) host would broaden or\n * non-standardize the cookie scope — reject all of them loudly.\n */\nconst assertHostname = (hostname: string): void => {\n if (hostname === '' || hostname.startsWith('.') || hostname.endsWith('.')) {\n throw new Error(`invalid shop hostname for the customer session cookie: '${hostname}'`)\n }\n}\n\n/** The shop custom host of the current request — the session isolation boundary. */\nexport function shopHostname(request: Request): string {\n return new URL(request.url).hostname\n}\n\n/**\n * Build the session cookie: `HttpOnly` (theme JS can never read the token), `Secure`, `SameSite=Lax`\n * (survives the IdP login-redirect round trip), `Domain` pinned host-scoped to the shop.\n */\nexport function buildCustomerSessionCookie(token: string, attrs: SessionCookieAttrs): string {\n assertHostname(attrs.hostname)\n const maxAge = attrs.maxAgeSeconds ?? DEFAULT_SESSION_MAX_AGE\n return (\n `${CUSTOMER_SESSION_COOKIE}=${encodeURIComponent(token)}; Domain=${attrs.hostname}; ` +\n `Path=/; Max-Age=${maxAge}; HttpOnly; Secure; SameSite=Lax`\n )\n}\n\n/** Expire the session cookie (logout) on the same host scope. */\nexport function clearCustomerSessionCookie(attrs: SessionCookieAttrs): string {\n assertHostname(attrs.hostname)\n return (\n `${CUSTOMER_SESSION_COOKIE}=; Domain=${attrs.hostname}; ` +\n `Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax`\n )\n}\n\n/** Read the session token out of a server-side `Cookie` header; null if absent or empty. */\nexport function readCustomerSessionToken(cookieHeader: string | null | undefined): string | null {\n if (cookieHeader === null || cookieHeader === undefined || cookieHeader === '') return null\n const match = cookieHeader\n .split(';')\n .map((part) => part.trim())\n .find((part) => part.startsWith(`${CUSTOMER_SESSION_COOKIE}=`))\n if (match === undefined) return null\n const raw = match.slice(CUSTOMER_SESSION_COOKIE.length + 1)\n if (raw === '') return null\n try {\n return decodeURIComponent(raw)\n } catch {\n return null // malformed percent-encoding → treat as no session, never throw at construction\n }\n}\n\n/** Build the opaque hosted-session cookie required by the `__Host-` browser contract. */\nexport function buildHostedCustomerSessionCookie(\n token: string,\n attrs: HostedSessionCookieAttrs = {},\n): string {\n if (token === '') throw new Error('hosted customer session token must not be empty')\n const maxAge = attrs.maxAgeSeconds ?? DEFAULT_HOSTED_SESSION_MAX_AGE\n if (!Number.isInteger(maxAge) || maxAge <= 0 || maxAge > MAX_HOSTED_SESSION_MAX_AGE) {\n throw new Error('hosted customer session Max-Age must be between 1 second and 365 days')\n }\n return (\n `${HOSTED_CUSTOMER_SESSION_COOKIE}=${encodeURIComponent(token)}; ` +\n `Path=/; Max-Age=${maxAge}; HttpOnly; Secure; SameSite=Lax`\n )\n}\n\n/** Clear the host-only opaque session without ever adding a Domain attribute. */\nexport function clearHostedCustomerSessionCookie(): string {\n return (\n `${HOSTED_CUSTOMER_SESSION_COOKIE}=; ` + 'Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax'\n )\n}\n\n/** Read only the new host-only opaque session cookie. */\nexport function readHostedCustomerSessionToken(\n cookieHeader: string | null | undefined,\n): string | null {\n return readBoundedCookie(cookieHeader, HOSTED_CUSTOMER_SESSION_COOKIE)\n}\n\nexport function readHostedCustomerCsrfToken(\n cookieHeader: string | null | undefined,\n): string | null {\n const token = readBoundedCookie(cookieHeader, HOSTED_CUSTOMER_CSRF_COOKIE, 43)\n return token !== null && /^[A-Za-z0-9_-]{43}$/.test(token) ? token : null\n}\n\n/**\n * Read the old stateless cookie only during an explicitly enabled migration window. Oversized\n * values are rejected before decoding so the compatibility path remains bounded.\n */\nexport function readLegacyCustomerSessionToken(\n cookieHeader: string | null | undefined,\n options: LegacySessionReadOptions,\n): string | null {\n if (!options.allowLegacy) return null\n return readBoundedCookie(\n cookieHeader,\n CUSTOMER_SESSION_COOKIE,\n MAX_LEGACY_CUSTOMER_SESSION_TOKEN_LENGTH,\n )\n}\n\n/** Explicitly clear the old Domain-scoped cookie after a migration attempt. */\nexport function clearLegacyCustomerSessionCookie(attrs: SessionCookieAttrs): string {\n return clearCustomerSessionCookie(attrs)\n}\n\nfunction readBoundedCookie(\n cookieHeader: string | null | undefined,\n name: string,\n maxLength = MAX_LEGACY_CUSTOMER_SESSION_TOKEN_LENGTH,\n): string | null {\n if (cookieHeader === null || cookieHeader === undefined || cookieHeader === '') return null\n const match = cookieHeader\n .split(';')\n .map((part) => part.trim())\n .find((part) => part.startsWith(`${name}=`))\n if (match === undefined) return null\n const raw = match.slice(name.length + 1)\n if (raw === '' || raw.length > maxLength) return null\n try {\n const decoded = decodeURIComponent(raw)\n return decoded.length <= maxLength ? decoded : null\n } catch {\n return null\n }\n}\n","import { CONSENT_BUCKETS, type ConsentBucket, type ConsentState } from '../analytics/consent'\n\nconst PARAM_PREFIX = 'consent_'\nconst VALID_PARAM_VALUES = new Set(['0', '1'])\n\nexport const CHECKOUT_CONSENT_PARAM_PREFIX = PARAM_PREFIX\nexport const CHECKOUT_CONSENT_CATEGORIES: readonly ConsentBucket[] = CONSENT_BUCKETS\n\n// Checkout app contract: every category is present as `consent_*` with a 0/1 value.\n// The platform checkout route decodes this before rendering and degrades gracefully when absent.\n\nexport function encodeCheckoutConsent(state: ConsentState): URLSearchParams {\n assertConsentState(state)\n const params = new URLSearchParams()\n for (const bucket of CHECKOUT_CONSENT_CATEGORIES) {\n params.set(paramName(bucket), state[bucket] ? '1' : '0')\n }\n return params\n}\n\nexport function decodeCheckoutConsent(input: URLSearchParams | string | URL): ConsentState {\n const params =\n input instanceof URL\n ? input.searchParams\n : typeof input === 'string'\n ? new URLSearchParams(input)\n : input\n\n const decoded = {} as Record<ConsentBucket, boolean>\n for (const bucket of CHECKOUT_CONSENT_CATEGORIES) {\n const key = paramName(bucket)\n const value = params.get(key)\n if (value === null) throw new Error(`Missing checkout consent param: ${key}`)\n if (!VALID_PARAM_VALUES.has(value)) {\n throw new Error(`Invalid checkout consent param ${key}: expected 0 or 1`)\n }\n decoded[bucket] = value === '1'\n }\n return decoded\n}\n\nfunction paramName(bucket: ConsentBucket): string {\n return `${PARAM_PREFIX}${bucket}`\n}\n\nfunction assertConsentState(state: ConsentState): void {\n for (const bucket of CHECKOUT_CONSENT_CATEGORIES) {\n if (typeof state[bucket] !== 'boolean') {\n throw new Error(`Invalid checkout consent state: ${bucket} must be boolean`)\n }\n }\n}\n","import type { ConsentState } from '../analytics/consent'\nimport { encodeCheckoutConsent } from './consent'\n\nexport interface ResolveCheckoutUrlOptions {\n readonly checkoutUrl: string\n readonly consent: ConsentState\n readonly shopDomain?: string\n readonly requestUrl?: string | URL | Request\n}\n\nexport function resolveCheckoutUrl(options: ResolveCheckoutUrlOptions): string {\n const origin = resolveShopOrigin(options)\n const rawCheckoutUrl = options.checkoutUrl.trim()\n const url = parseCheckoutUrl(options.checkoutUrl, origin)\n\n if (url.origin !== origin) {\n if (!isExternalHttpsCheckoutUrl(rawCheckoutUrl, url)) {\n throw new Error(`checkoutUrl must stay on the same origin as the shop domain (${origin})`)\n }\n appendConsent(url, options.consent)\n assertNoZoneIdentityLeak(url)\n return url.toString()\n }\n if (!isSameOriginCheckoutPath(url)) {\n throw new Error(`checkoutUrl must use the Gateway-owned /checkout/* carve-out`)\n }\n\n appendConsent(url, options.consent)\n assertNoZoneIdentityLeak(url)\n return url.toString()\n}\n\nfunction resolveShopOrigin(options: ResolveCheckoutUrlOptions): string {\n if (options.shopDomain !== undefined) return originFromDomain(options.shopDomain)\n if (options.requestUrl !== undefined) return originFromRequestUrl(options.requestUrl)\n throw new Error('checkoutUrl resolution requires shopDomain or requestUrl')\n}\n\nfunction originFromDomain(shopDomain: string): string {\n const trimmed = shopDomain.trim()\n if (trimmed === '') throw new Error('shopDomain must not be empty')\n const url = new URL(/^https?:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`)\n return url.origin\n}\n\nfunction originFromRequestUrl(requestUrl: string | URL | Request): string {\n if (requestUrl instanceof Request) return new URL(requestUrl.url).origin\n return new URL(requestUrl.toString()).origin\n}\n\nfunction parseCheckoutUrl(checkoutUrl: string, origin: string): URL {\n if (checkoutUrl.trim() === '') throw new Error('checkoutUrl must not be empty')\n if (checkoutUrl.startsWith('//')) {\n throw new Error('checkoutUrl must stay on the same origin as the shop domain')\n }\n return new URL(checkoutUrl, origin)\n}\n\nfunction isSameOriginCheckoutPath(url: URL): boolean {\n return url.pathname.startsWith('/checkout/')\n}\n\nfunction isExternalHttpsCheckoutUrl(rawCheckoutUrl: string, url: URL): boolean {\n return (\n /^https:\\/\\//i.test(rawCheckoutUrl) &&\n (/^\\/checkouts?\\//u.test(url.pathname) || /^\\/cart\\/c\\//u.test(url.pathname))\n )\n}\n\nfunction appendConsent(url: URL, consent: ConsentState): void {\n for (const [key, value] of encodeCheckoutConsent(consent)) {\n url.searchParams.set(key, value)\n }\n}\n\nfunction assertNoZoneIdentityLeak(url: URL): void {\n for (const [key, value] of url.searchParams) {\n const pair = `${key}=${value}`.toLowerCase()\n if (pair.includes('.kotao.com') || pair.includes('domain=kotao.com')) {\n throw new Error('checkout handoff URL must not carry zone-wide Kotao identity')\n }\n }\n}\n","import { HOSTED_SURFACE_DESIGN_INPUTS, type SettingInput } from '@kotao/storefront-contracts'\n\nimport type { ThemeSettingsSnapshot } from '../settings/types'\n\nexport interface CheckoutDesignTokens {\n readonly logo: { readonly src: string; readonly altText: string | null } | null\n readonly colors: {\n readonly accent: string\n readonly background: string\n readonly foreground: string\n }\n readonly fonts: {\n readonly body: string\n readonly heading: string\n }\n}\n\n// Checkout app contract: these global setting names are consumed by the platform checkout renderer.\nconst CHECKOUT_TOKEN_DEFAULTS = {\n checkoutLogoAlt: '',\n checkoutColorAccent: '#005bd3',\n checkoutColorBackground: '#ffffff',\n checkoutColorForeground: '#111827',\n checkoutFontBody: 'Inter',\n checkoutFontHeading: 'Inter',\n} as const\n\nexport const CHECKOUT_DESIGN_TOKEN_INPUTS = HOSTED_SURFACE_DESIGN_INPUTS.map((input) => ({\n ...input,\n ...(input.name in CHECKOUT_TOKEN_DEFAULTS\n ? { defaultValue: CHECKOUT_TOKEN_DEFAULTS[input.name as keyof typeof CHECKOUT_TOKEN_DEFAULTS] }\n : {}),\n})) satisfies readonly SettingInput[]\n\nexport function extractCheckoutDesignTokens(\n snapshot: Pick<ThemeSettingsSnapshot, 'global'>,\n): CheckoutDesignTokens {\n const global = snapshot.global\n const logoUrl = optionalString(global['checkoutLogoUrl'], 'checkoutLogoUrl')\n const logoAlt = optionalString(global['checkoutLogoAlt'], 'checkoutLogoAlt')\n return {\n logo: logoUrl === null ? null : { src: logoUrl, altText: logoAlt },\n colors: {\n accent: requiredString(global['checkoutColorAccent'], 'checkoutColorAccent'),\n background: requiredString(global['checkoutColorBackground'], 'checkoutColorBackground'),\n foreground: requiredString(global['checkoutColorForeground'], 'checkoutColorForeground'),\n },\n fonts: {\n body: requiredString(global['checkoutFontBody'], 'checkoutFontBody'),\n heading: requiredString(global['checkoutFontHeading'], 'checkoutFontHeading'),\n },\n }\n}\n\nfunction optionalString(value: unknown, key: string): string | null {\n if (value === undefined || value === null || value === '') return null\n if (typeof value !== 'string') throw new Error(`${key} must be a string`)\n const trimmed = value.trim()\n if (trimmed === '') return null\n return trimmed\n}\n\nfunction requiredString(value: unknown, key: string): string {\n if (typeof value !== 'string' || value.trim() === '') {\n throw new Error(`${key} must be a non-empty string`)\n }\n return value.trim()\n}\n","export const CART_FRAGMENT = /* GraphQL */ `\n fragment KotaoCart on Cart {\n id\n checkoutUrl\n totalQuantity\n cost {\n subtotalAmount {\n amount\n currencyCode\n }\n totalAmount {\n amount\n currencyCode\n }\n totalTaxAmount {\n amount\n currencyCode\n }\n }\n buyerIdentity {\n email\n phone\n countryCode\n companyLocationId\n }\n note\n attributes {\n key\n value\n }\n discountCodes\n lines(first: 250) {\n nodes {\n id\n quantity\n attributes {\n key\n value\n }\n merchandise {\n ... on ProductVariant {\n id\n title\n availableForSale\n image {\n url\n altText\n width\n height\n }\n price {\n amount\n currencyCode\n }\n compareAtPrice {\n amount\n currencyCode\n }\n selectedOptions {\n name\n value\n }\n product {\n handle\n title\n }\n }\n }\n cost {\n amountPerQuantity {\n amount\n currencyCode\n }\n subtotalAmount {\n amount\n currencyCode\n }\n totalAmount {\n amount\n currencyCode\n }\n }\n }\n }\n }\n`\n\nexport const CART_QUERY = /* GraphQL */ `\n ${CART_FRAGMENT}\n query KotaoCart($cartId: ID!) {\n cart(id: $cartId) {\n ...KotaoCart\n }\n }\n`\n\nexport const CART_CREATE_MUTATION = /* GraphQL */ `\n ${CART_FRAGMENT}\n mutation KotaoCartCreate($input: CartInput) {\n cartCreate(input: $input) {\n cart {\n ...KotaoCart\n }\n userErrors {\n field\n message\n code\n }\n }\n }\n`\n\nexport const CART_LINES_ADD_MUTATION = /* GraphQL */ `\n ${CART_FRAGMENT}\n mutation KotaoCartLinesAdd($cartId: ID!, $lines: [CartLineInput!]!) {\n cartLinesAdd(cartId: $cartId, lines: $lines) {\n cart {\n ...KotaoCart\n }\n userErrors {\n field\n message\n code\n }\n }\n }\n`\n\nexport const CART_LINES_UPDATE_MUTATION = /* GraphQL */ `\n ${CART_FRAGMENT}\n mutation KotaoCartLinesUpdate($cartId: ID!, $lines: [CartLineUpdateInput!]!) {\n cartLinesUpdate(cartId: $cartId, lines: $lines) {\n cart {\n ...KotaoCart\n }\n userErrors {\n field\n message\n code\n }\n }\n }\n`\n\nexport const CART_LINES_REMOVE_MUTATION = /* GraphQL */ `\n ${CART_FRAGMENT}\n mutation KotaoCartLinesRemove($cartId: ID!, $lineIds: [ID!]!) {\n cartLinesRemove(cartId: $cartId, lineIds: $lineIds) {\n cart {\n ...KotaoCart\n }\n userErrors {\n field\n message\n code\n }\n }\n }\n`\n\nexport const CART_BUYER_IDENTITY_UPDATE_MUTATION = /* GraphQL */ `\n ${CART_FRAGMENT}\n mutation KotaoCartBuyerIdentityUpdate($cartId: ID!, $buyerIdentity: CartBuyerIdentityInput!) {\n cartBuyerIdentityUpdate(cartId: $cartId, buyerIdentity: $buyerIdentity) {\n cart {\n ...KotaoCart\n }\n userErrors {\n field\n message\n code\n }\n }\n }\n`\n\nconst mutation = (\n operationName: string,\n fieldName: string,\n args: string,\n variables: string,\n): string => /* GraphQL */ `\n ${CART_FRAGMENT}\n mutation ${operationName}($cartId: ID!, ${variables}) {\n ${fieldName}(cartId: $cartId, ${args}) {\n cart {\n ...KotaoCart\n }\n userErrors {\n field\n message\n code\n }\n }\n }\n`\n\nexport const CART_DISCOUNT_CODES_UPDATE_MUTATION = mutation(\n 'CartDiscountCodesUpdate',\n 'cartDiscountCodesUpdate',\n 'discountCodes: $discountCodes',\n '$discountCodes: [String!]!',\n)\n\nexport const CART_GIFT_CARD_CODES_ADD_MUTATION = mutation(\n 'CartGiftCardCodesAdd',\n 'cartGiftCardCodesAdd',\n 'giftCardCodes: $giftCardCodes',\n '$giftCardCodes: [String!]!',\n)\n\nexport const CART_GIFT_CARD_CODES_REMOVE_MUTATION = mutation(\n 'CartGiftCardCodesRemove',\n 'cartGiftCardCodesRemove',\n 'giftCardCodes: $giftCardCodes',\n '$giftCardCodes: [String!]!',\n)\n\nexport const CART_NOTE_UPDATE_MUTATION = mutation(\n 'CartNoteUpdate',\n 'cartNoteUpdate',\n 'note: $note',\n '$note: String',\n)\n\nexport const CART_ATTRIBUTES_UPDATE_MUTATION = mutation(\n 'CartAttributesUpdate',\n 'cartAttributesUpdate',\n 'attributes: $attributes',\n '$attributes: [AttributeInput!]!',\n)\n\nexport const CART_METAFIELDS_SET_MUTATION = mutation(\n 'CartMetafieldsSet',\n 'cartMetafieldsSet',\n 'metafields: $metafields',\n '$metafields: [CartMetafieldInput!]!',\n)\n\nexport const CART_METAFIELDS_DELETE_MUTATION = mutation(\n 'CartMetafieldsDelete',\n 'cartMetafieldsDelete',\n 'metafields: $metafields',\n '$metafields: [CartMetafieldIdentifierInput!]!',\n)\n\nexport const CART_DELIVERY_ADDRESSES_REPLACE_MUTATION = mutation(\n 'CartDeliveryAddressesReplace',\n 'cartDeliveryAddressesReplace',\n 'addresses: $addresses',\n '$addresses: [CartDeliveryAddressInput!]!',\n)\n\nexport const CART_SELECTED_DELIVERY_OPTIONS_UPDATE_MUTATION = mutation(\n 'CartSelectedDeliveryOptionsUpdate',\n 'cartSelectedDeliveryOptionsUpdate',\n 'selectedDeliveryOptions: $selectedDeliveryOptions',\n '$selectedDeliveryOptions: [CartSelectedDeliveryOptionInput!]!',\n)\n","import { CacheNone } from '../cache/cache'\nimport {\n readCustomerSessionToken,\n readHostedCustomerSessionToken,\n} from '../customer-account/session'\nimport type { StorefrontClient } from '../storefront-client/client'\nimport { readConsentCookie } from '../analytics/consent'\nimport { resolveCheckoutUrl } from '../checkout'\nimport { CART_FORM_ACTIONS, type CartFormAction } from './actions'\nimport { buildCartIdCookie, readCartIdCookie } from './cookie'\nimport {\n CART_ATTRIBUTES_UPDATE_MUTATION,\n CART_BUYER_IDENTITY_UPDATE_MUTATION,\n CART_CREATE_MUTATION,\n CART_DELIVERY_ADDRESSES_REPLACE_MUTATION,\n CART_DISCOUNT_CODES_UPDATE_MUTATION,\n CART_GIFT_CARD_CODES_ADD_MUTATION,\n CART_GIFT_CARD_CODES_REMOVE_MUTATION,\n CART_LINES_ADD_MUTATION,\n CART_LINES_REMOVE_MUTATION,\n CART_LINES_UPDATE_MUTATION,\n CART_METAFIELDS_DELETE_MUTATION,\n CART_METAFIELDS_SET_MUTATION,\n CART_NOTE_UPDATE_MUTATION,\n CART_QUERY,\n CART_SELECTED_DELIVERY_OPTIONS_UPDATE_MUTATION,\n} from './queries'\nimport type {\n Cart,\n CartAttribute,\n CartBuyerIdentityInput,\n CartDeliveryAddress,\n CartLineInput,\n CartLineUpdateInput,\n CartMetafield,\n CartMetafieldIdentifier,\n CartMutationResult,\n CartSelectedDeliveryOption,\n} from './types'\n\ntype MutationEnvelope<K extends string> = Record<K, Omit<CartMutationResult, 'headers'>>\n\ninterface CartCreateInput {\n readonly lines?: readonly CartLineInput[]\n readonly note?: string | null\n readonly attributes?: readonly CartAttribute[]\n readonly buyerIdentity?: CartBuyerIdentityInput\n}\n\nexport interface CartDispatchAction {\n readonly action: CartFormAction\n readonly inputs: Record<string, unknown>\n}\n\nexport interface CartHandler {\n get(): Promise<Cart | null>\n getCart(): Promise<Cart | null>\n create(input?: CartCreateInput): Promise<CartMutationResult>\n addLines(lines: readonly CartLineInput[]): Promise<CartMutationResult>\n updateLines(lines: readonly CartLineUpdateInput[]): Promise<CartMutationResult>\n removeLines(lineIds: readonly string[]): Promise<CartMutationResult>\n updateBuyerIdentity(buyerIdentity: CartBuyerIdentityInput): Promise<CartMutationResult>\n updateDiscountCodes(discountCodes: readonly string[]): Promise<CartMutationResult>\n setCartId(cartId: string): Headers\n cartCreate(input?: CartCreateInput): Promise<CartMutationResult>\n linesAdd(lines: readonly CartLineInput[]): Promise<CartMutationResult>\n linesUpdate(lines: readonly CartLineUpdateInput[]): Promise<CartMutationResult>\n linesRemove(lineIds: readonly string[]): Promise<CartMutationResult>\n buyerIdentityUpdate(buyerIdentity: CartBuyerIdentityInput): Promise<CartMutationResult>\n discountCodesUpdate(discountCodes: readonly string[]): Promise<CartMutationResult>\n giftCardCodesAdd(giftCardCodes: readonly string[]): Promise<CartMutationResult>\n giftCardCodesRemove(giftCardCodes: readonly string[]): Promise<CartMutationResult>\n noteUpdate(note: string | null): Promise<CartMutationResult>\n attributesUpdate(attributes: readonly CartAttribute[]): Promise<CartMutationResult>\n metafieldsSet(metafields: readonly CartMetafield[]): Promise<CartMutationResult>\n metafieldsDelete(metafields: readonly CartMetafieldIdentifier[]): Promise<CartMutationResult>\n deliveryAddressesReplace(addresses: readonly CartDeliveryAddress[]): Promise<CartMutationResult>\n selectedDeliveryOptionsUpdate(\n selectedDeliveryOptions: readonly CartSelectedDeliveryOption[],\n ): Promise<CartMutationResult>\n dispatch(action: CartDispatchAction): Promise<CartMutationResult>\n}\n\ntype MaybePromise<T> = T | Promise<T>\n\nexport type CartGetId = () => MaybePromise<string | null | undefined>\n\nexport type CartSetId = (cartId: string) => MaybePromise<string | Headers | null | undefined | void>\n\nexport interface RequestCartHandlerOptions {\n request: Request\n storefront: StorefrontClient\n}\n\nexport interface HydrogenCartHandlerOptions {\n storefront: StorefrontClient\n customerAccount?: unknown\n getCartId: CartGetId\n setCartId: CartSetId\n}\n\nexport type CreateCartHandlerOptions = RequestCartHandlerOptions | HydrogenCartHandlerOptions\n\nexport function cartGetIdDefault(headers: Headers): CartGetId {\n return () => readCartIdCookie(headers.get('cookie'))\n}\n\nexport function cartSetIdDefault(): CartSetId {\n return (cartId: string) => buildCartIdCookie(cartId)\n}\n\nexport function createCartHandler(opts: CreateCartHandlerOptions): CartHandler {\n const request = 'request' in opts ? opts.request : undefined\n let getCartId: CartGetId\n let setCartId: CartSetId\n let cartId: string | null | undefined\n if ('request' in opts) {\n getCartId = () => readCartIdCookie(opts.request.headers.get('cookie'))\n setCartId = (nextCartId: string) => buildCartIdCookie(nextCartId)\n cartId = readCartIdCookie(opts.request.headers.get('cookie'))\n } else {\n getCartId = opts.getCartId\n setCartId = opts.setCartId\n cartId = undefined\n }\n const consent = readConsentCookie(request?.headers.get('cookie'))\n const cookieHeader = request?.headers.get('cookie')\n const customerAccessToken =\n readHostedCustomerSessionToken(cookieHeader) ?? readCustomerSessionToken(cookieHeader)\n\n const currentCartId = async (): Promise<string | null> => {\n if (cartId !== undefined) return cartId\n cartId = (await getCartId()) ?? null\n return cartId\n }\n\n const withCheckoutUrl = (cart: Cart | null): Cart | null => {\n if (cart === null) return null\n if (request === undefined) return cart\n return {\n ...cart,\n checkoutUrl: resolveCheckoutUrl({\n checkoutUrl: cart.checkoutUrl,\n requestUrl: request,\n consent,\n }),\n }\n }\n\n const withCookie = async (\n payload: Omit<CartMutationResult, 'headers'>,\n ): Promise<CartMutationResult> => {\n const headers = new Headers()\n if (payload.cart?.id) {\n cartId = payload.cart.id\n appendSetCartIdHeaders(headers, await setCartId(payload.cart.id))\n }\n return { ...payload, cart: withCheckoutUrl(payload.cart), headers }\n }\n\n const setCartIdSync = (nextCartId: string): Headers => {\n cartId = nextCartId\n const headers = new Headers()\n const value = setCartId(nextCartId)\n if (isPromiseLike(value)) {\n throw new Error('Hydrogen cart.setCartId requires a synchronous setCartId implementation')\n }\n appendSetCartIdHeaders(headers, value)\n return headers\n }\n\n const create = async (input: CartCreateInput = {}): Promise<CartMutationResult> => {\n const effectiveInput =\n customerAccessToken === null\n ? input\n : {\n ...input,\n buyerIdentity: {\n ...input.buyerIdentity,\n customerAccessToken: input.buyerIdentity?.customerAccessToken ?? customerAccessToken,\n },\n }\n const data = await opts.storefront.mutate<MutationEnvelope<'cartCreate'>>(\n CART_CREATE_MUTATION,\n { variables: { input: effectiveInput } },\n )\n return withCookie(data.cartCreate)\n }\n\n const ensureCartId = async (): Promise<string> => {\n const id = await currentCartId()\n if (id) return id\n const created = await create()\n if (!created.cart) throw new Error('cartCreate returned no cart')\n return created.cart.id\n }\n\n const mutateExisting = async <K extends string>(\n document: string,\n key: K,\n variables: Record<string, unknown>,\n ): Promise<CartMutationResult> => {\n const id = await ensureCartId()\n const data = await opts.storefront.mutate<MutationEnvelope<K>>(document, {\n variables: { cartId: id, ...variables },\n })\n return withCookie(data[key])\n }\n\n const handler: CartHandler = {\n async get() {\n const id = await currentCartId()\n if (!id) return null\n const data = await opts.storefront.query<{ cart: Cart | null }>(CART_QUERY, {\n variables: { cartId: id },\n cache: CacheNone(),\n })\n return withCheckoutUrl(data.cart)\n },\n\n getCart() {\n return handler.get()\n },\n\n create,\n addLines: (lines) => handler.linesAdd(lines),\n updateLines: (lines) => handler.linesUpdate(lines),\n removeLines: (lineIds) => handler.linesRemove(lineIds),\n updateBuyerIdentity: (buyerIdentity) => handler.buyerIdentityUpdate(buyerIdentity),\n updateDiscountCodes: (discountCodes) => handler.discountCodesUpdate(discountCodes),\n setCartId: setCartIdSync,\n\n cartCreate: create,\n\n async linesAdd(lines) {\n if (!(await currentCartId())) return create({ lines })\n return mutateExisting(CART_LINES_ADD_MUTATION, 'cartLinesAdd', { lines })\n },\n\n linesUpdate: (lines) =>\n mutateExisting(CART_LINES_UPDATE_MUTATION, 'cartLinesUpdate', { lines }),\n\n linesRemove: (lineIds) =>\n mutateExisting(CART_LINES_REMOVE_MUTATION, 'cartLinesRemove', { lineIds }),\n\n buyerIdentityUpdate: (buyerIdentity) =>\n mutateExisting(CART_BUYER_IDENTITY_UPDATE_MUTATION, 'cartBuyerIdentityUpdate', {\n buyerIdentity,\n }),\n\n discountCodesUpdate: (discountCodes) =>\n mutateExisting(CART_DISCOUNT_CODES_UPDATE_MUTATION, 'cartDiscountCodesUpdate', {\n discountCodes,\n }),\n\n giftCardCodesAdd: (giftCardCodes) =>\n mutateExisting(CART_GIFT_CARD_CODES_ADD_MUTATION, 'cartGiftCardCodesAdd', {\n giftCardCodes,\n }),\n\n giftCardCodesRemove: (giftCardCodes) =>\n mutateExisting(CART_GIFT_CARD_CODES_REMOVE_MUTATION, 'cartGiftCardCodesRemove', {\n giftCardCodes,\n }),\n\n noteUpdate: (note) => mutateExisting(CART_NOTE_UPDATE_MUTATION, 'cartNoteUpdate', { note }),\n\n attributesUpdate: (attributes) =>\n mutateExisting(CART_ATTRIBUTES_UPDATE_MUTATION, 'cartAttributesUpdate', { attributes }),\n\n metafieldsSet: (metafields) =>\n mutateExisting(CART_METAFIELDS_SET_MUTATION, 'cartMetafieldsSet', { metafields }),\n\n metafieldsDelete: (metafields) =>\n mutateExisting(CART_METAFIELDS_DELETE_MUTATION, 'cartMetafieldsDelete', { metafields }),\n\n deliveryAddressesReplace: (addresses) =>\n mutateExisting(CART_DELIVERY_ADDRESSES_REPLACE_MUTATION, 'cartDeliveryAddressesReplace', {\n addresses,\n }),\n\n selectedDeliveryOptionsUpdate: (selectedDeliveryOptions) =>\n mutateExisting(\n CART_SELECTED_DELIVERY_OPTIONS_UPDATE_MUTATION,\n 'cartSelectedDeliveryOptionsUpdate',\n { selectedDeliveryOptions },\n ),\n\n dispatch(action) {\n switch (action.action) {\n case CART_FORM_ACTIONS.LinesAdd:\n return handler.linesAdd(action.inputs.lines as CartLineInput[])\n case CART_FORM_ACTIONS.LinesUpdate:\n return handler.linesUpdate(action.inputs.lines as CartLineUpdateInput[])\n case CART_FORM_ACTIONS.LinesRemove:\n return handler.linesRemove(action.inputs.lineIds as string[])\n case CART_FORM_ACTIONS.DiscountCodesUpdate:\n return handler.discountCodesUpdate(action.inputs.discountCodes as string[])\n case CART_FORM_ACTIONS.GiftCardCodesAdd:\n return handler.giftCardCodesAdd(action.inputs.giftCardCodes as string[])\n case CART_FORM_ACTIONS.GiftCardCodesRemove:\n return handler.giftCardCodesRemove(action.inputs.giftCardCodes as string[])\n case CART_FORM_ACTIONS.BuyerIdentityUpdate:\n return handler.buyerIdentityUpdate(action.inputs.buyerIdentity as CartBuyerIdentityInput)\n case CART_FORM_ACTIONS.NoteUpdate:\n return handler.noteUpdate((action.inputs.note as string | null | undefined) ?? null)\n case CART_FORM_ACTIONS.AttributesUpdate:\n return handler.attributesUpdate(action.inputs.attributes as CartAttribute[])\n case CART_FORM_ACTIONS.MetafieldsSet:\n return handler.metafieldsSet(action.inputs.metafields as CartMetafield[])\n case CART_FORM_ACTIONS.MetafieldsDelete:\n return handler.metafieldsDelete(action.inputs.metafields as CartMetafieldIdentifier[])\n case CART_FORM_ACTIONS.DeliveryAddressesReplace:\n return handler.deliveryAddressesReplace(action.inputs.addresses as CartDeliveryAddress[])\n case CART_FORM_ACTIONS.SelectedDeliveryOptionsUpdate:\n return handler.selectedDeliveryOptionsUpdate(\n action.inputs.selectedDeliveryOptions as CartSelectedDeliveryOption[],\n )\n }\n },\n }\n\n return handler\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { then?: unknown }).then === 'function'\n )\n}\n\nfunction appendSetCartIdHeaders(\n headers: Headers,\n value: string | Headers | null | undefined | void,\n): void {\n if (typeof value === 'string' && value.length > 0) {\n headers.append('set-cookie', value)\n return\n }\n if (value instanceof Headers) {\n value.forEach((headerValue, headerName) => {\n headers.append(headerName, headerValue)\n })\n }\n}\n","/**\n * Typed customer-account shapes for the `@kotao/storefront` SDK surface (#91). The names/signatures\n * mirror Hydrogen's Customer Account API so a Hydrogen→Kotao theme migration stays mechanical\n * (ADR-0003). Kotao-native storefronts use the same-origin `/api/storefront` proxy, while migrated\n * Hydrogen server contexts can keep Shopify Customer Account OAuth/session semantics.\n */\n\nexport interface CustomerAccount {\n readonly id: string\n readonly email: string\n readonly firstName: string | null\n readonly lastName: string | null\n readonly displayName: string | null\n}\n\nexport interface Money {\n readonly amount: string\n readonly currencyCode: string\n}\n\nexport interface Order {\n readonly id: string\n readonly number: string\n readonly processedAt: string\n readonly financialStatus: string\n readonly fulfillmentStatus: string\n readonly totalPrice: Money\n}\n\n/** Order-history page info. Named distinctly from the SDK's relay-style `PageInfo` (pagination) to\n * avoid a barrel name collision. */\nexport interface OrderPageInfo {\n readonly hasNextPage: boolean\n readonly endCursor: string | null\n}\n\nexport interface OrderConnection {\n readonly nodes: readonly Order[]\n readonly pageInfo: OrderPageInfo\n}\n\nexport interface RequestLoginCodeInput {\n readonly email: string\n}\n\nexport interface RequestLoginCodeResult {\n readonly status: 'sent' | 'rate_limited' | 'error'\n /** Raw proxy response carrying CSRF rotation cookies/headers to the browser action. */\n readonly response: Response\n}\n\nexport interface VerifyLoginCodeInput {\n readonly email: string\n readonly code: string\n /** Same-origin path to redirect to after successful verification (optional). */\n readonly returnTo?: string\n}\n\nexport interface CustomerAccountGraphQLError {\n readonly message: string\n readonly [key: string]: unknown\n}\n\nexport interface CustomerAccountGraphQLResult<T = unknown> {\n readonly data: T | null\n readonly errors?: readonly CustomerAccountGraphQLError[]\n}\n\nexport interface CustomerAccountGraphQLOptions {\n readonly variables?: Record<string, unknown>\n}\n\nexport interface OrdersOptions {\n readonly first?: number\n readonly after?: string\n}\n\n/** Maps the backend `AddressDTO` shape (kernel fields renamed to Shopify-compatible names). */\nexport interface Address {\n readonly id: string\n readonly firstName: string | null\n readonly lastName: string | null\n readonly company: string | null\n readonly address1: string | null\n readonly address2: string | null\n readonly city: string | null\n readonly province: string | null\n readonly provinceCode: string | null\n readonly country: string | null\n readonly countryCode: string | null\n readonly zip: string | null\n readonly phone: string | null\n readonly default: boolean\n}\n\n/** Input for creating or updating an address — same as `Address` minus the server-assigned `id`. */\nexport type AddressInput = Omit<Address, 'id'>\n\nexport interface AddressConnection {\n readonly nodes: readonly Address[]\n}\n\nexport type CustomerAccountErrorCode = 'unauthenticated' | 'unreachable' | 'api_error'\n\n/**\n * Typed failure for account/order reads — the SDK never lets a bare network throw or a non-200\n * escape to theme code (acceptance criterion). `unauthenticated` = no/invalid session (401);\n * `unreachable` = the proxy fetch itself failed; `api_error` = any other non-OK response.\n */\nexport class CustomerAccountError extends Error {\n readonly code: CustomerAccountErrorCode\n constructor(code: CustomerAccountErrorCode, message: string) {\n super(message)\n this.name = 'CustomerAccountError'\n this.code = code\n }\n}\n\nexport interface CustomerAccountClient {\n /**\n * Hydrogen-compatible Customer Account GraphQL read. Kotao sessions go through the same-origin\n * proxy; Hydrogen AppSession credentials can call Shopify's Customer Account API directly. When\n * logged out it returns a GraphQL-shaped error instead of throwing so Hydrogen loaders can run their\n * normal logout/login branch.\n */\n query<T = unknown>(\n query: string,\n options?: CustomerAccountGraphQLOptions,\n ): Promise<CustomerAccountGraphQLResult<T>>\n /** Hydrogen-compatible Customer Account GraphQL mutation through the active customer-account mode. */\n mutate<T = unknown>(\n mutation: string,\n options?: CustomerAccountGraphQLOptions,\n ): Promise<CustomerAccountGraphQLResult<T>>\n /** Hydrogen-compatible login redirect entrypoint. */\n login(): Response | Promise<Response>\n /** Hydrogen-compatible authorize callback entrypoint. */\n authorize(): Response | Promise<Response>\n /** Throws the login redirect when unauthenticated, matching Hydrogen loader usage. */\n handleAuthStatus(): Promise<void>\n /**\n * POST to the proxy `/account/send` endpoint to trigger an OTP email. Returns a typed status:\n * `sent` (200), `rate_limited` (429), or `error` (any other failure). Never throws.\n */\n requestLoginCode(input: RequestLoginCodeInput): Promise<RequestLoginCodeResult>\n /**\n * POST to the proxy `/account/verify` endpoint with the OTP code. Returns the raw proxy `Response`\n * so its `Set-Cookie` and 302 redirect headers propagate to the theme's RR8 action unchanged —\n * do NOT swallow or re-create this Response.\n */\n verifyLoginCode(input: VerifyLoginCodeInput): Promise<Response>\n /** 302 logout redirect; also clears the active customer-account session cookie. */\n logout(): Response | Promise<Response>\n /** Boolean session check — never throws (false on absent/invalid/unreachable). */\n isLoggedIn(): Promise<boolean>\n /**\n * The active customer credential, or null. In Kotao proxy mode this is the opaque per-shop session\n * token from the cookie; in Hydrogen AppSession mode this is Shopify's Customer Account access\n * token and may refresh the session before resolving. Treat it as a credential: do not log it or\n * send it to unrelated origins.\n */\n getAccessToken(): Promise<string | null>\n /** The current customer profile; throws {@link CustomerAccountError} on failure. */\n account(): Promise<CustomerAccount>\n /** Cursor-paginated order history; throws {@link CustomerAccountError} on failure. */\n orders(options?: OrdersOptions): Promise<OrderConnection>\n /** List all saved addresses for the authenticated customer; throws {@link CustomerAccountError} on failure. */\n addresses(): Promise<AddressConnection>\n /** Create a new address; returns the raw proxy Response. */\n createAddress(input: AddressInput): Promise<Response>\n /** Update an existing address by id; returns the raw proxy Response. */\n updateAddress(id: string, input: AddressInput): Promise<Response>\n /** Delete an address by id; returns the raw proxy Response. */\n deleteAddress(id: string): Promise<Response>\n}\n","import {\n clearHostedCustomerSessionCookie,\n clearCustomerSessionCookie,\n CUSTOMER_SESSION_COOKIE,\n HOSTED_CUSTOMER_CSRF_COOKIE,\n HOSTED_CUSTOMER_CSRF_HEADER,\n HOSTED_CUSTOMER_SESSION_COOKIE,\n readCustomerSessionToken,\n readHostedCustomerCsrfToken,\n readHostedCustomerSessionToken,\n shopHostname,\n} from './session'\nimport {\n type AddressConnection,\n type AddressInput,\n type CustomerAccount,\n type CustomerAccountGraphQLOptions,\n type CustomerAccountGraphQLResult,\n CustomerAccountError,\n type CustomerAccountClient,\n type OrderConnection,\n type OrdersOptions,\n type RequestLoginCodeInput,\n type RequestLoginCodeResult,\n type VerifyLoginCodeInput,\n} from './types'\n\nconst DEFAULT_PROXY_BASE = '/api/storefront'\nconst DEFAULT_CUSTOMER_API_VERSION = '2026-04'\nconst CUSTOMER_ACCOUNT_SCOPE = 'openid email customer-account-api:full'\nconst HYDROGEN_CUSTOMER_ACCOUNT_SESSION_KEY = 'customerAccount'\n// A single leading slash whose next char is neither `/` nor `\\` — rejects protocol-relative (`//evil`)\n// AND backslash forms (`/\\evil`, which browsers normalize to `//evil`). Keeps every call + post-login\n// `returnTo` redirect same-origin, so a crafted base/returnTo can't become an open redirect or leak the\n// session cookie cross-origin.\nconst SAME_ORIGIN_PATH = /^\\/(?![/\\\\])/\n\nexport interface CustomerAccountClientOptions {\n /** The inbound theme request — supplies the session cookie to forward + the shop host. */\n readonly request: Request\n /** Injectable for tests; defaults to the global `fetch`. */\n readonly fetch?: typeof fetch | undefined\n /** Same-origin proxy base (#85); must be an absolute same-origin path. Defaults to `/api/storefront`. */\n readonly proxyBase?: string | undefined\n /** Hydrogen server compatibility: accepted for original server.ts call sites; Kotao proxies do not need it. */\n readonly waitUntil?: ((promise: Promise<unknown>) => void) | undefined\n /** Hydrogen server compatibility: accepted for original server.ts call sites; Kotao proxies do not need it. */\n readonly session?: unknown\n /** Hydrogen server compatibility: accepted for original server.ts call sites; Kotao proxies do not need it. */\n readonly customerAccountId?: string | undefined\n /** Hydrogen server compatibility: accepted for original server.ts call sites; Kotao proxies do not need it. */\n readonly shopId?: string | undefined\n /** Stage/configuration-pinned HTTPS shop origin used for account mutations. */\n readonly shopOrigin?: string | undefined\n /** Bounded rollout fallback; opaque hosted sessions always win. Defaults true during migration. */\n readonly allowLegacySessionForwarding?: boolean | undefined\n}\n\ninterface HydrogenSessionLike {\n get(key: string): unknown\n set(key: string, value: unknown): void\n unset?(key: string): void\n commit?(): string | Promise<string>\n destroy?(): string | Promise<string>\n}\n\ninterface HydrogenCustomerAccountSession {\n readonly accessToken?: string\n readonly expiresAt?: string\n readonly refreshToken?: string\n readonly idToken?: string\n readonly codeVerifier?: string\n readonly state?: string\n readonly nonce?: string\n readonly redirectPath?: string\n}\n\ninterface CustomerAccountTokenResponse {\n readonly access_token: string\n readonly expires_in: number\n readonly id_token?: string\n readonly refresh_token?: string\n}\n\n/**\n * Theme-facing customer-account client (#91), mirroring Hydrogen's `createCustomerAccount`. Kotao\n * sessions go through the same-origin `/api/storefront` proxy, while original Hydrogen contexts can\n * keep using Shopify Customer Account OAuth/session data when `shopId`, `customerAccountId`, and a\n * Hydrogen AppSession are supplied. Untrusted-mode safe: no `request.cf`, no `caches.default`.\n */\nexport function createCustomerAccountClient(\n opts: CustomerAccountClientOptions,\n): CustomerAccountClient {\n const proxyBase = opts.proxyBase ?? DEFAULT_PROXY_BASE\n if (!SAME_ORIGIN_PATH.test(proxyBase) || proxyBase.includes('..')) {\n throw new Error(`customer-account proxyBase must be a same-origin path, got '${proxyBase}'`)\n }\n const doFetch = opts.fetch ?? fetch\n const cookieHeader = opts.request.headers.get('cookie')\n const hostedToken = readHostedCustomerSessionToken(cookieHeader)\n const legacyToken =\n hostedToken === null && (opts.allowLegacySessionForwarding ?? true)\n ? readCustomerSessionToken(cookieHeader)\n : null\n const token = hostedToken ?? legacyToken\n const sessionCookie =\n hostedToken !== null\n ? `${HOSTED_CUSTOMER_SESSION_COOKIE}=${encodeURIComponent(hostedToken)}`\n : legacyToken !== null\n ? `${CUSTOMER_SESSION_COOKIE}=${encodeURIComponent(legacyToken)}`\n : null\n const configuredShopOrigin = configuredHttpsOrigin(opts.shopOrigin)\n const hydrogenCustomerAccountId = opts.customerAccountId?.trim()\n const hydrogenShopId = opts.shopId?.trim()\n const hasHydrogenCustomerAccount =\n hydrogenCustomerAccountId !== undefined &&\n hydrogenCustomerAccountId.length > 0 &&\n hydrogenShopId !== undefined &&\n hydrogenShopId.length > 0\n const hydrogenSession = isHydrogenSessionLike(opts.session) ? opts.session : undefined\n\n // GET a proxy sub-route, forwarding ONLY the session cookie (data minimization — the proxy needs no\n // other theme cookies). Network failures become a typed `unreachable` error, not a bare throw.\n const proxyGet = async (path: string): Promise<Response> => {\n try {\n return await doFetch(`${proxyBase}${path}`, {\n redirect: 'manual',\n headers: sessionCookie !== null ? { cookie: sessionCookie } : {},\n })\n } catch (cause) {\n throw new CustomerAccountError(\n 'unreachable',\n `customer-account proxy unreachable: ${cause instanceof Error ? cause.message : String(cause)}`,\n )\n }\n }\n\n // Map a proxy response to data or a typed error: 401 → unauthenticated, any other non-OK → api_error.\n const readJson = async <T>(res: Response, what: string): Promise<T> => {\n if (res.status === 401) {\n throw new CustomerAccountError('unauthenticated', `${what}: not logged in`)\n }\n if (!res.ok) {\n throw new CustomerAccountError('api_error', `${what} failed: HTTP ${res.status}`)\n }\n try {\n return (await res.json()) as T\n } catch {\n throw new CustomerAccountError('api_error', `${what}: malformed JSON in proxy response`)\n }\n }\n\n // POST helper for OTP endpoints — returns the raw Response (caller decides how to handle it).\n const proxyPost = async (path: string, body: Record<string, string>): Promise<Response> => {\n const csrf = await csrfHeaders()\n if (csrf === null) return new Response(null, { status: 503 })\n return doFetch(`${proxyBase}${path}`, {\n method: 'POST',\n redirect: 'manual',\n headers: { 'content-type': 'application/json', ...csrf.headers },\n body: JSON.stringify(body),\n })\n }\n\n // Authenticated write helper — forwards the session cookie like proxyGet does. Used for address\n // CRUD which requires an active customer session (unlike the pre-auth OTP endpoints).\n const proxyWrite = async (\n path: string,\n method: 'POST' | 'PUT' | 'DELETE',\n body?: unknown,\n ): Promise<Response> => {\n const csrf = await csrfHeaders()\n if (csrf === null) return new Response(null, { status: 503 })\n const headers: Record<string, string> = { 'content-type': 'application/json', ...csrf.headers }\n return doFetch(`${proxyBase}${path}`, {\n method,\n redirect: 'manual',\n headers,\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n })\n }\n\n const csrfHeaders = async (): Promise<{ headers: Record<string, string> } | null> => {\n if (configuredShopOrigin === null) return null\n let csrfToken = readHostedCustomerCsrfToken(cookieHeader)\n if (csrfToken === null) {\n const bootstrap = await doFetch(`${proxyBase}/account/csrf`, {\n redirect: 'manual',\n headers: sessionCookie !== null ? { cookie: sessionCookie } : {},\n })\n csrfToken = csrfTokenFromSetCookie(bootstrap.headers)\n if (csrfToken === null) return null\n }\n return {\n headers: {\n Origin: configuredShopOrigin,\n [HOSTED_CUSTOMER_CSRF_HEADER]: csrfToken,\n cookie: [sessionCookie, `${HOSTED_CUSTOMER_CSRF_COOKIE}=${csrfToken}`]\n .filter((value): value is string => value !== null)\n .join('; '),\n },\n }\n }\n\n const returnTo = (): string => {\n const url = new URL(opts.request.url)\n return `${url.pathname}${url.search}`\n }\n\n const requestHttpsOrigin = (): string => {\n const url = new URL(opts.request.url)\n return url.protocol === 'http:' ? url.origin.replace(/^http:/, 'https:') : url.origin\n }\n\n const redirectResponse = (location: string): Response =>\n new Response(null, { status: 302, headers: { location } })\n\n const commitHydrogenSession = async (headers: Headers): Promise<void> => {\n const cookie = await hydrogenSession?.commit?.()\n if (cookie !== undefined && cookie.length > 0) headers.append('set-cookie', cookie)\n }\n\n const redirectWithHydrogenSession = async (location: string): Promise<Response> => {\n const headers = new Headers({ location })\n await commitHydrogenSession(headers)\n return new Response(null, { status: 302, headers })\n }\n\n const readHydrogenCustomerSession = (): HydrogenCustomerAccountSession | null => {\n const value = hydrogenSession?.get(HYDROGEN_CUSTOMER_ACCOUNT_SESSION_KEY)\n if (value === null || value === undefined || typeof value !== 'object') return null\n return value as HydrogenCustomerAccountSession\n }\n\n const setHydrogenCustomerSession = (value: HydrogenCustomerAccountSession): void => {\n hydrogenSession?.set(HYDROGEN_CUSTOMER_ACCOUNT_SESSION_KEY, value)\n }\n\n const clearHydrogenCustomerSession = (): void => {\n if (hydrogenSession?.unset !== undefined) {\n hydrogenSession.unset(HYDROGEN_CUSTOMER_ACCOUNT_SESSION_KEY)\n return\n }\n hydrogenSession?.set(HYDROGEN_CUSTOMER_ACCOUNT_SESSION_KEY, undefined)\n }\n\n const hydrogenTokenEndpoint = (): string =>\n `https://shopify.com/authentication/${hydrogenShopId}/oauth/token`\n\n const setHydrogenCustomerTokens = (\n tokenResponse: CustomerAccountTokenResponse,\n previous?: HydrogenCustomerAccountSession | null,\n ): void => {\n const refreshToken = tokenResponse.refresh_token ?? previous?.refreshToken\n const idToken = tokenResponse.id_token ?? previous?.idToken\n const nextSession: HydrogenCustomerAccountSession = {\n accessToken: tokenResponse.access_token,\n expiresAt: String(Date.now() + Math.max(tokenResponse.expires_in - 120, 0) * 1000),\n ...(refreshToken !== undefined ? { refreshToken } : {}),\n ...(idToken !== undefined ? { idToken } : {}),\n }\n setHydrogenCustomerSession(nextSession)\n }\n\n const refreshHydrogenAccessToken = async (\n sessionValue: HydrogenCustomerAccountSession,\n ): Promise<string | null> => {\n const refreshToken = sessionValue.refreshToken\n if (refreshToken === undefined || refreshToken.length === 0) return null\n const body = new URLSearchParams()\n body.set('grant_type', 'refresh_token')\n body.set('client_id', hydrogenCustomerAccountId ?? '')\n body.set('refresh_token', refreshToken)\n\n try {\n const res = await doFetch(hydrogenTokenEndpoint(), {\n method: 'POST',\n headers: {\n 'content-type': 'application/x-www-form-urlencoded',\n Origin: requestHttpsOrigin(),\n },\n body,\n })\n if (!res.ok) {\n clearHydrogenCustomerSession()\n return null\n }\n const tokenResponse = (await res.json()) as CustomerAccountTokenResponse\n if (\n typeof tokenResponse.access_token !== 'string' ||\n tokenResponse.access_token.length === 0 ||\n typeof tokenResponse.expires_in !== 'number' ||\n !Number.isFinite(tokenResponse.expires_in)\n ) {\n clearHydrogenCustomerSession()\n return null\n }\n setHydrogenCustomerTokens(tokenResponse, sessionValue)\n return tokenResponse.access_token\n } catch {\n clearHydrogenCustomerSession()\n return null\n }\n }\n\n const hydrogenAccessToken = async (): Promise<string | null> => {\n if (!hasHydrogenCustomerAccount) return null\n const sessionValue = readHydrogenCustomerSession()\n if (sessionValue === null) return null\n const accessToken = sessionValue.accessToken\n const expiresAt = Number(sessionValue.expiresAt)\n if (accessToken === undefined || accessToken.length === 0) return null\n if (!Number.isFinite(expiresAt)) return null\n if (expiresAt <= Date.now()) return refreshHydrogenAccessToken(sessionValue)\n return accessToken\n }\n\n const loginRedirect = async (): Promise<Response> => {\n if (hasHydrogenCustomerAccount) {\n const state = randomOAuthToken()\n const nonce = randomOAuthToken()\n const codeVerifier = randomOAuthToken()\n const codeChallenge = await sha256Base64Url(codeVerifier)\n setHydrogenCustomerSession({\n ...(readHydrogenCustomerSession() ?? {}),\n codeVerifier,\n state,\n nonce,\n redirectPath: returnTo(),\n })\n const loginUrl = new URL(\n `https://shopify.com/authentication/${hydrogenShopId}/oauth/authorize`,\n )\n loginUrl.searchParams.set('client_id', hydrogenCustomerAccountId)\n loginUrl.searchParams.set('scope', CUSTOMER_ACCOUNT_SCOPE)\n loginUrl.searchParams.set('response_type', 'code')\n loginUrl.searchParams.set('redirect_uri', `${requestHttpsOrigin()}/account/authorize`)\n loginUrl.searchParams.set('state', state)\n loginUrl.searchParams.set('nonce', nonce)\n loginUrl.searchParams.set('code_challenge', codeChallenge)\n loginUrl.searchParams.set('code_challenge_method', 'S256')\n return redirectWithHydrogenSession(loginUrl.toString())\n }\n const params = new URLSearchParams({ returnTo: returnTo() })\n return redirectResponse(`${proxyBase}/account/login?${params.toString()}`)\n }\n\n const badRequest = (message: string): Response =>\n new Response(message, {\n status: 400,\n headers: { 'content-type': 'text/plain; charset=utf-8' },\n })\n\n const graphQLError = <T>(message: string): CustomerAccountGraphQLResult<T> => ({\n data: null,\n errors: [{ message }],\n })\n\n const proxyGraphQL = async <T>(\n document: string,\n options?: CustomerAccountGraphQLOptions,\n ): Promise<CustomerAccountGraphQLResult<T>> => {\n const directAccessToken = await hydrogenAccessToken()\n if (directAccessToken !== null) {\n try {\n const res = await doFetch(\n `https://shopify.com/${hydrogenShopId}/account/customer/api/${DEFAULT_CUSTOMER_API_VERSION}/graphql`,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n Authorization: directAccessToken,\n Origin: requestHttpsOrigin(),\n },\n body: JSON.stringify({ query: document, variables: options?.variables ?? {} }),\n },\n )\n if (res.status === 401) {\n clearHydrogenCustomerSession()\n return graphQLError<T>('not logged in')\n }\n if (!res.ok) return graphQLError<T>(`customer-account query failed: HTTP ${res.status}`)\n const body = (await res.json()) as Partial<CustomerAccountGraphQLResult<T>>\n return {\n data: body.data ?? null,\n ...(body.errors !== undefined ? { errors: body.errors } : {}),\n }\n } catch (cause) {\n return graphQLError<T>(\n `customer-account query failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n )\n }\n }\n if (token === null) return graphQLError<T>('not logged in')\n try {\n const res = await proxyWrite('/account/graphql', 'POST', {\n query: document,\n variables: options?.variables ?? {},\n })\n if (res.status === 401) return graphQLError<T>('not logged in')\n if (!res.ok) return graphQLError<T>(`customer-account query failed: HTTP ${res.status}`)\n const body = (await res.json()) as Partial<CustomerAccountGraphQLResult<T>>\n return {\n data: body.data ?? null,\n ...(body.errors !== undefined ? { errors: body.errors } : {}),\n }\n } catch (cause) {\n return graphQLError<T>(\n `customer-account query failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n )\n }\n }\n\n return {\n query: proxyGraphQL,\n\n mutate: proxyGraphQL,\n\n login: loginRedirect,\n\n async authorize(): Promise<Response> {\n if (!hasHydrogenCustomerAccount) return redirectResponse('/account')\n const url = new URL(opts.request.url)\n const code = url.searchParams.get('code')\n const state = url.searchParams.get('state')\n const sessionValue = readHydrogenCustomerSession()\n if (code === null || state === null) {\n clearHydrogenCustomerSession()\n return badRequest('No code or state parameter found in the redirect URL.')\n }\n if (sessionValue?.state !== state) {\n clearHydrogenCustomerSession()\n return badRequest('The session state does not match the state parameter.')\n }\n if (sessionValue.codeVerifier === undefined || sessionValue.codeVerifier.length === 0) {\n clearHydrogenCustomerSession()\n return badRequest('No code verifier found in the session.')\n }\n\n const body = new URLSearchParams()\n body.set('grant_type', 'authorization_code')\n body.set('client_id', hydrogenCustomerAccountId)\n body.set('redirect_uri', `${requestHttpsOrigin()}/account/authorize`)\n body.set('code', code)\n body.set('code_verifier', sessionValue.codeVerifier)\n\n const res = await doFetch(\n `https://shopify.com/authentication/${hydrogenShopId}/oauth/token`,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/x-www-form-urlencoded',\n Origin: requestHttpsOrigin(),\n },\n body,\n },\n )\n if (!res.ok) {\n return new Response(await res.text(), {\n status: res.status,\n headers: { 'content-type': 'text/html; charset=utf-8' },\n })\n }\n const tokenResponse = (await res.json()) as CustomerAccountTokenResponse\n const responseNonce = idTokenNonce(tokenResponse.id_token ?? '')\n if (sessionValue.nonce !== responseNonce) {\n clearHydrogenCustomerSession()\n return badRequest(\n `Returned nonce does not match: ${sessionValue.nonce} !== ${responseNonce}`,\n )\n }\n\n setHydrogenCustomerTokens(tokenResponse)\n return redirectWithHydrogenSession(sessionValue.redirectPath ?? '/account')\n },\n\n async handleAuthStatus(): Promise<void> {\n if (await this.isLoggedIn()) return\n throw await loginRedirect()\n },\n\n async requestLoginCode(input: RequestLoginCodeInput): Promise<RequestLoginCodeResult> {\n try {\n const res = await proxyPost('/account/send', { email: input.email })\n if (res.status === 200) return { status: 'sent', response: res }\n if (res.status === 429) return { status: 'rate_limited', response: res }\n return { status: 'error', response: res }\n } catch {\n return { status: 'error', response: new Response(null, { status: 503 }) }\n }\n },\n\n async verifyLoginCode(input: VerifyLoginCodeInput): Promise<Response> {\n const body: Record<string, string> = { email: input.email, code: input.code }\n if (input.returnTo !== undefined) body.returnTo = input.returnTo\n // Return the raw proxy Response so its Set-Cookie + 302 propagate to the theme action unchanged.\n try {\n return await proxyPost('/account/verify', body)\n } catch {\n // Network failure: return a 503 error Response instead of throwing (asymmetric with requestLoginCode which never throws).\n return new Response(null, { status: 503 })\n }\n },\n\n async logout(): Promise<Response> {\n const headers = new Headers()\n if (hasHydrogenCustomerAccount) {\n const idToken = readHydrogenCustomerSession()?.idToken\n const postLogoutRedirectUri = requestHttpsOrigin()\n if (idToken !== undefined && idToken.length > 0) {\n const logoutUrl = new URL(`https://shopify.com/authentication/${hydrogenShopId}/logout`)\n logoutUrl.searchParams.set('id_token_hint', idToken)\n logoutUrl.searchParams.set('post_logout_redirect_uri', postLogoutRedirectUri)\n headers.set('location', logoutUrl.toString())\n } else {\n headers.set('location', '/')\n }\n clearHydrogenCustomerSession()\n const destroyedCookie = await hydrogenSession?.destroy?.()\n if (destroyedCookie !== undefined && destroyedCookie.length > 0) {\n headers.append('set-cookie', destroyedCookie)\n } else {\n await commitHydrogenSession(headers)\n }\n } else {\n try {\n return await proxyWrite('/account/logout', 'POST')\n } catch {\n headers.set('location', '/')\n }\n }\n headers.append(\n 'set-cookie',\n clearCustomerSessionCookie({ hostname: shopHostname(opts.request) }),\n )\n headers.append('set-cookie', clearHostedCustomerSessionCookie())\n return new Response(null, { status: 302, headers })\n },\n\n async getAccessToken(): Promise<string | null> {\n const directAccessToken = await hydrogenAccessToken()\n if (directAccessToken !== null) return directAccessToken\n return hasHydrogenCustomerAccount ? token : null\n },\n\n async isLoggedIn(): Promise<boolean> {\n if ((await hydrogenAccessToken()) !== null) return true\n if (token === null) return false // no session cookie → not logged in, no network call\n try {\n const res = await proxyGet('/account')\n return res.ok\n } catch {\n return false // session check never throws — degrade to \"logged out\"\n }\n },\n\n async account(): Promise<CustomerAccount> {\n if (token === null) {\n throw new CustomerAccountError('unauthenticated', 'account read: not logged in')\n }\n return readJson<CustomerAccount>(await proxyGet('/account'), 'account read')\n },\n\n async orders(options?: OrdersOptions): Promise<OrderConnection> {\n const params = new URLSearchParams()\n if (options?.first !== undefined) params.set('first', String(options.first))\n if (options?.after !== undefined) params.set('after', options.after)\n const qs = params.toString()\n return readJson<OrderConnection>(\n await proxyGet(`/account/orders${qs ? `?${qs}` : ''}`),\n 'orders read',\n )\n },\n\n async addresses(): Promise<AddressConnection> {\n return readJson<AddressConnection>(await proxyGet('/account/addresses'), 'addresses read')\n },\n\n createAddress(input: AddressInput): Promise<Response> {\n return proxyWrite('/account/addresses', 'POST', input)\n },\n\n updateAddress(id: string, input: AddressInput): Promise<Response> {\n return proxyWrite(`/account/addresses/${encodeURIComponent(id)}`, 'PUT', input)\n },\n\n deleteAddress(id: string): Promise<Response> {\n return proxyWrite(`/account/addresses/${encodeURIComponent(id)}`, 'DELETE')\n },\n }\n}\n\nfunction randomOAuthToken(): string {\n const bytes = new Uint8Array(32)\n crypto.getRandomValues(bytes)\n let raw = ''\n for (const byte of bytes) raw += String.fromCharCode(byte)\n return base64UrlEncode(raw)\n}\n\nfunction configuredHttpsOrigin(value: string | undefined): string | null {\n if (!value) return null\n try {\n const candidate = value.includes('://') ? value : `https://${value}`\n const url = new URL(candidate)\n if (\n url.protocol !== 'https:' ||\n url.username ||\n url.password ||\n url.port ||\n url.pathname !== '/'\n )\n return null\n return url.origin\n } catch {\n return null\n }\n}\n\nfunction csrfTokenFromSetCookie(headers: Headers): string | null {\n const values =\n 'getSetCookie' in headers && typeof headers.getSetCookie === 'function'\n ? headers.getSetCookie()\n : [headers.get('set-cookie') ?? '']\n for (const value of values) {\n const match = value.match(/(?:^|,\\s*)__Host-kotao_customer_csrf=([A-Za-z0-9_-]{43})(?:;|$)/)\n if (match?.[1]) return match[1]\n }\n return null\n}\n\nfunction isHydrogenSessionLike(value: unknown): value is HydrogenSessionLike {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'get' in value &&\n 'set' in value &&\n typeof value.get === 'function' &&\n typeof value.set === 'function'\n )\n}\n\nasync function sha256Base64Url(value: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value))\n let raw = ''\n for (const byte of new Uint8Array(digest)) raw += String.fromCharCode(byte)\n return base64UrlEncode(raw)\n}\n\nfunction base64UrlEncode(raw: string): string {\n return btoa(raw).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '')\n}\n\nfunction idTokenNonce(idToken: string): string | null {\n const [, payload] = idToken.split('.')\n if (payload === undefined || payload.length === 0) return null\n try {\n const normalized = payload.replaceAll('-', '+').replaceAll('_', '/')\n const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=')\n const decoded = JSON.parse(atob(padded)) as { nonce?: unknown }\n return typeof decoded.nonce === 'string' ? decoded.nonce : null\n } catch {\n return null\n }\n}\n","import { decodeBase64UrlUtf8, encodeUtf8Base64Url, fromBase64Url, toBase64Url } from './base64url'\n\nexport const GEO_HEADER = 'x-kotao-geo'\nexport const GEO_SIGNATURE_HEADER = 'x-kotao-geo-signature'\n\n/**\n * Trusted geo surfaced to themes as `context.geo`. In untrusted WFP mode `request.cf` is\n * stripped, so the Gateway Worker (#81) injects this as signed `x-kotao-*` headers and the\n * SDK verifies them here. Both sides share this module so the contract can never drift.\n */\nexport interface Geo {\n country: string | null\n city: string | null\n colo: string | null\n botScore: number | null\n clientIp: string | null\n}\n\nconst importKey = (key: string): Promise<CryptoKey> =>\n crypto.subtle.importKey(\n 'raw',\n new TextEncoder().encode(key),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign', 'verify'],\n )\n\nconst toArrayBufferView = (bytes: Uint8Array): Uint8Array<ArrayBuffer> => {\n const view = new Uint8Array(bytes.byteLength)\n view.set(bytes)\n return view\n}\n\n/** Gateway side (#81): produce the two header values for a geo payload. */\nexport async function signGeo(\n geo: Geo,\n key: string,\n): Promise<{ payload: string; signature: string }> {\n const payload = encodeUtf8Base64Url(JSON.stringify(geo))\n const cryptoKey = await importKey(key)\n const sig = await crypto.subtle.sign('HMAC', cryptoKey, new TextEncoder().encode(payload))\n return { payload, signature: toBase64Url(new Uint8Array(sig)) }\n}\n\nconst isGeo = (v: unknown): v is Geo => {\n if (typeof v !== 'object' || v === null) return false\n const o = v as Record<string, unknown>\n const strOrNull = (x: unknown): boolean => x === null || typeof x === 'string'\n const numOrNull = (x: unknown): boolean => x === null || typeof x === 'number'\n return (\n strOrNull(o['country']) &&\n strOrNull(o['city']) &&\n strOrNull(o['colo']) &&\n numOrNull(o['botScore']) &&\n strOrNull(o['clientIp'])\n )\n}\n\n/** SDK side: reconstruct typed geo from signed headers. Returns null on any failure — never trusts unsigned data. */\nexport async function verifyGeo(headers: Headers, key: string): Promise<Geo | null> {\n const payload = headers.get(GEO_HEADER)\n const signature = headers.get(GEO_SIGNATURE_HEADER)\n if (!payload || !signature) return null\n try {\n const cryptoKey = await importKey(key)\n const ok = await crypto.subtle.verify(\n 'HMAC',\n cryptoKey,\n toArrayBufferView(fromBase64Url(signature)),\n new TextEncoder().encode(payload),\n )\n if (!ok) return null\n const parsed: unknown = JSON.parse(decodeBase64UrlUtf8(payload))\n return isGeo(parsed) ? parsed : null\n } catch {\n return null\n }\n}\n","export const LOCALIZATION_COOKIE = 'kotao_localization'\nconst MAX_AGE = 60 * 60 * 24 * 365\n\nexport function readLocalizationCookie(cookieHeader: string | null | undefined): {\n country: string | null\n locale: string | null\n} {\n if (cookieHeader == null || cookieHeader === '') return { country: null, locale: null }\n const match = cookieHeader\n .split(';')\n .map((p) => p.trim())\n .find((p) => p.startsWith(`${LOCALIZATION_COOKIE}=`))\n if (match === undefined) return { country: null, locale: null }\n const [country = '', locale = ''] = decodeURIComponent(\n match.slice(LOCALIZATION_COOKIE.length + 1),\n ).split('|')\n return { country: country || null, locale: locale || null }\n}\n\nexport function buildLocalizationCookie(sel: {\n country?: string | null\n locale?: string | null\n}): string {\n const value = `${sel.country ?? ''}|${sel.locale ?? ''}`\n return `${LOCALIZATION_COOKIE}=${encodeURIComponent(value)}; Path=/; Max-Age=${MAX_AGE}; SameSite=Lax; Secure; HttpOnly`\n}\n","const LOCALE_SEGMENT_RE = /^[a-z]{2}(?:-[a-zA-Z]{2,4})?$/\nexport const ROUTING_LOCALE_HEADER = 'x-kotao-route-locale'\nexport const ROUTING_ORIGINAL_PATHNAME_HEADER = 'x-kotao-original-pathname'\n\nexport interface StrippedLocalePath {\n readonly locale: string | null\n readonly pathname: string\n}\n\nexport interface LocalizePathOptions {\n readonly primaryLocale?: string | null\n /** Trusted Market subfolder prefix that must survive locale switching. */\n readonly marketPathPrefix?: string | null\n}\n\ninterface AcceptLanguageCandidate {\n readonly locale: string\n readonly quality: number\n readonly order: number\n}\n\nfunction splitFirstPathSegment(pathname: string): { segment: string; rest: string } | null {\n if (!pathname.startsWith('/')) return null\n const withoutSlash = pathname.slice(1)\n const slash = withoutSlash.indexOf('/')\n if (slash === -1) return { segment: withoutSlash, rest: '' }\n return {\n segment: withoutSlash.slice(0, slash),\n rest: withoutSlash.slice(slash),\n }\n}\n\nexport function isLocalePathSegment(segment: string): boolean {\n return LOCALE_SEGMENT_RE.test(segment)\n}\n\nfunction normalizeLocaleTag(value: string | null | undefined): string | null {\n const [tag = ''] = (value ?? '').trim().replaceAll('_', '-').split(';', 1)\n if (tag === '' || tag === '*') return null\n const [language = '', regionOrScript] = tag.split('-')\n const base = language.toLowerCase()\n if (!/^[a-z]{2,3}$/.test(base)) return null\n if (regionOrScript === undefined || regionOrScript.length === 0) return base\n if (!/^[a-zA-Z0-9]{2,4}$/.test(regionOrScript)) return null\n const suffix =\n regionOrScript.length === 2 && /^[a-zA-Z]{2}$/.test(regionOrScript)\n ? regionOrScript.toUpperCase()\n : regionOrScript.length === 4 && /^[a-zA-Z]{4}$/.test(regionOrScript)\n ? `${regionOrScript[0]!.toUpperCase()}${regionOrScript.slice(1).toLowerCase()}`\n : regionOrScript\n return `${base}-${suffix}`\n}\n\nfunction qualityFromAcceptLanguagePart(part: string): number {\n const params = part.split(';').slice(1)\n const q = params\n .map((param) => param.trim())\n .find((param) => param.toLowerCase().startsWith('q='))\n if (q === undefined) return 1\n const value = Number(q.slice(2))\n return Number.isFinite(value) && value >= 0 && value <= 1 ? value : 0\n}\n\nfunction parseAcceptLanguage(header: string | null | undefined): AcceptLanguageCandidate[] {\n if (header === null || header === undefined || header.trim().length === 0) return []\n return header\n .split(',')\n .map((part, order): AcceptLanguageCandidate | null => {\n const locale = normalizeLocaleTag(part)\n const quality = qualityFromAcceptLanguagePart(part)\n if (locale === null || quality <= 0) return null\n return { locale, quality, order }\n })\n .filter((candidate): candidate is AcceptLanguageCandidate => candidate !== null)\n .sort((left, right) => right.quality - left.quality || left.order - right.order)\n}\n\nexport function localeFromAcceptLanguage(\n header: string | null | undefined,\n availableLocales?: readonly string[],\n): string | null {\n const candidates = parseAcceptLanguage(header)\n if (candidates.length === 0) return null\n\n const available = (availableLocales ?? [])\n .map((locale) => {\n const normalized = normalizeLocaleTag(locale)\n return normalized === null ? null : { locale, normalized }\n })\n .filter((entry): entry is { locale: string; normalized: string } => entry !== null)\n\n if (available.length === 0) return candidates[0]!.locale\n\n for (const candidate of candidates) {\n const exact = available.find(\n (entry) => entry.normalized.toLowerCase() === candidate.locale.toLowerCase(),\n )\n if (exact !== undefined) return exact.locale\n const language = candidate.locale.split('-')[0]!\n const languageMatch = available.find((entry) => entry.normalized.split('-')[0] === language)\n if (languageMatch !== undefined) return languageMatch.locale\n }\n return null\n}\n\nexport function localeFromPathname(pathname: string): string | null {\n const first = splitFirstPathSegment(pathname)\n if (first === null || first.segment.length === 0) return null\n return isLocalePathSegment(first.segment) ? first.segment : null\n}\n\nexport function originalPathnameFromRequest(request: Request): string {\n const fromHeader = request.headers.get(ROUTING_ORIGINAL_PATHNAME_HEADER)\n return fromHeader !== null && fromHeader.startsWith('/')\n ? fromHeader\n : new URL(request.url).pathname\n}\n\nexport function localeFromRequest(request: Request): string | null {\n const fromHeader = request.headers.get(ROUTING_LOCALE_HEADER)\n if (fromHeader !== null && isLocalePathSegment(fromHeader)) return fromHeader\n return localeFromPathname(originalPathnameFromRequest(request))\n}\n\nexport function stripLocalePrefixFromPathname(pathname: string): StrippedLocalePath {\n const locale = localeFromPathname(pathname)\n if (locale === null) return { locale: null, pathname }\n const first = splitFirstPathSegment(pathname)\n const rest = first?.rest ?? ''\n return { locale, pathname: rest.length > 0 ? rest : '/' }\n}\n\nexport function stripLocalePrefixFromRequest(request: Request): Request {\n const url = new URL(request.url)\n const stripped = stripLocalePrefixFromPathname(url.pathname)\n if (stripped.locale === null) return request\n const originalPathname = url.pathname\n url.pathname = stripped.pathname\n const next = new Request(url, request)\n next.headers.set(ROUTING_LOCALE_HEADER, stripped.locale)\n next.headers.set(ROUTING_ORIGINAL_PATHNAME_HEADER, originalPathname)\n return next\n}\n\nfunction normalizeLocale(locale: string | null | undefined): string | null {\n const trimmed = locale?.trim() ?? ''\n return trimmed.length > 0 && isLocalePathSegment(trimmed) ? trimmed : null\n}\n\nexport function localizePath(\n path: string,\n locale: string | null | undefined,\n options: LocalizePathOptions = {},\n): string {\n const targetLocale = normalizeLocale(locale)\n const primaryLocale = normalizeLocale(options.primaryLocale)\n const url = new URL(path.startsWith('/') ? path : '/', 'https://storefront.local')\n const marketPrefix =\n options.marketPathPrefix !== null &&\n options.marketPathPrefix !== undefined &&\n options.marketPathPrefix.startsWith('/')\n ? options.marketPathPrefix.replace(/\\/+$/u, '')\n : null\n const withoutMarket =\n marketPrefix !== null &&\n (url.pathname === marketPrefix || url.pathname.startsWith(`${marketPrefix}/`))\n ? url.pathname.slice(marketPrefix.length) || '/'\n : url.pathname\n const stripped = stripLocalePrefixFromPathname(withoutMarket).pathname\n const suffix = `${url.search}${url.hash}`\n const marketBase = marketPrefix ?? ''\n if (targetLocale === null || (primaryLocale !== null && targetLocale === primaryLocale)) {\n return `${marketBase}${stripped}${suffix}` || '/'\n }\n const localized = stripped === '/' ? `/${targetLocale}` : `/${targetLocale}${stripped}`\n return `${marketBase}${localized}${suffix}`\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport {\n CacheCustom,\n CacheLong,\n CacheNone,\n CacheShort,\n type CacheStrategy,\n createCache,\n type KotaoCache,\n StorefrontDefaultCache,\n type StorefrontCache,\n type StorefrontCacheInput,\n} from '../cache/cache'\nimport { normalizeStorefrontHeaders, type StorefrontHeadersInit } from '../http-types'\n\nexport interface StorefrontQueryOptions {\n variables?: Record<string, unknown>\n cache?: CacheStrategy\n storefrontApiVersion?: string\n /** Per-read upstream budget in milliseconds. Defaults to the client's 5,000 ms budget. */\n timeoutMs?: number\n}\n\nexport class StorefrontQueryTimeoutError extends Error {\n readonly operationName: string\n readonly timeoutMs: number\n\n constructor(operationName: string, timeoutMs: number) {\n super(`Storefront query ${operationName} timed out after ${String(timeoutMs)}ms`)\n this.name = 'StorefrontQueryTimeoutError'\n this.operationName = operationName\n this.timeoutMs = timeoutMs\n }\n}\n\nexport class StorefrontUpstreamError extends Error {\n readonly operationName: string\n readonly status: number | undefined\n override readonly cause: unknown\n\n constructor(\n operationName: string,\n message: string,\n options?: { status?: number; cause?: unknown },\n ) {\n super(message)\n this.name = 'StorefrontUpstreamError'\n this.operationName = operationName\n this.status = options?.status\n this.cause = options?.cause\n }\n}\n\ninterface StorefrontLooseConnection<T = any> {\n readonly nodes: T[]\n readonly pageInfo: any\n}\n\ninterface StorefrontLooseProductCollection {\n readonly description: string\n readonly handle: string\n readonly id: string\n readonly products: StorefrontLooseConnection & {\n readonly filters: readonly {\n readonly values: readonly {\n readonly id: string\n readonly input?: string | null\n readonly label: string\n }[]\n }[]\n }\n readonly title: string\n}\n\nexport interface StorefrontDefaultQueryData {\n [key: string]: any\n additional: StorefrontLooseConnection\n articles: StorefrontLooseConnection\n blog: { readonly articles: StorefrontLooseConnection; readonly seo?: any; readonly title: string }\n blogs: StorefrontLooseConnection\n collection: StorefrontLooseProductCollection\n collections: StorefrontLooseConnection<{ handle: string; title: string }>\n page: any\n policies: any[]\n product: any\n products: StorefrontLooseConnection\n recommended: any[]\n search: StorefrontLooseConnection\n shop: any\n}\n\nexport interface StorefrontQueryPromise<T> extends Promise<T> {\n catch<TResult = never>(\n onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null,\n ): Promise<T | TResult>\n}\n\nexport interface StorefrontClient {\n query<T = StorefrontDefaultQueryData>(\n query: string,\n options?: StorefrontQueryOptions,\n ): StorefrontQueryPromise<T>\n mutate<T = any>(mutation: string, options?: { variables?: Record<string, unknown> }): Promise<T>\n CacheNone: typeof CacheNone\n CacheShort: typeof CacheShort\n CacheLong: typeof CacheLong\n CacheCustom: typeof CacheCustom\n readonly cache: StorefrontCache\n readonly i18n: StorefrontI18n\n}\n\nexport type Storefront<I18n = unknown> = StorefrontClient & {\n readonly i18n: I18n\n}\n\nexport type StorefrontClientResult<I18n = StorefrontI18n> = Storefront<I18n> & {\n readonly storefront: Storefront<I18n>\n}\n\nexport interface StorefrontI18n {\n readonly language: string\n readonly country: string\n readonly currency: string\n readonly pathPrefix: string\n}\n\nexport type StorefrontAuthHeader =\n | 'x-kotao-storefront-token'\n | 'x-api-key'\n | 'x-shopify-storefront-access-token'\n\nexport interface StorefrontClientOptions {\n endpoint: string\n token: string\n tokenHeader?: StorefrontAuthHeader\n siteId?: string\n cache: KotaoCache\n fetch?: typeof fetch | undefined\n defaultStrategy?: CacheStrategy | undefined\n /** Default budget for each independent read query. Mutations are intentionally excluded. */\n queryTimeoutMs?: number | undefined\n /**\n * Pre-signed `x-kotao-shop` / `x-kotao-shop-signature` header pair, merged into every request.\n * In production the Gateway signs the shop-context; in local dev (no Gateway) the theme dev\n * server signs it (see createKotaoContext). Absent in production.\n */\n signedShopContextHeaders?: Readonly<Record<string, string>> | undefined\n /**\n * Additional server request headers to forward to direct Storefront API calls. Used by\n * Hydrogen-compatible server adapters for `storefrontHeaders`.\n */\n extraHeaders?: StorefrontHeadersInit | undefined\n /**\n * BCP 47 locale tag derived from the localization cookie (e.g. `'nl'`, `'es'`, `'de-de'`).\n * When set, `x-kotao-locale` is added to every request so storefront-api can overlay\n * translations. Also folds into the SWR cache key so locales never share a cached response.\n */\n locale?: string | undefined\n /**\n * ISO 3166-1 alpha-2 country selected by the localization cookie. When valid, sent as\n * `x-kotao-country` and folded into the SWR key so country-specific prices never share cache.\n */\n country?: string | undefined\n i18n?: Partial<StorefrontI18n> | undefined\n}\n\nexport interface HydrogenStorefrontClientOptions<I18n extends object = StorefrontI18n> {\n cache: StorefrontCacheInput\n waitUntil: (promise: Promise<unknown>) => void\n i18n?: I18n | undefined\n publicStorefrontToken: string\n privateStorefrontToken?: string | undefined\n storeDomain: string\n storefrontId?: string | undefined\n storefrontHeaders?: StorefrontHeadersInit | undefined\n storefrontApiVersion?: string | undefined\n fetch?: typeof fetch | undefined\n defaultStrategy?: CacheStrategy | undefined\n queryTimeoutMs?: number | undefined\n}\n\ninterface GraphQLResponse<T> {\n data?: T\n errors?: { message: string }[]\n}\n\nconst hashKey = (query: string, variables?: Record<string, unknown>): string =>\n `sf:${query.replace(/\\s+/g, ' ').trim()}:${variables ? JSON.stringify(variables) : ''}`\n\nconst COUNTRY_RE = /^[A-Z]{2}$/\nconst DEFAULT_HYDROGEN_STOREFRONT_API_VERSION = '2025-01'\nconst DEFAULT_QUERY_TIMEOUT_MS = 5_000\n\nfunction endpointForStorefrontApiVersion(endpoint: string, version: string | undefined): string {\n if (version === undefined || version.length === 0) return endpoint\n try {\n const url = new URL(endpoint)\n if (!/^\\/api\\/[^/]+\\/graphql\\.json$/u.test(url.pathname)) return endpoint\n url.pathname = url.pathname.replace(\n /^\\/api\\/[^/]+\\/graphql\\.json$/u,\n `/api/${version}/graphql.json`,\n )\n return url.toString()\n } catch {\n return endpoint\n }\n}\n\n/**\n * Typed GraphQL client mirroring Hydrogen's `createStorefrontClient`. Queries are SWR-cached\n * (default {@link StorefrontDefaultCache}); mutations are never cached. Talks to the same-origin\n * `/api/storefront` proxy (#85) so tokens stay server-side and themes need no CORS.\n */\nexport function createStorefrontClient(opts: StorefrontClientOptions): StorefrontClientResult\nexport function createStorefrontClient<I18n extends object = StorefrontI18n>(\n opts: HydrogenStorefrontClientOptions<I18n>,\n): StorefrontClientResult<StorefrontI18n & I18n>\nexport function createStorefrontClient<I18n extends object = StorefrontI18n>(\n opts: StorefrontClientOptions | HydrogenStorefrontClientOptions<I18n>,\n): StorefrontClientResult | StorefrontClientResult<StorefrontI18n & I18n> {\n if (isHydrogenStorefrontClientOptions(opts)) {\n const i18n = normalizeHydrogenI18n(opts.i18n)\n const client = createStorefrontClientCore({\n endpoint: hydrogenStorefrontEndpoint(opts.storeDomain, opts.storefrontApiVersion),\n token: opts.publicStorefrontToken,\n tokenHeader: 'x-shopify-storefront-access-token',\n cache: createCache({ cache: opts.cache, waitUntil: opts.waitUntil }),\n fetch: opts.fetch,\n defaultStrategy: opts.defaultStrategy,\n queryTimeoutMs: opts.queryTimeoutMs,\n extraHeaders: opts.storefrontHeaders,\n i18n,\n }) as Storefront<StorefrontI18n & I18n>\n return attachHydrogenResult(client)\n }\n return attachHydrogenResult(createStorefrontClientCore(opts))\n}\n\nfunction createStorefrontClientCore(opts: StorefrontClientOptions): StorefrontClient {\n const doFetch = opts.fetch ?? fetch\n const defaultStrategy = opts.defaultStrategy ?? StorefrontDefaultCache()\n const defaultQueryTimeoutMs = opts.queryTimeoutMs ?? DEFAULT_QUERY_TIMEOUT_MS\n const tokenHeader = opts.tokenHeader ?? 'x-kotao-storefront-token'\n const localeKey = opts.locale !== undefined && opts.locale.length > 0 ? opts.locale : ''\n const countryKey = opts.country !== undefined && COUNTRY_RE.test(opts.country) ? opts.country : ''\n const i18n = normalizeStorefrontI18n(opts.i18n, opts.locale, countryKey)\n\n const execute = async <T>(\n document: string,\n options?: StorefrontQueryOptions,\n signal?: AbortSignal,\n timing?: { readonly cacheStatus: string; readonly timeoutMs?: number },\n ): Promise<T> => {\n const operationStartedAt = timing === undefined ? 0 : Date.now()\n const endpoint = endpointForStorefrontApiVersion(opts.endpoint, options?.storefrontApiVersion)\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n ...headersRecord(opts.extraHeaders),\n [tokenHeader]: opts.token,\n ...(opts.signedShopContextHeaders ?? {}),\n }\n if (opts.siteId !== undefined && opts.siteId.trim().length > 0) {\n headers['x-kotao-site-id'] = opts.siteId\n }\n if (localeKey.length > 0) {\n headers['x-kotao-locale'] = localeKey\n }\n if (countryKey.length > 0) {\n headers['x-kotao-country'] = countryKey\n }\n const operationName = operationNameFromDocument(document)\n let res: Response\n try {\n res = await doFetch(endpoint, {\n method: 'POST',\n headers,\n body: JSON.stringify({ query: document, variables: options?.variables }),\n ...(signal === undefined ? {} : { signal }),\n })\n } catch (cause) {\n if (signal?.aborted === true) {\n const timeoutMs = options?.timeoutMs ?? defaultQueryTimeoutMs\n console.error(\n JSON.stringify({\n event: 'storefront_query_failed',\n failure: 'timeout',\n operationName,\n timeoutMs,\n }),\n )\n throw new StorefrontQueryTimeoutError(operationName, timeoutMs)\n }\n console.error(\n JSON.stringify({\n event: 'storefront_query_failed',\n failure: 'transport',\n operationName,\n }),\n )\n throw new StorefrontUpstreamError(operationName, 'Storefront API request failed', { cause })\n }\n // Read the raw body once so a non-JSON response (e.g. an HTML SPA fallback when the\n // /api/storefront carve-out is not reached, or an auth/redirect page) is diagnosable instead of\n // throwing opaquely inside res.json(). A migrated theme swallows the throw and silently renders\n // preview defaults ($0 / no image / preview product), so the response status + a body snippet are\n // logged on every non-success path — the only trace of *why* the live data did not resolve.\n const opName = operationName\n let raw: string\n try {\n raw = await res.text()\n } catch (cause) {\n if (signal?.aborted === true) {\n const timeoutMs = options?.timeoutMs ?? defaultQueryTimeoutMs\n console.error(\n JSON.stringify({\n event: 'storefront_query_failed',\n failure: 'timeout',\n operationName,\n timeoutMs,\n }),\n )\n throw new StorefrontQueryTimeoutError(operationName, timeoutMs)\n }\n console.error(\n JSON.stringify({\n event: 'storefront_query_failed',\n failure: 'response_body',\n operationName,\n status: res.status,\n }),\n )\n throw new StorefrontUpstreamError(operationName, 'Storefront API response body failed', {\n status: res.status,\n cause,\n })\n }\n let body: GraphQLResponse<T>\n try {\n body = JSON.parse(raw) as GraphQLResponse<T>\n } catch {\n console.error(\n `[storefront] /api/storefront non-JSON response: status=${res.status} content-type=${res.headers.get('content-type') ?? ''} len=${raw.length} op=\"${opName}\" body=${raw.slice(0, 180)}`,\n )\n throw new StorefrontUpstreamError(\n operationName,\n `Storefront API returned a non-JSON response (status ${String(res.status)})`,\n { status: res.status },\n )\n }\n if (!res.ok) {\n // endpoint + shopCtx pinpoint a 401: confirms SSR hits the absolute api origin (not the\n // self-zone that 522s) and whether a signed shop context was actually attached to the request.\n const shopCtx = opts.signedShopContextHeaders !== undefined ? 'present' : 'absent'\n console.error(\n `[storefront] /api/storefront HTTP ${res.status} endpoint=${endpoint} shopCtx=${shopCtx} op=\"${opName}\" body=${raw.slice(0, 180)}`,\n )\n throw new StorefrontUpstreamError(\n operationName,\n `Storefront API returned HTTP ${String(res.status)}`,\n { status: res.status },\n )\n }\n if (body.errors?.length) {\n // Surface GraphQL errors before throwing. Callers in the migrated theme (the generated\n // `queryProduct`/`queryProducts`/… helpers) swallow this throw and fall back to preview\n // defaults, so without this log a partial/failed query renders as $0 / no image / a preview\n // product with no trace of the cause. Logged once here, centrally, for every query.\n console.error(`[storefront] GraphQL query failed: ${JSON.stringify(body.errors)}`)\n throw new Error(body.errors.map((e) => e.message).join('; '))\n }\n if (body.data === undefined) {\n console.error(\n `[storefront] /api/storefront returned no data: status=${res.status} op=\"${opName}\" body=${raw.slice(0, 180)}`,\n )\n throw new Error('Storefront API returned no data')\n }\n if (timing !== undefined) {\n console.info(\n JSON.stringify({\n event: 'storefront_operation_timing',\n operationName,\n wallTimeMs: Math.max(0, Date.now() - operationStartedAt),\n cacheStatus: timing.cacheStatus,\n queryCount: 1,\n payloadBytes: raw.length,\n ...(timing.timeoutMs !== undefined ? { timeoutMs: timing.timeoutMs } : {}),\n }),\n )\n }\n return body.data\n }\n\n return {\n CacheNone,\n CacheShort,\n CacheLong,\n CacheCustom,\n cache: opts.cache.raw as StorefrontCache,\n i18n,\n query<T = StorefrontDefaultQueryData>(\n query: string,\n options?: StorefrontQueryOptions,\n ): StorefrontQueryPromise<T> {\n const strategy = options?.cache ?? defaultStrategy\n const versionKey = options?.storefrontApiVersion ?? ''\n const operationName = operationNameFromDocument(query)\n return opts.cache.run(\n `${localeKey}:${countryKey}:${versionKey}:${hashKey(query, options?.variables)}`,\n strategy,\n () => {\n const timeoutMs = options?.timeoutMs ?? defaultQueryTimeoutMs\n return execute<T>(query, { ...options, timeoutMs }, AbortSignal.timeout(timeoutMs), {\n cacheStatus: 'miss',\n timeoutMs,\n })\n },\n ({ ageSeconds, error }) => {\n console.error(\n JSON.stringify({\n event: 'storefront_query_cache_fallback',\n operationName,\n staleAgeSeconds: ageSeconds,\n failure: storefrontFailureKind(error),\n }),\n )\n },\n ) as StorefrontQueryPromise<T>\n },\n mutate<T>(mutation: string, options?: { variables?: Record<string, unknown> }): Promise<T> {\n return execute<T>(mutation, options)\n },\n }\n}\n\nfunction operationNameFromDocument(document: string): string {\n return /\\b(?:query|mutation)\\s+([_A-Za-z][_0-9A-Za-z]*)/u.exec(document)?.[1] ?? 'anonymous'\n}\n\nfunction storefrontFailureKind(error: unknown): 'timeout' | 'upstream' | 'unknown' {\n if (error instanceof StorefrontQueryTimeoutError) return 'timeout'\n if (error instanceof StorefrontUpstreamError) return 'upstream'\n return 'unknown'\n}\n\nfunction isHydrogenStorefrontClientOptions<I18n extends object>(\n opts: StorefrontClientOptions | HydrogenStorefrontClientOptions<I18n>,\n): opts is HydrogenStorefrontClientOptions<I18n> {\n return 'storeDomain' in opts && 'publicStorefrontToken' in opts && 'waitUntil' in opts\n}\n\nfunction attachHydrogenResult<I18n>(client: Storefront<I18n>): StorefrontClientResult<I18n> {\n return Object.assign(client, { storefront: client })\n}\n\nfunction headersRecord(headers: StorefrontHeadersInit | undefined): Record<string, string> {\n if (headers === undefined) return {}\n const result: Record<string, string> = {}\n normalizeStorefrontHeaders(headers).forEach((value, key) => {\n result[key] = value\n })\n return result\n}\n\nfunction hydrogenStorefrontEndpoint(storeDomain: string, version: string | undefined): string {\n const trimmed = storeDomain.trim()\n if (trimmed === '') throw new Error('storeDomain must not be empty')\n const url = new URL(/^https?:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`)\n url.pathname = `/api/${version ?? DEFAULT_HYDROGEN_STOREFRONT_API_VERSION}/graphql.json`\n url.search = ''\n url.hash = ''\n return url.toString()\n}\n\nfunction normalizeHydrogenI18n<I18n extends object>(\n input: I18n | undefined,\n): StorefrontI18n & I18n {\n const source = (input ?? {}) as Partial<StorefrontI18n> & I18n\n const fallback = i18nFromLocale(undefined, '')\n return {\n ...source,\n language: String(source.language ?? fallback.language).toUpperCase(),\n country: String(source.country ?? fallback.country).toUpperCase(),\n currency: String(source.currency ?? fallback.currency).toUpperCase(),\n pathPrefix: normalizePathPrefix(source.pathPrefix ?? fallback.pathPrefix),\n } as StorefrontI18n & I18n\n}\n\nfunction normalizeStorefrontI18n<I18n extends object = object>(\n input: (Partial<StorefrontI18n> & I18n) | undefined,\n locale: string | undefined,\n fallbackCountry: string,\n): StorefrontI18n & I18n {\n const fallback = i18nFromLocale(locale, fallbackCountry)\n return {\n ...input,\n language: String(input?.language ?? fallback.language).toUpperCase(),\n country: String(input?.country ?? fallback.country).toUpperCase(),\n currency: String(input?.currency ?? fallback.currency).toUpperCase(),\n pathPrefix: normalizePathPrefix(input?.pathPrefix ?? fallback.pathPrefix),\n } as StorefrontI18n & I18n\n}\n\nfunction i18nFromLocale(locale: string | undefined, fallbackCountry: string): StorefrontI18n {\n const trimmedLocale = locale?.trim()\n const [language, country] = (\n trimmedLocale && trimmedLocale.length > 0 ? trimmedLocale : 'en-us'\n ).split(/[-_]/)\n return {\n language: (language ?? 'en').toUpperCase(),\n country: (country ?? (fallbackCountry || 'US')).toUpperCase(),\n currency: 'USD',\n pathPrefix: pathPrefixFromLocale(trimmedLocale),\n }\n}\n\nfunction pathPrefixFromLocale(locale: string | undefined): string {\n if (locale === undefined || locale.length === 0) return ''\n return `/${locale.toLowerCase().replaceAll('_', '-')}`\n}\n\nfunction normalizePathPrefix(prefix: string | undefined): string {\n if (prefix === undefined || prefix.trim().length === 0) return ''\n const trimmed = prefix.trim()\n return trimmed.startsWith('/') ? trimmed : `/${trimmed}`\n}\n","import type { CacheStrategy, KotaoCache } from '../cache/cache'\n\nexport type WithCache = <T>(\n key: string,\n strategy: CacheStrategy,\n fn: () => Promise<T>,\n) => Promise<T>\n\n/** Mirrors Hydrogen's `createWithCache`: SWR caching for arbitrary third-party data. */\nexport const createWithCache =\n (cache: KotaoCache): WithCache =>\n (key, strategy, fn) =>\n cache.run(key, strategy, fn)\n","import {\n AUTO_REDIRECT_COUNTRY_HEADER,\n autoRedirectEnabled,\n MARKET_ALTERNATE_LOCALES_HEADER,\n MARKET_CANONICAL_URL_HEADER,\n MARKET_DEFAULT_LOCALE_HEADER,\n MARKET_ID_HEADER,\n MARKET_PATH_PREFIX_HEADER,\n MARKET_ROOT_URLS_HEADER,\n MARKET_SETTINGS_ENVIRONMENT_HEADER,\n MARKET_THEME_ID_HEADER,\n rolloutVisitorCookieHeader,\n SHOP_HEADER,\n SHOP_ORIGIN_HEADER,\n SHOP_SIGNATURE_HEADER,\n signShopContext,\n} from '@kotao/storefront-contracts'\nimport { fetchThemeSettings, type StoredThemeSettings } from '../settings/fetch'\n\nimport { createCache, type StorefrontCacheInput } from '../cache/cache'\nimport { createCartHandler, type CartHandler } from '../cart/createCartHandler'\nimport { createCustomerAccountClient } from '../customer-account/client'\nimport {\n readCustomerSessionToken,\n readHostedCustomerSessionToken,\n} from '../customer-account/session'\nimport type { CustomerAccountClient } from '../customer-account/types'\nimport { createEventsClient, type EventsClient } from '../events/client'\nimport { type Geo, verifyGeo } from '../geo/geo'\nimport { readLocalizationCookie } from '../localization/cookie'\nimport { localeFromRequest } from '../localization/routing'\nimport type { HydrogenSession } from '../cart/types'\nimport {\n createStorefrontClient,\n type StorefrontAuthHeader,\n type StorefrontClient,\n} from '../storefront-client/client'\nimport { createWithCache, type WithCache } from '../with-cache/with-cache'\n\nexport interface KotaoEnv {\n STOREFRONT_API_ENDPOINT: string\n STOREFRONT_API_TOKEN: string\n STOREFRONT_API_TOKEN_HEADER?: string\n STOREFRONT_GEO_SIGNING_KEY: string\n /**\n * Per-deploy font CDN base `https://cdn.kotao.{stage}/{org}/fonts` (bound by apps/storefront-build).\n * Migrated themes stamp it onto the render runtime so `font_face`/`font_url` resolve fonts from the\n * org's R2-native CDN instead of the retired `/kotao-cdn/fonts/{id}` carve-out.\n */\n FONT_CDN_BASE?: string\n KOTAO_SITE_ID?: string\n KOTAO_SHOP_ID?: string\n /**\n * Local-dev only: HMAC key for self-signing the shop-context the proxy verifies. In production\n * the Gateway signs it (this is unset), so its presence is what enables the local signer below.\n * Must match the api proxy's STOREFRONT_SHOP_CONTEXT_KEY.\n */\n STOREFRONT_SHOP_CONTEXT_KEY?: string\n /** Explicit local-dev origin; production receives the gateway-overwritten header. */\n STOREFRONT_SHOP_ORIGIN?: string\n SESSION_SECRET?: string\n PUBLIC_STOREFRONT_API_TOKEN?: string\n PRIVATE_STOREFRONT_API_TOKEN?: string\n PUBLIC_STORE_DOMAIN?: string\n PUBLIC_STOREFRONT_ID?: string\n PUBLIC_CUSTOMER_ACCOUNT_API_CLIENT_ID?: string\n PUBLIC_CUSTOMER_ACCOUNT_API_URL?: string\n PUBLIC_CHECKOUT_DOMAIN?: string\n SHOP_ID?: string\n}\n\nexport interface StorefrontExecutionContext {\n waitUntil(promise: Promise<unknown>): void\n}\n\n/**\n * Local-dev shop-context signer. The standalone theme dev server has no Gateway in front to sign\n * the shop-context, so when a local signing key is present it signs `{ shopId: siteId }` itself.\n * The api proxy then derives the org via the site→org resolver — the exact production code path,\n * with no local-only divergence in `resolveTenant`. Returns `undefined` (no signing) in\n * production, where the key is unset and the Gateway supplies the signature.\n *\n * `hostname` mirrors what the Gateway stamps from its routing key so the api can pin the customer\n * session cookie `Domain` in local dev without a separate lookup.\n */\nexport async function localSignedShopContextHeaders(\n key: string | undefined,\n siteId: string | undefined,\n hostname?: string,\n): Promise<Record<string, string> | undefined> {\n if (key === undefined || key.length === 0) return undefined\n if (siteId === undefined || siteId.trim().length === 0) return undefined\n const { payload, signature } = await signShopContext(\n {\n shopId: siteId,\n ...(hostname !== undefined && hostname.length > 0 ? { hostname } : {}),\n },\n key,\n )\n return { [SHOP_HEADER]: payload, [SHOP_SIGNATURE_HEADER]: signature }\n}\n\nexport interface KotaoSession extends HydrogenSession {\n readonly isLoggedIn: boolean\n}\n\nexport interface KotaoContext {\n readonly storefront: StorefrontClient\n /**\n * Authenticated fetch for REST resources below `STOREFRONT_API_ENDPOINT`.\n *\n * This is deliberately not a general-purpose fetch: theme code is untrusted, so requests outside\n * the configured storefront API origin + base path fail closed before Gateway-signed shop headers\n * are attached.\n */\n readonly fetch: typeof fetch\n readonly events: EventsClient\n readonly cart: CartHandler\n readonly customerAccount: CustomerAccountClient\n readonly geo: Geo | null\n readonly withCache: WithCache\n readonly locale: string | null\n /** Gateway-selected Market context. Informational in theme code; API authorization uses HMAC. */\n readonly market?: StorefrontMarketContext | null\n /** Cookie-presence hint. `isLoggedIn` is true when the session cookie is present in the request.\n * The authoritative check (HMAC verification) happens server-side in the proxy. */\n readonly session: KotaoSession\n // Hydrogen demo helpers carry their own Env interface; expose env permissively while constructor\n // input remains KotaoEnv.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly env: any\n readonly waitUntil: (p: Promise<unknown>) => void\n /**\n * Fetch this shop's stored theme settings (ordered section instances + global tokens) for SSR.\n * The Gateway-signed shop context from the inbound request is forwarded automatically and the call\n * goes cross-origin to the API — mirroring how `storefront` authenticates, because a Worker\n * subrequest to its own zone bypasses the Gateway carve-out.\n */\n readonly loadThemeSettings: (opts?: {\n readonly fetch?: typeof fetch\n readonly templateHandle?: string\n }) => Promise<StoredThemeSettings>\n}\n\nexport interface StorefrontMarketContext {\n readonly id: string\n readonly pathPrefix: string | null\n readonly defaultLocale: string\n readonly alternateLocales: readonly string[]\n readonly rootUrls: readonly { readonly locale: string; readonly url: string }[]\n readonly canonicalUrl: string\n readonly themeId: string | null\n readonly settingsEnvironmentHandle: string | null\n}\n\nexport {\n MARKET_ALTERNATE_LOCALES_HEADER,\n MARKET_CANONICAL_URL_HEADER,\n MARKET_DEFAULT_LOCALE_HEADER,\n MARKET_ID_HEADER,\n MARKET_PATH_PREFIX_HEADER,\n MARKET_ROOT_URLS_HEADER,\n MARKET_SETTINGS_ENVIRONMENT_HEADER,\n MARKET_THEME_ID_HEADER,\n} from '@kotao/storefront-contracts'\n\nexport function marketContextFromHeaders(headers: {\n get(name: string): string | null\n}): StorefrontMarketContext | null {\n const id = headers.get(MARKET_ID_HEADER)?.trim()\n const defaultLocale = headers.get(MARKET_DEFAULT_LOCALE_HEADER)?.trim()\n const canonicalUrl = headers.get(MARKET_CANONICAL_URL_HEADER)?.trim()\n const encodedRoots = headers.get(MARKET_ROOT_URLS_HEADER)\n if (\n !id ||\n !defaultLocale ||\n !canonicalUrl?.startsWith('https://') ||\n encodedRoots === null ||\n encodedRoots.length > 32_768\n ) {\n return null\n }\n let rootUrls: StorefrontMarketContext['rootUrls']\n try {\n const parsed: unknown = JSON.parse(encodedRoots)\n if (\n !Array.isArray(parsed) ||\n parsed.length === 0 ||\n !parsed.every(\n (root) =>\n typeof root === 'object' &&\n root !== null &&\n 'locale' in root &&\n typeof root.locale === 'string' &&\n 'url' in root &&\n typeof root.url === 'string' &&\n root.url.startsWith('https://'),\n )\n ) {\n return null\n }\n rootUrls = parsed\n } catch {\n return null\n }\n const pathPrefix = headers.get(MARKET_PATH_PREFIX_HEADER)?.trim()\n const themeId = headers.get(MARKET_THEME_ID_HEADER)?.trim()\n const settingsEnvironmentHandle = headers.get(MARKET_SETTINGS_ENVIRONMENT_HEADER)?.trim()\n return {\n id,\n pathPrefix: pathPrefix ? pathPrefix : null,\n defaultLocale,\n alternateLocales:\n headers\n .get(MARKET_ALTERNATE_LOCALES_HEADER)\n ?.split(',')\n .map((locale) => locale.trim())\n .filter((locale) => locale.length > 0) ?? [],\n rootUrls,\n canonicalUrl,\n themeId: themeId ? themeId : null,\n settingsEnvironmentHandle: settingsEnvironmentHandle ? settingsEnvironmentHandle : null,\n }\n}\n\nconst CACHE_NAME = 'kotao-storefront-v1'\n/**\n * Header the dispatch worker forwards carrying the per-shop cache version (mirrors\n * storefront-dispatch's `CACHE_VERSION_HEADER` — a wire contract, duplicated rather than imported so\n * the theme package takes no dependency on the dispatch app). The SWR cache namespace is scoped to\n * it: a version bump (importer/redeploy invalidation, #90 / PR #840) abandons the old namespace, so\n * a stale render — e.g. a `$0` response cached mid-import before variants were imported — can no\n * longer be served. Absent the header (local dev / direct hits) the default `0` keeps one stable\n * namespace.\n */\nconst CACHE_VERSION_HEADER = 'x-kotao-cache-version'\nconst REQUEST_ID_HEADER = 'x-kotao-request-id'\nconst DEPLOYMENT_ID_HEADER = 'x-kotao-deployment-id'\n\nexport function trustedShopOrigin(value: string | null | undefined): string | undefined {\n if (!value) return undefined\n try {\n const url = new URL(value)\n if (\n url.protocol !== 'https:' ||\n url.username ||\n url.password ||\n url.port ||\n url.pathname !== '/' ||\n url.search ||\n url.hash\n ) {\n return undefined\n }\n return url.origin\n } catch {\n return undefined\n }\n}\n\nexport function trustedShopOriginFromHeaders(headers: Headers): string | undefined {\n if (!headers.has(SHOP_HEADER) || !headers.has(SHOP_SIGNATURE_HEADER)) return undefined\n return trustedShopOrigin(headers.get(SHOP_ORIGIN_HEADER))\n}\nconst API_LOCALE_RE = /^[a-z]{2,3}(-[a-zA-Z]{2,4})?$/\nconst API_COUNTRY_RE = /^[A-Z]{2}$/\nconst SAME_ORIGIN_PATH = /^\\/(?![/\\\\])/\nconst LEGACY_DIRECT_STOREFRONT_API_ORIGIN =\n /^https:\\/\\/storefront-api\\.kotao\\.(?:com|dev|local)\\/?$/\n\nconst parseLocale = (request: Request): string | null => {\n return localeFromRequest(request)\n}\n\nfunction storefrontAuthHeader(env: KotaoEnv): StorefrontAuthHeader {\n if (env.STOREFRONT_API_TOKEN_HEADER === 'x-shopify-storefront-access-token') {\n return 'x-shopify-storefront-access-token'\n }\n return env.STOREFRONT_API_TOKEN_HEADER === 'x-api-key' ? 'x-api-key' : 'x-kotao-storefront-token'\n}\n\nfunction resolveStorefrontApiEndpoint(endpoint: string, requestUrl: string): string {\n const trimmed = endpoint.trim()\n if (SAME_ORIGIN_PATH.test(trimmed)) return new URL(trimmed, requestUrl).toString()\n if (LEGACY_DIRECT_STOREFRONT_API_ORIGIN.test(trimmed))\n return new URL('/api/storefront', requestUrl).toString()\n return endpoint\n}\n\nconst STOREFRONT_API_PROTECTED_HEADERS = [\n SHOP_HEADER,\n SHOP_ORIGIN_HEADER,\n SHOP_SIGNATURE_HEADER,\n 'x-kotao-locale',\n 'x-kotao-country',\n REQUEST_ID_HEADER,\n DEPLOYMENT_ID_HEADER,\n] as const\n\nfunction createStorefrontApiFetch(endpoint: string, defaultHeaders: Headers): typeof fetch {\n const base = new URL(endpoint)\n const basePath = base.pathname.replace(/\\/+$/, '') || '/'\n\n return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const inputUrl = input instanceof Request ? input.url : String(input)\n const target = new URL(inputUrl, base)\n const withinBasePath =\n basePath === '/' || target.pathname === basePath || target.pathname.startsWith(`${basePath}/`)\n if (\n target.username !== '' ||\n target.password !== '' ||\n target.origin !== base.origin ||\n !withinBasePath\n ) {\n throw new TypeError('storefront API fetch target is outside the configured endpoint')\n }\n\n const request = new Request(input instanceof Request ? input : target, {\n ...init,\n // Never forward signed shop headers across a redirect selected by untrusted theme code.\n redirect: 'manual',\n })\n const headers = new Headers(request.headers)\n for (const name of STOREFRONT_API_PROTECTED_HEADERS) headers.delete(name)\n defaultHeaders.forEach((value, name) => headers.set(name, value))\n return fetch(new Request(request, { headers }))\n }\n}\n\n/**\n * Framework-agnostic per-request context, mirroring Hydrogen's `createHydrogenContext`:\n * storefront client + verified geo + SWR cache + locale + session seam.\n */\nexport async function createKotaoContext(\n request: Request,\n env: KotaoEnv,\n executionCtx: StorefrontExecutionContext,\n deps?: {\n openCache?: (name: string) => Promise<StorefrontCacheInput>\n session?: HydrogenSession\n },\n): Promise<KotaoContext> {\n const waitUntil = (p: Promise<unknown>): void => {\n executionCtx.waitUntil(p)\n }\n const cacheVersion = request.headers.get(CACHE_VERSION_HEADER)?.trim() || '0'\n const cacheName = `${CACHE_NAME}-${cacheVersion}`\n const rawCache = await (deps?.openCache ? deps.openCache(cacheName) : caches.open(cacheName))\n const cache = createCache({ cache: rawCache, waitUntil })\n const storefrontApiEndpoint = env.STOREFRONT_API_ENDPOINT ?? '/api/storefront'\n const storefrontApiToken =\n env.STOREFRONT_API_TOKEN ??\n env.PRIVATE_STOREFRONT_API_TOKEN ??\n env.PUBLIC_STOREFRONT_API_TOKEN ??\n ''\n const storefrontGeoSigningKey = env.STOREFRONT_GEO_SIGNING_KEY ?? ''\n const geo = await verifyGeo(request.headers, storefrontGeoSigningKey)\n const resolvedEnv = {\n ...env,\n STOREFRONT_API_ENDPOINT: resolveStorefrontApiEndpoint(storefrontApiEndpoint, request.url),\n STOREFRONT_API_TOKEN: storefrontApiToken,\n STOREFRONT_GEO_SIGNING_KEY: storefrontGeoSigningKey,\n }\n const siteId = resolvedEnv.KOTAO_SITE_ID ?? resolvedEnv.KOTAO_SHOP_ID\n // In production the Gateway stamps a freshly-signed shop context (SHOP_HEADER/SHOP_SIGNATURE_HEADER)\n // onto the dispatched request; forward it verbatim to the absolute api proxy origin so SSR reaches\n // the trusted proxy directly instead of self-looping on the shop's own same-origin /api/storefront\n // (a Worker subrequest to its own zone bypasses the Gateway and 522s). Fall back to the local-dev\n // self-signer (no Gateway in front) when the inbound pair is absent.\n const inboundShop = request.headers.get(SHOP_HEADER)\n const inboundShopSignature = request.headers.get(SHOP_SIGNATURE_HEADER)\n const signedShopContextHeaders =\n inboundShop !== null && inboundShopSignature !== null\n ? {\n [SHOP_HEADER]: inboundShop,\n [SHOP_SIGNATURE_HEADER]: inboundShopSignature,\n }\n : await localSignedShopContextHeaders(\n resolvedEnv.STOREFRONT_SHOP_CONTEXT_KEY,\n siteId,\n new URL(request.url).hostname,\n )\n // Language is URL-addressed: only a locale prefix may select translated storefront content.\n // The cookie remains country-bearing for presentment; its legacy locale half is used solely by\n // the document loader to redirect old selections onto their canonical prefixed URL.\n const requestUrl = new URL(request.url)\n const editorMode = requestUrl.searchParams.get('kotao_editor') === '1'\n const requestedEditorLocale = editorMode\n ? requestUrl.searchParams.get('kotao_locale')?.trim()\n : undefined\n const requestedEditorCountry = editorMode\n ? requestUrl.searchParams.get('kotao_country')?.trim().toUpperCase()\n : undefined\n const editorLocale =\n requestedEditorLocale !== undefined && API_LOCALE_RE.test(requestedEditorLocale)\n ? requestedEditorLocale\n : null\n const editorCountry =\n requestedEditorCountry !== undefined && API_COUNTRY_RE.test(requestedEditorCountry)\n ? requestedEditorCountry\n : null\n const pathLocale = editorLocale ?? parseLocale(request)\n const market = marketContextFromHeaders(request.headers)\n const localizationCookie = readLocalizationCookie(request.headers.get('cookie'))\n const autoCountry = autoRedirectEnabled(request.headers, AUTO_REDIRECT_COUNTRY_HEADER)\n const apiLocale = pathLocale !== null && API_LOCALE_RE.test(pathLocale) ? pathLocale : undefined\n const cookieCountry =\n localizationCookie.country !== null && API_COUNTRY_RE.test(localizationCookie.country)\n ? localizationCookie.country\n : null\n const geoCountry = autoCountry ? (geo?.country?.trim().toUpperCase() ?? null) : null\n const apiCountry =\n editorCountry ??\n cookieCountry ??\n (geoCountry !== null && API_COUNTRY_RE.test(geoCountry) ? geoCountry : null)\n const extraHeaders: Record<string, string> = {}\n const rolloutVisitorCookie = rolloutVisitorCookieHeader(request.headers.get('cookie'))\n if (rolloutVisitorCookie !== null) extraHeaders['cookie'] = rolloutVisitorCookie\n const requestId = request.headers.get(REQUEST_ID_HEADER)?.trim()\n if (requestId !== undefined && requestId.length > 0) extraHeaders[REQUEST_ID_HEADER] = requestId\n const deploymentId = request.headers.get(DEPLOYMENT_ID_HEADER)?.trim()\n if (deploymentId !== undefined && deploymentId.length > 0) {\n extraHeaders[DEPLOYMENT_ID_HEADER] = deploymentId\n }\n const storefront = createStorefrontClient({\n endpoint: resolvedEnv.STOREFRONT_API_ENDPOINT,\n token: resolvedEnv.STOREFRONT_API_TOKEN,\n tokenHeader: storefrontAuthHeader(resolvedEnv),\n ...(siteId !== undefined && siteId.trim().length > 0 ? { siteId } : {}),\n ...(signedShopContextHeaders ? { signedShopContextHeaders } : {}),\n ...(apiLocale !== undefined ? { locale: apiLocale } : {}),\n ...(apiCountry !== null ? { country: apiCountry } : {}),\n ...(Object.keys(extraHeaders).length > 0 ? { extraHeaders } : {}),\n cache,\n })\n const eventHeaders = new Headers(signedShopContextHeaders)\n if (rolloutVisitorCookie !== null) eventHeaders.set('cookie', rolloutVisitorCookie)\n if (apiLocale !== undefined) eventHeaders.set('x-kotao-locale', apiLocale)\n if (apiCountry !== null) eventHeaders.set('x-kotao-country', apiCountry)\n for (const [name, value] of Object.entries(extraHeaders)) eventHeaders.set(name, value)\n const events = createEventsClient({\n baseUrl: resolvedEnv.STOREFRONT_API_ENDPOINT,\n fetch,\n defaultHeaders: eventHeaders,\n })\n const storefrontApiFetch = createStorefrontApiFetch(\n resolvedEnv.STOREFRONT_API_ENDPOINT,\n eventHeaders,\n )\n const cart = createCartHandler({ request, storefront })\n const contextSession = withSessionPresenceHint(\n deps?.session,\n readHostedCustomerSessionToken(request.headers.get('cookie')) !== null ||\n readCustomerSessionToken(request.headers.get('cookie')) !== null,\n )\n const customerAccount = createCustomerAccountClient({\n request,\n customerAccountId: resolvedEnv.PUBLIC_CUSTOMER_ACCOUNT_API_CLIENT_ID,\n shopId: resolvedEnv.SHOP_ID,\n session: contextSession,\n shopOrigin:\n trustedShopOriginFromHeaders(request.headers) ??\n (inboundShop === null && inboundShopSignature === null\n ? trustedShopOrigin(resolvedEnv.STOREFRONT_SHOP_ORIGIN)\n : undefined),\n })\n\n // Settings live under the storefront API endpoint's `/settings` carve-out. Forward the same\n // signed shop context the GraphQL client uses and go cross-origin (the resolved endpoint is\n // absolute https in prod and local mkcert dev) — the same-origin default 522s from a Worker.\n const settingsEndpoint = `${resolvedEnv.STOREFRONT_API_ENDPOINT.replace(/\\/+$/, '')}/settings`\n\n return {\n storefront,\n fetch: storefrontApiFetch,\n events,\n cart,\n customerAccount,\n geo,\n withCache: createWithCache(cache),\n locale: pathLocale,\n market,\n // Cookie-presence hint only — the theme cannot validate the HMAC; the authoritative check is the proxy.\n session: contextSession,\n env: resolvedEnv,\n waitUntil,\n loadThemeSettings: (opts?: {\n readonly fetch?: typeof fetch\n readonly templateHandle?: string\n }) =>\n fetchThemeSettings({\n endpoint: settingsEndpoint,\n allowCrossOrigin: true,\n ...(signedShopContextHeaders || rolloutVisitorCookie !== null || apiCountry !== null\n ? {\n shopContextHeaders: {\n ...(signedShopContextHeaders ?? {}),\n ...(rolloutVisitorCookie === null ? {} : { cookie: rolloutVisitorCookie }),\n ...(apiCountry === null ? {} : { 'x-kotao-country': apiCountry }),\n },\n }\n : {}),\n ...(opts?.fetch ? { fetch: opts.fetch } : {}),\n ...(opts?.templateHandle ? { templateHandle: opts.templateHandle } : {}),\n }),\n }\n}\n\nfunction withSessionPresenceHint(\n session: HydrogenSession | undefined,\n isLoggedIn: boolean,\n): KotaoSession {\n if (session === undefined) return createEphemeralSession(isLoggedIn)\n Object.defineProperty(session, 'isLoggedIn', {\n configurable: true,\n enumerable: true,\n value: isLoggedIn,\n writable: true,\n })\n return session as KotaoSession\n}\n\nfunction createEphemeralSession(isLoggedIn: boolean): KotaoSession {\n const data = new Map<string, unknown>()\n let isPending = false\n return {\n get isPending(): boolean {\n return isPending\n },\n isLoggedIn,\n has: (name: string) => data.has(name),\n get: (name: string) => data.get(name),\n flash(name: string, value?: unknown): unknown {\n const previous = data.get(name)\n if (value !== undefined) {\n this.set(name, value)\n return undefined\n }\n this.unset(name)\n return previous\n },\n unset(name: string): void {\n isPending = true\n data.delete(name)\n },\n set(name: string, value: unknown): void {\n isPending = true\n data.set(name, value)\n },\n destroy(): string {\n isPending = false\n data.clear()\n return ''\n },\n commit(): string {\n isPending = false\n return ''\n },\n }\n}\n"]}
|