@shoppexio/storefront 1.0.38 → 1.0.39

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.
@@ -1 +1 @@
1
- {"version":3,"file":"shoppex.umd.js","names":["_a","F","initializer","util.jsonStringifyReplacer","core.$ZodAsyncError","util.finalizeIssue","core.config","errors.$ZodError","safeParse","errors.$ZodRealError","safeParseAsync","duration","email","_emoji","date","time","datetime","string","number","boolean","util.floatSafeRemainder","util.NUMBER_FORMAT_RANGES","regexes.integer","util.nullish","util.getLengthableOrigin","regexes.lowercase","regexes.uppercase","util.escapeRegex","content","util.aborted","util.explicitlyAborted","core.$ZodAsyncError","safeParse","safeParseAsync","regexes.string","regexes.guid","regexes.uuid","regexes.email","regexes.emoji","regexes.nanoid","regexes.cuid","regexes.cuid2","regexes.ulid","regexes.xid","regexes.ksuid","regexes.datetime","regexes.date","regexes.time","regexes.duration","regexes.ipv4","regexes.ipv6","regexes.cidrv4","regexes.cidrv6","regexes.base64","regexes.base64url","regexes.e164","regexes.number","regexes.boolean","util.prefixIssues","util.optionalKeys","util.cached","isObject","util.isObject","util.esc","allowsEval","util.allowsEval","util.finalizeIssue","core.config","util.cleanRegex","util.isPlainObject","util.getEnumValues","util.escapeRegex","core.$ZodEncodeError","util.issue","util.normalizeParams","checks.$ZodCheckLessThan","checks.$ZodCheckGreaterThan","checks.$ZodCheckMultipleOf","checks.$ZodCheckMaxLength","checks.$ZodCheckMinLength","checks.$ZodCheckLengthEquals","checks.$ZodCheckRegex","checks.$ZodCheckLowerCase","checks.$ZodCheckUpperCase","checks.$ZodCheckIncludes","checks.$ZodCheckStartsWith","checks.$ZodCheckEndsWith","checks.$ZodCheckOverwrite","util.slugify","issue","util.issue","checks.$ZodCheck","process","process","core._isoDateTime","core._isoDate","core._isoTime","core._isoDuration","core.formatError","core.flattenError","util.jsonStringifyReplacer","parse.parse","parse.safeParse","parse.parseAsync","parse.safeParseAsync","parse.encode","parse.decode","parse.encodeAsync","parse.decodeAsync","parse.safeEncode","parse.safeDecode","parse.safeEncodeAsync","parse.safeDecodeAsync","util.mergeDefs","core.clone","checks.overwrite","processors.stringProcessor","checks.regex","checks.includes","checks.startsWith","checks.endsWith","checks.minLength","checks.maxLength","checks.length","checks.lowercase","checks.uppercase","checks.trim","checks.normalize","checks.toLowerCase","checks.toUpperCase","checks.slugify","core._email","core._url","core._jwt","core._emoji","core._guid","core._uuid","core._uuidv4","core._uuidv6","core._uuidv7","core._nanoid","core._cuid","core._cuid2","core._ulid","core._base64","core._base64url","core._xid","core._ksuid","core._ipv4","core._ipv6","core._cidrv4","core._cidrv6","core._e164","iso.datetime","iso.date","iso.time","iso.duration","core._string","processors.numberProcessor","checks.gt","checks.gte","checks.lt","checks.lte","checks.multipleOf","number","core._number","core._int","processors.booleanProcessor","core._boolean","processors.unknownProcessor","core._unknown","processors.neverProcessor","core._never","processors.arrayProcessor","core._array","processors.objectProcessor","util.extend","util.safeExtend","util.merge","util.pick","util.omit","util.partial","util.required","util.normalizeParams","processors.unionProcessor","processors.intersectionProcessor","processors.recordProcessor","processors.enumProcessor","processors.literalProcessor","processors.transformProcessor","core.$ZodEncodeError","issue","util.issue","processors.optionalProcessor","processors.nullableProcessor","processors.defaultProcessor","util.shallowClone","processors.prefaultProcessor","processors.nonoptionalProcessor","processors.catchProcessor","processors.pipeProcessor","processors.readonlyProcessor","processors.customProcessor","core._refine","core._superRefine","core._coercedNumber","schemas.ZodNumber"],"sources":["../src/core/cache.ts","../src/core/errors.ts","../../../node_modules/.bun/openapi-fetch@0.17.0/node_modules/openapi-fetch/dist/index.mjs","../../contracts/src/navigation.ts","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/core.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/util.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/errors.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/parse.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/regexes.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/checks.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/doc.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/versions.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/schemas.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/registries.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/api.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/iso.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/errors.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/parse.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/schemas.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/coerce.js","../../contracts/src/email-marketing.ts","../../contracts/src/payment-gateways.ts","../../contracts/src/style-center.ts","../../contracts/src/storefront-addons.ts","../../contracts/src/manual-gateway-template.ts","../../contracts/src/invoice-wire.ts","../../contracts/src/catalog-unit-price.ts","../../contracts/src/customer-portal-wire.ts","../../contracts/src/index.ts","../src/core/typed-client.ts","../src/core/config.ts","../src/utils/storefront-custom-fields.ts","../src/utils/storefront-stock.ts","../src/utils/storefront-catalog.ts","../src/utils/storefront-search.ts","../src/utils/storefront-contact.ts","../src/core/endpoint.ts","../src/utils/storage.ts","../src/core/telemetry.ts","../src/core/client.ts","../src/modules/store.ts","../src/modules/products.ts","../src/modules/affiliates.ts","../src/utils/cart-line-id.ts","../src/utils/requested-currency.ts","../src/modules/cart.ts","../src/modules/checkout.ts","../src/modules/coupons.ts","../src/modules/reviews.ts","../src/modules/customer.ts","../src/modules/search.ts","../src/modules/invoices.ts","../src/modules/pages.ts","../src/modules/navigation.ts","../src/core/attribution.ts","../src/modules/analytics.ts","../src/modules/presence.ts","../src/utils/format.ts","../src/modules/theme.ts","../src/index.ts"],"sourcesContent":["/**\n * In-memory cache with pending request deduplication.\n */\n\nexport interface CacheEntry<T> {\n data: T;\n expiresAt: number;\n updatedAt: number;\n ttl: number;\n}\n\nexport interface CacheOptions {\n ttl: number;\n staleWhileRevalidate?: boolean;\n}\n\nexport interface CacheStats {\n hits: number;\n misses: number;\n pendingRequests: number;\n entries: number;\n}\n\nconst cache = new Map<string, CacheEntry<unknown>>();\nconst pending = new Map<string, Promise<unknown>>();\n\nconst stats = {\n hits: 0,\n misses: 0,\n};\n\nfunction isExpired(entry: CacheEntry<unknown>): boolean {\n return Date.now() > entry.expiresAt;\n}\n\nexport function getCacheStats(): CacheStats {\n return {\n hits: stats.hits,\n misses: stats.misses,\n pendingRequests: pending.size,\n entries: cache.size,\n };\n}\n\nexport function clearCache(): void {\n cache.clear();\n pending.clear();\n}\n\nexport function invalidateCache(prefixOrKey: string): void {\n for (const key of cache.keys()) {\n if (key === prefixOrKey || key.startsWith(prefixOrKey)) {\n cache.delete(key);\n }\n }\n}\n\nexport function setCacheEntry<T>(key: string, data: T, ttl: number): void {\n const now = Date.now();\n cache.set(key, {\n data,\n ttl,\n updatedAt: now,\n expiresAt: now + ttl,\n });\n}\n\nexport function getCacheEntry<T>(key: string): CacheEntry<T> | null {\n const entry = cache.get(key) as CacheEntry<T> | undefined;\n if (!entry) return null;\n return entry;\n}\n\nexport async function getOrFetch<T>(\n key: string,\n fetcher: () => Promise<T>,\n options: CacheOptions,\n shouldCache: (value: T) => boolean = () => true\n): Promise<T> {\n const entry = getCacheEntry<T>(key);\n\n if (entry && !isExpired(entry)) {\n stats.hits += 1;\n return entry.data;\n }\n\n if (entry && options.staleWhileRevalidate) {\n stats.hits += 1;\n if (!pending.has(key)) {\n const refreshPromise = (async () => {\n try {\n const data = await fetcher();\n if (shouldCache(data)) {\n setCacheEntry(key, data, options.ttl);\n }\n return data;\n } finally {\n pending.delete(key);\n }\n })();\n pending.set(key, refreshPromise as Promise<unknown>);\n }\n return entry.data;\n }\n\n if (pending.has(key)) {\n return pending.get(key) as Promise<T>;\n }\n\n stats.misses += 1;\n const promise = (async () => {\n try {\n const data = await fetcher();\n if (shouldCache(data)) {\n setCacheEntry(key, data, options.ttl);\n }\n return data;\n } finally {\n pending.delete(key);\n }\n })();\n\n pending.set(key, promise as Promise<unknown>);\n return promise;\n}\n","/**\n * SDK Error Classes\n */\n\nexport class ShoppexError extends Error {\n public readonly code: string;\n public readonly statusCode?: number;\n\n constructor(message: string, code: string, statusCode?: number) {\n super(message);\n this.name = 'ShoppexError';\n this.code = code;\n this.statusCode = statusCode;\n Object.setPrototypeOf(this, ShoppexError.prototype);\n }\n}\n\nexport class NotInitializedError extends ShoppexError {\n constructor() {\n super(\n 'SDK not initialized. Call shoppex.init() first.',\n 'NOT_INITIALIZED'\n );\n this.name = 'NotInitializedError';\n Object.setPrototypeOf(this, NotInitializedError.prototype);\n }\n}\n\nexport class NetworkError extends ShoppexError {\n constructor(message: string, statusCode?: number) {\n super(message, 'NETWORK_ERROR', statusCode);\n this.name = 'NetworkError';\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n\n/**\n * A refusal the SERVER made and named. `code` is the backend's `error_code`\n * (e.g. `errors.checkout.coupon_no_longer_valid`) — the branchable identity of\n * the refusal, stable across locales, unlike the localized `message`.\n *\n * Distinct from {@link NetworkError}, whose `code` is always `NETWORK_ERROR`:\n * that one means \"the request did not produce a named answer\".\n */\nexport class ApiError extends ShoppexError {\n public readonly errorParams?: Record<string, unknown>;\n\n constructor(\n message: string,\n code: string,\n statusCode?: number,\n errorParams?: Record<string, unknown>,\n ) {\n super(message, code, statusCode);\n this.name = 'ApiError';\n this.errorParams = errorParams;\n Object.setPrototypeOf(this, ApiError.prototype);\n }\n}\n\nexport class ValidationError extends ShoppexError {\n public readonly invalidFields?: string[];\n\n constructor(message: string, invalidFields?: string[]) {\n super(message, 'VALIDATION_ERROR');\n this.name = 'ValidationError';\n this.invalidFields = invalidFields;\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n\nexport class CartError extends ShoppexError {\n constructor(message: string) {\n super(message, 'BASKET_ERROR');\n this.name = 'CartError';\n Object.setPrototypeOf(this, CartError.prototype);\n }\n}\n","const PATH_PARAM_RE = /\\{[^{}]+\\}/g;\nconst supportsRequestInitExt = () => {\n return typeof process === \"object\" && Number.parseInt(process?.versions?.node?.substring(0, 2)) >= 18 && process.versions.undici;\n};\nfunction randomID() {\n return Math.random().toString(36).slice(2, 11);\n}\nfunction createClient(clientOptions) {\n let {\n baseUrl = \"\",\n Request: CustomRequest = globalThis.Request,\n fetch: baseFetch = globalThis.fetch,\n querySerializer: globalQuerySerializer,\n bodySerializer: globalBodySerializer,\n pathSerializer: globalPathSerializer,\n headers: baseHeaders,\n requestInitExt = void 0,\n ...baseOptions\n } = { ...clientOptions };\n requestInitExt = supportsRequestInitExt() ? requestInitExt : void 0;\n baseUrl = removeTrailingSlash(baseUrl);\n const globalMiddlewares = [];\n async function coreFetch(schemaPath, fetchOptions) {\n const {\n baseUrl: localBaseUrl,\n fetch = baseFetch,\n Request = CustomRequest,\n headers,\n params = {},\n parseAs = \"json\",\n querySerializer: requestQuerySerializer,\n bodySerializer = globalBodySerializer ?? defaultBodySerializer,\n pathSerializer: requestPathSerializer,\n body,\n middleware: requestMiddlewares = [],\n ...init\n } = fetchOptions || {};\n let finalBaseUrl = baseUrl;\n if (localBaseUrl) {\n finalBaseUrl = removeTrailingSlash(localBaseUrl) ?? baseUrl;\n }\n let querySerializer = typeof globalQuerySerializer === \"function\" ? globalQuerySerializer : createQuerySerializer(globalQuerySerializer);\n if (requestQuerySerializer) {\n querySerializer = typeof requestQuerySerializer === \"function\" ? requestQuerySerializer : createQuerySerializer({\n ...typeof globalQuerySerializer === \"object\" ? globalQuerySerializer : {},\n ...requestQuerySerializer\n });\n }\n const pathSerializer = requestPathSerializer || globalPathSerializer || defaultPathSerializer;\n const serializedBody = body === void 0 ? void 0 : bodySerializer(\n body,\n // Note: we declare mergeHeaders() both here and below because it’s a bit of a chicken-or-egg situation:\n // bodySerializer() needs all headers so we aren’t dropping ones set by the user, however,\n // the result of this ALSO sets the lowest-priority content-type header. So we re-merge below,\n // setting the content-type at the very beginning to be overwritten.\n // Lastly, based on the way headers work, it’s not a simple “present-or-not” check becauase null intentionally un-sets headers.\n mergeHeaders(baseHeaders, headers, params.header)\n );\n const finalHeaders = mergeHeaders(\n // with no body, we should not to set Content-Type\n serializedBody === void 0 || // if serialized body is FormData; browser will correctly set Content-Type & boundary expression\n serializedBody instanceof FormData ? {} : {\n \"Content-Type\": \"application/json\"\n },\n baseHeaders,\n headers,\n params.header\n );\n const finalMiddlewares = [...globalMiddlewares, ...requestMiddlewares];\n const requestInit = {\n redirect: \"follow\",\n ...baseOptions,\n ...init,\n body: serializedBody,\n headers: finalHeaders\n };\n let id;\n let options;\n let request = new Request(\n createFinalURL(schemaPath, { baseUrl: finalBaseUrl, params, querySerializer, pathSerializer }),\n requestInit\n );\n let response;\n for (const key in init) {\n if (!(key in request)) {\n request[key] = init[key];\n }\n }\n if (finalMiddlewares.length) {\n id = randomID();\n options = Object.freeze({\n baseUrl: finalBaseUrl,\n fetch,\n parseAs,\n querySerializer,\n bodySerializer,\n pathSerializer\n });\n for (const m of finalMiddlewares) {\n if (m && typeof m === \"object\" && typeof m.onRequest === \"function\") {\n const result = await m.onRequest({\n request,\n schemaPath,\n params,\n options,\n id\n });\n if (result) {\n if (result instanceof Request) {\n request = result;\n } else if (result instanceof Response) {\n response = result;\n break;\n } else {\n throw new Error(\"onRequest: must return new Request() or Response() when modifying the request\");\n }\n }\n }\n }\n }\n if (!response) {\n try {\n response = await fetch(request, requestInitExt);\n } catch (error2) {\n let errorAfterMiddleware = error2;\n if (finalMiddlewares.length) {\n for (let i = finalMiddlewares.length - 1; i >= 0; i--) {\n const m = finalMiddlewares[i];\n if (m && typeof m === \"object\" && typeof m.onError === \"function\") {\n const result = await m.onError({\n request,\n error: errorAfterMiddleware,\n schemaPath,\n params,\n options,\n id\n });\n if (result) {\n if (result instanceof Response) {\n errorAfterMiddleware = void 0;\n response = result;\n break;\n }\n if (result instanceof Error) {\n errorAfterMiddleware = result;\n continue;\n }\n throw new Error(\"onError: must return new Response() or instance of Error\");\n }\n }\n }\n }\n if (errorAfterMiddleware) {\n throw errorAfterMiddleware;\n }\n }\n if (finalMiddlewares.length) {\n for (let i = finalMiddlewares.length - 1; i >= 0; i--) {\n const m = finalMiddlewares[i];\n if (m && typeof m === \"object\" && typeof m.onResponse === \"function\") {\n const result = await m.onResponse({\n request,\n response,\n schemaPath,\n params,\n options,\n id\n });\n if (result) {\n if (!(result instanceof Response)) {\n throw new Error(\"onResponse: must return new Response() when modifying the response\");\n }\n response = result;\n }\n }\n }\n }\n }\n const contentLength = response.headers.get(\"Content-Length\");\n if (response.status === 204 || request.method === \"HEAD\" || contentLength === \"0\" && !response.headers.get(\"Transfer-Encoding\")?.includes(\"chunked\")) {\n return response.ok ? { data: void 0, response } : { error: void 0, response };\n }\n if (response.ok) {\n const getResponseData = async () => {\n if (parseAs === \"stream\") {\n return response.body;\n }\n if (parseAs === \"json\" && !contentLength) {\n const raw = await response.text();\n return raw ? JSON.parse(raw) : void 0;\n }\n return await response[parseAs]();\n };\n return { data: await getResponseData(), response };\n }\n let error = await response.text();\n try {\n error = JSON.parse(error);\n } catch {\n }\n return { error, response };\n }\n return {\n request(method, url, init) {\n return coreFetch(url, { ...init, method: method.toUpperCase() });\n },\n /** Call a GET endpoint */\n GET(url, init) {\n return coreFetch(url, { ...init, method: \"GET\" });\n },\n /** Call a PUT endpoint */\n PUT(url, init) {\n return coreFetch(url, { ...init, method: \"PUT\" });\n },\n /** Call a POST endpoint */\n POST(url, init) {\n return coreFetch(url, { ...init, method: \"POST\" });\n },\n /** Call a DELETE endpoint */\n DELETE(url, init) {\n return coreFetch(url, { ...init, method: \"DELETE\" });\n },\n /** Call a OPTIONS endpoint */\n OPTIONS(url, init) {\n return coreFetch(url, { ...init, method: \"OPTIONS\" });\n },\n /** Call a HEAD endpoint */\n HEAD(url, init) {\n return coreFetch(url, { ...init, method: \"HEAD\" });\n },\n /** Call a PATCH endpoint */\n PATCH(url, init) {\n return coreFetch(url, { ...init, method: \"PATCH\" });\n },\n /** Call a TRACE endpoint */\n TRACE(url, init) {\n return coreFetch(url, { ...init, method: \"TRACE\" });\n },\n /** Register middleware */\n use(...middleware) {\n for (const m of middleware) {\n if (!m) {\n continue;\n }\n if (typeof m !== \"object\" || !(\"onRequest\" in m || \"onResponse\" in m || \"onError\" in m)) {\n throw new Error(\"Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`\");\n }\n globalMiddlewares.push(m);\n }\n },\n /** Unregister middleware */\n eject(...middleware) {\n for (const m of middleware) {\n const i = globalMiddlewares.indexOf(m);\n if (i !== -1) {\n globalMiddlewares.splice(i, 1);\n }\n }\n }\n };\n}\nclass PathCallForwarder {\n constructor(client, url) {\n this.client = client;\n this.url = url;\n }\n GET = (init) => {\n return this.client.GET(this.url, init);\n };\n PUT = (init) => {\n return this.client.PUT(this.url, init);\n };\n POST = (init) => {\n return this.client.POST(this.url, init);\n };\n DELETE = (init) => {\n return this.client.DELETE(this.url, init);\n };\n OPTIONS = (init) => {\n return this.client.OPTIONS(this.url, init);\n };\n HEAD = (init) => {\n return this.client.HEAD(this.url, init);\n };\n PATCH = (init) => {\n return this.client.PATCH(this.url, init);\n };\n TRACE = (init) => {\n return this.client.TRACE(this.url, init);\n };\n}\nclass PathClientProxyHandler {\n constructor() {\n this.client = null;\n }\n // Assume the property is an URL.\n get(coreClient, url) {\n const forwarder = new PathCallForwarder(coreClient, url);\n this.client[url] = forwarder;\n return forwarder;\n }\n}\nfunction wrapAsPathBasedClient(coreClient) {\n const handler = new PathClientProxyHandler();\n const proxy = new Proxy(coreClient, handler);\n function Client() {\n }\n Client.prototype = proxy;\n const client = new Client();\n handler.client = client;\n return client;\n}\nfunction createPathBasedClient(clientOptions) {\n return wrapAsPathBasedClient(createClient(clientOptions));\n}\nfunction serializePrimitiveParam(name, value, options) {\n if (value === void 0 || value === null) {\n return \"\";\n }\n if (typeof value === \"object\") {\n throw new Error(\n \"Deeply-nested arrays/objects aren\\u2019t supported. Provide your own `querySerializer()` to handle these.\"\n );\n }\n return `${name}=${options?.allowReserved === true ? value : encodeURIComponent(value)}`;\n}\nfunction serializeObjectParam(name, value, options) {\n if (!value || typeof value !== \"object\") {\n return \"\";\n }\n const values = [];\n const joiner = {\n simple: \",\",\n label: \".\",\n matrix: \";\"\n }[options.style] || \"&\";\n if (options.style !== \"deepObject\" && options.explode === false) {\n for (const k in value) {\n values.push(k, options.allowReserved === true ? value[k] : encodeURIComponent(value[k]));\n }\n const final2 = values.join(\",\");\n switch (options.style) {\n case \"form\": {\n return `${name}=${final2}`;\n }\n case \"label\": {\n return `.${final2}`;\n }\n case \"matrix\": {\n return `;${name}=${final2}`;\n }\n default: {\n return final2;\n }\n }\n }\n for (const k in value) {\n const finalName = options.style === \"deepObject\" ? `${name}[${k}]` : k;\n values.push(serializePrimitiveParam(finalName, value[k], options));\n }\n const final = values.join(joiner);\n return options.style === \"label\" || options.style === \"matrix\" ? `${joiner}${final}` : final;\n}\nfunction serializeArrayParam(name, value, options) {\n if (!Array.isArray(value)) {\n return \"\";\n }\n if (options.explode === false) {\n const joiner2 = { form: \",\", spaceDelimited: \"%20\", pipeDelimited: \"|\" }[options.style] || \",\";\n const final = (options.allowReserved === true ? value : value.map((v) => encodeURIComponent(v))).join(joiner2);\n switch (options.style) {\n case \"simple\": {\n return final;\n }\n case \"label\": {\n return `.${final}`;\n }\n case \"matrix\": {\n return `;${name}=${final}`;\n }\n // case \"spaceDelimited\":\n // case \"pipeDelimited\":\n default: {\n return `${name}=${final}`;\n }\n }\n }\n const joiner = { simple: \",\", label: \".\", matrix: \";\" }[options.style] || \"&\";\n const values = [];\n for (const v of value) {\n if (options.style === \"simple\" || options.style === \"label\") {\n values.push(options.allowReserved === true ? v : encodeURIComponent(v));\n } else {\n values.push(serializePrimitiveParam(name, v, options));\n }\n }\n return options.style === \"label\" || options.style === \"matrix\" ? `${joiner}${values.join(joiner)}` : values.join(joiner);\n}\nfunction createQuerySerializer(options) {\n return function querySerializer(queryParams) {\n const search = [];\n if (queryParams && typeof queryParams === \"object\") {\n for (const name in queryParams) {\n const value = queryParams[name];\n if (value === void 0 || value === null) {\n continue;\n }\n if (Array.isArray(value)) {\n if (value.length === 0) {\n continue;\n }\n search.push(\n serializeArrayParam(name, value, {\n style: \"form\",\n explode: true,\n ...options?.array,\n allowReserved: options?.allowReserved || false\n })\n );\n continue;\n }\n if (typeof value === \"object\") {\n search.push(\n serializeObjectParam(name, value, {\n style: \"deepObject\",\n explode: true,\n ...options?.object,\n allowReserved: options?.allowReserved || false\n })\n );\n continue;\n }\n search.push(serializePrimitiveParam(name, value, options));\n }\n }\n return search.join(\"&\");\n };\n}\nfunction defaultPathSerializer(pathname, pathParams) {\n let nextURL = pathname;\n for (const match of pathname.match(PATH_PARAM_RE) ?? []) {\n let name = match.substring(1, match.length - 1);\n let explode = false;\n let style = \"simple\";\n if (name.endsWith(\"*\")) {\n explode = true;\n name = name.substring(0, name.length - 1);\n }\n if (name.startsWith(\".\")) {\n style = \"label\";\n name = name.substring(1);\n } else if (name.startsWith(\";\")) {\n style = \"matrix\";\n name = name.substring(1);\n }\n if (!pathParams || pathParams[name] === void 0 || pathParams[name] === null) {\n continue;\n }\n const value = pathParams[name];\n if (Array.isArray(value)) {\n nextURL = nextURL.replace(match, serializeArrayParam(name, value, { style, explode }));\n continue;\n }\n if (typeof value === \"object\") {\n nextURL = nextURL.replace(match, serializeObjectParam(name, value, { style, explode }));\n continue;\n }\n if (style === \"matrix\") {\n nextURL = nextURL.replace(match, `;${serializePrimitiveParam(name, value)}`);\n continue;\n }\n nextURL = nextURL.replace(match, style === \"label\" ? `.${encodeURIComponent(value)}` : encodeURIComponent(value));\n }\n return nextURL;\n}\nfunction defaultBodySerializer(body, headers) {\n if (body instanceof FormData) {\n return body;\n }\n if (headers) {\n const contentType = headers.get instanceof Function ? headers.get(\"Content-Type\") ?? headers.get(\"content-type\") : headers[\"Content-Type\"] ?? headers[\"content-type\"];\n if (contentType === \"application/x-www-form-urlencoded\") {\n return new URLSearchParams(body).toString();\n }\n }\n return JSON.stringify(body);\n}\nfunction createFinalURL(pathname, options) {\n let finalURL = `${options.baseUrl}${pathname}`;\n if (options.params?.path) {\n finalURL = options.pathSerializer(finalURL, options.params.path);\n }\n let search = options.querySerializer(options.params.query ?? {});\n if (search.startsWith(\"?\")) {\n search = search.substring(1);\n }\n if (search) {\n finalURL += `?${search}`;\n }\n return finalURL;\n}\nfunction mergeHeaders(...allHeaders) {\n const finalHeaders = new Headers();\n for (const h of allHeaders) {\n if (!h || typeof h !== \"object\") {\n continue;\n }\n const iterator = h instanceof Headers ? h.entries() : Object.entries(h);\n for (const [k, v] of iterator) {\n if (v === null) {\n finalHeaders.delete(k);\n } else if (Array.isArray(v)) {\n for (const v2 of v) {\n finalHeaders.append(k, v2);\n }\n } else if (v !== void 0) {\n finalHeaders.set(k, v);\n }\n }\n }\n return finalHeaders;\n}\nfunction removeTrailingSlash(url) {\n if (url.endsWith(\"/\")) {\n return url.substring(0, url.length - 1);\n }\n return url;\n}\n\nexport { createFinalURL, createPathBasedClient, createQuerySerializer, createClient as default, defaultBodySerializer, defaultPathSerializer, mergeHeaders, randomID, removeTrailingSlash, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, wrapAsPathBasedClient };\n//# sourceMappingURL=index.mjs.map\n","const NAVIGATION_MENU_SLOT_CONFIG = {\n header: {\n title: 'Header',\n aliases: ['Header Menu'],\n },\n footer: {\n title: 'Footer',\n aliases: ['Footer Links', 'Legal Links'],\n },\n} as const;\n\nexport type NavigationMenuSlot = keyof typeof NAVIGATION_MENU_SLOT_CONFIG;\n\nfunction normalizeNavigationToken(value: string): string {\n return value.trim().toLowerCase().replace(/\\s+/g, ' ');\n}\n\nexport function getNavigationMenuCanonicalTitle(slot: NavigationMenuSlot): string {\n return NAVIGATION_MENU_SLOT_CONFIG[slot].title;\n}\n\nexport function getNavigationMenuTitles(slot: NavigationMenuSlot): string[] {\n const config = NAVIGATION_MENU_SLOT_CONFIG[slot];\n return [config.title, ...config.aliases];\n}\n\nexport function isNavigationMenuSlot(value: string): value is NavigationMenuSlot {\n return value in NAVIGATION_MENU_SLOT_CONFIG;\n}\n\nexport function resolveNavigationMenuSlot(value: string | null | undefined): NavigationMenuSlot | null {\n if (!value) return null;\n\n const normalizedValue = normalizeNavigationToken(value);\n for (const slot of Object.keys(NAVIGATION_MENU_SLOT_CONFIG) as NavigationMenuSlot[]) {\n const candidates = [slot, ...getNavigationMenuTitles(slot)];\n if (candidates.some((candidate) => normalizeNavigationToken(candidate) === normalizedValue)) {\n return slot;\n }\n }\n\n return null;\n}\n\nexport function isSystemNavigationMenuTitle(value: string | null | undefined): boolean {\n return resolveNavigationMenuSlot(value) !== null;\n}\n\nexport const NAVIGATION_MENU_SLOTS = Object.keys(NAVIGATION_MENU_SLOT_CONFIG) as NavigationMenuSlot[];\n","var _a;\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const ratio = val / step;\n const roundedRatio = Math.round(ratio);\n // Use a relative epsilon scaled to the magnitude of the result\n const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);\n if (Math.abs(ratio - roundedRatio) < tolerance)\n return 0;\n return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n // Skip the probe under `jitless`: strict CSPs report the caught `new Function`\n // as a `securitypolicyviolation` even though the throw is swallowed.\n if (globalConfig.jitless) {\n return false;\n }\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n if (o instanceof Map)\n return new Map(o);\n if (o instanceof Set)\n return new Set(o);\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n \"string\",\n \"number\",\n \"bigint\",\n \"boolean\",\n \"symbol\",\n \"undefined\",\n]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n if (a._zod.def.checks?.length) {\n throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n }\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: b._zod.def.checks ?? [],\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined).\n// Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue === false) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;\n rest.path ?? (rest.path = []);\n rest.message = message;\n if (ctx?.reportInput) {\n rest.input = _input;\n }\n return rest;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error, path = []) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _parseAsync(_Err)(schema, value, _ctx);\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emoji = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^[A-Za-z0-9_-]*$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)\n// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// const dateSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\nexport const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const time = timeSource({ precision: args.precision });\n const opts = [\"Z\"];\n if (args.local)\n opts.push(\"\");\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n const timeRegex = `${time}(?:${opts.join(\"|\")})`;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n if (def.value < curr) {\n if (def.inclusive)\n bag.maximum = def.value;\n else\n bag.exclusiveMaximum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n if (def.value > curr) {\n if (def.inclusive)\n bag.minimum = def.value;\n else\n bag.exclusiveMinimum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n var _a;\n (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n });\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n if (isInt)\n bag.pattern = regexes.integer;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.size;\n bag.maximum = def.size;\n bag.size = def.size;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.length;\n bag.maximum = def.length;\n bag.length = def.length;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n if (def.pattern) {\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(def.pattern);\n }\n });\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.mime = def.mime;\n });\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export class Doc {\n constructor(args = []) {\n this.content = [];\n this.indent = 0;\n if (this)\n this.args = args;\n }\n indented(fn) {\n this.indent += 1;\n fn(this);\n this.indent -= 1;\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const args = this?.args;\n const content = this?.content ?? [``];\n const lines = [...content.map((x) => ` ${x}`)];\n // console.log(lines.join(\"\\n\"));\n return new F(...args, lines.join(\"\\n\"));\n }\n}\n","export const version = {\n major: 4,\n minor: 4,\n patch: 3,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync, safeParse, safeParseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const checks = [...(inst._zod.def.checks ?? [])];\n // if inst is itself a checks.$ZodCheck, run it as a check\n if (inst._zod.traits.has(\"$ZodCheck\")) {\n checks.unshift(inst);\n }\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer\n // inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (util.explicitlyAborted(payload))\n continue;\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary\n // initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n // Lazy initialize ~standard to avoid creating objects for every schema\n util.defineLazy(inst, \"~standard\", () => ({\n validate: (value) => {\n try {\n const r = safeParse(inst, value);\n return r.success ? { value: r.data } : { issues: r.error?.issues };\n }\n catch (_) {\n return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n }\n },\n vendor: \"zod\",\n version: 1,\n }));\n});\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n // When normalize is off, require :// for http/https URLs\n // This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source) {\n if (!/^https?:\\/\\//i.test(trimmed)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid URL format\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n }\n // @ts-ignore\n const url = new URL(trimmed);\n if (def.hostname) {\n def.hostname.lastIndex = 0;\n if (!def.hostname.test(url.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n if (def.protocol) {\n def.protocol.lastIndex = 0;\n if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n // Set the output value based on normalize flag\n if (def.normalize) {\n // Use normalized URL\n payload.value = url.href;\n }\n else {\n // Preserve the original input (trimmed)\n payload.value = trimmed;\n }\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.nanoid);\n $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv4`;\n});\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv6`;\n inst._zod.check = (payload) => {\n try {\n // @ts-ignore\n new URL(`http://[${payload.value}]`);\n // return;\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n const parts = payload.value.split(\"/\");\n try {\n if (parts.length !== 2)\n throw new Error();\n const [address, prefix] = parts;\n if (!prefix)\n throw new Error();\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n throw new Error();\n if (prefixNum < 0 || prefixNum > 128)\n throw new Error();\n // @ts-ignore\n new URL(`http://[${address}]`);\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n // atob ignores whitespace, so reject it up front.\n if (/\\s/.test(data))\n return false;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64\";\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64URL(data) {\n if (!regexes.base64url.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64url);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64url\";\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? \"Infinity\"\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = Array(input.length);\n const proms = [];\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {\n const isPresent = key in input;\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (isOptionalIn && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && !isOptionalIn) {\n if (!result.issues.length) {\n final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [key],\n });\n }\n return;\n }\n if (result.value === undefined) {\n if (isPresent) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n for (const k of keys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n keys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const isOptionalIn = _catchall.optin === \"optional\";\n const isOptionalOut = _catchall.optout === \"optional\";\n for (const key in input) {\n // skip __proto__ so it can't replace the result prototype via the\n // assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n if (keySet.has(key))\n continue;\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n // const sh = def.shape;\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n if (!desc?.get) {\n const sh = def.shape;\n Object.defineProperty(def, \"shape\", {\n get: () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", {\n value: newSh,\n });\n return newSh;\n },\n });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazy(inst._zod, \"propValues\", () => {\n const shape = def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n propValues[key] ?? (propValues[key] = new Set());\n for (const v of field.values)\n propValues[key].add(v);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = {};\n const proms = [];\n const shape = value.shape;\n for (const key of value.keys) {\n const el = shape[key];\n const isOptionalIn = el._zod.optin === \"optional\";\n const isOptionalOut = el._zod.optout === \"optional\";\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const generateFastpass = (shape) => {\n const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n const normalized = _normalized.value;\n const parseStr = (key) => {\n const k = util.esc(key);\n return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n };\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.keys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(`const newResult = {};`);\n for (const key of normalized.keys) {\n const id = ids[key];\n const k = util.esc(key);\n const schema = shape[key];\n const isOptionalIn = schema?._zod?.optin === \"optional\";\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(key)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys\n doc.write(`\n if (${id}.issues.length) {\n if (${k} in input) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${k} in input;\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n if (!${id}_present && !${id}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${k}]\n });\n }\n\n if (${id}_present) {\n if (${id}.value === undefined) {\n newResult[${k}] = undefined;\n } else {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n const fn = doc.compile();\n return (payload, ctx) => fn(shape, payload, ctx);\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"values\", () => {\n if (def.options.every((o) => o._zod.values)) {\n return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n if (def.options.every((o) => o._zod.pattern)) {\n const patterns = def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const successes = results.filter((r) => r.issues.length === 0);\n if (successes.length === 1) {\n final.value = successes[0].value;\n return final;\n }\n if (successes.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazy(inst._zod, \"propValues\", () => {\n const propValues = {};\n for (const option of def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const [k, v] of Object.entries(pv)) {\n if (!propValues[k])\n propValues[k] = new Set();\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n return propValues;\n });\n const disc = util.cached(() => {\n const opts = def.options;\n const map = new Map();\n for (const o of opts) {\n const values = o._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n for (const v of values) {\n if (map.has(v)) {\n throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n }\n map.set(v, o);\n }\n }\n return map;\n });\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const opt = disc.value.get(input?.[def.discriminator]);\n if (opt) {\n return opt._zod.run(payload, ctx);\n }\n // Fall back to union matching when the fast discriminator path fails:\n // - explicitly enabled via unionFallback, or\n // - during backward direction (encode), since codec-based discriminators\n // have different values in forward vs backward directions\n if (def.unionFallback || ctx.direction === \"backward\") {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n options: Array.from(disc.value.keys()),\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nfunction mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) report each key as unrecognized\n const unrecKeys = new Map();\n let unrecIssue;\n for (const iss of left.issues) {\n if (iss.code === \"unrecognized_keys\") {\n unrecIssue ?? (unrecIssue = iss);\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).l = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n for (const iss of right.issues) {\n if (iss.code === \"unrecognized_keys\") {\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).r = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n // Report only keys unrecognized by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length && unrecIssue) {\n result.issues.push({ ...unrecIssue, keys: bothKeys });\n }\n if (util.aborted(result))\n return result;\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = [];\n const proms = [];\n const optinStart = getTupleOptStart(items, \"optin\");\n const optoutStart = getTupleOptStart(items, \"optout\");\n if (!def.rest) {\n if (input.length < optinStart) {\n payload.issues.push({\n code: \"too_small\",\n minimum: optinStart,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n if (input.length > items.length) {\n payload.issues.push({\n code: \"too_big\",\n maximum: items.length,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n }\n }\n // Run every item in parallel, collecting results into an indexed\n // array. The post-processing in `handleTupleResults` walks them in\n // order so it can decide whether an absent optional-output error can\n // truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n for (let i = 0; i < items.length; i++) {\n const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((rr) => {\n itemResults[i] = rr;\n }));\n }\n else {\n itemResults[i] = r;\n }\n }\n if (def.rest) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n }\n return handleTupleResults(itemResults, payload, items, input, optoutStart);\n };\n});\nfunction getTupleOptStart(items, key) {\n for (let i = items.length - 1; i >= 0; i--) {\n if (items[i]._zod[key] !== \"optional\")\n return i + 1;\n }\n return 0;\n}\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional\n // rule, but only after `optoutStart`: the first index where the output\n // tuple tail can be absent.\n for (let i = 0; i < items.length; i++) {\n const r = itemResults[i];\n const isPresent = i < input.length;\n if (r.issues.length) {\n if (!isPresent && i >= optoutStart) {\n final.value.length = i;\n break;\n }\n final.issues.push(...util.prefixIssues(i, r.issues));\n }\n final.value[i] = r.value;\n }\n // Drop trailing slots that produced `undefined` for absent input\n // (the array analog of an absent optional key on an object). The\n // `i >= input.length` floor is critical: an explicit `undefined`\n // *inside* the input must be preserved even when the schema is\n // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n // explicit undefined value).\n for (let i = final.value.length - 1; i >= input.length; i--) {\n if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n final.value.length = i;\n }\n else {\n break;\n }\n }\n return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n const values = def.keyType._zod.values;\n if (values) {\n payload.value = {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n continue;\n }\n const outKey = keyResult.value;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n });\n }\n }\n else {\n payload.value = {};\n // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key))\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key)\n // This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = new Map();\n for (const [key, value] of input) {\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = new Set();\n for (const item of input) {\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n inst._zod.pattern = new RegExp(`^(${values\n .filter((k) => util.propertyKeyTypes.has(typeof k))\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n if (def.values.length === 0) {\n throw new Error(\"Cannot create literal schema with no valid values\");\n }\n const values = new Set(def.values);\n inst._zod.values = values;\n inst._zod.pattern = new RegExp(`^(${def.values\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n payload.fallback = true;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n payload.fallback = true;\n return payload;\n };\n});\nfunction handleOptionalResult(result, input) {\n if (input === undefined && (result.issues.length || result.fallback)) {\n return { issues: [], value: undefined };\n }\n return result;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (def.innerType._zod.optin === \"optional\") {\n const input = payload.value;\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise)\n return result.then((r) => handleOptionalResult(r, input));\n return handleOptionalResult(result, input);\n }\n if (payload.value === undefined) {\n return payload;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"pattern\", () => def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => {\n const v = def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n payload.fallback = true;\n }\n return payload;\n });\n }\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n payload.fallback = true;\n }\n return payload;\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n if (left.issues.length) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType?._zod?.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n payload.value = Object.freeze(payload.value);\n return payload;\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n if (!part._zod.pattern) {\n // if (!source)\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n if (!source)\n throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n regexParts.push(source.slice(start, end));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._def = def;\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n return function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n };\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n };\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // Cache the resolved inner type on the shared `def` so all clones of this\n // lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance,\n // preserving identity for cycle detection on recursive schemas.\n util.defineLazy(inst._zod, \"innerType\", () => {\n const d = def;\n if (!d._cachedInner)\n d._cachedInner = def.getter();\n return d._cachedInner;\n });\n util.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType?._zod?.pattern);\n util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType?._zod?.propValues);\n util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType?._zod?.optin ?? undefined);\n util.defineLazy(inst._zod, \"optout\", () => inst._zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","var _a;\nexport const $output = Symbol(\"ZodOutput\");\nexport const $input = Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class({\n type: \"string\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class({\n type: \"string\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class({\n type: \"number\",\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class({\n type: \"number\",\n coerce: true,\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n }, params);\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n ...util.normalizeParams(_params),\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import { globalRegistry } from \"./registries.js\";\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n external: params?.external ?? undefined,\n };\n}\nexport function process(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n process(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n Object.assign(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && \"_prefault\" in result.schema)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema\n // defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes\n // multiple schemas map to the same seen object.\n // e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${id}` };\n }\n if (entry[1] === root) {\n return { ref: \"#\" };\n }\n // self-contained schema\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + defId };\n };\n // stored cached version in `def` property\n // remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema\n // or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/<root>` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n // biome-ignore lint:\n continue;\n }\n }\n }\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n Object.assign(schema, refSchema);\n }\n // restore child's own properties (child wins)\n Object.assign(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema\n // This handles cases like: readonly().meta({id}).describe()\n // where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n Object.assign(result, root.def ?? root.schema);\n // The `id` in `.meta()` is a Zod-specific registration tag used to extract\n // schemas into $defs — it is not user-facing JSON Schema metadata. Strip it\n // from the output body where it would otherwise leak. The id is preserved\n // implicitly via the $defs key (and via $ref paths).\n const rootMetaId = ctx.metadataRegistry.get(schema)?.id;\n if (rootMetaId !== undefined && result.id === rootMetaId)\n delete result.id;\n // build defs object\n const defs = ctx.external?.defs ?? {};\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n if (seen.def.id === seen.defId)\n delete seen.def.id;\n defs[seen.defId] = seen.def;\n }\n }\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed\n // each call to finalize() is functionally independent\n // though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n if (_schema._zod.traits.has(\"$ZodCodec\"))\n return true;\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\nimport { getEnumValues } from \"./util.js\";\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding } = schema._zod\n .bag;\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // JSON Schema format: \"time\" requires a full time with offset or Z\n // z.iso.time() does not include timezone information, so format: \"time\" should never be used\n if (format === \"time\") {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const regexes = [...patterns];\n if (regexes.length === 1)\n json.pattern = regexes[0].source;\n else if (regexes.length > 1) {\n json.allOf = [\n ...regexes.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n if (typeof format === \"string\" && format.includes(\"int\"))\n json.type = \"integer\";\n else\n json.type = \"number\";\n // when both minimum and exclusiveMinimum exist, pick the more restrictive one\n const exMin = typeof exclusiveMinimum === \"number\" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);\n const exMax = typeof exclusiveMaximum === \"number\" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);\n const legacy = ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\";\n if (exMin) {\n if (legacy) {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n else if (typeof minimum === \"number\") {\n json.minimum = minimum;\n }\n if (exMax) {\n if (legacy) {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n else if (typeof maximum === \"number\") {\n json.maximum = maximum;\n }\n if (typeof multipleOf === \"number\")\n json.multipleOf = multipleOf;\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt cannot be represented in JSON Schema\");\n }\n};\nexport const symbolProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Symbols cannot be represented in JSON Schema\");\n }\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Undefined cannot be represented in JSON Schema\");\n }\n};\nexport const voidProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Void cannot be represented in JSON Schema\");\n }\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Date cannot be represented in JSON Schema\");\n }\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, _params) => {\n const def = schema._zod.def;\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Literal `undefined` cannot be represented in JSON Schema\");\n }\n else {\n // do not add to vals\n }\n }\n else if (typeof val === \"bigint\") {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt literals cannot be represented in JSON Schema\");\n }\n else {\n vals.push(Number(val));\n }\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"NaN cannot be represented in JSON Schema\");\n }\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const file = {\n type: \"string\",\n format: \"binary\",\n contentEncoding: \"binary\",\n };\n const { minimum, maximum, mime } = schema._zod.bag;\n if (minimum !== undefined)\n file.minLength = minimum;\n if (maximum !== undefined)\n file.maxLength = maximum;\n if (mime) {\n if (mime.length === 1) {\n file.contentMediaType = mime[0];\n Object.assign(_json, file);\n }\n else {\n Object.assign(_json, file); // shared props at root\n _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs\n }\n }\n else {\n Object.assign(_json, file);\n }\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Custom types cannot be represented in JSON Schema\");\n }\n};\nexport const functionProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Function types cannot be represented in JSON Schema\");\n }\n};\nexport const transformProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Transforms cannot be represented in JSON Schema\");\n }\n};\nexport const mapProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Map cannot be represented in JSON Schema\");\n }\n};\nexport const setProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Set cannot be represented in JSON Schema\");\n }\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = process(def.element, ctx, {\n ...params,\n path: [...params.path, \"items\"],\n });\n};\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n json.properties = {};\n const shape = def.shape;\n for (const key in shape) {\n json.properties[key] = process(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n });\n }\n // required keys\n const allKeys = new Set(Object.keys(shape));\n const requiredKeys = new Set([...allKeys].filter((key) => {\n const v = def.shape[key]._zod;\n if (ctx.io === \"input\") {\n return v.optin === undefined;\n }\n else {\n return v.optout === undefined;\n }\n }));\n if (requiredKeys.size > 0) {\n json.required = Array.from(requiredKeys);\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = process(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches)\n // This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = process(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = process(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? process(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (rest) {\n json.items = rest;\n }\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n json.minItems = prefixItems.length;\n if (!rest) {\n json.maxItems = prefixItems.length;\n }\n }\n else {\n json.items = prefixItems;\n if (rest) {\n json.additionalItems = rest;\n }\n }\n // length\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties\n // This correctly represents \"only validate keys matching the pattern\" semantics\n // and composes well with allOf (intersections)\n const keyType = def.keyType;\n const keyBag = keyType._zod.bag;\n const patterns = keyBag?.patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n json.patternProperties[pattern.source] = valueSchema;\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = process(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n }\n json.additionalProperties = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n if (keyValues) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues;\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.default = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io === \"input\")\n json._prefault = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n throw new Error(\"Dynamic catch values are not supported in JSON Schema\");\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const inIsTransform = def.in._zod.traits.has(\"$ZodTransform\");\n const innerType = ctx.io === \"input\" ? (inIsTransform ? def.out : def.in) : def.out;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n process(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n schemas[key] = finalize(ctx, schema);\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n process(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function datetime(params) {\n return core._isoDateTime(ZodISODateTime, params);\n}\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function date(params) {\n return core._isoDate(ZodISODate, params);\n}\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function time(params) {\n return core._isoTime(ZodISOTime, params);\n}\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function duration(params) {\n return core._isoDuration(ZodISODuration, params);\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n Object.defineProperties(inst, {\n format: {\n value: (mapper) => core.formatError(inst, mapper),\n // enumerable: false,\n },\n flatten: {\n value: (mapper) => core.flattenError(inst, mapper),\n // enumerable: false,\n },\n addIssue: {\n value: (issue) => {\n inst.issues.push(issue);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n addIssues: {\n value: (issues) => {\n inst.issues.push(...issues);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n isEmpty: {\n get() {\n return inst.issues.length === 0;\n },\n // enumerable: false,\n },\n });\n // Object.defineProperty(inst, \"isEmpty\", {\n // get() {\n // return inst.issues.length === 0;\n // },\n // });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport * as checks from \"./checks.js\";\nimport * as iso from \"./iso.js\";\nimport * as parse from \"./parse.js\";\n// Lazy-bind builder methods.\n//\n// Builder methods (`.optional`, `.array`, `.refine`, ...) live as\n// non-enumerable getters on each concrete schema constructor's\n// prototype. On first access from an instance the getter allocates\n// `fn.bind(this)` and caches it as an own property on that instance,\n// so detached usage (`const m = schema.optional; m()`) still works\n// and the per-instance allocation only happens for methods actually\n// touched.\n//\n// One install per (prototype, group), memoized by `_installedGroups`.\nconst _installedGroups = /* @__PURE__ */ new WeakMap();\nfunction _installLazyMethods(inst, group, methods) {\n const proto = Object.getPrototypeOf(inst);\n let installed = _installedGroups.get(proto);\n if (!installed) {\n installed = new Set();\n _installedGroups.set(proto, installed);\n }\n if (installed.has(group))\n return;\n installed.add(group);\n for (const key in methods) {\n const fn = methods[key];\n Object.defineProperty(proto, key, {\n configurable: true,\n enumerable: false,\n get() {\n const bound = fn.bind(this);\n Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n enumerable: true,\n value: bound,\n });\n return bound;\n },\n set(v) {\n Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n enumerable: true,\n value: v,\n });\n },\n });\n }\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n core.$ZodType.init(inst, def);\n Object.assign(inst[\"~standard\"], {\n jsonSchema: {\n input: createStandardJSONSchemaMethod(inst, \"input\"),\n output: createStandardJSONSchemaMethod(inst, \"output\"),\n },\n });\n inst.toJSONSchema = createToJSONSchemaMethod(inst, {});\n inst.def = def;\n inst.type = def.type;\n Object.defineProperty(inst, \"_def\", { value: def });\n // Parse-family is intentionally kept as per-instance closures: these are\n // the hot path AND the most-detached methods (`arr.map(schema.parse)`,\n // `const { parse } = schema`, etc.). Eager closures here mean callers pay\n // ~12 closure allocations per schema but get monomorphic call sites and\n // detached usage that \"just works\".\n inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n inst.spa = inst.safeParseAsync;\n inst.encode = (data, params) => parse.encode(inst, data, params);\n inst.decode = (data, params) => parse.decode(inst, data, params);\n inst.encodeAsync = async (data, params) => parse.encodeAsync(inst, data, params);\n inst.decodeAsync = async (data, params) => parse.decodeAsync(inst, data, params);\n inst.safeEncode = (data, params) => parse.safeEncode(inst, data, params);\n inst.safeDecode = (data, params) => parse.safeDecode(inst, data, params);\n inst.safeEncodeAsync = async (data, params) => parse.safeEncodeAsync(inst, data, params);\n inst.safeDecodeAsync = async (data, params) => parse.safeDecodeAsync(inst, data, params);\n // All builder methods are placed on the internal prototype as lazy-bind\n // getters. On first access per-instance, a bound thunk is allocated and\n // cached as an own property; subsequent accesses skip the getter. This\n // means: no per-instance allocation for unused methods, full\n // detachability preserved (`const m = schema.optional; m()` works), and\n // shared underlying function references across all instances.\n _installLazyMethods(inst, \"ZodType\", {\n check(...chks) {\n const def = this.def;\n return this.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...chks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), { parent: true });\n },\n with(...chks) {\n return this.check(...chks);\n },\n clone(def, params) {\n return core.clone(this, def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n refine(check, params) {\n return this.check(refine(check, params));\n },\n superRefine(refinement, params) {\n return this.check(superRefine(refinement, params));\n },\n overwrite(fn) {\n return this.check(checks.overwrite(fn));\n },\n optional() {\n return optional(this);\n },\n exactOptional() {\n return exactOptional(this);\n },\n nullable() {\n return nullable(this);\n },\n nullish() {\n return optional(nullable(this));\n },\n nonoptional(params) {\n return nonoptional(this, params);\n },\n array() {\n return array(this);\n },\n or(arg) {\n return union([this, arg]);\n },\n and(arg) {\n return intersection(this, arg);\n },\n transform(tx) {\n return pipe(this, transform(tx));\n },\n default(d) {\n return _default(this, d);\n },\n prefault(d) {\n return prefault(this, d);\n },\n catch(params) {\n return _catch(this, params);\n },\n pipe(target) {\n return pipe(this, target);\n },\n readonly() {\n return readonly(this);\n },\n describe(description) {\n const cl = this.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n },\n meta(...args) {\n // overloaded: meta() returns the registered metadata, meta(data)\n // returns a clone with `data` registered. The mapped type picks\n // up the second overload, so we accept variadic any-args and\n // return `any` to satisfy both at runtime.\n if (args.length === 0)\n return core.globalRegistry.get(this);\n const cl = this.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n },\n isOptional() {\n return this.safeParse(undefined).success;\n },\n isNullable() {\n return this.safeParse(null).success;\n },\n apply(fn) {\n return fn(this);\n },\n });\n Object.defineProperty(inst, \"description\", {\n get() {\n return core.globalRegistry.get(inst)?.description;\n },\n configurable: true,\n });\n return inst;\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n const bag = inst._zod.bag;\n inst.format = bag.format ?? null;\n inst.minLength = bag.minimum ?? null;\n inst.maxLength = bag.maximum ?? null;\n _installLazyMethods(inst, \"_ZodString\", {\n regex(...args) {\n return this.check(checks.regex(...args));\n },\n includes(...args) {\n return this.check(checks.includes(...args));\n },\n startsWith(...args) {\n return this.check(checks.startsWith(...args));\n },\n endsWith(...args) {\n return this.check(checks.endsWith(...args));\n },\n min(...args) {\n return this.check(checks.minLength(...args));\n },\n max(...args) {\n return this.check(checks.maxLength(...args));\n },\n length(...args) {\n return this.check(checks.length(...args));\n },\n nonempty(...args) {\n return this.check(checks.minLength(1, ...args));\n },\n lowercase(params) {\n return this.check(checks.lowercase(params));\n },\n uppercase(params) {\n return this.check(checks.uppercase(params));\n },\n trim() {\n return this.check(checks.trim());\n },\n normalize(...args) {\n return this.check(checks.normalize(...args));\n },\n toLowerCase() {\n return this.check(checks.toLowerCase());\n },\n toUpperCase() {\n return this.check(checks.toUpperCase());\n },\n slugify() {\n return this.check(checks.slugify());\n },\n });\n});\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n inst.email = (params) => inst.check(core._email(ZodEmail, params));\n inst.url = (params) => inst.check(core._url(ZodURL, params));\n inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params));\n inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params));\n inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params));\n inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params));\n inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params));\n inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params));\n inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params));\n inst.ulid = (params) => inst.check(core._ulid(ZodULID, params));\n inst.base64 = (params) => inst.check(core._base64(ZodBase64, params));\n inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params));\n inst.xid = (params) => inst.check(core._xid(ZodXID, params));\n inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params));\n inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params));\n inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params));\n inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params));\n inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params));\n inst.e164 = (params) => inst.check(core._e164(ZodE164, params));\n // iso\n inst.datetime = (params) => inst.check(iso.datetime(params));\n inst.date = (params) => inst.check(iso.date(params));\n inst.time = (params) => inst.check(iso.time(params));\n inst.duration = (params) => inst.check(iso.duration(params));\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: core.regexes.httpProtocol,\n hostname: core.regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", core.regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", core.regexes.hex, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n _installLazyMethods(inst, \"ZodNumber\", {\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n int(params) {\n return this.check(int(params));\n },\n safe(params) {\n return this.check(int(params));\n },\n positive(params) {\n return this.check(checks.gt(0, params));\n },\n nonnegative(params) {\n return this.check(checks.gte(0, params));\n },\n negative(params) {\n return this.check(checks.lt(0, params));\n },\n nonpositive(params) {\n return this.check(checks.lte(0, params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n step(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n finite() {\n return this;\n },\n });\n const bag = inst._zod.bag;\n inst.minValue =\n Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;\n inst.maxValue =\n Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;\n inst.isInt = (bag.format ?? \"\").includes(\"int\") || Number.isSafeInteger(bag.multipleOf ?? 0.5);\n inst.isFinite = true;\n inst.format = bag.format ?? null;\n});\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.positive = (params) => inst.check(checks.gt(BigInt(0), params));\n inst.negative = (params) => inst.check(checks.lt(BigInt(0), params));\n inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params));\n inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n const bag = inst._zod.bag;\n inst.minValue = bag.minimum ?? null;\n inst.maxValue = bag.maximum ?? null;\n inst.format = bag.format ?? null;\n});\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\n// int64\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\n// uint64\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n const c = inst._zod.bag;\n inst.minDate = c.minimum ? new Date(c.minimum) : null;\n inst.maxDate = c.maximum ? new Date(c.maximum) : null;\n});\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n _installLazyMethods(inst, \"ZodArray\", {\n min(n, params) {\n return this.check(checks.minLength(n, params));\n },\n nonempty(params) {\n return this.check(checks.minLength(1, params));\n },\n max(n, params) {\n return this.check(checks.maxLength(n, params));\n },\n length(n, params) {\n return this.check(checks.length(n, params));\n },\n unwrap() {\n return this.element;\n },\n });\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.defineLazy(inst, \"shape\", () => {\n return def.shape;\n });\n _installLazyMethods(inst, \"ZodObject\", {\n keyof() {\n return _enum(Object.keys(this._zod.def.shape));\n },\n catchall(catchall) {\n return this.clone({ ...this._zod.def, catchall: catchall });\n },\n passthrough() {\n return this.clone({ ...this._zod.def, catchall: unknown() });\n },\n loose() {\n return this.clone({ ...this._zod.def, catchall: unknown() });\n },\n strict() {\n return this.clone({ ...this._zod.def, catchall: never() });\n },\n strip() {\n return this.clone({ ...this._zod.def, catchall: undefined });\n },\n extend(incoming) {\n return util.extend(this, incoming);\n },\n safeExtend(incoming) {\n return util.safeExtend(this, incoming);\n },\n merge(other) {\n return util.merge(this, other);\n },\n pick(mask) {\n return util.pick(this, mask);\n },\n omit(mask) {\n return util.omit(this, mask);\n },\n partial(...args) {\n return util.partial(ZodOptional, this, args[0]);\n },\n required(...args) {\n return util.required(ZodNonOptional, this, args[0]);\n },\n });\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n inst.rest = (rest) => inst.clone({\n ...inst._zod.def,\n rest: rest,\n });\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n const k = core.clone(keyType);\n k._zod.values = undefined;\n return new ZodRecord({\n type: \"record\",\n keyType: k,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n inst.options = Object.values(def.entries);\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n payload.fallback = true;\n return payload;\n });\n }\n payload.value = output;\n payload.fallback = true;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodPreprocess = /*@__PURE__*/ core.$constructor(\"ZodPreprocess\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodPreprocess.init(inst, def);\n});\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodCustom({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\nexport function preprocess(fn, schema) {\n return new ZodPreprocess({\n type: \"pipe\",\n in: transform(fn),\n out: schema,\n });\n}\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport function string(params) {\n return core._coercedString(schemas.ZodString, params);\n}\nexport function number(params) {\n return core._coercedNumber(schemas.ZodNumber, params);\n}\nexport function boolean(params) {\n return core._coercedBoolean(schemas.ZodBoolean, params);\n}\nexport function bigint(params) {\n return core._coercedBigint(schemas.ZodBigInt, params);\n}\nexport function date(params) {\n return core._coercedDate(schemas.ZodDate, params);\n}\n","import * as z from 'zod/v4';\n\nexport const EmailMarketingConsentBasisSchema = z.enum(['CONSENT', 'SOFT_OPT_IN', 'TRANSACTIONAL_ONLY', 'UNKNOWN']);\nexport const EmailMarketingSuppressionReasonSchema = z.enum(['MANUAL_UNSUB', 'ONE_CLICK_UNSUB', 'HARD_BOUNCE', 'COMPLAINT', 'ADMIN_BLOCK']);\nexport const EmailMarketingCampaignTypeSchema = z.enum(['BROADCAST', 'AUTOMATION']);\nexport const EmailMarketingAutomationTriggerSchema = z.enum([\n 'ABANDONED_CART',\n 'POST_PURCHASE',\n 'WELCOME',\n 'WIN_BACK',\n 'RE_ENGAGEMENT',\n 'TAG_ADDED',\n]);\n\nexport const EmailMarketingContactCreateSchema = z.object({\n email: z.email(),\n name: z.string().trim().min(1).nullable().optional(),\n customer_id: z.string().uuid().nullable().optional(),\n tags: z.array(z.string().trim().min(1)).default([]),\n consent_basis: EmailMarketingConsentBasisSchema.default('UNKNOWN'),\n source: z.string().trim().min(1).default('dashboard'),\n});\n\nexport const EmailMarketingTemplateCreateSchema = z.object({\n name: z.string().trim().min(1),\n subject: z.string().trim().min(1),\n preheader: z.string().nullable().optional(),\n mjml_source: z.string().trim().min(1),\n builder_project_json: z.record(z.string(), z.unknown()).nullable().optional(),\n thumbnail_url: z.url().nullable().optional(),\n});\n\nexport const EmailMarketingTemplatePreviewSchema = z.object({\n mjml_source: z.string().trim().min(1),\n sample_variables: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const EmailMarketingTemplateTestSendSchema = z.object({\n recipient_email: z.email(),\n sample_variables: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const EmailMarketingSettingsUpdateSchema = z.object({\n marketing_enabled: z.boolean().optional(),\n default_from_name: z.string().trim().min(1).nullable().optional(),\n default_from_email: z.email().nullable().optional(),\n default_reply_to_email: z.email().nullable().optional(),\n physical_address: z.string().trim().min(1).nullable().optional(),\n physical_address_line2: z.string().trim().min(1).nullable().optional(),\n physical_city: z.string().trim().min(1).nullable().optional(),\n physical_postal_code: z.string().trim().min(1).nullable().optional(),\n physical_country: z.string().trim().length(2).nullable().optional(),\n daily_limit: z.number().int().positive().optional(),\n monthly_soft_cap: z.number().int().positive().optional(),\n});\n\nexport const EmailMarketingCampaignCreateSchema = z.object({\n type: EmailMarketingCampaignTypeSchema.default('BROADCAST'),\n name: z.string().trim().min(1),\n subject: z.string().trim().min(1),\n template_id: z.string().uuid(),\n list_id: z.string().uuid().nullable().optional(),\n segment_id: z.string().uuid().nullable().optional(),\n from_name: z.string().trim().min(1),\n from_email: z.email(),\n reply_to_email: z.email().nullable().optional(),\n schedule_at: z.string().datetime().nullable().optional(),\n target_emails: z.array(z.email()).max(0, 'Direct recipient entry is disabled. Use lists or segments built from Shoppex customers and paid order buyers.').default([]),\n idempotency_key: z.string().trim().min(1).nullable().optional(),\n});\n\nexport const EmailMarketingAutomationCreateSchema = z.object({\n name: z.string().trim().min(1),\n subject: z.string().trim().min(1),\n template_id: z.string().uuid(),\n from_name: z.string().trim().min(1),\n from_email: z.email(),\n reply_to_email: z.email().nullable().optional(),\n trigger: EmailMarketingAutomationTriggerSchema,\n delay_seconds: z.number().int().min(0).default(0),\n conditions: z.record(z.string(), z.unknown()).default({}),\n});\n\nexport const EmailMarketingAutomationTriggerEventSchema = z.object({\n trigger: EmailMarketingAutomationTriggerSchema,\n email: z.email(),\n customer_id: z.string().uuid().nullable().optional(),\n name: z.string().trim().min(1).nullable().optional(),\n consent_basis: EmailMarketingConsentBasisSchema.default('UNKNOWN'),\n variables: z.record(z.string(), z.unknown()).default({}),\n idempotency_key: z.string().trim().min(1).nullable().optional(),\n});\n\nexport const EmailMarketingSuppressionCreateSchema = z.object({\n email: z.email(),\n reason: EmailMarketingSuppressionReasonSchema.default('ADMIN_BLOCK'),\n notes: z.string().nullable().optional(),\n});\n\nexport type EmailMarketingContactCreate = z.infer<typeof EmailMarketingContactCreateSchema>;\nexport type EmailMarketingTemplateCreate = z.infer<typeof EmailMarketingTemplateCreateSchema>;\nexport type EmailMarketingTemplatePreview = z.infer<typeof EmailMarketingTemplatePreviewSchema>;\nexport type EmailMarketingTemplateTestSend = z.infer<typeof EmailMarketingTemplateTestSendSchema>;\nexport type EmailMarketingSettingsUpdate = z.infer<typeof EmailMarketingSettingsUpdateSchema>;\nexport type EmailMarketingCampaignCreate = z.infer<typeof EmailMarketingCampaignCreateSchema>;\nexport type EmailMarketingAutomationCreate = z.infer<typeof EmailMarketingAutomationCreateSchema>;\nexport type EmailMarketingAutomationTriggerEvent = z.infer<typeof EmailMarketingAutomationTriggerEventSchema>;\nexport type EmailMarketingSuppressionCreate = z.infer<typeof EmailMarketingSuppressionCreateSchema>;\n","import * as z from 'zod/v4';\n\nexport const COIN_GATEWAY_KEYS = [\n 'BITCOIN',\n 'LITECOIN',\n 'ETHEREUM',\n 'BITCOIN_CASH',\n 'MONERO',\n 'RIPPLE',\n 'TRON',\n 'SOLANA',\n 'POLYGON',\n 'BINANCE_COIN',\n 'CRONOS',\n 'CONCORDIUM',\n 'NANO',\n 'DOGECOIN',\n 'DASH',\n] as const;\n\nexport const CRYPTO_PROVIDER_KEYS = [\n 'NOWPAYMENTS',\n 'CRYPTOMUS',\n 'OXAPAY',\n] as const;\n\nexport const MANAGED_CRYPTO_PROVIDER_KEYS = [\n 'NOWPAYMENTS_WHITELABEL',\n] as const;\n\nexport const GENERIC_STABLECOIN_GATEWAY_FAMILIES = {\n USDT: ['USDT_TRC20', 'USDT_ERC20', 'USDT_BEP20', 'USDT_POLYGON', 'USDT_SOL'],\n USDC: ['USDC_ERC20', 'USDC_TRC20', 'USDC_BEP20', 'USDC_POLYGON', 'USDC_SOL'],\n DAI: ['DAI_ERC20'],\n} as const;\n\nexport const GENERIC_STABLECOIN_GATEWAY_KEYS = Object.keys(\n GENERIC_STABLECOIN_GATEWAY_FAMILIES,\n) as Array<keyof typeof GENERIC_STABLECOIN_GATEWAY_FAMILIES>;\n\nexport const TOKEN_GATEWAY_KEYS = [\n ...GENERIC_STABLECOIN_GATEWAY_FAMILIES.USDT,\n ...GENERIC_STABLECOIN_GATEWAY_FAMILIES.USDC,\n ...GENERIC_STABLECOIN_GATEWAY_FAMILIES.DAI,\n] as const;\n\nexport const CRYPTO_GATEWAY_KEYS = [\n ...COIN_GATEWAY_KEYS,\n ...TOKEN_GATEWAY_KEYS,\n] as const;\n\nexport const LEGACY_CRYPTO_GATEWAY_KEYS = [\n 'BITCOIN_LN',\n] as const;\n\nexport const CRYPTO_PROVIDER_GATEWAY_KEYS = [\n ...CRYPTO_PROVIDER_KEYS,\n ...MANAGED_CRYPTO_PROVIDER_KEYS,\n] as const;\n\nexport const CONCRETE_CRYPTO_GATEWAY_KEYS = [\n ...CRYPTO_GATEWAY_KEYS,\n ...LEGACY_CRYPTO_GATEWAY_KEYS,\n] as const;\n\nexport type CoinGatewayKey = typeof COIN_GATEWAY_KEYS[number];\nexport type TokenGatewayKey = typeof TOKEN_GATEWAY_KEYS[number];\nexport type CryptoGatewayKey = typeof CRYPTO_GATEWAY_KEYS[number];\nexport type LegacyCryptoGatewayKey = typeof LEGACY_CRYPTO_GATEWAY_KEYS[number];\nexport type CryptoProviderKey = typeof CRYPTO_PROVIDER_KEYS[number];\nexport type ManagedCryptoProviderKey = typeof MANAGED_CRYPTO_PROVIDER_KEYS[number];\nexport type CryptoProviderGatewayKey = typeof CRYPTO_PROVIDER_GATEWAY_KEYS[number];\n\nexport const NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX = 'NOWPAYMENTS:' as const;\nexport type NowPaymentsDynamicGatewayKey = `${typeof NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX}${string}`;\n\nconst NOWPAYMENTS_CURRENCY_CODE_PATTERN = /^[A-Z0-9]{2,12}$/;\n\nexport function buildNowPaymentsDynamicGatewayKey(\n currencyCode: string,\n): NowPaymentsDynamicGatewayKey | null {\n const normalizedCode = currencyCode.trim().toUpperCase();\n if (!NOWPAYMENTS_CURRENCY_CODE_PATTERN.test(normalizedCode)) {\n return null;\n }\n\n return `${NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX}${normalizedCode}`;\n}\n\nexport function parseNowPaymentsDynamicGatewayKey(gateway: string): string | null {\n const normalized = gateway.trim().toUpperCase();\n if (!normalized.startsWith(NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX)) {\n return null;\n }\n\n const code = normalized.slice(NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX.length);\n return NOWPAYMENTS_CURRENCY_CODE_PATTERN.test(code) ? code.toLowerCase() : null;\n}\n\nexport function isNowPaymentsDynamicGatewayKey(\n gateway: string,\n): gateway is NowPaymentsDynamicGatewayKey {\n return parseNowPaymentsDynamicGatewayKey(gateway) !== null;\n}\n\nexport const DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS = CRYPTO_GATEWAY_KEYS;\n\nexport const DEFAULT_CRYPTOMUS_CRYPTO_GATEWAY_KEYS = [\n 'BITCOIN',\n 'LITECOIN',\n 'ETHEREUM',\n 'TRON',\n 'SOLANA',\n 'POLYGON',\n 'BINANCE_COIN',\n 'BITCOIN_CASH',\n 'MONERO',\n 'RIPPLE',\n 'DOGECOIN',\n 'USDT_TRC20',\n 'USDT_ERC20',\n 'USDT_BEP20',\n 'USDT_POLYGON',\n 'USDT_SOL',\n 'USDC_ERC20',\n 'USDC_BEP20',\n 'USDC_POLYGON',\n 'DAI_ERC20',\n] as const;\n\nexport const DEFAULT_OXAPAY_CRYPTO_GATEWAY_KEYS = [\n 'BITCOIN',\n 'LITECOIN',\n 'ETHEREUM',\n 'TRON',\n 'SOLANA',\n 'POLYGON',\n 'BINANCE_COIN',\n 'BITCOIN_CASH',\n 'MONERO',\n 'RIPPLE',\n 'DOGECOIN',\n 'USDT_TRC20',\n 'USDT_ERC20',\n 'USDT_BEP20',\n 'USDT_POLYGON',\n 'USDC_ERC20',\n] as const;\n\nexport const DEFAULT_PROVIDER_GATEWAY_SELECTIONS = {\n NOWPAYMENTS: DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS,\n NOWPAYMENTS_WHITELABEL: DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS,\n CRYPTOMUS: DEFAULT_CRYPTOMUS_CRYPTO_GATEWAY_KEYS,\n OXAPAY: DEFAULT_OXAPAY_CRYPTO_GATEWAY_KEYS,\n} as const;\n\nexport const POPULAR_PLATFORM_MANAGED_CRYPTO_GATEWAY_KEYS = [\n 'BITCOIN',\n 'LITECOIN',\n 'ETHEREUM',\n 'USDT_TRC20',\n 'USDT_ERC20',\n] as const;\n\nexport const CHECKOUT_METHOD_ORDER_KEYS = [\n 'STRIPE',\n 'PAYPAL',\n 'PAYPAL_FF',\n 'MOLLIE',\n 'AUTHORIZENET',\n 'NMI',\n 'SQUARE',\n 'SUMUP',\n 'SHOPIFY',\n 'SUBY',\n 'PANDABASE',\n 'STORRIK',\n 'DEBLOMASSI',\n 'SHOPPEXPAY',\n 'MONEYMOTION',\n 'OVGC',\n 'WHOP',\n 'DODO',\n 'MAVERICK',\n 'CASHAPP',\n 'VENMO',\n 'CRYPTO',\n 'CUSTOMER_BALANCE',\n 'MANUAL',\n] as const;\n\n/**\n * Gateway implementations that remain in the codebase but must not be\n * advertised or selectable in merchant and buyer UI.\n */\nexport const RETIRED_UI_PAYMENT_GATEWAY_KEYS = ['SHOPPEXPAY'] as const;\n\nconst RETIRED_UI_PAYMENT_GATEWAY_KEY_SET = new Set<string>(\n RETIRED_UI_PAYMENT_GATEWAY_KEYS,\n);\n\nexport function isRetiredUiPaymentGateway(gateway: string): boolean {\n return RETIRED_UI_PAYMENT_GATEWAY_KEY_SET.has(gateway.trim().toUpperCase());\n}\n\nexport const DEFAULT_PAYPAL_FF_MANAGED_IPN_URL = 'https://paypal-ff.myshoppex.io';\n\nexport type CheckoutMethodOrderKey = typeof CHECKOUT_METHOD_ORDER_KEYS[number];\n\nexport interface StoredPaymentGatewayRow {\n provider?: string | null;\n is_active?: boolean | number | string | null;\n isActive?: boolean | number | string | null;\n external_id?: string | null;\n externalId?: string | null;\n has_credentials?: boolean | number | string | null;\n hasCredentials?: boolean | number | string | null;\n has_settings?: boolean | number | string | null;\n hasSettings?: boolean | number | string | null;\n}\n\nexport interface OxapayCheckoutGatewayInfo {\n gateway_key?: string;\n gatewayKey?: string;\n display_name?: string;\n displayName?: string;\n symbol?: string;\n network?: string;\n network_name?: string | null;\n networkName?: string | null;\n required_confirmations?: number | null;\n requiredConfirmations?: number | null;\n deposit_min?: number | null;\n depositMin?: number | null;\n withdraw_min?: number | null;\n withdrawMin?: number | null;\n withdraw_fee?: number | null;\n withdrawFee?: number | null;\n}\n\nexport interface PaymentGatewaySecretRef {\n set: boolean;\n}\n\nexport interface PaymentGatewayHealth {\n status: 'READY' | 'NEEDS_ATTENTION';\n code?: string;\n message?: string;\n checked_at?: string;\n}\n\nexport interface PaymentGatewayState {\n provider: string;\n type: string;\n enabled: boolean;\n connected: boolean;\n credentials: Record<string, PaymentGatewaySecretRef>;\n public_config: Record<string, unknown>;\n webhook?: Record<string, unknown>;\n health?: PaymentGatewayHealth;\n}\n\nexport type GatewayIntegrationType =\n | 'OAUTH'\n | 'API_KEY'\n | 'SDK'\n | 'LEGACY'\n | 'DIRECT'\n | 'FORWARDING'\n | 'AGGREGATOR';\n\nexport interface NormalizedPaymentGatewayState {\n provider: string;\n id: string;\n type: string;\n name: string;\n enabled: boolean;\n connected: boolean;\n health_status?: 'READY' | 'NEEDS_ATTENTION';\n health_code?: string;\n health_message?: string;\n health_checked_at?: string;\n created_at: string;\n updated_at: string;\n integration_type?: 'SDK' | 'LEGACY';\n config?: Record<string, unknown>;\n}\n\nconst COIN_GATEWAY_KEY_SET = new Set<string>(COIN_GATEWAY_KEYS);\nconst TOKEN_GATEWAY_KEY_SET = new Set<string>(TOKEN_GATEWAY_KEYS);\nconst CRYPTO_GATEWAY_KEY_SET = new Set<string>(CRYPTO_GATEWAY_KEYS);\nconst LEGACY_CRYPTO_GATEWAY_KEY_SET = new Set<string>(LEGACY_CRYPTO_GATEWAY_KEYS);\nconst CRYPTO_PROVIDER_KEY_SET = new Set<string>(CRYPTO_PROVIDER_KEYS);\nconst MANAGED_CRYPTO_PROVIDER_KEY_SET = new Set<string>(MANAGED_CRYPTO_PROVIDER_KEYS);\nconst CRYPTO_PROVIDER_GATEWAY_KEY_SET = new Set<string>(CRYPTO_PROVIDER_GATEWAY_KEYS);\nconst CONCRETE_CRYPTO_GATEWAY_KEY_SET = new Set<string>(CONCRETE_CRYPTO_GATEWAY_KEYS);\nconst GENERIC_STABLECOIN_GATEWAY_KEY_SET = new Set<string>(GENERIC_STABLECOIN_GATEWAY_KEYS);\nconst CHECKOUT_METHOD_ORDER_KEY_SET = new Set<string>(CHECKOUT_METHOD_ORDER_KEYS);\nconst CHECKOUT_METHOD_GROUP_BY_GATEWAY: Record<string, CheckoutMethodOrderKey> = {\n STRIPE: 'STRIPE',\n PAYPAL: 'PAYPAL',\n PAYPAL_FF: 'PAYPAL_FF',\n MOLLIE: 'MOLLIE',\n AUTHORIZENET: 'AUTHORIZENET',\n NMI: 'NMI',\n SQUARE: 'SQUARE',\n SUMUP: 'SUMUP',\n SHOPIFY: 'SHOPIFY',\n SUBY: 'SUBY',\n PANDABASE: 'PANDABASE',\n STORRIK: 'STORRIK',\n DEBLOMASSI: 'DEBLOMASSI',\n SHOPPEXPAY: 'SHOPPEXPAY',\n MONEYMOTION: 'MONEYMOTION',\n OVGC: 'OVGC',\n WHOP: 'WHOP',\n DODO: 'DODO',\n MAVERICK: 'MAVERICK',\n CASH_APP: 'CASHAPP',\n VENMO: 'VENMO',\n CUSTOMER_BALANCE: 'CUSTOMER_BALANCE',\n};\n\nconst LEGACY_GATEWAY_ALIASES: Record<string, string> = {\n CASHAPP: 'CASH_APP',\n PAYPAL_CREDIT_CARD: 'PAYPAL',\n EUTHEREUM: 'ETHEREUM',\n USDT_MATIC: 'USDT_POLYGON',\n USDC_MATIC: 'USDC_POLYGON',\n};\n\nfunction assertUniqueEntries(name: string, values: readonly string[]) {\n if (new Set(values).size !== values.length) {\n throw new Error(`${name} contains duplicate entries`);\n }\n}\n\nassertUniqueEntries('COIN_GATEWAY_KEYS', COIN_GATEWAY_KEYS);\nassertUniqueEntries('TOKEN_GATEWAY_KEYS', TOKEN_GATEWAY_KEYS);\nassertUniqueEntries('CRYPTO_GATEWAY_KEYS', CRYPTO_GATEWAY_KEYS);\nassertUniqueEntries('LEGACY_CRYPTO_GATEWAY_KEYS', LEGACY_CRYPTO_GATEWAY_KEYS);\nassertUniqueEntries('CRYPTO_PROVIDER_KEYS', CRYPTO_PROVIDER_KEYS);\nassertUniqueEntries('MANAGED_CRYPTO_PROVIDER_KEYS', MANAGED_CRYPTO_PROVIDER_KEYS);\nassertUniqueEntries('CRYPTO_PROVIDER_GATEWAY_KEYS', CRYPTO_PROVIDER_GATEWAY_KEYS);\nassertUniqueEntries('DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS', DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS);\nassertUniqueEntries('DEFAULT_CRYPTOMUS_CRYPTO_GATEWAY_KEYS', DEFAULT_CRYPTOMUS_CRYPTO_GATEWAY_KEYS);\nassertUniqueEntries('DEFAULT_OXAPAY_CRYPTO_GATEWAY_KEYS', DEFAULT_OXAPAY_CRYPTO_GATEWAY_KEYS);\n\nfor (const key of CRYPTO_GATEWAY_KEYS) {\n if (!COIN_GATEWAY_KEY_SET.has(key) && !TOKEN_GATEWAY_KEY_SET.has(key)) {\n throw new Error(`CRYPTO_GATEWAY_KEYS contains an unclassified gateway: ${key}`);\n }\n}\n\nexport function parseGatewayList(input: unknown): string[] {\n if (Array.isArray(input)) {\n return input.filter((entry): entry is string => typeof entry === 'string');\n }\n\n if (typeof input !== 'string') {\n return [];\n }\n\n const trimmed = input.trim();\n if (!trimmed) {\n return [];\n }\n\n if (trimmed.startsWith('[') && trimmed.endsWith(']')) {\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n if (Array.isArray(parsed)) {\n return parsed.filter((entry): entry is string => typeof entry === 'string');\n }\n } catch {\n // Fallback to comma-separated parsing.\n }\n }\n\n return trimmed\n .split(',')\n .map((entry) => entry.trim())\n .filter(Boolean);\n}\n\nexport function normalizeGatewayKey(input: string): string {\n const trimmed = input.trim();\n if (!trimmed) {\n return '';\n }\n\n if (/^manual:/i.test(trimmed)) {\n const manualId = trimmed.slice(trimmed.indexOf(':') + 1).trim();\n return manualId ? `MANUAL:${manualId}` : 'MANUAL';\n }\n\n let normalized = trimmed.toUpperCase();\n\n const stablecoinNetworkMatch = normalized.match(/^(USDT|USDC|DAI):([A-Z0-9_]+)$/);\n if (stablecoinNetworkMatch) {\n const [, asset, rawNetwork] = stablecoinNetworkMatch;\n const network = rawNetwork === 'MATIC' ? 'POLYGON' : rawNetwork;\n normalized = `${asset}_${network}`;\n }\n\n return LEGACY_GATEWAY_ALIASES[normalized] ?? normalized;\n}\n\nexport function normalizeGatewayRestrictionValues(values: readonly string[]): string[] {\n const normalized = new Set<string>();\n\n for (const value of values) {\n const gateway = normalizeGatewayKey(value);\n if (gateway) {\n normalized.add(gateway);\n }\n }\n\n return [...normalized];\n}\n\nexport function normalizeGatewayRestrictionInput(input: unknown): string[] | null {\n const normalized = normalizeGatewayRestrictionValues(parseGatewayList(input));\n return normalized.length > 0 ? normalized : null;\n}\n\nexport function isValidProductGatewaySelection(input: string): boolean {\n const normalized = normalizeGatewayKey(input);\n if (!normalized || normalized === 'NULL' || normalized === 'UNDEFINED') {\n return false;\n }\n\n return normalized === 'CUSTOMER_BALANCE'\n || normalized === 'CRYPTO'\n || isFinanceGateway(normalized)\n || isCryptoProviderGatewayKey(normalized)\n || isConcreteCryptoGatewayKey(normalized)\n || isGenericStablecoinGatewayKey(normalized);\n}\n\nexport function findInvalidProductGatewaySelections(input: unknown): string[] {\n return normalizeGatewayRestrictionValues(parseGatewayList(input))\n .filter((gateway) => !isValidProductGatewaySelection(gateway));\n}\n\n/**\n * Canonical persisted product restrictions. External write paths should reject\n * `invalid`; trusted repair/import paths may deliberately keep only `gateways`.\n */\nexport function partitionProductGatewaySelections(input: unknown): {\n gateways: string[];\n invalid: string[];\n} {\n const normalized = normalizeGatewayRestrictionValues(parseGatewayList(input));\n const gateways: string[] = [];\n const invalid: string[] = [];\n\n for (const gateway of normalized) {\n (isValidProductGatewaySelection(gateway) ? gateways : invalid).push(gateway);\n }\n\n return { gateways, invalid };\n}\n\nexport const FINANCE_GATEWAY_KEYS = [\n 'STRIPE', 'PAYPAL', 'PAYPAL_FF', 'SKRILL', 'CASHAPP', 'CASH_APP', 'PERFECT_MONEY',\n 'SQUARE', 'SUMUP', 'SHOPIFY', 'SUBY', 'PANDABASE', 'STORRIK', 'DEBLOMASSI', 'SHOPPEXPAY', 'MONEYMOTION', 'OVGC', 'WHOP',\n 'DODO', 'MAVERICK', 'VENMO', 'MOLLIE', 'AUTHORIZENET', 'NMI',\n] as const;\n\nconst FINANCE_GATEWAY_KEY_SET = new Set<string>(\n FINANCE_GATEWAY_KEYS.map((gateway) => normalizeGatewayKey(gateway)),\n);\n\nexport function isFinanceGateway(gateway: string): boolean {\n const normalized = normalizeGatewayKey(gateway);\n return normalized === 'MANUAL' || normalized.startsWith('MANUAL:') || FINANCE_GATEWAY_KEY_SET.has(normalized);\n}\n\nexport const VALID_PRODUCT_PAYMENT_GATEWAY_RESTRICTION_MODES = ['USE_STORE_DEFAULT', 'CUSTOM'] as const;\n\nexport type ProductPaymentGatewayRestrictionMode =\n (typeof VALID_PRODUCT_PAYMENT_GATEWAY_RESTRICTION_MODES)[number];\n\nexport function normalizeProductPaymentGatewayRestrictionMode(\n value: unknown,\n): ProductPaymentGatewayRestrictionMode {\n return value === 'CUSTOM' ? 'CUSTOM' : 'USE_STORE_DEFAULT';\n}\n\nexport function isProductGatewayRestrictionPublishable(\n mode: unknown,\n gateways: unknown,\n): boolean {\n return normalizeProductPaymentGatewayRestrictionMode(mode) !== 'CUSTOM'\n || normalizeGatewayRestrictionInput(gateways) !== null;\n}\n\nexport function isCoinGateway(gateway: string): gateway is CoinGatewayKey {\n return COIN_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isTokenGateway(gateway: string): gateway is TokenGatewayKey {\n return TOKEN_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isCryptoGateway(gateway: string): gateway is CryptoGatewayKey {\n return CRYPTO_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isProviderKey(gateway: string): gateway is CryptoProviderKey {\n return CRYPTO_PROVIDER_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isManagedCryptoProviderKey(gateway: string): gateway is ManagedCryptoProviderKey {\n return MANAGED_CRYPTO_PROVIDER_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isCryptoProviderGatewayKey(gateway: string): boolean {\n return CRYPTO_PROVIDER_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isGenericStablecoinGatewayKey(gateway: string): boolean {\n return GENERIC_STABLECOIN_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isConcreteCryptoGatewayKey(gateway: string): boolean {\n const normalizedGateway = normalizeGatewayKey(gateway);\n return isCryptoGateway(normalizedGateway)\n || LEGACY_CRYPTO_GATEWAY_KEY_SET.has(normalizedGateway)\n || CONCRETE_CRYPTO_GATEWAY_KEY_SET.has(normalizedGateway)\n || isNowPaymentsDynamicGatewayKey(normalizedGateway);\n}\n\n/**\n * True for anything that resolves to a crypto payment, in every shape a gateway\n * key can take: a concrete coin (`BITCOIN`, `USDT:ERC20`), a generic stablecoin\n * whose chain the buyer still has to choose (`USDT`), and a provider key that\n * expands into a coin list (`OXAPAY`, `NOWPAYMENTS`, `CRYPTOMUS`).\n *\n * Use this — not `isConcreteCryptoGatewayKey` on its own — wherever the question\n * is \"may this be selected without the buyer choosing it?\". Selecting crypto\n * locks an exchange rate against a deposit address, so a caller that only\n * recognises concrete coins lets a provider key through and starts that session\n * anyway. Both halves of that mistake have been shipped before.\n */\nexport function isCryptoPaymentSelection(gateway: string): boolean {\n return isConcreteCryptoGatewayKey(gateway)\n || isGenericStablecoinGatewayKey(gateway)\n || isCryptoProviderGatewayKey(gateway);\n}\n\nexport function getConcreteCryptoGatewaySelections(gateways: Iterable<string>): string[] {\n const selected = new Set<string>();\n\n for (const gateway of gateways) {\n const normalized = normalizeGatewayKey(gateway);\n if (isConcreteCryptoGatewayKey(normalized)) {\n selected.add(normalized);\n }\n }\n\n return [...selected];\n}\n\n/**\n * External labels of crypto payment rails as emitted by the invoice read model\n * (resolveExternalCryptoRailLabel): WHITE_LABEL for managed provider rails and\n * NATIVE for self-hosted BTC/LTC nodes. These are rail labels, not gateway or\n * processor keys.\n */\nexport const CRYPTO_RAIL_GATEWAY_LABELS = ['WHITE_LABEL', 'NATIVE'] as const;\nexport type CryptoRailGatewayLabel = typeof CRYPTO_RAIL_GATEWAY_LABELS[number];\nconst CRYPTO_RAIL_GATEWAY_LABEL_SET = new Set<string>(CRYPTO_RAIL_GATEWAY_LABELS);\n\n/**\n * `PaymentProvider` enum value persisted for the self-hosted crypto rail. The\n * read model emits the 'NATIVE' rail label, while invoice and attempt rows carry\n * the provider value itself — both name the same rail.\n */\nexport const NATIVE_CRYPTO_PROVIDER_KEY = 'NATIVE_CRYPTO' as const;\n\n/** Processor keys persisted on crypto payment attempts (providers plus the NATIVE rail). */\nexport const CRYPTO_PAYMENT_PROCESSOR_KEYS = [...CRYPTO_PROVIDER_GATEWAY_KEYS, 'NATIVE'] as const;\nexport type CryptoPaymentProcessorKey = typeof CRYPTO_PAYMENT_PROCESSOR_KEYS[number];\nconst CRYPTO_PAYMENT_PROCESSOR_KEY_SET = new Set<string>(CRYPTO_PAYMENT_PROCESSOR_KEYS);\n\nexport function isCryptoRailGatewayLabel(value: string): value is CryptoRailGatewayLabel {\n return CRYPTO_RAIL_GATEWAY_LABEL_SET.has(normalizeGatewayKey(value));\n}\n\nexport function isCryptoPaymentProcessorKey(value: string): value is CryptoPaymentProcessorKey {\n return CRYPTO_PAYMENT_PROCESSOR_KEY_SET.has(normalizeGatewayKey(value));\n}\n\n/**\n * Single source of truth for \"does this invoice gateway value mean crypto\":\n * concrete coin/token keys (incl. legacy), generic stablecoin families,\n * provider gateway keys, and external rail labels. Consumers classifying\n * invoice rows by their public `gateway` value must use this instead of\n * maintaining local lists.\n */\nexport function isCryptoInvoiceGatewayLabel(value: string): boolean {\n const normalized = normalizeGatewayKey(value);\n return isConcreteCryptoGatewayKey(normalized)\n || GENERIC_STABLECOIN_GATEWAY_KEY_SET.has(normalized)\n || CRYPTO_PROVIDER_GATEWAY_KEY_SET.has(normalized)\n || CRYPTO_RAIL_GATEWAY_LABEL_SET.has(normalized)\n || normalized === NATIVE_CRYPTO_PROVIDER_KEY;\n}\n\nfunction getAvailableManualGatewaySelections(gateways: Iterable<string>): string[] {\n const selected = new Set<string>();\n\n for (const gateway of gateways) {\n const normalized = normalizeGatewayKey(gateway);\n if (normalized === 'MANUAL' || normalized.startsWith('MANUAL:')) {\n selected.add(normalized);\n }\n }\n\n return [...selected];\n}\n\nfunction getProviderScopedGatewaySelections(\n providerGateway: keyof typeof DEFAULT_PROVIDER_GATEWAY_SELECTIONS,\n availableGateways: string[],\n): string[] {\n const providerDefaults = DEFAULT_PROVIDER_GATEWAY_SELECTIONS[providerGateway];\n\n if (availableGateways.length === 0) {\n return [...providerDefaults];\n }\n\n const availableConcreteGateways = new Set(getConcreteCryptoGatewaySelections(availableGateways));\n return providerDefaults.filter((gateway) => availableConcreteGateways.has(gateway));\n}\n\nexport function expandGatewaySelection(\n gateway: string,\n options?: { availableGateways?: Iterable<string> },\n): string[] {\n const normalized = normalizeGatewayKey(gateway);\n if (!normalized) {\n return [];\n }\n\n const availableGateways = options?.availableGateways\n ? [...options.availableGateways].map((entry) => normalizeGatewayKey(entry)).filter(Boolean)\n : [];\n\n if (normalized === 'MANUAL') {\n return availableGateways.length > 0\n ? getAvailableManualGatewaySelections(availableGateways)\n : ['MANUAL'];\n }\n\n if (normalized.startsWith('MANUAL:')) {\n return [normalized];\n }\n\n if (normalized === 'CRYPTO') {\n return availableGateways.length > 0\n ? getConcreteCryptoGatewaySelections(availableGateways)\n : [...CRYPTO_GATEWAY_KEYS];\n }\n\n if (isCryptoProviderGatewayKey(normalized)) {\n return getProviderScopedGatewaySelections(\n normalized as keyof typeof DEFAULT_PROVIDER_GATEWAY_SELECTIONS,\n availableGateways,\n );\n }\n\n if (isGenericStablecoinGatewayKey(normalized)) {\n const concreteGateways =\n GENERIC_STABLECOIN_GATEWAY_FAMILIES[\n normalized as keyof typeof GENERIC_STABLECOIN_GATEWAY_FAMILIES\n ];\n\n if (availableGateways.length > 0) {\n const availableSet = new Set(availableGateways);\n return concreteGateways.filter((entry) => availableSet.has(entry));\n }\n\n return [...concreteGateways];\n }\n\n return [normalized];\n}\n\nexport function resolveConcreteGatewaySelections(\n input: unknown,\n options?: { availableGateways?: Iterable<string> },\n): string[] | null {\n const normalized = normalizeGatewayRestrictionInput(input);\n if (!normalized) {\n return null;\n }\n\n const resolved = new Set<string>();\n for (const gateway of normalized) {\n for (const expanded of expandGatewaySelection(gateway, options)) {\n resolved.add(expanded);\n }\n }\n\n return [...resolved];\n}\n\nexport function normalizeCheckoutMethodOrder(\n input: Iterable<string> | null | undefined,\n): CheckoutMethodOrderKey[] {\n if (!input) {\n return [];\n }\n\n const normalized = new Set<CheckoutMethodOrderKey>();\n\n for (const entry of input) {\n if (typeof entry !== 'string') {\n continue;\n }\n\n const candidate = entry.trim().toUpperCase();\n if (CHECKOUT_METHOD_ORDER_KEY_SET.has(candidate)) {\n normalized.add(candidate as CheckoutMethodOrderKey);\n }\n }\n\n return [...normalized];\n}\n\nexport function resolveCheckoutMethodOrder(\n input: Iterable<string> | null | undefined,\n): CheckoutMethodOrderKey[] {\n const normalized = normalizeCheckoutMethodOrder(input);\n const resolved = [...normalized];\n\n for (const key of CHECKOUT_METHOD_ORDER_KEYS) {\n if (!resolved.includes(key)) {\n resolved.push(key);\n }\n }\n\n return resolved;\n}\n\nexport function getCheckoutMethodOrderGroup(\n gateway: string,\n): CheckoutMethodOrderKey | null {\n const normalized = normalizeGatewayKey(gateway);\n if (!normalized) {\n return null;\n }\n\n if (normalized === 'MANUAL' || normalized.startsWith('MANUAL:')) {\n return 'MANUAL';\n }\n\n if (isCryptoProviderGatewayKey(normalized) || isConcreteCryptoGatewayKey(normalized)) {\n return 'CRYPTO';\n }\n\n return CHECKOUT_METHOD_GROUP_BY_GATEWAY[normalized] ?? null;\n}\n\nexport function sortGatewaysByCheckoutMethodOrder(\n gateways: Iterable<string>,\n input: Iterable<string> | null | undefined,\n): string[] {\n const explicitOrder = normalizeCheckoutMethodOrder(input);\n if (explicitOrder.length === 0) {\n return [...gateways];\n }\n\n const resolvedOrder = resolveCheckoutMethodOrder(explicitOrder);\n const orderIndex = new Map(\n resolvedOrder.map((key, index) => [key, index] as const),\n );\n\n return [...gateways].sort((left, right) => {\n const leftGroup = getCheckoutMethodOrderGroup(left);\n const rightGroup = getCheckoutMethodOrderGroup(right);\n const leftIndex = leftGroup ? (orderIndex.get(leftGroup) ?? Number.MAX_SAFE_INTEGER) : Number.MAX_SAFE_INTEGER;\n const rightIndex = rightGroup ? (orderIndex.get(rightGroup) ?? Number.MAX_SAFE_INTEGER) : Number.MAX_SAFE_INTEGER;\n\n if (leftIndex !== rightIndex) {\n return leftIndex - rightIndex;\n }\n\n return 0;\n });\n}\n\nexport function getCheckoutMethodOrderKeysForGateways(\n gateways: Iterable<string>,\n input?: Iterable<string> | null,\n): CheckoutMethodOrderKey[] {\n const orderedGroups = new Set<CheckoutMethodOrderKey>();\n\n for (const gateway of sortGatewaysByCheckoutMethodOrder(gateways, input)) {\n const group = getCheckoutMethodOrderGroup(gateway);\n if (group) {\n orderedGroups.add(group);\n }\n }\n\n return [...orderedGroups];\n}\n\nexport function getCheckoutMethodOrderLabel(key: CheckoutMethodOrderKey): string {\n switch (key) {\n case 'STRIPE':\n return 'Credit / Debit Cards';\n case 'PAYPAL':\n return 'PayPal';\n case 'PAYPAL_FF':\n return 'PayPal F&F';\n case 'MOLLIE':\n return 'Mollie';\n case 'AUTHORIZENET':\n return 'Authorize.net';\n case 'NMI':\n return 'NMI';\n case 'SQUARE':\n return 'Square';\n case 'SUMUP':\n return 'SumUp';\n case 'SHOPIFY':\n return 'Shopify';\n case 'SUBY':\n return 'Suby';\n case 'PANDABASE':\n return 'Pandabase';\n case 'STORRIK':\n return 'Storrik';\n case 'DEBLOMASSI':\n return 'DebloMassi';\n case 'SHOPPEXPAY':\n return 'Card payment';\n case 'MONEYMOTION':\n return 'MoneyMotion';\n case 'OVGC':\n return 'OVGC Payments';\n case 'WHOP':\n return 'Whop';\n case 'DODO':\n return 'Dodo Payments';\n case 'MAVERICK':\n return 'Maverick Payments';\n case 'CASHAPP':\n return 'Cash App';\n case 'VENMO':\n return 'Venmo';\n case 'CRYPTO':\n return 'Crypto';\n case 'CUSTOMER_BALANCE':\n return 'Store Credit';\n case 'MANUAL':\n return 'Manual Payment Methods';\n }\n}\n\nexport const SecretRefSchema = z.object({\n set: z.boolean(),\n});\n\nexport const PaymentGatewayHealthSchema = z.object({\n status: z.enum(['READY', 'NEEDS_ATTENTION']).optional(),\n code: z.string().optional(),\n message: z.string().optional(),\n checked_at: z.string().optional(),\n});\n\nexport const PaymentGatewayStateSchema = z.object({\n provider: z.string(),\n type: z.string(),\n enabled: z.boolean(),\n connected: z.boolean(),\n credentials: z.record(z.string(), SecretRefSchema),\n public_config: z.record(z.string(), z.unknown()),\n webhook: z.record(z.string(), z.unknown()).optional(),\n health: PaymentGatewayHealthSchema.optional(),\n});\n\nexport type PaymentGatewayStateFromSchema = z.infer<typeof PaymentGatewayStateSchema>;\n","import * as z from 'zod/v4';\n\n/** Canonical Shoppex hosted-checkout brand (matches `apps/checkout/app/globals.css` `--primary`). */\nexport const CHECKOUT_PLATFORM_BRAND_COLOR = '#2563eb';\n\n/** Curated font label for Style Center controls (runtime loads Geist via `next/font`). */\nexport const CHECKOUT_PLATFORM_FONT_FAMILY = 'Geist';\n\n/** Stripe/PayPal appearance and CSS var() fallbacks when no merchant brand override exists. */\nexport const CHECKOUT_PLATFORM_BRAND_FALLBACK = CHECKOUT_PLATFORM_BRAND_COLOR;\n\n/** Runtime font stack when no merchant typography override exists. */\nexport const CHECKOUT_PLATFORM_FONT_STACK =\n 'var(--font-geist-sans, Geist), Geist, system-ui, sans-serif';\n\n/** Stripe appearance fontFamily (no CSS var() — provider SDK string). */\nexport const CHECKOUT_PLATFORM_STRIPE_FONT_FAMILY = 'Geist, system-ui, sans-serif';\n\nconst BRAND_DERIVED_TOKEN_KEYS: Partial<Record<string, string>> = {\n 'component.primaryButton.background': 'color.brand',\n 'component.radio.checkedFill': 'color.brand',\n};\n\n/**\n * Platform baseline values for unset checkout tokens.\n * Used by Style Center UI, validation, and documentation — not emitted to live CSS unless explicit.\n */\nexport const CHECKOUT_PLATFORM_BASELINE: Partial<Record<string, string | number>> = {\n 'color.brand': CHECKOUT_PLATFORM_BRAND_COLOR,\n 'color.brandContrast': '#ffffff',\n 'color.background': '#000000',\n 'color.surface': '#18181b',\n 'color.surfaceRaised': '#27272a',\n 'color.text': '#fafafa',\n 'color.textMuted': '#a1a1aa',\n 'color.border': '#222222',\n 'color.focus': CHECKOUT_PLATFORM_BRAND_COLOR,\n 'color.success': '#22c55e',\n 'color.warning': '#f59e0b',\n 'color.error': '#ef4444',\n 'typography.fontFamily': CHECKOUT_PLATFORM_FONT_FAMILY,\n 'typography.baseSize': 14,\n 'shape.buttonRadius': 8,\n 'shape.inputRadius': 8,\n 'shape.cardRadius': 12,\n 'spacing.density': 'comfortable',\n 'spacing.controlHeight': 48,\n 'component.primaryButton.text': '#ffffff',\n 'component.input.background': '#111111',\n 'component.input.border': '#222222',\n 'component.input.focusRing': 'rgba(37,99,235,0.35)',\n 'component.productCard.background': 'rgba(255,255,255,0.03)',\n 'component.productCard.border': 'rgba(255,255,255,0.06)',\n 'component.productCard.shadow': 'none',\n 'component.productImage.background': 'rgba(255,255,255,0.06)',\n 'component.productImage.border': 'rgba(255,255,255,0.04)',\n 'component.productImage.icon': 'rgba(250,250,250,0.4)',\n 'component.brandAvatar.background': 'rgba(255,255,255,0.06)',\n 'component.brandAvatar.text': '#ffffff',\n 'component.brandAvatar.border': 'rgba(255,255,255,0.1)',\n 'component.pill.background': 'rgba(255,255,255,0.04)',\n 'component.pill.border': 'rgba(255,255,255,0.08)',\n 'component.pill.text': '#a1a1aa',\n 'component.errorBanner.background': 'rgba(239,68,68,0.1)',\n 'component.errorBanner.border': 'rgba(239,68,68,0.2)',\n 'component.errorBanner.text': '#ef4444',\n 'component.radio.idleRing': 'rgba(161,161,170,0.5)',\n 'component.radio.checkedIcon': '#ffffff',\n 'component.divider.color': 'rgba(255,255,255,0.06)',\n};\n\nexport function isExplicitCheckoutStyleTokenValue(value: unknown): value is string | number {\n if (typeof value === 'number' && Number.isFinite(value)) return true;\n if (typeof value === 'string') return value.trim().length > 0;\n return false;\n}\n\nfunction resolveCheckoutStyleBrandDerivedTokenKey(key: string): string | undefined {\n return BRAND_DERIVED_TOKEN_KEYS[key];\n}\n\nexport const checkoutStyleSurfaceValues = ['checkout', 'payment_link', 'embed'] as const;\nexport const checkoutEmbedDesignValues = ['current', 'clean-light', 'clean-dark', 'v2', 'v3'] as const;\nexport const checkoutStyleDensityValues = ['comfortable', 'compact'] as const;\nexport const checkoutStyleModeValues = ['light', 'dark', 'system'] as const;\nexport const checkoutStylePaymentLinkHeroPositionValues = ['top', 'side', 'background'] as const;\nexport const embedCloseButtonStyleValues = ['ghost', 'outlined', 'filled'] as const;\nexport const embedMobileLayoutValues = ['sheet', 'fullscreen', 'center'] as const;\nexport const embedContentVisibilityValues = ['visible', 'hidden'] as const;\nexport const checkoutStyleManagedAssetHostValues = ['assets.shoppex.io', 'cdn.shoppex.io', 'imagedelivery.net'] as const;\n\nexport const CheckoutStyleSurfaceSchema = z.enum(checkoutStyleSurfaceValues);\nexport const CheckoutEmbedDesignSchema = z.enum(checkoutEmbedDesignValues);\nexport const CheckoutStyleDensitySchema = z.enum(checkoutStyleDensityValues);\nexport const CheckoutStyleModeSchema = z.enum(checkoutStyleModeValues);\nexport const CheckoutStylePaymentLinkHeroPositionSchema = z.enum(checkoutStylePaymentLinkHeroPositionValues);\nexport const EmbedCloseButtonStyleSchema = z.enum(embedCloseButtonStyleValues);\nexport const EmbedMobileLayoutSchema = z.enum(embedMobileLayoutValues);\nexport const EmbedContentVisibilitySchema = z.enum(embedContentVisibilityValues);\n\nexport type CheckoutStyleSurface = z.infer<typeof CheckoutStyleSurfaceSchema>;\nexport type CheckoutEmbedDesign = z.infer<typeof CheckoutEmbedDesignSchema>;\nexport type CheckoutStyleDensity = z.infer<typeof CheckoutStyleDensitySchema>;\nexport type CheckoutStyleMode = z.infer<typeof CheckoutStyleModeSchema>;\nexport type CheckoutStylePaymentLinkHeroPosition = z.infer<typeof CheckoutStylePaymentLinkHeroPositionSchema>;\nexport type EmbedCloseButtonStyle = z.infer<typeof EmbedCloseButtonStyleSchema>;\nexport type EmbedMobileLayout = z.infer<typeof EmbedMobileLayoutSchema>;\nexport type EmbedContentVisibility = z.infer<typeof EmbedContentVisibilitySchema>;\n\nexport const CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION = 1;\nexport const SHOPPEX_STYLE_THEME_EXPORT_FORMAT_VERSION = 2;\n\nexport type CheckoutStyleTokenType = 'asset_url' | 'color' | 'font' | 'number' | 'select' | 'shadow';\nexport type CheckoutStyleTokenGroup = 'asset' | 'brand' | 'color' | 'typography' | 'shape' | 'spacing' | 'component' | 'embed';\n\nexport type CheckoutStyleCssTokenDefinition = {\n key: string;\n cssVar: `--spx-checkout-${string}` | `--spx-embed-${string}`;\n group: Exclude<CheckoutStyleTokenGroup, 'asset'>;\n type: Exclude<CheckoutStyleTokenType, 'asset_url'>;\n default: string | number;\n min?: number;\n max?: number;\n step?: number;\n unit?: 'px' | 'rem';\n allowedValues?: readonly string[];\n protected?: boolean;\n};\n\nexport type CheckoutStyleAssetTokenDefinition = {\n key: string;\n group: 'asset';\n type: 'asset_url' | 'number' | 'select';\n default: string | number | null;\n accept?: readonly string[];\n maxBytes?: number;\n min?: number;\n max?: number;\n step?: number;\n unit?: 'px';\n allowedValues?: readonly string[];\n surface?: CheckoutStyleSurface;\n};\n\nexport type CheckoutStyleTokenDefinition = CheckoutStyleCssTokenDefinition | CheckoutStyleAssetTokenDefinition;\n\nexport const checkoutStyleTokenDefinitions = [\n { key: 'color.brand', cssVar: '--spx-checkout-brand', group: 'brand', type: 'color', default: CHECKOUT_PLATFORM_BRAND_COLOR },\n { key: 'color.brandContrast', cssVar: '--spx-checkout-brand-contrast', group: 'brand', type: 'color', default: '#ffffff', protected: true },\n // Empty default → CSS variable is omitted by createCheckoutStyleCssVariables,\n // so the layout's `var(--spx-checkout-bg, fallback)` resolves to the original\n // Tailwind/ambient-gradient fallback for shops that haven't customised the\n // background. Setting an explicit hex would clobber the ambient gradient and\n // the right-panel `--surface-2` accent for every default-theme checkout.\n { key: 'color.background', cssVar: '--spx-checkout-bg', group: 'color', type: 'color', default: '' },\n { key: 'color.surface', cssVar: '--spx-checkout-surface', group: 'color', type: 'color', default: '#18181b' },\n { key: 'color.surfaceRaised', cssVar: '--spx-checkout-surface-raised', group: 'color', type: 'color', default: '#27272a' },\n { key: 'color.text', cssVar: '--spx-checkout-text', group: 'color', type: 'color', default: '#fafafa', protected: true },\n { key: 'color.textMuted', cssVar: '--spx-checkout-text-muted', group: 'color', type: 'color', default: '#a1a1aa' },\n // Default '#3f3f46' (zinc-700) feeds many runtime-style fallbacks for\n // payment-method cards, product cards, pills, and inputs. Setting it to ''\n // would turn those slots' `var(--spx-checkout-border, currentColor)` into\n // bright text-color borders. The grey-divider regression on the aside is\n // fixed in the layout file by using the Tailwind `border-border` class\n // instead of binding to this token, which keeps both concerns separated.\n { key: 'color.border', cssVar: '--spx-checkout-border', group: 'color', type: 'color', default: '#222222' },\n { key: 'color.focus', cssVar: '--spx-checkout-focus', group: 'color', type: 'color', default: CHECKOUT_PLATFORM_BRAND_COLOR, protected: true },\n { key: 'color.success', cssVar: '--spx-checkout-success', group: 'color', type: 'color', default: '#22c55e', protected: true },\n { key: 'color.warning', cssVar: '--spx-checkout-warning', group: 'color', type: 'color', default: '#f59e0b', protected: true },\n { key: 'color.error', cssVar: '--spx-checkout-error', group: 'color', type: 'color', default: '#ef4444', protected: true },\n { key: 'typography.fontFamily', cssVar: '--spx-checkout-font', group: 'typography', type: 'font', default: CHECKOUT_PLATFORM_FONT_FAMILY },\n // Optional Google Fonts family. Empty default → CSS variable is omitted\n // so the curated fontFamily wins. When set, the storefront also injects\n // a <link rel=\"stylesheet\"> to fonts.googleapis.com so the family is\n // actually loaded.\n { key: 'typography.googleFontFamily', cssVar: '--spx-checkout-google-font', group: 'typography', type: 'font', default: '' },\n { key: 'typography.baseSize', cssVar: '--spx-checkout-font-size', group: 'typography', type: 'number', default: 14, min: 12, max: 18, step: 1, unit: 'px' },\n { key: 'shape.buttonRadius', cssVar: '--spx-checkout-button-radius', group: 'shape', type: 'number', default: 8, min: 0, max: 24, step: 1, unit: 'px' },\n { key: 'shape.inputRadius', cssVar: '--spx-checkout-input-radius', group: 'shape', type: 'number', default: 8, min: 0, max: 24, step: 1, unit: 'px' },\n { key: 'shape.cardRadius', cssVar: '--spx-checkout-card-radius', group: 'shape', type: 'number', default: 12, min: 0, max: 28, step: 1, unit: 'px' },\n {\n key: 'spacing.density',\n cssVar: '--spx-checkout-density',\n group: 'spacing',\n type: 'select',\n default: 'comfortable',\n allowedValues: checkoutStyleDensityValues,\n },\n { key: 'spacing.controlHeight', cssVar: '--spx-checkout-control-height', group: 'spacing', type: 'number', default: 48, min: 36, max: 56, step: 2, unit: 'px' },\n { key: 'component.primaryButton.background', cssVar: '--spx-checkout-button-bg', group: 'component', type: 'color', default: '', protected: true },\n { key: 'component.primaryButton.text', cssVar: '--spx-checkout-button-text', group: 'component', type: 'color', default: '#ffffff', protected: true },\n { key: 'component.input.background', cssVar: '--spx-checkout-input-bg', group: 'component', type: 'color', default: '#111111' },\n { key: 'component.input.border', cssVar: '--spx-checkout-input-border', group: 'component', type: 'color', default: '#222222' },\n { key: 'component.input.focusRing', cssVar: '--spx-checkout-input-focus-ring', group: 'component', type: 'color', default: '' },\n // Default '' is filtered out by the preview-iframe normaliser, so the\n // CSS fallback chain on [data-spx-slot=\"summary.panel\"] resolves to\n // --spx-checkout-bg when no merchant override is set. A merchant who\n // only edits color.background therefore sees the aside follow that\n // change without an explicit summary override.\n { key: 'component.summary.background', cssVar: '--spx-checkout-summary-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.paymentMethod.background', cssVar: '--spx-checkout-payment-method-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.paymentMethod.cardBackground', cssVar: '--spx-checkout-payment-method-card-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.paymentMethod.border', cssVar: '--spx-checkout-payment-method-border', group: 'component', type: 'color', default: '' },\n { key: 'component.paymentMethod.selectedBackground', cssVar: '--spx-checkout-payment-method-selected-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.checkoutHeader.background', cssVar: '--spx-checkout-embed-header-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.checkoutHeader.text', cssVar: '--spx-checkout-embed-header-text', group: 'component', type: 'color', default: '' },\n { key: 'component.productCard.background', cssVar: '--spx-checkout-product-card-bg', group: 'component', type: 'color', default: 'rgba(255,255,255,0.03)' },\n { key: 'component.productCard.border', cssVar: '--spx-checkout-product-card-border', group: 'component', type: 'color', default: 'rgba(255,255,255,0.06)' },\n { key: 'component.productCard.shadow', cssVar: '--spx-checkout-product-card-shadow', group: 'component', type: 'shadow', default: 'none' },\n { key: 'component.productImage.background', cssVar: '--spx-checkout-product-image-bg', group: 'component', type: 'color', default: 'rgba(255,255,255,0.06)' },\n { key: 'component.productImage.border', cssVar: '--spx-checkout-product-image-border', group: 'component', type: 'color', default: 'rgba(255,255,255,0.04)' },\n { key: 'component.productImage.icon', cssVar: '--spx-checkout-product-image-icon', group: 'component', type: 'color', default: 'rgba(250,250,250,0.4)' },\n { key: 'component.brandAvatar.background', cssVar: '--spx-checkout-brand-avatar-bg', group: 'component', type: 'color', default: 'rgba(255,255,255,0.06)' },\n { key: 'component.brandAvatar.text', cssVar: '--spx-checkout-brand-avatar-text', group: 'component', type: 'color', default: '#ffffff' },\n { key: 'component.brandAvatar.border', cssVar: '--spx-checkout-brand-avatar-border', group: 'component', type: 'color', default: 'rgba(255,255,255,0.1)' },\n { key: 'component.pill.background', cssVar: '--spx-checkout-pill-bg', group: 'component', type: 'color', default: 'rgba(255,255,255,0.04)' },\n { key: 'component.pill.border', cssVar: '--spx-checkout-pill-border', group: 'component', type: 'color', default: 'rgba(255,255,255,0.08)' },\n { key: 'component.pill.text', cssVar: '--spx-checkout-pill-text', group: 'component', type: 'color', default: '#a1a1aa' },\n { key: 'component.errorBanner.background', cssVar: '--spx-checkout-error-bg', group: 'component', type: 'color', default: 'rgba(239,68,68,0.1)' },\n { key: 'component.errorBanner.border', cssVar: '--spx-checkout-error-border', group: 'component', type: 'color', default: 'rgba(239,68,68,0.2)' },\n { key: 'component.errorBanner.text', cssVar: '--spx-checkout-error-text', group: 'component', type: 'color', default: '#ef4444' },\n { key: 'component.warningBanner.background', cssVar: '--spx-checkout-warning-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.warningBanner.border', cssVar: '--spx-checkout-warning-border', group: 'component', type: 'color', default: '' },\n { key: 'component.warningBanner.text', cssVar: '--spx-checkout-warning-text', group: 'component', type: 'color', default: '' },\n { key: 'component.radio.idleRing', cssVar: '--spx-checkout-radio-idle-ring', group: 'component', type: 'color', default: 'rgba(161,161,170,0.5)' },\n { key: 'component.radio.checkedFill', cssVar: '--spx-checkout-radio-checked-fill', group: 'component', type: 'color', default: '' },\n { key: 'component.radio.checkedIcon', cssVar: '--spx-checkout-radio-checked-icon', group: 'component', type: 'color', default: '#ffffff' },\n { key: 'component.divider.color', cssVar: '--spx-checkout-divider', group: 'component', type: 'color', default: 'rgba(255,255,255,0.06)' },\n] as const satisfies readonly CheckoutStyleCssTokenDefinition[];\n\nexport const checkoutStyleAssetTokenDefinitions = [\n {\n key: 'brand.logoUrl',\n group: 'asset',\n type: 'asset_url',\n default: null,\n accept: ['image/png', 'image/jpeg', 'image/svg+xml', 'image/webp'],\n maxBytes: 512_000,\n },\n {\n key: 'brand.logoDarkUrl',\n group: 'asset',\n type: 'asset_url',\n default: null,\n accept: ['image/png', 'image/jpeg', 'image/svg+xml', 'image/webp'],\n maxBytes: 512_000,\n },\n {\n key: 'brand.logoMaxHeight',\n group: 'asset',\n type: 'number',\n default: 32,\n min: 16,\n max: 80,\n step: 2,\n unit: 'px',\n },\n {\n key: 'brand.faviconUrl',\n group: 'asset',\n type: 'asset_url',\n default: null,\n accept: ['image/png', 'image/x-icon', 'image/svg+xml'],\n maxBytes: 64_000,\n },\n {\n key: 'paymentLink.heroImageUrl',\n group: 'asset',\n type: 'asset_url',\n default: null,\n accept: ['image/png', 'image/jpeg', 'image/webp'],\n maxBytes: 1_048_576,\n surface: 'payment_link',\n },\n {\n key: 'paymentLink.heroPosition',\n group: 'asset',\n type: 'select',\n default: 'top',\n allowedValues: checkoutStylePaymentLinkHeroPositionValues,\n surface: 'payment_link',\n },\n] as const satisfies readonly CheckoutStyleAssetTokenDefinition[];\n\nexport const checkoutStyleControlTokenDefinitions = [\n ...checkoutStyleTokenDefinitions,\n ...checkoutStyleAssetTokenDefinitions,\n] as const satisfies readonly CheckoutStyleTokenDefinition[];\n\nexport type CheckoutStyleTokenKey = typeof checkoutStyleTokenDefinitions[number]['key'];\nexport type CheckoutStyleControlTokenKey = typeof checkoutStyleControlTokenDefinitions[number]['key'];\nexport type CheckoutStyleCssVariable = typeof checkoutStyleTokenDefinitions[number]['cssVar'];\n\nexport const embedStyleTokenDefinitions = [\n { key: 'embed.launcher.background', cssVar: '--spx-embed-launcher-background', group: 'embed', type: 'color', default: '#7c5cff' },\n { key: 'embed.launcher.text', cssVar: '--spx-embed-launcher-text', group: 'embed', type: 'color', default: '#ffffff', protected: true },\n { key: 'embed.launcher.radius', cssVar: '--spx-embed-launcher-radius', group: 'embed', type: 'number', default: 10, min: 0, max: 28, step: 1, unit: 'px' },\n { key: 'embed.launcher.paddingX', cssVar: '--spx-embed-launcher-padding-x', group: 'embed', type: 'number', default: 18, min: 8, max: 32, step: 1, unit: 'px' },\n { key: 'embed.launcher.paddingY', cssVar: '--spx-embed-launcher-padding-y', group: 'embed', type: 'number', default: 12, min: 6, max: 24, step: 1, unit: 'px' },\n { key: 'embed.launcher.shadow', cssVar: '--spx-embed-launcher-shadow', group: 'embed', type: 'shadow', default: '0 12px 32px rgba(0,0,0,0.18)' },\n { key: 'embed.productCard.background', cssVar: '--spx-embed-product-card-background', group: 'embed', type: 'color', default: '#ffffff' },\n { key: 'embed.productCard.border', cssVar: '--spx-embed-product-card-border', group: 'embed', type: 'color', default: 'rgba(24,24,27,0.12)' },\n { key: 'embed.productCard.imageRadius', cssVar: '--spx-embed-product-card-image-radius', group: 'embed', type: 'number', default: 8, min: 0, max: 24, step: 1, unit: 'px' },\n { key: 'embed.productCard.padding', cssVar: '--spx-embed-product-card-padding', group: 'embed', type: 'number', default: 16, min: 8, max: 32, step: 1, unit: 'px' },\n { key: 'embed.cart.background', cssVar: '--spx-embed-cart-background', group: 'embed', type: 'color', default: '#ffffff' },\n { key: 'embed.cart.rowBorder', cssVar: '--spx-embed-cart-row-border', group: 'embed', type: 'color', default: 'rgba(24,24,27,0.1)' },\n { key: 'embed.cart.itemSpacing', cssVar: '--spx-embed-cart-item-spacing', group: 'embed', type: 'number', default: 12, min: 4, max: 28, step: 1, unit: 'px' },\n { key: 'embed.modal.background', cssVar: '--spx-embed-modal-background', group: 'embed', type: 'color', default: '#ffffff' },\n { key: 'embed.modal.radius', cssVar: '--spx-embed-modal-radius', group: 'embed', type: 'number', default: 16, min: 0, max: 32, step: 1, unit: 'px' },\n { key: 'embed.modal.maxWidth', cssVar: '--spx-embed-modal-max-width', group: 'embed', type: 'number', default: 560, min: 360, max: 960, step: 20, unit: 'px' },\n { key: 'embed.modal.shadow', cssVar: '--spx-embed-modal-shadow', group: 'embed', type: 'shadow', default: '0 20px 60px rgba(0,0,0,0.2)' },\n { key: 'embed.backdrop.color', cssVar: '--spx-embed-backdrop-color', group: 'embed', type: 'color', default: 'rgba(0,0,0,0.6)' },\n { key: 'embed.backdrop.blur', cssVar: '--spx-embed-backdrop-blur', group: 'embed', type: 'number', default: 4, min: 0, max: 24, step: 1, unit: 'px' },\n { key: 'embed.backdrop.opacity', cssVar: '--spx-embed-backdrop-opacity', group: 'embed', type: 'number', default: 1, min: 0, max: 1, step: 0.05 },\n { key: 'embed.skeleton.background', cssVar: '--spx-embed-skeleton-background', group: 'embed', type: 'color', default: '#f4f4f5' },\n { key: 'embed.skeleton.shimmer', cssVar: '--spx-embed-skeleton-shimmer', group: 'embed', type: 'color', default: '#e8e8ec' },\n { key: 'embed.spinner.color', cssVar: '--spx-embed-spinner-color', group: 'embed', type: 'color', default: '#7c5cff' },\n {\n key: 'embed.closeButton.style',\n cssVar: '--spx-embed-close-button-style',\n group: 'embed',\n type: 'select',\n default: 'ghost',\n allowedValues: embedCloseButtonStyleValues,\n },\n {\n key: 'embed.mobile.layout',\n cssVar: '--spx-embed-mobile-layout',\n group: 'embed',\n type: 'select',\n default: 'sheet',\n allowedValues: embedMobileLayoutValues,\n },\n {\n key: 'embed.content.productDescription',\n cssVar: '--spx-embed-product-description-visibility',\n group: 'embed',\n type: 'select',\n default: 'visible',\n allowedValues: embedContentVisibilityValues,\n },\n {\n key: 'embed.content.termsShortcut',\n cssVar: '--spx-embed-terms-shortcut-visibility',\n group: 'embed',\n type: 'select',\n default: 'visible',\n allowedValues: embedContentVisibilityValues,\n },\n] as const satisfies readonly CheckoutStyleCssTokenDefinition[];\n\nexport type EmbedStyleTokenKey = typeof embedStyleTokenDefinitions[number]['key'];\nexport type EmbedStyleCssVariable = typeof embedStyleTokenDefinitions[number]['cssVar'];\n\nexport type EmbedStyleCssVariableOptions = {\n mode?: CheckoutStyleMode;\n embedDesign?: CheckoutEmbedDesign;\n};\n\nexport const checkoutStyleSlotValues = [\n 'checkout.shell',\n 'checkout.panel',\n 'checkout.header',\n 'brand.logo',\n 'product.card',\n 'product.image',\n 'product.title',\n 'product.description',\n 'product.price',\n 'product.quantity',\n 'product.addon',\n 'paymentLink.hero',\n 'summary.panel',\n 'summary.line',\n 'summary.total',\n 'form.field',\n 'form.label',\n 'form.help',\n 'coupon.input',\n 'input.base',\n 'input.error',\n 'button.primary',\n 'button.secondary',\n 'payment.methods',\n 'payment.method',\n 'payment.method.icon',\n 'payment.method.label',\n 'payment.method.meta',\n 'payment.method.fee',\n 'payment.method.indicator',\n 'payment.provider_widget',\n 'payment.loading',\n 'payment.error',\n 'payment.warning',\n 'legal.terms',\n 'status.success',\n 'status.processing',\n 'embed.launcher',\n 'embed.launcher.icon',\n 'embed.productCard',\n 'embed.productCard.image',\n 'embed.productCard.title',\n 'embed.productCard.price',\n 'embed.cart',\n 'embed.cart.row',\n 'embed.cart.summary',\n 'embed.modal',\n 'embed.modal.header',\n 'embed.modal.close',\n 'embed.skeleton',\n 'embed.loader',\n 'embed.branding',\n] as const;\n\nexport const checkoutStyleProtectedSlotValues = [\n 'product.title',\n 'product.price',\n 'summary.total',\n 'payment.method.label',\n 'payment.provider_widget',\n 'payment.loading',\n 'payment.error',\n 'payment.warning',\n 'legal.terms',\n 'status.success',\n 'status.processing',\n 'embed.modal.close',\n 'embed.branding',\n] as const;\n\nexport const CheckoutStyleSlotSchema = z.enum(checkoutStyleSlotValues);\nexport const CheckoutStyleProtectedSlotSchema = z.enum(checkoutStyleProtectedSlotValues);\n\nexport type CheckoutStyleSlot = z.infer<typeof CheckoutStyleSlotSchema>;\nexport type CheckoutStyleProtectedSlot = z.infer<typeof CheckoutStyleProtectedSlotSchema>;\n\nconst HexColorSchema = z.string().regex(/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/, 'Use a valid hex color');\n// Permissive color schema for composite values (rgba, gradients, color-mix)\n// used by token slots that aren't simple solid color picks. The CSS pipeline\n// is the consumer; we just guard against unbounded length and obviously\n// suspicious payloads (no semicolons, no curly braces, no @-rules).\nconst ExtendedColorSchema = z.string().trim().min(1).max(200).refine(\n (value) => !/[;{}]|@import|expression\\s*\\(/i.test(value),\n 'Use a valid CSS color or gradient',\n);\nconst ShadowSchema = z.string().trim().min(1).max(400).refine(\n (value) => !/[;{}]|@import|expression\\s*\\(/i.test(value),\n 'Use a valid CSS box-shadow value',\n);\n// Curated font list — the families the Style Center dropdown offers. Every\n// value here is served without a third-party request: the nine web families are\n// bundled by `next/font/google` in `apps/checkout/app/layout.tsx`, and \"Arial\" /\n// \"System UI\" come from the OS. A payment page must not hand the buyer's IP to\n// fonts.googleapis.com, so a family added here MUST also be added to\n// `app/layout.tsx` and to both maps in `apps/checkout/lib/checkout-style.tsx`\n// (LOCALLY_LOADED_FONTS + LOCAL_FONT_FAMILY_TOKENS); the checkout font-stack\n// test fails otherwise. Order matters: it drives both the dropdown in the\n// editor and the type-checked union here.\nexport const curatedFontValues = [\n 'Inter',\n 'Geist',\n 'Manrope',\n 'Plus Jakarta Sans',\n 'DM Sans',\n 'Space Grotesk',\n 'Sora',\n 'IBM Plex Sans',\n 'JetBrains Mono',\n 'Arial',\n 'System UI',\n] as const;\nconst CuratedFontSchema = z.enum(curatedFontValues);\n\n// Google Fonts family schema — accepts a single Google-hosted family name\n// like \"Source Serif 4\" or \"Crimson Pro\". Restricted to the character set\n// Google Fonts permits in family names (alphanumerics, spaces, +, -, _,\n// digits) and capped at 60 chars to avoid abuse via giant CSS imports.\nconst GoogleFontFamilySchema = z\n .string()\n .trim()\n .min(1)\n .max(60)\n .regex(/^[A-Za-z0-9 +\\-_]+$/, 'Use a Google Fonts family name');\nconst AssetUrlSchema = z.string().url();\n\nexport function isCheckoutStyleManagedAssetUrl(value: string): boolean {\n try {\n const url = new URL(value);\n return url.protocol === 'https:' && checkoutStyleManagedAssetHostValues.includes(\n url.hostname as typeof checkoutStyleManagedAssetHostValues[number],\n );\n } catch {\n return false;\n }\n}\n\nexport const CheckoutStyleTokensSchema = z.object({\n brand: z.object({\n logoUrl: AssetUrlSchema.optional().nullable(),\n logoDarkUrl: AssetUrlSchema.optional().nullable(),\n logoMaxHeight: z.number().int().min(16).max(80).optional(),\n faviconUrl: AssetUrlSchema.optional().nullable(),\n }).strict().optional(),\n color: z.object({\n brand: HexColorSchema.optional(),\n brandContrast: HexColorSchema.optional(),\n background: HexColorSchema.optional(),\n surface: HexColorSchema.optional(),\n surfaceRaised: HexColorSchema.optional(),\n text: HexColorSchema.optional(),\n textMuted: HexColorSchema.optional(),\n border: HexColorSchema.optional(),\n focus: HexColorSchema.optional(),\n success: HexColorSchema.optional(),\n warning: HexColorSchema.optional(),\n error: HexColorSchema.optional(),\n }).strict().optional(),\n typography: z.object({\n fontFamily: CuratedFontSchema.optional(),\n // Optional Google Fonts override. When set, the storefront injects the\n // fonts.googleapis.com stylesheet and uses this family in addition to\n // (or instead of) the curated fontFamily as the leftmost name in the\n // CSS font stack.\n googleFontFamily: GoogleFontFamilySchema.optional(),\n baseSize: z.number().int().min(12).max(18).optional(),\n }).strict().optional(),\n shape: z.object({\n buttonRadius: z.number().int().min(0).max(24).optional(),\n inputRadius: z.number().int().min(0).max(24).optional(),\n cardRadius: z.number().int().min(0).max(28).optional(),\n }).strict().optional(),\n spacing: z.object({\n density: CheckoutStyleDensitySchema.optional(),\n controlHeight: z.number().int().min(36).max(56).optional(),\n }).strict().optional(),\n component: z.object({\n primaryButton: z.object({\n background: HexColorSchema.optional(),\n text: HexColorSchema.optional(),\n }).strict().optional(),\n input: z.object({\n background: HexColorSchema.optional(),\n border: HexColorSchema.optional(),\n focusRing: ExtendedColorSchema.optional(),\n }).strict().optional(),\n summary: z.object({\n background: HexColorSchema.optional(),\n }).strict().optional(),\n paymentMethod: z.object({\n background: ExtendedColorSchema.optional(),\n cardBackground: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n selectedBackground: ExtendedColorSchema.optional(),\n }).strict().optional(),\n productCard: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n shadow: ShadowSchema.optional(),\n }).strict().optional(),\n productImage: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n icon: ExtendedColorSchema.optional(),\n }).strict().optional(),\n brandAvatar: z.object({\n background: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n }).strict().optional(),\n pill: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n }).strict().optional(),\n errorBanner: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n }).strict().optional(),\n warningBanner: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n }).strict().optional(),\n radio: z.object({\n idleRing: ExtendedColorSchema.optional(),\n checkedFill: HexColorSchema.optional(),\n checkedIcon: HexColorSchema.optional(),\n }).strict().optional(),\n divider: z.object({\n color: ExtendedColorSchema.optional(),\n }).strict().optional(),\n }).strict().optional(),\n paymentLink: z.object({\n heroImageUrl: AssetUrlSchema.optional().nullable(),\n heroPosition: CheckoutStylePaymentLinkHeroPositionSchema.optional(),\n }).strict().optional(),\n embed: z.object({\n launcher: z.object({\n background: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n radius: z.number().int().min(0).max(28).optional(),\n paddingX: z.number().int().min(8).max(32).optional(),\n paddingY: z.number().int().min(6).max(24).optional(),\n shadow: ShadowSchema.optional(),\n }).strict().optional(),\n productCard: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n imageRadius: z.number().int().min(0).max(24).optional(),\n padding: z.number().int().min(8).max(32).optional(),\n }).strict().optional(),\n cart: z.object({\n background: ExtendedColorSchema.optional(),\n rowBorder: ExtendedColorSchema.optional(),\n itemSpacing: z.number().int().min(4).max(28).optional(),\n }).strict().optional(),\n modal: z.object({\n background: ExtendedColorSchema.optional(),\n radius: z.number().int().min(0).max(32).optional(),\n maxWidth: z.number().int().min(360).max(960).optional(),\n shadow: ShadowSchema.optional(),\n }).strict().optional(),\n backdrop: z.object({\n color: ExtendedColorSchema.optional(),\n blur: z.number().int().min(0).max(24).optional(),\n opacity: z.number().min(0).max(1).optional(),\n }).strict().optional(),\n skeleton: z.object({\n background: ExtendedColorSchema.optional(),\n shimmer: ExtendedColorSchema.optional(),\n }).strict().optional(),\n spinner: z.object({\n color: ExtendedColorSchema.optional(),\n }).strict().optional(),\n closeButton: z.object({\n style: EmbedCloseButtonStyleSchema.optional(),\n }).strict().optional(),\n mobile: z.object({\n layout: EmbedMobileLayoutSchema.optional(),\n }).strict().optional(),\n content: z.object({\n productDescription: EmbedContentVisibilitySchema.optional(),\n termsShortcut: EmbedContentVisibilitySchema.optional(),\n }).strict().optional(),\n }).strict().optional(),\n}).strict();\n\nexport type CheckoutStyleTokens = z.infer<typeof CheckoutStyleTokensSchema>;\n\nexport const CheckoutStyleSettingsSchema = z.object({\n mode: CheckoutStyleModeSchema.default('system'),\n fontSource: z.enum(['curated']).default('curated'),\n}).strict();\n\nexport type CheckoutStyleSettings = z.infer<typeof CheckoutStyleSettingsSchema>;\n\nexport const StyleThemeShareModeSchema = z.enum(['standalone', 'bundle', 'pointer']);\nexport type StyleThemeShareMode = z.infer<typeof StyleThemeShareModeSchema>;\n\nexport const StyleThemeParentHintSchema = z.object({\n name: z.string().trim().min(1).max(80),\n fingerprint: z.string().trim().min(1).max(128),\n}).strict();\n\nexport const CheckoutStyleBundledParentThemeExportSchema = z.object({\n type: z.literal('shoppex.style_theme'),\n surface: z.literal('checkout'),\n format_version: z.union([\n z.literal(1),\n z.literal(SHOPPEX_STYLE_THEME_EXPORT_FORMAT_VERSION),\n ]),\n name: z.string().trim().min(1).max(80),\n description: z.string().trim().max(240).optional(),\n embed_design: CheckoutEmbedDesignSchema.default('current'),\n token_schema_version: z.literal(CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION),\n tokens: CheckoutStyleTokensSchema.default({}),\n custom_css: z.string().max(20_000).default(''),\n settings: CheckoutStyleSettingsSchema.default({ mode: 'system', fontSource: 'curated' }),\n _meta: z.record(z.string(), z.unknown()).optional(),\n}).strict();\n\nexport const CheckoutStyleThemeExportSchema = z.object({\n type: z.literal('shoppex.style_theme'),\n surface: CheckoutStyleSurfaceSchema,\n format_version: z.union([\n z.literal(1),\n z.literal(SHOPPEX_STYLE_THEME_EXPORT_FORMAT_VERSION),\n ]),\n name: z.string().trim().min(1).max(80),\n description: z.string().trim().max(240).optional(),\n embed_design: CheckoutEmbedDesignSchema.default('current'),\n token_schema_version: z.literal(CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION),\n tokens: CheckoutStyleTokensSchema.default({}),\n custom_css: z.string().max(20_000).default(''),\n settings: CheckoutStyleSettingsSchema.default({ mode: 'system', fontSource: 'curated' }),\n share_mode: StyleThemeShareModeSchema.default('standalone'),\n parent_hint: StyleThemeParentHintSchema.optional(),\n bundled_parent: CheckoutStyleBundledParentThemeExportSchema.optional(),\n _meta: z.record(z.string(), z.unknown()).optional(),\n}).strict();\n\nexport type CheckoutStyleThemeExport = z.infer<typeof CheckoutStyleThemeExportSchema>;\n\nexport const ResolvedCheckoutStyleSchema = z.object({\n theme_id: z.string().uuid().nullable(),\n surface: CheckoutStyleSurfaceSchema,\n embed_design: CheckoutEmbedDesignSchema,\n token_schema_version: z.literal(CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION),\n revision: z.number().int().min(1),\n tokens: CheckoutStyleTokensSchema,\n custom_css: z.string(),\n css_variables: z.record(z.string(), z.string()),\n}).strict();\n\nexport type ResolvedCheckoutStyle = z.infer<typeof ResolvedCheckoutStyleSchema>;\n\nexport const ResolvedEmbedStyleSchema = z.object({\n theme_id: z.string().uuid().nullable(),\n parent_theme_id: z.string().uuid().nullable(),\n surface: z.literal('embed'),\n embed_design: CheckoutEmbedDesignSchema,\n token_schema_version: z.literal(CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION),\n revision: z.number().int().min(1),\n parent_revision: z.number().int().min(1).nullable(),\n tokens: CheckoutStyleTokensSchema,\n custom_css: z.string(),\n css_variables: z.record(z.string(), z.string()),\n}).strict();\n\nexport type ResolvedEmbedStyle = z.infer<typeof ResolvedEmbedStyleSchema>;\n\n/** Canonical embed runtime contract shared by SDK shell and checkout iframe. */\nexport const EmbedRuntimeStyleSchema = ResolvedEmbedStyleSchema;\nexport type EmbedRuntimeStyle = ResolvedEmbedStyle;\n\nexport const EmbedRuntimeSessionContextSchema = z.object({\n shop_id: z.string().uuid(),\n product_id: z.string().uuid().nullable(),\n product_group_id: z.string().uuid().nullable(),\n payment_link_id: z.string().uuid().nullable(),\n invoice_id: z.string().nullable(),\n}).strict();\n\nexport type EmbedRuntimeSessionContext = z.infer<typeof EmbedRuntimeSessionContextSchema>;\n\nexport const EmbedRuntimeThemeResponseSchema = z.object({\n embed_runtime: z.string().min(16).max(128),\n embed_design: CheckoutEmbedDesignSchema,\n revision: z.number().int().min(1),\n parent_revision: z.number().int().min(1).nullable(),\n theme_id: z.string().uuid().nullable(),\n css_variables: z.record(z.string(), z.string()),\n custom_css: z.string(),\n}).strict();\n\nexport type EmbedRuntimeThemeResponse = z.infer<typeof EmbedRuntimeThemeResponseSchema>;\n\nexport const EmbedRuntimeTransportSchema = z.object({\n embed_design: CheckoutEmbedDesignSchema.optional(),\n embed_style_revision: z.coerce.number().int().min(1).optional(),\n embed_runtime: z.string().min(16).max(128).optional(),\n preview: z.boolean().optional(),\n}).strict();\n\nexport type EmbedRuntimeTransport = z.infer<typeof EmbedRuntimeTransportSchema>;\n\nfunction readPath(input: unknown, path: string): unknown {\n return path.split('.').reduce<unknown>((current, segment) => {\n if (!current || typeof current !== 'object' || Array.isArray(current)) return undefined;\n return (current as Record<string, unknown>)[segment];\n }, input);\n}\n\nfunction formatCssValue(definition: CheckoutStyleTokenDefinition, value: string | number): string {\n if (definition.type === 'number' && definition.unit) {\n return `${value}${definition.unit}`;\n }\n\n // Multi-word font family names must be quoted so they survive var()\n // substitution into a font-family list. Single-word names like \"Inter\"\n // or generic keywords are left bare so they keep their generic-family\n // semantics.\n if (definition.type === 'font' && typeof value === 'string') {\n const trimmed = value.trim();\n if (trimmed.length === 0) return '';\n if (/\\s/.test(trimmed) && !/^['\"]/.test(trimmed)) {\n return `\"${trimmed.replace(/\"/g, '\\\\\"')}\"`;\n }\n return trimmed;\n }\n\n return String(value);\n}\n\nexport function resolveCheckoutStyleTokenValue(\n tokens: CheckoutStyleTokens,\n key: CheckoutStyleTokenKey,\n options: { parentTokens?: CheckoutStyleTokens } = {},\n): string | number | undefined {\n const own = readPath(tokens, key);\n if (isExplicitCheckoutStyleTokenValue(own)) {\n return own as string | number;\n }\n\n const parent = options.parentTokens ? readPath(options.parentTokens, key) : undefined;\n if (isExplicitCheckoutStyleTokenValue(parent)) {\n return parent as string | number;\n }\n\n const brandDerivedKey = resolveCheckoutStyleBrandDerivedTokenKey(key);\n if (brandDerivedKey) {\n const brand = resolveCheckoutStyleTokenValue(tokens, brandDerivedKey as CheckoutStyleTokenKey, options);\n if (isExplicitCheckoutStyleTokenValue(brand)) {\n return brand;\n }\n }\n\n const definition = checkoutStyleTokenDefinitions.find((entry) => entry.key === key);\n if (definition && isExplicitCheckoutStyleTokenValue(definition.default)) {\n return definition.default;\n }\n\n const baseline = CHECKOUT_PLATFORM_BASELINE[key];\n return baseline !== undefined ? baseline : undefined;\n}\n\nexport function createCheckoutStyleCssVariables(tokens: CheckoutStyleTokens): Record<CheckoutStyleCssVariable, string> {\n const variables = {} as Record<CheckoutStyleCssVariable, string>;\n\n for (const definition of checkoutStyleTokenDefinitions) {\n const value = readPath(tokens, definition.key);\n if (!isExplicitCheckoutStyleTokenValue(value)) {\n continue;\n }\n variables[definition.cssVar] = formatCssValue(definition, value);\n }\n\n return variables;\n}\n\n/**\n * Token groups whose defaults are safe to materialise into the live checkout\n * root. These are the \"foundation\" tokens (brand, base colors, shape, spacing)\n * that sit at the INNER end of the system-CSS `var()` fallback chains —\n * e.g. `var(--spx-checkout-product-card-border, var(--spx-checkout-border, …))`.\n * Materialising them kills the white-`currentColor` fallback bug without\n * touching the cascade.\n *\n * The `component` group is deliberately excluded: those tokens are the OUTER\n * end of the chains, so emitting their defaults (e.g. `--spx-checkout-product-card-bg`)\n * would shadow base-token edits — a merchant who only customises `color.surfaceRaised`\n * would no longer see it cascade into product cards. Their defaults stay inline\n * in the system CSS as the final hex fallback instead.\n *\n * The `typography` group is also excluded: `typography.fontFamily` resolves to a\n * bare family name (\"Geist\") that no `@font-face` declares — the checkout loads\n * Geist via `next/font` as `--font-geist-sans`. Materialising `--spx-checkout-font`\n * as \"Geist\" would make the font-family rule bypass the Next webfont and fall\n * back to system sans. The system CSS keeps CHECKOUT_PLATFORM_FONT_STACK (which\n * references `--font-geist-sans`) as its inline default instead.\n */\nconst CHECKOUT_BASELINE_TOKEN_GROUPS = new Set(['brand', 'color', 'shape', 'spacing']);\n\n/**\n * Like {@link createCheckoutStyleCssVariables}, but materialises each foundation\n * token's SSOT default when the merchant hasn't set an explicit value. The live\n * hosted checkout renders this so the base `--spx-checkout-*` variables are\n * always present in the DOM, which means the system CSS never falls back to\n * `currentColor` (that fallback resolved to the white text colour → white\n * borders/buttons for any merchant who never opened the Style Center).\n *\n * Rules:\n * - Explicit merchant values are always emitted (any group, including component\n * overrides), so partial Style Center themes keep working.\n * - Unset tokens only get their default emitted when they belong to a foundation\n * group (see {@link CHECKOUT_BASELINE_TOKEN_GROUPS}); component defaults are\n * left to the inline system-CSS fallbacks so base-token edits cascade.\n * - Empty defaults (`''`) are skipped so the value stays unset — most importantly\n * `color.background` (`--spx-checkout-bg`), which must remain absent so the\n * ambient gradient survives. This resolves only to `definition.default`, NOT\n * through `resolveCheckoutStyleTokenValue`, because that resolver would fall\n * through to the opaque `#000000` `CHECKOUT_PLATFORM_BASELINE` background.\n */\n/**\n * Light-appearance defaults for the baseline foundation tokens. Keys not listed\n * here keep their (appearance-neutral) definition default. `color.background`\n * stays absent in both appearances so the ambient gradient survives.\n */\nexport const CHECKOUT_PLATFORM_BASELINE_LIGHT_DEFAULTS: Partial<Record<string, string>> = {\n 'color.surface': '#ffffff',\n 'color.surfaceRaised': '#f4f4f5',\n 'color.text': '#101012',\n 'color.textMuted': '#6b7280',\n 'color.border': '#e4e4e7',\n 'color.success': '#16a34a',\n 'color.warning': '#ca8a04',\n 'color.error': '#dc2626',\n};\n\nexport type CheckoutStyleAppearance = 'dark' | 'light';\n\nexport function createCheckoutStyleBaselineCssVariables(\n tokens: CheckoutStyleTokens,\n appearance: CheckoutStyleAppearance = 'dark',\n): Record<CheckoutStyleCssVariable, string> {\n const variables = {} as Record<CheckoutStyleCssVariable, string>;\n\n for (const definition of checkoutStyleTokenDefinitions) {\n const own = readPath(tokens, definition.key);\n if (isExplicitCheckoutStyleTokenValue(own)) {\n variables[definition.cssVar] = formatCssValue(definition, own);\n continue;\n }\n if (!CHECKOUT_BASELINE_TOKEN_GROUPS.has(definition.group)) {\n continue;\n }\n const baselineDefault = appearance === 'light'\n ? CHECKOUT_PLATFORM_BASELINE_LIGHT_DEFAULTS[definition.key] ?? definition.default\n : definition.default;\n if (!isExplicitCheckoutStyleTokenValue(baselineDefault)) {\n continue;\n }\n variables[definition.cssVar] = formatCssValue(definition, baselineDefault);\n }\n\n return variables;\n}\n\nfunction shouldUseDarkEmbedDefaults(options: EmbedStyleCssVariableOptions): boolean {\n if (options.mode === 'dark') return true;\n if (options.mode === 'light') return false;\n return options.embedDesign === 'clean-dark' || options.embedDesign === 'v2' || options.embedDesign === 'v3';\n}\n\nfunction resolveEmbedStyleDefault(\n definition: typeof embedStyleTokenDefinitions[number],\n options: EmbedStyleCssVariableOptions,\n): string | number {\n if (!shouldUseDarkEmbedDefaults(options)) {\n return definition.default;\n }\n\n switch (definition.key) {\n case 'embed.productCard.background':\n return '#09090b';\n case 'embed.productCard.border':\n return 'rgba(255,255,255,0.08)';\n case 'embed.cart.background':\n return '#09090b';\n case 'embed.cart.rowBorder':\n return '#27272a';\n case 'embed.modal.background':\n return '#0a0a0c';\n case 'embed.modal.shadow':\n return options.embedDesign === 'v2'\n ? '0 24px 80px rgba(124,92,255,0.28), 0 16px 48px rgba(0,0,0,0.45)'\n : '0 20px 60px rgba(0,0,0,0.45)';\n case 'embed.skeleton.background':\n return '#1a1a1e';\n case 'embed.skeleton.shimmer':\n return '#2a2a2f';\n default:\n return definition.default;\n }\n}\n\nexport function createEmbedStyleCssVariables(\n tokens: CheckoutStyleTokens,\n options: EmbedStyleCssVariableOptions = {},\n): Record<EmbedStyleCssVariable, string> {\n const variables = {} as Record<EmbedStyleCssVariable, string>;\n\n for (const definition of embedStyleTokenDefinitions) {\n const value = readPath(tokens, definition.key);\n const resolvedValue = typeof value === 'string' || typeof value === 'number'\n ? value\n : resolveEmbedStyleDefault(definition, options);\n if (typeof resolvedValue === 'string' && resolvedValue.length === 0) {\n continue;\n }\n variables[definition.cssVar] = formatCssValue(definition, resolvedValue);\n }\n\n return variables;\n}\n","import * as z from 'zod/v4';\n\nexport const storefrontAddonTypeValues = [\n 'announcement_bar',\n 'countdown_bar',\n 'promo_info_card',\n 'recent_purchase_popup',\n 'coupon_popup_modal',\n 'live_chat',\n] as const;\n\nexport const storefrontAddonSlotValues = [\n 'layout.header.before',\n 'layout.header.after',\n 'layout.overlay',\n 'home.hero.after',\n 'home.grid.before',\n 'product.buybox.after',\n 'layout.footer.before',\n 'floating.bottom_right',\n] as const;\n\nexport const storefrontAddonComponentValues = [\n 'announcement_bar',\n 'countdown_bar',\n 'promo_info_card',\n 'recent_purchase_popup',\n 'coupon_popup_modal',\n 'live_chat',\n] as const;\n\nexport const StorefrontAddonTypeSchema = z.enum(storefrontAddonTypeValues);\nexport const StorefrontAddonSlotSchema = z.enum(storefrontAddonSlotValues);\nexport const StorefrontAddonComponentSchema = z.enum(storefrontAddonComponentValues);\n\nexport type StorefrontAddonType = z.infer<typeof StorefrontAddonTypeSchema>;\nexport type StorefrontAddonSlot = z.infer<typeof StorefrontAddonSlotSchema>;\nexport type StorefrontAddonComponent = z.infer<typeof StorefrontAddonComponentSchema>;\n\nconst HexColorSchema = z.string().regex(/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/, 'Use a valid hex color');\n\nexport const announcementBarDisplayModeValues = [\n 'static',\n 'marquee',\n] as const;\n\nexport const announcementBarThemePresetValues = [\n 'brand_blue',\n 'emerald',\n 'sunset',\n 'rose',\n 'charcoal',\n 'custom',\n] as const;\n\nexport const DEFAULT_ANNOUNCEMENT_BAR_ANIMATION_SPEED_SECONDS = 30;\n\nexport const AnnouncementBarDisplayModeSchema = z.enum(announcementBarDisplayModeValues);\nexport const AnnouncementBarThemePresetSchema = z.enum(announcementBarThemePresetValues);\n\nexport const countdownBarExpiryBehaviorValues = [\n 'hide',\n 'message',\n] as const;\n\nexport const countdownBarDensityValues = [\n 'compact',\n 'comfortable',\n] as const;\n\nexport const countdownBarCtaStyleValues = [\n 'subtle',\n 'outline',\n 'solid',\n] as const;\n\nexport const countdownBarTimerStyleValues = [\n 'minimal',\n 'boxed',\n] as const;\n\nexport const promoInfoCardThemePresetValues = [\n 'indigo',\n 'emerald',\n 'amber',\n 'rose',\n 'slate',\n 'custom',\n] as const;\n\nexport const promoInfoCardLayoutStyleValues = [\n 'compact',\n 'feature',\n 'alert',\n] as const;\n\nexport const promoInfoCardDensityValues = [\n 'compact',\n 'comfortable',\n] as const;\n\nexport const promoInfoCardCtaStyleValues = [\n 'subtle',\n 'outline',\n 'solid',\n] as const;\n\nexport const promoInfoCardIconVisibilityValues = [\n 'show',\n 'hide',\n] as const;\n\nexport const promoInfoCardIconValues = [\n 'sparkles',\n 'megaphone',\n 'gift',\n 'truck',\n 'shield',\n 'support',\n 'none',\n] as const;\n\nexport const CountdownBarExpiryBehaviorSchema = z.enum(countdownBarExpiryBehaviorValues);\nexport const CountdownBarDensitySchema = z.enum(countdownBarDensityValues);\nexport const CountdownBarCtaStyleSchema = z.enum(countdownBarCtaStyleValues);\nexport const CountdownBarTimerStyleSchema = z.enum(countdownBarTimerStyleValues);\nexport const PromoInfoCardThemePresetSchema = z.enum(promoInfoCardThemePresetValues);\nexport const PromoInfoCardLayoutStyleSchema = z.enum(promoInfoCardLayoutStyleValues);\nexport const PromoInfoCardDensitySchema = z.enum(promoInfoCardDensityValues);\nexport const PromoInfoCardCtaStyleSchema = z.enum(promoInfoCardCtaStyleValues);\nexport const PromoInfoCardIconSchema = z.enum(promoInfoCardIconValues);\nexport const PromoInfoCardIconVisibilitySchema = z.enum(promoInfoCardIconVisibilityValues);\n\nexport const couponPopupModalThemePresetValues = [\n 'midnight',\n 'ocean',\n 'ember',\n 'forest',\n 'custom',\n] as const;\n\nexport const couponPopupModalTriggerValues = [\n 'delay',\n 'exit_intent',\n] as const;\n\nexport const CouponPopupModalThemePresetSchema = z.enum(couponPopupModalThemePresetValues);\nexport const CouponPopupModalTriggerSchema = z.enum(couponPopupModalTriggerValues);\n\nconst RelativeOrAbsoluteUrlSchema = z.string().trim().refine((value) => {\n if (value.startsWith('/')) {\n return true;\n }\n\n try {\n const parsed = new URL(value);\n return parsed.protocol === 'http:' || parsed.protocol === 'https:';\n } catch {\n return false;\n }\n}, 'Use a valid absolute URL or a path starting with \"/\"');\n\nconst DatetimeStringSchema = z.string().trim().refine((value) => {\n const parsed = new Date(value);\n return !Number.isNaN(parsed.getTime());\n}, 'Use a valid date and time');\n\nexport const AnnouncementBarConfigSchema = z.object({\n text: z.string().trim().min(1, 'Text is required').max(160, 'Text must be 160 characters or fewer'),\n linkLabel: z.string().trim().max(32, 'Link label must be 32 characters or fewer').optional().nullable(),\n linkUrl: RelativeOrAbsoluteUrlSchema.optional().nullable(),\n dismissible: z.boolean().default(false),\n displayMode: AnnouncementBarDisplayModeSchema.default('marquee'),\n themePreset: AnnouncementBarThemePresetSchema.default('custom'),\n animationSpeedSeconds: z.number().int().min(8).max(40).default(DEFAULT_ANNOUNCEMENT_BAR_ANIMATION_SPEED_SECONDS),\n backgroundColor: HexColorSchema.default('#111827'),\n textColor: HexColorSchema.default('#f9fafb'),\n});\n\nexport const CountdownBarConfigSchema = z.object({\n text: z.string().trim().min(1, 'Text is required').max(120, 'Text must be 120 characters or fewer'),\n endAt: DatetimeStringSchema,\n linkLabel: z.string().trim().max(32, 'Link label must be 32 characters or fewer').optional().nullable(),\n linkUrl: RelativeOrAbsoluteUrlSchema.optional().nullable(),\n dismissible: z.boolean().default(false),\n themePreset: AnnouncementBarThemePresetSchema.default('brand_blue'),\n expiredBehavior: CountdownBarExpiryBehaviorSchema.default('hide'),\n expiredMessage: z.string().trim().max(120, 'Expired message must be 120 characters or fewer').optional().nullable(),\n density: CountdownBarDensitySchema.default('compact'),\n ctaStyle: CountdownBarCtaStyleSchema.default('subtle'),\n timerStyle: CountdownBarTimerStyleSchema.default('boxed'),\n backgroundColor: HexColorSchema.default('#111827'),\n textColor: HexColorSchema.default('#f9fafb'),\n});\n\nexport const PromoInfoCardConfigSchema = z.object({\n eyebrow: z.string().trim().max(32, 'Eyebrow must be 32 characters or fewer').optional().nullable(),\n title: z.string().trim().min(1, 'Title is required').max(80, 'Title must be 80 characters or fewer'),\n body: z.string().trim().min(1, 'Body is required').max(240, 'Body must be 240 characters or fewer'),\n linkLabel: z.string().trim().max(32, 'Link label must be 32 characters or fewer').optional().nullable(),\n linkUrl: RelativeOrAbsoluteUrlSchema.optional().nullable(),\n themePreset: PromoInfoCardThemePresetSchema.default('indigo'),\n layoutStyle: PromoInfoCardLayoutStyleSchema.default('feature'),\n density: PromoInfoCardDensitySchema.default('comfortable'),\n ctaStyle: PromoInfoCardCtaStyleSchema.default('outline'),\n icon: PromoInfoCardIconSchema.default('sparkles'),\n iconVisibility: PromoInfoCardIconVisibilitySchema.default('show'),\n backgroundColor: HexColorSchema.default('#111827'),\n textColor: HexColorSchema.default('#f9fafb'),\n accentColor: HexColorSchema.default('#818cf8'),\n});\n\nexport const RecentPurchasePopupConfigSchema = z.object({\n title: z.string().trim().min(1, 'Title is required').max(80, 'Title must be 80 characters or fewer').default('Recent purchases'),\n lookbackHours: z.number().int().min(1).max(168).default(24),\n cooldownSeconds: z.number().int().min(5).max(300).default(20),\n maxItems: z.number().int().min(1).max(20).default(8),\n anonymizeMode: z.enum([\n 'first_name_city',\n 'first_name_country',\n 'initial_country',\n 'anonymous',\n ]).default('first_name_city'),\n includedProductIds: z.array(z.string().min(1)).max(50).default([]),\n});\n\nexport const CouponPopupModalConfigSchema = z.object({\n eyebrow: z.string().trim().max(32, 'Eyebrow must be 32 characters or fewer').optional().nullable(),\n title: z.string().trim().min(1, 'Title is required').max(80, 'Title must be 80 characters or fewer'),\n body: z.string().trim().min(1, 'Body is required').max(240, 'Body must be 240 characters or fewer'),\n couponCode: z.string().trim().min(2, 'Coupon code is required').max(40, 'Coupon code must be 40 characters or fewer'),\n primaryButtonLabel: z.string().trim().min(1, 'Primary button label is required').max(24, 'Primary button label must be 24 characters or fewer').default('Copy code'),\n secondaryButtonLabel: z.string().trim().min(1, 'Secondary button label is required').max(24, 'Secondary button label must be 24 characters or fewer').default('Maybe later'),\n disclaimer: z.string().trim().max(100, 'Disclaimer must be 100 characters or fewer').optional().nullable(),\n themePreset: CouponPopupModalThemePresetSchema.default('midnight'),\n trigger: CouponPopupModalTriggerSchema.default('delay'),\n delaySeconds: z.number().int().min(0).max(60).default(6),\n showOncePerSession: z.boolean().default(true),\n reminderHours: z.number().int().min(1).max(720).default(24),\n backgroundColor: HexColorSchema.default('#111827'),\n textColor: HexColorSchema.default('#f8fafc'),\n accentColor: HexColorSchema.default('#7c9cff'),\n heroImageUrl: RelativeOrAbsoluteUrlSchema.optional().nullable(),\n discountDisplay: z.string().trim().max(24, 'Discount display must be 24 characters or fewer').optional().nullable(),\n expiresAt: DatetimeStringSchema.optional().nullable(),\n});\n\nexport const liveChatContactFieldsValues = [\n 'hidden',\n 'optional',\n] as const;\n\nexport const LiveChatContactFieldsSchema = z.enum(liveChatContactFieldsValues);\n\nexport const LiveChatConfigSchema = z.object({\n headline: z.string().trim().min(1, 'Headline is required').max(60, 'Headline must be 60 characters or fewer').default('Chat with us'),\n greeting: z.string().trim().min(1, 'Greeting is required').max(240, 'Greeting must be 240 characters or fewer').default('Hi! Send us a message and we will reply as soon as possible.'),\n inputPlaceholder: z.string().trim().min(1, 'Placeholder is required').max(80, 'Placeholder must be 80 characters or fewer').default('Type your message…'),\n contactFields: LiveChatContactFieldsSchema.default('optional'),\n accentColor: HexColorSchema.default('#111827'),\n launcherIconColor: HexColorSchema.default('#f9fafb'),\n});\n\nexport type LiveChatConfig = z.infer<typeof LiveChatConfigSchema>;\n\nexport type AnnouncementBarConfig = z.infer<typeof AnnouncementBarConfigSchema>;\nexport type CountdownBarConfig = z.infer<typeof CountdownBarConfigSchema>;\nexport type PromoInfoCardConfig = z.infer<typeof PromoInfoCardConfigSchema>;\nexport type RecentPurchasePopupConfig = z.infer<typeof RecentPurchasePopupConfigSchema>;\nexport type CouponPopupModalConfig = z.infer<typeof CouponPopupModalConfigSchema>;\n\nexport type StorefrontAddonConfigByType = {\n announcement_bar: AnnouncementBarConfig;\n countdown_bar: CountdownBarConfig;\n promo_info_card: PromoInfoCardConfig;\n recent_purchase_popup: RecentPurchasePopupConfig;\n coupon_popup_modal: CouponPopupModalConfig;\n live_chat: LiveChatConfig;\n};\n\nexport const StorefrontAddonConfigSchemaByType = {\n announcement_bar: AnnouncementBarConfigSchema,\n countdown_bar: CountdownBarConfigSchema,\n promo_info_card: PromoInfoCardConfigSchema,\n recent_purchase_popup: RecentPurchasePopupConfigSchema,\n coupon_popup_modal: CouponPopupModalConfigSchema,\n live_chat: LiveChatConfigSchema,\n} as const satisfies Record<StorefrontAddonType, z.ZodTypeAny>;\n\nconst AnnouncementBarDraftSchema = z.object({\n type: z.literal('announcement_bar'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: AnnouncementBarConfigSchema,\n});\n\nconst RecentPurchasePopupDraftSchema = z.object({\n type: z.literal('recent_purchase_popup'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: RecentPurchasePopupConfigSchema,\n});\n\nconst CountdownBarDraftSchema = z.object({\n type: z.literal('countdown_bar'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: CountdownBarConfigSchema,\n});\n\nconst PromoInfoCardDraftSchema = z.object({\n type: z.literal('promo_info_card'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: PromoInfoCardConfigSchema,\n});\n\nconst CouponPopupModalDraftSchema = z.object({\n type: z.literal('coupon_popup_modal'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: CouponPopupModalConfigSchema,\n});\n\nconst LiveChatDraftSchema = z.object({\n type: z.literal('live_chat'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: LiveChatConfigSchema,\n});\n\nexport const StorefrontAddonCreateSchema = z.discriminatedUnion('type', [\n AnnouncementBarDraftSchema,\n CountdownBarDraftSchema,\n PromoInfoCardDraftSchema,\n RecentPurchasePopupDraftSchema,\n CouponPopupModalDraftSchema,\n LiveChatDraftSchema,\n]);\n\nexport const StorefrontAddonUpdateSchema = z.discriminatedUnion('type', [\n AnnouncementBarDraftSchema.extend({\n id: z.string().min(1),\n }),\n CountdownBarDraftSchema.extend({\n id: z.string().min(1),\n }),\n PromoInfoCardDraftSchema.extend({\n id: z.string().min(1),\n }),\n RecentPurchasePopupDraftSchema.extend({\n id: z.string().min(1),\n }),\n CouponPopupModalDraftSchema.extend({\n id: z.string().min(1),\n }),\n LiveChatDraftSchema.extend({\n id: z.string().min(1),\n }),\n]);\n\nexport type StorefrontAddonCreateInput = z.infer<typeof StorefrontAddonCreateSchema>;\nexport type StorefrontAddonUpdateInput = z.infer<typeof StorefrontAddonUpdateSchema>;\n\nexport interface StorefrontAddonInstanceBase {\n id: string;\n shopId: string;\n type: StorefrontAddonType;\n slot: StorefrontAddonSlot;\n enabled: boolean;\n sortOrder: number;\n createdAt: string;\n updatedAt: string;\n}\n\nexport type StorefrontAddonInstance =\n | (StorefrontAddonInstanceBase & {\n type: 'announcement_bar';\n config: AnnouncementBarConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'countdown_bar';\n config: CountdownBarConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'promo_info_card';\n config: PromoInfoCardConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'recent_purchase_popup';\n config: RecentPurchasePopupConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'coupon_popup_modal';\n config: CouponPopupModalConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'live_chat';\n config: LiveChatConfig;\n });\n\nexport interface StorefrontAddonCatalogItem {\n type: StorefrontAddonType;\n title: string;\n description: string;\n slots: StorefrontAddonSlot[];\n supportsMultiple: boolean;\n features: string[];\n defaults: StorefrontAddonCreateInput;\n}\n\nexport interface AnnouncementBarResolvedProps extends AnnouncementBarConfig {\n addonId: string;\n}\n\nexport interface CountdownBarResolvedProps extends CountdownBarConfig {\n addonId: string;\n}\n\nexport interface PromoInfoCardResolvedProps extends PromoInfoCardConfig {\n addonId: string;\n}\n\nexport interface RecentPurchasePopupItem {\n customerLabel: string;\n productTitle: string;\n createdAt: string;\n}\n\nexport interface RecentPurchasePopupResolvedProps {\n addonId: string;\n title: string;\n cooldownSeconds: number;\n items: RecentPurchasePopupItem[];\n}\n\nexport interface CouponPopupModalResolvedProps extends CouponPopupModalConfig {\n addonId: string;\n}\n\nexport interface LiveChatResolvedProps extends LiveChatConfig {\n addonId: string;\n}\n\nexport type ResolvedStorefrontAddon =\n | {\n id: string;\n type: 'announcement_bar';\n slot: StorefrontAddonSlot;\n component: 'announcement_bar';\n sortOrder: number;\n props: AnnouncementBarResolvedProps;\n }\n | {\n id: string;\n type: 'countdown_bar';\n slot: StorefrontAddonSlot;\n component: 'countdown_bar';\n sortOrder: number;\n props: CountdownBarResolvedProps;\n }\n | {\n id: string;\n type: 'promo_info_card';\n slot: StorefrontAddonSlot;\n component: 'promo_info_card';\n sortOrder: number;\n props: PromoInfoCardResolvedProps;\n }\n | {\n id: string;\n type: 'recent_purchase_popup';\n slot: StorefrontAddonSlot;\n component: 'recent_purchase_popup';\n sortOrder: number;\n props: RecentPurchasePopupResolvedProps;\n }\n | {\n id: string;\n type: 'coupon_popup_modal';\n slot: StorefrontAddonSlot;\n component: 'coupon_popup_modal';\n sortOrder: number;\n props: CouponPopupModalResolvedProps;\n }\n | {\n id: string;\n type: 'live_chat';\n slot: StorefrontAddonSlot;\n component: 'live_chat';\n sortOrder: number;\n props: LiveChatResolvedProps;\n };\n\nexport interface StorefrontAddonBootstrap {\n items: ResolvedStorefrontAddon[];\n}\n","export const MANUAL_GATEWAY_TEMPLATE_VARIABLES = [\n 'amount',\n 'currency',\n 'invoice_id',\n 'customer_email',\n 'id',\n 'email',\n 'price',\n 'price_usd',\n 'product_name',\n 'quantity',\n] as const;\n\nexport type ManualGatewayTemplateVariable = typeof MANUAL_GATEWAY_TEMPLATE_VARIABLES[number];\nexport type ManualGatewayTemplateVars = Record<string, string>;\n\nexport const MANUAL_GATEWAY_TEMPLATE_VARIABLE_EXAMPLES = [\n '{{amount}}',\n '{{currency}}',\n '{{invoice_id}}',\n '{{customer_email}}',\n '{id}',\n '{email}',\n '{price}',\n '{currency}',\n '{price_usd}',\n '{product_name}',\n '{quantity}',\n] as const;\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction buildVariablePattern(key: string, style: 'double' | 'single'): RegExp {\n const escapedKey = escapeRegExp(key);\n if (style === 'double') {\n return new RegExp(`\\\\{\\\\{\\\\s*${escapedKey}\\\\s*\\\\}\\\\}`, 'gi');\n }\n\n return new RegExp(`(?<!\\\\{)\\\\{\\\\s*${escapedKey}\\\\s*\\\\}(?!\\\\})`, 'gi');\n}\n\nexport function renderManualGatewayTemplate(\n template: string,\n vars: ManualGatewayTemplateVars,\n options: { encodeValues?: boolean } = {},\n): string {\n let rendered = template;\n for (const [key, value] of Object.entries(vars)) {\n const replacement = options.encodeValues ? encodeURIComponent(value) : value;\n rendered = rendered.replace(buildVariablePattern(key, 'double'), replacement);\n rendered = rendered.replace(buildVariablePattern(key, 'single'), replacement);\n }\n return rendered;\n}\n\nconst PLACEHOLDER_SCAN_PATTERNS = [\n /\\{\\{\\s*([a-zA-Z][a-zA-Z0-9_]*)\\s*\\}\\}/g,\n /(?<!\\{)\\{\\s*([a-zA-Z][a-zA-Z0-9_]*)\\s*\\}(?!\\})/g,\n] as const;\n\nconst REMAINING_PLACEHOLDER_PATTERNS = [\n /\\{\\{[\\s\\S]*?\\}\\}/g,\n /(?<!\\{)\\{[^{}]+\\}(?!\\})/g,\n] as const;\n\nexport const MANUAL_GATEWAY_CUSTOM_FIELD_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*$/;\n\nexport function isValidManualGatewayCustomFieldName(name: string): boolean {\n return MANUAL_GATEWAY_CUSTOM_FIELD_NAME_PATTERN.test(name.trim());\n}\n\nexport function findUnsupportedManualGatewayPlaceholders(\n template: string,\n additionalVariables: Iterable<string> = [],\n): string[] {\n if (!template.trim()) {\n return [];\n }\n\n const allowedVariables = new Set<string>(MANUAL_GATEWAY_TEMPLATE_VARIABLES);\n for (const variable of additionalVariables) {\n const normalized = variable.trim().toLowerCase();\n if (normalized) {\n allowedVariables.add(normalized);\n }\n }\n\n const unsupported = new Set<string>();\n // Track the raw spans of syntactically-valid placeholders that ARE allowed, so\n // we don't double-flag them when sweeping for malformed syntax below.\n const allowedRawSpans = new Set<string>();\n for (const pattern of PLACEHOLDER_SCAN_PATTERNS) {\n for (const match of template.matchAll(pattern)) {\n const raw = match[0];\n const name = match[1]?.toLowerCase();\n if (name && !allowedVariables.has(name)) {\n unsupported.add(raw);\n } else if (name) {\n allowedRawSpans.add(raw);\n }\n }\n }\n\n // Also reject ANY remaining {{...}}/{...} placeholder syntax that is not an\n // allowed variable — a mistyped or filtered token such as `{{order-id}}` or\n // `{{ amount | money }}` is not caught by the strict name patterns above, so\n // it would survive save and only fail at checkout (session 400 / raw token in\n // instructions). Flag it at save time instead.\n for (const pattern of REMAINING_PLACEHOLDER_PATTERNS) {\n for (const match of template.matchAll(pattern)) {\n const raw = match[0];\n if (!allowedRawSpans.has(raw)) {\n unsupported.add(raw);\n }\n }\n }\n\n return [...unsupported];\n}\n\nexport function collectUnsupportedManualGatewayPlaceholders(\n ...templates: Array<string | null | undefined>\n): string[] {\n const unsupported = new Set<string>();\n for (const template of templates) {\n for (const placeholder of findUnsupportedManualGatewayPlaceholders(template ?? '')) {\n unsupported.add(placeholder);\n }\n }\n return [...unsupported];\n}\n\nexport function collectUnsupportedManualGatewayPlaceholdersWithExtras(\n additionalVariables: Iterable<string>,\n ...templates: Array<string | null | undefined>\n): string[] {\n const unsupported = new Set<string>();\n for (const template of templates) {\n for (const placeholder of findUnsupportedManualGatewayPlaceholders(template ?? '', additionalVariables)) {\n unsupported.add(placeholder);\n }\n }\n return [...unsupported];\n}\n\nconst RESERVED_MANUAL_GATEWAY_FIELD_NAMES = new Set<string>(\n MANUAL_GATEWAY_TEMPLATE_VARIABLES.map((name) => name.toLowerCase()),\n);\n\nexport function isReservedManualGatewayFieldName(name: string): boolean {\n const normalized = name.trim().toLowerCase();\n return normalized.length > 0 && RESERVED_MANUAL_GATEWAY_FIELD_NAMES.has(normalized);\n}\n\nexport function findRemainingManualGatewayPlaceholders(template: string): string[] {\n if (!template.trim()) {\n return [];\n }\n\n const remaining = new Set<string>();\n for (const pattern of REMAINING_PLACEHOLDER_PATTERNS) {\n for (const match of template.matchAll(pattern)) {\n remaining.add(match[0]);\n }\n }\n\n return [...remaining];\n}\n\nexport function stableGatewayFieldValuesKey(fields: Record<string, string> | null | undefined): string {\n if (!fields) {\n return '{}';\n }\n\n const sortedEntries = Object.keys(fields)\n .sort((left, right) => left.localeCompare(right))\n .map((key) => [key, fields[key]] as const);\n\n return JSON.stringify(sortedEntries);\n}\n\nexport function isSafeManualGatewayRedirectUrl(url: string): boolean {\n const trimmed = url.trim();\n if (!trimmed) {\n return false;\n }\n\n try {\n const parsed = new URL(trimmed);\n return parsed.protocol === 'http:' || parsed.protocol === 'https:';\n } catch {\n return false;\n }\n}\n\nexport function mergeManualGatewayTemplateVars(\n trustedVars: ManualGatewayTemplateVars,\n gatewayFieldVars: Record<string, string> = {},\n): ManualGatewayTemplateVars {\n return {\n ...gatewayFieldVars,\n ...trustedVars,\n };\n}\n","import { z } from 'zod';\n\nconst unknownRecordSchema = z.record(z.string(), z.unknown());\nconst stringOrNumberSchema = z.union([z.string(), z.number()]);\n\nexport const embedPaymentSessionWireSchema = z.object({\n kind: z.enum(['address', 'redirect', 'embed_pending']),\n gateway: z.string(),\n checkout_url: z.string().nullable().optional(),\n address: z.string().optional(),\n amount: z.string().optional(),\n qr_code: z.string().optional(),\n expires_at: z.string().optional(),\n payment_id: z.string().optional(),\n confirmations_needed: z.number().optional(),\n}).passthrough();\n\n/** Critical runtime boundary for the public embed-start response. */\nexport const embedCheckoutStartWireSchema = z.object({\n data: z.object({\n invoice: z.object({\n uniqid: z.string().uuid(),\n }).passthrough(),\n invoice_url: z.string().nullable(),\n checkout_url: z.string().nullable(),\n selected_gateway: z.string().nullable(),\n session_started: z.boolean(),\n payment_session: embedPaymentSessionWireSchema.nullable(),\n completion_access_grant: z.string().nullable(),\n }).passthrough(),\n}).passthrough();\n\nexport type EmbedCheckoutStartWire = z.infer<typeof embedCheckoutStartWireSchema>;\n\nconst publicInvoiceWireCustomFieldDefinitionSchema = z.object({\n default_value: z.string().optional(),\n min_length: z.number().optional(),\n name: z.string(),\n placeholder: z.string().optional(),\n regex: z.string().optional(),\n required: z.boolean(),\n type: z.string(),\n});\n\nconst publicInvoiceWireProductAddonSchema = z.object({\n id: z.string(),\n price: z.number(),\n quantity: z.number(),\n title: z.string(),\n});\n\nconst publicInvoiceWireProductSchema = z.object({\n addons: z.array(publicInvoiceWireProductAddonSchema).optional(),\n available_addons: z.array(z.unknown()).optional(),\n cloudflare_image_id: z.string().nullable(),\n created_at: z.string().optional(),\n currency: z.string(),\n custom_fields: unknownRecordSchema.nullable().optional(),\n custom_fields_config: z.array(publicInvoiceWireCustomFieldDefinitionSchema).nullable().optional(),\n delivery_instruction: z.unknown().optional(),\n delivery_instruction_config: z.unknown().optional(),\n delivery_instruction_label: z.unknown().optional(),\n delivery_text: z.string().nullable().optional(),\n // Delivery wait as a bare COUNT. `0` and `null` both mean instant (the\n // digital-goods default); a positive value is a \"within N <unit>\" promise.\n delivery_time: z.number().nullable().optional(),\n // The unit `delivery_time` is counted in. The column is NOT NULL with a\n // `days` default — which is what every row meant before the unit existed — so\n // a live producer always sends one. It stays optional here because this\n // schema also describes payment-link and other synthesized products that\n // carry no catalog row, and those quote no wait at all.\n delivery_time_unit: z.enum(['minutes', 'hours', 'days']).nullable().optional(),\n description: z.string().nullable(),\n discount_percent: z.number().optional(),\n discount_display: z.number().optional(),\n discounted_total_display: z.number().optional(),\n gateways: z.array(z.string()).nullable().optional(),\n id: z.string().optional(),\n image_name: z.string().nullable(),\n image_storage: z.string().optional(),\n line_item_id: z.string().nullable().optional(),\n pay_what_you_want: z.boolean().optional(),\n price: z.string().optional(),\n price_display: stringOrNumberSchema,\n quantity: z.number(),\n quantity_max: z.number().optional(),\n quantity_min: z.number().optional(),\n recurring_interval: z.string().nullable().optional(),\n recurring_interval_count: z.number().nullable().optional(),\n redirect_link: z.string().nullable().optional(),\n redirect_time: z.number().nullable().optional(),\n service_text: z.string().nullable().optional(),\n setup_cost: z.string().optional(),\n slug: z.string().nullable().optional(),\n storefront_url: z.string().nullable().optional(),\n status: z.string().nullable().optional(),\n subtype: z.string().nullable().optional(),\n terms_of_service: z.string().nullable().optional(),\n title: z.string(),\n total: z.number(),\n trial_period: z.number().nullable().optional(),\n type: z.string().nullable().optional(),\n uniqid: z.string().nullable(),\n unit_price: z.number().optional(),\n unit_price_display: stringOrNumberSchema.optional(),\n unit_quantity: z.number(),\n updated_at: z.string().optional(),\n variant_title: z.string().nullable().optional(),\n video_link: z.string().nullable().optional(),\n volume_discounts: z.unknown().optional(),\n warranty_days: z.number().nullable().optional(),\n warranty_text: z.string().nullable().optional(),\n});\n\nconst gatewayFeePreviewSchema = z.object({\n amount: z.number(),\n gateway: z.string(),\n});\n\nconst checkoutTippingSchema = z.object({\n custom_tip_enabled: z.boolean().optional(),\n enabled: z.boolean(),\n preset_percentages: z.array(z.number()).optional(),\n});\n\nconst customerBalanceSchema = z.object({\n allow_partial_payment: z.boolean().optional(),\n auto_apply: z.boolean().optional(),\n available: z.string(),\n currency: z.string(),\n});\n\nconst pricingBreakdownSchema = z.object({\n affiliate_code: z.string().nullable().optional(),\n already_paid: stringOrNumberSchema.nullable().optional(),\n amount_due: stringOrNumberSchema.nullable().optional(),\n currency: z.string().nullable().optional(),\n discount: stringOrNumberSchema.nullable().optional(),\n discount_label: z.string().nullable().optional(),\n gateway_fee: stringOrNumberSchema.nullable().optional(),\n platform_fee: stringOrNumberSchema.nullable().optional(),\n subtotal: stringOrNumberSchema.nullable().optional(),\n tip: stringOrNumberSchema.nullable().optional(),\n total: stringOrNumberSchema.nullable().optional(),\n});\n\nconst pollingSchema = z.object({\n active: z.boolean(),\n expires_at: z.string(),\n});\n\nconst supportSchema = z.object({\n faq_url: z.string().nullable(),\n support_email: z.string().nullable(),\n support_url: z.string().nullable(),\n telegram_invite: z.string().nullable(),\n /** shop_social_links.discord — the checkout renders an optional join row from it. */\n discord_invite_url: z.string().nullable(),\n});\n\nconst gatewayEligibilityStateSchema = z.object({\n currency: z.string().nullable().optional(),\n enabled: z.boolean(),\n max_amount: z.number().nullable().optional(),\n min_amount: z.number().nullable().optional(),\n reason: z.enum(['BELOW_MIN_AMOUNT', 'ABOVE_MAX_AMOUNT']).nullable().optional(),\n});\n\nconst deliverySchema = z.object({\n delivered_items: z.array(z.unknown()),\n downloads: z.array(z.unknown()),\n external_urls: z.array(z.unknown()),\n license_keys: z.array(z.unknown()),\n tracking_codes: z.array(z.unknown()),\n});\n\nconst underpaymentSchema = z.object({\n active: z.boolean().optional(),\n attempt_id: z.string().optional(),\n buyer_actionable: z.boolean().nullable().optional(),\n crypto_currency: z.string().nullable().optional(),\n currency: z.string().optional(),\n expected_amount: z.string().nullable().optional(),\n expected_crypto_amount: z.string().nullable().optional(),\n last_checked_at: z.string().optional(),\n missing_amount: z.string().nullable().optional(),\n missing_crypto_amount: z.string().nullable().optional(),\n // InvoiceEnricher.applyUnderpayment serializes providerReference ?? null —\n // an active underpayment without a provider reference is a valid payload.\n provider_reference: z.string().nullable().optional(),\n provider_status: z.string().nullable().optional(),\n received_amount: z.string().nullable().optional(),\n received_crypto_amount: z.string().nullable().optional(),\n shortfall_percent: z.string().nullable().optional(),\n});\n\nconst statusHistoryEntrySchema = z.object({\n created_at: z.string().nullable(),\n details: z.string().nullable(),\n id: z.string(),\n invoice_id: z.string(),\n status: z.string().nullable(),\n});\n\nconst paymentMethodOverrideSchema = z.object({\n billing_address_mode: z.enum(['INHERIT', 'REQUIRED', 'DISABLED']).optional(),\n button_label: z.string().nullable().optional(),\n display_name: z.string().nullable().optional(),\n gateway: z.string(),\n hide_provider_attribution: z.boolean().optional(),\n icon_url: z.string().nullable().optional(),\n terms_mode: z.enum(['INHERIT', 'REQUIRED', 'DISABLED']).optional(),\n});\n\nconst customGatewaySchema = z.object({\n custom_fields: z.array(z.unknown()).optional(),\n description: z.string().nullable(),\n display_order: z.number(),\n icon_preset: z.string().nullable(),\n icon_url: z.string().nullable(),\n id: z.string(),\n instructions: z.string().nullable(),\n is_active: z.boolean().optional(),\n name: z.string(),\n payment_type: z.enum(['INSTRUCTIONS', 'REDIRECT']),\n redirect_url: z.string().nullable(),\n require_proof: z.boolean(),\n // Which fields the buyer has to fill in when proof is required. Optional so\n // an older cached payload stays parseable; the checkout falls back to BOTH.\n proof_type: z.enum(['TEXT', 'IMAGE', 'BOTH']).optional(),\n void_after_hours: z.number(),\n});\n\nconst buyerIdentitySchema = z.object({\n email: z.object({\n masked: z.string().nullable(),\n persisted: z.boolean(),\n required_for_provider_session: z.boolean().optional(),\n }),\n});\n\nconst cryptoTransactionSchema = z.object({\n amount: z.string().nullable(),\n confirmations: z.number().nullable(),\n created_at: z.number().optional(),\n hash: z.string().nullable(),\n status: z.string().optional(),\n});\n\nconst voidTimeSchema = z.object({\n conf: z.object({\n partial: z.number().optional(),\n void: z.number(),\n waiting_for_confirmations: z.number().optional(),\n }),\n gateways: z.array(z.string()),\n});\n\nconst invoicePaymentSessionStateSchema = z.object({\n invoice_payable: z.boolean(),\n resumable: z.boolean(),\n resumable_gateway: z.string().nullable(),\n gateway: z.string().nullable().optional(),\n crypto_gateway: z.string().nullable().optional(),\n processor: z.string().nullable().optional(),\n flow_type: z.string().nullable().optional(),\n status: z.string().nullable().optional(),\n provider_reference: z.string().nullable().optional(),\n provider_reference_type: z.string().nullable().optional(),\n capture_id: z.string().nullable().optional(),\n manual_confirmation_pending: z.boolean().optional(),\n payment_method_switch_locked: z.boolean().optional(),\n awaiting_payment_method: z.boolean().optional(),\n started_at: z.number().nullable().optional(),\n completed_at: z.number().nullable().optional(),\n});\n\n/**\n * Public invoice JSON after `toInvoiceTransportSnakeCase`.\n *\n * Gateway-specific invoice row fields can still pass the backend allowlist.\n * Unknown top-level keys are therefore preserved, while every known key is\n * validated whenever it is present.\n */\nexport const publicInvoiceWireSchema = z.object({\n already_paid_amount: stringOrNumberSchema.nullable().optional(),\n apm_method: z.string().nullable().optional(),\n blockchain: z.string().nullable(),\n buyer_identity: buyerIdentitySchema.nullable().optional(),\n checkout_tipping: checkoutTippingSchema.nullable().optional(),\n country_regulations: z.string().nullable().optional(),\n coupon_applied: z.boolean().optional(),\n crypto_mode: z.string().nullable().optional(),\n crypto_transactions: z.array(cryptoTransactionSchema).optional(),\n currency: z.string().nullable(),\n custom_fields: unknownRecordSchema.nullable().optional(),\n custom_gateways: z.array(customGatewaySchema).optional(),\n customer_balance: customerBalanceSchema.nullable().optional(),\n customer_email_masked: z.string().nullable().optional(),\n dark_mode: z.union([z.literal(0), z.literal(1)]).optional(),\n delivery: deliverySchema.optional(),\n delivery_info: deliverySchema.optional(),\n discount: z.number().optional(),\n discount_display: stringOrNumberSchema.optional(),\n eligible_gateways: z.array(z.string()).optional(),\n environment: z.string().optional(),\n fee_breakdown: unknownRecordSchema.nullable().optional(),\n gateway: z.string().nullable(),\n gateway_data: unknownRecordSchema.nullable().optional(),\n gateway_eligibility: z.record(z.string(), gatewayEligibilityStateSchema).optional(),\n gateway_fee_previews: z.array(gatewayFeePreviewSchema).optional(),\n gateways_available: z.array(z.string()),\n license: z.union([unknownRecordSchema, z.literal(false)]).optional(),\n name: z.string().nullable(),\n paddle_token: z.string().nullable().optional(),\n paddle_transaction_id: z.unknown().optional(),\n payment_link_id: z.string().nullable().optional(),\n payment_method_overrides: z.array(paymentMethodOverrideSchema).optional(),\n payment_session_state: invoicePaymentSessionStateSchema.nullable().optional(),\n polling: pollingSchema,\n pricing_breakdown: pricingBreakdownSchema.nullable().optional(),\n product: z.array(publicInvoiceWireProductSchema).optional(),\n quantity: z.number().nullable(),\n rates_snapshot: z.record(z.string(), z.number()).optional(),\n remaining_amount: stringOrNumberSchema.nullable().optional(),\n selected_gateway: z.string().nullable().optional(),\n shop_checkout_ambient_color: z.string().nullable().optional(),\n shop_cloudflare_image_id: z.string().nullable(),\n shop_domain: z.string().nullable().optional(),\n shop_force_paypal_email_delivery: z.union([z.literal(0), z.literal(1)]).optional(),\n shop_image_name: z.string().nullable(),\n shop_image_storage: z.string().nullable().optional(),\n shop_payment_gateways_fees: z.array(unknownRecordSchema).optional(),\n shop_paypal_credit_card: z.union([z.literal(0), z.literal(1)]).optional(),\n shop_return_url: z.string().nullable().optional(),\n shop_slug: z.string().nullable().optional(),\n shop_terms_enabled: z.boolean().optional(),\n shop_terms_of_service: z.string().nullable().optional(),\n shop_terms_url: z.string().nullable().optional(),\n shop_privacy_policy_url: z.string().nullable().optional(),\n shop_refund_policy_url: z.string().nullable().optional(),\n shop_walletconnect_id: z.string().nullable().optional(),\n status: z.string().nullable(),\n status_history: z.array(statusHistoryEntrySchema).optional(),\n status_history_legacy: z.array(statusHistoryEntrySchema).optional(),\n status_history_raw: z.array(statusHistoryEntrySchema).optional(),\n stripe_publishable_key: z.string().nullable().optional(),\n stripe_user_id: z.string().nullable().optional(),\n subtotal: z.number().optional(),\n subtype: z.string().nullable().optional(),\n support: supportSchema.optional(),\n theme: z.string().optional(),\n tip_amount: stringOrNumberSchema.nullable().optional(),\n tip_amount_display: stringOrNumberSchema.nullable().optional(),\n tip_metadata: z.unknown().optional(),\n total: stringOrNumberSchema,\n total_conversions: unknownRecordSchema.optional(),\n total_display: stringOrNumberSchema,\n type: z.string().nullable(),\n underpayment: underpaymentSchema.nullable().optional(),\n underpayment_status: z.string().nullable().optional(),\n uniqid: z.string(),\n void_times: z.array(voidTimeSchema).optional(),\n\n // PUBLIC_INVOICE_FIELDS entries not exercised by the golden fixtures.\n addons: z.unknown().optional(),\n affiliate_data: z.unknown().optional(),\n affiliate_revenue_customer_id: z.string().nullable().optional(),\n bill_info: z.unknown().optional(),\n binance_checkout_url: z.string().nullable().optional(),\n binance_invoice_id: z.string().nullable().optional(),\n binance_qrcode: z.string().nullable().optional(),\n bundle_config: z.unknown().optional(),\n bundles: z.unknown().optional(),\n cashapp_cashtag: z.string().nullable().optional(),\n cashapp_note: z.string().nullable().optional(),\n cashapp_qrcode: z.string().nullable().optional(),\n created_at: z.string().optional(),\n crypto_address: z.string().nullable().optional(),\n crypto_amount: stringOrNumberSchema.optional(),\n crypto_confirmations_needed: z.number().nullable().optional(),\n crypto_exchange_rate: stringOrNumberSchema.nullable().optional(),\n crypto_received: stringOrNumberSchema.optional(),\n crypto_uri: z.string().nullable().optional(),\n developer_invoice: z.unknown().optional(),\n developer_return_url: z.string().nullable().optional(),\n developer_title: z.string().nullable().optional(),\n exchange_rate: stringOrNumberSchema.nullable().optional(),\n external_order_id: z.string().nullable().optional(),\n lex_order_id: z.string().nullable().optional(),\n lex_payment_method: z.string().nullable().optional(),\n paydash_payment_id: z.string().nullable().optional(),\n paypal_apm: z.string().nullable().optional(),\n paypal_email_delivery: z.boolean().optional(),\n paypal_fee: stringOrNumberSchema.nullable().optional(),\n paypal_order_id: z.string().nullable().optional(),\n paypal_payer_email: z.string().nullable().optional(),\n paypal_subscription_id: z.string().nullable().optional(),\n paypal_subscription_link: z.string().nullable().optional(),\n perfectmoney_id: z.string().nullable().optional(),\n product_addons: z.unknown().optional(),\n product_id: z.string().nullable().optional(),\n product_title: z.string().nullable().optional(),\n product_type: z.string().nullable().optional(),\n product_variants: z.unknown().optional(),\n recurring_billing_id: z.string().nullable().optional(),\n skrill_link: z.string().nullable().optional(),\n skrill_sid: z.string().nullable().optional(),\n status_details: z.unknown().optional(),\n stripe_apm: z.string().nullable().optional(),\n stripe_client_secret: z.string().nullable().optional(),\n stripe_id: z.string().nullable().optional(),\n stripe_price_id: z.string().nullable().optional(),\n subscription: z.unknown().optional(),\n subscription_id: z.string().nullable().optional(),\n sumup_id: z.string().nullable().optional(),\n telegram_stars_payment_link: z.string().nullable().optional(),\n telegram_stars_payment_note: z.string().nullable().optional(),\n updated_at: z.string().optional(),\n virtual_payments_id: z.string().nullable().optional(),\n void_details: z.unknown().optional(),\n}).catchall(z.unknown());\n\nexport type PublicInvoiceWire = z.infer<typeof publicInvoiceWireSchema>;\n","/**\n * Catalog unit prices support mills (one thousandth of a currency unit).\n *\n * This is intentionally separate from invoice and payment totals. A unit can\n * cost $0.012, while the payable line total is still rounded to the currency's\n * minor unit after `unit price × quantity`.\n */\nexport const CATALOG_UNIT_PRICE_DECIMAL_PLACES = 3;\n\n/**\n * Payable line amounts and invoice totals remain cent amounts. This is a\n * separate boundary from catalog unit prices: multiply the mill-priced unit by\n * quantity first, then round the resulting line amount to this precision.\n */\nexport const PAYABLE_AMOUNT_DECIMAL_PLACES = 2;\n\nexport const CATALOG_UNIT_PRICE_FORMAT_OPTIONS = {\n maximumFractionDigits: CATALOG_UNIT_PRICE_DECIMAL_PLACES,\n} as const;\n\n/**\n * Browser-safe half-up rounding for non-negative payable amounts.\n *\n * The exponent shift avoids the common `1.005 * 100` binary-float trap and\n * mirrors the backend's decimal.js ROUND_HALF_UP policy. Negative values are\n * handled symmetrically so the helper remains safe for display calculations.\n */\nexport function roundPayableAmount(value: number): number {\n if (!Number.isFinite(value)) return value;\n\n const sign = value < 0 ? -1 : 1;\n const shifted = shiftDecimal(Math.abs(value), PAYABLE_AMOUNT_DECIMAL_PLACES);\n const rounded = Math.round(shifted);\n if (rounded === 0) return 0;\n return sign * shiftDecimal(rounded, -PAYABLE_AMOUNT_DECIMAL_PLACES);\n}\n\nfunction shiftDecimal(value: number, places: number): number {\n const [coefficient, currentExponent = '0'] = String(value).split('e');\n return Number(`${coefficient}e${Number(currentExponent) + places}`);\n}\n\nfunction countSignificantDecimalPlaces(value: string | number): number | null {\n const source = String(value).trim();\n const match = source.match(/^[-+]?(\\d+)(?:\\.(\\d*))?(?:e([-+]?\\d+))?$/i)\n ?? source.match(/^[-+]?\\.(\\d+)(?:e([-+]?\\d+))?$/i);\n if (!match) return null;\n\n const startsWithDecimalPoint = /^[-+]?\\./.test(source);\n const integerPart = startsWithDecimalPoint ? '0' : match[1];\n const fractionPart = startsWithDecimalPoint ? match[1] : (match[2] ?? '');\n const exponentText = startsWithDecimalPoint ? match[2] : match[3];\n const exponent = Number(exponentText ?? 0);\n if (!Number.isInteger(exponent)) return null;\n\n const digitsWithoutInsignificantZeros = `${integerPart}${fractionPart}`.replace(/0+$/, '');\n if (digitsWithoutInsignificantZeros.length === 0) return 0;\n\n const decimalPoint = integerPart.length + exponent;\n return Math.max(0, digitsWithoutInsignificantZeros.length - decimalPoint);\n}\n\nexport function hasCatalogUnitPricePrecision(value: string | number): boolean {\n const decimalPlaces = countSignificantDecimalPlaces(value);\n return decimalPlaces !== null && decimalPlaces <= CATALOG_UNIT_PRICE_DECIMAL_PLACES;\n}\n\nexport function getCatalogUnitPricePrecisionMessage(value: string | number): string {\n return `Price supports at most ${CATALOG_UNIT_PRICE_DECIMAL_PLACES} decimal places; received ${String(value)}.`;\n}\n","import { z } from 'zod';\n\nconst nullableStringSchema = z.string().nullable();\nconst unknownRecordSchema = z.record(z.string(), z.unknown());\n\nconst customerPortalBrandingSchema = z.object({\n logo_url: nullableStringSchema,\n primary_color: z.string(),\n secondary_color: z.string(),\n accent_color: z.string(),\n});\n\nconst customerPortalProductImageSnakeSchema = z.object({\n attachment_image_id: z.object({\n cloudflare_image_id: nullableStringSchema,\n }).nullable(),\n});\n\nconst customerPortalProductImageCamelSchema = z.object({\n attachment_imageId: z.object({\n cloudflareImageId: nullableStringSchema,\n }).nullable(),\n});\n\nexport const customerPortalDashboardInvoiceSchema = z.object({\n uniqid: z.string(),\n status: z.string(),\n total: z.string(),\n total_display: nullableStringSchema,\n currency: z.string(),\n created_at: z.string(),\n line_items: z.array(z.object({\n product_title: nullableStringSchema,\n quantity: z.number(),\n product: customerPortalProductImageSnakeSchema.nullable(),\n })),\n});\n\nexport const customerPortalPaginatedInvoiceSchema = z.object({\n uniqid: z.string(),\n status: z.string(),\n total: z.string(),\n totalDisplay: nullableStringSchema,\n currency: z.string(),\n createdAt: z.string(),\n lineItems: z.array(z.object({\n productTitle: nullableStringSchema,\n quantity: z.number(),\n product: customerPortalProductImageCamelSchema.nullable(),\n })),\n});\n\nexport const customerPortalPaginatedInvoicesSchema = z.object({\n invoices: z.array(customerPortalPaginatedInvoiceSchema),\n pagination: z.object({\n page: z.number(),\n limit: z.number(),\n total: z.number(),\n has_more: z.boolean(),\n }),\n});\n\nconst customerPortalPaymentSchema = z.object({\n gateway: z.string(),\n /** Merchant-configured buyer label frozen when the payment attempt started. */\n displayName: nullableStringSchema,\n /** Concrete coin gateway key (e.g. USDT_TRC20) for crypto payments — the\n * buyer-facing label; `gateway` may carry an internal rail name. */\n cryptoGateway: nullableStringSchema.optional(),\n blockchain: nullableStringSchema,\n cryptoAddress: nullableStringSchema,\n apmMethod: nullableStringSchema,\n});\n\nexport const customerPortalInvoiceDetailSchema = z.object({\n id: z.string(),\n uniqid: z.string(),\n status: z.string(),\n statusDetails: nullableStringSchema,\n total: z.string(),\n totalDisplay: nullableStringSchema,\n subtotal: z.string(),\n discount: z.string(),\n discountDisplay: nullableStringSchema,\n tax: z.string(),\n taxPercentage: z.string(),\n currency: z.string(),\n createdAt: z.string(),\n updatedAt: z.string(),\n gatewayUpdatedAt: nullableStringSchema,\n customFields: unknownRecordSchema.nullable(),\n balancePaidAmount: z.string(),\n currentPaymentAttemptId: nullableStringSchema,\n lineItems: z.array(z.object({\n id: z.string(),\n productTitle: z.string(),\n productType: z.string(),\n variantTitle: nullableStringSchema,\n unitPrice: z.string(),\n quantity: z.number(),\n total: z.string(),\n deliveryText: nullableStringSchema,\n deliverySummary: z.object({\n codes: z.array(z.string()),\n links: z.array(z.object({\n label: z.string(),\n value: z.string(),\n href: nullableStringSchema.optional(),\n })),\n notes: z.array(z.string()),\n serials: z.array(z.object({\n value: z.string(),\n is_replacement: z.boolean(),\n is_replaced: z.boolean(),\n })),\n }).nullable(),\n deliveredAt: nullableStringSchema,\n /**\n * Per-line fulfillment state, resolved server-side\n * (docs/architecture/domains/order-fulfillment.md). Independent of the\n * invoice payment status: a COMPLETED order can still hold items the\n * seller delivers later.\n */\n deliveryStatus: z.enum(['PENDING', 'AWAITING_FULFILLMENT', 'DELIVERED', 'FAILED']),\n customFields: unknownRecordSchema.nullable(),\n product: z.object({\n uniqid: z.string(),\n slug: nullableStringSchema,\n serviceText: nullableStringSchema,\n attachment_imageId: z.object({\n cloudflareImageId: nullableStringSchema,\n }).nullable(),\n }).nullable(),\n })),\n currentPayment: customerPortalPaymentSchema.nullable(),\n payments: z.array(customerPortalPaymentSchema),\n});\n\nexport const customerPortalWalletTopupQuoteSchema = z.object({\n quote: z.object({\n enabled: z.boolean(),\n currency: z.string(),\n min_amount: z.string(),\n max_amount: nullableStringSchema,\n bonus_tiers: z.array(z.object({\n min_amount: z.string(),\n bonus_percent: z.number(),\n })),\n }),\n});\n\nexport const customerPortalWalletTopupResultSchema = z.object({\n invoice_id: z.string(),\n url: z.string(),\n});\n\nexport const customerPortalRewardActivityItemSchema = z.object({\n id: z.string(),\n type: z.string(),\n status: z.string(),\n amount: nullableStringSchema,\n currency: nullableStringSchema,\n coupon_code: nullableStringSchema,\n reason: z.string(),\n trigger_reference_type: z.string(),\n trigger_reference_id: z.string(),\n created_at: z.number(),\n fulfilled_at: z.number().nullable(),\n expires_at: z.number().nullable(),\n});\n\nexport const customerPortalRewardsSchema = z.object({\n summary: z.object({\n available: z.string(),\n pending: z.string(),\n lifetime_earned: z.string(),\n redeemed: nullableStringSchema,\n currency: z.string(),\n }),\n activity: z.array(customerPortalRewardActivityItemSchema),\n earned_after_invoice: z.array(customerPortalRewardActivityItemSchema),\n pending_after_invoice: z.array(customerPortalRewardActivityItemSchema),\n});\n\nconst customerPortalAffiliateLinkSchema = z.object({\n id: z.string(),\n uniqid: z.string(),\n label: nullableStringSchema,\n code: z.string(),\n url: nullableStringSchema,\n status: z.enum(['pending', 'active', 'inactive', 'rejected']),\n is_primary: z.boolean(),\n total_clicks: z.number(),\n total_sales: z.number(),\n total_revenue: z.string(),\n is_active: z.boolean(),\n is_approved: z.boolean(),\n requested_affiliate_revenue_percent: z.number().nullable(),\n requested_affiliate_customer_discount_percent: z.number().nullable(),\n affiliate_revenue_percent_override: z.number().nullable(),\n affiliate_customer_discount_percent_override: z.number().nullable(),\n effective_commission_percent: z.number(),\n effective_customer_discount_percent: z.number(),\n commission_shareback_percent: z.number(),\n commission_shareback_enabled: z.boolean(),\n max_commission_shareback_percent: z.number(),\n created_at: nullableStringSchema,\n updated_at: nullableStringSchema,\n});\n\nexport const customerPortalAffiliateSummarySchema = z.object({\n customer: z.object({\n id: z.string(),\n email: z.string(),\n name: nullableStringSchema,\n }).nullable(),\n state: z.string(),\n can_create_custom_links: z.boolean(),\n custom_link_request_disabled_reason: nullableStringSchema,\n custom_links_require_approval: z.boolean(),\n affiliate_codes_accepted_at_checkout: z.boolean(),\n cash_payout_enabled: z.boolean(),\n links: z.array(customerPortalAffiliateLinkSchema),\n preferred_payout: z.object({\n asset: z.string(),\n network: z.string(),\n address: z.string(),\n }).nullable(),\n balance_currency: z.string(),\n balances: z.object({\n pending: z.string(),\n available: z.string(),\n requested: z.string(),\n converted: z.string(),\n paid: z.string(),\n approved_total: z.string(),\n }),\n commissions: z.array(z.object({\n id: z.string(),\n invoice_id: z.string(),\n commission_amount: z.string(),\n base_amount: z.string(),\n discount_amount: z.string(),\n status: z.string(),\n created_at: nullableStringSchema,\n paid_at: nullableStringSchema,\n converted_at: nullableStringSchema,\n })),\n claims: z.array(z.object({\n id: z.string(),\n type: z.string(),\n status: z.string(),\n amount: z.string(),\n currency: z.string(),\n allocations: z.array(z.object({\n source_type: z.string(),\n commission_id: nullableStringSchema,\n adjustment_id: nullableStringSchema,\n amount: z.string(),\n })),\n wallet_transaction_id: nullableStringSchema,\n payout_asset: nullableStringSchema,\n payout_network: nullableStringSchema,\n payout_address: nullableStringSchema,\n note: nullableStringSchema,\n metadata: z.unknown(),\n completed_at: nullableStringSchema,\n rejected_at: nullableStringSchema,\n cancelled_at: nullableStringSchema,\n created_at: nullableStringSchema,\n updated_at: nullableStringSchema,\n })),\n});\n\nexport const customerPortalSubscriptionSummarySchema = z.object({\n uniqid: z.string(),\n status: z.string(),\n gateway: z.string(),\n current_period_start: z.string(),\n current_period_end: z.string(),\n trial_end: nullableStringSchema,\n cancel_at_period_end: z.boolean(),\n canceled_at: nullableStringSchema,\n created_at: z.string(),\n plan: z.object({\n id: z.string(),\n uniqid: z.string(),\n name: z.string(),\n price: z.string(),\n currency: z.string(),\n interval: z.string(),\n interval_count: z.number(),\n trial_days: z.number(),\n }).nullable(),\n payment_method: z.object({\n id: z.string(),\n gateway: z.string(),\n type: z.string(),\n card_brand: nullableStringSchema,\n card_last4: nullableStringSchema,\n card_exp_month: z.number().nullable(),\n card_exp_year: z.number().nullable(),\n is_default: z.boolean(),\n }).nullable(),\n actions: z.object({\n can_pause: z.boolean(),\n can_resume: z.boolean(),\n can_cancel: z.boolean(),\n can_manage_payment_method: z.boolean(),\n }),\n});\n\nexport const customerPortalDashboardSchema = z.object({\n shop: z.object({\n id: z.string(),\n slug: z.string(),\n name: z.string(),\n currency: z.string(),\n branding: customerPortalBrandingSchema,\n }),\n customer: z.object({\n email: z.string(),\n name: z.string(),\n }),\n stats: z.object({\n invoices_count: z.number(),\n licenses_count: z.number(),\n deliverables_count: z.number(),\n tickets_count: z.number(),\n }),\n wallet: z.object({\n available: z.string(),\n total: z.string(),\n hold: z.string(),\n currency: z.string(),\n enabled: z.boolean(),\n }).nullable(),\n rewards: customerPortalRewardsSchema,\n affiliate: customerPortalAffiliateSummarySchema,\n invoices: z.array(customerPortalDashboardInvoiceSchema),\n subscriptions: z.array(customerPortalSubscriptionSummarySchema),\n licenses: z.array(z.object({\n uniqid: z.string(),\n /*\n * Both of these are produced by `getCustomerProductsLicenses` and were\n * simply missing here. Without `invoice_id` a consumer cannot tell which\n * purchase a license belongs to, and without `status` it cannot tell an\n * active license from a suspended, revoked or expired one — the projection\n * computes exactly that.\n */\n invoice_id: z.string(),\n status: z.string(),\n license_key: z.string(),\n hardware_id: nullableStringSchema,\n expires_at: z.number().nullable(),\n /*\n * Server-decided: the product behind this license still exists, still\n * sells through storefront checkout, and still has licensing enabled.\n * The portal cannot derive any of that, so it renders the renew action\n * from this flag alone instead of guessing and offering a dead button.\n */\n renewable: z.boolean(),\n product: z.object({\n title: z.string().optional(),\n }).optional(),\n })),\n deliverables: z.array(z.object({\n id: z.string(),\n invoice_uniqid: z.string(),\n product_title: z.string(),\n kind: z.enum(['file', 'serial', 'license']),\n label: z.string(),\n value: z.string(),\n href: nullableStringSchema,\n created_at: z.string(),\n })),\n tickets: z.array(z.object({\n uniqid: z.string(),\n title: z.string(),\n status: z.string(),\n updated_at: z.string(),\n created_at: nullableStringSchema,\n })),\n});\n\nexport type CustomerPortalDashboardWire = z.infer<typeof customerPortalDashboardSchema>;\nexport type CustomerPortalAffiliateSummaryWire = z.infer<typeof customerPortalAffiliateSummarySchema>;\nexport type CustomerPortalInvoiceDetailWire = z.infer<typeof customerPortalInvoiceDetailSchema>;\nexport type CustomerPortalPaginatedInvoicesWire = z.infer<typeof customerPortalPaginatedInvoicesSchema>;\nexport type CustomerPortalRewardActivityItemWire = z.infer<typeof customerPortalRewardActivityItemSchema>;\nexport type CustomerPortalRewardsWire = z.infer<typeof customerPortalRewardsSchema>;\nexport type CustomerPortalSubscriptionSummaryWire = z.infer<typeof customerPortalSubscriptionSummarySchema>;\nexport type CustomerPortalWalletTopupQuoteWire = z.infer<typeof customerPortalWalletTopupQuoteSchema>;\nexport type CustomerPortalWalletTopupResultWire = z.infer<typeof customerPortalWalletTopupResultSchema>;\n","/**\n * @shoppex/contracts\n *\n * Shared TypeScript types generated from OpenAPI spec.\n * These types ensure type-safety between the Elysia API runtime and frontend apps.\n *\n * Usage:\n * import { paths, components } from '@shoppex/contracts/api-types';\n * import { createApiClient } from '@shoppex/contracts';\n */\n\nimport createClient from 'openapi-fetch';\nimport type { paths } from './api-types.js';\n\n// Re-export generated types\nexport * from './api-types.js';\nexport * from './navigation.js';\nexport * from './observability.js';\nexport * from './email-marketing.js';\nexport * from './payment-gateways.js';\nexport * from './platform-billing.js';\nexport * from './style-center.js';\nexport * from './style-center/presets.js';\nexport * from './storefront-addons.js';\nexport * from './api-error-codes.js';\nexport * from './merchant-safe-errors.js';\nexport * from './manual-gateway-template.js';\nexport * from './redirect-link-template.js';\nexport * from './checkout-api.js';\nexport * from './invoice-wire.js';\nexport * from './developer-webhook.js';\nexport * from './catalog-unit-price.js';\nexport * from './customer-portal-wire.js';\nexport * from './type-assertions.js';\nexport * from './theme-ai-handoff.js';\n\n/**\n * Create a type-safe API client\n *\n * @example\n * const client = createApiClient('https://api.shoppex.io/v1');\n *\n * // Fully typed request and response\n * const { data, error } = await client.GET('/products', {\n * params: { query: { page: 1, limit: 25 } }\n * });\n */\nexport function createApiClient(baseUrl: string, token?: string) {\n return createClient<paths>({\n baseUrl,\n headers: token ? { Authorization: `Bearer ${token}` } : undefined,\n });\n}\n\n// Common response types used across the app\nexport interface ApiResponse<T> {\n status: number;\n data: T | null;\n error: string | null;\n message: string | null;\n env: string;\n}\n\nexport interface PaginatedResponse<T> {\n data: T[];\n meta: {\n total: number;\n page: number;\n perPage: number;\n totalPages: number;\n };\n}\n\nexport interface ApiError {\n status: number;\n error: string;\n message: string;\n}\n","/**\n * Typed OpenAPI client factory.\n *\n * Surfaces the generated `createApiClient` from `@shoppex/contracts` with the\n * SDK's configured `apiBaseUrl`. This lets consumers of `@shoppexio/storefront`\n * call any public Dev API endpoint with full end-to-end types without\n * rebuilding a client from scratch.\n *\n * Prefer the high-level modules (`shoppex.getProducts()` etc.) for common\n * read flows — they handle caching, pagination defaults, and storefront\n * scoping. Drop down to `shoppex.client()` only when you need an endpoint\n * the high-level API does not cover yet.\n */\n\nimport { createApiClient } from '@shoppex/contracts';\nimport { DEFAULT_API_BASE_URL, getConfig } from './config';\n\ntype ApiClient = ReturnType<typeof createApiClient>;\n\nlet cachedClient: ApiClient | null = null;\nlet cachedBaseUrl: string | null = null;\n\n/**\n * Return a typed OpenAPI client bound to the SDK's configured API base URL.\n * The client is cached per base URL and recreated when the SDK is re-initialized\n * against a different host.\n */\nexport function getTypedClient(token?: string): ApiClient {\n const config = getConfig();\n const baseUrl = config.apiBaseUrl ?? DEFAULT_API_BASE_URL;\n\n if (cachedClient && cachedBaseUrl === baseUrl && !token) {\n return cachedClient;\n }\n\n const client = createApiClient(baseUrl, token);\n\n if (!token) {\n cachedClient = client;\n cachedBaseUrl = baseUrl;\n }\n\n return client;\n}\n\n/**\n * Reset the cached client. Called when the SDK is re-initialized so that a new\n * `apiBaseUrl` takes effect immediately on the next `client()` call.\n */\nexport function resetTypedClient(): void {\n cachedClient = null;\n cachedBaseUrl = null;\n}\n","/**\n * SDK Configuration Management\n */\n\nimport type { ShoppexConfig, ShoppexInitOptions } from '../types';\nimport { clearCache } from './cache';\nimport { NotInitializedError } from './errors';\nimport { resetTypedClient } from './typed-client';\n\nexport const DEFAULT_API_BASE_URL = 'https://api.shoppex.io';\n\nlet currentConfig: ShoppexConfig | null = null;\nlet cachedShopId: string | null = null;\n\nexport const DEFAULT_CHECKOUT_BASE_URL = 'https://checkout.shoppex.io';\n\nexport function initConfig(\n storeSlug: string,\n options?: ShoppexInitOptions\n): ShoppexConfig {\n const normalizedShopId = options?.shopId?.trim();\n\n // Reset cached shop id on every init to avoid cross-store leakage\n // when the SDK is re-initialized with a different slug.\n cachedShopId = normalizedShopId ? normalizedShopId : null;\n\n const previousLocale = currentConfig?.locale;\n currentConfig = {\n storeSlug,\n locale: options?.locale,\n currency: options?.currency,\n apiBaseUrl: options?.apiBaseUrl ?? DEFAULT_API_BASE_URL,\n checkoutBaseUrl: options?.checkoutBaseUrl ?? DEFAULT_CHECKOUT_BASE_URL,\n };\n // Response cache keys are locale-agnostic (products:slug, product:id, …) —\n // a locale switch across re-inits must not serve the previous locale's\n // payloads for up to the cache TTL (Codex P2).\n if (previousLocale !== currentConfig.locale) {\n clearCache();\n }\n resetTypedClient();\n return currentConfig;\n}\n\nexport function getConfig(): ShoppexConfig {\n if (!currentConfig) {\n throw new NotInitializedError();\n }\n return currentConfig;\n}\n\nexport function isInitialized(): boolean {\n return currentConfig !== null;\n}\n\nexport function resetConfig(): void {\n currentConfig = null;\n cachedShopId = null;\n resetTypedClient();\n}\n\nexport function setShopId(shopId: string): void {\n cachedShopId = shopId;\n}\n\nexport function getShopId(): string | null {\n return cachedShopId;\n}\n","export interface StorefrontCustomField {\n name: string;\n type: string;\n required: boolean;\n defaultValue: string;\n placeholder: string;\n regex?: string;\n}\n\nfunction parseCustomFieldsSource(raw: unknown): unknown[] {\n if (Array.isArray(raw)) return raw;\n\n if (typeof raw === 'string') {\n try {\n const parsed = JSON.parse(raw) as unknown;\n if (Array.isArray(parsed)) return parsed;\n if (parsed && typeof parsed === 'object') {\n const fields = (parsed as { custom_fields?: unknown[]; customFields?: unknown[] }).custom_fields\n ?? (parsed as { custom_fields?: unknown[]; customFields?: unknown[] }).customFields;\n return Array.isArray(fields) ? fields : [];\n }\n } catch {\n return [];\n }\n\n return [];\n }\n\n if (raw && typeof raw === 'object') {\n const fields = (raw as { custom_fields?: unknown[]; customFields?: unknown[] }).custom_fields\n ?? (raw as { custom_fields?: unknown[]; customFields?: unknown[] }).customFields;\n return Array.isArray(fields) ? fields : [];\n }\n\n return [];\n}\n\nexport function normalizeStorefrontCustomFields(raw: unknown): StorefrontCustomField[] {\n return parseCustomFieldsSource(raw)\n .filter((field): field is Record<string, unknown> => !!field && typeof field === 'object' && !Array.isArray(field))\n .map((field) => {\n const rawType = typeof field.type === 'string' ? field.type.trim().toLowerCase() : 'text';\n const type = rawType.length > 0 ? rawType : 'text';\n const defaultValue = [\n field.default_value,\n field.default,\n field.value,\n ].find((candidate) => typeof candidate === 'string' && candidate.trim().length > 0);\n\n return {\n name: typeof field.name === 'string' ? field.name.trim() : '',\n type,\n required: field.required === true || field.required === 'true' || field.required === 1 || field.required === '1',\n defaultValue: typeof defaultValue === 'string' ? defaultValue : '',\n placeholder: typeof field.placeholder === 'string' ? field.placeholder : '',\n regex: typeof field.regex === 'string' ? field.regex : undefined,\n };\n })\n .filter((field) => field.name.length > 0 && field.type !== 'hidden');\n}\n\nexport function isStorefrontCheckboxCustomFieldValueChecked(value: string | undefined): boolean {\n const normalized = value?.trim().toLowerCase() ?? '';\n return normalized === 'true' || normalized === '1' || normalized === 'yes' || normalized === 'on';\n}\n\nexport function validateStorefrontCustomFieldValue(field: StorefrontCustomField, value: string): string | null {\n if (field.type === 'checkbox') {\n if (field.required && !isStorefrontCheckboxCustomFieldValueChecked(value)) {\n return `${field.name} is required.`;\n }\n return null;\n }\n\n const normalized = value.trim();\n if (field.required && !normalized) {\n return `${field.name} is required.`;\n }\n\n if (field.regex && normalized) {\n try {\n const pattern = new RegExp(field.regex);\n if (!pattern.test(normalized)) {\n return `${field.name} has an invalid format.`;\n }\n } catch {\n return null;\n }\n }\n\n return null;\n}\n\nexport function buildStorefrontCustomFieldPayload(\n fields: StorefrontCustomField[],\n values: Record<string, string>,\n): Record<string, string> {\n const nextValues: Record<string, string> = {};\n\n fields.forEach((field) => {\n const rawValue = values[field.name] ?? field.defaultValue ?? '';\n\n if (field.type === 'checkbox') {\n if (isStorefrontCheckboxCustomFieldValueChecked(rawValue)) {\n nextValues[field.name] = 'true';\n }\n return;\n }\n\n const normalized = rawValue.trim();\n if (normalized.length > 0) {\n nextValues[field.name] = normalized;\n }\n });\n\n return nextValues;\n}\n","import type { Product, PriceVariant, ProductVariant } from '../types/index.js';\n\ntype VariantLike =\n | Pick<ProductVariant, 'stock' | 'orderable' | 'supplier_backed'>\n | Pick<PriceVariant, 'stock' | 'orderable' | 'supplier_backed'>;\n\ntype ProductLike = Pick<Product, 'type' | 'stock' | 'orderable' | 'supplier_backed' | 'on_hold' | 'price_variants' | 'variants'> & {\n onHold?: boolean | number | string | null;\n is_on_hold?: boolean | number | string | null;\n isOnHold?: boolean | number | string | null;\n};\n\n/** The sentinel every predicate in this module already treats as \"unbounded\". */\nconst UNLIMITED_STOCK = -1;\n\n/**\n * Dynamic Delivery (S8): fold `orderable` into the stock value.\n *\n * `orderable` is the backend's authoritative buyability predicate — `local stock\n * covers one unit OR an eligible supplier source can fulfil the line` — and it is\n * exactly what the order-time gates apply. A supplier-backed row holds NO local\n * stock by design, so gating the buyer on `stock` alone renders it \"out of stock\"\n * and the purchase can never happen.\n *\n * Rather than introduce a fourth availability state, a row that is orderable\n * without local units is normalised to the unlimited sentinel — the same value an\n * unlimited row already carries. Every downstream badge, quantity cap, variant\n * gate and CTA then behaves as it already does for unlimited stock.\n *\n * `orderable` alone cannot decide how far to widen: it is also `true` for an\n * ordinary locally-stocked row, whose finite counter must stay finite. That is what\n * `supplier_backed` settles. A supplier-backed row is fulfilled by the supplier\n * purchase and the completion excludes it from the local decrement, so any residual\n * local units bound NOTHING — its cap is unlimited even at `stock: 1`. A row that is\n * NOT supplier-backed keeps its exact finite counter, and only widens from 0 (the\n * product-wide mapping case, where the backend folded the mapping into `orderable`\n * and left `stock` at 0).\n *\n * When `orderable` is absent (an older payload or a cached response shape that\n * predates the field) the raw value is returned UNCHANGED, and an absent\n * `supplier_backed` widens nothing beyond what the previous rule already did. That\n * is the only permitted fallback direction: a missing field must never flip a\n * genuinely sold-out row into a buyable one, nor a finite counter into unlimited.\n */\nfunction applyOrderable(stock: number, orderable: unknown, supplierBacked?: unknown): number {\n if (orderable !== true) {\n return stock;\n }\n // Supplier-backed: local units do not bound the line, at any stock value.\n if (supplierBacked === true) {\n return UNLIMITED_STOCK;\n }\n // Already buyable or already unbounded — nothing to widen.\n if (stock !== 0) {\n return stock;\n }\n return UNLIMITED_STOCK;\n}\n\nfunction normalizeStockValue(value: unknown): number | null {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n return null;\n }\n\n return Math.trunc(value);\n}\n\nfunction isTruthyFlag(value: unknown): boolean {\n if (value === true) return true;\n if (typeof value === 'number' && Number.isFinite(value)) return value !== 0;\n if (typeof value === 'string') {\n const normalized = value.trim().toLowerCase();\n return normalized === 'true' || normalized === '1';\n }\n return false;\n}\n\nfunction isProductOnHold(product: ProductLike | null | undefined): boolean {\n if (!product) return false;\n return isTruthyFlag(product.on_hold)\n || isTruthyFlag(product.onHold)\n || isTruthyFlag(product.is_on_hold)\n || isTruthyFlag(product.isOnHold);\n}\n\nfunction collectVariantStocks(product: ProductLike): number[] {\n const priceVariants = Array.isArray(product.price_variants) ? product.price_variants : [];\n if (priceVariants.length > 0) {\n return priceVariants.map((variant) => resolveVariantStockValue(variant));\n }\n\n const legacyVariants = Array.isArray(product.variants) ? product.variants : [];\n\n return legacyVariants.map((variant) => resolveVariantStockValue(variant));\n}\n\nexport function resolveVariantStockValue(variant: VariantLike | null | undefined): number {\n const normalized = normalizeStockValue(variant?.stock);\n return applyOrderable(normalized ?? UNLIMITED_STOCK, variant?.orderable, variant?.supplier_backed);\n}\n\nexport function resolveDisplayStock(product: ProductLike | null | undefined): number {\n if (!product) {\n return UNLIMITED_STOCK;\n }\n\n if (typeof product.type === 'string' && product.type.toUpperCase() === 'SERIALS') {\n return applyOrderable(\n normalizeStockValue(product.stock) ?? UNLIMITED_STOCK,\n product.orderable,\n product.supplier_backed,\n );\n }\n\n const variantStocks = collectVariantStocks(product);\n if (variantStocks.length > 0) {\n // A single unbounded option (including a supplier-backed one, already folded\n // into the sentinel above) makes the product unbounded — summing finite\n // siblings would understate it.\n if (variantStocks.some((stock) => stock < 0)) {\n return UNLIMITED_STOCK;\n }\n\n const total = variantStocks.reduce((sum, stock) => sum + Math.max(stock, 0), 0);\n // The product-level flag still applies: the backend folds a product-wide\n // supplier mapping into it, and that mapping backs options with no local units.\n return applyOrderable(total, product.orderable, product.supplier_backed);\n }\n\n return applyOrderable(\n normalizeStockValue(product.stock) ?? UNLIMITED_STOCK,\n product.orderable,\n product.supplier_backed,\n );\n}\n\nexport function isProductOutOfStock(product: ProductLike | null | undefined): boolean {\n // `on_hold` is a merchant pause, not a supply signal — it forces unavailable\n // BEFORE any `orderable` widening can apply.\n if (isProductOnHold(product)) return true;\n return resolveDisplayStock(product) === 0;\n}\n\nexport function isProductInStock(product: ProductLike | null | undefined): boolean {\n return !isProductOutOfStock(product);\n}\n\nexport function isVariantOutOfStock(variant: VariantLike | null | undefined): boolean {\n return resolveVariantStockValue(variant) === 0;\n}\n","import type { Product, ProductGroup } from '../types/index.js';\n\nexport function buildStorefrontProductLookup(products: Product[] = []): Map<string, Product> {\n const lookup = new Map<string, Product>();\n for (const product of products) {\n if (!product?.uniqid || lookup.has(product.uniqid)) continue;\n lookup.set(product.uniqid, product);\n }\n return lookup;\n}\n\n// Groups reference their products by uniqid; the objects live once in `products`.\nexport function getStorefrontGroupProducts(\n group: ProductGroup,\n productsOrLookup: Product[] | Map<string, Product> = [],\n): Product[] {\n const lookup = productsOrLookup instanceof Map\n ? productsOrLookup\n : buildStorefrontProductLookup(productsOrLookup);\n return (group.product_uniqids ?? []).flatMap((uniqid) => {\n const product = lookup.get(uniqid);\n return product ? [product] : [];\n });\n}\n\nexport function getMergedStorefrontProducts(products: Product[] = []): Product[] {\n return Array.from(buildStorefrontProductLookup(products).values());\n}\n","import type { Product, ProductGroup } from '../types/index.js';\nimport {\n buildStorefrontProductLookup,\n getMergedStorefrontProducts,\n getStorefrontGroupProducts,\n} from './storefront-catalog.js';\nimport { isProductInStock } from './storefront-stock.js';\n\nexport interface StorefrontSearchFilterOptions {\n hideOutOfStock?: boolean;\n maxResults?: number;\n}\n\nexport type StorefrontCatalogSearchItem =\n | { type: 'product'; product: Product }\n // Groups only carry `product_uniqids`; `products` holds the resolved product\n // objects (in group order) so consumers never re-resolve references themselves.\n | { type: 'group'; group: ProductGroup; products: Product[] };\n\nexport function stripHtmlFromText(value: string | null | undefined): string {\n if (!value) return '';\n return value.replace(/<[^>]*>/g, ' ').replace(/\\s+/g, ' ').trim();\n}\n\nexport function normalizeSearchQuery(query: string): string {\n return query.trim().toLowerCase();\n}\n\nfunction pushSearchPart(parts: string[], value: string | null | undefined): void {\n const normalized = stripHtmlFromText(value).toLowerCase();\n if (normalized) {\n parts.push(normalized);\n }\n}\n\nexport function collectProductSearchHaystack(product: Product): string[] {\n const parts: string[] = [];\n\n pushSearchPart(parts, product.title);\n pushSearchPart(parts, product.slug ?? undefined);\n pushSearchPart(parts, product.description);\n\n for (const highlight of product.product_highlights ?? []) {\n pushSearchPart(parts, highlight);\n }\n\n for (const variant of product.variants ?? []) {\n pushSearchPart(parts, variant.title);\n }\n\n for (const variant of product.price_variants ?? []) {\n pushSearchPart(parts, variant.title ?? variant.label);\n }\n\n return parts;\n}\n\nexport function productMatchesSearchQuery(product: Product, query: string): boolean {\n const normalized = normalizeSearchQuery(query);\n if (!normalized) return false;\n\n return collectProductSearchHaystack(product).some((haystack) => haystack.includes(normalized));\n}\n\nexport function groupMatchesSearchQuery(group: ProductGroup, query: string): boolean {\n const normalized = normalizeSearchQuery(query);\n if (!normalized) return false;\n\n const title = stripHtmlFromText(group.title).toLowerCase();\n const slug = stripHtmlFromText(group.slug ?? group.name ?? undefined).toLowerCase();\n const description = stripHtmlFromText(group.description).toLowerCase();\n\n return title.includes(normalized)\n || slug.includes(normalized)\n || description.includes(normalized);\n}\n\nexport function filterProductsBySearchQuery(\n products: Product[],\n query: string,\n options?: StorefrontSearchFilterOptions,\n): Product[] {\n const normalized = normalizeSearchQuery(query);\n if (!normalized) return [];\n\n let results = products.filter((product) => productMatchesSearchQuery(product, normalized));\n\n if (options?.hideOutOfStock) {\n results = results.filter((product) => isProductInStock(product));\n }\n\n if (options?.maxResults != null) {\n return results.slice(0, options.maxResults);\n }\n\n return results;\n}\n\nfunction groupHasVisibleProducts(\n groupProducts: Product[],\n hideOutOfStock: boolean,\n): boolean {\n if (groupProducts.length === 0) return false;\n if (!hideOutOfStock) return true;\n return groupProducts.some((product) => isProductInStock(product));\n}\n\nexport function searchMergedStorefrontCatalogItems(\n products: Product[],\n groups: ProductGroup[],\n query: string,\n options?: StorefrontSearchFilterOptions,\n): StorefrontCatalogSearchItem[] {\n const normalized = normalizeSearchQuery(query);\n if (!normalized) return [];\n\n const hideOutOfStock = options?.hideOutOfStock === true;\n const coveredProductIds = new Set<string>();\n const coveredGroupIds = new Set<string>();\n const results: StorefrontCatalogSearchItem[] = [];\n // Build the uniqid lookup once per search run; groups resolve against it.\n const lookup = buildStorefrontProductLookup(products);\n\n for (const group of groups) {\n const groupKey = group.uniqid ?? group.id;\n if (!groupKey || coveredGroupIds.has(groupKey)) continue;\n if (!groupMatchesSearchQuery(group, normalized)) continue;\n\n const groupProducts = getStorefrontGroupProducts(group, lookup);\n if (!groupHasVisibleProducts(groupProducts, hideOutOfStock)) continue;\n\n coveredGroupIds.add(groupKey);\n for (const product of groupProducts) {\n if (product?.uniqid) coveredProductIds.add(product.uniqid);\n }\n results.push({ type: 'group', group, products: groupProducts });\n }\n\n const merged = getMergedStorefrontProducts(products);\n for (const product of merged) {\n if (!product?.uniqid || coveredProductIds.has(product.uniqid)) continue;\n if (!productMatchesSearchQuery(product, normalized)) continue;\n if (hideOutOfStock && !isProductInStock(product)) continue;\n coveredProductIds.add(product.uniqid);\n results.push({ type: 'product', product });\n }\n\n if (options?.maxResults != null) {\n return results.slice(0, options.maxResults);\n }\n\n return results;\n}\n\nexport function searchMergedStorefrontCatalog(\n products: Product[],\n groups: ProductGroup[],\n query: string,\n options?: StorefrontSearchFilterOptions,\n): Product[] {\n const items = searchMergedStorefrontCatalogItems(products, groups, query, options);\n const matchedIds = new Set<string>();\n const results: Product[] = [];\n\n const addProduct = (product: Product) => {\n if (!product?.uniqid || matchedIds.has(product.uniqid)) return;\n if (options?.hideOutOfStock && !isProductInStock(product)) return;\n matchedIds.add(product.uniqid);\n results.push(product);\n };\n\n for (const item of items) {\n if (item.type === 'product') {\n addProduct(item.product);\n continue;\n }\n\n for (const product of item.products) {\n addProduct(product);\n }\n }\n\n if (options?.maxResults != null) {\n return results.slice(0, options.maxResults);\n }\n\n return results;\n}\n","import { DEFAULT_API_BASE_URL } from '../core/config';\n\nexport type StorefrontContactTicketInput = {\n shopSlug: string;\n email: string;\n message: string;\n title?: string;\n name?: string;\n invoiceId?: string;\n apiBaseUrl?: string;\n};\n\nexport type StorefrontContactTicketResult = {\n uniqid: string;\n};\n\nfunction isLocalDevHost(host: string): boolean {\n if (host === 'localhost' || host === '127.0.0.1' || host === '::1' || host.endsWith('.localhost')) {\n return true;\n }\n if (/^10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(host)) {\n return true;\n }\n if (/^192\\.168\\.\\d{1,3}\\.\\d{1,3}$/.test(host)) {\n return true;\n }\n const private172 = host.match(/^172\\.(\\d{1,2})\\.\\d{1,3}\\.\\d{1,3}$/);\n if (private172) {\n const octet = Number(private172[1]);\n return octet >= 16 && octet <= 31;\n }\n return false;\n}\n\nexport function resolveStorefrontApiBaseUrl(options?: {\n apiBaseUrl?: string;\n hostname?: string;\n}): string {\n if (options?.apiBaseUrl?.trim()) {\n return options.apiBaseUrl.replace(/\\/+$/, '');\n }\n\n const hostname = options?.hostname\n ?? (typeof window !== 'undefined' ? window.location.hostname : '');\n\n if (hostname && !isLocalDevHost(hostname)) {\n return DEFAULT_API_BASE_URL;\n }\n\n // Edge/njk commerce is a classic IIFE (not an ES module) — import.meta is a syntax error there.\n // Storefront bootstrap sets window.apiBaseUrl; Vite/React callers may pass options.apiBaseUrl.\n if (typeof window !== 'undefined') {\n const bootstrapBase = (window as { apiBaseUrl?: unknown }).apiBaseUrl;\n if (typeof bootstrapBase === 'string' && bootstrapBase.trim()) {\n return bootstrapBase.replace(/\\/+$/, '');\n }\n }\n\n return 'http://localhost:3001'.replace(/\\/+$/, '');\n}\n\nexport function buildStorefrontContactMessage(input: {\n name?: string;\n message: string;\n maxLength?: number;\n}): string {\n const customerName = input.name?.trim() ?? '';\n const baseMessage = input.message.trim();\n const fullMessage = `${customerName ? `Name: ${customerName}\\n\\n` : ''}${baseMessage}`;\n const maxLength = input.maxLength ?? 2000;\n return fullMessage.slice(0, maxLength);\n}\n\nexport async function submitStorefrontContactTicket(\n input: StorefrontContactTicketInput,\n): Promise<StorefrontContactTicketResult> {\n const shopSlug = input.shopSlug.trim();\n if (!shopSlug) {\n throw new Error('Store data is not ready yet. Please try again in a moment.');\n }\n\n const normalizedEmail = input.email.trim().toLowerCase();\n const subject = input.title?.trim() ?? '';\n const title = subject.length >= 2 ? subject.slice(0, 30) : 'Contact Request';\n const message = buildStorefrontContactMessage({\n name: input.name,\n message: input.message,\n });\n const invoiceId = input.invoiceId?.trim() || undefined;\n const apiBaseUrl = resolveStorefrontApiBaseUrl({ apiBaseUrl: input.apiBaseUrl });\n\n const response = await fetch(\n `${apiBaseUrl}/v1/storefront/shops/name/${encodeURIComponent(shopSlug)}/tickets`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n body: JSON.stringify({\n email: normalizedEmail,\n title,\n message,\n ...(invoiceId ? { invoice_id: invoiceId } : {}),\n }),\n },\n );\n\n const payload = await response.json().catch(() => null) as {\n message?: string;\n error?: string;\n data?: { uniqid?: string };\n } | null;\n\n if (!response.ok) {\n throw new Error(payload?.message || payload?.error || 'Failed to send your message.');\n }\n\n const uniqid = payload?.data?.uniqid;\n if (!uniqid) {\n throw new Error('Ticket created, but the response was incomplete.');\n }\n\n return { uniqid };\n}\n\nexport type StorefrontSocialLinks = {\n discord?: string | null;\n telegram?: string | null;\n};\n\nexport function resolveStorefrontSocialLinks(store: {\n discord_link?: string | null;\n telegram_link?: string | null;\n social?: Record<string, string | null | undefined> | null;\n} | null | undefined): StorefrontSocialLinks {\n return {\n discord: store?.discord_link ?? store?.social?.discord ?? null,\n telegram: store?.telegram_link ?? store?.social?.telegram ?? null,\n };\n}\n","const PARAM_PATTERN = /:([A-Za-z0-9_]+)/g;\n\nexport function buildEndpoint(\n template: string,\n params: Record<string, string | number | null | undefined>\n): string {\n return template.replace(PARAM_PATTERN, (_, key: string) => {\n const rawValue = params[key];\n if (rawValue === null || rawValue === undefined) {\n throw new Error(`Missing endpoint param: ${key}`);\n }\n\n const value = String(rawValue).trim();\n if (!value) {\n throw new Error(`Endpoint param \"${key}\" must not be empty`);\n }\n\n return encodeURIComponent(value);\n });\n}\n","/**\n * localStorage Wrapper\n *\n * Handles localStorage access with error handling for\n * environments where localStorage is not available.\n */\n\nconst STORAGE_PREFIX = 'shoppex_';\n\nfunction getKey(key: string): string {\n return `${STORAGE_PREFIX}${key}`;\n}\n\nexport function getItem<T>(key: string): T | null {\n try {\n const item = localStorage.getItem(getKey(key));\n if (!item) return null;\n return JSON.parse(item) as T;\n } catch {\n return null;\n }\n}\n\nexport function setItem<T>(key: string, value: T): void {\n try {\n localStorage.setItem(getKey(key), JSON.stringify(value));\n } catch {\n console.warn('[shoppex] Failed to save to localStorage');\n }\n}\n\nexport function removeItem(key: string): void {\n try {\n localStorage.removeItem(getKey(key));\n } catch {\n // Ignore errors\n }\n}\n","import { getConfig, getShopId, isInitialized } from './config';\nimport { buildEndpoint } from './endpoint';\nimport { getItem, setItem } from '../utils/storage';\n\nconst CONNECTION_ID_STORAGE_PREFIX = 'presence_connection_';\nconst CLIENT_ERROR_DEDUPE_WINDOW_MS = 15_000;\n\ntype VisibilityStateValue = 'hidden' | 'visible' | 'prerender' | 'unloaded';\ntype RequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\nexport interface StorefrontClientErrorPayload {\n endpoint: string;\n method: RequestMethod;\n message: string;\n statusCode?: number;\n source?: 'sdk';\n phase?: 'request';\n attemptCount?: number;\n responseReceived?: boolean;\n pageUrl?: string;\n requestUrl?: string;\n online?: boolean;\n visibilityState?: VisibilityStateValue;\n}\n\nfunction createPresenceConnectionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `spx_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;\n}\n\nexport function getStorefrontConnectionId(storeSlug: string): string | null {\n if (typeof window === 'undefined') return null;\n\n const storageKey = `${CONNECTION_ID_STORAGE_PREFIX}${storeSlug}`;\n const existing = getItem<string>(storageKey);\n if (existing && existing.trim()) {\n return existing;\n }\n\n const nextId = createPresenceConnectionId();\n setItem(storageKey, nextId);\n return nextId;\n}\n\nfunction getRecentClientErrorKey(payload: StorefrontClientErrorPayload): string {\n return [\n payload.method,\n payload.endpoint,\n payload.statusCode ?? 'none',\n payload.message.trim().toLowerCase(),\n payload.responseReceived ? 'response' : 'no-response',\n ].join('|');\n}\n\nfunction shouldSkipDuplicateClientError(payload: StorefrontClientErrorPayload): boolean {\n const dedupeKey = `client_error_${getRecentClientErrorKey(payload)}`;\n const now = Date.now();\n const lastSeenAt = getItem<number>(dedupeKey);\n if (typeof lastSeenAt === 'number' && now - lastSeenAt < CLIENT_ERROR_DEDUPE_WINDOW_MS) {\n return true;\n }\n\n setItem(dedupeKey, now);\n return false;\n}\n\nexport async function reportStorefrontClientError(payload: StorefrontClientErrorPayload): Promise<void> {\n if (!isInitialized()) return;\n if (typeof window === 'undefined') return;\n if (shouldSkipDuplicateClientError(payload)) return;\n\n const config = getConfig();\n const shopId = getShopId();\n const endpoint = shopId\n ? buildEndpoint('/v1/storefront/shops/id/:id/ping', { id: shopId })\n : buildEndpoint('/v1/storefront/shops/:storeSlug/ping', { storeSlug: config.storeSlug });\n const body = JSON.stringify({\n event_type: 'client_error',\n referer: document.referrer || undefined,\n connection_id: getStorefrontConnectionId(config.storeSlug) ?? undefined,\n client_error: {\n source: payload.source ?? 'sdk',\n phase: payload.phase ?? 'request',\n endpoint: payload.endpoint,\n method: payload.method,\n message: payload.message,\n status_code: payload.statusCode,\n attempt_count: payload.attemptCount,\n response_received: payload.responseReceived ?? false,\n page_url: payload.pageUrl ?? window.location.href,\n request_url: payload.requestUrl,\n online: payload.online ?? (typeof navigator !== 'undefined' ? navigator.onLine : undefined),\n visibility_state:\n payload.visibilityState ??\n (typeof document !== 'undefined'\n ? (document.visibilityState as VisibilityStateValue)\n : undefined),\n },\n });\n\n const targetUrl = `${config.apiBaseUrl}${endpoint}`;\n\n try {\n if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {\n const beaconBody = new Blob([body], { type: 'application/json' });\n if (navigator.sendBeacon(targetUrl, beaconBody)) {\n return;\n }\n }\n\n await fetch(targetUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body,\n keepalive: true,\n });\n } catch {\n // Telemetry must never break storefront usage.\n }\n}\n","/**\n * HTTP Client for SDK\n *\n * IMPORTANT: No credentials! SDK runs on external domains,\n * and CORS with wildcard origin doesn't allow credentials.\n * All endpoints are public storefront endpoints.\n */\n\nimport type { ApiResponse, SDKResponse } from '../types';\nimport { getConfig, isInitialized } from './config';\nimport { ApiError, NetworkError, ShoppexError } from './errors';\nimport { getOrFetch, type CacheOptions } from './cache';\nimport { reportStorefrontClientError } from './telemetry';\n\nconst DEFAULT_TIMEOUT = 10000;\nconst MAX_RETRIES = 2;\n\ninterface RequestOptions {\n method?: 'GET' | 'POST' | 'PUT' | 'DELETE';\n body?: unknown;\n timeout?: number;\n retries?: number;\n baseUrl?: string;\n cache?: (CacheOptions & { key?: string }) | false;\n}\n\ninterface ParsedResponsePayload {\n data: unknown | null;\n rawText: string | null;\n}\n\ninterface FailureInfo {\n message: string;\n statusCode?: number;\n isTransport: boolean;\n /** The server's `error_code`, when the failure was a named refusal. */\n code?: string;\n errorParams?: Record<string, unknown>;\n}\n\nasync function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport async function request<T>(\n endpoint: string,\n options: RequestOptions = {}\n): Promise<SDKResponse<T>> {\n const config = options.baseUrl ? null : getConfig();\n // The locale travels with EVERY request of an initialized SDK — a baseUrl\n // override (e.g. resolveStoreByDomain) must not silently drop it back to\n // Accept-Language negotiation (Codex P2).\n const localeConfig = config ?? (isInitialized() ? getConfig() : null);\n const {\n method = 'GET',\n body,\n timeout = DEFAULT_TIMEOUT,\n retries,\n baseUrl,\n cache,\n } = options;\n const retryCount =\n retries ?? (method === 'GET' ? MAX_RETRIES : 0);\n\n const apiBaseUrl = baseUrl ?? config?.apiBaseUrl ?? '';\n const url = `${apiBaseUrl}${endpoint}`;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n };\n // Explicit request locale (ADR-0055): without it the backend would fall\n // back to Accept-Language, detaching catalog content from the page locale.\n if (typeof localeConfig?.locale === 'string' && localeConfig.locale.trim()) {\n headers['x-shoppex-locale'] = localeConfig.locale.trim();\n }\n\n let lastFailure: FailureInfo | null = null;\n\n const executeRequest = async (): Promise<SDKResponse<T>> => {\n for (let attempt = 0; attempt <= retryCount; attempt++) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n const payload = await parseResponsePayload(response);\n\n if (!response.ok) {\n const fallbackHttpMessage = response.statusText\n ? `HTTP ${response.status}: ${response.statusText}`\n : `HTTP ${response.status}`;\n const message =\n (payload.data && typeof payload.data === 'object' && 'error' in payload.data && typeof payload.data.error === 'string'\n ? payload.data.error\n : null) ??\n (payload.data && typeof payload.data === 'object' && 'message' in payload.data && typeof payload.data.message === 'string'\n ? payload.data.message\n : null) ??\n payload.rawText ??\n fallbackHttpMessage;\n\n // A named server refusal keeps its name. Everything else stays a\n // NetworkError, exactly as before.\n const named = readErrorCodeFields(payload.data);\n if (named.code) {\n throw new ApiError(message, named.code, response.status, named.errorParams);\n }\n\n throw new NetworkError(message, response.status);\n }\n\n if (response.status === 204 && payload.data === null) {\n return {\n success: true,\n };\n }\n\n if (!payload.data || typeof payload.data !== 'object' || !('status' in payload.data)) {\n throw new NetworkError('Invalid API response', response.status);\n }\n\n const data = payload.data as ApiResponse<T>;\n\n return mapApiResponse(data);\n } catch (error) {\n let normalizedError = error instanceof Error ? error : new Error(String(error));\n\n if (error instanceof DOMException && error.name === 'AbortError') {\n normalizedError = new NetworkError('Request timeout', 408);\n }\n\n // Read from the base class, not NetworkError: a named ApiError also\n // carries the HTTP status, and losing it would misclassify a 400\n // refusal as a transport failure — retried and reported as an outage.\n const statusCode =\n normalizedError instanceof ShoppexError\n ? normalizedError.statusCode\n : undefined;\n\n lastFailure = {\n message: normalizedError.message,\n statusCode,\n isTransport: statusCode === undefined || statusCode === 408,\n ...(normalizedError instanceof ApiError\n ? {\n code: normalizedError.code,\n ...(normalizedError.errorParams ? { errorParams: normalizedError.errorParams } : {}),\n }\n : {}),\n };\n\n // A named 4xx is the server's decision, not a transport hiccup:\n // `ApiError` only exists when the response carried an error code, and\n // a client-error status means the request itself was refused. Repeating\n // it verbatim cannot change the answer — it just multiplies the load\n // and delays the refusal the caller is waiting on by the full backoff\n // schedule. 408 stays retryable (it is a timeout wearing a 4xx) and\n // every 5xx, network failure and unnamed error retries exactly as\n // before.\n const isNamedClientRefusal =\n normalizedError instanceof ApiError\n && statusCode !== undefined\n && statusCode >= 400\n && statusCode < 500\n && statusCode !== 408;\n\n if (isNamedClientRefusal) {\n break;\n }\n\n if (attempt < retryCount) {\n await sleep(Math.pow(2, attempt) * 500);\n continue;\n }\n }\n }\n\n return {\n success: false,\n message: lastFailure?.message ?? 'Unknown error',\n ...(lastFailure?.code ? { code: lastFailure.code } : {}),\n ...(lastFailure?.errorParams ? { errorParams: lastFailure.errorParams } : {}),\n };\n };\n\n const result =\n method === 'GET' && cache && cache.ttl > 0\n ? await getOrFetch(\n cache.key ?? `GET:${url}`,\n executeRequest,\n { ttl: cache.ttl, staleWhileRevalidate: cache.staleWhileRevalidate },\n (value) => value.success\n )\n : await executeRequest();\n\n const failureForTelemetry = lastFailure as FailureInfo | null;\n\n if (!result.success && failureForTelemetry?.isTransport) {\n\n await reportStorefrontClientError({\n endpoint,\n method,\n message: result.message ?? failureForTelemetry.message,\n statusCode: failureForTelemetry.statusCode,\n attemptCount: retryCount + 1,\n requestUrl: url,\n responseReceived:\n failureForTelemetry.statusCode !== undefined &&\n failureForTelemetry.statusCode !== 408,\n });\n }\n\n return result;\n}\n\nasync function parseResponsePayload(response: Response): Promise<ParsedResponsePayload> {\n const responseWithOptionalMethods = response as Response & {\n text?: () => Promise<string>;\n json?: () => Promise<unknown>;\n };\n\n // Runtime-safe fallback for test mocks that only implement `json()`.\n if (typeof responseWithOptionalMethods.text !== 'function') {\n if (typeof responseWithOptionalMethods.json === 'function') {\n try {\n return {\n data: await responseWithOptionalMethods.json(),\n rawText: null,\n };\n } catch {\n return { data: null, rawText: null };\n }\n }\n return { data: null, rawText: null };\n }\n\n try {\n const rawText = await responseWithOptionalMethods.text();\n if (!rawText) {\n return { data: null, rawText: null };\n }\n\n try {\n return {\n data: JSON.parse(rawText) as unknown,\n rawText: null,\n };\n } catch {\n const normalizedText = rawText.trim();\n return {\n data: null,\n rawText: normalizedText.length > 0 ? normalizedText : null,\n };\n }\n } catch {\n return { data: null, rawText: null };\n }\n}\n\nfunction mapApiResponse<T>(apiResponse: ApiResponse<T>): SDKResponse<T> {\n if (apiResponse.status >= 200 && apiResponse.status < 300) {\n return {\n success: true,\n data: apiResponse.data,\n ...(apiResponse.message ? { message: apiResponse.message } : {}),\n };\n }\n\n return {\n success: false,\n message: apiResponse.error ?? apiResponse.message ?? `Request failed with status ${apiResponse.status}`,\n // The refusal the server actually made, kept machine-readable. Without it\n // a caller can only string-match a localized sentence, which breaks in\n // every locale but one.\n ...readErrorCodeFields(apiResponse),\n };\n}\n\n/**\n * Pull the localized-error envelope (`error_code` / `error_params`) off any\n * server payload shape. Returns an empty object when the payload carries none,\n * so the fields stay absent rather than becoming `undefined` keys.\n */\nfunction readErrorCodeFields(payload: unknown): { code?: string; errorParams?: Record<string, unknown> } {\n if (!payload || typeof payload !== 'object') {\n return {};\n }\n\n const record = payload as Record<string, unknown>;\n const code = typeof record.error_code === 'string' && record.error_code.length > 0\n ? record.error_code\n : null;\n if (!code) {\n return {};\n }\n\n const params = record.error_params;\n return {\n code,\n ...(params && typeof params === 'object' && !Array.isArray(params)\n ? { errorParams: params as Record<string, unknown> }\n : {}),\n };\n}\n\nexport async function get<T>(\n endpoint: string,\n options?: Omit<RequestOptions, 'method' | 'body'>\n): Promise<SDKResponse<T>> {\n return request<T>(endpoint, { ...options, method: 'GET' });\n}\n\nexport async function post<T>(\n endpoint: string,\n body?: unknown,\n options?: Omit<RequestOptions, 'method' | 'body'>\n): Promise<SDKResponse<T>> {\n return request<T>(endpoint, { ...options, method: 'POST', body });\n}\n","/**\n * Store Module\n *\n * API methods for store data.\n */\n\nimport { get } from '../core/client';\nimport { DEFAULT_API_BASE_URL, getConfig, isInitialized, setShopId } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type {\n SDKResponse,\n Shop,\n Product,\n StorefrontData,\n ProductGroup,\n Category,\n StorefrontAddonBootstrap,\n CursorPagination,\n} from '../types';\n\ninterface StoreResponse {\n shop: Shop;\n products?: Product[];\n products_pagination?: CursorPagination | null;\n groups?: ProductGroup[];\n items?: StorefrontData['items'];\n categories?: Category[];\n addons?: StorefrontAddonBootstrap;\n}\n\ninterface StorefrontResponse {\n shop: Shop;\n}\n\nexport interface GetStorefrontOptions {\n productsLimit?: number;\n productsCursor?: string | null;\n}\n\nconst STORE_CACHE_TTL = 5 * 60 * 1000;\n\nexport async function getStore(): Promise<SDKResponse<Shop>> {\n const config = getConfig();\n const response = await get<StoreResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug', {\n storeSlug: config.storeSlug,\n }),\n {\n cache: {\n key: `store:${config.storeSlug}`,\n ttl: STORE_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n // Cache the shopId for slug lookups\n if (response.data.shop?.id) {\n setShopId(response.data.shop.id);\n }\n return {\n success: true,\n data: response.data.shop,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function resolveStoreByDomain(\n domain?: string,\n apiBaseUrl?: string\n): Promise<SDKResponse<Shop>> {\n const resolvedDomain =\n domain ??\n (typeof window !== 'undefined' ? window.location.hostname : '');\n\n if (!resolvedDomain) {\n return {\n success: false,\n message: 'Domain is required to resolve store',\n };\n }\n\n const cleanDomain = resolvedDomain\n .replace(/^https?:\\/\\//, '')\n .split('/')[0]\n .trim();\n\n const baseUrl =\n apiBaseUrl ??\n (isInitialized() ? getConfig().apiBaseUrl : DEFAULT_API_BASE_URL);\n\n const response = await get<StorefrontResponse>(\n buildEndpoint('/v1/storefront/shops/domain/:domain', {\n domain: cleanDomain,\n }),\n {\n baseUrl,\n cache: {\n key: `store:domain:${cleanDomain}`,\n ttl: STORE_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data?.shop) {\n if (response.data.shop.id) {\n setShopId(response.data.shop.id);\n }\n return {\n success: true,\n data: response.data.shop,\n };\n }\n\n return {\n success: false,\n message: response.message ?? 'Failed to resolve store',\n };\n}\n\nexport async function getStorefront(options?: GetStorefrontOptions): Promise<SDKResponse<StorefrontData>> {\n const config = getConfig();\n const query = new URLSearchParams();\n if (Number.isFinite(options?.productsLimit)) {\n query.set('products_limit', String(Math.max(1, Math.floor(options?.productsLimit ?? 0))));\n }\n if (typeof options?.productsCursor === 'string' && options.productsCursor.trim().length > 0) {\n query.set('products_cursor', options.productsCursor);\n }\n const querySuffix = query.size > 0 ? `?${query.toString()}` : '';\n const response = await get<StoreResponse>(\n `${buildEndpoint('/v1/storefront/shops/name/:storeSlug', {\n storeSlug: config.storeSlug,\n })}${querySuffix}`,\n {\n cache: {\n key: `storefront:${config.storeSlug}:${options?.productsLimit ?? 'full'}:${options?.productsCursor ?? 'start'}`,\n ttl: STORE_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n // Cache the shopId for slug lookups\n if (response.data.shop?.id) {\n setShopId(response.data.shop.id);\n }\n return {\n success: true,\n data: {\n shop: response.data.shop,\n products: response.data.products ?? [],\n products_pagination: response.data.products_pagination ?? null,\n groups: response.data.groups ?? [],\n items: response.data.items ?? [],\n categories: response.data.categories ?? [],\n addons: response.data.addons ?? { items: [] },\n },\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function getStoreLogoUrl(): Promise<string | null> {\n const response = await getStore();\n\n if (response.success && response.data?.logo) {\n return response.data.logo;\n }\n\n return null;\n}\n\nexport async function getStoreBannerUrl(): Promise<string | null> {\n const response = await getStore();\n\n if (response.success && response.data?.banner) {\n return response.data.banner;\n }\n\n return null;\n}\n","/**\n * Products Module\n *\n * API methods for product data.\n */\n\nimport { get } from '../core/client';\nimport { getConfig, getShopId } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type {\n SDKResponse,\n Product,\n ProductCategory,\n ProductGroup,\n ProductVariant,\n PriceVariant,\n CursorPagination,\n} from '../types';\nimport { getStore } from './store';\nimport { getMergedStorefrontProducts } from '../utils/storefront-catalog';\n\ninterface ProductsResponse {\n products: Product[];\n groups?: ProductGroup[];\n pagination?: CursorPagination | null;\n}\n\ninterface ProductResponse {\n product: Product;\n}\n\nconst PRODUCTS_CACHE_TTL = 2 * 60 * 1000;\n\nexport interface GetStorefrontProductsPageOptions {\n cursor?: string | null;\n limit?: number;\n sort?: 'featured' | 'newest' | 'price-asc' | 'price-desc' | string | null;\n category?: string | null;\n hideOutOfStock?: boolean;\n}\n\nfunction getStorefrontProductsPageCategoryCacheKey(category: string | null | undefined): string {\n if (category === undefined) return 'category:unset';\n if (category === null) return 'category:null';\n return `category:${category}`;\n}\n\nfunction priceVariantToProductVariant(variant: PriceVariant & { stock?: number }): ProductVariant {\n return {\n id: variant.id,\n title: variant.title ?? variant.label ?? '',\n price: typeof variant.price === 'number' ? variant.price : Number(variant.price) || 0,\n stock: typeof variant.stock === 'number' ? variant.stock : undefined,\n // Dynamic Delivery (S8): carry the availability pair through. A supplier-backed\n // variant reports `stock: 0`, so dropping `orderable` here would make the mapped\n // variant look sold out. Left `undefined` when the source omits it, which keeps\n // the historical stock-only behaviour for payloads that predate the field.\n orderable: typeof variant.orderable === 'boolean' ? variant.orderable : undefined,\n supplier_backed:\n typeof variant.supplier_backed === 'boolean' ? variant.supplier_backed : undefined,\n quantity_min: variant.quantity_min,\n quantity_max: variant.quantity_max,\n quantityMin: variant.quantityMin,\n quantityMax: variant.quantityMax,\n image_id: variant.image_id,\n imageId: variant.imageId,\n cloudflare_image_id: variant.cloudflare_image_id,\n cloudflareImageId: variant.cloudflareImageId,\n image_url: variant.image_url,\n imageUrl: variant.imageUrl,\n };\n}\n\nfunction normalizeProduct(product: Product): Product {\n if (product.variants && product.variants.length > 0) {\n return product;\n }\n\n const priceVariants = product.price_variants;\n if (!Array.isArray(priceVariants) || priceVariants.length === 0) {\n return product;\n }\n\n return {\n ...product,\n variants: priceVariants.map((variant) =>\n priceVariantToProductVariant(variant as PriceVariant & { stock?: number })\n ),\n };\n}\n\nexport async function getProducts(): Promise<SDKResponse<Product[]>> {\n const config = getConfig();\n const response = await get<ProductsResponse>(\n buildEndpoint('/v1/storefront/products/public/:storeSlug', {\n storeSlug: config.storeSlug,\n }),\n {\n cache: {\n key: `products:${config.storeSlug}`,\n ttl: PRODUCTS_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n // The public route returns every public product exactly once in the flat `products` array —\n // group-bound products (e.g. variant-style DYNAMIC products) are included there too, so no\n // group merge is needed anymore. Groups only carry `product_uniqids` references into this\n // list. getMergedStorefrontProducts just dedupes by uniqid (first entry wins).\n return {\n success: true,\n data: getMergedStorefrontProducts(response.data.products.map(normalizeProduct)),\n };\n }\n\n return {\n success: false,\n message: response.message,\n data: [],\n };\n}\n\nexport async function getStorefrontProductsPage(\n options?: GetStorefrontProductsPageOptions,\n): Promise<SDKResponse<{ products: Product[]; pagination: CursorPagination | null }>> {\n const config = getConfig();\n const query = new URLSearchParams();\n if (typeof options?.cursor === 'string' && options.cursor.trim().length > 0) {\n query.set('cursor', options.cursor);\n }\n if (Number.isFinite(options?.limit)) {\n query.set('limit', String(Math.max(1, Math.floor(options?.limit ?? 0))));\n }\n if (typeof options?.sort === 'string' && options.sort.trim().length > 0) {\n query.set('sort', options.sort.trim());\n }\n if (typeof options?.category === 'string' && options.category.trim().length > 0) {\n query.set('category', options.category.trim());\n }\n if (options?.hideOutOfStock === true) {\n query.set('hide_out_of_stock', 'true');\n }\n const querySuffix = query.size > 0 ? `?${query.toString()}` : '';\n\n const response = await get<ProductsResponse>(\n `${buildEndpoint('/v1/storefront/products/shop/:storeSlug', {\n storeSlug: config.storeSlug,\n })}${querySuffix}`,\n {\n cache: {\n key: `products:page:${config.storeSlug}:${options?.limit ?? 'default'}:${options?.cursor ?? 'start'}:${options?.sort ?? 'featured'}:${getStorefrontProductsPageCategoryCacheKey(options?.category)}:${options?.hideOutOfStock === true ? 'in-stock' : 'all-stock'}`,\n ttl: PRODUCTS_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: {\n products: response.data.products.map(normalizeProduct),\n pagination: response.data.pagination ?? null,\n },\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function getProduct(\n idOrSlug: string\n): Promise<SDKResponse<Product>> {\n // Slug lookups need the current shop id. Resolve it lazily so callers do not\n // have to remember to call getStore()/getStorefront() first.\n let shopId = getShopId();\n if (!shopId) {\n const store = await getStore();\n shopId = store.success ? (store.data?.id ?? null) : null;\n }\n\n const queryParams = shopId ? `?slug_shop_id=${encodeURIComponent(shopId)}` : '';\n\n const response = await get<ProductResponse>(\n `${buildEndpoint('/v1/storefront/products/unique/:idOrSlug', { idOrSlug })}${queryParams}`,\n {\n cache: {\n key: `product:${idOrSlug}:${shopId ?? 'no-shop'}`,\n ttl: PRODUCTS_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data?.product) {\n return {\n success: true,\n data: normalizeProduct(response.data.product),\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function getCategories(): Promise<SDKResponse<string[]>> {\n const products = await getProducts();\n\n if (!products.success || !products.data) {\n return {\n success: false,\n message: products.message,\n };\n }\n\n const categories = new Set<string>();\n for (const product of products.data) {\n if (product.categories) {\n for (const category of product.categories) {\n if (typeof category === 'string') {\n categories.add(category);\n } else if (category && typeof category === 'object' && 'uniqid' in category) {\n categories.add((category as ProductCategory).uniqid);\n }\n }\n }\n }\n\n return {\n success: true,\n data: Array.from(categories),\n };\n}\n","import { getConfig, isInitialized } from '../core/config';\nimport { post } from '../core/client';\nimport type { AffiliateValidation, SDKResponse } from '../types';\n\nconst STORAGE_KEY = 'shoppex:affiliate_code:v1';\nconst DEFAULT_TTL_DAYS = 30;\n\ntype StoredAffiliate = {\n code: string;\n expiresAt: number;\n};\n\nfunction nowMs() {\n return Date.now();\n}\n\nfunction ttlMs(days: number) {\n return Math.max(1, days) * 24 * 60 * 60 * 1000;\n}\n\nfunction normalizeAffiliateCode(code: string | null | undefined): string | null {\n const normalized = code?.trim().toLowerCase();\n return normalized ? normalized : null;\n}\n\nfunction safeRead(): StoredAffiliate | null {\n if (typeof window === 'undefined') return null;\n try {\n const raw = window.localStorage.getItem(STORAGE_KEY);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as StoredAffiliate;\n if (!parsed || typeof parsed.code !== 'string' || typeof parsed.expiresAt !== 'number') return null;\n return parsed;\n } catch {\n return null;\n }\n}\n\nfunction safeWrite(value: StoredAffiliate) {\n if (typeof window === 'undefined') return;\n try {\n window.localStorage.setItem(STORAGE_KEY, JSON.stringify(value));\n } catch {\n // ignore\n }\n}\n\nexport function setAffiliateCode(code: string | null | undefined, ttlDays = DEFAULT_TTL_DAYS): string | null {\n const normalized = normalizeAffiliateCode(code);\n if (!normalized) {\n clearAffiliateCode();\n return null;\n }\n\n safeWrite({ code: normalized, expiresAt: nowMs() + ttlMs(ttlDays) });\n return normalized;\n}\n\nexport function clearAffiliateCode(): void {\n if (typeof window === 'undefined') return;\n try {\n window.localStorage.removeItem(STORAGE_KEY);\n } catch {\n // ignore\n }\n}\n\nexport function getAffiliateCode(): string | null {\n const stored = safeRead();\n if (!stored) return null;\n if (stored.expiresAt <= nowMs()) {\n clearAffiliateCode();\n return null;\n }\n return normalizeAffiliateCode(stored.code);\n}\n\nexport async function validateAffiliateCode(code: string): Promise<SDKResponse<AffiliateValidation>> {\n const normalizedCode = normalizeAffiliateCode(code);\n if (!normalizedCode) {\n return {\n success: false,\n data: {\n valid: false,\n affiliate_code: null,\n discount_active: false,\n discount_percent: 0,\n },\n message: 'Affiliate code is required',\n };\n }\n\n const config = getConfig();\n const response = await post<AffiliateValidation>(\n '/v1/storefront/affiliates/resolve',\n {\n shop_slug: config.storeSlug,\n code: normalizedCode,\n },\n { retries: 0 }\n );\n\n if (!response.success) {\n return response;\n }\n\n if (!response.data?.valid || !response.data.affiliate_code) {\n const programDisabled = response.data?.program_enabled === false;\n return {\n success: false,\n data: {\n valid: false,\n ...(response.data?.program_enabled !== undefined ? { program_enabled: response.data.program_enabled } : {}),\n affiliate_code: null,\n discount_active: false,\n discount_percent: 0,\n },\n message: response.message\n ?? (programDisabled ? 'Affiliate program is disabled for this shop.' : 'Invalid affiliate code.'),\n };\n }\n\n return {\n success: true,\n data: {\n valid: true,\n ...(response.data.program_enabled !== undefined ? { program_enabled: response.data.program_enabled } : {}),\n affiliate_code: normalizeAffiliateCode(response.data.affiliate_code),\n discount_active: Boolean(response.data.discount_active),\n discount_percent: Number(response.data.discount_percent ?? 0),\n },\n ...(response.message ? { message: response.message } : {}),\n };\n}\n\nexport async function applyAffiliateCode(code: string): Promise<SDKResponse<AffiliateValidation>> {\n const result = await validateAffiliateCode(code);\n if (result.success && result.data?.affiliate_code) {\n setAffiliateCode(result.data.affiliate_code);\n }\n\n return result;\n}\n\n/**\n * Capture an affiliate code from the current URL and store it for 30 days (last-click).\n *\n * Example:\n * - URL: https://mystore.com/product/abc?ref=deadbeef\n * - captureAffiliateFromUrl() stores \"deadbeef\" and returns it.\n */\nexport async function captureAffiliateFromUrl(param = 'ref'): Promise<string | null> {\n if (typeof window === 'undefined') return null;\n\n let code: string | null = null;\n try {\n const url = new URL(window.location.href);\n const raw = url.searchParams.get(param);\n code = raw ? raw.trim() : null;\n } catch {\n code = null;\n }\n\n code = normalizeAffiliateCode(code);\n if (!code) return null;\n\n // Store immediately so we don't lose it if attribution call fails.\n setAffiliateCode(code);\n\n // Optional: validate + normalize with backend. If invalid, clear it.\n if (isInitialized()) {\n try {\n const config = getConfig();\n const res = await post<{ accepted?: boolean; affiliate_code?: string | null }>(\n '/v1/storefront/affiliates/attribution',\n { shop_slug: config.storeSlug, code },\n { retries: 0 }\n );\n if (!res.success || !res.data?.accepted || !res.data?.affiliate_code) {\n clearAffiliateCode();\n return null;\n }\n setAffiliateCode(res.data.affiliate_code);\n return res.data.affiliate_code;\n } catch {\n // keep stored raw code, from-cart will validate later\n return code;\n }\n }\n\n return code;\n}\n","import type { CartAddon, CartItem } from '../types/cart';\n\nfunction hashString(value: string): string {\n let hash = 2166136261;\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i);\n hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);\n }\n return (hash >>> 0).toString(16);\n}\n\nfunction normalizeAddons(addons: CartAddon[] | undefined): CartAddon[] {\n if (!addons?.length) return [];\n return [...addons]\n .map((addon) => ({ id: addon.id, quantity: addon.quantity ?? 1 }))\n .sort((a, b) => a.id.localeCompare(b.id));\n}\n\nfunction normalizeCustomFields(fields: Record<string, string> | undefined): Record<string, string> {\n if (!fields) return {};\n const entries = Object.entries(fields)\n .filter(([, value]) => typeof value === 'string')\n .sort(([a], [b]) => a.localeCompare(b));\n return Object.fromEntries(entries);\n}\n\nexport type CartLineIdentityInput = Pick<\n CartItem,\n 'product_id' | 'variant_id' | 'price_variant_id' | 'addons' | 'custom_fields' | 'price_data' | 'pay_what_you_want_price'\n>;\n\nexport function computeCartLineId(input: CartLineIdentityInput): string {\n const payload = {\n product_id: input.product_id,\n variant_id: input.variant_id,\n price_variant_id: input.price_variant_id ?? null,\n addons: normalizeAddons(input.addons),\n custom_fields: normalizeCustomFields(input.custom_fields),\n unit_price:\n typeof input.price_data?.unit_price === 'number' && Number.isFinite(input.price_data.unit_price)\n ? input.price_data.unit_price\n : null,\n pay_what_you_want_price:\n typeof input.pay_what_you_want_price === 'number' && Number.isFinite(input.pay_what_you_want_price)\n ? input.pay_what_you_want_price\n : null,\n };\n return hashString(JSON.stringify(payload));\n}\n\nexport function ensureCartLineId(item: CartItem): CartItem {\n if (typeof item.line_id === 'string' && item.line_id.trim()) {\n return item;\n }\n return { ...item, line_id: computeCartLineId(item) };\n}\n","export function normalizeRequestedCurrency(value: string | null | undefined): string | null {\n const normalized = value?.trim().toUpperCase();\n return normalized && /^[A-Z]{3}$/.test(normalized) ? normalized : null;\n}\n\nexport function getRequestedCurrencyFromLocation(): string | null {\n if (typeof window === 'undefined' || !window.location) {\n return null;\n }\n\n const search = typeof window.location.search === 'string' ? window.location.search : '';\n if (search) {\n return normalizeRequestedCurrency(new URLSearchParams(search).get('currency'));\n }\n\n const href = typeof window.location.href === 'string' ? window.location.href : '';\n if (!href) {\n return null;\n }\n\n try {\n return normalizeRequestedCurrency(\n new URL(href, 'https://storefront.shoppex.local').searchParams.get('currency'),\n );\n } catch {\n return null;\n }\n}\n","/**\n * Cart Module\n *\n * localStorage-based cart with support for Shoppex features:\n * - Addons (express shipping, gift wrap, etc.)\n * - Custom Fields (engraving, gift message, etc.)\n * - Price Variants (different pricing tiers)\n */\n\nimport { getItem, setItem, removeItem } from '../utils/storage';\nimport { getConfig } from '../core/config';\nimport { post } from '../core/client';\nimport { CartError } from '../core/errors';\nimport type {\n CartItem,\n CartAddOptions,\n CartItemUpdate,\n CartPayload,\n CartMetadata,\n CartStats,\n CartQuote,\n CartBasketMergeLine,\n CartCodeSource,\n} from '../types';\nimport { getAffiliateCode } from './affiliates';\nimport { computeCartLineId, ensureCartLineId } from '../utils/cart-line-id';\nimport {\n getRequestedCurrencyFromLocation,\n normalizeRequestedCurrency,\n} from '../utils/requested-currency';\nimport { roundPayableAmount } from '@shoppex/contracts/catalog-unit-price';\n\nconst STORAGE_KEYS = {\n cart: 'cart',\n cartBackup: 'cart_backup',\n meta: 'cart_meta',\n metaBackup: 'cart_backup_meta',\n coupon: 'cart_coupon',\n couponBackup: 'cart_coupon_backup',\n} as const;\n\ntype StorageKeyType = keyof typeof STORAGE_KEYS;\n\nfunction getStorageKey(type: StorageKeyType): string {\n return `${STORAGE_KEYS[type]}_${getConfig().storeSlug}`;\n}\n\nfunction hashString(value: string): string {\n let hash = 2166136261;\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i);\n hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);\n }\n return (hash >>> 0).toString(16);\n}\n\nfunction computeChecksum(cart: CartItem[]): string {\n return hashString(JSON.stringify(cart));\n}\n\nfunction normalizeQuantity(value: number): number {\n if (!Number.isFinite(value)) {\n throw new CartError('quantity must be a finite number');\n }\n return Math.floor(value);\n}\n\nfunction normalizeCouponCode(value: string | null | undefined): string | null {\n const normalized = value?.trim().toUpperCase();\n return normalized ? normalized : null;\n}\n\ntype StoredCartCode = {\n code: string;\n source: CartCodeSource;\n};\n\nfunction getStoredCartCode(): StoredCartCode | null {\n const raw = getItem<unknown>(getStorageKey('coupon'));\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {\n return null;\n }\n const record = raw as Record<string, unknown>;\n const code = typeof record.code === 'string' ? normalizeCouponCode(record.code) : null;\n const source = record.source === 'COUPON' || record.source === 'AFFILIATE'\n ? record.source\n : null;\n return code && source ? { code, source } : null;\n}\n\nfunction normalizeCartItems(value: unknown): CartItem[] {\n if (!Array.isArray(value)) return [];\n const normalized: CartItem[] = [];\n for (const entry of value) {\n if (!entry || typeof entry !== 'object') continue;\n const record = entry as Record<string, unknown>;\n const productId = typeof record.product_id === 'string' ? record.product_id.trim() : '';\n const variantId = typeof record.variant_id === 'string' ? record.variant_id.trim() : '';\n const quantity = Number(record.quantity);\n\n if (!productId || !variantId || !Number.isFinite(quantity) || quantity < 1) {\n continue;\n }\n\n const item: CartItem = {\n line_id: '',\n product_id: productId,\n variant_id: variantId,\n quantity: Math.floor(quantity),\n };\n\n if (typeof record.price_variant_id === 'string') {\n item.price_variant_id = record.price_variant_id;\n }\n if (record.price_data && typeof record.price_data === 'object') {\n const priceData = record.price_data as Record<string, unknown>;\n if (typeof priceData.unit_price === 'number' && Number.isFinite(priceData.unit_price)) {\n item.price_data = { unit_price: priceData.unit_price };\n }\n }\n if (typeof record.pay_what_you_want_price === 'number' && Number.isFinite(record.pay_what_you_want_price)) {\n item.pay_what_you_want_price = record.pay_what_you_want_price;\n }\n if (Array.isArray(record.addons)) {\n item.addons = record.addons as CartItem['addons'];\n }\n if (record.custom_fields && typeof record.custom_fields === 'object' && !Array.isArray(record.custom_fields)) {\n item.custom_fields = record.custom_fields as Record<string, string>;\n }\n\n // Preserve the optional display snapshot (title/variant_title/image_url/addon_labels) across the\n // localStorage round-trip so the njk cart drawer/page can render without a product fetch.\n if (typeof record.title === 'string') {\n item.title = record.title;\n }\n if (typeof record.variant_title === 'string') {\n item.variant_title = record.variant_title;\n }\n if (typeof record.image_url === 'string') {\n item.image_url = record.image_url;\n }\n if (Array.isArray(record.addon_labels)) {\n item.addon_labels = record.addon_labels.filter((label): label is string => typeof label === 'string');\n }\n if (typeof record.max_quantity === 'number' && Number.isFinite(record.max_quantity)) {\n item.max_quantity = record.max_quantity;\n }\n if (typeof record.min_quantity === 'number' && Number.isFinite(record.min_quantity)) {\n item.min_quantity = record.min_quantity;\n }\n\n // Self-heal on READ: clamp quantity to the stored [min,max] here, after the bounds are read. This is\n // the single chokepoint every access flows through (getCart -> getCartPayload -> serializeCart/\n // quoteCart -> checkout), so a stale/tampered/restored localStorage line can never reach checkout\n // out of bounds — closing restoreCartFromBackup and direct-localStorage-edit at the root, not just\n // the write paths.\n clampQuantityToBounds(item);\n\n const storedLineId = typeof record.line_id === 'string' ? record.line_id.trim() : '';\n item.line_id = storedLineId || computeCartLineId(item);\n\n normalized.push(ensureCartLineId(item));\n }\n return normalized;\n}\n\nfunction getCartMetadata(): CartMetadata | null {\n return getItem<CartMetadata>(getStorageKey('meta'));\n}\n\nexport function getCartCoupon(): string | null {\n return getStoredCartCode()?.code ?? null;\n}\n\nexport function getCartCouponSource(): CartCodeSource | null {\n return getStoredCartCode()?.source ?? null;\n}\n\nexport function setCartCoupon(\n coupon: string | null | undefined,\n source: CartCodeSource = 'COUPON',\n): string | null {\n const normalizedCoupon = normalizeCouponCode(coupon);\n if (!normalizedCoupon) {\n removeItem(getStorageKey('coupon'));\n return null;\n }\n\n setItem(getStorageKey('coupon'), { code: normalizedCoupon, source });\n return normalizedCoupon;\n}\n\nexport function clearCartCoupon(): void {\n removeItem(getStorageKey('coupon'));\n}\n\nfunction writeCart(cart: CartItem[]): void {\n const normalizedCart = normalizeCartItems(cart);\n setItem(getStorageKey('cart'), normalizedCart);\n const now = Date.now();\n const previous = getCartMetadata();\n const nextMeta: CartMetadata = {\n created_at: previous?.created_at ?? now,\n last_modified: now,\n version: (previous?.version ?? 0) + 1,\n checksum: computeChecksum(normalizedCart),\n };\n setItem(getStorageKey('meta'), nextMeta);\n\n if (normalizedCart.length === 0) {\n clearCartCoupon();\n }\n}\n\nfunction setCartWithMetadata(cart: CartItem[], metadata?: CartMetadata | null): void {\n const normalizedCart = normalizeCartItems(cart);\n setItem(getStorageKey('cart'), normalizedCart);\n const now = Date.now();\n const base = metadata ?? getCartMetadata();\n const nextMeta: CartMetadata = {\n created_at: base?.created_at ?? now,\n last_modified: now,\n version: base?.version ?? 1,\n checksum: computeChecksum(normalizedCart),\n };\n setItem(getStorageKey('meta'), nextMeta);\n}\n\nexport function getCart(): CartItem[] {\n const raw = getItem<unknown>(getStorageKey('cart'));\n return normalizeCartItems(raw);\n}\n\n/** Resolve a cart line_id for product+variant. When multiple configs exist, returns the first line. */\nexport function resolveCartLineId(\n productId: string,\n variantId: string,\n cart: CartItem[] = getCart(),\n): string {\n const matches = cart.filter(\n (item) => item.product_id === productId && item.variant_id === variantId,\n );\n if (matches.length === 0) {\n throw new CartError(`No cart line found for ${productId}/${variantId}`);\n }\n return matches[0].line_id;\n}\n\nexport function getCartItemCount(): number {\n const cart = getCart();\n return cart.reduce((sum, item) => sum + item.quantity, 0);\n}\n\nexport function addToCart(\n productId: string,\n variantId: string,\n quantity: number = 1,\n options?: CartAddOptions\n): void {\n if (!productId || !variantId) {\n throw new CartError('product_id and variant_id are required');\n }\n\n const normalizedQuantity = normalizeQuantity(quantity);\n if (normalizedQuantity < 1) {\n throw new CartError('quantity must be at least 1');\n }\n\n const cart = getCart();\n\n const lineId = computeCartLineId({\n product_id: productId,\n variant_id: variantId,\n addons: options?.addons,\n custom_fields: options?.custom_fields,\n price_variant_id: options?.price_variant_id,\n price_data: options?.price_data,\n pay_what_you_want_price: options?.pay_what_you_want_price,\n });\n\n const existingIndex = cart.findIndex((item) => item.line_id === lineId);\n\n if (existingIndex >= 0) {\n cart[existingIndex].quantity += normalizedQuantity;\n\n if (options?.addons) {\n cart[existingIndex].addons = options.addons;\n }\n if (options?.custom_fields) {\n cart[existingIndex].custom_fields = options.custom_fields;\n }\n if (options?.price_variant_id) {\n cart[existingIndex].price_variant_id = options.price_variant_id;\n }\n if (options?.price_data) {\n cart[existingIndex].price_data = options.price_data;\n }\n if (options?.pay_what_you_want_price !== undefined) {\n cart[existingIndex].pay_what_you_want_price = options.pay_what_you_want_price;\n }\n applyDisplaySnapshot(cart[existingIndex], options);\n clampQuantityToBounds(cart[existingIndex]);\n } else {\n const pushed: CartItem = {\n line_id: lineId,\n product_id: productId,\n variant_id: variantId,\n quantity: normalizedQuantity,\n addons: options?.addons,\n custom_fields: options?.custom_fields,\n price_variant_id: options?.price_variant_id,\n price_data: options?.price_data,\n pay_what_you_want_price: options?.pay_what_you_want_price,\n title: options?.title,\n variant_title: options?.variant_title,\n image_url: options?.image_url,\n addon_labels: options?.addon_labels,\n max_quantity: options?.max_quantity,\n min_quantity: options?.min_quantity,\n };\n clampQuantityToBounds(pushed);\n cart.push(pushed);\n }\n\n writeCart(cart);\n}\n\n// Cart-wide invariant: a line's quantity must stay within its stored [min_quantity, max_quantity]\n// bounds. Every write path routes through this — addToCart (merge+push), setCartItem (merge+push),\n// updateCartItem, mergeBaskets (merge+push), moveBasketItem (merge+push) — AND, crucially, the READ\n// path normalizeCartItems (getCart) clamps too, so a stale/tampered/restored localStorage line is\n// self-healed before it can reach checkout. No entrypoint can persist or serve a quantity outside the\n// purchasable range the backend would reject.\n// Order matters: apply min FIRST, then max — so on the degenerate min>max case (e.g. quantity_min 2 but\n// only 1 in stock) MAX wins and the line is never pushed above the stock cap (over-stock is the harder\n// backend reject than under-min). Never below 1. No-op for the bound(s) that are absent.\nfunction clampQuantityToBounds(item: CartItem): void {\n const min = item.min_quantity;\n if (typeof min === 'number' && Number.isFinite(min) && item.quantity < min) {\n item.quantity = Math.floor(min);\n }\n const max = item.max_quantity;\n if (typeof max === 'number' && Number.isFinite(max) && item.quantity > max) {\n item.quantity = Math.floor(max);\n }\n if (item.quantity < 1) {\n item.quantity = 1;\n }\n}\n\n// Copy the optional display snapshot fields from add-options onto an existing line. Display-only —\n// kept separate from the pricing/identity fields so the snapshot logic is identical for add and set.\nfunction applyDisplaySnapshot(item: CartItem, options?: CartAddOptions): void {\n // Authoritative full re-snapshot (buy-box producer): replace ALL display fields verbatim, including\n // CLEARING ones the new snapshot omits — a removed add-on or a lifted cap must not leave stale data.\n if (options?.replace_display_snapshot) {\n item.title = options.title;\n item.variant_title = options.variant_title;\n item.image_url = options.image_url;\n item.addon_labels = options.addon_labels;\n item.max_quantity = options.max_quantity;\n item.min_quantity = options.min_quantity;\n return;\n }\n // Partial direct SDK call: only overwrite the fields actually provided.\n if (options?.title !== undefined) {\n item.title = options.title;\n }\n if (options?.variant_title !== undefined) {\n item.variant_title = options.variant_title;\n }\n if (options?.image_url !== undefined) {\n item.image_url = options.image_url;\n }\n if (options?.addon_labels !== undefined) {\n item.addon_labels = options.addon_labels;\n }\n if (options?.max_quantity !== undefined) {\n item.max_quantity = options.max_quantity;\n }\n if (options?.min_quantity !== undefined) {\n item.min_quantity = options.min_quantity;\n }\n}\n\nexport function setCartItem(\n productId: string,\n variantId: string,\n quantity: number = 1,\n options?: CartAddOptions\n): void {\n if (!productId || !variantId) {\n throw new CartError('product_id and variant_id are required');\n }\n\n const normalizedQuantity = normalizeQuantity(quantity);\n if (normalizedQuantity < 1) {\n throw new CartError('quantity must be at least 1');\n }\n\n const cart = getCart();\n const lineId = computeCartLineId({\n product_id: productId,\n variant_id: variantId,\n addons: options?.addons,\n custom_fields: options?.custom_fields,\n price_variant_id: options?.price_variant_id,\n price_data: options?.price_data,\n pay_what_you_want_price: options?.pay_what_you_want_price,\n });\n\n // Buy-now / replace semantics: one visible line per (product_id, variant_id). Drop any prior\n // line_ids for that pair so a config change (addons, price_data) does not leave a stale sibling.\n for (let index = cart.length - 1; index >= 0; index -= 1) {\n if (cart[index].product_id === productId && cart[index].variant_id === variantId) {\n cart.splice(index, 1);\n }\n }\n\n const pushed: CartItem = {\n line_id: lineId,\n product_id: productId,\n variant_id: variantId,\n quantity: normalizedQuantity,\n addons: options?.addons,\n custom_fields: options?.custom_fields,\n price_variant_id: options?.price_variant_id,\n price_data: options?.price_data,\n pay_what_you_want_price: options?.pay_what_you_want_price,\n title: options?.title,\n variant_title: options?.variant_title,\n image_url: options?.image_url,\n addon_labels: options?.addon_labels,\n max_quantity: options?.max_quantity,\n min_quantity: options?.min_quantity,\n };\n clampQuantityToBounds(pushed);\n cart.push(pushed);\n\n writeCart(cart);\n}\n\n/**\n * Patch one cart line.\n *\n * TRI-STATE BOUNDS: `min_quantity`/`max_quantity` accept `null` to DELETE the\n * stored bound — see {@link CartItemUpdate}. `undefined` (or an absent key)\n * leaves it alone, which is why a removed ceiling needs its own spelling.\n *\n * NO-OP UPDATES DO NOT WRITE. An update that leaves the cart byte-identical\n * returns without touching storage: no metadata bump, no `version` increment,\n * and — because the storage write is what other tabs observe — no `storage`\n * event. Writing anyway made an ineffective heal indistinguishable from a real\n * cart change, and two tabs healing the same line could hand the event back and\n * forth indefinitely. Line-shape healing of a legacy stored row is NOT this\n * function's job: `normalizeCartItems` clamps and repairs on every READ, which\n * is the chokepoint every access already flows through.\n */\nexport function updateCartItem(\n lineId: string,\n updates: CartItemUpdate\n): void {\n const cart = getCart();\n const normalizedLineId = lineId.trim();\n if (!normalizedLineId) {\n throw new CartError('line_id is required');\n }\n\n const index = cart.findIndex((item) => item.line_id === normalizedLineId);\n\n if (index < 0) {\n throw new CartError('Item not found in cart');\n }\n\n // The exact bytes the result is compared against, taken BEFORE any mutation.\n const before = JSON.stringify(cart);\n\n if (updates.quantity !== undefined) {\n const normalizedQuantity = normalizeQuantity(updates.quantity);\n if (normalizedQuantity < 1) {\n cart.splice(index, 1);\n writeCart(cart);\n return;\n }\n cart[index].quantity = normalizedQuantity;\n }\n\n if (updates.addons !== undefined) {\n cart[index].addons = updates.addons;\n }\n\n if (updates.custom_fields !== undefined) {\n cart[index].custom_fields = updates.custom_fields;\n }\n\n if (updates.price_variant_id !== undefined) {\n cart[index].price_variant_id = updates.price_variant_id;\n }\n if (updates.price_data !== undefined) {\n cart[index].price_data = updates.price_data;\n }\n if (updates.pay_what_you_want_price !== undefined) {\n cart[index].pay_what_you_want_price = updates.pay_what_you_want_price;\n }\n // Tri-state: `null` is the merchant's bound being REMOVED, and it has to\n // delete the stored key — a bound that can only be raised and lowered but\n // never cleared outlives the limit it describes.\n if (updates.max_quantity !== undefined) {\n if (updates.max_quantity === null) delete cart[index].max_quantity;\n else cart[index].max_quantity = updates.max_quantity;\n }\n if (updates.min_quantity !== undefined) {\n if (updates.min_quantity === null) delete cart[index].min_quantity;\n else cart[index].min_quantity = updates.min_quantity;\n }\n clampQuantityToBounds(cart[index]);\n\n // Pricing and configuration fields are part of a cart line's identity.\n // Recompute after every update and merge if the new identity already exists.\n const nextLineId = computeCartLineId(cart[index]);\n const duplicateIndex = cart.findIndex((item, itemIndex) => itemIndex !== index && item.line_id === nextLineId);\n if (duplicateIndex >= 0) {\n cart[duplicateIndex].quantity += cart[index].quantity;\n clampQuantityToBounds(cart[duplicateIndex]);\n cart.splice(index, 1);\n } else {\n cart[index].line_id = nextLineId;\n }\n\n // Nothing moved: writing would bump `version`/`last_modified` and emit a\n // storage event that says the cart changed when it did not.\n if (JSON.stringify(cart) === before) return;\n\n writeCart(cart);\n}\n\nexport function removeFromCart(lineId: string): void {\n const normalizedLineId = lineId.trim();\n if (!normalizedLineId) {\n throw new CartError('line_id is required');\n }\n\n const cart = getCart();\n const filtered = cart.filter((item) => item.line_id !== normalizedLineId);\n writeCart(filtered);\n}\n\n/**\n * Discards the cart entirely — and with it the proof that describes it.\n *\n * PAYMENT PATH. `latestQuoteToken` is evidence about a specific cart, and this\n * is the one mutation after which that cart does not exist in any form. Held\n * across the clear, the proof outlives its subject: a caller that clears and\n * re-adds (Buy Now REPLACES the cart) hands `/from-cart` a token bound to the\n * previous cart's hash, which is refused as `quote_token_stale` — a hand-off\n * dead-ended by a proof nobody asked for. And with no re-quote in between there\n * is nothing to replace it with, so the retry is refused identically.\n *\n * Only this path clears it. Every OTHER mutation turns one cart into another\n * cart, where a proof that no longer matches is the server's to refuse: it\n * answers `quote_token_stale`, the surfaces re-quote, and the buyer approves the\n * new total. Dropping the proof there instead would silently remove the approved\n * -total ceiling from a checkout that raced the re-quote, which is the failure\n * the token exists to prevent.\n */\nexport function clearCart(): void {\n removeItem(getStorageKey('cart'));\n removeItem(getStorageKey('meta'));\n clearCartCoupon();\n clearLatestQuoteToken();\n}\n\nexport function createCartBackup(): void {\n const cart = getCart();\n setItem(getStorageKey('cartBackup'), cart);\n const cartCode = getStoredCartCode();\n if (cartCode) {\n setItem(getStorageKey('couponBackup'), cartCode);\n } else {\n removeItem(getStorageKey('couponBackup'));\n }\n const metadata = getCartMetadata();\n if (metadata) {\n setItem(getStorageKey('metaBackup'), metadata);\n } else {\n const now = Date.now();\n setItem(getStorageKey('metaBackup'), {\n created_at: now,\n last_modified: now,\n version: 1,\n checksum: computeChecksum(cart),\n });\n }\n}\n\nexport function restoreCartFromBackup(): boolean {\n const backupRaw = getItem<unknown>(getStorageKey('cartBackup'));\n const backup = normalizeCartItems(backupRaw);\n const backupMeta = getItem<CartMetadata>(getStorageKey('metaBackup'));\n const backupCoupon = getItem<unknown>(getStorageKey('couponBackup'));\n\n if (backup && backup.length > 0) {\n setCartWithMetadata(backup, backupMeta);\n if (backupCoupon && typeof backupCoupon === 'object' && !Array.isArray(backupCoupon)) {\n const record = backupCoupon as Record<string, unknown>;\n const source = record.source === 'COUPON' || record.source === 'AFFILIATE'\n ? record.source\n : null;\n if (typeof record.code === 'string' && source) {\n setCartCoupon(record.code, source);\n } else {\n clearCartCoupon();\n }\n } else {\n clearCartCoupon();\n }\n return true;\n }\n\n return false;\n}\n\nexport function mergeBaskets(items: CartBasketMergeLine[]): CartItem[] {\n const cart = getCart();\n\n for (const incoming of items) {\n const productId = typeof incoming.product_id === 'string' ? incoming.product_id.trim() : '';\n const variantId = typeof incoming.variant_id === 'string' ? incoming.variant_id.trim() : '';\n if (!productId || !variantId) {\n continue;\n }\n\n let normalizedQuantity: number;\n try {\n normalizedQuantity = normalizeQuantity(incoming.quantity);\n } catch {\n continue;\n }\n\n if (normalizedQuantity < 1) {\n continue;\n }\n\n const mergedLine = ensureCartLineId({\n ...incoming,\n line_id: incoming.line_id ?? computeCartLineId(incoming),\n product_id: productId,\n variant_id: variantId,\n quantity: normalizedQuantity,\n });\n const index = cart.findIndex((item) => item.line_id === mergedLine.line_id);\n\n if (index >= 0) {\n cart[index].quantity = Math.max(cart[index].quantity, normalizedQuantity);\n clampQuantityToBounds(cart[index]);\n } else {\n clampQuantityToBounds(mergedLine);\n cart.push(mergedLine);\n }\n }\n\n writeCart(cart);\n return cart;\n}\n\nexport function moveBasketItem(\n fromProductId: string,\n fromVariantId: string,\n toProductId: string,\n toVariantId: string\n): void {\n const cart = getCart();\n const fromIndex = cart.findIndex(\n (item) => item.product_id === fromProductId && item.variant_id === fromVariantId\n );\n\n if (fromIndex < 0) {\n throw new CartError('Item not found in cart');\n }\n\n const [fromItem] = cart.splice(fromIndex, 1);\n const toLineId = computeCartLineId({\n ...fromItem,\n product_id: toProductId,\n variant_id: toVariantId,\n });\n const toIndex = cart.findIndex((item) => item.line_id === toLineId);\n\n if (toIndex >= 0) {\n cart[toIndex].quantity += fromItem.quantity;\n clampQuantityToBounds(cart[toIndex]);\n } else {\n const moved = ensureCartLineId({\n ...fromItem,\n product_id: toProductId,\n variant_id: toVariantId,\n line_id: toLineId,\n });\n clampQuantityToBounds(moved);\n cart.push(moved);\n }\n\n writeCart(cart);\n}\n\nexport function validateCartIntegrity(): boolean {\n const cart = getCart();\n const metadata = getCartMetadata();\n const checksum = computeChecksum(cart);\n\n if (!metadata) {\n setCartWithMetadata(cart, null);\n return true;\n }\n\n return metadata.checksum === checksum;\n}\n\nexport function getCartStats(): CartStats {\n const cart = getCart();\n const integrityValid = validateCartIntegrity();\n const metadata = getCartMetadata();\n const backup = getItem<CartItem[]>(getStorageKey('cartBackup')) ?? [];\n const hasCompletePriceSnapshots =\n cart.length > 0 &&\n cart.every((item) => typeof item.price_data?.unit_price === 'number');\n const totalPrice = cart.reduce((sum, item) => {\n const unitPrice = item.price_data?.unit_price ?? 0;\n return sum + roundPayableAmount(unitPrice * item.quantity);\n }, 0);\n\n return {\n item_count: cart.length,\n total_quantity: cart.reduce((sum, item) => sum + item.quantity, 0),\n last_modified: metadata?.last_modified ?? 0,\n version: metadata?.version ?? 0,\n has_backup: backup.length > 0,\n integrity_valid: integrityValid,\n total_price: roundPayableAmount(totalPrice),\n total_price_is_estimate: cart.length > 0 && !hasCompletePriceSnapshots,\n };\n}\n\nexport function getCartPayload(coupon?: string): CartPayload {\n const config = getConfig();\n const normalizedCoupon = normalizeCouponCode(coupon) ?? getCartCoupon() ?? undefined;\n return {\n store_slug: config.storeSlug,\n items: getCart(),\n coupon: normalizedCoupon,\n };\n}\n\n/**\n * The ambient referral code checkout() will submit as `affiliate_code`.\n *\n * Read exactly like checkout()'s normalizeAffiliateCode ambient branch: the\n * referral code the cart itself carries (source `AFFILIATE`) takes precedence\n * over the stored `?ref=` attribution. Sending it with the quote is what makes\n * the displayed total equal the amount the invoice will charge — without it a\n * cart holding both a coupon and a `?ref=` attribution quotes high.\n */\nfunction getAmbientAffiliateCodeForQuote(): string | null {\n const storedCode = getCartCoupon();\n const storedSource = getCartCouponSource();\n if (storedSource === 'AFFILIATE' && storedCode) {\n return storedCode.trim().toLowerCase();\n }\n return getAffiliateCode();\n}\n\n/**\n * The proof from the most recent successful quote, held in memory only.\n *\n * Module-scoped rather than persisted: the token is evidence about a cart as\n * it was priced moments ago, and a stale one from a previous page load is\n * simply ignored by the server. Not exported as public API — `checkout()`\n * reads it, callers do not have to know it exists.\n */\nlet latestQuoteToken: string | null = null;\n\n/**\n * Which quote call the held token belongs to.\n *\n * Quote responses settle in ARRIVAL order, not request order: two overlapping\n * `quoteCart` calls (cart A, then cart A+B) can answer with the OLDER one last,\n * and the token stored is then evidence about a cart the buyer no longer has.\n *\n * That is not a mispricing — `/from-cart` binds the token to a hash of the cart\n * content, currency, shop and submitted codes (`isCartQuoteTokenApplicable`),\n * so a superseded token simply fails to apply and is treated as ABSENT, and the\n * proof is a one-directional CEILING that can never lower a price. What it\n * costs is the ceiling itself: the buyer silently loses the protection for the\n * rest of that checkout. Keeping the newest call's answer is what keeps the\n * proof present for the cart actually on screen.\n */\nlet quoteSequence = 0;\n\n/** @internal — read by checkout(); exported only across module boundaries. */\nexport function getLatestQuoteToken(): string | null {\n return latestQuoteToken;\n}\n\n/** @internal — test seam and cart-reset hook. */\nexport function clearLatestQuoteToken(): void {\n latestQuoteToken = null;\n // A quote already in flight must not resurrect the proof this cleared.\n quoteSequence += 1;\n}\n\nexport async function quoteCart(coupon?: string, currency?: string) {\n const sequence = (quoteSequence += 1);\n const payload = getCartPayload(coupon);\n const normalizedCurrency = normalizeRequestedCurrency(currency)\n ?? getRequestedCurrencyFromLocation()\n ?? normalizeRequestedCurrency(getConfig().currency);\n const response = await post<CartQuote>('/v1/storefront/cart/quote', {\n shop_slug: payload.store_slug,\n cart: payload.items,\n coupon: payload.coupon,\n affiliate_code: getAmbientAffiliateCodeForQuote() ?? undefined,\n currency: normalizedCurrency ?? undefined,\n });\n\n // Only a successful quote replaces the held proof — a failed quote must not\n // clear a still-valid one.\n //\n // A SUCCESSFUL quote that carries no token clears it, rather than leaving the\n // previous one in place. The proof is evidence about one specific priced\n // cart, and `/from-cart` refuses a submitted proof it cannot apply\n // (`quote_token_stale` / `_invalid`) instead of ignoring it. So a held token\n // that this quote did not reissue is not a harmless leftover: every later\n // `checkout()` submits it, is refused, and re-quoting never helps because a\n // tokenless answer used to leave it untouched — a dead end the buyer cannot\n // escape from inside the cart.\n //\n // And only the NEWEST call may replace it: a slower earlier quote answering\n // last would otherwise overwrite the current cart's proof with one bound to a\n // cart hash that no longer exists.\n if (sequence !== quoteSequence) return response;\n if (response.success) {\n latestQuoteToken = typeof response.data?.quote_token === 'string'\n ? response.data.quote_token\n : null;\n }\n\n return response;\n}\n\nexport function serializeCart(coupon?: string): string {\n const payload = getCartPayload(coupon);\n const json = JSON.stringify(payload);\n // UTF-8 safe Base64: encodeURIComponent converts to UTF-8, unescape converts percent-encoding to bytes\n if (typeof btoa !== 'undefined') {\n return btoa(unescape(encodeURIComponent(json)));\n }\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(json, 'utf8').toString('base64');\n }\n throw new CartError('Base64 encoding is not available in this environment');\n}\n","/**\n * Checkout Module\n *\n * Creates invoice via backend API and redirects to hosted checkout page.\n * All checkout flows go through: checkout.shoppex.io/invoice/{invoiceId}\n */\n\nimport { getConfig } from '../core/config';\nimport { post } from '../core/client';\nimport { getCart, getCartCoupon, getCartCouponSource, createCartBackup, clearCart, getLatestQuoteToken } from './cart';\nimport { getAffiliateCode } from './affiliates';\nimport type { CartItem, CartAddon } from '../types/cart';\nimport type { BuyerRewards } from '../types/api';\nimport {\n getRequestedCurrencyFromLocation,\n normalizeRequestedCurrency,\n} from '../utils/requested-currency';\n\nexport interface CheckoutOptions {\n autoRedirect?: boolean;\n locale?: string;\n email?: string;\n coupon?: string;\n currency?: string;\n /**\n * Referral (affiliate) code to submit, as a tri-state:\n *\n * - `undefined` — the SDK resolves it from storage (cart-applied referral\n * code first, then the ambient `?ref=` attribution).\n * - `''` — explicitly none: submit no referral code and do NOT re-read\n * storage. This is how a caller pins \"quoted WITHOUT a referral\"; without\n * it a code captured between the quote and the submit would be applied to\n * a total the buyer never saw.\n * - non-empty — pinned: submit exactly this code.\n *\n * `referralCode` is an alias and follows the same rules; `affiliateCode`\n * wins when both are present.\n */\n affiliateCode?: string;\n /** Alias of {@link CheckoutOptions.affiliateCode}, same tri-state. */\n referralCode?: string;\n customerCheckoutPath?: '/dashboard/api/checkout';\n /**\n * The cart this hand-off was approved FOR, as `JSON.stringify(getCart())`.\n *\n * PAYMENT PATH. A caller that writes the cart and reads it back before\n * checking out (Buy Now, which replaces the cart, is the sharp case) verifies\n * a cart it read at one moment, while these functions read storage again on\n * their way into the request — and localStorage is shared with every other\n * tab on the domain. A write landing in that gap is billed without ever\n * having passed the caller's verification.\n *\n * The caller cannot close that itself: any check it makes is one more read\n * BEFORE this one. Pinning the expected bytes moves the comparison to the\n * only place it can be conclusive — against the exact cart the call is about\n * to POST. A mismatch refuses before anything is created or sent.\n *\n * Honoured identically by BOTH invoice-creating entry points, `checkout()`\n * and `buildCheckoutUrl()` — they hit the same endpoint and create the same\n * invoice, so a pin that held on one and not the other would be a promise\n * the caller could not rely on. Only the refusal shape differs, following\n * each function's own success shape: `checkout()` returns\n * `{ success: false }`, `buildCheckoutUrl()` throws.\n *\n * Optional and additive: omitted, nothing changes, and the server is not\n * involved either way.\n */\n expectedCart?: string;\n}\n\nexport interface CheckoutResult {\n success: boolean;\n redirectUrl?: string;\n invoiceId?: string;\n rewards?: BuyerRewards | null;\n message?: string;\n /**\n * The server's machine-readable refusal identifier when the checkout was\n * refused, e.g. `errors.checkout.price_increased_since_quote` or\n * `errors.checkout.affiliate_code_not_applicable`. Branch on this rather\n * than on `message`, which is localized display copy.\n *\n * The quote-proof family — `errors.checkout.quote_token_invalid`,\n * `errors.checkout.quote_token_expired`, `errors.checkout.quote_token_stale`\n * — says the proof this call submitted could not be honoured: not ours, past\n * its window, or priced for a cart/currency/codes that have since moved. The\n * server refuses rather than pricing without the ceiling, so the caller's\n * response is always the same: `quoteCart()` again, show the buyer the new\n * total, and only then retry. A retry with the same stale token is refused\n * identically.\n *\n * Absent for failures the server never named (transport, timeout, an empty\n * cart caught client-side).\n */\n code?: string;\n}\n\ninterface CheckoutApiResponse {\n invoiceId?: string;\n checkoutUrl?: string;\n invoice_id?: string;\n checkout_url?: string;\n uniqid?: string;\n url?: string;\n url_branded?: string;\n rewards?: BuyerRewards | null;\n invoice?: {\n invoiceId?: string;\n checkoutUrl?: string;\n invoice_id?: string;\n checkout_url?: string;\n uniqid?: string;\n url?: string;\n url_branded?: string;\n rewards?: BuyerRewards | null;\n };\n}\n\ninterface NormalizedCheckoutData {\n invoiceId: string;\n checkoutUrl: string;\n rewards: BuyerRewards | null;\n}\n\nconst CHECKOUT_PREFILL_EMAIL_HASH_KEY = 'shoppex_prefill_email';\n\n/**\n * PAYMENT PATH. The single refusal copy for a broken `expectedCart` pin, shared\n * by every entry point that honours the pin so the buyer reads the same\n * sentence whichever one the theme calls. One literal, because two copies drift\n * and the difference would be visible to buyers on the same storefront.\n */\nconst CART_CHANGED_MESSAGE = 'Your cart changed while checkout was starting. Please review it and try again.';\n\n/**\n * PAYMENT PATH. True when the caller pinned a cart and storage no longer holds\n * it — see `CheckoutOptions.expectedCart`. Compared against the exact array the\n * caller is about to bill, which is the only comparison that is conclusive:\n * anything the caller checks itself is one more read BEFORE the read that\n * feeds the request.\n *\n * An omitted pin is not a mismatch. The pin is additive, and a caller that\n * never made the promise is left exactly as it was.\n */\nfunction isExpectedCartMismatch(cart: CartItem[], expectedCart: string | undefined): boolean {\n return expectedCart !== undefined && JSON.stringify(cart) !== expectedCart;\n}\n\nfunction normalizeCoupon(coupon: string | null | undefined): string | null {\n const normalized = coupon?.trim();\n return normalized ? normalized : null;\n}\n\nfunction normalizeEmail(email: string | null | undefined): string | null {\n const normalized = email?.trim();\n return normalized ? normalized : null;\n}\n\nfunction resolveCustomerCheckoutRequestTarget(options: CheckoutOptions): {\n endpoint: string;\n baseUrl?: string;\n} {\n if (\n options.customerCheckoutPath === '/dashboard/api/checkout'\n && typeof window !== 'undefined'\n && typeof window.location?.origin === 'string'\n ) {\n return {\n endpoint: options.customerCheckoutPath,\n baseUrl: window.location.origin,\n };\n }\n\n return { endpoint: '/v1/storefront/invoices/from-cart' };\n}\n\nfunction resolveRequestedCheckoutCurrency(options: CheckoutOptions): string | null {\n return normalizeRequestedCurrency(options.currency)\n ?? getRequestedCurrencyFromLocation()\n ?? normalizeRequestedCurrency(getConfig().currency);\n}\n\nfunction normalizeCheckoutFailureMessage(rawMessage: string | null | undefined): string {\n const message = rawMessage?.trim() ?? '';\n if (!message) {\n return 'Checkout failed. Please try again.';\n }\n\n if (isStaleCartProductError(message)) {\n return 'Your cart is outdated. Please add the products again.';\n }\n\n const httpMatch = message.match(/^HTTP\\s+(\\d{3})(?::\\s*(.*))?$/i);\n if (httpMatch) {\n const status = Number(httpMatch[1]);\n const detail = httpMatch[2]?.trim();\n\n if (detail && detail.length > 0) {\n return `Checkout failed: ${detail}`;\n }\n\n if (status >= 500) {\n return 'Checkout is temporarily unavailable. Please try again.';\n }\n\n if (status === 400) {\n return 'Checkout failed. Please check your details and try again.';\n }\n\n if (status === 401 || status === 403) {\n return 'Checkout is currently unavailable for this request.';\n }\n\n return 'Checkout failed. Please try again.';\n }\n\n if (/^internal server error$/i.test(message)) {\n return 'Checkout is temporarily unavailable. Please try again.';\n }\n\n return message;\n}\n\nfunction isStaleCartProductError(rawMessage: string | null | undefined): boolean {\n const message = rawMessage?.trim().toLowerCase() ?? '';\n if (!message) {\n return false;\n }\n\n return message.includes('product not found')\n || message.includes('product not available')\n || message.includes('products are no longer available')\n || message.includes('outdated product');\n}\n\nfunction validateCheckoutUrl(\n checkoutUrl: string,\n checkoutBaseUrl: string | undefined,\n expectedInvoiceId?: string\n): string | null {\n const expectedBaseUrl = checkoutBaseUrl?.trim();\n if (!expectedBaseUrl) {\n return null;\n }\n\n try {\n const parsedCheckoutUrl = new URL(checkoutUrl);\n const parsedExpectedBaseUrl = new URL(expectedBaseUrl);\n\n if (parsedCheckoutUrl.origin !== parsedExpectedBaseUrl.origin) {\n return null;\n }\n\n const normalizedPath = parsedCheckoutUrl.pathname.replace(/\\/+$/, '');\n const normalizedBasePath = parsedExpectedBaseUrl.pathname.replace(/\\/+$/, '');\n const expectedInvoicePath = `${normalizedBasePath}/invoice/`.replace(/\\/{2,}/g, '/');\n if (!normalizedPath.startsWith(expectedInvoicePath)) {\n return null;\n }\n\n const invoiceIdSegment = normalizedPath.slice(expectedInvoicePath.length);\n if (!invoiceIdSegment || invoiceIdSegment.includes('/')) {\n return null;\n }\n\n if (expectedInvoiceId) {\n const normalizedExpectedInvoiceId = expectedInvoiceId.trim();\n const invoiceIdFromUrl = decodeURIComponent(invoiceIdSegment);\n if (!normalizedExpectedInvoiceId || invoiceIdFromUrl !== normalizedExpectedInvoiceId) {\n return null;\n }\n }\n\n return parsedCheckoutUrl.toString();\n } catch {\n return null;\n }\n}\n\nfunction buildCheckoutUrlFromInvoiceId(\n checkoutBaseUrl: string | undefined,\n invoiceId: string\n): string | null {\n const normalizedBaseUrl = checkoutBaseUrl?.trim();\n if (!normalizedBaseUrl) {\n return null;\n }\n\n try {\n const baseUrl = new URL(normalizedBaseUrl);\n const basePath = baseUrl.pathname.replace(/\\/+$/, '');\n baseUrl.pathname = `${basePath}/invoice/${encodeURIComponent(invoiceId)}`.replace(/\\/{2,}/g, '/');\n baseUrl.search = '';\n baseUrl.hash = '';\n return baseUrl.toString();\n } catch {\n return null;\n }\n}\n\nfunction appendCheckoutUrlOptions(\n checkoutUrl: string,\n options: { email?: string | null; locale?: string },\n): string {\n const normalizedEmail = normalizeEmail(options.email);\n const normalizedLocale = typeof options.locale === 'string' ? options.locale.trim() : '';\n\n if (!normalizedEmail && !normalizedLocale) {\n return checkoutUrl;\n }\n\n try {\n const parsedCheckoutUrl = new URL(checkoutUrl);\n if (normalizedLocale) {\n parsedCheckoutUrl.searchParams.set('locale', normalizedLocale);\n }\n if (normalizedEmail) {\n const hashParams = new URLSearchParams(parsedCheckoutUrl.hash.startsWith('#')\n ? parsedCheckoutUrl.hash.slice(1)\n : parsedCheckoutUrl.hash);\n hashParams.set(CHECKOUT_PREFILL_EMAIL_HASH_KEY, normalizedEmail);\n parsedCheckoutUrl.hash = hashParams.toString();\n }\n return parsedCheckoutUrl.toString();\n } catch {\n return checkoutUrl;\n }\n}\n\nfunction normalizeCheckoutResponse(\n response: CheckoutApiResponse | undefined,\n checkoutBaseUrl: string | undefined\n): NormalizedCheckoutData | null {\n const nestedInvoice = response?.invoice;\n const invoiceId = response?.invoiceId?.trim()\n || response?.invoice_id?.trim()\n || response?.uniqid?.trim()\n || nestedInvoice?.invoiceId?.trim()\n || nestedInvoice?.invoice_id?.trim()\n || nestedInvoice?.uniqid?.trim();\n let checkoutUrl = response?.checkoutUrl?.trim()\n || response?.checkout_url?.trim()\n || response?.url_branded?.trim()\n || response?.url?.trim()\n || nestedInvoice?.checkoutUrl?.trim()\n || nestedInvoice?.checkout_url?.trim()\n || nestedInvoice?.url_branded?.trim()\n || nestedInvoice?.url?.trim();\n\n if (!checkoutUrl && invoiceId && nestedInvoice) {\n checkoutUrl = buildCheckoutUrlFromInvoiceId(checkoutBaseUrl, invoiceId) ?? undefined;\n }\n\n if (!invoiceId || !checkoutUrl) {\n return null;\n }\n\n return {\n invoiceId,\n checkoutUrl,\n rewards: response?.rewards ?? nestedInvoice?.rewards ?? null,\n };\n}\n\nfunction resolveCheckoutOptions(\n couponOrOptions?: string | CheckoutOptions,\n options?: CheckoutOptions\n): CheckoutOptions {\n if (typeof couponOrOptions === 'string') {\n return {\n ...options,\n coupon: couponOrOptions,\n };\n }\n\n return couponOrOptions ?? options ?? {};\n}\n\nfunction normalizeAffiliateCode(options: CheckoutOptions, storedAffiliateCode: string | null): string | null {\n const explicitCode = options.affiliateCode ?? options.referralCode;\n // Tri-state, mirroring `coupon`: an explicit empty string means \"none\" and\n // must suppress the storage re-read. Only `undefined` lets the SDK resolve\n // the code itself — otherwise a referral captured after the quote was\n // rendered would be applied to a total the buyer never saw.\n if (typeof explicitCode === 'string') {\n const normalized = explicitCode.trim().toLowerCase();\n return normalized.length > 0 ? normalized : null;\n }\n\n return storedAffiliateCode?.trim().toLowerCase() ?? getAffiliateCode();\n}\n\nfunction resolveCheckoutCodes(options: CheckoutOptions): {\n coupon: string | null;\n affiliateCode: string | null;\n} {\n const storedCode = getCartCoupon();\n const storedSource = getCartCouponSource();\n const coupon = options.coupon === undefined\n ? (storedSource === 'COUPON' ? storedCode : null)\n : normalizeCoupon(options.coupon);\n const storedAffiliateCode = options.coupon === undefined && storedSource === 'AFFILIATE'\n ? storedCode\n : null;\n\n return {\n coupon,\n affiliateCode: normalizeAffiliateCode(options, storedAffiliateCode),\n };\n}\n\nfunction mapCartItemsForApi(items: CartItem[]) {\n const normalizeVariantIdForApi = (value: string | null | undefined): string | null => {\n const normalized = value?.trim();\n if (!normalized) return null;\n // Themes use \"default\" as a sentinel for \"no variant selected\".\n // Backend expects `null` in that case.\n if (normalized.toLowerCase() === 'default') return null;\n return normalized;\n };\n\n return items.map((item) => ({\n product_id: item.product_id,\n variant_id: normalizeVariantIdForApi(item.variant_id),\n quantity: item.quantity,\n addons: item.addons?.map((a: CartAddon) => ({ id: a.id, quantity: a.quantity ?? 1 })),\n custom_fields: item.custom_fields,\n price_variant_id: item.price_variant_id || null,\n pay_what_you_want_price: item.pay_what_you_want_price,\n }));\n}\n\nexport async function checkout(\n couponOrOptions?: string | CheckoutOptions,\n options?: CheckoutOptions\n): Promise<CheckoutResult> {\n const resolvedOptions = resolveCheckoutOptions(couponOrOptions, options);\n const { autoRedirect = true, email } = resolvedOptions;\n const checkoutCodes = resolveCheckoutCodes(resolvedOptions);\n const normalizedCoupon = checkoutCodes.coupon;\n const normalizedEmail = normalizeEmail(email);\n const normalizedAffiliateCode = checkoutCodes.affiliateCode;\n const requestedCurrency = resolveRequestedCheckoutCurrency(resolvedOptions);\n\n const cart = getCart();\n if (cart.length === 0) {\n return {\n success: false,\n message: 'Cart is empty',\n };\n }\n\n // PAYMENT PATH. The cart the caller approved, compared against the cart this\n // call will actually POST — see `CheckoutOptions.expectedCart`. Refused\n // before the backup and before the request, so a cart that changed under the\n // caller is never billed and nothing is left half-done.\n if (isExpectedCartMismatch(cart, resolvedOptions.expectedCart)) {\n return {\n success: false,\n message: CART_CHANGED_MESSAGE,\n };\n }\n\n createCartBackup();\n\n const config = getConfig();\n const checkoutRequestTarget = resolveCustomerCheckoutRequestTarget(resolvedOptions);\n\n const response = await post<CheckoutApiResponse>(\n checkoutRequestTarget.endpoint,\n {\n shop_slug: config.storeSlug,\n cart: mapCartItemsForApi(cart),\n email: normalizedEmail,\n coupon: normalizedCoupon,\n currency: requestedCurrency,\n affiliate_code: normalizedAffiliateCode,\n // Proof of the total the buyer approved, from the last quoteCart(). Sent\n // automatically so the server can refuse an invoice priced above it.\n // Undefined when nothing has been quoted this session — the endpoint\n // treats that exactly as an older SDK.\n quote_token: getLatestQuoteToken() ?? undefined,\n },\n { retries: 0, baseUrl: checkoutRequestTarget.baseUrl }\n );\n\n if (!response.success || !response.data) {\n if (isStaleCartProductError(response.message)) {\n clearCart();\n }\n return {\n success: false,\n message: normalizeCheckoutFailureMessage(response.message),\n // The server's machine-readable refusal, preserved so callers can react\n // to e.g. `errors.checkout.price_increased_since_quote` without matching\n // localized copy.\n ...(response.code ? { code: response.code } : {}),\n };\n }\n\n const checkoutData = normalizeCheckoutResponse(response.data, config.checkoutBaseUrl);\n if (!checkoutData) {\n return {\n success: false,\n message: 'Failed to create invoice',\n };\n }\n\n const { invoiceId } = checkoutData;\n const safeCheckoutUrl = validateCheckoutUrl(\n checkoutData.checkoutUrl,\n config.checkoutBaseUrl,\n invoiceId\n );\n if (!safeCheckoutUrl) {\n return {\n success: false,\n message: 'Failed to create invoice',\n };\n }\n\n const checkoutUrlWithPrefill = appendCheckoutUrlOptions(safeCheckoutUrl, {\n email: normalizedEmail,\n locale: resolvedOptions.locale ?? config.locale,\n });\n\n if (autoRedirect) {\n if (typeof window !== 'undefined' && window?.location) {\n window.location.href = checkoutUrlWithPrefill;\n clearCart();\n }\n }\n\n return {\n success: true,\n redirectUrl: checkoutUrlWithPrefill,\n invoiceId,\n rewards: checkoutData.rewards,\n };\n}\n\n/**\n * Build checkout URL by creating invoice first.\n * Returns the checkout URL for the created invoice.\n *\n * PAYMENT PATH. \"Build a URL\" names what this returns, not a lighter way to\n * price a cart: it POSTs the same invoice-creating endpoint as `checkout()` and\n * bills whatever storage holds when it reads. It therefore honours\n * `CheckoutOptions.expectedCart` on exactly the same terms — a pinned cart that\n * moved is refused, not invoiced.\n *\n * A refusal throws, like every other refusal on this function: the success\n * shape is a URL string, so there is no in-band value that a caller could\n * mistake for one. The thrown message is the buyer-facing copy, identical to\n * the sentence `checkout()` returns, and callers that already handle the\n * `Cart is empty` throw handle this one unchanged.\n */\nexport async function buildCheckoutUrl(\n couponOrOptions?: string | CheckoutOptions,\n options?: CheckoutOptions\n): Promise<string> {\n const resolvedOptions = resolveCheckoutOptions(couponOrOptions, options);\n const { email } = resolvedOptions;\n const checkoutCodes = resolveCheckoutCodes(resolvedOptions);\n const normalizedCoupon = checkoutCodes.coupon;\n const normalizedEmail = normalizeEmail(email);\n const normalizedAffiliateCode = checkoutCodes.affiliateCode;\n const requestedCurrency = resolveRequestedCheckoutCurrency(resolvedOptions);\n\n const cart = getCart();\n if (cart.length === 0) {\n throw new Error('Cart is empty');\n }\n\n // PAYMENT PATH. Same position `checkout()` puts it in: after the empty-cart\n // check and before anything is created or sent. This path has no cart backup\n // to write, so the request is the first side effect there is — refusing here\n // means a cart that changed under the caller never reaches the endpoint, and\n // the buyer's cart is left exactly as the interfering write left it. It\n // matters most with no quote token in play, because then nothing downstream\n // carries an approved-total ceiling either.\n if (isExpectedCartMismatch(cart, resolvedOptions.expectedCart)) {\n throw new Error(CART_CHANGED_MESSAGE);\n }\n\n const config = getConfig();\n const checkoutRequestTarget = resolveCustomerCheckoutRequestTarget(resolvedOptions);\n\n const response = await post<CheckoutApiResponse>(\n checkoutRequestTarget.endpoint,\n {\n shop_slug: config.storeSlug,\n cart: mapCartItemsForApi(cart),\n email: normalizedEmail,\n coupon: normalizedCoupon,\n currency: requestedCurrency,\n affiliate_code: normalizedAffiliateCode,\n // Same invoice-creating endpoint as `checkout()`, so it carries the same\n // proof of the approved total. \"Build a URL\" describes what this returns\n // to the caller, not a different way to price a cart — omitting the\n // token here left a public path on which the server had nothing to check\n // the invoice against. Same optional semantics: undefined when nothing\n // was quoted this session.\n quote_token: getLatestQuoteToken() ?? undefined,\n },\n { retries: 0, baseUrl: checkoutRequestTarget.baseUrl }\n );\n\n if (!response.success || !response.data) {\n if (isStaleCartProductError(response.message)) {\n clearCart();\n }\n throw new Error(normalizeCheckoutFailureMessage(response.message));\n }\n const checkoutData = normalizeCheckoutResponse(response.data, config.checkoutBaseUrl);\n if (!checkoutData) {\n throw new Error('Failed to create invoice');\n }\n\n const safeCheckoutUrl = validateCheckoutUrl(\n checkoutData.checkoutUrl,\n config.checkoutBaseUrl,\n checkoutData.invoiceId\n );\n if (!safeCheckoutUrl) {\n throw new Error('Failed to create invoice');\n }\n\n return appendCheckoutUrlOptions(safeCheckoutUrl, {\n email: normalizedEmail,\n locale: resolvedOptions.locale ?? config.locale,\n });\n}\n\n/**\n * @deprecated Use buildCheckoutUrl instead.\n * Sync version is no longer supported as invoice creation requires API call.\n */\nexport function buildCheckoutUrlSync(): never {\n throw new Error('buildCheckoutUrlSync is deprecated. Use buildCheckoutUrl (async) instead.');\n}\n","/**\n * Coupons Module\n *\n * Coupon validation before checkout.\n */\n\nimport { post } from '../core/client';\nimport { getShopId } from '../core/config';\nimport { getStore } from './store';\nimport { getCart } from './cart';\nimport type { SDKResponse, CouponValidation, CouponValidationOptions } from '../types';\n\nasync function resolveShopId(): Promise<string | null> {\n const cachedShopId = getShopId();\n if (cachedShopId) {\n return cachedShopId;\n }\n\n const storeResult = await getStore();\n if (!storeResult.success || !storeResult.data?.id) {\n return null;\n }\n\n return storeResult.data.id;\n}\n\nexport async function validateCoupon(\n code: string,\n productOrOptions?: string | CouponValidationOptions\n): Promise<SDKResponse<CouponValidation>> {\n const trimmedCode = code.trim();\n if (!trimmedCode) {\n return {\n success: false,\n message: 'Coupon code is required',\n };\n }\n\n const payload: Record<string, unknown> = {\n code: trimmedCode,\n };\n const productId = typeof productOrOptions === 'string'\n ? productOrOptions\n : productOrOptions?.productId;\n const variantId = typeof productOrOptions === 'string'\n ? undefined\n : productOrOptions?.variantId;\n\n if (variantId && !productId) {\n return {\n success: false,\n message: 'productId is required when variantId is provided',\n };\n }\n\n if (productId) {\n payload.product_id = productId;\n if (variantId) {\n payload.variant_id = variantId;\n }\n } else {\n const cart = getCart();\n if (cart.length === 0) {\n return {\n success: false,\n message: 'Cart is empty',\n };\n }\n\n const shopId = await resolveShopId();\n if (!shopId) {\n return {\n success: false,\n message: 'Failed to resolve store',\n };\n }\n\n payload.cart = JSON.stringify({\n shop_id: shopId,\n products: cart.map((item) => ({\n uniqid: item.product_id,\n quantity: item.quantity,\n variant_id: item.variant_id,\n price_variant_id: item.price_variant_id,\n addons: item.addons?.map((addon) => ({\n id: addon.id,\n quantity: addon.quantity ?? 1,\n })),\n })),\n });\n }\n\n const response = await post<CouponValidation>(\n '/v1/storefront/coupons/check',\n payload\n );\n\n return response;\n}\n","/**\n * Reviews Module\n *\n * Shop-level feedback/reviews.\n * Note: Shoppex has shop-level feedback, not product-level reviews.\n */\n\nimport { get } from '../core/client';\nimport { getConfig } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type { SDKResponse, Feedback, ShopReviewsPage } from '../types';\n\nconst REVIEWS_PAGE_LIMIT = 100;\nconst REVIEWS_CACHE_TTL = 2 * 60 * 1000;\n\nfunction toFiniteNumber(value: unknown): number | null {\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value;\n }\n\n if (typeof value === 'string' && value.trim() !== '') {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : null;\n }\n\n return null;\n}\n\nfunction firstString(...values: unknown[]): string | undefined {\n for (const value of values) {\n if (typeof value === 'string' && value.length > 0) {\n return value;\n }\n }\n\n return undefined;\n}\n\nfunction normalizeFeedback(raw: Feedback, index: number): Feedback {\n const record = raw as Feedback & Record<string, unknown>;\n const rating = toFiniteNumber(record.rating) ?? toFiniteNumber(record.score) ?? 0;\n const comment = firstString(record.comment, record.message);\n const author = firstString(record.author, record.customer_name);\n const createdAt = record.created_at ?? record.createdAt;\n const created_at =\n typeof createdAt === 'number' || typeof createdAt === 'string'\n ? String(createdAt)\n : '';\n const id = firstString(record.id, record.uniqid) ?? `review:${created_at || index}`;\n\n return {\n ...record,\n id,\n rating,\n ...(comment ? { comment } : {}),\n ...(author ? { author } : {}),\n created_at,\n };\n}\n\nexport async function getShopReviewsPage(cursor?: string | null): Promise<SDKResponse<ShopReviewsPage>> {\n const config = getConfig();\n const query = new URLSearchParams();\n query.set('limit', String(REVIEWS_PAGE_LIMIT));\n if (typeof cursor === 'string' && cursor.trim().length > 0) {\n query.set('cursor', cursor);\n }\n const querySuffix = `?${query.toString()}`;\n\n const response = await get<ShopReviewsPage>(\n `${buildEndpoint('/v1/storefront/feedback/shop/:storeSlug', {\n storeSlug: config.storeSlug,\n })}${querySuffix}`,\n {\n cache: {\n key: `reviews:${config.storeSlug}:${cursor ?? 'start'}:${REVIEWS_PAGE_LIMIT}`,\n ttl: REVIEWS_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: {\n ...response.data,\n feedback: response.data.feedback.map(normalizeFeedback),\n },\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function getShopReviews(): Promise<SDKResponse<Feedback[]>> {\n const allFeedback: Feedback[] = [];\n const seenCursors = new Set<string>();\n let cursor: string | null = null;\n\n while (true) {\n const response = await getShopReviewsPage(cursor);\n if (!response.success || !response.data) {\n return {\n success: false,\n message: response.message,\n data: [],\n };\n }\n\n allFeedback.push(...response.data.feedback);\n\n const pagination = response.data.pagination;\n if (!pagination?.has_more || !pagination.next_cursor) {\n break;\n }\n\n if (seenCursors.has(pagination.next_cursor)) {\n break;\n }\n\n seenCursors.add(pagination.next_cursor);\n cursor = pagination.next_cursor;\n }\n\n return {\n success: true,\n data: allFeedback,\n };\n}\n","/**\n * Customer Module\n *\n * Authenticated customer account calls for code-lane storefronts. The edge\n * worker owns the HttpOnly session cookie and derives the shop from the host.\n * This module therefore sends neither a session token nor shop identity.\n */\n\nimport {\n customerPortalDashboardSchema,\n customerPortalInvoiceDetailSchema,\n customerPortalPaginatedInvoicesSchema,\n type CustomerPortalDashboardWire,\n type CustomerPortalInvoiceDetailWire,\n type CustomerPortalPaginatedInvoicesWire,\n} from '@shoppex/contracts';\nimport type { SDKResponse } from '../types';\n\nconst CUSTOMER_API_PREFIX = '/api/customer';\n\ntype CustomerMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';\n\n/**\n * A producer-owned schema for the response payload.\n *\n * Only the endpoints whose shape is defined in `@shoppex/contracts` get one.\n * The rest stay `unknown` on purpose: inventing a type here would assert a wire\n * shape the producer never promised, which is the pattern the retired portal's\n * 544-line hand-written type file demonstrates the cost of.\n */\ninterface CustomerPayloadSchema<T> {\n safeParse(value: unknown): { success: true; data: T } | { success: false };\n}\n\ninterface CustomerRequestOptions<T> {\n method?: CustomerMethod;\n body?: unknown;\n /** Multipart payload. Mutually exclusive with `body`; the browser sets the boundary. */\n formData?: FormData;\n schema?: CustomerPayloadSchema<T>;\n}\n\nexport interface CustomerOrdersQuery {\n page?: number;\n limit?: number;\n /**\n * Invoice status filter, verbatim from the producer's enum. Anything else is\n * answered with a 400 rather than quietly ignored, so pass what the buyer\n * actually chose.\n */\n status?: string;\n /** Partial invoice-id search. The producer trims it to 64 characters. */\n search?: string;\n}\n\ninterface CustomerApiEnvelope {\n status: number;\n data: unknown;\n error?: unknown;\n message?: unknown;\n error_code?: unknown;\n error_params?: unknown;\n}\n\nexport interface CustomerTicketPayload {\n title?: string;\n message: string;\n invoice_id?: string;\n}\n\nexport interface CustomerProfilePatch {\n name: string;\n}\n\nexport interface CustomerSubscriptionCancelOptions {\n cancel_at_period_end?: boolean;\n reason?: string | null;\n}\n\nexport interface CustomerEmailPreferencesPatch {\n global_unsubscribed?: boolean;\n list_subscriptions?: Array<{ list_id: string; subscribed: boolean }>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction narrowEnvelope(value: unknown): CustomerApiEnvelope | null {\n if (!isRecord(value) || typeof value.status !== 'number' || !('data' in value)) {\n return null;\n }\n\n return value as unknown as CustomerApiEnvelope;\n}\n\nfunction readMessage(envelope: CustomerApiEnvelope, response: Response): string {\n if (typeof envelope.error === 'string' && envelope.error.length > 0) {\n return envelope.error;\n }\n\n if (typeof envelope.message === 'string' && envelope.message.length > 0) {\n return envelope.message;\n }\n\n return response.statusText\n ? `HTTP ${response.status}: ${response.statusText}`\n : `HTTP ${response.status}`;\n}\n\nfunction readErrorFields(envelope: CustomerApiEnvelope): Pick<SDKResponse<unknown>, 'code' | 'errorParams'> {\n const code = typeof envelope.error_code === 'string' && envelope.error_code.length > 0\n ? envelope.error_code\n : null;\n\n if (!code) {\n return {};\n }\n\n return {\n code,\n ...(isRecord(envelope.error_params) ? { errorParams: envelope.error_params } : {}),\n };\n}\n\nasync function requestCustomer<T = unknown>(\n path: string,\n options: CustomerRequestOptions<T> = {},\n): Promise<SDKResponse<T>> {\n const method = options.method ?? 'GET';\n const headers: Record<string, string> = {\n Accept: 'application/json',\n };\n\n if (options.body !== undefined) {\n headers['Content-Type'] = 'application/json';\n }\n\n // FormData carries its own multipart boundary in the Content-Type the browser\n // generates; setting the header here would produce a body the server cannot parse.\n const payload = options.formData ?? (options.body !== undefined ? JSON.stringify(options.body) : undefined);\n\n try {\n const response = await fetch(`${CUSTOMER_API_PREFIX}${path}`, {\n method,\n headers,\n body: payload,\n credentials: 'same-origin',\n cache: 'no-store',\n });\n\n if (response.status === 204) {\n return response.ok\n ? { success: true, status: response.status }\n : {\n success: false,\n status: response.status,\n message: readMessage({ status: response.status, data: null }, response),\n };\n }\n\n let rawEnvelope: unknown;\n try {\n rawEnvelope = await response.json();\n } catch {\n return { success: false, status: response.status, message: 'Invalid customer API response' };\n }\n\n const envelope = narrowEnvelope(rawEnvelope);\n if (!envelope) {\n return { success: false, status: response.status, message: 'Invalid customer API response' };\n }\n\n if (!response.ok || envelope.status < 200 || envelope.status >= 300) {\n return {\n success: false,\n // The transport status, not the envelope's: a caller deciding whether\n // the buyer is signed out must not be steered by a body the edge may\n // never have produced.\n status: response.status,\n message: readMessage(envelope, response),\n ...readErrorFields(envelope),\n };\n }\n\n const message = typeof envelope.message === 'string' && envelope.message.length > 0\n ? { message: envelope.message }\n : {};\n\n if (!options.schema) {\n return { success: true, data: envelope.data as T, ...message };\n }\n\n const parsed = options.schema.safeParse(envelope.data);\n if (!parsed.success) {\n // Fail loudly instead of handing back a payload that does not match what\n // the producer promised. A silently reshaped or partially-read response\n // is how a contract drift reaches the buyer's screen as wrong data.\n return { success: false, message: 'Customer API response did not match the expected contract' };\n }\n\n return { success: true, data: parsed.data, ...message };\n } catch (error) {\n return {\n success: false,\n message: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/** One basket line for a QUOTE. `variant_id` is omitted, never null, when a product has no variants. */\nexport interface ResellerOrderItem {\n product_id: string;\n variant_id?: string;\n quantity: number;\n}\n\nexport interface ResellerCatalogQuery {\n search?: string;\n page?: number;\n per_page?: number;\n}\n\nexport interface ResellerOrdersQuery {\n page?: number;\n per_page?: number;\n}\n\nexport function requestOtp(email: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/auth/otp/request', {\n method: 'POST',\n body: { email },\n });\n}\n\n/**\n * The wire field is `otp`, not `code` — `CustomerOtpVerifyBodySchema` in\n * `apps/backend-elysia/src/routes/v1/customer/schemas.ts` requires it under that\n * name, and a `code` body is rejected with 400.\n */\nexport function verifyOtp(email: string, otp: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/auth/otp/verify', {\n method: 'POST',\n body: { email, otp },\n });\n}\n\nexport function logout(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/auth/logout', { method: 'POST' });\n}\n\nexport function me(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/me');\n}\n\nexport function dashboard(): Promise<SDKResponse<CustomerPortalDashboardWire>> {\n return requestCustomer('/dashboard', { schema: customerPortalDashboardSchema });\n}\n\n/**\n * Paginated order history.\n *\n * Page-based, matching the producer: `invoices.routes.ts` reads `page` and\n * `limit` and answers with a `has_more` envelope. A cursor parameter would be\n * ignored upstream and silently return page one forever.\n *\n * `status` and `search` are filtered SERVER-side, which is why they belong\n * here rather than in the caller: `/invoices` is paged, and a filter applied\n * to the page in hand would filter only the rows that page happens to hold.\n * The producer spells the search `q`.\n */\nexport function orders(options: CustomerOrdersQuery = {}): Promise<SDKResponse<CustomerPortalPaginatedInvoicesWire>> {\n const query = new URLSearchParams();\n if (options.page !== undefined) query.set('page', String(options.page));\n if (options.limit !== undefined) query.set('limit', String(options.limit));\n if (options.status) query.set('status', options.status);\n if (options.search) query.set('q', options.search);\n\n const suffix = query.size > 0 ? `?${query.toString()}` : '';\n return requestCustomer(`/invoices${suffix}`, { schema: customerPortalPaginatedInvoicesSchema });\n}\n\nexport function order(id: string): Promise<SDKResponse<CustomerPortalInvoiceDetailWire>> {\n return requestCustomer(`/invoice/${encodeURIComponent(id)}`, {\n schema: customerPortalInvoiceDetailSchema,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Licenses, subscriptions and tickets have NO collection route.\n//\n// Those three lists arrive inside `/dashboard` — `licenses.routes.ts`,\n// `subscriptions.routes.ts` and `tickets.routes.ts` expose per-item routes only.\n// A `GET /licenses` here would 404 on every call, which is what the earlier\n// spelling of this module did.\n// ---------------------------------------------------------------------------\n\nexport function resetLicenseHwid(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/licenses/${encodeURIComponent(uniqid)}/reset-hwid`, {\n method: 'POST',\n body: {},\n });\n}\n\nexport function subscriptionBillingHistory(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/subscriptions/${encodeURIComponent(uniqid)}/billing-history`);\n}\n\nexport function cancelSubscription(\n uniqid: string,\n options: CustomerSubscriptionCancelOptions = {},\n): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/subscriptions/${encodeURIComponent(uniqid)}/cancel`, {\n method: 'POST',\n body: {\n ...(options.cancel_at_period_end !== undefined\n ? { cancel_at_period_end: options.cancel_at_period_end }\n : {}),\n ...(options.reason !== undefined ? { reason: options.reason } : {}),\n },\n });\n}\n\nexport function pauseSubscription(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/subscriptions/${encodeURIComponent(uniqid)}/pause`, {\n method: 'POST',\n body: {},\n });\n}\n\nexport function resumeSubscription(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/subscriptions/${encodeURIComponent(uniqid)}/resume`, {\n method: 'POST',\n body: {},\n });\n}\n\nexport function favorites(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/favorites');\n}\n\n/** Idempotent upstream, and a PUT — `customer-favorites.ts` has no POST route. */\nexport function addFavorite(productUniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/favorites/${encodeURIComponent(productUniqid)}`, { method: 'PUT' });\n}\n\nexport function removeFavorite(productUniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/favorites/${encodeURIComponent(productUniqid)}`, { method: 'DELETE' });\n}\n\nexport function affiliate(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/affiliate');\n}\n\nexport function createTicket(payload: CustomerTicketPayload): Promise<SDKResponse<unknown>> {\n return requestCustomer('/tickets', {\n method: 'POST',\n body: {\n ...(payload.title !== undefined ? { title: payload.title } : {}),\n message: payload.message,\n ...(payload.invoice_id !== undefined ? { invoice_id: payload.invoice_id } : {}),\n },\n });\n}\n\nexport function ticket(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/tickets/${encodeURIComponent(uniqid)}`);\n}\n\nexport function replyToTicket(uniqid: string, message: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/tickets/${encodeURIComponent(uniqid)}/reply`, {\n method: 'POST',\n body: { message },\n });\n}\n\n/**\n * The producer is `POST /v1/customer/profile`, not PATCH.\n *\n * There is no `GET /profile` to pair with it — the buyer's own record comes from\n * `/me` and `/dashboard`.\n */\nexport function updateProfile(patch: CustomerProfilePatch): Promise<SDKResponse<unknown>> {\n return requestCustomer('/profile', {\n method: 'POST',\n body: { name: patch.name },\n });\n}\n\nexport function updateAvatar(file: File): Promise<SDKResponse<unknown>> {\n const form = new FormData();\n form.append('file', file);\n return requestCustomer('/profile/avatar', { method: 'POST', formData: form });\n}\n\nexport function removeAvatar(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/profile/avatar', { method: 'DELETE' });\n}\n\nexport function emailPreferences(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/email-marketing/preferences');\n}\n\nexport function updateEmailPreferences(\n patch: CustomerEmailPreferencesPatch,\n): Promise<SDKResponse<unknown>> {\n return requestCustomer('/email-marketing/preferences', {\n method: 'PATCH',\n body: {\n ...(patch.global_unsubscribed !== undefined\n ? { global_unsubscribed: patch.global_unsubscribed }\n : {}),\n ...(patch.list_subscriptions !== undefined\n ? { list_subscriptions: patch.list_subscriptions }\n : {}),\n },\n });\n}\n\nexport function sessions(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/sessions');\n}\n\nexport function revokeSession(id: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/sessions/${encodeURIComponent(id)}`, { method: 'DELETE' });\n}\n\n/**\n * Ends every session except this one.\n *\n * `others=true` is required, not decorative: `RevokeOtherSessionsQuerySchema`\n * declares it as a literal, so the route answers 400 without it. The selector\n * is explicit on purpose — \"revoke sessions\" with no qualifier is one typo away\n * from signing the buyer out of the device they are holding.\n */\nexport function revokeAllSessions(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/sessions?others=true', { method: 'DELETE' });\n}\n\n// ---------------------------------------------------------------------------\n// Store credit\n//\n// `topup` creates an UNPAID invoice and answers with its hosted-checkout URL.\n// Nothing is credited here: the balance moves when that invoice completes. The\n// shop's enablement toggles, the amount bounds and the check that the credited\n// result still fits under the shop's maximum balance all live in\n// `WalletTopupService`, which is why a storefront may ask for this at all.\n// ---------------------------------------------------------------------------\n\n/** Whether the shop takes top-ups, between which amounts, and its bonus teaser. */\nexport function walletTopupQuote(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/wallet/topup-quote');\n}\n\n/**\n * Starts a top-up. `amount` is a decimal string with at most two places — the\n * producer's schema rejects anything else rather than rounding it.\n */\nexport function walletTopup(amount: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/wallet/topup', { method: 'POST', body: { amount } });\n}\n\n// ---------------------------------------------------------------------------\n// Wholesale (reseller program)\n//\n// A second program on the same account: its own way in, its own prepaid\n// balance, its own prices. Every route re-checks \"program enabled AND this\n// reseller is ACTIVE\" server-side, so nothing a storefront caches can widen\n// what a buyer may do here.\n//\n// Two writes are deliberately absent, and adding them back would be adding\n// methods that answer 404: the storefront worker refuses them. On a code\n// storefront the JavaScript on this origin is the MERCHANT's and it holds the\n// buyer's cookie, so the edge's same-origin check proves that script sent the\n// request, never that the buyer wanted it.\n// - placing a wholesale order debits the buyer's prepaid balance; a purchase\n// needs a boundary the merchant does not control\n// - minting an API key hands back a plaintext credential that keeps\n// authorizing orders after the session ends\n// Pricing a basket stays, because it writes nothing.\n// ---------------------------------------------------------------------------\n\n/** The program's state and this buyer's place in it. Null reseller means not enrolled. */\nexport function reseller(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller');\n}\n\n/** `APPLICATION` mode. The note is optional unless the shop requires one. */\nexport function applyForReseller(note?: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/apply', {\n method: 'POST',\n body: note === undefined ? {} : { note },\n });\n}\n\n/** `OPEN` mode: no application, the buyer is a reseller when they say so. */\nexport function enrollAsReseller(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/enroll', { method: 'POST', body: {} });\n}\n\n/** `MANUAL` mode: the merchant invited this buyer and gave them a token. */\nexport function acceptResellerInvite(token: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/accept-invite', { method: 'POST', body: { token } });\n}\n\n/** The buyer's own tier prices. Page-based, like the order history. */\nexport function resellerCatalog(options: ResellerCatalogQuery = {}): Promise<SDKResponse<unknown>> {\n const query = new URLSearchParams();\n if (options.search !== undefined) query.set('search', options.search);\n if (options.page !== undefined) query.set('page', String(options.page));\n if (options.per_page !== undefined) query.set('per_page', String(options.per_page));\n\n const suffix = query.size > 0 ? `?${query.toString()}` : '';\n return requestCustomer(`/reseller/catalog${suffix}`);\n}\n\n/**\n * Prices a basket and writes nothing.\n *\n * The volume discount cannot be derived from the catalog — it only reports that\n * one exists — so a storefront that adds up unit prices itself shows a total\n * the shop will not charge. This is the number to display.\n */\nexport function quoteResellerOrder(items: ResellerOrderItem[]): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/orders/quote', { method: 'POST', body: { items } });\n}\n\nexport function resellerOrders(options: ResellerOrdersQuery = {}): Promise<SDKResponse<unknown>> {\n const query = new URLSearchParams();\n if (options.page !== undefined) query.set('page', String(options.page));\n if (options.per_page !== undefined) query.set('per_page', String(options.per_page));\n\n const suffix = query.size > 0 ? `?${query.toString()}` : '';\n return requestCustomer(`/reseller/orders${suffix}`);\n}\n\n/** One order with its lines, delivery state and delivered serials. */\nexport function resellerOrder(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/reseller/orders/${encodeURIComponent(uniqid)}`);\n}\n\n/** The prepaid balance the wholesale orders are paid from. */\nexport function resellerWallet(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/wallet');\n}\n\n/**\n * Top-up bounds in the WHOLESALE context.\n *\n * Not interchangeable with `walletTopupQuote`: the retail one advertises bonus\n * tiers the rewards pipeline never grants on wholesale float, and its `enabled`\n * flag mirrors the retail wallet toggles while the wholesale gate is the\n * reseller program itself.\n */\nexport function resellerTopupQuote(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/wallet/topup-quote');\n}\n\n/** Creates an UNPAID invoice for wholesale float and answers with its URL. */\nexport function resellerTopup(amount: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/wallet/topup', { method: 'POST', body: { amount } });\n}\n\nexport function resellerApiKeys(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/api-keys');\n}\n\nexport function revokeResellerApiKey(id: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/reseller/api-keys/${encodeURIComponent(id)}`, { method: 'DELETE' });\n}\n","import { getStorefront } from './store.js';\nimport { isInitialized } from '../core/config.js';\nimport {\n searchMergedStorefrontCatalog,\n searchMergedStorefrontCatalogItems,\n type StorefrontCatalogSearchItem,\n} from '../utils/storefront-search.js';\nimport type { SDKResponse, Product } from '../types/index.js';\n\nexport interface SearchOptions {\n hideOutOfStock?: boolean;\n maxResults?: number;\n}\n\nexport type { StorefrontCatalogSearchItem };\n\nexport async function searchCatalogItems(\n query: string,\n options?: SearchOptions,\n): Promise<SDKResponse<StorefrontCatalogSearchItem[]>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n\n const trimmed = query.trim();\n if (!trimmed) {\n return { success: true, data: [] };\n }\n\n const storefront = await getStorefront();\n if (!storefront.success || !storefront.data) {\n return {\n success: false,\n message: storefront.message ?? 'Failed to fetch storefront catalog',\n };\n }\n\n const results = searchMergedStorefrontCatalogItems(\n storefront.data.products ?? [],\n storefront.data.groups ?? [],\n trimmed,\n {\n hideOutOfStock: options?.hideOutOfStock,\n maxResults: options?.maxResults,\n },\n );\n\n return { success: true, data: results };\n}\n\nexport async function searchProducts(\n query: string,\n options?: SearchOptions,\n): Promise<SDKResponse<Product[]>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n\n const trimmed = query.trim();\n if (!trimmed) {\n return { success: true, data: [] };\n }\n\n const storefront = await getStorefront();\n if (!storefront.success || !storefront.data) {\n return {\n success: false,\n message: storefront.message ?? 'Failed to fetch storefront catalog',\n };\n }\n\n const results = searchMergedStorefrontCatalog(\n storefront.data.products ?? [],\n storefront.data.groups ?? [],\n trimmed,\n {\n hideOutOfStock: options?.hideOutOfStock,\n maxResults: options?.maxResults,\n },\n );\n\n return { success: true, data: results };\n}\n","/**\n * Invoices Module\n *\n * Invoice status checking after payment.\n */\n\nimport { get } from '../core/client';\nimport { buildEndpoint } from '../core/endpoint';\nimport type { SDKResponse, Invoice } from '../types';\n\nfunction normalizeInvoiceId(invoiceId: string): string | null {\n const normalized = invoiceId.trim();\n if (!normalized) {\n return null;\n }\n return normalized;\n}\n\nexport async function getInvoice(\n invoiceId: string\n): Promise<SDKResponse<Invoice>> {\n const normalizedInvoiceId = normalizeInvoiceId(invoiceId);\n if (!normalizedInvoiceId) {\n return {\n success: false,\n message: 'Invoice ID is required',\n };\n }\n\n const response = await get<{ invoice: Invoice }>(\n buildEndpoint('/v1/storefront/invoices/unique/:invoiceId', {\n invoiceId: normalizedInvoiceId,\n })\n );\n if (!response.success) {\n return {\n success: false,\n message: response.message,\n };\n }\n\n if (!response.data?.invoice) {\n return {\n success: false,\n message: 'Invalid invoice response',\n };\n }\n\n return {\n success: true,\n data: response.data.invoice,\n };\n}\n\nexport async function getInvoiceStatus(\n invoiceId: string\n): Promise<SDKResponse<{ status: string }>> {\n const normalizedInvoiceId = normalizeInvoiceId(invoiceId);\n if (!normalizedInvoiceId) {\n return {\n success: false,\n message: 'Invoice ID is required',\n };\n }\n\n const response = await get<{ invoice: { status: string } }>(\n buildEndpoint('/v1/storefront/invoices/status/:invoiceId', {\n invoiceId: normalizedInvoiceId,\n })\n );\n if (!response.success) {\n return {\n success: false,\n message: response.message,\n };\n }\n\n if (!response.data?.invoice?.status) {\n return {\n success: false,\n message: 'Invalid invoice status response',\n };\n }\n\n return {\n success: true,\n data: { status: response.data.invoice.status },\n };\n}\n","/**\n * Pages Module\n *\n * API methods for public pages.\n */\n\nimport { get } from '../core/client';\nimport { getConfig } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type { SDKResponse, Page } from '../types';\n\ninterface PagesResponse {\n pages: Page[];\n}\n\ninterface PageResponse {\n page: Page;\n}\n\nconst PAGES_CACHE_TTL = 5 * 60 * 1000;\n\n/**\n * Get all public pages for the store\n */\nexport async function getPages(): Promise<SDKResponse<Page[]>> {\n const config = getConfig();\n const response = await get<PagesResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/pages', {\n storeSlug: config.storeSlug,\n }),\n {\n cache: {\n key: `pages:${config.storeSlug}`,\n ttl: PAGES_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.pages,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\n/**\n * Get a public page by slug\n */\nexport async function getPage(slug: string): Promise<SDKResponse<Page>> {\n const config = getConfig();\n const response = await get<PageResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/pages/:slug', {\n storeSlug: config.storeSlug,\n slug,\n }),\n {\n cache: {\n key: `page:${config.storeSlug}:${slug}`,\n ttl: PAGES_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.page,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n","/**\n * Navigation Module\n *\n * API methods for menus and navigation.\n */\n\nimport { get } from '../core/client';\nimport { getConfig } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type { SDKResponse, Menu } from '../types';\nimport type { NavigationMenuSlot } from '@shoppex/contracts/navigation';\nimport { getNavigationMenuTitles } from '@shoppex/contracts/navigation';\n\ninterface MenusResponse {\n menus: Menu[];\n}\n\ninterface MenuResponse {\n menu: Menu;\n}\n\nconst NAVIGATION_CACHE_TTL = 5 * 60 * 1000;\n\n/**\n * Get all menus for the store\n */\nexport async function getMenus(): Promise<SDKResponse<Menu[]>> {\n const config = getConfig();\n const response = await get<MenusResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/menus', {\n storeSlug: config.storeSlug,\n }),\n {\n cache: {\n key: `menus:${config.storeSlug}`,\n ttl: NAVIGATION_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.menus,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\n/**\n * Get a menu by its exact title.\n */\nexport async function getMenuByTitle(title: string): Promise<SDKResponse<Menu>> {\n const config = getConfig();\n const response = await get<MenuResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/menus/:title', {\n storeSlug: config.storeSlug,\n title,\n }),\n {\n cache: {\n key: `menu:${config.storeSlug}:${title}`,\n ttl: NAVIGATION_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.menu,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\n/**\n * Get a menu by its exact title.\n */\nexport async function getMenu(title: string): Promise<SDKResponse<Menu>> {\n return getMenuByTitle(title);\n}\n\n/**\n * Get a menu by canonical slot. The backend resolves legacy menu titles too.\n */\nexport async function getMenuBySlot(slot: NavigationMenuSlot): Promise<SDKResponse<Menu>> {\n const config = getConfig();\n const response = await get<MenuResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/menus/:title', {\n storeSlug: config.storeSlug,\n title: slot,\n }),\n {\n cache: {\n key: `menu-slot:${config.storeSlug}:${slot}`,\n ttl: NAVIGATION_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.menu,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport function getMenuSlotTitles(slot: NavigationMenuSlot): string[] {\n return getNavigationMenuTitles(slot);\n}\n","/**\n * UTM attribution for storefront page views.\n *\n * Campaign parameters only appear on the landing URL, but a visitor usually\n * browses several pages before doing anything interesting. Without persistence\n * every page after the first would be attributed to \"direct\" and the numbers\n * would understate every campaign.\n *\n * Last-touch: a fresh set of parameters replaces the stored one, matching what\n * merchants expect from analytics tools — the most recent campaign gets credit.\n * Navigating without parameters keeps whatever was stored.\n */\n\nconst STORAGE_PREFIX = 'shoppex:utm:';\nconst TTL_MS = 30 * 24 * 60 * 60 * 1000;\n\nconst UTM_KEYS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'] as const;\n\ntype UtmKey = (typeof UTM_KEYS)[number];\n\nexport type UtmParameters = Partial<Record<UtmKey, string>>;\n\ninterface StoredAttribution {\n utm: UtmParameters;\n /** Epoch ms of the last touch, used for TTL expiry. */\n at: number;\n}\n\n/** Values are merchant-supplied and land in a text column; keep them bounded. */\nconst MAX_VALUE_LENGTH = 255;\n\nfunction readFromUrl(search: string): UtmParameters {\n let params: URLSearchParams;\n try {\n params = new URLSearchParams(search);\n } catch {\n return {};\n }\n\n const utm: UtmParameters = {};\n for (const key of UTM_KEYS) {\n const value = params.get(key)?.trim();\n if (value) {\n utm[key] = value.slice(0, MAX_VALUE_LENGTH);\n }\n }\n return utm;\n}\n\nfunction storageKey(storeSlug: string): string {\n return `${STORAGE_PREFIX}${storeSlug}`;\n}\n\nfunction readStored(storeSlug: string): UtmParameters {\n try {\n const raw = window.localStorage.getItem(storageKey(storeSlug));\n if (!raw) return {};\n\n const parsed = JSON.parse(raw) as StoredAttribution;\n if (!parsed || typeof parsed.at !== 'number' || typeof parsed.utm !== 'object') return {};\n if (Date.now() - parsed.at > TTL_MS) {\n window.localStorage.removeItem(storageKey(storeSlug));\n return {};\n }\n\n const utm: UtmParameters = {};\n for (const key of UTM_KEYS) {\n const value = parsed.utm?.[key];\n if (typeof value === 'string' && value.length > 0) {\n utm[key] = value.slice(0, MAX_VALUE_LENGTH);\n }\n }\n return utm;\n } catch {\n // Private mode, quota errors, corrupt JSON — attribution is best-effort and\n // must never break a page view.\n return {};\n }\n}\n\nfunction writeStored(storeSlug: string, utm: UtmParameters): void {\n try {\n const payload: StoredAttribution = { utm, at: Date.now() };\n window.localStorage.setItem(storageKey(storeSlug), JSON.stringify(payload));\n } catch {\n // Ignore: the current page view still reports the parameters it just read.\n }\n}\n\n/**\n * Resolves the UTM parameters to report for the current page view.\n *\n * Reads the current URL first; when it carries any campaign parameter that set\n * wins and is persisted. Otherwise the stored set is returned unchanged.\n *\n * @returns the parameters, or undefined when there is nothing to report\n */\nexport function resolveUtmParameters(storeSlug: string): UtmParameters | undefined {\n if (typeof window === 'undefined' || typeof window.location === 'undefined') {\n return undefined;\n }\n\n const fromUrl = readFromUrl(window.location.search);\n if (Object.keys(fromUrl).length > 0) {\n writeStored(storeSlug, fromUrl);\n return fromUrl;\n }\n\n const stored = readStored(storeSlug);\n return Object.keys(stored).length > 0 ? stored : undefined;\n}\n","import { isInitialized, getConfig } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport { getStorefrontConnectionId } from '../core/telemetry';\nimport { resolveUtmParameters } from '../core/attribution';\n\nexport async function trackPageView(cartValue?: number, itemCount?: number): Promise<void> {\n if (!isInitialized()) return;\n if (typeof document === 'undefined') return;\n\n const config = getConfig();\n const connectionId = getStorefrontConnectionId(config.storeSlug);\n\n try {\n const endpoint = buildEndpoint('/v1/storefront/shops/:storeSlug/ping', {\n storeSlug: config.storeSlug,\n });\n await fetch(`${config.apiBaseUrl}${endpoint}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n referer: document.referrer || undefined,\n cart_value: cartValue ?? undefined,\n item_count: itemCount ?? undefined,\n connection_id: connectionId ?? undefined,\n utm: resolveUtmParameters(config.storeSlug),\n }),\n });\n } catch {\n // Intentionally silent - analytics should never block the user experience\n }\n}\n","import { get, post } from '../core/client';\nimport { getConfig, getShopId, isInitialized } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport { getStorefrontConnectionId } from '../core/telemetry';\nimport { resolveUtmParameters } from '../core/attribution';\nimport type { SDKResponse, StorefrontOnlineUsers, StorefrontRecentSales } from '../types';\n\n/**\n * Anonymized recent-sales feed for storefront social proof (product title +\n * relative age only — never buyer identity). Empty items when the shop has no\n * recent completed orders.\n */\nexport async function getStorefrontRecentSales(): Promise<SDKResponse<StorefrontRecentSales>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n\n const config = getConfig();\n const shopId = getShopId();\n const endpoint = shopId\n ? buildEndpoint('/v1/storefront/shops/id/:id/recent-sales', { id: shopId })\n : buildEndpoint('/v1/storefront/shops/:storeSlug/recent-sales', {\n storeSlug: config.storeSlug,\n });\n\n return get<StorefrontRecentSales>(endpoint, {\n cache: false,\n retries: 0,\n timeout: 5000,\n });\n}\n\nexport async function getStorefrontOnlineUsers(): Promise<SDKResponse<StorefrontOnlineUsers>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n\n const config = getConfig();\n const shopId = getShopId();\n const endpoint = shopId\n ? buildEndpoint('/v1/storefront/shops/id/:id/online-users', { id: shopId })\n : buildEndpoint('/v1/storefront/shops/:storeSlug/online-users', {\n storeSlug: config.storeSlug,\n });\n\n return get<StorefrontOnlineUsers>(endpoint, {\n cache: false,\n retries: 0,\n timeout: 5000,\n });\n}\n\nexport async function touchStorefrontPresence(): Promise<SDKResponse<{ pong: string }>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n if (typeof document === 'undefined') {\n return { success: false, message: 'Document is not available' };\n }\n\n const config = getConfig();\n const shopId = getShopId();\n const endpoint = shopId\n ? buildEndpoint('/v1/storefront/shops/id/:id/ping', { id: shopId })\n : buildEndpoint('/v1/storefront/shops/:storeSlug/ping', {\n storeSlug: config.storeSlug,\n });\n\n return post<{ pong: string }>(\n endpoint,\n {\n referer: document.referrer || undefined,\n connection_id: getStorefrontConnectionId(config.storeSlug) ?? undefined,\n utm: resolveUtmParameters(config.storeSlug),\n },\n {\n retries: 0,\n timeout: 5000,\n },\n );\n}\n","/**\n * Formatting Utilities\n */\n\nimport { getConfig } from '../core/config';\nimport { CATALOG_UNIT_PRICE_FORMAT_OPTIONS } from '@shoppex/contracts/catalog-unit-price';\n\nexport function createFormatter(\n currency?: string,\n locale?: string\n): Intl.NumberFormat {\n const config = getConfig();\n\n return new Intl.NumberFormat(locale ?? config.locale ?? 'en-US', {\n style: 'currency',\n currency: currency ?? config.currency ?? 'USD',\n ...CATALOG_UNIT_PRICE_FORMAT_OPTIONS,\n });\n}\n\nexport function formatPrice(\n amount: number | string,\n currency?: string,\n locale?: string\n): string {\n const numericAmount = typeof amount === 'string' ? parseFloat(amount) : amount;\n if (Number.isNaN(numericAmount)) {\n return createFormatter(currency, locale).format(0);\n }\n return createFormatter(currency, locale).format(numericAmount);\n}\n","import type { ThemeConfig, ResolvedThemeSettings } from '../types/theme-config';\nimport { get } from '../core/client';\nimport { buildEndpoint } from '../core/endpoint';\n\ntype JsonRecord = Record<string, unknown>;\n\nexport interface PublishedBuilderSettings {\n version: number;\n revision: number;\n theme: {\n content: JsonRecord;\n layout: JsonRecord;\n style_slots: JsonRecord;\n pages?: unknown[];\n terms?: JsonRecord;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\nexport interface PublishedThemeSettingsPayload {\n settings: ResolvedThemeSettings;\n builder_settings: PublishedBuilderSettings | null;\n content: JsonRecord;\n style_slots: JsonRecord;\n}\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction normalizePublishedBuilderSettings(value: unknown): PublishedBuilderSettings | null {\n if (!isRecord(value) || !isRecord(value.theme)) {\n return null;\n }\n\n return {\n ...value,\n version: typeof value.version === 'number' ? value.version : 0,\n revision: typeof value.revision === 'number' ? value.revision : 0,\n theme: {\n ...value.theme,\n content: isRecord(value.theme.content) ? value.theme.content : {},\n layout: isRecord(value.theme.layout) ? value.theme.layout : {},\n style_slots: isRecord(value.theme.style_slots) ? value.theme.style_slots : {},\n ...(Array.isArray(value.theme.pages) ? { pages: value.theme.pages } : {}),\n ...(isRecord(value.theme.terms) ? { terms: value.theme.terms } : {}),\n },\n };\n}\n\nfunction normalizePublishedThemeSettingsPayload(value: unknown): PublishedThemeSettingsPayload | null {\n if (!isRecord(value)) {\n return null;\n }\n\n return {\n settings: isRecord(value.settings) ? value.settings as ResolvedThemeSettings : {},\n builder_settings: normalizePublishedBuilderSettings(value.builder_settings),\n content: isRecord(value.content) ? value.content : {},\n style_slots: isRecord(value.style_slots) ? value.style_slots : {},\n };\n}\n\nexport async function fetchPublishedBuilderSettings(\n shopSlug: string\n): Promise<PublishedThemeSettingsPayload | null> {\n const result = await get<PublishedThemeSettingsPayload>(\n buildEndpoint('/v1/storefront/themes/builder/published/:shopSlug', { shopSlug })\n );\n\n return result.success && result.data ? normalizePublishedThemeSettingsPayload(result.data) : null;\n}\n\nexport async function fetchPublishedThemeSettings(\n shopSlug: string\n): Promise<ResolvedThemeSettings | null> {\n const payload = await fetchPublishedBuilderSettings(shopSlug);\n return payload ? payload.settings : null;\n}\n\nexport function resolveDefaults(config: ThemeConfig): ResolvedThemeSettings {\n const resolved: ResolvedThemeSettings = {};\n for (const [category, fields] of Object.entries(config.settings)) {\n resolved[category] = {};\n for (const [key, field] of Object.entries(fields)) {\n resolved[category][key] = field.default;\n }\n }\n return resolved;\n}\n\nexport function mergeSettings(\n defaults: ResolvedThemeSettings,\n overrides: Partial<ResolvedThemeSettings>\n): ResolvedThemeSettings {\n const merged = { ...defaults };\n for (const [category, fields] of Object.entries(overrides)) {\n if (fields) {\n merged[category] = { ...merged[category], ...fields };\n }\n }\n return merged;\n}\n","/**\n * Shoppex Storefront SDK\n *\n * Usage:\n * ```html\n * <script src=\"https://cdn.shoppex.io/sdk/v1.0/shoppex.umd.js\"></script>\n * <script>\n * shoppex.init('my-store');\n *\n * shoppex.getStore().then(store => console.log(store));\n * shoppex.addToCart('product-id', 'variant-id', 2);\n * shoppex.checkout();\n * </script>\n * ```\n */\n\nimport { initConfig, isInitialized, getConfig } from './core/config';\nimport { getTypedClient } from './core/typed-client';\nimport type { ShoppexInitOptions } from './types';\n\n// Re-export types\nexport * from './types';\nexport * from './core/errors';\nexport {\n buildStorefrontCustomFieldPayload,\n isStorefrontCheckboxCustomFieldValueChecked,\n normalizeStorefrontCustomFields,\n validateStorefrontCustomFieldValue,\n} from './utils/storefront-custom-fields';\nexport type { StorefrontCustomField } from './utils/storefront-custom-fields';\nexport {\n isProductInStock,\n isProductOutOfStock,\n isVariantOutOfStock,\n resolveDisplayStock,\n resolveVariantStockValue,\n} from './utils/storefront-stock';\nexport {\n buildStorefrontProductLookup,\n getMergedStorefrontProducts,\n getStorefrontGroupProducts,\n} from './utils/storefront-catalog';\nexport {\n stripHtmlFromText,\n normalizeSearchQuery,\n collectProductSearchHaystack,\n productMatchesSearchQuery,\n groupMatchesSearchQuery,\n filterProductsBySearchQuery,\n searchMergedStorefrontCatalog,\n searchMergedStorefrontCatalogItems,\n} from './utils/storefront-search';\nexport type { StorefrontSearchFilterOptions, StorefrontCatalogSearchItem } from './utils/storefront-search';\nexport {\n buildStorefrontContactMessage,\n resolveStorefrontApiBaseUrl,\n resolveStorefrontSocialLinks,\n submitStorefrontContactTicket,\n} from './utils/storefront-contact';\nexport type {\n StorefrontContactTicketInput,\n StorefrontContactTicketResult,\n StorefrontSocialLinks,\n} from './utils/storefront-contact';\nexport type {\n BlockDefinition,\n BlockInstance,\n PageLayout,\n ThemeConfig,\n ThemeBlockManifest,\n SettingField,\n SectionDefinition,\n ResolvedThemeSettings,\n} from './types/theme-config';\nexport type { PublishedBuilderSettings, PublishedThemeSettingsPayload } from './modules/theme';\nexport type { NavigationMenuSlot } from '@shoppex/contracts/navigation';\nexport {\n CATALOG_UNIT_PRICE_DECIMAL_PLACES,\n CATALOG_UNIT_PRICE_FORMAT_OPTIONS,\n PAYABLE_AMOUNT_DECIMAL_PLACES,\n roundPayableAmount,\n} from '@shoppex/contracts/catalog-unit-price';\n\n// Store module\nimport {\n getStore,\n getStorefront,\n getStoreLogoUrl,\n getStoreBannerUrl,\n resolveStoreByDomain,\n} from './modules/store';\n\n// Products module\nimport { getProducts, getProduct, getCategories, getStorefrontProductsPage } from './modules/products';\n\n// Cart module\nimport {\n getCart,\n getCartItemCount,\n getCartCoupon,\n getCartCouponSource,\n setCartCoupon,\n clearCartCoupon,\n addToCart,\n setCartItem,\n updateCartItem,\n removeFromCart,\n clearCart,\n createCartBackup,\n restoreCartFromBackup,\n mergeBaskets,\n moveBasketItem,\n getCartStats,\n validateCartIntegrity,\n quoteCart,\n resolveCartLineId,\n} from './modules/cart';\n// resolveCartLineId is re-exported on the default shoppex object below (not only type-only).\nexport { computeCartLineId, ensureCartLineId } from './utils/cart-line-id';\nexport type { CartLineIdentityInput } from './utils/cart-line-id';\n\n// Checkout module\nimport { checkout, buildCheckoutUrl, buildCheckoutUrlSync } from './modules/checkout';\nexport type { CheckoutOptions, CheckoutResult } from './modules/checkout';\nexport type { SearchOptions } from './modules/search';\n\n// Affiliate module\nimport {\n applyAffiliateCode,\n captureAffiliateFromUrl,\n getAffiliateCode,\n setAffiliateCode,\n clearAffiliateCode,\n validateAffiliateCode,\n} from './modules/affiliates';\n\n// Coupons module\nimport { validateCoupon } from './modules/coupons';\n\n// Reviews module\nimport { getShopReviews, getShopReviewsPage } from './modules/reviews';\nexport { getShopReviewsPage } from './modules/reviews';\n\n// Customer module\nimport {\n requestOtp,\n verifyOtp,\n logout,\n me,\n dashboard,\n orders,\n order,\n resetLicenseHwid,\n subscriptionBillingHistory,\n cancelSubscription,\n pauseSubscription,\n resumeSubscription,\n favorites,\n addFavorite,\n removeFavorite,\n affiliate,\n createTicket,\n ticket,\n replyToTicket,\n updateProfile,\n updateAvatar,\n removeAvatar,\n emailPreferences,\n updateEmailPreferences,\n sessions,\n revokeSession,\n revokeAllSessions,\n walletTopupQuote,\n walletTopup,\n reseller,\n applyForReseller,\n enrollAsReseller,\n acceptResellerInvite,\n resellerCatalog,\n quoteResellerOrder,\n resellerOrders,\n resellerOrder,\n resellerWallet,\n resellerTopupQuote,\n resellerTopup,\n resellerApiKeys,\n revokeResellerApiKey,\n} from './modules/customer';\nexport {\n requestOtp,\n verifyOtp,\n logout,\n me,\n dashboard,\n orders,\n order,\n resetLicenseHwid,\n subscriptionBillingHistory,\n cancelSubscription,\n pauseSubscription,\n resumeSubscription,\n favorites,\n addFavorite,\n removeFavorite,\n affiliate,\n createTicket,\n ticket,\n replyToTicket,\n updateProfile,\n updateAvatar,\n removeAvatar,\n emailPreferences,\n updateEmailPreferences,\n sessions,\n revokeSession,\n revokeAllSessions,\n walletTopupQuote,\n walletTopup,\n reseller,\n applyForReseller,\n enrollAsReseller,\n acceptResellerInvite,\n resellerCatalog,\n quoteResellerOrder,\n resellerOrders,\n resellerOrder,\n resellerWallet,\n resellerTopupQuote,\n resellerTopup,\n resellerApiKeys,\n revokeResellerApiKey,\n} from './modules/customer';\nexport type {\n CustomerTicketPayload,\n CustomerProfilePatch,\n CustomerSubscriptionCancelOptions,\n CustomerEmailPreferencesPatch,\n ResellerOrderItem,\n ResellerCatalogQuery,\n ResellerOrdersQuery,\n} from './modules/customer';\n\n// Search module\nimport { searchProducts, searchCatalogItems } from './modules/search';\n\n// Invoices module\nimport { getInvoice, getInvoiceStatus } from './modules/invoices';\n\n// Pages module\nimport { getPages, getPage } from './modules/pages';\n\n// Navigation module\nimport { getMenus, getMenu, getMenuBySlot, getMenuByTitle, getMenuSlotTitles } from './modules/navigation';\n\n// Analytics module\nimport { trackPageView } from './modules/analytics';\nimport { getStorefrontOnlineUsers, getStorefrontRecentSales, touchStorefrontPresence } from './modules/presence';\n\n// Format utilities\nimport { createFormatter, formatPrice } from './utils/format';\nimport { clearCache, invalidateCache, getCacheStats } from './core/cache';\nimport { fetchPublishedBuilderSettings, fetchPublishedThemeSettings, resolveDefaults, mergeSettings } from './modules/theme';\n\nexport { fetchPublishedBuilderSettings, fetchPublishedThemeSettings, resolveDefaults, mergeSettings } from './modules/theme';\nexport { trackPageView } from './modules/analytics';\nexport { getStorefrontOnlineUsers, getStorefrontRecentSales, touchStorefrontPresence } from './modules/presence';\nexport { getMenus, getMenu, getMenuBySlot, getMenuByTitle, getMenuSlotTitles } from './modules/navigation';\n\n/**\n * Initialize the SDK with a store slug\n */\nfunction init(storeSlug: string, options?: ShoppexInitOptions): void;\nfunction init(options: ShoppexInitOptions & { storeId: string }): void;\nfunction init(\n storeSlugOrOptions: string | (ShoppexInitOptions & { storeId: string }),\n options?: ShoppexInitOptions\n): void {\n if (typeof storeSlugOrOptions === 'string') {\n initConfig(storeSlugOrOptions, options);\n } else {\n initConfig(storeSlugOrOptions.storeId, storeSlugOrOptions);\n }\n}\n\n/**\n * Shoppex SDK instance\n */\nexport const shoppex = {\n // Initialization\n init,\n isInitialized,\n getConfig,\n\n // Typed OpenAPI client — drop to this when you need an endpoint the\n // high-level modules below do not cover yet.\n client: getTypedClient,\n\n // Store\n getStore,\n getStorefront,\n getStoreLogoUrl,\n getStoreBannerUrl,\n resolveStoreByDomain,\n\n // Products\n getProducts,\n getStorefrontProductsPage,\n getProduct,\n getCategories,\n\n // Cart\n getCart,\n getCartItemCount,\n getCartCoupon,\n getCartCouponSource,\n setCartCoupon,\n clearCartCoupon,\n addToCart,\n setCartItem,\n updateCartItem,\n removeFromCart,\n clearCart,\n createCartBackup,\n restoreCartFromBackup,\n mergeBaskets,\n moveBasketItem,\n getCartStats,\n validateCartIntegrity,\n quoteCart,\n resolveCartLineId,\n\n // Checkout\n checkout,\n buildCheckoutUrl,\n buildCheckoutUrlSync,\n\n // Affiliates\n captureAffiliateFromUrl,\n validateAffiliateCode,\n applyAffiliateCode,\n getAffiliateCode,\n setAffiliateCode,\n clearAffiliateCode,\n\n // Coupons\n validateCoupon,\n\n // Reviews\n getShopReviews,\n getShopReviewsPage,\n\n // Customer account\n requestOtp,\n verifyOtp,\n logout,\n me,\n dashboard,\n orders,\n order,\n resetLicenseHwid,\n subscriptionBillingHistory,\n cancelSubscription,\n pauseSubscription,\n resumeSubscription,\n favorites,\n addFavorite,\n removeFavorite,\n affiliate,\n createTicket,\n ticket,\n replyToTicket,\n updateProfile,\n updateAvatar,\n removeAvatar,\n emailPreferences,\n updateEmailPreferences,\n sessions,\n revokeSession,\n revokeAllSessions,\n walletTopupQuote,\n walletTopup,\n reseller,\n applyForReseller,\n enrollAsReseller,\n acceptResellerInvite,\n resellerCatalog,\n quoteResellerOrder,\n resellerOrders,\n resellerOrder,\n resellerWallet,\n resellerTopupQuote,\n resellerTopup,\n resellerApiKeys,\n revokeResellerApiKey,\n\n // Search\n searchProducts,\n searchCatalogItems,\n\n // Invoices\n getInvoice,\n getInvoiceStatus,\n\n // Pages\n getPages,\n getPage,\n\n // Navigation\n getMenus,\n getMenu,\n getMenuBySlot,\n getMenuByTitle,\n getMenuSlotTitles,\n\n // Analytics\n trackPageView,\n getStorefrontOnlineUsers,\n getStorefrontRecentSales,\n touchStorefrontPresence,\n\n // Formatting\n createFormatter,\n formatPrice,\n\n // Cache\n clearCache,\n invalidateCache,\n getCacheStats,\n\n // Theme settings helpers\n fetchPublishedBuilderSettings,\n fetchPublishedThemeSettings,\n resolveDefaults,\n mergeSettings,\n};\n\n// Default export for ES modules\nexport default shoppex;\n\n// UMD global exposure — never clobber an already-initialized client. Theme\n// artifacts can load multiple SDK chunks; a late bundle must not reset init.\nif (typeof window !== 'undefined') {\n const w = window as unknown as { shoppex?: typeof shoppex };\n if (!w.shoppex?.isInitialized?.()) {\n w.shoppex = shoppex;\n }\n}\n"],"x_google_ignoreList":[2,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21],"mappings":"0TAuBA,IAAM,EAAQ,IAAI,IACZ,EAAU,IAAI,IAEd,EAAQ,CACZ,KAAM,EACN,OAAQ,GAgBV,SAAgB,IACd,EAAM,QACN,EAAQ,OACV,CAUA,SAAgB,EAAiB,EAAa,EAAS,GACrD,MAAM,EAAM,KAAK,MACjB,EAAM,IAAI,EAAK,CACb,OACA,MACA,UAAW,EACX,UAAW,EAAM,GAErB,CAQA,eAAsB,EACpB,EACA,EACA,EACA,EAAA,KAA2C,GAE3C,MAAM,EAZR,SAAiC,GAC/B,MAAM,EAAQ,EAAM,IAAI,GACxB,OAAK,GAAc,IAErB,CAQgB,CAAiB,GAE/B,GAAI,IAlDN,SAAmB,GACjB,OAAO,KAAK,MAAQ,EAAM,SAC5B,CAgDgB,CAAU,GAEtB,OADA,EAAM,MAAQ,EACP,EAAM,KAGf,GAAI,GAAS,EAAQ,qBAAsB,CAEzC,GADA,EAAM,MAAQ,GACT,EAAQ,IAAI,GAAM,CACrB,MAAM,EAAA,WACJ,IACE,MAAM,QAAa,IAInB,OAHI,EAAY,IACd,EAAc,EAAK,EAAM,EAAQ,KAE5B,CACT,CAAA,QACE,EAAQ,OAAO,EACjB,CACF,EAVM,GAWN,EAAQ,IAAI,EAAK,EACnB,CACA,OAAO,EAAM,IACf,CAEA,GAAI,EAAQ,IAAI,GACd,OAAO,EAAQ,IAAI,GAGrB,EAAM,QAAU,EAChB,MAAM,EAAA,WACJ,IACE,MAAM,QAAa,IAInB,OAHI,EAAY,IACd,EAAc,EAAK,EAAM,EAAQ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,MAAM,IAAI,MAAM,8DAGlB,MAAM,EAAkB,EAAM,MAAM,OAAO,cACrC,EAAU,EAAM,OAAO,QAAU,GACjC,EAAQ,EAAQ,QAAU,EAAI,EAAQ,MAAM,EAAG,IAAM,kBACrD,EAAU,GAA8B,CAC5C,KAAM,EAAM,KACZ,QAAS,EAAM,UAEX,EAAY,EAAM,WAAW,aAAU,EACvC,EAAa,GAA4B,CAAE,WAAY,EAAM,aAE7D,QAAiB,MACrB,GAAG,8BAAuC,mBAAmB,aAC7D,CACE,OAAQ,OACR,QAAS,CACP,eAAgB,mBAChB,OAAQ,oBAEV,KAAM,KAAK,UAAU,CACnB,MAAO,EACP,QACA,aACI,EAAY,CAAE,WAAY,GAAc,CAAC,MAK7C,QAAgB,EAAS,OAAO,MAAA,IAAY,MAMlD,IAAK,EAAS,GACZ,MAAM,IAAI,MAAM,GAAS,SAAW,GAAS,OAAS,gCAGxD,MAAM,EAAS,GAAS,MAAM,OAC9B,IAAK,EACH,MAAM,IAAI,MAAM,oDAGlB,MAAO,CAAE,SACX,oMJ1DA,SAAmD,EAA8B,GAC/E,GAAmB,aAAf,EAAM,KACR,OAAI,EAAM,WAAa,GAA4C,GAC1D,GAAG,EAAM,oBAEX,KAGT,MAAM,EAAa,EAAM,OACzB,GAAI,EAAM,WAAa,EACrB,MAAO,GAAG,EAAM,oBAGlB,GAAI,EAAM,OAAS,EACjB,IAEE,IAAK,IADe,OAAO,EAAM,OACpB,KAAK,GAChB,MAAO,GAAG,EAAM,6BAEpB,CAAA,MACE,OAAO,IACT,CAGF,OAAO,IACT"}
1
+ {"version":3,"file":"shoppex.umd.js","names":["_a","F","initializer","util.jsonStringifyReplacer","core.$ZodAsyncError","util.finalizeIssue","core.config","errors.$ZodError","safeParse","errors.$ZodRealError","safeParseAsync","duration","email","_emoji","date","time","datetime","string","number","boolean","util.floatSafeRemainder","util.NUMBER_FORMAT_RANGES","regexes.integer","util.nullish","util.getLengthableOrigin","regexes.lowercase","regexes.uppercase","util.escapeRegex","content","util.aborted","util.explicitlyAborted","core.$ZodAsyncError","safeParse","safeParseAsync","regexes.string","regexes.guid","regexes.uuid","regexes.email","regexes.emoji","regexes.nanoid","regexes.cuid","regexes.cuid2","regexes.ulid","regexes.xid","regexes.ksuid","regexes.datetime","regexes.date","regexes.time","regexes.duration","regexes.ipv4","regexes.ipv6","regexes.cidrv4","regexes.cidrv6","regexes.base64","regexes.base64url","regexes.e164","regexes.number","regexes.boolean","util.prefixIssues","util.optionalKeys","util.cached","isObject","util.isObject","util.esc","allowsEval","util.allowsEval","util.finalizeIssue","core.config","util.cleanRegex","util.isPlainObject","util.getEnumValues","util.escapeRegex","core.$ZodEncodeError","util.issue","util.normalizeParams","checks.$ZodCheckLessThan","checks.$ZodCheckGreaterThan","checks.$ZodCheckMultipleOf","checks.$ZodCheckMaxLength","checks.$ZodCheckMinLength","checks.$ZodCheckLengthEquals","checks.$ZodCheckRegex","checks.$ZodCheckLowerCase","checks.$ZodCheckUpperCase","checks.$ZodCheckIncludes","checks.$ZodCheckStartsWith","checks.$ZodCheckEndsWith","checks.$ZodCheckOverwrite","util.slugify","issue","util.issue","checks.$ZodCheck","process","process","core._isoDateTime","core._isoDate","core._isoTime","core._isoDuration","core.formatError","core.flattenError","util.jsonStringifyReplacer","parse.parse","parse.safeParse","parse.parseAsync","parse.safeParseAsync","parse.encode","parse.decode","parse.encodeAsync","parse.decodeAsync","parse.safeEncode","parse.safeDecode","parse.safeEncodeAsync","parse.safeDecodeAsync","util.mergeDefs","core.clone","checks.overwrite","processors.stringProcessor","checks.regex","checks.includes","checks.startsWith","checks.endsWith","checks.minLength","checks.maxLength","checks.length","checks.lowercase","checks.uppercase","checks.trim","checks.normalize","checks.toLowerCase","checks.toUpperCase","checks.slugify","core._email","core._url","core._jwt","core._emoji","core._guid","core._uuid","core._uuidv4","core._uuidv6","core._uuidv7","core._nanoid","core._cuid","core._cuid2","core._ulid","core._base64","core._base64url","core._xid","core._ksuid","core._ipv4","core._ipv6","core._cidrv4","core._cidrv6","core._e164","iso.datetime","iso.date","iso.time","iso.duration","core._string","processors.numberProcessor","checks.gt","checks.gte","checks.lt","checks.lte","checks.multipleOf","number","core._number","core._int","processors.booleanProcessor","core._boolean","processors.unknownProcessor","core._unknown","processors.neverProcessor","core._never","processors.arrayProcessor","core._array","processors.objectProcessor","util.extend","util.safeExtend","util.merge","util.pick","util.omit","util.partial","util.required","util.normalizeParams","processors.unionProcessor","processors.intersectionProcessor","processors.recordProcessor","processors.enumProcessor","processors.literalProcessor","processors.transformProcessor","core.$ZodEncodeError","issue","util.issue","processors.optionalProcessor","processors.nullableProcessor","processors.defaultProcessor","util.shallowClone","processors.prefaultProcessor","processors.nonoptionalProcessor","processors.catchProcessor","processors.pipeProcessor","processors.readonlyProcessor","processors.customProcessor","core._refine","core._superRefine","core._coercedNumber","schemas.ZodNumber"],"sources":["../src/core/cache.ts","../src/core/errors.ts","../../../node_modules/.bun/openapi-fetch@0.17.0/node_modules/openapi-fetch/dist/index.mjs","../../contracts/src/navigation.ts","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/core.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/util.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/errors.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/parse.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/regexes.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/checks.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/doc.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/versions.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/schemas.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/registries.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/api.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/iso.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/errors.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/parse.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/schemas.js","../../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/coerce.js","../../contracts/src/email-marketing.ts","../../contracts/src/payment-gateways.ts","../../contracts/src/style-center.ts","../../contracts/src/storefront-addons.ts","../../contracts/src/manual-gateway-template.ts","../../contracts/src/invoice-wire.ts","../../contracts/src/catalog-unit-price.ts","../../contracts/src/customer-portal-wire.ts","../../contracts/src/index.ts","../src/core/typed-client.ts","../src/core/config.ts","../src/utils/storefront-custom-fields.ts","../src/utils/storefront-stock.ts","../src/utils/storefront-catalog.ts","../src/utils/storefront-search.ts","../src/utils/storefront-contact.ts","../src/core/endpoint.ts","../src/utils/storage.ts","../src/core/telemetry.ts","../src/core/client.ts","../src/modules/store.ts","../src/modules/products.ts","../src/modules/affiliates.ts","../src/utils/cart-line-id.ts","../src/utils/requested-currency.ts","../src/modules/cart.ts","../src/modules/checkout.ts","../src/modules/coupons.ts","../src/modules/reviews.ts","../src/modules/customer.ts","../src/modules/search.ts","../src/modules/invoices.ts","../src/modules/pages.ts","../src/modules/navigation.ts","../src/core/attribution.ts","../src/modules/analytics.ts","../src/modules/presence.ts","../src/utils/format.ts","../src/modules/theme.ts","../src/index.ts"],"sourcesContent":["/**\n * In-memory cache with pending request deduplication.\n */\n\nexport interface CacheEntry<T> {\n data: T;\n expiresAt: number;\n updatedAt: number;\n ttl: number;\n}\n\nexport interface CacheOptions {\n ttl: number;\n staleWhileRevalidate?: boolean;\n}\n\nexport interface CacheStats {\n hits: number;\n misses: number;\n pendingRequests: number;\n entries: number;\n}\n\nconst cache = new Map<string, CacheEntry<unknown>>();\nconst pending = new Map<string, Promise<unknown>>();\n\nconst stats = {\n hits: 0,\n misses: 0,\n};\n\nfunction isExpired(entry: CacheEntry<unknown>): boolean {\n return Date.now() > entry.expiresAt;\n}\n\nexport function getCacheStats(): CacheStats {\n return {\n hits: stats.hits,\n misses: stats.misses,\n pendingRequests: pending.size,\n entries: cache.size,\n };\n}\n\nexport function clearCache(): void {\n cache.clear();\n pending.clear();\n}\n\nexport function invalidateCache(prefixOrKey: string): void {\n for (const key of cache.keys()) {\n if (key === prefixOrKey || key.startsWith(prefixOrKey)) {\n cache.delete(key);\n }\n }\n}\n\nexport function setCacheEntry<T>(key: string, data: T, ttl: number): void {\n const now = Date.now();\n cache.set(key, {\n data,\n ttl,\n updatedAt: now,\n expiresAt: now + ttl,\n });\n}\n\nexport function getCacheEntry<T>(key: string): CacheEntry<T> | null {\n const entry = cache.get(key) as CacheEntry<T> | undefined;\n if (!entry) return null;\n return entry;\n}\n\nexport async function getOrFetch<T>(\n key: string,\n fetcher: () => Promise<T>,\n options: CacheOptions,\n shouldCache: (value: T) => boolean = () => true\n): Promise<T> {\n const entry = getCacheEntry<T>(key);\n\n if (entry && !isExpired(entry)) {\n stats.hits += 1;\n return entry.data;\n }\n\n if (entry && options.staleWhileRevalidate) {\n stats.hits += 1;\n if (!pending.has(key)) {\n const refreshPromise = (async () => {\n try {\n const data = await fetcher();\n if (shouldCache(data)) {\n setCacheEntry(key, data, options.ttl);\n }\n return data;\n } finally {\n pending.delete(key);\n }\n })();\n pending.set(key, refreshPromise as Promise<unknown>);\n }\n return entry.data;\n }\n\n if (pending.has(key)) {\n return pending.get(key) as Promise<T>;\n }\n\n stats.misses += 1;\n const promise = (async () => {\n try {\n const data = await fetcher();\n if (shouldCache(data)) {\n setCacheEntry(key, data, options.ttl);\n }\n return data;\n } finally {\n pending.delete(key);\n }\n })();\n\n pending.set(key, promise as Promise<unknown>);\n return promise;\n}\n","/**\n * SDK Error Classes\n */\n\nexport class ShoppexError extends Error {\n public readonly code: string;\n public readonly statusCode?: number;\n\n constructor(message: string, code: string, statusCode?: number) {\n super(message);\n this.name = 'ShoppexError';\n this.code = code;\n this.statusCode = statusCode;\n Object.setPrototypeOf(this, ShoppexError.prototype);\n }\n}\n\nexport class NotInitializedError extends ShoppexError {\n constructor() {\n super(\n 'SDK not initialized. Call shoppex.init() first.',\n 'NOT_INITIALIZED'\n );\n this.name = 'NotInitializedError';\n Object.setPrototypeOf(this, NotInitializedError.prototype);\n }\n}\n\nexport class NetworkError extends ShoppexError {\n constructor(message: string, statusCode?: number) {\n super(message, 'NETWORK_ERROR', statusCode);\n this.name = 'NetworkError';\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n\n/**\n * A refusal the SERVER made and named. `code` is the backend's `error_code`\n * (e.g. `errors.checkout.coupon_no_longer_valid`) — the branchable identity of\n * the refusal, stable across locales, unlike the localized `message`.\n *\n * Distinct from {@link NetworkError}, whose `code` is always `NETWORK_ERROR`:\n * that one means \"the request did not produce a named answer\".\n */\nexport class ApiError extends ShoppexError {\n public readonly errorParams?: Record<string, unknown>;\n\n constructor(\n message: string,\n code: string,\n statusCode?: number,\n errorParams?: Record<string, unknown>,\n ) {\n super(message, code, statusCode);\n this.name = 'ApiError';\n this.errorParams = errorParams;\n Object.setPrototypeOf(this, ApiError.prototype);\n }\n}\n\nexport class ValidationError extends ShoppexError {\n public readonly invalidFields?: string[];\n\n constructor(message: string, invalidFields?: string[]) {\n super(message, 'VALIDATION_ERROR');\n this.name = 'ValidationError';\n this.invalidFields = invalidFields;\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n\nexport class CartError extends ShoppexError {\n constructor(message: string) {\n super(message, 'BASKET_ERROR');\n this.name = 'CartError';\n Object.setPrototypeOf(this, CartError.prototype);\n }\n}\n","const PATH_PARAM_RE = /\\{[^{}]+\\}/g;\nconst supportsRequestInitExt = () => {\n return typeof process === \"object\" && Number.parseInt(process?.versions?.node?.substring(0, 2)) >= 18 && process.versions.undici;\n};\nfunction randomID() {\n return Math.random().toString(36).slice(2, 11);\n}\nfunction createClient(clientOptions) {\n let {\n baseUrl = \"\",\n Request: CustomRequest = globalThis.Request,\n fetch: baseFetch = globalThis.fetch,\n querySerializer: globalQuerySerializer,\n bodySerializer: globalBodySerializer,\n pathSerializer: globalPathSerializer,\n headers: baseHeaders,\n requestInitExt = void 0,\n ...baseOptions\n } = { ...clientOptions };\n requestInitExt = supportsRequestInitExt() ? requestInitExt : void 0;\n baseUrl = removeTrailingSlash(baseUrl);\n const globalMiddlewares = [];\n async function coreFetch(schemaPath, fetchOptions) {\n const {\n baseUrl: localBaseUrl,\n fetch = baseFetch,\n Request = CustomRequest,\n headers,\n params = {},\n parseAs = \"json\",\n querySerializer: requestQuerySerializer,\n bodySerializer = globalBodySerializer ?? defaultBodySerializer,\n pathSerializer: requestPathSerializer,\n body,\n middleware: requestMiddlewares = [],\n ...init\n } = fetchOptions || {};\n let finalBaseUrl = baseUrl;\n if (localBaseUrl) {\n finalBaseUrl = removeTrailingSlash(localBaseUrl) ?? baseUrl;\n }\n let querySerializer = typeof globalQuerySerializer === \"function\" ? globalQuerySerializer : createQuerySerializer(globalQuerySerializer);\n if (requestQuerySerializer) {\n querySerializer = typeof requestQuerySerializer === \"function\" ? requestQuerySerializer : createQuerySerializer({\n ...typeof globalQuerySerializer === \"object\" ? globalQuerySerializer : {},\n ...requestQuerySerializer\n });\n }\n const pathSerializer = requestPathSerializer || globalPathSerializer || defaultPathSerializer;\n const serializedBody = body === void 0 ? void 0 : bodySerializer(\n body,\n // Note: we declare mergeHeaders() both here and below because it’s a bit of a chicken-or-egg situation:\n // bodySerializer() needs all headers so we aren’t dropping ones set by the user, however,\n // the result of this ALSO sets the lowest-priority content-type header. So we re-merge below,\n // setting the content-type at the very beginning to be overwritten.\n // Lastly, based on the way headers work, it’s not a simple “present-or-not” check becauase null intentionally un-sets headers.\n mergeHeaders(baseHeaders, headers, params.header)\n );\n const finalHeaders = mergeHeaders(\n // with no body, we should not to set Content-Type\n serializedBody === void 0 || // if serialized body is FormData; browser will correctly set Content-Type & boundary expression\n serializedBody instanceof FormData ? {} : {\n \"Content-Type\": \"application/json\"\n },\n baseHeaders,\n headers,\n params.header\n );\n const finalMiddlewares = [...globalMiddlewares, ...requestMiddlewares];\n const requestInit = {\n redirect: \"follow\",\n ...baseOptions,\n ...init,\n body: serializedBody,\n headers: finalHeaders\n };\n let id;\n let options;\n let request = new Request(\n createFinalURL(schemaPath, { baseUrl: finalBaseUrl, params, querySerializer, pathSerializer }),\n requestInit\n );\n let response;\n for (const key in init) {\n if (!(key in request)) {\n request[key] = init[key];\n }\n }\n if (finalMiddlewares.length) {\n id = randomID();\n options = Object.freeze({\n baseUrl: finalBaseUrl,\n fetch,\n parseAs,\n querySerializer,\n bodySerializer,\n pathSerializer\n });\n for (const m of finalMiddlewares) {\n if (m && typeof m === \"object\" && typeof m.onRequest === \"function\") {\n const result = await m.onRequest({\n request,\n schemaPath,\n params,\n options,\n id\n });\n if (result) {\n if (result instanceof Request) {\n request = result;\n } else if (result instanceof Response) {\n response = result;\n break;\n } else {\n throw new Error(\"onRequest: must return new Request() or Response() when modifying the request\");\n }\n }\n }\n }\n }\n if (!response) {\n try {\n response = await fetch(request, requestInitExt);\n } catch (error2) {\n let errorAfterMiddleware = error2;\n if (finalMiddlewares.length) {\n for (let i = finalMiddlewares.length - 1; i >= 0; i--) {\n const m = finalMiddlewares[i];\n if (m && typeof m === \"object\" && typeof m.onError === \"function\") {\n const result = await m.onError({\n request,\n error: errorAfterMiddleware,\n schemaPath,\n params,\n options,\n id\n });\n if (result) {\n if (result instanceof Response) {\n errorAfterMiddleware = void 0;\n response = result;\n break;\n }\n if (result instanceof Error) {\n errorAfterMiddleware = result;\n continue;\n }\n throw new Error(\"onError: must return new Response() or instance of Error\");\n }\n }\n }\n }\n if (errorAfterMiddleware) {\n throw errorAfterMiddleware;\n }\n }\n if (finalMiddlewares.length) {\n for (let i = finalMiddlewares.length - 1; i >= 0; i--) {\n const m = finalMiddlewares[i];\n if (m && typeof m === \"object\" && typeof m.onResponse === \"function\") {\n const result = await m.onResponse({\n request,\n response,\n schemaPath,\n params,\n options,\n id\n });\n if (result) {\n if (!(result instanceof Response)) {\n throw new Error(\"onResponse: must return new Response() when modifying the response\");\n }\n response = result;\n }\n }\n }\n }\n }\n const contentLength = response.headers.get(\"Content-Length\");\n if (response.status === 204 || request.method === \"HEAD\" || contentLength === \"0\" && !response.headers.get(\"Transfer-Encoding\")?.includes(\"chunked\")) {\n return response.ok ? { data: void 0, response } : { error: void 0, response };\n }\n if (response.ok) {\n const getResponseData = async () => {\n if (parseAs === \"stream\") {\n return response.body;\n }\n if (parseAs === \"json\" && !contentLength) {\n const raw = await response.text();\n return raw ? JSON.parse(raw) : void 0;\n }\n return await response[parseAs]();\n };\n return { data: await getResponseData(), response };\n }\n let error = await response.text();\n try {\n error = JSON.parse(error);\n } catch {\n }\n return { error, response };\n }\n return {\n request(method, url, init) {\n return coreFetch(url, { ...init, method: method.toUpperCase() });\n },\n /** Call a GET endpoint */\n GET(url, init) {\n return coreFetch(url, { ...init, method: \"GET\" });\n },\n /** Call a PUT endpoint */\n PUT(url, init) {\n return coreFetch(url, { ...init, method: \"PUT\" });\n },\n /** Call a POST endpoint */\n POST(url, init) {\n return coreFetch(url, { ...init, method: \"POST\" });\n },\n /** Call a DELETE endpoint */\n DELETE(url, init) {\n return coreFetch(url, { ...init, method: \"DELETE\" });\n },\n /** Call a OPTIONS endpoint */\n OPTIONS(url, init) {\n return coreFetch(url, { ...init, method: \"OPTIONS\" });\n },\n /** Call a HEAD endpoint */\n HEAD(url, init) {\n return coreFetch(url, { ...init, method: \"HEAD\" });\n },\n /** Call a PATCH endpoint */\n PATCH(url, init) {\n return coreFetch(url, { ...init, method: \"PATCH\" });\n },\n /** Call a TRACE endpoint */\n TRACE(url, init) {\n return coreFetch(url, { ...init, method: \"TRACE\" });\n },\n /** Register middleware */\n use(...middleware) {\n for (const m of middleware) {\n if (!m) {\n continue;\n }\n if (typeof m !== \"object\" || !(\"onRequest\" in m || \"onResponse\" in m || \"onError\" in m)) {\n throw new Error(\"Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`\");\n }\n globalMiddlewares.push(m);\n }\n },\n /** Unregister middleware */\n eject(...middleware) {\n for (const m of middleware) {\n const i = globalMiddlewares.indexOf(m);\n if (i !== -1) {\n globalMiddlewares.splice(i, 1);\n }\n }\n }\n };\n}\nclass PathCallForwarder {\n constructor(client, url) {\n this.client = client;\n this.url = url;\n }\n GET = (init) => {\n return this.client.GET(this.url, init);\n };\n PUT = (init) => {\n return this.client.PUT(this.url, init);\n };\n POST = (init) => {\n return this.client.POST(this.url, init);\n };\n DELETE = (init) => {\n return this.client.DELETE(this.url, init);\n };\n OPTIONS = (init) => {\n return this.client.OPTIONS(this.url, init);\n };\n HEAD = (init) => {\n return this.client.HEAD(this.url, init);\n };\n PATCH = (init) => {\n return this.client.PATCH(this.url, init);\n };\n TRACE = (init) => {\n return this.client.TRACE(this.url, init);\n };\n}\nclass PathClientProxyHandler {\n constructor() {\n this.client = null;\n }\n // Assume the property is an URL.\n get(coreClient, url) {\n const forwarder = new PathCallForwarder(coreClient, url);\n this.client[url] = forwarder;\n return forwarder;\n }\n}\nfunction wrapAsPathBasedClient(coreClient) {\n const handler = new PathClientProxyHandler();\n const proxy = new Proxy(coreClient, handler);\n function Client() {\n }\n Client.prototype = proxy;\n const client = new Client();\n handler.client = client;\n return client;\n}\nfunction createPathBasedClient(clientOptions) {\n return wrapAsPathBasedClient(createClient(clientOptions));\n}\nfunction serializePrimitiveParam(name, value, options) {\n if (value === void 0 || value === null) {\n return \"\";\n }\n if (typeof value === \"object\") {\n throw new Error(\n \"Deeply-nested arrays/objects aren\\u2019t supported. Provide your own `querySerializer()` to handle these.\"\n );\n }\n return `${name}=${options?.allowReserved === true ? value : encodeURIComponent(value)}`;\n}\nfunction serializeObjectParam(name, value, options) {\n if (!value || typeof value !== \"object\") {\n return \"\";\n }\n const values = [];\n const joiner = {\n simple: \",\",\n label: \".\",\n matrix: \";\"\n }[options.style] || \"&\";\n if (options.style !== \"deepObject\" && options.explode === false) {\n for (const k in value) {\n values.push(k, options.allowReserved === true ? value[k] : encodeURIComponent(value[k]));\n }\n const final2 = values.join(\",\");\n switch (options.style) {\n case \"form\": {\n return `${name}=${final2}`;\n }\n case \"label\": {\n return `.${final2}`;\n }\n case \"matrix\": {\n return `;${name}=${final2}`;\n }\n default: {\n return final2;\n }\n }\n }\n for (const k in value) {\n const finalName = options.style === \"deepObject\" ? `${name}[${k}]` : k;\n values.push(serializePrimitiveParam(finalName, value[k], options));\n }\n const final = values.join(joiner);\n return options.style === \"label\" || options.style === \"matrix\" ? `${joiner}${final}` : final;\n}\nfunction serializeArrayParam(name, value, options) {\n if (!Array.isArray(value)) {\n return \"\";\n }\n if (options.explode === false) {\n const joiner2 = { form: \",\", spaceDelimited: \"%20\", pipeDelimited: \"|\" }[options.style] || \",\";\n const final = (options.allowReserved === true ? value : value.map((v) => encodeURIComponent(v))).join(joiner2);\n switch (options.style) {\n case \"simple\": {\n return final;\n }\n case \"label\": {\n return `.${final}`;\n }\n case \"matrix\": {\n return `;${name}=${final}`;\n }\n // case \"spaceDelimited\":\n // case \"pipeDelimited\":\n default: {\n return `${name}=${final}`;\n }\n }\n }\n const joiner = { simple: \",\", label: \".\", matrix: \";\" }[options.style] || \"&\";\n const values = [];\n for (const v of value) {\n if (options.style === \"simple\" || options.style === \"label\") {\n values.push(options.allowReserved === true ? v : encodeURIComponent(v));\n } else {\n values.push(serializePrimitiveParam(name, v, options));\n }\n }\n return options.style === \"label\" || options.style === \"matrix\" ? `${joiner}${values.join(joiner)}` : values.join(joiner);\n}\nfunction createQuerySerializer(options) {\n return function querySerializer(queryParams) {\n const search = [];\n if (queryParams && typeof queryParams === \"object\") {\n for (const name in queryParams) {\n const value = queryParams[name];\n if (value === void 0 || value === null) {\n continue;\n }\n if (Array.isArray(value)) {\n if (value.length === 0) {\n continue;\n }\n search.push(\n serializeArrayParam(name, value, {\n style: \"form\",\n explode: true,\n ...options?.array,\n allowReserved: options?.allowReserved || false\n })\n );\n continue;\n }\n if (typeof value === \"object\") {\n search.push(\n serializeObjectParam(name, value, {\n style: \"deepObject\",\n explode: true,\n ...options?.object,\n allowReserved: options?.allowReserved || false\n })\n );\n continue;\n }\n search.push(serializePrimitiveParam(name, value, options));\n }\n }\n return search.join(\"&\");\n };\n}\nfunction defaultPathSerializer(pathname, pathParams) {\n let nextURL = pathname;\n for (const match of pathname.match(PATH_PARAM_RE) ?? []) {\n let name = match.substring(1, match.length - 1);\n let explode = false;\n let style = \"simple\";\n if (name.endsWith(\"*\")) {\n explode = true;\n name = name.substring(0, name.length - 1);\n }\n if (name.startsWith(\".\")) {\n style = \"label\";\n name = name.substring(1);\n } else if (name.startsWith(\";\")) {\n style = \"matrix\";\n name = name.substring(1);\n }\n if (!pathParams || pathParams[name] === void 0 || pathParams[name] === null) {\n continue;\n }\n const value = pathParams[name];\n if (Array.isArray(value)) {\n nextURL = nextURL.replace(match, serializeArrayParam(name, value, { style, explode }));\n continue;\n }\n if (typeof value === \"object\") {\n nextURL = nextURL.replace(match, serializeObjectParam(name, value, { style, explode }));\n continue;\n }\n if (style === \"matrix\") {\n nextURL = nextURL.replace(match, `;${serializePrimitiveParam(name, value)}`);\n continue;\n }\n nextURL = nextURL.replace(match, style === \"label\" ? `.${encodeURIComponent(value)}` : encodeURIComponent(value));\n }\n return nextURL;\n}\nfunction defaultBodySerializer(body, headers) {\n if (body instanceof FormData) {\n return body;\n }\n if (headers) {\n const contentType = headers.get instanceof Function ? headers.get(\"Content-Type\") ?? headers.get(\"content-type\") : headers[\"Content-Type\"] ?? headers[\"content-type\"];\n if (contentType === \"application/x-www-form-urlencoded\") {\n return new URLSearchParams(body).toString();\n }\n }\n return JSON.stringify(body);\n}\nfunction createFinalURL(pathname, options) {\n let finalURL = `${options.baseUrl}${pathname}`;\n if (options.params?.path) {\n finalURL = options.pathSerializer(finalURL, options.params.path);\n }\n let search = options.querySerializer(options.params.query ?? {});\n if (search.startsWith(\"?\")) {\n search = search.substring(1);\n }\n if (search) {\n finalURL += `?${search}`;\n }\n return finalURL;\n}\nfunction mergeHeaders(...allHeaders) {\n const finalHeaders = new Headers();\n for (const h of allHeaders) {\n if (!h || typeof h !== \"object\") {\n continue;\n }\n const iterator = h instanceof Headers ? h.entries() : Object.entries(h);\n for (const [k, v] of iterator) {\n if (v === null) {\n finalHeaders.delete(k);\n } else if (Array.isArray(v)) {\n for (const v2 of v) {\n finalHeaders.append(k, v2);\n }\n } else if (v !== void 0) {\n finalHeaders.set(k, v);\n }\n }\n }\n return finalHeaders;\n}\nfunction removeTrailingSlash(url) {\n if (url.endsWith(\"/\")) {\n return url.substring(0, url.length - 1);\n }\n return url;\n}\n\nexport { createFinalURL, createPathBasedClient, createQuerySerializer, createClient as default, defaultBodySerializer, defaultPathSerializer, mergeHeaders, randomID, removeTrailingSlash, serializeArrayParam, serializeObjectParam, serializePrimitiveParam, wrapAsPathBasedClient };\n//# sourceMappingURL=index.mjs.map\n","const NAVIGATION_MENU_SLOT_CONFIG = {\n header: {\n title: 'Header',\n aliases: ['Header Menu'],\n },\n footer: {\n title: 'Footer',\n aliases: ['Footer Links', 'Legal Links'],\n },\n} as const;\n\nexport type NavigationMenuSlot = keyof typeof NAVIGATION_MENU_SLOT_CONFIG;\n\nfunction normalizeNavigationToken(value: string): string {\n return value.trim().toLowerCase().replace(/\\s+/g, ' ');\n}\n\nexport function getNavigationMenuCanonicalTitle(slot: NavigationMenuSlot): string {\n return NAVIGATION_MENU_SLOT_CONFIG[slot].title;\n}\n\nexport function getNavigationMenuTitles(slot: NavigationMenuSlot): string[] {\n const config = NAVIGATION_MENU_SLOT_CONFIG[slot];\n return [config.title, ...config.aliases];\n}\n\nexport function isNavigationMenuSlot(value: string): value is NavigationMenuSlot {\n return value in NAVIGATION_MENU_SLOT_CONFIG;\n}\n\nexport function resolveNavigationMenuSlot(value: string | null | undefined): NavigationMenuSlot | null {\n if (!value) return null;\n\n const normalizedValue = normalizeNavigationToken(value);\n for (const slot of Object.keys(NAVIGATION_MENU_SLOT_CONFIG) as NavigationMenuSlot[]) {\n const candidates = [slot, ...getNavigationMenuTitles(slot)];\n if (candidates.some((candidate) => normalizeNavigationToken(candidate) === normalizedValue)) {\n return slot;\n }\n }\n\n return null;\n}\n\nexport function isSystemNavigationMenuTitle(value: string | null | undefined): boolean {\n return resolveNavigationMenuSlot(value) !== null;\n}\n\nexport const NAVIGATION_MENU_SLOTS = Object.keys(NAVIGATION_MENU_SLOT_CONFIG) as NavigationMenuSlot[];\n","var _a;\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const ratio = val / step;\n const roundedRatio = Math.round(ratio);\n // Use a relative epsilon scaled to the magnitude of the result\n const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);\n if (Math.abs(ratio - roundedRatio) < tolerance)\n return 0;\n return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n // Skip the probe under `jitless`: strict CSPs report the caught `new Function`\n // as a `securitypolicyviolation` even though the throw is swallowed.\n if (globalConfig.jitless) {\n return false;\n }\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n if (o instanceof Map)\n return new Map(o);\n if (o instanceof Set)\n return new Set(o);\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n \"string\",\n \"number\",\n \"bigint\",\n \"boolean\",\n \"symbol\",\n \"undefined\",\n]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n if (a._zod.def.checks?.length) {\n throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n }\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: b._zod.def.checks ?? [],\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined).\n// Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue === false) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;\n rest.path ?? (rest.path = []);\n rest.message = message;\n if (ctx?.reportInput) {\n rest.input = _input;\n }\n return rest;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error, path = []) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _parseAsync(_Err)(schema, value, _ctx);\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emoji = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^[A-Za-z0-9_-]*$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)\n// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// const dateSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\nexport const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const time = timeSource({ precision: args.precision });\n const opts = [\"Z\"];\n if (args.local)\n opts.push(\"\");\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n const timeRegex = `${time}(?:${opts.join(\"|\")})`;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n if (def.value < curr) {\n if (def.inclusive)\n bag.maximum = def.value;\n else\n bag.exclusiveMaximum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n if (def.value > curr) {\n if (def.inclusive)\n bag.minimum = def.value;\n else\n bag.exclusiveMinimum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n var _a;\n (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n });\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n if (isInt)\n bag.pattern = regexes.integer;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.size;\n bag.maximum = def.size;\n bag.size = def.size;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.length;\n bag.maximum = def.length;\n bag.length = def.length;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n if (def.pattern) {\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(def.pattern);\n }\n });\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.mime = def.mime;\n });\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export class Doc {\n constructor(args = []) {\n this.content = [];\n this.indent = 0;\n if (this)\n this.args = args;\n }\n indented(fn) {\n this.indent += 1;\n fn(this);\n this.indent -= 1;\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const args = this?.args;\n const content = this?.content ?? [``];\n const lines = [...content.map((x) => ` ${x}`)];\n // console.log(lines.join(\"\\n\"));\n return new F(...args, lines.join(\"\\n\"));\n }\n}\n","export const version = {\n major: 4,\n minor: 4,\n patch: 3,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync, safeParse, safeParseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const checks = [...(inst._zod.def.checks ?? [])];\n // if inst is itself a checks.$ZodCheck, run it as a check\n if (inst._zod.traits.has(\"$ZodCheck\")) {\n checks.unshift(inst);\n }\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer\n // inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (util.explicitlyAborted(payload))\n continue;\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary\n // initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n // Lazy initialize ~standard to avoid creating objects for every schema\n util.defineLazy(inst, \"~standard\", () => ({\n validate: (value) => {\n try {\n const r = safeParse(inst, value);\n return r.success ? { value: r.data } : { issues: r.error?.issues };\n }\n catch (_) {\n return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n }\n },\n vendor: \"zod\",\n version: 1,\n }));\n});\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n // When normalize is off, require :// for http/https URLs\n // This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source) {\n if (!/^https?:\\/\\//i.test(trimmed)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid URL format\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n }\n // @ts-ignore\n const url = new URL(trimmed);\n if (def.hostname) {\n def.hostname.lastIndex = 0;\n if (!def.hostname.test(url.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n if (def.protocol) {\n def.protocol.lastIndex = 0;\n if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n // Set the output value based on normalize flag\n if (def.normalize) {\n // Use normalized URL\n payload.value = url.href;\n }\n else {\n // Preserve the original input (trimmed)\n payload.value = trimmed;\n }\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.nanoid);\n $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv4`;\n});\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv6`;\n inst._zod.check = (payload) => {\n try {\n // @ts-ignore\n new URL(`http://[${payload.value}]`);\n // return;\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n const parts = payload.value.split(\"/\");\n try {\n if (parts.length !== 2)\n throw new Error();\n const [address, prefix] = parts;\n if (!prefix)\n throw new Error();\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n throw new Error();\n if (prefixNum < 0 || prefixNum > 128)\n throw new Error();\n // @ts-ignore\n new URL(`http://[${address}]`);\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n // atob ignores whitespace, so reject it up front.\n if (/\\s/.test(data))\n return false;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64\";\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64URL(data) {\n if (!regexes.base64url.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64url);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64url\";\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? \"Infinity\"\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = Array(input.length);\n const proms = [];\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {\n const isPresent = key in input;\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (isOptionalIn && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && !isOptionalIn) {\n if (!result.issues.length) {\n final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [key],\n });\n }\n return;\n }\n if (result.value === undefined) {\n if (isPresent) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n for (const k of keys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n keys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const isOptionalIn = _catchall.optin === \"optional\";\n const isOptionalOut = _catchall.optout === \"optional\";\n for (const key in input) {\n // skip __proto__ so it can't replace the result prototype via the\n // assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n if (keySet.has(key))\n continue;\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n // const sh = def.shape;\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n if (!desc?.get) {\n const sh = def.shape;\n Object.defineProperty(def, \"shape\", {\n get: () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", {\n value: newSh,\n });\n return newSh;\n },\n });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazy(inst._zod, \"propValues\", () => {\n const shape = def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n propValues[key] ?? (propValues[key] = new Set());\n for (const v of field.values)\n propValues[key].add(v);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = {};\n const proms = [];\n const shape = value.shape;\n for (const key of value.keys) {\n const el = shape[key];\n const isOptionalIn = el._zod.optin === \"optional\";\n const isOptionalOut = el._zod.optout === \"optional\";\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const generateFastpass = (shape) => {\n const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n const normalized = _normalized.value;\n const parseStr = (key) => {\n const k = util.esc(key);\n return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n };\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.keys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(`const newResult = {};`);\n for (const key of normalized.keys) {\n const id = ids[key];\n const k = util.esc(key);\n const schema = shape[key];\n const isOptionalIn = schema?._zod?.optin === \"optional\";\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(key)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys\n doc.write(`\n if (${id}.issues.length) {\n if (${k} in input) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${k} in input;\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n if (!${id}_present && !${id}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${k}]\n });\n }\n\n if (${id}_present) {\n if (${id}.value === undefined) {\n newResult[${k}] = undefined;\n } else {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n const fn = doc.compile();\n return (payload, ctx) => fn(shape, payload, ctx);\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"values\", () => {\n if (def.options.every((o) => o._zod.values)) {\n return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n if (def.options.every((o) => o._zod.pattern)) {\n const patterns = def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const successes = results.filter((r) => r.issues.length === 0);\n if (successes.length === 1) {\n final.value = successes[0].value;\n return final;\n }\n if (successes.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazy(inst._zod, \"propValues\", () => {\n const propValues = {};\n for (const option of def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const [k, v] of Object.entries(pv)) {\n if (!propValues[k])\n propValues[k] = new Set();\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n return propValues;\n });\n const disc = util.cached(() => {\n const opts = def.options;\n const map = new Map();\n for (const o of opts) {\n const values = o._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n for (const v of values) {\n if (map.has(v)) {\n throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n }\n map.set(v, o);\n }\n }\n return map;\n });\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const opt = disc.value.get(input?.[def.discriminator]);\n if (opt) {\n return opt._zod.run(payload, ctx);\n }\n // Fall back to union matching when the fast discriminator path fails:\n // - explicitly enabled via unionFallback, or\n // - during backward direction (encode), since codec-based discriminators\n // have different values in forward vs backward directions\n if (def.unionFallback || ctx.direction === \"backward\") {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n options: Array.from(disc.value.keys()),\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nfunction mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) report each key as unrecognized\n const unrecKeys = new Map();\n let unrecIssue;\n for (const iss of left.issues) {\n if (iss.code === \"unrecognized_keys\") {\n unrecIssue ?? (unrecIssue = iss);\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).l = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n for (const iss of right.issues) {\n if (iss.code === \"unrecognized_keys\") {\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).r = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n // Report only keys unrecognized by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length && unrecIssue) {\n result.issues.push({ ...unrecIssue, keys: bothKeys });\n }\n if (util.aborted(result))\n return result;\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = [];\n const proms = [];\n const optinStart = getTupleOptStart(items, \"optin\");\n const optoutStart = getTupleOptStart(items, \"optout\");\n if (!def.rest) {\n if (input.length < optinStart) {\n payload.issues.push({\n code: \"too_small\",\n minimum: optinStart,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n if (input.length > items.length) {\n payload.issues.push({\n code: \"too_big\",\n maximum: items.length,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n }\n }\n // Run every item in parallel, collecting results into an indexed\n // array. The post-processing in `handleTupleResults` walks them in\n // order so it can decide whether an absent optional-output error can\n // truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n for (let i = 0; i < items.length; i++) {\n const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((rr) => {\n itemResults[i] = rr;\n }));\n }\n else {\n itemResults[i] = r;\n }\n }\n if (def.rest) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n }\n return handleTupleResults(itemResults, payload, items, input, optoutStart);\n };\n});\nfunction getTupleOptStart(items, key) {\n for (let i = items.length - 1; i >= 0; i--) {\n if (items[i]._zod[key] !== \"optional\")\n return i + 1;\n }\n return 0;\n}\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional\n // rule, but only after `optoutStart`: the first index where the output\n // tuple tail can be absent.\n for (let i = 0; i < items.length; i++) {\n const r = itemResults[i];\n const isPresent = i < input.length;\n if (r.issues.length) {\n if (!isPresent && i >= optoutStart) {\n final.value.length = i;\n break;\n }\n final.issues.push(...util.prefixIssues(i, r.issues));\n }\n final.value[i] = r.value;\n }\n // Drop trailing slots that produced `undefined` for absent input\n // (the array analog of an absent optional key on an object). The\n // `i >= input.length` floor is critical: an explicit `undefined`\n // *inside* the input must be preserved even when the schema is\n // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n // explicit undefined value).\n for (let i = final.value.length - 1; i >= input.length; i--) {\n if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n final.value.length = i;\n }\n else {\n break;\n }\n }\n return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n const values = def.keyType._zod.values;\n if (values) {\n payload.value = {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n continue;\n }\n const outKey = keyResult.value;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n });\n }\n }\n else {\n payload.value = {};\n // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key))\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key)\n // This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = new Map();\n for (const [key, value] of input) {\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = new Set();\n for (const item of input) {\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n inst._zod.pattern = new RegExp(`^(${values\n .filter((k) => util.propertyKeyTypes.has(typeof k))\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n if (def.values.length === 0) {\n throw new Error(\"Cannot create literal schema with no valid values\");\n }\n const values = new Set(def.values);\n inst._zod.values = values;\n inst._zod.pattern = new RegExp(`^(${def.values\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n payload.fallback = true;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n payload.fallback = true;\n return payload;\n };\n});\nfunction handleOptionalResult(result, input) {\n if (input === undefined && (result.issues.length || result.fallback)) {\n return { issues: [], value: undefined };\n }\n return result;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (def.innerType._zod.optin === \"optional\") {\n const input = payload.value;\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise)\n return result.then((r) => handleOptionalResult(r, input));\n return handleOptionalResult(result, input);\n }\n if (payload.value === undefined) {\n return payload;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"pattern\", () => def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => {\n const v = def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n payload.fallback = true;\n }\n return payload;\n });\n }\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n payload.fallback = true;\n }\n return payload;\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n if (left.issues.length) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType?._zod?.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n payload.value = Object.freeze(payload.value);\n return payload;\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n if (!part._zod.pattern) {\n // if (!source)\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n if (!source)\n throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n regexParts.push(source.slice(start, end));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._def = def;\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n return function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n };\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n };\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // Cache the resolved inner type on the shared `def` so all clones of this\n // lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance,\n // preserving identity for cycle detection on recursive schemas.\n util.defineLazy(inst._zod, \"innerType\", () => {\n const d = def;\n if (!d._cachedInner)\n d._cachedInner = def.getter();\n return d._cachedInner;\n });\n util.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType?._zod?.pattern);\n util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType?._zod?.propValues);\n util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType?._zod?.optin ?? undefined);\n util.defineLazy(inst._zod, \"optout\", () => inst._zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","var _a;\nexport const $output = Symbol(\"ZodOutput\");\nexport const $input = Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class({\n type: \"string\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class({\n type: \"string\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class({\n type: \"number\",\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class({\n type: \"number\",\n coerce: true,\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n }, params);\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n ...util.normalizeParams(_params),\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import { globalRegistry } from \"./registries.js\";\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n external: params?.external ?? undefined,\n };\n}\nexport function process(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n process(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n Object.assign(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && \"_prefault\" in result.schema)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema\n // defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes\n // multiple schemas map to the same seen object.\n // e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${id}` };\n }\n if (entry[1] === root) {\n return { ref: \"#\" };\n }\n // self-contained schema\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + defId };\n };\n // stored cached version in `def` property\n // remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema\n // or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/<root>` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n // biome-ignore lint:\n continue;\n }\n }\n }\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n Object.assign(schema, refSchema);\n }\n // restore child's own properties (child wins)\n Object.assign(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema\n // This handles cases like: readonly().meta({id}).describe()\n // where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n Object.assign(result, root.def ?? root.schema);\n // The `id` in `.meta()` is a Zod-specific registration tag used to extract\n // schemas into $defs — it is not user-facing JSON Schema metadata. Strip it\n // from the output body where it would otherwise leak. The id is preserved\n // implicitly via the $defs key (and via $ref paths).\n const rootMetaId = ctx.metadataRegistry.get(schema)?.id;\n if (rootMetaId !== undefined && result.id === rootMetaId)\n delete result.id;\n // build defs object\n const defs = ctx.external?.defs ?? {};\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n if (seen.def.id === seen.defId)\n delete seen.def.id;\n defs[seen.defId] = seen.def;\n }\n }\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed\n // each call to finalize() is functionally independent\n // though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n if (_schema._zod.traits.has(\"$ZodCodec\"))\n return true;\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\nimport { getEnumValues } from \"./util.js\";\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding } = schema._zod\n .bag;\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // JSON Schema format: \"time\" requires a full time with offset or Z\n // z.iso.time() does not include timezone information, so format: \"time\" should never be used\n if (format === \"time\") {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const regexes = [...patterns];\n if (regexes.length === 1)\n json.pattern = regexes[0].source;\n else if (regexes.length > 1) {\n json.allOf = [\n ...regexes.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n if (typeof format === \"string\" && format.includes(\"int\"))\n json.type = \"integer\";\n else\n json.type = \"number\";\n // when both minimum and exclusiveMinimum exist, pick the more restrictive one\n const exMin = typeof exclusiveMinimum === \"number\" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);\n const exMax = typeof exclusiveMaximum === \"number\" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);\n const legacy = ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\";\n if (exMin) {\n if (legacy) {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n else if (typeof minimum === \"number\") {\n json.minimum = minimum;\n }\n if (exMax) {\n if (legacy) {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n else if (typeof maximum === \"number\") {\n json.maximum = maximum;\n }\n if (typeof multipleOf === \"number\")\n json.multipleOf = multipleOf;\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt cannot be represented in JSON Schema\");\n }\n};\nexport const symbolProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Symbols cannot be represented in JSON Schema\");\n }\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Undefined cannot be represented in JSON Schema\");\n }\n};\nexport const voidProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Void cannot be represented in JSON Schema\");\n }\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Date cannot be represented in JSON Schema\");\n }\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, _params) => {\n const def = schema._zod.def;\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Literal `undefined` cannot be represented in JSON Schema\");\n }\n else {\n // do not add to vals\n }\n }\n else if (typeof val === \"bigint\") {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt literals cannot be represented in JSON Schema\");\n }\n else {\n vals.push(Number(val));\n }\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"NaN cannot be represented in JSON Schema\");\n }\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const file = {\n type: \"string\",\n format: \"binary\",\n contentEncoding: \"binary\",\n };\n const { minimum, maximum, mime } = schema._zod.bag;\n if (minimum !== undefined)\n file.minLength = minimum;\n if (maximum !== undefined)\n file.maxLength = maximum;\n if (mime) {\n if (mime.length === 1) {\n file.contentMediaType = mime[0];\n Object.assign(_json, file);\n }\n else {\n Object.assign(_json, file); // shared props at root\n _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs\n }\n }\n else {\n Object.assign(_json, file);\n }\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Custom types cannot be represented in JSON Schema\");\n }\n};\nexport const functionProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Function types cannot be represented in JSON Schema\");\n }\n};\nexport const transformProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Transforms cannot be represented in JSON Schema\");\n }\n};\nexport const mapProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Map cannot be represented in JSON Schema\");\n }\n};\nexport const setProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Set cannot be represented in JSON Schema\");\n }\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = process(def.element, ctx, {\n ...params,\n path: [...params.path, \"items\"],\n });\n};\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n json.properties = {};\n const shape = def.shape;\n for (const key in shape) {\n json.properties[key] = process(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n });\n }\n // required keys\n const allKeys = new Set(Object.keys(shape));\n const requiredKeys = new Set([...allKeys].filter((key) => {\n const v = def.shape[key]._zod;\n if (ctx.io === \"input\") {\n return v.optin === undefined;\n }\n else {\n return v.optout === undefined;\n }\n }));\n if (requiredKeys.size > 0) {\n json.required = Array.from(requiredKeys);\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = process(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches)\n // This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = process(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = process(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? process(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (rest) {\n json.items = rest;\n }\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n json.minItems = prefixItems.length;\n if (!rest) {\n json.maxItems = prefixItems.length;\n }\n }\n else {\n json.items = prefixItems;\n if (rest) {\n json.additionalItems = rest;\n }\n }\n // length\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties\n // This correctly represents \"only validate keys matching the pattern\" semantics\n // and composes well with allOf (intersections)\n const keyType = def.keyType;\n const keyBag = keyType._zod.bag;\n const patterns = keyBag?.patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n json.patternProperties[pattern.source] = valueSchema;\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = process(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n }\n json.additionalProperties = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n if (keyValues) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues;\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.default = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io === \"input\")\n json._prefault = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n throw new Error(\"Dynamic catch values are not supported in JSON Schema\");\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const inIsTransform = def.in._zod.traits.has(\"$ZodTransform\");\n const innerType = ctx.io === \"input\" ? (inIsTransform ? def.out : def.in) : def.out;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n process(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n schemas[key] = finalize(ctx, schema);\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n process(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function datetime(params) {\n return core._isoDateTime(ZodISODateTime, params);\n}\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function date(params) {\n return core._isoDate(ZodISODate, params);\n}\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function time(params) {\n return core._isoTime(ZodISOTime, params);\n}\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function duration(params) {\n return core._isoDuration(ZodISODuration, params);\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n Object.defineProperties(inst, {\n format: {\n value: (mapper) => core.formatError(inst, mapper),\n // enumerable: false,\n },\n flatten: {\n value: (mapper) => core.flattenError(inst, mapper),\n // enumerable: false,\n },\n addIssue: {\n value: (issue) => {\n inst.issues.push(issue);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n addIssues: {\n value: (issues) => {\n inst.issues.push(...issues);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n isEmpty: {\n get() {\n return inst.issues.length === 0;\n },\n // enumerable: false,\n },\n });\n // Object.defineProperty(inst, \"isEmpty\", {\n // get() {\n // return inst.issues.length === 0;\n // },\n // });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport * as checks from \"./checks.js\";\nimport * as iso from \"./iso.js\";\nimport * as parse from \"./parse.js\";\n// Lazy-bind builder methods.\n//\n// Builder methods (`.optional`, `.array`, `.refine`, ...) live as\n// non-enumerable getters on each concrete schema constructor's\n// prototype. On first access from an instance the getter allocates\n// `fn.bind(this)` and caches it as an own property on that instance,\n// so detached usage (`const m = schema.optional; m()`) still works\n// and the per-instance allocation only happens for methods actually\n// touched.\n//\n// One install per (prototype, group), memoized by `_installedGroups`.\nconst _installedGroups = /* @__PURE__ */ new WeakMap();\nfunction _installLazyMethods(inst, group, methods) {\n const proto = Object.getPrototypeOf(inst);\n let installed = _installedGroups.get(proto);\n if (!installed) {\n installed = new Set();\n _installedGroups.set(proto, installed);\n }\n if (installed.has(group))\n return;\n installed.add(group);\n for (const key in methods) {\n const fn = methods[key];\n Object.defineProperty(proto, key, {\n configurable: true,\n enumerable: false,\n get() {\n const bound = fn.bind(this);\n Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n enumerable: true,\n value: bound,\n });\n return bound;\n },\n set(v) {\n Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n enumerable: true,\n value: v,\n });\n },\n });\n }\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n core.$ZodType.init(inst, def);\n Object.assign(inst[\"~standard\"], {\n jsonSchema: {\n input: createStandardJSONSchemaMethod(inst, \"input\"),\n output: createStandardJSONSchemaMethod(inst, \"output\"),\n },\n });\n inst.toJSONSchema = createToJSONSchemaMethod(inst, {});\n inst.def = def;\n inst.type = def.type;\n Object.defineProperty(inst, \"_def\", { value: def });\n // Parse-family is intentionally kept as per-instance closures: these are\n // the hot path AND the most-detached methods (`arr.map(schema.parse)`,\n // `const { parse } = schema`, etc.). Eager closures here mean callers pay\n // ~12 closure allocations per schema but get monomorphic call sites and\n // detached usage that \"just works\".\n inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n inst.spa = inst.safeParseAsync;\n inst.encode = (data, params) => parse.encode(inst, data, params);\n inst.decode = (data, params) => parse.decode(inst, data, params);\n inst.encodeAsync = async (data, params) => parse.encodeAsync(inst, data, params);\n inst.decodeAsync = async (data, params) => parse.decodeAsync(inst, data, params);\n inst.safeEncode = (data, params) => parse.safeEncode(inst, data, params);\n inst.safeDecode = (data, params) => parse.safeDecode(inst, data, params);\n inst.safeEncodeAsync = async (data, params) => parse.safeEncodeAsync(inst, data, params);\n inst.safeDecodeAsync = async (data, params) => parse.safeDecodeAsync(inst, data, params);\n // All builder methods are placed on the internal prototype as lazy-bind\n // getters. On first access per-instance, a bound thunk is allocated and\n // cached as an own property; subsequent accesses skip the getter. This\n // means: no per-instance allocation for unused methods, full\n // detachability preserved (`const m = schema.optional; m()` works), and\n // shared underlying function references across all instances.\n _installLazyMethods(inst, \"ZodType\", {\n check(...chks) {\n const def = this.def;\n return this.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...chks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), { parent: true });\n },\n with(...chks) {\n return this.check(...chks);\n },\n clone(def, params) {\n return core.clone(this, def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n refine(check, params) {\n return this.check(refine(check, params));\n },\n superRefine(refinement, params) {\n return this.check(superRefine(refinement, params));\n },\n overwrite(fn) {\n return this.check(checks.overwrite(fn));\n },\n optional() {\n return optional(this);\n },\n exactOptional() {\n return exactOptional(this);\n },\n nullable() {\n return nullable(this);\n },\n nullish() {\n return optional(nullable(this));\n },\n nonoptional(params) {\n return nonoptional(this, params);\n },\n array() {\n return array(this);\n },\n or(arg) {\n return union([this, arg]);\n },\n and(arg) {\n return intersection(this, arg);\n },\n transform(tx) {\n return pipe(this, transform(tx));\n },\n default(d) {\n return _default(this, d);\n },\n prefault(d) {\n return prefault(this, d);\n },\n catch(params) {\n return _catch(this, params);\n },\n pipe(target) {\n return pipe(this, target);\n },\n readonly() {\n return readonly(this);\n },\n describe(description) {\n const cl = this.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n },\n meta(...args) {\n // overloaded: meta() returns the registered metadata, meta(data)\n // returns a clone with `data` registered. The mapped type picks\n // up the second overload, so we accept variadic any-args and\n // return `any` to satisfy both at runtime.\n if (args.length === 0)\n return core.globalRegistry.get(this);\n const cl = this.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n },\n isOptional() {\n return this.safeParse(undefined).success;\n },\n isNullable() {\n return this.safeParse(null).success;\n },\n apply(fn) {\n return fn(this);\n },\n });\n Object.defineProperty(inst, \"description\", {\n get() {\n return core.globalRegistry.get(inst)?.description;\n },\n configurable: true,\n });\n return inst;\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n const bag = inst._zod.bag;\n inst.format = bag.format ?? null;\n inst.minLength = bag.minimum ?? null;\n inst.maxLength = bag.maximum ?? null;\n _installLazyMethods(inst, \"_ZodString\", {\n regex(...args) {\n return this.check(checks.regex(...args));\n },\n includes(...args) {\n return this.check(checks.includes(...args));\n },\n startsWith(...args) {\n return this.check(checks.startsWith(...args));\n },\n endsWith(...args) {\n return this.check(checks.endsWith(...args));\n },\n min(...args) {\n return this.check(checks.minLength(...args));\n },\n max(...args) {\n return this.check(checks.maxLength(...args));\n },\n length(...args) {\n return this.check(checks.length(...args));\n },\n nonempty(...args) {\n return this.check(checks.minLength(1, ...args));\n },\n lowercase(params) {\n return this.check(checks.lowercase(params));\n },\n uppercase(params) {\n return this.check(checks.uppercase(params));\n },\n trim() {\n return this.check(checks.trim());\n },\n normalize(...args) {\n return this.check(checks.normalize(...args));\n },\n toLowerCase() {\n return this.check(checks.toLowerCase());\n },\n toUpperCase() {\n return this.check(checks.toUpperCase());\n },\n slugify() {\n return this.check(checks.slugify());\n },\n });\n});\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n inst.email = (params) => inst.check(core._email(ZodEmail, params));\n inst.url = (params) => inst.check(core._url(ZodURL, params));\n inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params));\n inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params));\n inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params));\n inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params));\n inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params));\n inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params));\n inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params));\n inst.ulid = (params) => inst.check(core._ulid(ZodULID, params));\n inst.base64 = (params) => inst.check(core._base64(ZodBase64, params));\n inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params));\n inst.xid = (params) => inst.check(core._xid(ZodXID, params));\n inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params));\n inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params));\n inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params));\n inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params));\n inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params));\n inst.e164 = (params) => inst.check(core._e164(ZodE164, params));\n // iso\n inst.datetime = (params) => inst.check(iso.datetime(params));\n inst.date = (params) => inst.check(iso.date(params));\n inst.time = (params) => inst.check(iso.time(params));\n inst.duration = (params) => inst.check(iso.duration(params));\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: core.regexes.httpProtocol,\n hostname: core.regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", core.regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", core.regexes.hex, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n _installLazyMethods(inst, \"ZodNumber\", {\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n int(params) {\n return this.check(int(params));\n },\n safe(params) {\n return this.check(int(params));\n },\n positive(params) {\n return this.check(checks.gt(0, params));\n },\n nonnegative(params) {\n return this.check(checks.gte(0, params));\n },\n negative(params) {\n return this.check(checks.lt(0, params));\n },\n nonpositive(params) {\n return this.check(checks.lte(0, params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n step(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n finite() {\n return this;\n },\n });\n const bag = inst._zod.bag;\n inst.minValue =\n Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;\n inst.maxValue =\n Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;\n inst.isInt = (bag.format ?? \"\").includes(\"int\") || Number.isSafeInteger(bag.multipleOf ?? 0.5);\n inst.isFinite = true;\n inst.format = bag.format ?? null;\n});\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.positive = (params) => inst.check(checks.gt(BigInt(0), params));\n inst.negative = (params) => inst.check(checks.lt(BigInt(0), params));\n inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params));\n inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n const bag = inst._zod.bag;\n inst.minValue = bag.minimum ?? null;\n inst.maxValue = bag.maximum ?? null;\n inst.format = bag.format ?? null;\n});\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\n// int64\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\n// uint64\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n const c = inst._zod.bag;\n inst.minDate = c.minimum ? new Date(c.minimum) : null;\n inst.maxDate = c.maximum ? new Date(c.maximum) : null;\n});\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n _installLazyMethods(inst, \"ZodArray\", {\n min(n, params) {\n return this.check(checks.minLength(n, params));\n },\n nonempty(params) {\n return this.check(checks.minLength(1, params));\n },\n max(n, params) {\n return this.check(checks.maxLength(n, params));\n },\n length(n, params) {\n return this.check(checks.length(n, params));\n },\n unwrap() {\n return this.element;\n },\n });\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.defineLazy(inst, \"shape\", () => {\n return def.shape;\n });\n _installLazyMethods(inst, \"ZodObject\", {\n keyof() {\n return _enum(Object.keys(this._zod.def.shape));\n },\n catchall(catchall) {\n return this.clone({ ...this._zod.def, catchall: catchall });\n },\n passthrough() {\n return this.clone({ ...this._zod.def, catchall: unknown() });\n },\n loose() {\n return this.clone({ ...this._zod.def, catchall: unknown() });\n },\n strict() {\n return this.clone({ ...this._zod.def, catchall: never() });\n },\n strip() {\n return this.clone({ ...this._zod.def, catchall: undefined });\n },\n extend(incoming) {\n return util.extend(this, incoming);\n },\n safeExtend(incoming) {\n return util.safeExtend(this, incoming);\n },\n merge(other) {\n return util.merge(this, other);\n },\n pick(mask) {\n return util.pick(this, mask);\n },\n omit(mask) {\n return util.omit(this, mask);\n },\n partial(...args) {\n return util.partial(ZodOptional, this, args[0]);\n },\n required(...args) {\n return util.required(ZodNonOptional, this, args[0]);\n },\n });\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n inst.rest = (rest) => inst.clone({\n ...inst._zod.def,\n rest: rest,\n });\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n const k = core.clone(keyType);\n k._zod.values = undefined;\n return new ZodRecord({\n type: \"record\",\n keyType: k,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n inst.options = Object.values(def.entries);\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n payload.fallback = true;\n return payload;\n });\n }\n payload.value = output;\n payload.fallback = true;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodPreprocess = /*@__PURE__*/ core.$constructor(\"ZodPreprocess\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodPreprocess.init(inst, def);\n});\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodCustom({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\nexport function preprocess(fn, schema) {\n return new ZodPreprocess({\n type: \"pipe\",\n in: transform(fn),\n out: schema,\n });\n}\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport function string(params) {\n return core._coercedString(schemas.ZodString, params);\n}\nexport function number(params) {\n return core._coercedNumber(schemas.ZodNumber, params);\n}\nexport function boolean(params) {\n return core._coercedBoolean(schemas.ZodBoolean, params);\n}\nexport function bigint(params) {\n return core._coercedBigint(schemas.ZodBigInt, params);\n}\nexport function date(params) {\n return core._coercedDate(schemas.ZodDate, params);\n}\n","import * as z from 'zod/v4';\n\nexport const EmailMarketingConsentBasisSchema = z.enum(['CONSENT', 'SOFT_OPT_IN', 'TRANSACTIONAL_ONLY', 'UNKNOWN']);\nexport const EmailMarketingSuppressionReasonSchema = z.enum(['MANUAL_UNSUB', 'ONE_CLICK_UNSUB', 'HARD_BOUNCE', 'COMPLAINT', 'ADMIN_BLOCK']);\nexport const EmailMarketingCampaignTypeSchema = z.enum(['BROADCAST', 'AUTOMATION']);\nexport const EmailMarketingAutomationTriggerSchema = z.enum([\n 'ABANDONED_CART',\n 'POST_PURCHASE',\n 'WELCOME',\n 'WIN_BACK',\n 'RE_ENGAGEMENT',\n 'TAG_ADDED',\n]);\n\nexport const EmailMarketingContactCreateSchema = z.object({\n email: z.email(),\n name: z.string().trim().min(1).nullable().optional(),\n customer_id: z.string().uuid().nullable().optional(),\n tags: z.array(z.string().trim().min(1)).default([]),\n consent_basis: EmailMarketingConsentBasisSchema.default('UNKNOWN'),\n source: z.string().trim().min(1).default('dashboard'),\n});\n\nexport const EmailMarketingTemplateCreateSchema = z.object({\n name: z.string().trim().min(1),\n subject: z.string().trim().min(1),\n preheader: z.string().nullable().optional(),\n mjml_source: z.string().trim().min(1),\n builder_project_json: z.record(z.string(), z.unknown()).nullable().optional(),\n thumbnail_url: z.url().nullable().optional(),\n});\n\nexport const EmailMarketingTemplatePreviewSchema = z.object({\n mjml_source: z.string().trim().min(1),\n sample_variables: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const EmailMarketingTemplateTestSendSchema = z.object({\n recipient_email: z.email(),\n sample_variables: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const EmailMarketingSettingsUpdateSchema = z.object({\n marketing_enabled: z.boolean().optional(),\n default_from_name: z.string().trim().min(1).nullable().optional(),\n default_from_email: z.email().nullable().optional(),\n default_reply_to_email: z.email().nullable().optional(),\n physical_address: z.string().trim().min(1).nullable().optional(),\n physical_address_line2: z.string().trim().min(1).nullable().optional(),\n physical_city: z.string().trim().min(1).nullable().optional(),\n physical_postal_code: z.string().trim().min(1).nullable().optional(),\n physical_country: z.string().trim().length(2).nullable().optional(),\n daily_limit: z.number().int().positive().optional(),\n monthly_soft_cap: z.number().int().positive().optional(),\n});\n\nexport const EmailMarketingCampaignCreateSchema = z.object({\n type: EmailMarketingCampaignTypeSchema.default('BROADCAST'),\n name: z.string().trim().min(1),\n subject: z.string().trim().min(1),\n template_id: z.string().uuid(),\n list_id: z.string().uuid().nullable().optional(),\n segment_id: z.string().uuid().nullable().optional(),\n from_name: z.string().trim().min(1),\n from_email: z.email(),\n reply_to_email: z.email().nullable().optional(),\n schedule_at: z.string().datetime().nullable().optional(),\n target_emails: z.array(z.email()).max(0, 'Direct recipient entry is disabled. Use lists or segments built from Shoppex customers and paid order buyers.').default([]),\n idempotency_key: z.string().trim().min(1).nullable().optional(),\n});\n\nexport const EmailMarketingAutomationCreateSchema = z.object({\n name: z.string().trim().min(1),\n subject: z.string().trim().min(1),\n template_id: z.string().uuid(),\n from_name: z.string().trim().min(1),\n from_email: z.email(),\n reply_to_email: z.email().nullable().optional(),\n trigger: EmailMarketingAutomationTriggerSchema,\n delay_seconds: z.number().int().min(0).default(0),\n conditions: z.record(z.string(), z.unknown()).default({}),\n});\n\nexport const EmailMarketingAutomationTriggerEventSchema = z.object({\n trigger: EmailMarketingAutomationTriggerSchema,\n email: z.email(),\n customer_id: z.string().uuid().nullable().optional(),\n name: z.string().trim().min(1).nullable().optional(),\n consent_basis: EmailMarketingConsentBasisSchema.default('UNKNOWN'),\n variables: z.record(z.string(), z.unknown()).default({}),\n idempotency_key: z.string().trim().min(1).nullable().optional(),\n});\n\nexport const EmailMarketingSuppressionCreateSchema = z.object({\n email: z.email(),\n reason: EmailMarketingSuppressionReasonSchema.default('ADMIN_BLOCK'),\n notes: z.string().nullable().optional(),\n});\n\nexport type EmailMarketingContactCreate = z.infer<typeof EmailMarketingContactCreateSchema>;\nexport type EmailMarketingTemplateCreate = z.infer<typeof EmailMarketingTemplateCreateSchema>;\nexport type EmailMarketingTemplatePreview = z.infer<typeof EmailMarketingTemplatePreviewSchema>;\nexport type EmailMarketingTemplateTestSend = z.infer<typeof EmailMarketingTemplateTestSendSchema>;\nexport type EmailMarketingSettingsUpdate = z.infer<typeof EmailMarketingSettingsUpdateSchema>;\nexport type EmailMarketingCampaignCreate = z.infer<typeof EmailMarketingCampaignCreateSchema>;\nexport type EmailMarketingAutomationCreate = z.infer<typeof EmailMarketingAutomationCreateSchema>;\nexport type EmailMarketingAutomationTriggerEvent = z.infer<typeof EmailMarketingAutomationTriggerEventSchema>;\nexport type EmailMarketingSuppressionCreate = z.infer<typeof EmailMarketingSuppressionCreateSchema>;\n","import * as z from 'zod/v4';\n\nexport const COIN_GATEWAY_KEYS = [\n 'BITCOIN',\n 'LITECOIN',\n 'ETHEREUM',\n 'BITCOIN_CASH',\n 'MONERO',\n 'RIPPLE',\n 'TRON',\n 'SOLANA',\n 'POLYGON',\n 'BINANCE_COIN',\n 'CRONOS',\n 'CONCORDIUM',\n 'NANO',\n 'DOGECOIN',\n 'DASH',\n] as const;\n\nexport const CRYPTO_PROVIDER_KEYS = [\n 'NOWPAYMENTS',\n 'CRYPTOMUS',\n 'OXAPAY',\n] as const;\n\nexport const MANAGED_CRYPTO_PROVIDER_KEYS = [\n 'NOWPAYMENTS_WHITELABEL',\n] as const;\n\nexport const GENERIC_STABLECOIN_GATEWAY_FAMILIES = {\n USDT: ['USDT_TRC20', 'USDT_ERC20', 'USDT_BEP20', 'USDT_POLYGON', 'USDT_SOL'],\n USDC: ['USDC_ERC20', 'USDC_TRC20', 'USDC_BEP20', 'USDC_POLYGON', 'USDC_SOL'],\n DAI: ['DAI_ERC20'],\n} as const;\n\nexport const GENERIC_STABLECOIN_GATEWAY_KEYS = Object.keys(\n GENERIC_STABLECOIN_GATEWAY_FAMILIES,\n) as Array<keyof typeof GENERIC_STABLECOIN_GATEWAY_FAMILIES>;\n\nexport const TOKEN_GATEWAY_KEYS = [\n ...GENERIC_STABLECOIN_GATEWAY_FAMILIES.USDT,\n ...GENERIC_STABLECOIN_GATEWAY_FAMILIES.USDC,\n ...GENERIC_STABLECOIN_GATEWAY_FAMILIES.DAI,\n] as const;\n\nexport const CRYPTO_GATEWAY_KEYS = [\n ...COIN_GATEWAY_KEYS,\n ...TOKEN_GATEWAY_KEYS,\n] as const;\n\nexport const LEGACY_CRYPTO_GATEWAY_KEYS = [\n 'BITCOIN_LN',\n] as const;\n\nexport const CRYPTO_PROVIDER_GATEWAY_KEYS = [\n ...CRYPTO_PROVIDER_KEYS,\n ...MANAGED_CRYPTO_PROVIDER_KEYS,\n] as const;\n\nexport const CONCRETE_CRYPTO_GATEWAY_KEYS = [\n ...CRYPTO_GATEWAY_KEYS,\n ...LEGACY_CRYPTO_GATEWAY_KEYS,\n] as const;\n\nexport type CoinGatewayKey = typeof COIN_GATEWAY_KEYS[number];\nexport type TokenGatewayKey = typeof TOKEN_GATEWAY_KEYS[number];\nexport type CryptoGatewayKey = typeof CRYPTO_GATEWAY_KEYS[number];\nexport type LegacyCryptoGatewayKey = typeof LEGACY_CRYPTO_GATEWAY_KEYS[number];\nexport type CryptoProviderKey = typeof CRYPTO_PROVIDER_KEYS[number];\nexport type ManagedCryptoProviderKey = typeof MANAGED_CRYPTO_PROVIDER_KEYS[number];\nexport type CryptoProviderGatewayKey = typeof CRYPTO_PROVIDER_GATEWAY_KEYS[number];\n\nexport const NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX = 'NOWPAYMENTS:' as const;\nexport type NowPaymentsDynamicGatewayKey = `${typeof NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX}${string}`;\n\nconst NOWPAYMENTS_CURRENCY_CODE_PATTERN = /^[A-Z0-9]{2,12}$/;\n\nexport function buildNowPaymentsDynamicGatewayKey(\n currencyCode: string,\n): NowPaymentsDynamicGatewayKey | null {\n const normalizedCode = currencyCode.trim().toUpperCase();\n if (!NOWPAYMENTS_CURRENCY_CODE_PATTERN.test(normalizedCode)) {\n return null;\n }\n\n return `${NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX}${normalizedCode}`;\n}\n\nexport function parseNowPaymentsDynamicGatewayKey(gateway: string): string | null {\n const normalized = gateway.trim().toUpperCase();\n if (!normalized.startsWith(NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX)) {\n return null;\n }\n\n const code = normalized.slice(NOWPAYMENTS_DYNAMIC_GATEWAY_PREFIX.length);\n return NOWPAYMENTS_CURRENCY_CODE_PATTERN.test(code) ? code.toLowerCase() : null;\n}\n\nexport function isNowPaymentsDynamicGatewayKey(\n gateway: string,\n): gateway is NowPaymentsDynamicGatewayKey {\n return parseNowPaymentsDynamicGatewayKey(gateway) !== null;\n}\n\nexport const DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS = CRYPTO_GATEWAY_KEYS;\n\nexport const DEFAULT_CRYPTOMUS_CRYPTO_GATEWAY_KEYS = [\n 'BITCOIN',\n 'LITECOIN',\n 'ETHEREUM',\n 'TRON',\n 'SOLANA',\n 'POLYGON',\n 'BINANCE_COIN',\n 'BITCOIN_CASH',\n 'MONERO',\n 'RIPPLE',\n 'DOGECOIN',\n 'USDT_TRC20',\n 'USDT_ERC20',\n 'USDT_BEP20',\n 'USDT_POLYGON',\n 'USDT_SOL',\n 'USDC_ERC20',\n 'USDC_BEP20',\n 'USDC_POLYGON',\n 'DAI_ERC20',\n] as const;\n\nexport const DEFAULT_OXAPAY_CRYPTO_GATEWAY_KEYS = [\n 'BITCOIN',\n 'LITECOIN',\n 'ETHEREUM',\n 'TRON',\n 'SOLANA',\n 'POLYGON',\n 'BINANCE_COIN',\n 'BITCOIN_CASH',\n 'MONERO',\n 'RIPPLE',\n 'DOGECOIN',\n 'USDT_TRC20',\n 'USDT_ERC20',\n 'USDT_BEP20',\n 'USDT_POLYGON',\n 'USDC_ERC20',\n] as const;\n\nexport const DEFAULT_PROVIDER_GATEWAY_SELECTIONS = {\n NOWPAYMENTS: DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS,\n NOWPAYMENTS_WHITELABEL: DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS,\n CRYPTOMUS: DEFAULT_CRYPTOMUS_CRYPTO_GATEWAY_KEYS,\n OXAPAY: DEFAULT_OXAPAY_CRYPTO_GATEWAY_KEYS,\n} as const;\n\nexport const POPULAR_PLATFORM_MANAGED_CRYPTO_GATEWAY_KEYS = [\n 'BITCOIN',\n 'LITECOIN',\n 'ETHEREUM',\n 'USDT_TRC20',\n 'USDT_ERC20',\n] as const;\n\nexport const CHECKOUT_METHOD_ORDER_KEYS = [\n 'STRIPE',\n 'PAYPAL',\n 'PAYPAL_FF',\n 'MOLLIE',\n 'AUTHORIZENET',\n 'NMI',\n 'SQUARE',\n 'SUMUP',\n 'SHOPIFY',\n 'SUBY',\n 'PANDABASE',\n 'STORRIK',\n 'DEBLOMASSI',\n 'SHOPPEXPAY',\n 'MONEYMOTION',\n 'OVGC',\n 'WHOP',\n 'DODO',\n 'MAVERICK',\n 'CASHAPP',\n 'VENMO',\n 'CRYPTO',\n 'CUSTOMER_BALANCE',\n 'MANUAL',\n] as const;\n\n/**\n * Gateway implementations that remain in the codebase but must not be\n * advertised or selectable in merchant and buyer UI.\n */\nexport const RETIRED_UI_PAYMENT_GATEWAY_KEYS = ['SHOPPEXPAY'] as const;\n\nconst RETIRED_UI_PAYMENT_GATEWAY_KEY_SET = new Set<string>(\n RETIRED_UI_PAYMENT_GATEWAY_KEYS,\n);\n\nexport function isRetiredUiPaymentGateway(gateway: string): boolean {\n return RETIRED_UI_PAYMENT_GATEWAY_KEY_SET.has(gateway.trim().toUpperCase());\n}\n\nexport const DEFAULT_PAYPAL_FF_MANAGED_IPN_URL = 'https://paypal-ff.myshoppex.io';\n\nexport type CheckoutMethodOrderKey = typeof CHECKOUT_METHOD_ORDER_KEYS[number];\n\nexport interface StoredPaymentGatewayRow {\n provider?: string | null;\n is_active?: boolean | number | string | null;\n isActive?: boolean | number | string | null;\n external_id?: string | null;\n externalId?: string | null;\n has_credentials?: boolean | number | string | null;\n hasCredentials?: boolean | number | string | null;\n has_settings?: boolean | number | string | null;\n hasSettings?: boolean | number | string | null;\n}\n\nexport interface OxapayCheckoutGatewayInfo {\n gateway_key?: string;\n gatewayKey?: string;\n display_name?: string;\n displayName?: string;\n symbol?: string;\n network?: string;\n network_name?: string | null;\n networkName?: string | null;\n required_confirmations?: number | null;\n requiredConfirmations?: number | null;\n deposit_min?: number | null;\n depositMin?: number | null;\n withdraw_min?: number | null;\n withdrawMin?: number | null;\n withdraw_fee?: number | null;\n withdrawFee?: number | null;\n}\n\nexport interface PaymentGatewaySecretRef {\n set: boolean;\n}\n\nexport interface PaymentGatewayHealth {\n status: 'READY' | 'NEEDS_ATTENTION';\n code?: string;\n message?: string;\n checked_at?: string;\n}\n\nexport interface PaymentGatewayState {\n provider: string;\n type: string;\n enabled: boolean;\n connected: boolean;\n credentials: Record<string, PaymentGatewaySecretRef>;\n public_config: Record<string, unknown>;\n webhook?: Record<string, unknown>;\n health?: PaymentGatewayHealth;\n}\n\nexport type GatewayIntegrationType =\n | 'OAUTH'\n | 'API_KEY'\n | 'SDK'\n | 'LEGACY'\n | 'DIRECT'\n | 'FORWARDING'\n | 'AGGREGATOR';\n\nexport interface NormalizedPaymentGatewayState {\n provider: string;\n id: string;\n type: string;\n name: string;\n enabled: boolean;\n connected: boolean;\n health_status?: 'READY' | 'NEEDS_ATTENTION';\n health_code?: string;\n health_message?: string;\n health_checked_at?: string;\n created_at: string;\n updated_at: string;\n integration_type?: 'SDK' | 'LEGACY';\n config?: Record<string, unknown>;\n}\n\nconst COIN_GATEWAY_KEY_SET = new Set<string>(COIN_GATEWAY_KEYS);\nconst TOKEN_GATEWAY_KEY_SET = new Set<string>(TOKEN_GATEWAY_KEYS);\nconst CRYPTO_GATEWAY_KEY_SET = new Set<string>(CRYPTO_GATEWAY_KEYS);\nconst LEGACY_CRYPTO_GATEWAY_KEY_SET = new Set<string>(LEGACY_CRYPTO_GATEWAY_KEYS);\nconst CRYPTO_PROVIDER_KEY_SET = new Set<string>(CRYPTO_PROVIDER_KEYS);\nconst MANAGED_CRYPTO_PROVIDER_KEY_SET = new Set<string>(MANAGED_CRYPTO_PROVIDER_KEYS);\nconst CRYPTO_PROVIDER_GATEWAY_KEY_SET = new Set<string>(CRYPTO_PROVIDER_GATEWAY_KEYS);\nconst CONCRETE_CRYPTO_GATEWAY_KEY_SET = new Set<string>(CONCRETE_CRYPTO_GATEWAY_KEYS);\nconst GENERIC_STABLECOIN_GATEWAY_KEY_SET = new Set<string>(GENERIC_STABLECOIN_GATEWAY_KEYS);\nconst CHECKOUT_METHOD_ORDER_KEY_SET = new Set<string>(CHECKOUT_METHOD_ORDER_KEYS);\nconst CHECKOUT_METHOD_GROUP_BY_GATEWAY: Record<string, CheckoutMethodOrderKey> = {\n STRIPE: 'STRIPE',\n PAYPAL: 'PAYPAL',\n PAYPAL_FF: 'PAYPAL_FF',\n MOLLIE: 'MOLLIE',\n AUTHORIZENET: 'AUTHORIZENET',\n NMI: 'NMI',\n SQUARE: 'SQUARE',\n SUMUP: 'SUMUP',\n SHOPIFY: 'SHOPIFY',\n SUBY: 'SUBY',\n PANDABASE: 'PANDABASE',\n STORRIK: 'STORRIK',\n DEBLOMASSI: 'DEBLOMASSI',\n SHOPPEXPAY: 'SHOPPEXPAY',\n MONEYMOTION: 'MONEYMOTION',\n OVGC: 'OVGC',\n WHOP: 'WHOP',\n DODO: 'DODO',\n MAVERICK: 'MAVERICK',\n CASH_APP: 'CASHAPP',\n VENMO: 'VENMO',\n CUSTOMER_BALANCE: 'CUSTOMER_BALANCE',\n};\n\nconst LEGACY_GATEWAY_ALIASES: Record<string, string> = {\n CASHAPP: 'CASH_APP',\n PAYPAL_CREDIT_CARD: 'PAYPAL',\n EUTHEREUM: 'ETHEREUM',\n USDT_MATIC: 'USDT_POLYGON',\n USDC_MATIC: 'USDC_POLYGON',\n};\n\nfunction assertUniqueEntries(name: string, values: readonly string[]) {\n if (new Set(values).size !== values.length) {\n throw new Error(`${name} contains duplicate entries`);\n }\n}\n\nassertUniqueEntries('COIN_GATEWAY_KEYS', COIN_GATEWAY_KEYS);\nassertUniqueEntries('TOKEN_GATEWAY_KEYS', TOKEN_GATEWAY_KEYS);\nassertUniqueEntries('CRYPTO_GATEWAY_KEYS', CRYPTO_GATEWAY_KEYS);\nassertUniqueEntries('LEGACY_CRYPTO_GATEWAY_KEYS', LEGACY_CRYPTO_GATEWAY_KEYS);\nassertUniqueEntries('CRYPTO_PROVIDER_KEYS', CRYPTO_PROVIDER_KEYS);\nassertUniqueEntries('MANAGED_CRYPTO_PROVIDER_KEYS', MANAGED_CRYPTO_PROVIDER_KEYS);\nassertUniqueEntries('CRYPTO_PROVIDER_GATEWAY_KEYS', CRYPTO_PROVIDER_GATEWAY_KEYS);\nassertUniqueEntries('DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS', DEFAULT_NOWPAYMENTS_CRYPTO_GATEWAY_KEYS);\nassertUniqueEntries('DEFAULT_CRYPTOMUS_CRYPTO_GATEWAY_KEYS', DEFAULT_CRYPTOMUS_CRYPTO_GATEWAY_KEYS);\nassertUniqueEntries('DEFAULT_OXAPAY_CRYPTO_GATEWAY_KEYS', DEFAULT_OXAPAY_CRYPTO_GATEWAY_KEYS);\n\nfor (const key of CRYPTO_GATEWAY_KEYS) {\n if (!COIN_GATEWAY_KEY_SET.has(key) && !TOKEN_GATEWAY_KEY_SET.has(key)) {\n throw new Error(`CRYPTO_GATEWAY_KEYS contains an unclassified gateway: ${key}`);\n }\n}\n\nexport function parseGatewayList(input: unknown): string[] {\n if (Array.isArray(input)) {\n return input.filter((entry): entry is string => typeof entry === 'string');\n }\n\n if (typeof input !== 'string') {\n return [];\n }\n\n const trimmed = input.trim();\n if (!trimmed) {\n return [];\n }\n\n if (trimmed.startsWith('[') && trimmed.endsWith(']')) {\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n if (Array.isArray(parsed)) {\n return parsed.filter((entry): entry is string => typeof entry === 'string');\n }\n } catch {\n // Fallback to comma-separated parsing.\n }\n }\n\n return trimmed\n .split(',')\n .map((entry) => entry.trim())\n .filter(Boolean);\n}\n\nexport function normalizeGatewayKey(input: string): string {\n const trimmed = input.trim();\n if (!trimmed) {\n return '';\n }\n\n if (/^manual:/i.test(trimmed)) {\n const manualId = trimmed.slice(trimmed.indexOf(':') + 1).trim();\n return manualId ? `MANUAL:${manualId}` : 'MANUAL';\n }\n\n let normalized = trimmed.toUpperCase();\n\n const stablecoinNetworkMatch = normalized.match(/^(USDT|USDC|DAI):([A-Z0-9_]+)$/);\n if (stablecoinNetworkMatch) {\n const [, asset, rawNetwork] = stablecoinNetworkMatch;\n const network = rawNetwork === 'MATIC' ? 'POLYGON' : rawNetwork;\n normalized = `${asset}_${network}`;\n }\n\n return LEGACY_GATEWAY_ALIASES[normalized] ?? normalized;\n}\n\nexport function normalizeGatewayRestrictionValues(values: readonly string[]): string[] {\n const normalized = new Set<string>();\n\n for (const value of values) {\n const gateway = normalizeGatewayKey(value);\n if (gateway) {\n normalized.add(gateway);\n }\n }\n\n return [...normalized];\n}\n\nexport function normalizeGatewayRestrictionInput(input: unknown): string[] | null {\n const normalized = normalizeGatewayRestrictionValues(parseGatewayList(input));\n return normalized.length > 0 ? normalized : null;\n}\n\nexport function isValidProductGatewaySelection(input: string): boolean {\n const normalized = normalizeGatewayKey(input);\n if (!normalized || normalized === 'NULL' || normalized === 'UNDEFINED') {\n return false;\n }\n\n return normalized === 'CUSTOMER_BALANCE'\n || normalized === 'CRYPTO'\n || isFinanceGateway(normalized)\n || isCryptoProviderGatewayKey(normalized)\n || isConcreteCryptoGatewayKey(normalized)\n || isGenericStablecoinGatewayKey(normalized);\n}\n\nexport function findInvalidProductGatewaySelections(input: unknown): string[] {\n return normalizeGatewayRestrictionValues(parseGatewayList(input))\n .filter((gateway) => !isValidProductGatewaySelection(gateway));\n}\n\n/**\n * Canonical persisted product restrictions. External write paths should reject\n * `invalid`; trusted repair/import paths may deliberately keep only `gateways`.\n */\nexport function partitionProductGatewaySelections(input: unknown): {\n gateways: string[];\n invalid: string[];\n} {\n const normalized = normalizeGatewayRestrictionValues(parseGatewayList(input));\n const gateways: string[] = [];\n const invalid: string[] = [];\n\n for (const gateway of normalized) {\n (isValidProductGatewaySelection(gateway) ? gateways : invalid).push(gateway);\n }\n\n return { gateways, invalid };\n}\n\nexport const FINANCE_GATEWAY_KEYS = [\n 'STRIPE', 'PAYPAL', 'PAYPAL_FF', 'SKRILL', 'CASHAPP', 'CASH_APP', 'PERFECT_MONEY',\n 'SQUARE', 'SUMUP', 'SHOPIFY', 'SUBY', 'PANDABASE', 'STORRIK', 'DEBLOMASSI', 'SHOPPEXPAY', 'MONEYMOTION', 'OVGC', 'WHOP',\n 'DODO', 'MAVERICK', 'VENMO', 'MOLLIE', 'AUTHORIZENET', 'NMI',\n] as const;\n\nconst FINANCE_GATEWAY_KEY_SET = new Set<string>(\n FINANCE_GATEWAY_KEYS.map((gateway) => normalizeGatewayKey(gateway)),\n);\n\nexport function isFinanceGateway(gateway: string): boolean {\n const normalized = normalizeGatewayKey(gateway);\n return normalized === 'MANUAL' || normalized.startsWith('MANUAL:') || FINANCE_GATEWAY_KEY_SET.has(normalized);\n}\n\nexport const VALID_PRODUCT_PAYMENT_GATEWAY_RESTRICTION_MODES = ['USE_STORE_DEFAULT', 'CUSTOM'] as const;\n\nexport type ProductPaymentGatewayRestrictionMode =\n (typeof VALID_PRODUCT_PAYMENT_GATEWAY_RESTRICTION_MODES)[number];\n\nexport function normalizeProductPaymentGatewayRestrictionMode(\n value: unknown,\n): ProductPaymentGatewayRestrictionMode {\n return value === 'CUSTOM' ? 'CUSTOM' : 'USE_STORE_DEFAULT';\n}\n\nexport function isProductGatewayRestrictionPublishable(\n mode: unknown,\n gateways: unknown,\n): boolean {\n return normalizeProductPaymentGatewayRestrictionMode(mode) !== 'CUSTOM'\n || normalizeGatewayRestrictionInput(gateways) !== null;\n}\n\nexport function isCoinGateway(gateway: string): gateway is CoinGatewayKey {\n return COIN_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isTokenGateway(gateway: string): gateway is TokenGatewayKey {\n return TOKEN_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isCryptoGateway(gateway: string): gateway is CryptoGatewayKey {\n return CRYPTO_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isProviderKey(gateway: string): gateway is CryptoProviderKey {\n return CRYPTO_PROVIDER_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isManagedCryptoProviderKey(gateway: string): gateway is ManagedCryptoProviderKey {\n return MANAGED_CRYPTO_PROVIDER_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isCryptoProviderGatewayKey(gateway: string): boolean {\n return CRYPTO_PROVIDER_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isGenericStablecoinGatewayKey(gateway: string): boolean {\n return GENERIC_STABLECOIN_GATEWAY_KEY_SET.has(normalizeGatewayKey(gateway));\n}\n\nexport function isConcreteCryptoGatewayKey(gateway: string): boolean {\n const normalizedGateway = normalizeGatewayKey(gateway);\n return isCryptoGateway(normalizedGateway)\n || LEGACY_CRYPTO_GATEWAY_KEY_SET.has(normalizedGateway)\n || CONCRETE_CRYPTO_GATEWAY_KEY_SET.has(normalizedGateway)\n || isNowPaymentsDynamicGatewayKey(normalizedGateway);\n}\n\n/**\n * True for anything that resolves to a crypto payment, in every shape a gateway\n * key can take: a concrete coin (`BITCOIN`, `USDT:ERC20`), a generic stablecoin\n * whose chain the buyer still has to choose (`USDT`), and a provider key that\n * expands into a coin list (`OXAPAY`, `NOWPAYMENTS`, `CRYPTOMUS`).\n *\n * Use this — not `isConcreteCryptoGatewayKey` on its own — wherever the question\n * is \"may this be selected without the buyer choosing it?\". Selecting crypto\n * locks an exchange rate against a deposit address, so a caller that only\n * recognises concrete coins lets a provider key through and starts that session\n * anyway. Both halves of that mistake have been shipped before.\n */\nexport function isCryptoPaymentSelection(gateway: string): boolean {\n return isConcreteCryptoGatewayKey(gateway)\n || isGenericStablecoinGatewayKey(gateway)\n || isCryptoProviderGatewayKey(gateway);\n}\n\nexport function getConcreteCryptoGatewaySelections(gateways: Iterable<string>): string[] {\n const selected = new Set<string>();\n\n for (const gateway of gateways) {\n const normalized = normalizeGatewayKey(gateway);\n if (isConcreteCryptoGatewayKey(normalized)) {\n selected.add(normalized);\n }\n }\n\n return [...selected];\n}\n\n/**\n * External labels of crypto payment rails as emitted by the invoice read model\n * (resolveExternalCryptoRailLabel): WHITE_LABEL for managed provider rails and\n * NATIVE for self-hosted BTC/LTC nodes. These are rail labels, not gateway or\n * processor keys.\n */\nexport const CRYPTO_RAIL_GATEWAY_LABELS = ['WHITE_LABEL', 'NATIVE'] as const;\nexport type CryptoRailGatewayLabel = typeof CRYPTO_RAIL_GATEWAY_LABELS[number];\nconst CRYPTO_RAIL_GATEWAY_LABEL_SET = new Set<string>(CRYPTO_RAIL_GATEWAY_LABELS);\n\n/**\n * `PaymentProvider` enum value persisted for the self-hosted crypto rail. The\n * read model emits the 'NATIVE' rail label, while invoice and attempt rows carry\n * the provider value itself — both name the same rail.\n */\nexport const NATIVE_CRYPTO_PROVIDER_KEY = 'NATIVE_CRYPTO' as const;\n\n/** Processor keys persisted on crypto payment attempts (providers plus the NATIVE rail). */\nexport const CRYPTO_PAYMENT_PROCESSOR_KEYS = [...CRYPTO_PROVIDER_GATEWAY_KEYS, 'NATIVE'] as const;\nexport type CryptoPaymentProcessorKey = typeof CRYPTO_PAYMENT_PROCESSOR_KEYS[number];\nconst CRYPTO_PAYMENT_PROCESSOR_KEY_SET = new Set<string>(CRYPTO_PAYMENT_PROCESSOR_KEYS);\n\nexport function isCryptoRailGatewayLabel(value: string): value is CryptoRailGatewayLabel {\n return CRYPTO_RAIL_GATEWAY_LABEL_SET.has(normalizeGatewayKey(value));\n}\n\nexport function isCryptoPaymentProcessorKey(value: string): value is CryptoPaymentProcessorKey {\n return CRYPTO_PAYMENT_PROCESSOR_KEY_SET.has(normalizeGatewayKey(value));\n}\n\n/**\n * Single source of truth for \"does this invoice gateway value mean crypto\":\n * concrete coin/token keys (incl. legacy), generic stablecoin families,\n * provider gateway keys, and external rail labels. Consumers classifying\n * invoice rows by their public `gateway` value must use this instead of\n * maintaining local lists.\n */\nexport function isCryptoInvoiceGatewayLabel(value: string): boolean {\n const normalized = normalizeGatewayKey(value);\n return isConcreteCryptoGatewayKey(normalized)\n || GENERIC_STABLECOIN_GATEWAY_KEY_SET.has(normalized)\n || CRYPTO_PROVIDER_GATEWAY_KEY_SET.has(normalized)\n || CRYPTO_RAIL_GATEWAY_LABEL_SET.has(normalized)\n || normalized === NATIVE_CRYPTO_PROVIDER_KEY;\n}\n\nfunction getAvailableManualGatewaySelections(gateways: Iterable<string>): string[] {\n const selected = new Set<string>();\n\n for (const gateway of gateways) {\n const normalized = normalizeGatewayKey(gateway);\n if (normalized === 'MANUAL' || normalized.startsWith('MANUAL:')) {\n selected.add(normalized);\n }\n }\n\n return [...selected];\n}\n\nfunction getProviderScopedGatewaySelections(\n providerGateway: keyof typeof DEFAULT_PROVIDER_GATEWAY_SELECTIONS,\n availableGateways: string[],\n): string[] {\n const providerDefaults = DEFAULT_PROVIDER_GATEWAY_SELECTIONS[providerGateway];\n\n if (availableGateways.length === 0) {\n return [...providerDefaults];\n }\n\n const availableConcreteGateways = new Set(getConcreteCryptoGatewaySelections(availableGateways));\n return providerDefaults.filter((gateway) => availableConcreteGateways.has(gateway));\n}\n\nexport function expandGatewaySelection(\n gateway: string,\n options?: { availableGateways?: Iterable<string> },\n): string[] {\n const normalized = normalizeGatewayKey(gateway);\n if (!normalized) {\n return [];\n }\n\n const availableGateways = options?.availableGateways\n ? [...options.availableGateways].map((entry) => normalizeGatewayKey(entry)).filter(Boolean)\n : [];\n\n if (normalized === 'MANUAL') {\n return availableGateways.length > 0\n ? getAvailableManualGatewaySelections(availableGateways)\n : ['MANUAL'];\n }\n\n if (normalized.startsWith('MANUAL:')) {\n return [normalized];\n }\n\n if (normalized === 'CRYPTO') {\n return availableGateways.length > 0\n ? getConcreteCryptoGatewaySelections(availableGateways)\n : [...CRYPTO_GATEWAY_KEYS];\n }\n\n if (isCryptoProviderGatewayKey(normalized)) {\n return getProviderScopedGatewaySelections(\n normalized as keyof typeof DEFAULT_PROVIDER_GATEWAY_SELECTIONS,\n availableGateways,\n );\n }\n\n if (isGenericStablecoinGatewayKey(normalized)) {\n const concreteGateways =\n GENERIC_STABLECOIN_GATEWAY_FAMILIES[\n normalized as keyof typeof GENERIC_STABLECOIN_GATEWAY_FAMILIES\n ];\n\n if (availableGateways.length > 0) {\n const availableSet = new Set(availableGateways);\n return concreteGateways.filter((entry) => availableSet.has(entry));\n }\n\n return [...concreteGateways];\n }\n\n return [normalized];\n}\n\nexport function resolveConcreteGatewaySelections(\n input: unknown,\n options?: { availableGateways?: Iterable<string> },\n): string[] | null {\n const normalized = normalizeGatewayRestrictionInput(input);\n if (!normalized) {\n return null;\n }\n\n const resolved = new Set<string>();\n for (const gateway of normalized) {\n for (const expanded of expandGatewaySelection(gateway, options)) {\n resolved.add(expanded);\n }\n }\n\n return [...resolved];\n}\n\nexport function normalizeCheckoutMethodOrder(\n input: Iterable<string> | null | undefined,\n): CheckoutMethodOrderKey[] {\n if (!input) {\n return [];\n }\n\n const normalized = new Set<CheckoutMethodOrderKey>();\n\n for (const entry of input) {\n if (typeof entry !== 'string') {\n continue;\n }\n\n const candidate = entry.trim().toUpperCase();\n if (CHECKOUT_METHOD_ORDER_KEY_SET.has(candidate)) {\n normalized.add(candidate as CheckoutMethodOrderKey);\n }\n }\n\n return [...normalized];\n}\n\nexport function resolveCheckoutMethodOrder(\n input: Iterable<string> | null | undefined,\n): CheckoutMethodOrderKey[] {\n const normalized = normalizeCheckoutMethodOrder(input);\n const resolved = [...normalized];\n\n for (const key of CHECKOUT_METHOD_ORDER_KEYS) {\n if (!resolved.includes(key)) {\n resolved.push(key);\n }\n }\n\n return resolved;\n}\n\nexport function getCheckoutMethodOrderGroup(\n gateway: string,\n): CheckoutMethodOrderKey | null {\n const normalized = normalizeGatewayKey(gateway);\n if (!normalized) {\n return null;\n }\n\n if (normalized === 'MANUAL' || normalized.startsWith('MANUAL:')) {\n return 'MANUAL';\n }\n\n if (isCryptoProviderGatewayKey(normalized) || isConcreteCryptoGatewayKey(normalized)) {\n return 'CRYPTO';\n }\n\n return CHECKOUT_METHOD_GROUP_BY_GATEWAY[normalized] ?? null;\n}\n\nexport function sortGatewaysByCheckoutMethodOrder(\n gateways: Iterable<string>,\n input: Iterable<string> | null | undefined,\n): string[] {\n const explicitOrder = normalizeCheckoutMethodOrder(input);\n if (explicitOrder.length === 0) {\n return [...gateways];\n }\n\n const resolvedOrder = resolveCheckoutMethodOrder(explicitOrder);\n const orderIndex = new Map(\n resolvedOrder.map((key, index) => [key, index] as const),\n );\n\n return [...gateways].sort((left, right) => {\n const leftGroup = getCheckoutMethodOrderGroup(left);\n const rightGroup = getCheckoutMethodOrderGroup(right);\n const leftIndex = leftGroup ? (orderIndex.get(leftGroup) ?? Number.MAX_SAFE_INTEGER) : Number.MAX_SAFE_INTEGER;\n const rightIndex = rightGroup ? (orderIndex.get(rightGroup) ?? Number.MAX_SAFE_INTEGER) : Number.MAX_SAFE_INTEGER;\n\n if (leftIndex !== rightIndex) {\n return leftIndex - rightIndex;\n }\n\n return 0;\n });\n}\n\nexport function getCheckoutMethodOrderKeysForGateways(\n gateways: Iterable<string>,\n input?: Iterable<string> | null,\n): CheckoutMethodOrderKey[] {\n const orderedGroups = new Set<CheckoutMethodOrderKey>();\n\n for (const gateway of sortGatewaysByCheckoutMethodOrder(gateways, input)) {\n const group = getCheckoutMethodOrderGroup(gateway);\n if (group) {\n orderedGroups.add(group);\n }\n }\n\n return [...orderedGroups];\n}\n\nexport function getCheckoutMethodOrderLabel(key: CheckoutMethodOrderKey): string {\n switch (key) {\n case 'STRIPE':\n return 'Credit / Debit Cards';\n case 'PAYPAL':\n return 'PayPal';\n case 'PAYPAL_FF':\n return 'PayPal F&F';\n case 'MOLLIE':\n return 'Mollie';\n case 'AUTHORIZENET':\n return 'Authorize.net';\n case 'NMI':\n return 'NMI';\n case 'SQUARE':\n return 'Square';\n case 'SUMUP':\n return 'SumUp';\n case 'SHOPIFY':\n return 'Shopify';\n case 'SUBY':\n return 'Suby';\n case 'PANDABASE':\n return 'Pandabase';\n case 'STORRIK':\n return 'Storrik';\n case 'DEBLOMASSI':\n return 'DebloMassi';\n case 'SHOPPEXPAY':\n return 'Card payment';\n case 'MONEYMOTION':\n return 'MoneyMotion';\n case 'OVGC':\n return 'OVGC Payments';\n case 'WHOP':\n return 'Whop';\n case 'DODO':\n return 'Dodo Payments';\n case 'MAVERICK':\n return 'Maverick Payments';\n case 'CASHAPP':\n return 'Cash App';\n case 'VENMO':\n return 'Venmo';\n case 'CRYPTO':\n return 'Crypto';\n case 'CUSTOMER_BALANCE':\n return 'Store Credit';\n case 'MANUAL':\n return 'Manual Payment Methods';\n }\n}\n\nexport const SecretRefSchema = z.object({\n set: z.boolean(),\n});\n\nexport const PaymentGatewayHealthSchema = z.object({\n status: z.enum(['READY', 'NEEDS_ATTENTION']).optional(),\n code: z.string().optional(),\n message: z.string().optional(),\n checked_at: z.string().optional(),\n});\n\nexport const PaymentGatewayStateSchema = z.object({\n provider: z.string(),\n type: z.string(),\n enabled: z.boolean(),\n connected: z.boolean(),\n credentials: z.record(z.string(), SecretRefSchema),\n public_config: z.record(z.string(), z.unknown()),\n webhook: z.record(z.string(), z.unknown()).optional(),\n health: PaymentGatewayHealthSchema.optional(),\n});\n\nexport type PaymentGatewayStateFromSchema = z.infer<typeof PaymentGatewayStateSchema>;\n","import * as z from 'zod/v4';\n\n/** Canonical Shoppex hosted-checkout brand (matches `apps/checkout/app/globals.css` `--primary`). */\nexport const CHECKOUT_PLATFORM_BRAND_COLOR = '#2563eb';\n\n/** Curated font label for Style Center controls (runtime loads Geist via `next/font`). */\nexport const CHECKOUT_PLATFORM_FONT_FAMILY = 'Geist';\n\n/** Stripe/PayPal appearance and CSS var() fallbacks when no merchant brand override exists. */\nexport const CHECKOUT_PLATFORM_BRAND_FALLBACK = CHECKOUT_PLATFORM_BRAND_COLOR;\n\n/** Runtime font stack when no merchant typography override exists. */\nexport const CHECKOUT_PLATFORM_FONT_STACK =\n 'var(--font-geist-sans, Geist), Geist, system-ui, sans-serif';\n\n/** Stripe appearance fontFamily (no CSS var() — provider SDK string). */\nexport const CHECKOUT_PLATFORM_STRIPE_FONT_FAMILY = 'Geist, system-ui, sans-serif';\n\nconst BRAND_DERIVED_TOKEN_KEYS: Partial<Record<string, string>> = {\n 'component.primaryButton.background': 'color.brand',\n 'component.radio.checkedFill': 'color.brand',\n};\n\n/**\n * Platform baseline values for unset checkout tokens.\n * Used by Style Center UI, validation, and documentation — not emitted to live CSS unless explicit.\n */\nexport const CHECKOUT_PLATFORM_BASELINE: Partial<Record<string, string | number>> = {\n 'color.brand': CHECKOUT_PLATFORM_BRAND_COLOR,\n 'color.brandContrast': '#ffffff',\n 'color.background': '#000000',\n 'color.surface': '#18181b',\n 'color.surfaceRaised': '#27272a',\n 'color.text': '#fafafa',\n 'color.textMuted': '#a1a1aa',\n 'color.border': '#222222',\n 'color.focus': CHECKOUT_PLATFORM_BRAND_COLOR,\n 'color.success': '#22c55e',\n 'color.warning': '#f59e0b',\n 'color.error': '#ef4444',\n 'typography.fontFamily': CHECKOUT_PLATFORM_FONT_FAMILY,\n 'typography.baseSize': 14,\n 'shape.buttonRadius': 8,\n 'shape.inputRadius': 8,\n 'shape.cardRadius': 12,\n 'spacing.density': 'comfortable',\n 'spacing.controlHeight': 48,\n 'component.primaryButton.text': '#ffffff',\n 'component.input.background': '#111111',\n 'component.input.border': '#222222',\n 'component.input.focusRing': 'rgba(37,99,235,0.35)',\n 'component.productCard.background': 'rgba(255,255,255,0.03)',\n 'component.productCard.border': 'rgba(255,255,255,0.06)',\n 'component.productCard.shadow': 'none',\n 'component.productImage.background': 'rgba(255,255,255,0.06)',\n 'component.productImage.border': 'rgba(255,255,255,0.04)',\n 'component.productImage.icon': 'rgba(250,250,250,0.4)',\n 'component.brandAvatar.background': 'rgba(255,255,255,0.06)',\n 'component.brandAvatar.text': '#ffffff',\n 'component.brandAvatar.border': 'rgba(255,255,255,0.1)',\n 'component.pill.background': 'rgba(255,255,255,0.04)',\n 'component.pill.border': 'rgba(255,255,255,0.08)',\n 'component.pill.text': '#a1a1aa',\n 'component.errorBanner.background': 'rgba(239,68,68,0.1)',\n 'component.errorBanner.border': 'rgba(239,68,68,0.2)',\n 'component.errorBanner.text': '#ef4444',\n 'component.radio.idleRing': 'rgba(161,161,170,0.5)',\n 'component.radio.checkedIcon': '#ffffff',\n 'component.divider.color': 'rgba(255,255,255,0.06)',\n};\n\nexport function isExplicitCheckoutStyleTokenValue(value: unknown): value is string | number {\n if (typeof value === 'number' && Number.isFinite(value)) return true;\n if (typeof value === 'string') return value.trim().length > 0;\n return false;\n}\n\nfunction resolveCheckoutStyleBrandDerivedTokenKey(key: string): string | undefined {\n return BRAND_DERIVED_TOKEN_KEYS[key];\n}\n\nexport const checkoutStyleSurfaceValues = ['checkout', 'payment_link', 'embed'] as const;\nexport const checkoutEmbedDesignValues = ['current', 'clean-light', 'clean-dark', 'v2', 'v3'] as const;\nexport const checkoutStyleDensityValues = ['comfortable', 'compact'] as const;\nexport const checkoutStyleModeValues = ['light', 'dark', 'system'] as const;\nexport const checkoutStylePaymentLinkHeroPositionValues = ['top', 'side', 'background'] as const;\nexport const embedCloseButtonStyleValues = ['ghost', 'outlined', 'filled'] as const;\nexport const embedMobileLayoutValues = ['sheet', 'fullscreen', 'center'] as const;\nexport const embedContentVisibilityValues = ['visible', 'hidden'] as const;\nexport const checkoutStyleManagedAssetHostValues = ['assets.shoppex.io', 'cdn.shoppex.io', 'imagedelivery.net'] as const;\n\nexport const CheckoutStyleSurfaceSchema = z.enum(checkoutStyleSurfaceValues);\nexport const CheckoutEmbedDesignSchema = z.enum(checkoutEmbedDesignValues);\nexport const CheckoutStyleDensitySchema = z.enum(checkoutStyleDensityValues);\nexport const CheckoutStyleModeSchema = z.enum(checkoutStyleModeValues);\nexport const CheckoutStylePaymentLinkHeroPositionSchema = z.enum(checkoutStylePaymentLinkHeroPositionValues);\nexport const EmbedCloseButtonStyleSchema = z.enum(embedCloseButtonStyleValues);\nexport const EmbedMobileLayoutSchema = z.enum(embedMobileLayoutValues);\nexport const EmbedContentVisibilitySchema = z.enum(embedContentVisibilityValues);\n\nexport type CheckoutStyleSurface = z.infer<typeof CheckoutStyleSurfaceSchema>;\nexport type CheckoutEmbedDesign = z.infer<typeof CheckoutEmbedDesignSchema>;\nexport type CheckoutStyleDensity = z.infer<typeof CheckoutStyleDensitySchema>;\nexport type CheckoutStyleMode = z.infer<typeof CheckoutStyleModeSchema>;\nexport type CheckoutStylePaymentLinkHeroPosition = z.infer<typeof CheckoutStylePaymentLinkHeroPositionSchema>;\nexport type EmbedCloseButtonStyle = z.infer<typeof EmbedCloseButtonStyleSchema>;\nexport type EmbedMobileLayout = z.infer<typeof EmbedMobileLayoutSchema>;\nexport type EmbedContentVisibility = z.infer<typeof EmbedContentVisibilitySchema>;\n\nexport const CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION = 1;\nexport const SHOPPEX_STYLE_THEME_EXPORT_FORMAT_VERSION = 2;\n\nexport type CheckoutStyleTokenType = 'asset_url' | 'color' | 'font' | 'number' | 'select' | 'shadow';\nexport type CheckoutStyleTokenGroup = 'asset' | 'brand' | 'color' | 'typography' | 'shape' | 'spacing' | 'component' | 'embed';\n\nexport type CheckoutStyleCssTokenDefinition = {\n key: string;\n cssVar: `--spx-checkout-${string}` | `--spx-embed-${string}`;\n group: Exclude<CheckoutStyleTokenGroup, 'asset'>;\n type: Exclude<CheckoutStyleTokenType, 'asset_url'>;\n default: string | number;\n min?: number;\n max?: number;\n step?: number;\n unit?: 'px' | 'rem';\n allowedValues?: readonly string[];\n protected?: boolean;\n};\n\nexport type CheckoutStyleAssetTokenDefinition = {\n key: string;\n group: 'asset';\n type: 'asset_url' | 'number' | 'select';\n default: string | number | null;\n accept?: readonly string[];\n maxBytes?: number;\n min?: number;\n max?: number;\n step?: number;\n unit?: 'px';\n allowedValues?: readonly string[];\n surface?: CheckoutStyleSurface;\n};\n\nexport type CheckoutStyleTokenDefinition = CheckoutStyleCssTokenDefinition | CheckoutStyleAssetTokenDefinition;\n\nexport const checkoutStyleTokenDefinitions = [\n { key: 'color.brand', cssVar: '--spx-checkout-brand', group: 'brand', type: 'color', default: CHECKOUT_PLATFORM_BRAND_COLOR },\n { key: 'color.brandContrast', cssVar: '--spx-checkout-brand-contrast', group: 'brand', type: 'color', default: '#ffffff', protected: true },\n // Empty default → CSS variable is omitted by createCheckoutStyleCssVariables,\n // so the layout's `var(--spx-checkout-bg, fallback)` resolves to the original\n // Tailwind/ambient-gradient fallback for shops that haven't customised the\n // background. Setting an explicit hex would clobber the ambient gradient and\n // the right-panel `--surface-2` accent for every default-theme checkout.\n { key: 'color.background', cssVar: '--spx-checkout-bg', group: 'color', type: 'color', default: '' },\n { key: 'color.surface', cssVar: '--spx-checkout-surface', group: 'color', type: 'color', default: '#18181b' },\n { key: 'color.surfaceRaised', cssVar: '--spx-checkout-surface-raised', group: 'color', type: 'color', default: '#27272a' },\n { key: 'color.text', cssVar: '--spx-checkout-text', group: 'color', type: 'color', default: '#fafafa', protected: true },\n { key: 'color.textMuted', cssVar: '--spx-checkout-text-muted', group: 'color', type: 'color', default: '#a1a1aa' },\n // Default '#3f3f46' (zinc-700) feeds many runtime-style fallbacks for\n // payment-method cards, product cards, pills, and inputs. Setting it to ''\n // would turn those slots' `var(--spx-checkout-border, currentColor)` into\n // bright text-color borders. The grey-divider regression on the aside is\n // fixed in the layout file by using the Tailwind `border-border` class\n // instead of binding to this token, which keeps both concerns separated.\n { key: 'color.border', cssVar: '--spx-checkout-border', group: 'color', type: 'color', default: '#222222' },\n { key: 'color.focus', cssVar: '--spx-checkout-focus', group: 'color', type: 'color', default: CHECKOUT_PLATFORM_BRAND_COLOR, protected: true },\n { key: 'color.success', cssVar: '--spx-checkout-success', group: 'color', type: 'color', default: '#22c55e', protected: true },\n { key: 'color.warning', cssVar: '--spx-checkout-warning', group: 'color', type: 'color', default: '#f59e0b', protected: true },\n { key: 'color.error', cssVar: '--spx-checkout-error', group: 'color', type: 'color', default: '#ef4444', protected: true },\n { key: 'typography.fontFamily', cssVar: '--spx-checkout-font', group: 'typography', type: 'font', default: CHECKOUT_PLATFORM_FONT_FAMILY },\n // Optional Google Fonts family. Empty default → CSS variable is omitted\n // so the curated fontFamily wins. When set, the storefront also injects\n // a <link rel=\"stylesheet\"> to fonts.googleapis.com so the family is\n // actually loaded.\n { key: 'typography.googleFontFamily', cssVar: '--spx-checkout-google-font', group: 'typography', type: 'font', default: '' },\n { key: 'typography.baseSize', cssVar: '--spx-checkout-font-size', group: 'typography', type: 'number', default: 14, min: 12, max: 18, step: 1, unit: 'px' },\n { key: 'shape.buttonRadius', cssVar: '--spx-checkout-button-radius', group: 'shape', type: 'number', default: 8, min: 0, max: 24, step: 1, unit: 'px' },\n { key: 'shape.inputRadius', cssVar: '--spx-checkout-input-radius', group: 'shape', type: 'number', default: 8, min: 0, max: 24, step: 1, unit: 'px' },\n { key: 'shape.cardRadius', cssVar: '--spx-checkout-card-radius', group: 'shape', type: 'number', default: 12, min: 0, max: 28, step: 1, unit: 'px' },\n {\n key: 'spacing.density',\n cssVar: '--spx-checkout-density',\n group: 'spacing',\n type: 'select',\n default: 'comfortable',\n allowedValues: checkoutStyleDensityValues,\n },\n { key: 'spacing.controlHeight', cssVar: '--spx-checkout-control-height', group: 'spacing', type: 'number', default: 48, min: 36, max: 56, step: 2, unit: 'px' },\n { key: 'component.primaryButton.background', cssVar: '--spx-checkout-button-bg', group: 'component', type: 'color', default: '', protected: true },\n { key: 'component.primaryButton.text', cssVar: '--spx-checkout-button-text', group: 'component', type: 'color', default: '#ffffff', protected: true },\n { key: 'component.input.background', cssVar: '--spx-checkout-input-bg', group: 'component', type: 'color', default: '#111111' },\n { key: 'component.input.border', cssVar: '--spx-checkout-input-border', group: 'component', type: 'color', default: '#222222' },\n { key: 'component.input.focusRing', cssVar: '--spx-checkout-input-focus-ring', group: 'component', type: 'color', default: '' },\n // Default '' is filtered out by the preview-iframe normaliser, so the\n // CSS fallback chain on [data-spx-slot=\"summary.panel\"] resolves to\n // --spx-checkout-bg when no merchant override is set. A merchant who\n // only edits color.background therefore sees the aside follow that\n // change without an explicit summary override.\n { key: 'component.summary.background', cssVar: '--spx-checkout-summary-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.paymentMethod.background', cssVar: '--spx-checkout-payment-method-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.paymentMethod.cardBackground', cssVar: '--spx-checkout-payment-method-card-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.paymentMethod.border', cssVar: '--spx-checkout-payment-method-border', group: 'component', type: 'color', default: '' },\n { key: 'component.paymentMethod.selectedBackground', cssVar: '--spx-checkout-payment-method-selected-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.checkoutHeader.background', cssVar: '--spx-checkout-embed-header-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.checkoutHeader.text', cssVar: '--spx-checkout-embed-header-text', group: 'component', type: 'color', default: '' },\n { key: 'component.productCard.background', cssVar: '--spx-checkout-product-card-bg', group: 'component', type: 'color', default: 'rgba(255,255,255,0.03)' },\n { key: 'component.productCard.border', cssVar: '--spx-checkout-product-card-border', group: 'component', type: 'color', default: 'rgba(255,255,255,0.06)' },\n { key: 'component.productCard.shadow', cssVar: '--spx-checkout-product-card-shadow', group: 'component', type: 'shadow', default: 'none' },\n { key: 'component.productImage.background', cssVar: '--spx-checkout-product-image-bg', group: 'component', type: 'color', default: 'rgba(255,255,255,0.06)' },\n { key: 'component.productImage.border', cssVar: '--spx-checkout-product-image-border', group: 'component', type: 'color', default: 'rgba(255,255,255,0.04)' },\n { key: 'component.productImage.icon', cssVar: '--spx-checkout-product-image-icon', group: 'component', type: 'color', default: 'rgba(250,250,250,0.4)' },\n { key: 'component.brandAvatar.background', cssVar: '--spx-checkout-brand-avatar-bg', group: 'component', type: 'color', default: 'rgba(255,255,255,0.06)' },\n { key: 'component.brandAvatar.text', cssVar: '--spx-checkout-brand-avatar-text', group: 'component', type: 'color', default: '#ffffff' },\n { key: 'component.brandAvatar.border', cssVar: '--spx-checkout-brand-avatar-border', group: 'component', type: 'color', default: 'rgba(255,255,255,0.1)' },\n { key: 'component.pill.background', cssVar: '--spx-checkout-pill-bg', group: 'component', type: 'color', default: 'rgba(255,255,255,0.04)' },\n { key: 'component.pill.border', cssVar: '--spx-checkout-pill-border', group: 'component', type: 'color', default: 'rgba(255,255,255,0.08)' },\n { key: 'component.pill.text', cssVar: '--spx-checkout-pill-text', group: 'component', type: 'color', default: '#a1a1aa' },\n { key: 'component.errorBanner.background', cssVar: '--spx-checkout-error-bg', group: 'component', type: 'color', default: 'rgba(239,68,68,0.1)' },\n { key: 'component.errorBanner.border', cssVar: '--spx-checkout-error-border', group: 'component', type: 'color', default: 'rgba(239,68,68,0.2)' },\n { key: 'component.errorBanner.text', cssVar: '--spx-checkout-error-text', group: 'component', type: 'color', default: '#ef4444' },\n { key: 'component.warningBanner.background', cssVar: '--spx-checkout-warning-bg', group: 'component', type: 'color', default: '' },\n { key: 'component.warningBanner.border', cssVar: '--spx-checkout-warning-border', group: 'component', type: 'color', default: '' },\n { key: 'component.warningBanner.text', cssVar: '--spx-checkout-warning-text', group: 'component', type: 'color', default: '' },\n { key: 'component.radio.idleRing', cssVar: '--spx-checkout-radio-idle-ring', group: 'component', type: 'color', default: 'rgba(161,161,170,0.5)' },\n { key: 'component.radio.checkedFill', cssVar: '--spx-checkout-radio-checked-fill', group: 'component', type: 'color', default: '' },\n { key: 'component.radio.checkedIcon', cssVar: '--spx-checkout-radio-checked-icon', group: 'component', type: 'color', default: '#ffffff' },\n { key: 'component.divider.color', cssVar: '--spx-checkout-divider', group: 'component', type: 'color', default: 'rgba(255,255,255,0.06)' },\n] as const satisfies readonly CheckoutStyleCssTokenDefinition[];\n\nexport const checkoutStyleAssetTokenDefinitions = [\n {\n key: 'brand.logoUrl',\n group: 'asset',\n type: 'asset_url',\n default: null,\n accept: ['image/png', 'image/jpeg', 'image/svg+xml', 'image/webp'],\n maxBytes: 512_000,\n },\n {\n key: 'brand.logoDarkUrl',\n group: 'asset',\n type: 'asset_url',\n default: null,\n accept: ['image/png', 'image/jpeg', 'image/svg+xml', 'image/webp'],\n maxBytes: 512_000,\n },\n {\n key: 'brand.logoMaxHeight',\n group: 'asset',\n type: 'number',\n default: 32,\n min: 16,\n max: 80,\n step: 2,\n unit: 'px',\n },\n {\n key: 'brand.faviconUrl',\n group: 'asset',\n type: 'asset_url',\n default: null,\n accept: ['image/png', 'image/x-icon', 'image/svg+xml'],\n maxBytes: 64_000,\n },\n {\n key: 'paymentLink.heroImageUrl',\n group: 'asset',\n type: 'asset_url',\n default: null,\n accept: ['image/png', 'image/jpeg', 'image/webp'],\n maxBytes: 1_048_576,\n surface: 'payment_link',\n },\n {\n key: 'paymentLink.heroPosition',\n group: 'asset',\n type: 'select',\n default: 'top',\n allowedValues: checkoutStylePaymentLinkHeroPositionValues,\n surface: 'payment_link',\n },\n] as const satisfies readonly CheckoutStyleAssetTokenDefinition[];\n\nexport const checkoutStyleControlTokenDefinitions = [\n ...checkoutStyleTokenDefinitions,\n ...checkoutStyleAssetTokenDefinitions,\n] as const satisfies readonly CheckoutStyleTokenDefinition[];\n\nexport type CheckoutStyleTokenKey = typeof checkoutStyleTokenDefinitions[number]['key'];\nexport type CheckoutStyleControlTokenKey = typeof checkoutStyleControlTokenDefinitions[number]['key'];\nexport type CheckoutStyleCssVariable = typeof checkoutStyleTokenDefinitions[number]['cssVar'];\n\nexport const embedStyleTokenDefinitions = [\n { key: 'embed.launcher.background', cssVar: '--spx-embed-launcher-background', group: 'embed', type: 'color', default: '#7c5cff' },\n { key: 'embed.launcher.text', cssVar: '--spx-embed-launcher-text', group: 'embed', type: 'color', default: '#ffffff', protected: true },\n { key: 'embed.launcher.radius', cssVar: '--spx-embed-launcher-radius', group: 'embed', type: 'number', default: 10, min: 0, max: 28, step: 1, unit: 'px' },\n { key: 'embed.launcher.paddingX', cssVar: '--spx-embed-launcher-padding-x', group: 'embed', type: 'number', default: 18, min: 8, max: 32, step: 1, unit: 'px' },\n { key: 'embed.launcher.paddingY', cssVar: '--spx-embed-launcher-padding-y', group: 'embed', type: 'number', default: 12, min: 6, max: 24, step: 1, unit: 'px' },\n { key: 'embed.launcher.shadow', cssVar: '--spx-embed-launcher-shadow', group: 'embed', type: 'shadow', default: '0 12px 32px rgba(0,0,0,0.18)' },\n { key: 'embed.productCard.background', cssVar: '--spx-embed-product-card-background', group: 'embed', type: 'color', default: '#ffffff' },\n { key: 'embed.productCard.border', cssVar: '--spx-embed-product-card-border', group: 'embed', type: 'color', default: 'rgba(24,24,27,0.12)' },\n { key: 'embed.productCard.imageRadius', cssVar: '--spx-embed-product-card-image-radius', group: 'embed', type: 'number', default: 8, min: 0, max: 24, step: 1, unit: 'px' },\n { key: 'embed.productCard.padding', cssVar: '--spx-embed-product-card-padding', group: 'embed', type: 'number', default: 16, min: 8, max: 32, step: 1, unit: 'px' },\n { key: 'embed.cart.background', cssVar: '--spx-embed-cart-background', group: 'embed', type: 'color', default: '#ffffff' },\n { key: 'embed.cart.rowBorder', cssVar: '--spx-embed-cart-row-border', group: 'embed', type: 'color', default: 'rgba(24,24,27,0.1)' },\n { key: 'embed.cart.itemSpacing', cssVar: '--spx-embed-cart-item-spacing', group: 'embed', type: 'number', default: 12, min: 4, max: 28, step: 1, unit: 'px' },\n { key: 'embed.modal.background', cssVar: '--spx-embed-modal-background', group: 'embed', type: 'color', default: '#ffffff' },\n { key: 'embed.modal.radius', cssVar: '--spx-embed-modal-radius', group: 'embed', type: 'number', default: 16, min: 0, max: 32, step: 1, unit: 'px' },\n { key: 'embed.modal.maxWidth', cssVar: '--spx-embed-modal-max-width', group: 'embed', type: 'number', default: 560, min: 360, max: 960, step: 20, unit: 'px' },\n { key: 'embed.modal.shadow', cssVar: '--spx-embed-modal-shadow', group: 'embed', type: 'shadow', default: '0 20px 60px rgba(0,0,0,0.2)' },\n { key: 'embed.backdrop.color', cssVar: '--spx-embed-backdrop-color', group: 'embed', type: 'color', default: 'rgba(0,0,0,0.6)' },\n { key: 'embed.backdrop.blur', cssVar: '--spx-embed-backdrop-blur', group: 'embed', type: 'number', default: 4, min: 0, max: 24, step: 1, unit: 'px' },\n { key: 'embed.backdrop.opacity', cssVar: '--spx-embed-backdrop-opacity', group: 'embed', type: 'number', default: 1, min: 0, max: 1, step: 0.05 },\n { key: 'embed.skeleton.background', cssVar: '--spx-embed-skeleton-background', group: 'embed', type: 'color', default: '#f4f4f5' },\n { key: 'embed.skeleton.shimmer', cssVar: '--spx-embed-skeleton-shimmer', group: 'embed', type: 'color', default: '#e8e8ec' },\n { key: 'embed.spinner.color', cssVar: '--spx-embed-spinner-color', group: 'embed', type: 'color', default: '#7c5cff' },\n {\n key: 'embed.closeButton.style',\n cssVar: '--spx-embed-close-button-style',\n group: 'embed',\n type: 'select',\n default: 'ghost',\n allowedValues: embedCloseButtonStyleValues,\n },\n {\n key: 'embed.mobile.layout',\n cssVar: '--spx-embed-mobile-layout',\n group: 'embed',\n type: 'select',\n default: 'sheet',\n allowedValues: embedMobileLayoutValues,\n },\n {\n key: 'embed.content.productDescription',\n cssVar: '--spx-embed-product-description-visibility',\n group: 'embed',\n type: 'select',\n default: 'visible',\n allowedValues: embedContentVisibilityValues,\n },\n {\n key: 'embed.content.termsShortcut',\n cssVar: '--spx-embed-terms-shortcut-visibility',\n group: 'embed',\n type: 'select',\n default: 'visible',\n allowedValues: embedContentVisibilityValues,\n },\n] as const satisfies readonly CheckoutStyleCssTokenDefinition[];\n\nexport type EmbedStyleTokenKey = typeof embedStyleTokenDefinitions[number]['key'];\nexport type EmbedStyleCssVariable = typeof embedStyleTokenDefinitions[number]['cssVar'];\n\nexport type EmbedStyleCssVariableOptions = {\n mode?: CheckoutStyleMode;\n embedDesign?: CheckoutEmbedDesign;\n};\n\nexport const checkoutStyleSlotValues = [\n 'checkout.shell',\n 'checkout.panel',\n 'checkout.header',\n 'brand.logo',\n 'product.card',\n 'product.image',\n 'product.title',\n 'product.description',\n 'product.price',\n 'product.quantity',\n 'product.addon',\n 'paymentLink.hero',\n 'summary.panel',\n 'summary.line',\n 'summary.total',\n 'form.field',\n 'form.label',\n 'form.help',\n 'coupon.input',\n 'input.base',\n 'input.error',\n 'button.primary',\n 'button.secondary',\n 'payment.methods',\n 'payment.method',\n 'payment.method.icon',\n 'payment.method.label',\n 'payment.method.meta',\n 'payment.method.fee',\n 'payment.method.indicator',\n 'payment.provider_widget',\n 'payment.loading',\n 'payment.error',\n 'payment.warning',\n 'legal.terms',\n 'status.success',\n 'status.processing',\n 'embed.launcher',\n 'embed.launcher.icon',\n 'embed.productCard',\n 'embed.productCard.image',\n 'embed.productCard.title',\n 'embed.productCard.price',\n 'embed.cart',\n 'embed.cart.row',\n 'embed.cart.summary',\n 'embed.modal',\n 'embed.modal.header',\n 'embed.modal.close',\n 'embed.skeleton',\n 'embed.loader',\n 'embed.branding',\n] as const;\n\nexport const checkoutStyleProtectedSlotValues = [\n 'product.title',\n 'product.price',\n 'summary.total',\n 'payment.method.label',\n 'payment.provider_widget',\n 'payment.loading',\n 'payment.error',\n 'payment.warning',\n 'legal.terms',\n 'status.success',\n 'status.processing',\n 'embed.modal.close',\n 'embed.branding',\n] as const;\n\nexport const CheckoutStyleSlotSchema = z.enum(checkoutStyleSlotValues);\nexport const CheckoutStyleProtectedSlotSchema = z.enum(checkoutStyleProtectedSlotValues);\n\nexport type CheckoutStyleSlot = z.infer<typeof CheckoutStyleSlotSchema>;\nexport type CheckoutStyleProtectedSlot = z.infer<typeof CheckoutStyleProtectedSlotSchema>;\n\nconst HexColorSchema = z.string().regex(/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/, 'Use a valid hex color');\n// Permissive color schema for composite values (rgba, gradients, color-mix)\n// used by token slots that aren't simple solid color picks. The CSS pipeline\n// is the consumer; we just guard against unbounded length and obviously\n// suspicious payloads (no semicolons, no curly braces, no @-rules).\nconst ExtendedColorSchema = z.string().trim().min(1).max(200).refine(\n (value) => !/[;{}]|@import|expression\\s*\\(/i.test(value),\n 'Use a valid CSS color or gradient',\n);\nconst ShadowSchema = z.string().trim().min(1).max(400).refine(\n (value) => !/[;{}]|@import|expression\\s*\\(/i.test(value),\n 'Use a valid CSS box-shadow value',\n);\n// Curated font list — the families the Style Center dropdown offers. Every\n// value here is served without a third-party request: the nine web families are\n// bundled by `next/font/google` in `apps/checkout/app/layout.tsx`, and \"Arial\" /\n// \"System UI\" come from the OS. A payment page must not hand the buyer's IP to\n// fonts.googleapis.com, so a family added here MUST also be added to\n// `app/layout.tsx` and to both maps in `apps/checkout/lib/checkout-style.tsx`\n// (LOCALLY_LOADED_FONTS + LOCAL_FONT_FAMILY_TOKENS); the checkout font-stack\n// test fails otherwise. Order matters: it drives both the dropdown in the\n// editor and the type-checked union here.\nexport const curatedFontValues = [\n 'Inter',\n 'Geist',\n 'Manrope',\n 'Plus Jakarta Sans',\n 'DM Sans',\n 'Space Grotesk',\n 'Sora',\n 'IBM Plex Sans',\n 'JetBrains Mono',\n 'Arial',\n 'System UI',\n] as const;\nconst CuratedFontSchema = z.enum(curatedFontValues);\n\n// Google Fonts family schema — accepts a single Google-hosted family name\n// like \"Source Serif 4\" or \"Crimson Pro\". Restricted to the character set\n// Google Fonts permits in family names (alphanumerics, spaces, +, -, _,\n// digits) and capped at 60 chars to avoid abuse via giant CSS imports.\nconst GoogleFontFamilySchema = z\n .string()\n .trim()\n .min(1)\n .max(60)\n .regex(/^[A-Za-z0-9 +\\-_]+$/, 'Use a Google Fonts family name');\nconst AssetUrlSchema = z.string().url();\n\nexport function isCheckoutStyleManagedAssetUrl(value: string): boolean {\n try {\n const url = new URL(value);\n return url.protocol === 'https:' && checkoutStyleManagedAssetHostValues.includes(\n url.hostname as typeof checkoutStyleManagedAssetHostValues[number],\n );\n } catch {\n return false;\n }\n}\n\nexport const CheckoutStyleTokensSchema = z.object({\n brand: z.object({\n logoUrl: AssetUrlSchema.optional().nullable(),\n logoDarkUrl: AssetUrlSchema.optional().nullable(),\n logoMaxHeight: z.number().int().min(16).max(80).optional(),\n faviconUrl: AssetUrlSchema.optional().nullable(),\n }).strict().optional(),\n color: z.object({\n brand: HexColorSchema.optional(),\n brandContrast: HexColorSchema.optional(),\n background: HexColorSchema.optional(),\n surface: HexColorSchema.optional(),\n surfaceRaised: HexColorSchema.optional(),\n text: HexColorSchema.optional(),\n textMuted: HexColorSchema.optional(),\n border: HexColorSchema.optional(),\n focus: HexColorSchema.optional(),\n success: HexColorSchema.optional(),\n warning: HexColorSchema.optional(),\n error: HexColorSchema.optional(),\n }).strict().optional(),\n typography: z.object({\n fontFamily: CuratedFontSchema.optional(),\n // Optional Google Fonts override. When set, the storefront injects the\n // fonts.googleapis.com stylesheet and uses this family in addition to\n // (or instead of) the curated fontFamily as the leftmost name in the\n // CSS font stack.\n googleFontFamily: GoogleFontFamilySchema.optional(),\n baseSize: z.number().int().min(12).max(18).optional(),\n }).strict().optional(),\n shape: z.object({\n buttonRadius: z.number().int().min(0).max(24).optional(),\n inputRadius: z.number().int().min(0).max(24).optional(),\n cardRadius: z.number().int().min(0).max(28).optional(),\n }).strict().optional(),\n spacing: z.object({\n density: CheckoutStyleDensitySchema.optional(),\n controlHeight: z.number().int().min(36).max(56).optional(),\n }).strict().optional(),\n component: z.object({\n primaryButton: z.object({\n background: HexColorSchema.optional(),\n text: HexColorSchema.optional(),\n }).strict().optional(),\n input: z.object({\n background: HexColorSchema.optional(),\n border: HexColorSchema.optional(),\n focusRing: ExtendedColorSchema.optional(),\n }).strict().optional(),\n summary: z.object({\n background: HexColorSchema.optional(),\n }).strict().optional(),\n paymentMethod: z.object({\n background: ExtendedColorSchema.optional(),\n cardBackground: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n selectedBackground: ExtendedColorSchema.optional(),\n }).strict().optional(),\n productCard: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n shadow: ShadowSchema.optional(),\n }).strict().optional(),\n productImage: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n icon: ExtendedColorSchema.optional(),\n }).strict().optional(),\n brandAvatar: z.object({\n background: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n }).strict().optional(),\n pill: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n }).strict().optional(),\n errorBanner: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n }).strict().optional(),\n warningBanner: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n }).strict().optional(),\n radio: z.object({\n idleRing: ExtendedColorSchema.optional(),\n checkedFill: HexColorSchema.optional(),\n checkedIcon: HexColorSchema.optional(),\n }).strict().optional(),\n divider: z.object({\n color: ExtendedColorSchema.optional(),\n }).strict().optional(),\n }).strict().optional(),\n paymentLink: z.object({\n heroImageUrl: AssetUrlSchema.optional().nullable(),\n heroPosition: CheckoutStylePaymentLinkHeroPositionSchema.optional(),\n }).strict().optional(),\n embed: z.object({\n launcher: z.object({\n background: ExtendedColorSchema.optional(),\n text: HexColorSchema.optional(),\n radius: z.number().int().min(0).max(28).optional(),\n paddingX: z.number().int().min(8).max(32).optional(),\n paddingY: z.number().int().min(6).max(24).optional(),\n shadow: ShadowSchema.optional(),\n }).strict().optional(),\n productCard: z.object({\n background: ExtendedColorSchema.optional(),\n border: ExtendedColorSchema.optional(),\n imageRadius: z.number().int().min(0).max(24).optional(),\n padding: z.number().int().min(8).max(32).optional(),\n }).strict().optional(),\n cart: z.object({\n background: ExtendedColorSchema.optional(),\n rowBorder: ExtendedColorSchema.optional(),\n itemSpacing: z.number().int().min(4).max(28).optional(),\n }).strict().optional(),\n modal: z.object({\n background: ExtendedColorSchema.optional(),\n radius: z.number().int().min(0).max(32).optional(),\n maxWidth: z.number().int().min(360).max(960).optional(),\n shadow: ShadowSchema.optional(),\n }).strict().optional(),\n backdrop: z.object({\n color: ExtendedColorSchema.optional(),\n blur: z.number().int().min(0).max(24).optional(),\n opacity: z.number().min(0).max(1).optional(),\n }).strict().optional(),\n skeleton: z.object({\n background: ExtendedColorSchema.optional(),\n shimmer: ExtendedColorSchema.optional(),\n }).strict().optional(),\n spinner: z.object({\n color: ExtendedColorSchema.optional(),\n }).strict().optional(),\n closeButton: z.object({\n style: EmbedCloseButtonStyleSchema.optional(),\n }).strict().optional(),\n mobile: z.object({\n layout: EmbedMobileLayoutSchema.optional(),\n }).strict().optional(),\n content: z.object({\n productDescription: EmbedContentVisibilitySchema.optional(),\n termsShortcut: EmbedContentVisibilitySchema.optional(),\n }).strict().optional(),\n }).strict().optional(),\n}).strict();\n\nexport type CheckoutStyleTokens = z.infer<typeof CheckoutStyleTokensSchema>;\n\nexport const CheckoutStyleSettingsSchema = z.object({\n mode: CheckoutStyleModeSchema.default('system'),\n fontSource: z.enum(['curated']).default('curated'),\n}).strict();\n\nexport type CheckoutStyleSettings = z.infer<typeof CheckoutStyleSettingsSchema>;\n\nexport const StyleThemeShareModeSchema = z.enum(['standalone', 'bundle', 'pointer']);\nexport type StyleThemeShareMode = z.infer<typeof StyleThemeShareModeSchema>;\n\nexport const StyleThemeParentHintSchema = z.object({\n name: z.string().trim().min(1).max(80),\n fingerprint: z.string().trim().min(1).max(128),\n}).strict();\n\nexport const CheckoutStyleBundledParentThemeExportSchema = z.object({\n type: z.literal('shoppex.style_theme'),\n surface: z.literal('checkout'),\n format_version: z.union([\n z.literal(1),\n z.literal(SHOPPEX_STYLE_THEME_EXPORT_FORMAT_VERSION),\n ]),\n name: z.string().trim().min(1).max(80),\n description: z.string().trim().max(240).optional(),\n embed_design: CheckoutEmbedDesignSchema.default('current'),\n token_schema_version: z.literal(CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION),\n tokens: CheckoutStyleTokensSchema.default({}),\n custom_css: z.string().max(20_000).default(''),\n settings: CheckoutStyleSettingsSchema.default({ mode: 'system', fontSource: 'curated' }),\n _meta: z.record(z.string(), z.unknown()).optional(),\n}).strict();\n\nexport const CheckoutStyleThemeExportSchema = z.object({\n type: z.literal('shoppex.style_theme'),\n surface: CheckoutStyleSurfaceSchema,\n format_version: z.union([\n z.literal(1),\n z.literal(SHOPPEX_STYLE_THEME_EXPORT_FORMAT_VERSION),\n ]),\n name: z.string().trim().min(1).max(80),\n description: z.string().trim().max(240).optional(),\n embed_design: CheckoutEmbedDesignSchema.default('current'),\n token_schema_version: z.literal(CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION),\n tokens: CheckoutStyleTokensSchema.default({}),\n custom_css: z.string().max(20_000).default(''),\n settings: CheckoutStyleSettingsSchema.default({ mode: 'system', fontSource: 'curated' }),\n share_mode: StyleThemeShareModeSchema.default('standalone'),\n parent_hint: StyleThemeParentHintSchema.optional(),\n bundled_parent: CheckoutStyleBundledParentThemeExportSchema.optional(),\n _meta: z.record(z.string(), z.unknown()).optional(),\n}).strict();\n\nexport type CheckoutStyleThemeExport = z.infer<typeof CheckoutStyleThemeExportSchema>;\n\nexport const ResolvedCheckoutStyleSchema = z.object({\n theme_id: z.string().uuid().nullable(),\n surface: CheckoutStyleSurfaceSchema,\n embed_design: CheckoutEmbedDesignSchema,\n token_schema_version: z.literal(CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION),\n revision: z.number().int().min(1),\n tokens: CheckoutStyleTokensSchema,\n custom_css: z.string(),\n css_variables: z.record(z.string(), z.string()),\n}).strict();\n\nexport type ResolvedCheckoutStyle = z.infer<typeof ResolvedCheckoutStyleSchema>;\n\nexport const ResolvedEmbedStyleSchema = z.object({\n theme_id: z.string().uuid().nullable(),\n parent_theme_id: z.string().uuid().nullable(),\n surface: z.literal('embed'),\n embed_design: CheckoutEmbedDesignSchema,\n token_schema_version: z.literal(CHECKOUT_STYLE_TOKEN_SCHEMA_VERSION),\n revision: z.number().int().min(1),\n parent_revision: z.number().int().min(1).nullable(),\n tokens: CheckoutStyleTokensSchema,\n custom_css: z.string(),\n css_variables: z.record(z.string(), z.string()),\n}).strict();\n\nexport type ResolvedEmbedStyle = z.infer<typeof ResolvedEmbedStyleSchema>;\n\n/** Canonical embed runtime contract shared by SDK shell and checkout iframe. */\nexport const EmbedRuntimeStyleSchema = ResolvedEmbedStyleSchema;\nexport type EmbedRuntimeStyle = ResolvedEmbedStyle;\n\nexport const EmbedRuntimeSessionContextSchema = z.object({\n shop_id: z.string().uuid(),\n product_id: z.string().uuid().nullable(),\n product_group_id: z.string().uuid().nullable(),\n payment_link_id: z.string().uuid().nullable(),\n invoice_id: z.string().nullable(),\n}).strict();\n\nexport type EmbedRuntimeSessionContext = z.infer<typeof EmbedRuntimeSessionContextSchema>;\n\nexport const EmbedRuntimeThemeResponseSchema = z.object({\n embed_runtime: z.string().min(16).max(128),\n embed_design: CheckoutEmbedDesignSchema,\n revision: z.number().int().min(1),\n parent_revision: z.number().int().min(1).nullable(),\n theme_id: z.string().uuid().nullable(),\n css_variables: z.record(z.string(), z.string()),\n custom_css: z.string(),\n}).strict();\n\nexport type EmbedRuntimeThemeResponse = z.infer<typeof EmbedRuntimeThemeResponseSchema>;\n\nexport const EmbedRuntimeTransportSchema = z.object({\n embed_design: CheckoutEmbedDesignSchema.optional(),\n embed_style_revision: z.coerce.number().int().min(1).optional(),\n embed_runtime: z.string().min(16).max(128).optional(),\n preview: z.boolean().optional(),\n}).strict();\n\nexport type EmbedRuntimeTransport = z.infer<typeof EmbedRuntimeTransportSchema>;\n\nfunction readPath(input: unknown, path: string): unknown {\n return path.split('.').reduce<unknown>((current, segment) => {\n if (!current || typeof current !== 'object' || Array.isArray(current)) return undefined;\n return (current as Record<string, unknown>)[segment];\n }, input);\n}\n\nfunction formatCssValue(definition: CheckoutStyleTokenDefinition, value: string | number): string {\n if (definition.type === 'number' && definition.unit) {\n return `${value}${definition.unit}`;\n }\n\n // Multi-word font family names must be quoted so they survive var()\n // substitution into a font-family list. Single-word names like \"Inter\"\n // or generic keywords are left bare so they keep their generic-family\n // semantics.\n if (definition.type === 'font' && typeof value === 'string') {\n const trimmed = value.trim();\n if (trimmed.length === 0) return '';\n if (/\\s/.test(trimmed) && !/^['\"]/.test(trimmed)) {\n return `\"${trimmed.replace(/\"/g, '\\\\\"')}\"`;\n }\n return trimmed;\n }\n\n return String(value);\n}\n\nexport function resolveCheckoutStyleTokenValue(\n tokens: CheckoutStyleTokens,\n key: CheckoutStyleTokenKey,\n options: { parentTokens?: CheckoutStyleTokens } = {},\n): string | number | undefined {\n const own = readPath(tokens, key);\n if (isExplicitCheckoutStyleTokenValue(own)) {\n return own as string | number;\n }\n\n const parent = options.parentTokens ? readPath(options.parentTokens, key) : undefined;\n if (isExplicitCheckoutStyleTokenValue(parent)) {\n return parent as string | number;\n }\n\n const brandDerivedKey = resolveCheckoutStyleBrandDerivedTokenKey(key);\n if (brandDerivedKey) {\n const brand = resolveCheckoutStyleTokenValue(tokens, brandDerivedKey as CheckoutStyleTokenKey, options);\n if (isExplicitCheckoutStyleTokenValue(brand)) {\n return brand;\n }\n }\n\n const definition = checkoutStyleTokenDefinitions.find((entry) => entry.key === key);\n if (definition && isExplicitCheckoutStyleTokenValue(definition.default)) {\n return definition.default;\n }\n\n const baseline = CHECKOUT_PLATFORM_BASELINE[key];\n return baseline !== undefined ? baseline : undefined;\n}\n\nexport function createCheckoutStyleCssVariables(tokens: CheckoutStyleTokens): Record<CheckoutStyleCssVariable, string> {\n const variables = {} as Record<CheckoutStyleCssVariable, string>;\n\n for (const definition of checkoutStyleTokenDefinitions) {\n const value = readPath(tokens, definition.key);\n if (!isExplicitCheckoutStyleTokenValue(value)) {\n continue;\n }\n variables[definition.cssVar] = formatCssValue(definition, value);\n }\n\n return variables;\n}\n\n/**\n * Token groups whose defaults are safe to materialise into the live checkout\n * root. These are the \"foundation\" tokens (brand, base colors, shape, spacing)\n * that sit at the INNER end of the system-CSS `var()` fallback chains —\n * e.g. `var(--spx-checkout-product-card-border, var(--spx-checkout-border, …))`.\n * Materialising them kills the white-`currentColor` fallback bug without\n * touching the cascade.\n *\n * The `component` group is deliberately excluded: those tokens are the OUTER\n * end of the chains, so emitting their defaults (e.g. `--spx-checkout-product-card-bg`)\n * would shadow base-token edits — a merchant who only customises `color.surfaceRaised`\n * would no longer see it cascade into product cards. Their defaults stay inline\n * in the system CSS as the final hex fallback instead.\n *\n * The `typography` group is also excluded: `typography.fontFamily` resolves to a\n * bare family name (\"Geist\") that no `@font-face` declares — the checkout loads\n * Geist via `next/font` as `--font-geist-sans`. Materialising `--spx-checkout-font`\n * as \"Geist\" would make the font-family rule bypass the Next webfont and fall\n * back to system sans. The system CSS keeps CHECKOUT_PLATFORM_FONT_STACK (which\n * references `--font-geist-sans`) as its inline default instead.\n */\nconst CHECKOUT_BASELINE_TOKEN_GROUPS = new Set(['brand', 'color', 'shape', 'spacing']);\n\n/**\n * Like {@link createCheckoutStyleCssVariables}, but materialises each foundation\n * token's SSOT default when the merchant hasn't set an explicit value. The live\n * hosted checkout renders this so the base `--spx-checkout-*` variables are\n * always present in the DOM, which means the system CSS never falls back to\n * `currentColor` (that fallback resolved to the white text colour → white\n * borders/buttons for any merchant who never opened the Style Center).\n *\n * Rules:\n * - Explicit merchant values are always emitted (any group, including component\n * overrides), so partial Style Center themes keep working.\n * - Unset tokens only get their default emitted when they belong to a foundation\n * group (see {@link CHECKOUT_BASELINE_TOKEN_GROUPS}); component defaults are\n * left to the inline system-CSS fallbacks so base-token edits cascade.\n * - Empty defaults (`''`) are skipped so the value stays unset — most importantly\n * `color.background` (`--spx-checkout-bg`), which must remain absent so the\n * ambient gradient survives. This resolves only to `definition.default`, NOT\n * through `resolveCheckoutStyleTokenValue`, because that resolver would fall\n * through to the opaque `#000000` `CHECKOUT_PLATFORM_BASELINE` background.\n */\n/**\n * Light-appearance defaults for the baseline foundation tokens. Keys not listed\n * here keep their (appearance-neutral) definition default. `color.background`\n * stays absent in both appearances so the ambient gradient survives.\n */\nexport const CHECKOUT_PLATFORM_BASELINE_LIGHT_DEFAULTS: Partial<Record<string, string>> = {\n 'color.surface': '#ffffff',\n 'color.surfaceRaised': '#f4f4f5',\n 'color.text': '#101012',\n 'color.textMuted': '#6b7280',\n 'color.border': '#e4e4e7',\n 'color.success': '#16a34a',\n 'color.warning': '#ca8a04',\n 'color.error': '#dc2626',\n};\n\nexport type CheckoutStyleAppearance = 'dark' | 'light';\n\nexport function createCheckoutStyleBaselineCssVariables(\n tokens: CheckoutStyleTokens,\n appearance: CheckoutStyleAppearance = 'dark',\n): Record<CheckoutStyleCssVariable, string> {\n const variables = {} as Record<CheckoutStyleCssVariable, string>;\n\n for (const definition of checkoutStyleTokenDefinitions) {\n const own = readPath(tokens, definition.key);\n if (isExplicitCheckoutStyleTokenValue(own)) {\n variables[definition.cssVar] = formatCssValue(definition, own);\n continue;\n }\n if (!CHECKOUT_BASELINE_TOKEN_GROUPS.has(definition.group)) {\n continue;\n }\n const baselineDefault = appearance === 'light'\n ? CHECKOUT_PLATFORM_BASELINE_LIGHT_DEFAULTS[definition.key] ?? definition.default\n : definition.default;\n if (!isExplicitCheckoutStyleTokenValue(baselineDefault)) {\n continue;\n }\n variables[definition.cssVar] = formatCssValue(definition, baselineDefault);\n }\n\n return variables;\n}\n\nfunction shouldUseDarkEmbedDefaults(options: EmbedStyleCssVariableOptions): boolean {\n if (options.mode === 'dark') return true;\n if (options.mode === 'light') return false;\n return options.embedDesign === 'clean-dark' || options.embedDesign === 'v2' || options.embedDesign === 'v3';\n}\n\nfunction resolveEmbedStyleDefault(\n definition: typeof embedStyleTokenDefinitions[number],\n options: EmbedStyleCssVariableOptions,\n): string | number {\n if (!shouldUseDarkEmbedDefaults(options)) {\n return definition.default;\n }\n\n switch (definition.key) {\n case 'embed.productCard.background':\n return '#09090b';\n case 'embed.productCard.border':\n return 'rgba(255,255,255,0.08)';\n case 'embed.cart.background':\n return '#09090b';\n case 'embed.cart.rowBorder':\n return '#27272a';\n case 'embed.modal.background':\n return '#0a0a0c';\n case 'embed.modal.shadow':\n return options.embedDesign === 'v2'\n ? '0 24px 80px rgba(124,92,255,0.28), 0 16px 48px rgba(0,0,0,0.45)'\n : '0 20px 60px rgba(0,0,0,0.45)';\n case 'embed.skeleton.background':\n return '#1a1a1e';\n case 'embed.skeleton.shimmer':\n return '#2a2a2f';\n default:\n return definition.default;\n }\n}\n\nexport function createEmbedStyleCssVariables(\n tokens: CheckoutStyleTokens,\n options: EmbedStyleCssVariableOptions = {},\n): Record<EmbedStyleCssVariable, string> {\n const variables = {} as Record<EmbedStyleCssVariable, string>;\n\n for (const definition of embedStyleTokenDefinitions) {\n const value = readPath(tokens, definition.key);\n const resolvedValue = typeof value === 'string' || typeof value === 'number'\n ? value\n : resolveEmbedStyleDefault(definition, options);\n if (typeof resolvedValue === 'string' && resolvedValue.length === 0) {\n continue;\n }\n variables[definition.cssVar] = formatCssValue(definition, resolvedValue);\n }\n\n return variables;\n}\n","import * as z from 'zod/v4';\n\nexport const storefrontAddonTypeValues = [\n 'announcement_bar',\n 'countdown_bar',\n 'promo_info_card',\n 'recent_purchase_popup',\n 'coupon_popup_modal',\n 'live_chat',\n] as const;\n\nexport const storefrontAddonSlotValues = [\n 'layout.header.before',\n 'layout.header.after',\n 'layout.overlay',\n 'home.hero.after',\n 'home.grid.before',\n 'product.buybox.after',\n 'layout.footer.before',\n 'floating.bottom_right',\n] as const;\n\nexport const storefrontAddonComponentValues = [\n 'announcement_bar',\n 'countdown_bar',\n 'promo_info_card',\n 'recent_purchase_popup',\n 'coupon_popup_modal',\n 'live_chat',\n] as const;\n\nexport const StorefrontAddonTypeSchema = z.enum(storefrontAddonTypeValues);\nexport const StorefrontAddonSlotSchema = z.enum(storefrontAddonSlotValues);\nexport const StorefrontAddonComponentSchema = z.enum(storefrontAddonComponentValues);\n\nexport type StorefrontAddonType = z.infer<typeof StorefrontAddonTypeSchema>;\nexport type StorefrontAddonSlot = z.infer<typeof StorefrontAddonSlotSchema>;\nexport type StorefrontAddonComponent = z.infer<typeof StorefrontAddonComponentSchema>;\n\nconst HexColorSchema = z.string().regex(/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/, 'Use a valid hex color');\n\nexport const announcementBarDisplayModeValues = [\n 'static',\n 'marquee',\n] as const;\n\nexport const announcementBarThemePresetValues = [\n 'brand_blue',\n 'emerald',\n 'sunset',\n 'rose',\n 'charcoal',\n 'custom',\n] as const;\n\nexport const DEFAULT_ANNOUNCEMENT_BAR_ANIMATION_SPEED_SECONDS = 30;\n\nexport const AnnouncementBarDisplayModeSchema = z.enum(announcementBarDisplayModeValues);\nexport const AnnouncementBarThemePresetSchema = z.enum(announcementBarThemePresetValues);\n\nexport const countdownBarExpiryBehaviorValues = [\n 'hide',\n 'message',\n] as const;\n\nexport const countdownBarDensityValues = [\n 'compact',\n 'comfortable',\n] as const;\n\nexport const countdownBarCtaStyleValues = [\n 'subtle',\n 'outline',\n 'solid',\n] as const;\n\nexport const countdownBarTimerStyleValues = [\n 'minimal',\n 'boxed',\n] as const;\n\nexport const promoInfoCardThemePresetValues = [\n 'indigo',\n 'emerald',\n 'amber',\n 'rose',\n 'slate',\n 'custom',\n] as const;\n\nexport const promoInfoCardLayoutStyleValues = [\n 'compact',\n 'feature',\n 'alert',\n] as const;\n\nexport const promoInfoCardDensityValues = [\n 'compact',\n 'comfortable',\n] as const;\n\nexport const promoInfoCardCtaStyleValues = [\n 'subtle',\n 'outline',\n 'solid',\n] as const;\n\nexport const promoInfoCardIconVisibilityValues = [\n 'show',\n 'hide',\n] as const;\n\nexport const promoInfoCardIconValues = [\n 'sparkles',\n 'megaphone',\n 'gift',\n 'truck',\n 'shield',\n 'support',\n 'none',\n] as const;\n\nexport const CountdownBarExpiryBehaviorSchema = z.enum(countdownBarExpiryBehaviorValues);\nexport const CountdownBarDensitySchema = z.enum(countdownBarDensityValues);\nexport const CountdownBarCtaStyleSchema = z.enum(countdownBarCtaStyleValues);\nexport const CountdownBarTimerStyleSchema = z.enum(countdownBarTimerStyleValues);\nexport const PromoInfoCardThemePresetSchema = z.enum(promoInfoCardThemePresetValues);\nexport const PromoInfoCardLayoutStyleSchema = z.enum(promoInfoCardLayoutStyleValues);\nexport const PromoInfoCardDensitySchema = z.enum(promoInfoCardDensityValues);\nexport const PromoInfoCardCtaStyleSchema = z.enum(promoInfoCardCtaStyleValues);\nexport const PromoInfoCardIconSchema = z.enum(promoInfoCardIconValues);\nexport const PromoInfoCardIconVisibilitySchema = z.enum(promoInfoCardIconVisibilityValues);\n\nexport const couponPopupModalThemePresetValues = [\n 'midnight',\n 'ocean',\n 'ember',\n 'forest',\n 'custom',\n] as const;\n\nexport const couponPopupModalTriggerValues = [\n 'delay',\n 'exit_intent',\n] as const;\n\nexport const CouponPopupModalThemePresetSchema = z.enum(couponPopupModalThemePresetValues);\nexport const CouponPopupModalTriggerSchema = z.enum(couponPopupModalTriggerValues);\n\nconst RelativeOrAbsoluteUrlSchema = z.string().trim().refine((value) => {\n if (value.startsWith('/')) {\n return true;\n }\n\n try {\n const parsed = new URL(value);\n return parsed.protocol === 'http:' || parsed.protocol === 'https:';\n } catch {\n return false;\n }\n}, 'Use a valid absolute URL or a path starting with \"/\"');\n\nconst DatetimeStringSchema = z.string().trim().refine((value) => {\n const parsed = new Date(value);\n return !Number.isNaN(parsed.getTime());\n}, 'Use a valid date and time');\n\nexport const AnnouncementBarConfigSchema = z.object({\n text: z.string().trim().min(1, 'Text is required').max(160, 'Text must be 160 characters or fewer'),\n linkLabel: z.string().trim().max(32, 'Link label must be 32 characters or fewer').optional().nullable(),\n linkUrl: RelativeOrAbsoluteUrlSchema.optional().nullable(),\n dismissible: z.boolean().default(false),\n displayMode: AnnouncementBarDisplayModeSchema.default('marquee'),\n themePreset: AnnouncementBarThemePresetSchema.default('custom'),\n animationSpeedSeconds: z.number().int().min(8).max(40).default(DEFAULT_ANNOUNCEMENT_BAR_ANIMATION_SPEED_SECONDS),\n backgroundColor: HexColorSchema.default('#111827'),\n textColor: HexColorSchema.default('#f9fafb'),\n});\n\nexport const CountdownBarConfigSchema = z.object({\n text: z.string().trim().min(1, 'Text is required').max(120, 'Text must be 120 characters or fewer'),\n endAt: DatetimeStringSchema,\n linkLabel: z.string().trim().max(32, 'Link label must be 32 characters or fewer').optional().nullable(),\n linkUrl: RelativeOrAbsoluteUrlSchema.optional().nullable(),\n dismissible: z.boolean().default(false),\n themePreset: AnnouncementBarThemePresetSchema.default('brand_blue'),\n expiredBehavior: CountdownBarExpiryBehaviorSchema.default('hide'),\n expiredMessage: z.string().trim().max(120, 'Expired message must be 120 characters or fewer').optional().nullable(),\n density: CountdownBarDensitySchema.default('compact'),\n ctaStyle: CountdownBarCtaStyleSchema.default('subtle'),\n timerStyle: CountdownBarTimerStyleSchema.default('boxed'),\n backgroundColor: HexColorSchema.default('#111827'),\n textColor: HexColorSchema.default('#f9fafb'),\n});\n\nexport const PromoInfoCardConfigSchema = z.object({\n eyebrow: z.string().trim().max(32, 'Eyebrow must be 32 characters or fewer').optional().nullable(),\n title: z.string().trim().min(1, 'Title is required').max(80, 'Title must be 80 characters or fewer'),\n body: z.string().trim().min(1, 'Body is required').max(240, 'Body must be 240 characters or fewer'),\n linkLabel: z.string().trim().max(32, 'Link label must be 32 characters or fewer').optional().nullable(),\n linkUrl: RelativeOrAbsoluteUrlSchema.optional().nullable(),\n themePreset: PromoInfoCardThemePresetSchema.default('indigo'),\n layoutStyle: PromoInfoCardLayoutStyleSchema.default('feature'),\n density: PromoInfoCardDensitySchema.default('comfortable'),\n ctaStyle: PromoInfoCardCtaStyleSchema.default('outline'),\n icon: PromoInfoCardIconSchema.default('sparkles'),\n iconVisibility: PromoInfoCardIconVisibilitySchema.default('show'),\n backgroundColor: HexColorSchema.default('#111827'),\n textColor: HexColorSchema.default('#f9fafb'),\n accentColor: HexColorSchema.default('#818cf8'),\n});\n\nexport const RecentPurchasePopupConfigSchema = z.object({\n title: z.string().trim().min(1, 'Title is required').max(80, 'Title must be 80 characters or fewer').default('Recent purchases'),\n lookbackHours: z.number().int().min(1).max(168).default(24),\n cooldownSeconds: z.number().int().min(5).max(300).default(20),\n maxItems: z.number().int().min(1).max(20).default(8),\n anonymizeMode: z.enum([\n 'first_name_city',\n 'first_name_country',\n 'initial_country',\n 'anonymous',\n ]).default('first_name_city'),\n includedProductIds: z.array(z.string().min(1)).max(50).default([]),\n});\n\nexport const CouponPopupModalConfigSchema = z.object({\n eyebrow: z.string().trim().max(32, 'Eyebrow must be 32 characters or fewer').optional().nullable(),\n title: z.string().trim().min(1, 'Title is required').max(80, 'Title must be 80 characters or fewer'),\n body: z.string().trim().min(1, 'Body is required').max(240, 'Body must be 240 characters or fewer'),\n couponCode: z.string().trim().min(2, 'Coupon code is required').max(40, 'Coupon code must be 40 characters or fewer'),\n primaryButtonLabel: z.string().trim().min(1, 'Primary button label is required').max(24, 'Primary button label must be 24 characters or fewer').default('Copy code'),\n secondaryButtonLabel: z.string().trim().min(1, 'Secondary button label is required').max(24, 'Secondary button label must be 24 characters or fewer').default('Maybe later'),\n disclaimer: z.string().trim().max(100, 'Disclaimer must be 100 characters or fewer').optional().nullable(),\n themePreset: CouponPopupModalThemePresetSchema.default('midnight'),\n trigger: CouponPopupModalTriggerSchema.default('delay'),\n delaySeconds: z.number().int().min(0).max(60).default(6),\n showOncePerSession: z.boolean().default(true),\n reminderHours: z.number().int().min(1).max(720).default(24),\n backgroundColor: HexColorSchema.default('#111827'),\n textColor: HexColorSchema.default('#f8fafc'),\n accentColor: HexColorSchema.default('#7c9cff'),\n heroImageUrl: RelativeOrAbsoluteUrlSchema.optional().nullable(),\n discountDisplay: z.string().trim().max(24, 'Discount display must be 24 characters or fewer').optional().nullable(),\n expiresAt: DatetimeStringSchema.optional().nullable(),\n});\n\nexport const liveChatContactFieldsValues = [\n 'hidden',\n 'optional',\n] as const;\n\nexport const LiveChatContactFieldsSchema = z.enum(liveChatContactFieldsValues);\n\nexport const LiveChatConfigSchema = z.object({\n headline: z.string().trim().min(1, 'Headline is required').max(60, 'Headline must be 60 characters or fewer').default('Chat with us'),\n greeting: z.string().trim().min(1, 'Greeting is required').max(240, 'Greeting must be 240 characters or fewer').default('Hi! Send us a message and we will reply as soon as possible.'),\n inputPlaceholder: z.string().trim().min(1, 'Placeholder is required').max(80, 'Placeholder must be 80 characters or fewer').default('Type your message…'),\n contactFields: LiveChatContactFieldsSchema.default('optional'),\n accentColor: HexColorSchema.default('#111827'),\n launcherIconColor: HexColorSchema.default('#f9fafb'),\n});\n\nexport type LiveChatConfig = z.infer<typeof LiveChatConfigSchema>;\n\nexport type AnnouncementBarConfig = z.infer<typeof AnnouncementBarConfigSchema>;\nexport type CountdownBarConfig = z.infer<typeof CountdownBarConfigSchema>;\nexport type PromoInfoCardConfig = z.infer<typeof PromoInfoCardConfigSchema>;\nexport type RecentPurchasePopupConfig = z.infer<typeof RecentPurchasePopupConfigSchema>;\nexport type CouponPopupModalConfig = z.infer<typeof CouponPopupModalConfigSchema>;\n\nexport type StorefrontAddonConfigByType = {\n announcement_bar: AnnouncementBarConfig;\n countdown_bar: CountdownBarConfig;\n promo_info_card: PromoInfoCardConfig;\n recent_purchase_popup: RecentPurchasePopupConfig;\n coupon_popup_modal: CouponPopupModalConfig;\n live_chat: LiveChatConfig;\n};\n\nexport const StorefrontAddonConfigSchemaByType = {\n announcement_bar: AnnouncementBarConfigSchema,\n countdown_bar: CountdownBarConfigSchema,\n promo_info_card: PromoInfoCardConfigSchema,\n recent_purchase_popup: RecentPurchasePopupConfigSchema,\n coupon_popup_modal: CouponPopupModalConfigSchema,\n live_chat: LiveChatConfigSchema,\n} as const satisfies Record<StorefrontAddonType, z.ZodTypeAny>;\n\nconst AnnouncementBarDraftSchema = z.object({\n type: z.literal('announcement_bar'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: AnnouncementBarConfigSchema,\n});\n\nconst RecentPurchasePopupDraftSchema = z.object({\n type: z.literal('recent_purchase_popup'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: RecentPurchasePopupConfigSchema,\n});\n\nconst CountdownBarDraftSchema = z.object({\n type: z.literal('countdown_bar'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: CountdownBarConfigSchema,\n});\n\nconst PromoInfoCardDraftSchema = z.object({\n type: z.literal('promo_info_card'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: PromoInfoCardConfigSchema,\n});\n\nconst CouponPopupModalDraftSchema = z.object({\n type: z.literal('coupon_popup_modal'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: CouponPopupModalConfigSchema,\n});\n\nconst LiveChatDraftSchema = z.object({\n type: z.literal('live_chat'),\n slot: StorefrontAddonSlotSchema,\n enabled: z.boolean().default(true),\n sortOrder: z.number().int().min(0).max(999).default(0),\n config: LiveChatConfigSchema,\n});\n\nexport const StorefrontAddonCreateSchema = z.discriminatedUnion('type', [\n AnnouncementBarDraftSchema,\n CountdownBarDraftSchema,\n PromoInfoCardDraftSchema,\n RecentPurchasePopupDraftSchema,\n CouponPopupModalDraftSchema,\n LiveChatDraftSchema,\n]);\n\nexport const StorefrontAddonUpdateSchema = z.discriminatedUnion('type', [\n AnnouncementBarDraftSchema.extend({\n id: z.string().min(1),\n }),\n CountdownBarDraftSchema.extend({\n id: z.string().min(1),\n }),\n PromoInfoCardDraftSchema.extend({\n id: z.string().min(1),\n }),\n RecentPurchasePopupDraftSchema.extend({\n id: z.string().min(1),\n }),\n CouponPopupModalDraftSchema.extend({\n id: z.string().min(1),\n }),\n LiveChatDraftSchema.extend({\n id: z.string().min(1),\n }),\n]);\n\nexport type StorefrontAddonCreateInput = z.infer<typeof StorefrontAddonCreateSchema>;\nexport type StorefrontAddonUpdateInput = z.infer<typeof StorefrontAddonUpdateSchema>;\n\nexport interface StorefrontAddonInstanceBase {\n id: string;\n shopId: string;\n type: StorefrontAddonType;\n slot: StorefrontAddonSlot;\n enabled: boolean;\n sortOrder: number;\n createdAt: string;\n updatedAt: string;\n}\n\nexport type StorefrontAddonInstance =\n | (StorefrontAddonInstanceBase & {\n type: 'announcement_bar';\n config: AnnouncementBarConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'countdown_bar';\n config: CountdownBarConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'promo_info_card';\n config: PromoInfoCardConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'recent_purchase_popup';\n config: RecentPurchasePopupConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'coupon_popup_modal';\n config: CouponPopupModalConfig;\n })\n | (StorefrontAddonInstanceBase & {\n type: 'live_chat';\n config: LiveChatConfig;\n });\n\nexport interface StorefrontAddonCatalogItem {\n type: StorefrontAddonType;\n title: string;\n description: string;\n slots: StorefrontAddonSlot[];\n supportsMultiple: boolean;\n features: string[];\n defaults: StorefrontAddonCreateInput;\n}\n\nexport interface AnnouncementBarResolvedProps extends AnnouncementBarConfig {\n addonId: string;\n}\n\nexport interface CountdownBarResolvedProps extends CountdownBarConfig {\n addonId: string;\n}\n\nexport interface PromoInfoCardResolvedProps extends PromoInfoCardConfig {\n addonId: string;\n}\n\nexport interface RecentPurchasePopupItem {\n customerLabel: string;\n productTitle: string;\n createdAt: string;\n}\n\nexport interface RecentPurchasePopupResolvedProps {\n addonId: string;\n title: string;\n cooldownSeconds: number;\n items: RecentPurchasePopupItem[];\n}\n\nexport interface CouponPopupModalResolvedProps extends CouponPopupModalConfig {\n addonId: string;\n}\n\nexport interface LiveChatResolvedProps extends LiveChatConfig {\n addonId: string;\n}\n\nexport type ResolvedStorefrontAddon =\n | {\n id: string;\n type: 'announcement_bar';\n slot: StorefrontAddonSlot;\n component: 'announcement_bar';\n sortOrder: number;\n props: AnnouncementBarResolvedProps;\n }\n | {\n id: string;\n type: 'countdown_bar';\n slot: StorefrontAddonSlot;\n component: 'countdown_bar';\n sortOrder: number;\n props: CountdownBarResolvedProps;\n }\n | {\n id: string;\n type: 'promo_info_card';\n slot: StorefrontAddonSlot;\n component: 'promo_info_card';\n sortOrder: number;\n props: PromoInfoCardResolvedProps;\n }\n | {\n id: string;\n type: 'recent_purchase_popup';\n slot: StorefrontAddonSlot;\n component: 'recent_purchase_popup';\n sortOrder: number;\n props: RecentPurchasePopupResolvedProps;\n }\n | {\n id: string;\n type: 'coupon_popup_modal';\n slot: StorefrontAddonSlot;\n component: 'coupon_popup_modal';\n sortOrder: number;\n props: CouponPopupModalResolvedProps;\n }\n | {\n id: string;\n type: 'live_chat';\n slot: StorefrontAddonSlot;\n component: 'live_chat';\n sortOrder: number;\n props: LiveChatResolvedProps;\n };\n\nexport interface StorefrontAddonBootstrap {\n items: ResolvedStorefrontAddon[];\n}\n","export const MANUAL_GATEWAY_TEMPLATE_VARIABLES = [\n 'amount',\n 'currency',\n 'invoice_id',\n 'customer_email',\n 'id',\n 'email',\n 'price',\n 'price_usd',\n 'product_name',\n 'quantity',\n] as const;\n\nexport type ManualGatewayTemplateVariable = typeof MANUAL_GATEWAY_TEMPLATE_VARIABLES[number];\nexport type ManualGatewayTemplateVars = Record<string, string>;\n\nexport const MANUAL_GATEWAY_TEMPLATE_VARIABLE_EXAMPLES = [\n '{{amount}}',\n '{{currency}}',\n '{{invoice_id}}',\n '{{customer_email}}',\n '{id}',\n '{email}',\n '{price}',\n '{currency}',\n '{price_usd}',\n '{product_name}',\n '{quantity}',\n] as const;\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction buildVariablePattern(key: string, style: 'double' | 'single'): RegExp {\n const escapedKey = escapeRegExp(key);\n if (style === 'double') {\n return new RegExp(`\\\\{\\\\{\\\\s*${escapedKey}\\\\s*\\\\}\\\\}`, 'gi');\n }\n\n return new RegExp(`(?<!\\\\{)\\\\{\\\\s*${escapedKey}\\\\s*\\\\}(?!\\\\})`, 'gi');\n}\n\nexport function renderManualGatewayTemplate(\n template: string,\n vars: ManualGatewayTemplateVars,\n options: { encodeValues?: boolean } = {},\n): string {\n let rendered = template;\n for (const [key, value] of Object.entries(vars)) {\n const replacement = options.encodeValues ? encodeURIComponent(value) : value;\n rendered = rendered.replace(buildVariablePattern(key, 'double'), replacement);\n rendered = rendered.replace(buildVariablePattern(key, 'single'), replacement);\n }\n return rendered;\n}\n\nconst PLACEHOLDER_SCAN_PATTERNS = [\n /\\{\\{\\s*([a-zA-Z][a-zA-Z0-9_]*)\\s*\\}\\}/g,\n /(?<!\\{)\\{\\s*([a-zA-Z][a-zA-Z0-9_]*)\\s*\\}(?!\\})/g,\n] as const;\n\nconst REMAINING_PLACEHOLDER_PATTERNS = [\n /\\{\\{[\\s\\S]*?\\}\\}/g,\n /(?<!\\{)\\{[^{}]+\\}(?!\\})/g,\n] as const;\n\nexport const MANUAL_GATEWAY_CUSTOM_FIELD_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*$/;\n\nexport function isValidManualGatewayCustomFieldName(name: string): boolean {\n return MANUAL_GATEWAY_CUSTOM_FIELD_NAME_PATTERN.test(name.trim());\n}\n\nexport function findUnsupportedManualGatewayPlaceholders(\n template: string,\n additionalVariables: Iterable<string> = [],\n): string[] {\n if (!template.trim()) {\n return [];\n }\n\n const allowedVariables = new Set<string>(MANUAL_GATEWAY_TEMPLATE_VARIABLES);\n for (const variable of additionalVariables) {\n const normalized = variable.trim().toLowerCase();\n if (normalized) {\n allowedVariables.add(normalized);\n }\n }\n\n const unsupported = new Set<string>();\n // Track the raw spans of syntactically-valid placeholders that ARE allowed, so\n // we don't double-flag them when sweeping for malformed syntax below.\n const allowedRawSpans = new Set<string>();\n for (const pattern of PLACEHOLDER_SCAN_PATTERNS) {\n for (const match of template.matchAll(pattern)) {\n const raw = match[0];\n const name = match[1]?.toLowerCase();\n if (name && !allowedVariables.has(name)) {\n unsupported.add(raw);\n } else if (name) {\n allowedRawSpans.add(raw);\n }\n }\n }\n\n // Also reject ANY remaining {{...}}/{...} placeholder syntax that is not an\n // allowed variable — a mistyped or filtered token such as `{{order-id}}` or\n // `{{ amount | money }}` is not caught by the strict name patterns above, so\n // it would survive save and only fail at checkout (session 400 / raw token in\n // instructions). Flag it at save time instead.\n for (const pattern of REMAINING_PLACEHOLDER_PATTERNS) {\n for (const match of template.matchAll(pattern)) {\n const raw = match[0];\n if (!allowedRawSpans.has(raw)) {\n unsupported.add(raw);\n }\n }\n }\n\n return [...unsupported];\n}\n\nexport function collectUnsupportedManualGatewayPlaceholders(\n ...templates: Array<string | null | undefined>\n): string[] {\n const unsupported = new Set<string>();\n for (const template of templates) {\n for (const placeholder of findUnsupportedManualGatewayPlaceholders(template ?? '')) {\n unsupported.add(placeholder);\n }\n }\n return [...unsupported];\n}\n\nexport function collectUnsupportedManualGatewayPlaceholdersWithExtras(\n additionalVariables: Iterable<string>,\n ...templates: Array<string | null | undefined>\n): string[] {\n const unsupported = new Set<string>();\n for (const template of templates) {\n for (const placeholder of findUnsupportedManualGatewayPlaceholders(template ?? '', additionalVariables)) {\n unsupported.add(placeholder);\n }\n }\n return [...unsupported];\n}\n\nconst RESERVED_MANUAL_GATEWAY_FIELD_NAMES = new Set<string>(\n MANUAL_GATEWAY_TEMPLATE_VARIABLES.map((name) => name.toLowerCase()),\n);\n\nexport function isReservedManualGatewayFieldName(name: string): boolean {\n const normalized = name.trim().toLowerCase();\n return normalized.length > 0 && RESERVED_MANUAL_GATEWAY_FIELD_NAMES.has(normalized);\n}\n\nexport function findRemainingManualGatewayPlaceholders(template: string): string[] {\n if (!template.trim()) {\n return [];\n }\n\n const remaining = new Set<string>();\n for (const pattern of REMAINING_PLACEHOLDER_PATTERNS) {\n for (const match of template.matchAll(pattern)) {\n remaining.add(match[0]);\n }\n }\n\n return [...remaining];\n}\n\nexport function stableGatewayFieldValuesKey(fields: Record<string, string> | null | undefined): string {\n if (!fields) {\n return '{}';\n }\n\n const sortedEntries = Object.keys(fields)\n .sort((left, right) => left.localeCompare(right))\n .map((key) => [key, fields[key]] as const);\n\n return JSON.stringify(sortedEntries);\n}\n\nexport function isSafeManualGatewayRedirectUrl(url: string): boolean {\n const trimmed = url.trim();\n if (!trimmed) {\n return false;\n }\n\n try {\n const parsed = new URL(trimmed);\n return parsed.protocol === 'http:' || parsed.protocol === 'https:';\n } catch {\n return false;\n }\n}\n\nexport function mergeManualGatewayTemplateVars(\n trustedVars: ManualGatewayTemplateVars,\n gatewayFieldVars: Record<string, string> = {},\n): ManualGatewayTemplateVars {\n return {\n ...gatewayFieldVars,\n ...trustedVars,\n };\n}\n","import { z } from 'zod';\n\nconst unknownRecordSchema = z.record(z.string(), z.unknown());\nconst stringOrNumberSchema = z.union([z.string(), z.number()]);\n\nexport const embedPaymentSessionWireSchema = z.object({\n kind: z.enum(['address', 'redirect', 'embed_pending']),\n gateway: z.string(),\n checkout_url: z.string().nullable().optional(),\n address: z.string().optional(),\n amount: z.string().optional(),\n qr_code: z.string().optional(),\n expires_at: z.string().optional(),\n payment_id: z.string().optional(),\n confirmations_needed: z.number().optional(),\n}).passthrough();\n\n/** Critical runtime boundary for the public embed-start response. */\nexport const embedCheckoutStartWireSchema = z.object({\n data: z.object({\n invoice: z.object({\n uniqid: z.string().uuid(),\n }).passthrough(),\n invoice_url: z.string().nullable(),\n checkout_url: z.string().nullable(),\n selected_gateway: z.string().nullable(),\n session_started: z.boolean(),\n payment_session: embedPaymentSessionWireSchema.nullable(),\n completion_access_grant: z.string().nullable(),\n }).passthrough(),\n}).passthrough();\n\nexport type EmbedCheckoutStartWire = z.infer<typeof embedCheckoutStartWireSchema>;\n\nconst publicInvoiceWireCustomFieldDefinitionSchema = z.object({\n default_value: z.string().optional(),\n min_length: z.number().optional(),\n name: z.string(),\n placeholder: z.string().optional(),\n regex: z.string().optional(),\n required: z.boolean(),\n type: z.string(),\n});\n\nconst publicInvoiceWireProductAddonSchema = z.object({\n id: z.string(),\n price: z.number(),\n quantity: z.number(),\n title: z.string(),\n});\n\nconst publicInvoiceWireProductSchema = z.object({\n addons: z.array(publicInvoiceWireProductAddonSchema).optional(),\n available_addons: z.array(z.unknown()).optional(),\n cloudflare_image_id: z.string().nullable(),\n created_at: z.string().optional(),\n currency: z.string(),\n custom_fields: unknownRecordSchema.nullable().optional(),\n custom_fields_config: z.array(publicInvoiceWireCustomFieldDefinitionSchema).nullable().optional(),\n delivery_instruction: z.unknown().optional(),\n delivery_instruction_config: z.unknown().optional(),\n delivery_instruction_label: z.unknown().optional(),\n delivery_text: z.string().nullable().optional(),\n // Delivery wait as a bare COUNT. `0` and `null` both mean instant (the\n // digital-goods default); a positive value is a \"within N <unit>\" promise.\n delivery_time: z.number().nullable().optional(),\n // The unit `delivery_time` is counted in. The column is NOT NULL with a\n // `days` default — which is what every row meant before the unit existed — so\n // a live producer always sends one. It stays optional here because this\n // schema also describes payment-link and other synthesized products that\n // carry no catalog row, and those quote no wait at all.\n delivery_time_unit: z.enum(['minutes', 'hours', 'days']).nullable().optional(),\n description: z.string().nullable(),\n discount_percent: z.number().optional(),\n discount_display: z.number().optional(),\n discounted_total_display: z.number().optional(),\n gateways: z.array(z.string()).nullable().optional(),\n id: z.string().optional(),\n image_name: z.string().nullable(),\n image_storage: z.string().optional(),\n line_item_id: z.string().nullable().optional(),\n pay_what_you_want: z.boolean().optional(),\n price: z.string().optional(),\n price_display: stringOrNumberSchema,\n quantity: z.number(),\n quantity_max: z.number().optional(),\n quantity_min: z.number().optional(),\n recurring_interval: z.string().nullable().optional(),\n recurring_interval_count: z.number().nullable().optional(),\n redirect_link: z.string().nullable().optional(),\n redirect_time: z.number().nullable().optional(),\n service_text: z.string().nullable().optional(),\n setup_cost: z.string().optional(),\n slug: z.string().nullable().optional(),\n storefront_url: z.string().nullable().optional(),\n status: z.string().nullable().optional(),\n subtype: z.string().nullable().optional(),\n terms_of_service: z.string().nullable().optional(),\n title: z.string(),\n total: z.number(),\n trial_period: z.number().nullable().optional(),\n type: z.string().nullable().optional(),\n uniqid: z.string().nullable(),\n unit_price: z.number().optional(),\n unit_price_display: stringOrNumberSchema.optional(),\n unit_quantity: z.number(),\n updated_at: z.string().optional(),\n variant_title: z.string().nullable().optional(),\n video_link: z.string().nullable().optional(),\n volume_discounts: z.unknown().optional(),\n warranty_days: z.number().nullable().optional(),\n warranty_text: z.string().nullable().optional(),\n});\n\nconst gatewayFeePreviewSchema = z.object({\n amount: z.number(),\n gateway: z.string(),\n});\n\nconst checkoutTippingSchema = z.object({\n custom_tip_enabled: z.boolean().optional(),\n enabled: z.boolean(),\n preset_percentages: z.array(z.number()).optional(),\n});\n\nconst customerBalanceSchema = z.object({\n allow_partial_payment: z.boolean().optional(),\n auto_apply: z.boolean().optional(),\n available: z.string(),\n currency: z.string(),\n});\n\nconst pricingBreakdownSchema = z.object({\n affiliate_code: z.string().nullable().optional(),\n already_paid: stringOrNumberSchema.nullable().optional(),\n amount_due: stringOrNumberSchema.nullable().optional(),\n currency: z.string().nullable().optional(),\n discount: stringOrNumberSchema.nullable().optional(),\n discount_label: z.string().nullable().optional(),\n gateway_fee: stringOrNumberSchema.nullable().optional(),\n platform_fee: stringOrNumberSchema.nullable().optional(),\n subtotal: stringOrNumberSchema.nullable().optional(),\n tip: stringOrNumberSchema.nullable().optional(),\n total: stringOrNumberSchema.nullable().optional(),\n});\n\nconst pollingSchema = z.object({\n active: z.boolean(),\n expires_at: z.string(),\n});\n\nconst supportSchema = z.object({\n faq_url: z.string().nullable(),\n support_email: z.string().nullable(),\n support_url: z.string().nullable(),\n telegram_invite: z.string().nullable(),\n /** shop_social_links.discord — the checkout renders an optional join row from it. */\n discord_invite_url: z.string().nullable(),\n});\n\nconst gatewayEligibilityStateSchema = z.object({\n currency: z.string().nullable().optional(),\n enabled: z.boolean(),\n max_amount: z.number().nullable().optional(),\n min_amount: z.number().nullable().optional(),\n reason: z.enum(['BELOW_MIN_AMOUNT', 'ABOVE_MAX_AMOUNT']).nullable().optional(),\n});\n\nconst deliverySchema = z.object({\n delivered_items: z.array(z.unknown()),\n downloads: z.array(z.unknown()),\n external_urls: z.array(z.unknown()),\n license_keys: z.array(z.unknown()),\n tracking_codes: z.array(z.unknown()),\n});\n\nconst underpaymentSchema = z.object({\n active: z.boolean().optional(),\n attempt_id: z.string().optional(),\n buyer_actionable: z.boolean().nullable().optional(),\n crypto_currency: z.string().nullable().optional(),\n currency: z.string().optional(),\n expected_amount: z.string().nullable().optional(),\n expected_crypto_amount: z.string().nullable().optional(),\n last_checked_at: z.string().optional(),\n missing_amount: z.string().nullable().optional(),\n missing_crypto_amount: z.string().nullable().optional(),\n // InvoiceEnricher.applyUnderpayment serializes providerReference ?? null —\n // an active underpayment without a provider reference is a valid payload.\n provider_reference: z.string().nullable().optional(),\n provider_status: z.string().nullable().optional(),\n received_amount: z.string().nullable().optional(),\n received_crypto_amount: z.string().nullable().optional(),\n shortfall_percent: z.string().nullable().optional(),\n});\n\nconst statusHistoryEntrySchema = z.object({\n created_at: z.string().nullable(),\n details: z.string().nullable(),\n id: z.string(),\n invoice_id: z.string(),\n status: z.string().nullable(),\n});\n\nconst paymentMethodOverrideSchema = z.object({\n billing_address_mode: z.enum(['INHERIT', 'REQUIRED', 'DISABLED']).optional(),\n button_label: z.string().nullable().optional(),\n display_name: z.string().nullable().optional(),\n gateway: z.string(),\n hide_provider_attribution: z.boolean().optional(),\n icon_url: z.string().nullable().optional(),\n terms_mode: z.enum(['INHERIT', 'REQUIRED', 'DISABLED']).optional(),\n});\n\nconst customGatewaySchema = z.object({\n custom_fields: z.array(z.unknown()).optional(),\n description: z.string().nullable(),\n display_order: z.number(),\n icon_preset: z.string().nullable(),\n icon_url: z.string().nullable(),\n id: z.string(),\n instructions: z.string().nullable(),\n is_active: z.boolean().optional(),\n name: z.string(),\n payment_type: z.enum(['INSTRUCTIONS', 'REDIRECT']),\n redirect_url: z.string().nullable(),\n require_proof: z.boolean(),\n // Which fields the buyer has to fill in when proof is required. Optional so\n // an older cached payload stays parseable; the checkout falls back to BOTH.\n proof_type: z.enum(['TEXT', 'IMAGE', 'BOTH']).optional(),\n void_after_hours: z.number(),\n});\n\nconst buyerIdentitySchema = z.object({\n email: z.object({\n masked: z.string().nullable(),\n persisted: z.boolean(),\n required_for_provider_session: z.boolean().optional(),\n }),\n});\n\nconst cryptoTransactionSchema = z.object({\n amount: z.string().nullable(),\n confirmations: z.number().nullable(),\n created_at: z.number().optional(),\n hash: z.string().nullable(),\n status: z.string().optional(),\n});\n\nconst voidTimeSchema = z.object({\n conf: z.object({\n partial: z.number().optional(),\n void: z.number(),\n waiting_for_confirmations: z.number().optional(),\n }),\n gateways: z.array(z.string()),\n});\n\nconst invoicePaymentSessionStateSchema = z.object({\n invoice_payable: z.boolean(),\n resumable: z.boolean(),\n resumable_gateway: z.string().nullable(),\n gateway: z.string().nullable().optional(),\n crypto_gateway: z.string().nullable().optional(),\n processor: z.string().nullable().optional(),\n flow_type: z.string().nullable().optional(),\n status: z.string().nullable().optional(),\n provider_reference: z.string().nullable().optional(),\n provider_reference_type: z.string().nullable().optional(),\n capture_id: z.string().nullable().optional(),\n manual_confirmation_pending: z.boolean().optional(),\n payment_method_switch_locked: z.boolean().optional(),\n awaiting_payment_method: z.boolean().optional(),\n started_at: z.number().nullable().optional(),\n completed_at: z.number().nullable().optional(),\n});\n\n/**\n * Public invoice JSON after `toInvoiceTransportSnakeCase`.\n *\n * Gateway-specific invoice row fields can still pass the backend allowlist.\n * Unknown top-level keys are therefore preserved, while every known key is\n * validated whenever it is present.\n */\nexport const publicInvoiceWireSchema = z.object({\n already_paid_amount: stringOrNumberSchema.nullable().optional(),\n apm_method: z.string().nullable().optional(),\n blockchain: z.string().nullable(),\n buyer_identity: buyerIdentitySchema.nullable().optional(),\n checkout_tipping: checkoutTippingSchema.nullable().optional(),\n country_regulations: z.string().nullable().optional(),\n coupon_applied: z.boolean().optional(),\n crypto_mode: z.string().nullable().optional(),\n crypto_transactions: z.array(cryptoTransactionSchema).optional(),\n currency: z.string().nullable(),\n custom_fields: unknownRecordSchema.nullable().optional(),\n custom_gateways: z.array(customGatewaySchema).optional(),\n customer_balance: customerBalanceSchema.nullable().optional(),\n customer_email_masked: z.string().nullable().optional(),\n dark_mode: z.union([z.literal(0), z.literal(1)]).optional(),\n delivery: deliverySchema.optional(),\n delivery_info: deliverySchema.optional(),\n discount: z.number().optional(),\n discount_display: stringOrNumberSchema.optional(),\n eligible_gateways: z.array(z.string()).optional(),\n environment: z.string().optional(),\n fee_breakdown: unknownRecordSchema.nullable().optional(),\n gateway: z.string().nullable(),\n gateway_data: unknownRecordSchema.nullable().optional(),\n gateway_eligibility: z.record(z.string(), gatewayEligibilityStateSchema).optional(),\n gateway_fee_previews: z.array(gatewayFeePreviewSchema).optional(),\n gateways_available: z.array(z.string()),\n license: z.union([unknownRecordSchema, z.literal(false)]).optional(),\n name: z.string().nullable(),\n paddle_token: z.string().nullable().optional(),\n paddle_transaction_id: z.unknown().optional(),\n payment_link_id: z.string().nullable().optional(),\n payment_method_overrides: z.array(paymentMethodOverrideSchema).optional(),\n payment_session_state: invoicePaymentSessionStateSchema.nullable().optional(),\n polling: pollingSchema,\n pricing_breakdown: pricingBreakdownSchema.nullable().optional(),\n product: z.array(publicInvoiceWireProductSchema).optional(),\n quantity: z.number().nullable(),\n rates_snapshot: z.record(z.string(), z.number()).optional(),\n remaining_amount: stringOrNumberSchema.nullable().optional(),\n selected_gateway: z.string().nullable().optional(),\n shop_checkout_ambient_color: z.string().nullable().optional(),\n shop_cloudflare_image_id: z.string().nullable(),\n shop_domain: z.string().nullable().optional(),\n shop_force_paypal_email_delivery: z.union([z.literal(0), z.literal(1)]).optional(),\n shop_image_name: z.string().nullable(),\n shop_image_storage: z.string().nullable().optional(),\n shop_payment_gateways_fees: z.array(unknownRecordSchema).optional(),\n shop_paypal_credit_card: z.union([z.literal(0), z.literal(1)]).optional(),\n shop_return_url: z.string().nullable().optional(),\n shop_slug: z.string().nullable().optional(),\n shop_terms_enabled: z.boolean().optional(),\n shop_terms_of_service: z.string().nullable().optional(),\n shop_terms_url: z.string().nullable().optional(),\n shop_privacy_policy_url: z.string().nullable().optional(),\n shop_refund_policy_url: z.string().nullable().optional(),\n shop_walletconnect_id: z.string().nullable().optional(),\n status: z.string().nullable(),\n status_history: z.array(statusHistoryEntrySchema).optional(),\n status_history_legacy: z.array(statusHistoryEntrySchema).optional(),\n status_history_raw: z.array(statusHistoryEntrySchema).optional(),\n stripe_publishable_key: z.string().nullable().optional(),\n stripe_user_id: z.string().nullable().optional(),\n subtotal: z.number().optional(),\n subtype: z.string().nullable().optional(),\n support: supportSchema.optional(),\n theme: z.string().optional(),\n tip_amount: stringOrNumberSchema.nullable().optional(),\n tip_amount_display: stringOrNumberSchema.nullable().optional(),\n tip_metadata: z.unknown().optional(),\n total: stringOrNumberSchema,\n total_conversions: unknownRecordSchema.optional(),\n total_display: stringOrNumberSchema,\n type: z.string().nullable(),\n underpayment: underpaymentSchema.nullable().optional(),\n underpayment_status: z.string().nullable().optional(),\n uniqid: z.string(),\n void_times: z.array(voidTimeSchema).optional(),\n\n // PUBLIC_INVOICE_FIELDS entries not exercised by the golden fixtures.\n addons: z.unknown().optional(),\n affiliate_data: z.unknown().optional(),\n affiliate_revenue_customer_id: z.string().nullable().optional(),\n bill_info: z.unknown().optional(),\n binance_checkout_url: z.string().nullable().optional(),\n binance_invoice_id: z.string().nullable().optional(),\n binance_qrcode: z.string().nullable().optional(),\n bundle_config: z.unknown().optional(),\n bundles: z.unknown().optional(),\n cashapp_cashtag: z.string().nullable().optional(),\n cashapp_note: z.string().nullable().optional(),\n cashapp_qrcode: z.string().nullable().optional(),\n created_at: z.string().optional(),\n crypto_address: z.string().nullable().optional(),\n crypto_amount: stringOrNumberSchema.optional(),\n crypto_confirmations_needed: z.number().nullable().optional(),\n crypto_exchange_rate: stringOrNumberSchema.nullable().optional(),\n crypto_received: stringOrNumberSchema.optional(),\n crypto_uri: z.string().nullable().optional(),\n developer_invoice: z.unknown().optional(),\n developer_return_url: z.string().nullable().optional(),\n developer_title: z.string().nullable().optional(),\n exchange_rate: stringOrNumberSchema.nullable().optional(),\n external_order_id: z.string().nullable().optional(),\n lex_order_id: z.string().nullable().optional(),\n lex_payment_method: z.string().nullable().optional(),\n paydash_payment_id: z.string().nullable().optional(),\n paypal_apm: z.string().nullable().optional(),\n paypal_email_delivery: z.boolean().optional(),\n paypal_fee: stringOrNumberSchema.nullable().optional(),\n paypal_order_id: z.string().nullable().optional(),\n paypal_payer_email: z.string().nullable().optional(),\n paypal_subscription_id: z.string().nullable().optional(),\n paypal_subscription_link: z.string().nullable().optional(),\n perfectmoney_id: z.string().nullable().optional(),\n product_addons: z.unknown().optional(),\n product_id: z.string().nullable().optional(),\n product_title: z.string().nullable().optional(),\n product_type: z.string().nullable().optional(),\n product_variants: z.unknown().optional(),\n recurring_billing_id: z.string().nullable().optional(),\n skrill_link: z.string().nullable().optional(),\n skrill_sid: z.string().nullable().optional(),\n status_details: z.unknown().optional(),\n stripe_apm: z.string().nullable().optional(),\n stripe_client_secret: z.string().nullable().optional(),\n stripe_id: z.string().nullable().optional(),\n stripe_price_id: z.string().nullable().optional(),\n subscription: z.unknown().optional(),\n subscription_id: z.string().nullable().optional(),\n sumup_id: z.string().nullable().optional(),\n telegram_stars_payment_link: z.string().nullable().optional(),\n telegram_stars_payment_note: z.string().nullable().optional(),\n updated_at: z.string().optional(),\n virtual_payments_id: z.string().nullable().optional(),\n void_details: z.unknown().optional(),\n}).catchall(z.unknown());\n\nexport type PublicInvoiceWire = z.infer<typeof publicInvoiceWireSchema>;\n","/**\n * Catalog unit prices support mills (one thousandth of a currency unit).\n *\n * This is intentionally separate from invoice and payment totals. A unit can\n * cost $0.012, while the payable line total is still rounded to the currency's\n * minor unit after `unit price × quantity`.\n */\nexport const CATALOG_UNIT_PRICE_DECIMAL_PLACES = 3;\n\n/**\n * Payable line amounts and invoice totals remain cent amounts. This is a\n * separate boundary from catalog unit prices: multiply the mill-priced unit by\n * quantity first, then round the resulting line amount to this precision.\n */\nexport const PAYABLE_AMOUNT_DECIMAL_PLACES = 2;\n\nexport const CATALOG_UNIT_PRICE_FORMAT_OPTIONS = {\n maximumFractionDigits: CATALOG_UNIT_PRICE_DECIMAL_PLACES,\n} as const;\n\n/**\n * Browser-safe half-up rounding for non-negative payable amounts.\n *\n * The exponent shift avoids the common `1.005 * 100` binary-float trap and\n * mirrors the backend's decimal.js ROUND_HALF_UP policy. Negative values are\n * handled symmetrically so the helper remains safe for display calculations.\n */\nexport function roundPayableAmount(value: number): number {\n if (!Number.isFinite(value)) return value;\n\n const sign = value < 0 ? -1 : 1;\n const shifted = shiftDecimal(Math.abs(value), PAYABLE_AMOUNT_DECIMAL_PLACES);\n const rounded = Math.round(shifted);\n if (rounded === 0) return 0;\n return sign * shiftDecimal(rounded, -PAYABLE_AMOUNT_DECIMAL_PLACES);\n}\n\nfunction shiftDecimal(value: number, places: number): number {\n const [coefficient, currentExponent = '0'] = String(value).split('e');\n return Number(`${coefficient}e${Number(currentExponent) + places}`);\n}\n\nfunction countSignificantDecimalPlaces(value: string | number): number | null {\n const source = String(value).trim();\n const match = source.match(/^[-+]?(\\d+)(?:\\.(\\d*))?(?:e([-+]?\\d+))?$/i)\n ?? source.match(/^[-+]?\\.(\\d+)(?:e([-+]?\\d+))?$/i);\n if (!match) return null;\n\n const startsWithDecimalPoint = /^[-+]?\\./.test(source);\n const integerPart = startsWithDecimalPoint ? '0' : match[1];\n const fractionPart = startsWithDecimalPoint ? match[1] : (match[2] ?? '');\n const exponentText = startsWithDecimalPoint ? match[2] : match[3];\n const exponent = Number(exponentText ?? 0);\n if (!Number.isInteger(exponent)) return null;\n\n const digitsWithoutInsignificantZeros = `${integerPart}${fractionPart}`.replace(/0+$/, '');\n if (digitsWithoutInsignificantZeros.length === 0) return 0;\n\n const decimalPoint = integerPart.length + exponent;\n return Math.max(0, digitsWithoutInsignificantZeros.length - decimalPoint);\n}\n\nexport function hasCatalogUnitPricePrecision(value: string | number): boolean {\n const decimalPlaces = countSignificantDecimalPlaces(value);\n return decimalPlaces !== null && decimalPlaces <= CATALOG_UNIT_PRICE_DECIMAL_PLACES;\n}\n\nexport function getCatalogUnitPricePrecisionMessage(value: string | number): string {\n return `Price supports at most ${CATALOG_UNIT_PRICE_DECIMAL_PLACES} decimal places; received ${String(value)}.`;\n}\n","import { z } from 'zod';\n\nconst nullableStringSchema = z.string().nullable();\nconst unknownRecordSchema = z.record(z.string(), z.unknown());\n\nconst customerPortalBrandingSchema = z.object({\n logo_url: nullableStringSchema,\n primary_color: z.string(),\n secondary_color: z.string(),\n accent_color: z.string(),\n});\n\nconst customerPortalProductImageSnakeSchema = z.object({\n attachment_image_id: z.object({\n cloudflare_image_id: nullableStringSchema,\n }).nullable(),\n});\n\nconst customerPortalProductImageCamelSchema = z.object({\n attachment_imageId: z.object({\n cloudflareImageId: nullableStringSchema,\n }).nullable(),\n});\n\nexport const customerPortalDashboardInvoiceSchema = z.object({\n uniqid: z.string(),\n status: z.string(),\n total: z.string(),\n total_display: nullableStringSchema,\n currency: z.string(),\n created_at: z.string(),\n line_items: z.array(z.object({\n product_title: nullableStringSchema,\n quantity: z.number(),\n product: customerPortalProductImageSnakeSchema.nullable(),\n })),\n});\n\nexport const customerPortalPaginatedInvoiceSchema = z.object({\n uniqid: z.string(),\n status: z.string(),\n total: z.string(),\n totalDisplay: nullableStringSchema,\n currency: z.string(),\n createdAt: z.string(),\n lineItems: z.array(z.object({\n productTitle: nullableStringSchema,\n quantity: z.number(),\n product: customerPortalProductImageCamelSchema.nullable(),\n })),\n});\n\nexport const customerPortalPaginatedInvoicesSchema = z.object({\n invoices: z.array(customerPortalPaginatedInvoiceSchema),\n pagination: z.object({\n page: z.number(),\n limit: z.number(),\n total: z.number(),\n has_more: z.boolean(),\n }),\n});\n\nconst customerPortalPaymentSchema = z.object({\n gateway: z.string(),\n /** Merchant-configured buyer label frozen when the payment attempt started. */\n displayName: nullableStringSchema,\n /** Concrete coin gateway key (e.g. USDT_TRC20) for crypto payments — the\n * buyer-facing label; `gateway` may carry an internal rail name. */\n cryptoGateway: nullableStringSchema.optional(),\n blockchain: nullableStringSchema,\n cryptoAddress: nullableStringSchema,\n apmMethod: nullableStringSchema,\n});\n\nexport const customerPortalInvoiceDetailSchema = z.object({\n id: z.string(),\n uniqid: z.string(),\n status: z.string(),\n statusDetails: nullableStringSchema,\n total: z.string(),\n totalDisplay: nullableStringSchema,\n subtotal: z.string(),\n discount: z.string(),\n discountDisplay: nullableStringSchema,\n tax: z.string(),\n taxPercentage: z.string(),\n currency: z.string(),\n createdAt: z.string(),\n updatedAt: z.string(),\n gatewayUpdatedAt: nullableStringSchema,\n customFields: unknownRecordSchema.nullable(),\n balancePaidAmount: z.string(),\n currentPaymentAttemptId: nullableStringSchema,\n lineItems: z.array(z.object({\n id: z.string(),\n productTitle: z.string(),\n productType: z.string(),\n variantTitle: nullableStringSchema,\n unitPrice: z.string(),\n quantity: z.number(),\n total: z.string(),\n deliveryText: nullableStringSchema,\n deliverySummary: z.object({\n codes: z.array(z.string()),\n links: z.array(z.object({\n label: z.string(),\n value: z.string(),\n href: nullableStringSchema.optional(),\n })),\n notes: z.array(z.string()),\n serials: z.array(z.object({\n value: z.string(),\n is_replacement: z.boolean(),\n is_replaced: z.boolean(),\n })),\n }).nullable(),\n deliveredAt: nullableStringSchema,\n /**\n * Per-line fulfillment state, resolved server-side\n * (docs/architecture/domains/order-fulfillment.md). Independent of the\n * invoice payment status: a COMPLETED order can still hold items the\n * seller delivers later.\n */\n deliveryStatus: z.enum(['PENDING', 'AWAITING_FULFILLMENT', 'DELIVERED', 'FAILED']),\n customFields: unknownRecordSchema.nullable(),\n product: z.object({\n uniqid: z.string(),\n slug: nullableStringSchema,\n serviceText: nullableStringSchema,\n attachment_imageId: z.object({\n cloudflareImageId: nullableStringSchema,\n }).nullable(),\n }).nullable(),\n })),\n currentPayment: customerPortalPaymentSchema.nullable(),\n payments: z.array(customerPortalPaymentSchema),\n});\n\nexport const customerPortalWalletTopupQuoteSchema = z.object({\n quote: z.object({\n enabled: z.boolean(),\n currency: z.string(),\n min_amount: z.string(),\n max_amount: nullableStringSchema,\n bonus_tiers: z.array(z.object({\n min_amount: z.string(),\n bonus_percent: z.number(),\n })),\n }),\n});\n\nexport const customerPortalWalletTopupResultSchema = z.object({\n invoice_id: z.string(),\n url: z.string(),\n});\n\nexport const customerPortalRewardActivityItemSchema = z.object({\n id: z.string(),\n type: z.string(),\n status: z.string(),\n amount: nullableStringSchema,\n currency: nullableStringSchema,\n coupon_code: nullableStringSchema,\n reason: z.string(),\n trigger_reference_type: z.string(),\n trigger_reference_id: z.string(),\n created_at: z.number(),\n fulfilled_at: z.number().nullable(),\n expires_at: z.number().nullable(),\n});\n\nexport const customerPortalRewardsSchema = z.object({\n summary: z.object({\n available: z.string(),\n pending: z.string(),\n lifetime_earned: z.string(),\n redeemed: nullableStringSchema,\n currency: z.string(),\n }),\n activity: z.array(customerPortalRewardActivityItemSchema),\n earned_after_invoice: z.array(customerPortalRewardActivityItemSchema),\n pending_after_invoice: z.array(customerPortalRewardActivityItemSchema),\n});\n\nconst customerPortalAffiliateLinkSchema = z.object({\n id: z.string(),\n uniqid: z.string(),\n label: nullableStringSchema,\n code: z.string(),\n url: nullableStringSchema,\n status: z.enum(['pending', 'active', 'inactive', 'rejected']),\n is_primary: z.boolean(),\n total_clicks: z.number(),\n total_sales: z.number(),\n total_revenue: z.string(),\n is_active: z.boolean(),\n is_approved: z.boolean(),\n requested_affiliate_revenue_percent: z.number().nullable(),\n requested_affiliate_customer_discount_percent: z.number().nullable(),\n affiliate_revenue_percent_override: z.number().nullable(),\n affiliate_customer_discount_percent_override: z.number().nullable(),\n effective_commission_percent: z.number(),\n effective_customer_discount_percent: z.number(),\n commission_shareback_percent: z.number(),\n commission_shareback_enabled: z.boolean(),\n max_commission_shareback_percent: z.number(),\n created_at: nullableStringSchema,\n updated_at: nullableStringSchema,\n});\n\nexport const customerPortalAffiliateSummarySchema = z.object({\n customer: z.object({\n id: z.string(),\n email: z.string(),\n name: nullableStringSchema,\n }).nullable(),\n state: z.string(),\n can_create_custom_links: z.boolean(),\n custom_link_request_disabled_reason: nullableStringSchema,\n custom_links_require_approval: z.boolean(),\n affiliate_codes_accepted_at_checkout: z.boolean(),\n cash_payout_enabled: z.boolean(),\n links: z.array(customerPortalAffiliateLinkSchema),\n preferred_payout: z.object({\n asset: z.string(),\n network: z.string(),\n address: z.string(),\n }).nullable(),\n balance_currency: z.string(),\n balances: z.object({\n pending: z.string(),\n available: z.string(),\n requested: z.string(),\n converted: z.string(),\n paid: z.string(),\n approved_total: z.string(),\n }),\n commissions: z.array(z.object({\n id: z.string(),\n invoice_id: z.string(),\n commission_amount: z.string(),\n base_amount: z.string(),\n discount_amount: z.string(),\n status: z.string(),\n created_at: nullableStringSchema,\n paid_at: nullableStringSchema,\n converted_at: nullableStringSchema,\n })),\n claims: z.array(z.object({\n id: z.string(),\n type: z.string(),\n status: z.string(),\n amount: z.string(),\n currency: z.string(),\n allocations: z.array(z.object({\n source_type: z.string(),\n commission_id: nullableStringSchema,\n adjustment_id: nullableStringSchema,\n amount: z.string(),\n })),\n wallet_transaction_id: nullableStringSchema,\n payout_asset: nullableStringSchema,\n payout_network: nullableStringSchema,\n payout_address: nullableStringSchema,\n note: nullableStringSchema,\n metadata: z.unknown(),\n completed_at: nullableStringSchema,\n rejected_at: nullableStringSchema,\n cancelled_at: nullableStringSchema,\n created_at: nullableStringSchema,\n updated_at: nullableStringSchema,\n })),\n});\n\nexport const customerPortalSubscriptionSummarySchema = z.object({\n uniqid: z.string(),\n status: z.string(),\n gateway: z.string(),\n current_period_start: z.string(),\n current_period_end: z.string(),\n trial_end: nullableStringSchema,\n cancel_at_period_end: z.boolean(),\n canceled_at: nullableStringSchema,\n created_at: z.string(),\n plan: z.object({\n id: z.string(),\n uniqid: z.string(),\n name: z.string(),\n price: z.string(),\n currency: z.string(),\n interval: z.string(),\n interval_count: z.number(),\n trial_days: z.number(),\n }).nullable(),\n payment_method: z.object({\n id: z.string(),\n gateway: z.string(),\n type: z.string(),\n card_brand: nullableStringSchema,\n card_last4: nullableStringSchema,\n card_exp_month: z.number().nullable(),\n card_exp_year: z.number().nullable(),\n is_default: z.boolean(),\n }).nullable(),\n actions: z.object({\n can_pause: z.boolean(),\n can_resume: z.boolean(),\n can_cancel: z.boolean(),\n can_manage_payment_method: z.boolean(),\n }),\n});\n\nexport const customerPortalDashboardSchema = z.object({\n shop: z.object({\n id: z.string(),\n slug: z.string(),\n name: z.string(),\n currency: z.string(),\n branding: customerPortalBrandingSchema,\n }),\n customer: z.object({\n email: z.string(),\n name: z.string(),\n }),\n stats: z.object({\n invoices_count: z.number(),\n licenses_count: z.number(),\n deliverables_count: z.number(),\n tickets_count: z.number(),\n }),\n wallet: z.object({\n available: z.string(),\n total: z.string(),\n hold: z.string(),\n currency: z.string(),\n enabled: z.boolean(),\n }).nullable(),\n rewards: customerPortalRewardsSchema,\n affiliate: customerPortalAffiliateSummarySchema,\n invoices: z.array(customerPortalDashboardInvoiceSchema),\n subscriptions: z.array(customerPortalSubscriptionSummarySchema),\n licenses: z.array(z.object({\n uniqid: z.string(),\n /*\n * Both of these are produced by `getCustomerProductsLicenses` and were\n * simply missing here. Without `invoice_id` a consumer cannot tell which\n * purchase a license belongs to, and without `status` it cannot tell an\n * active license from a suspended, revoked or expired one — the projection\n * computes exactly that.\n */\n invoice_id: z.string(),\n status: z.string(),\n license_key: z.string(),\n hardware_id: nullableStringSchema,\n expires_at: z.number().nullable(),\n /*\n * Server-decided: the product behind this license still exists, still\n * sells through storefront checkout, and still has licensing enabled.\n * The portal cannot derive any of that, so it renders the renew action\n * from this flag alone instead of guessing and offering a dead button.\n */\n renewable: z.boolean(),\n product: z.object({\n title: z.string().optional(),\n }).optional(),\n })),\n deliverables: z.array(z.object({\n id: z.string(),\n invoice_uniqid: z.string(),\n product_title: z.string(),\n kind: z.enum(['file', 'serial', 'license']),\n label: z.string(),\n value: z.string(),\n href: nullableStringSchema,\n created_at: z.string(),\n })),\n tickets: z.array(z.object({\n uniqid: z.string(),\n title: z.string(),\n status: z.string(),\n updated_at: z.string(),\n created_at: nullableStringSchema,\n })),\n});\n\nexport type CustomerPortalDashboardWire = z.infer<typeof customerPortalDashboardSchema>;\nexport type CustomerPortalAffiliateSummaryWire = z.infer<typeof customerPortalAffiliateSummarySchema>;\nexport type CustomerPortalInvoiceDetailWire = z.infer<typeof customerPortalInvoiceDetailSchema>;\nexport type CustomerPortalPaginatedInvoicesWire = z.infer<typeof customerPortalPaginatedInvoicesSchema>;\nexport type CustomerPortalRewardActivityItemWire = z.infer<typeof customerPortalRewardActivityItemSchema>;\nexport type CustomerPortalRewardsWire = z.infer<typeof customerPortalRewardsSchema>;\nexport type CustomerPortalSubscriptionSummaryWire = z.infer<typeof customerPortalSubscriptionSummarySchema>;\nexport type CustomerPortalWalletTopupQuoteWire = z.infer<typeof customerPortalWalletTopupQuoteSchema>;\nexport type CustomerPortalWalletTopupResultWire = z.infer<typeof customerPortalWalletTopupResultSchema>;\n","/**\n * @shoppex/contracts\n *\n * Shared TypeScript types generated from OpenAPI spec.\n * These types ensure type-safety between the Elysia API runtime and frontend apps.\n *\n * Usage:\n * import { paths, components } from '@shoppex/contracts/api-types';\n * import { createApiClient } from '@shoppex/contracts';\n */\n\nimport createClient from 'openapi-fetch';\nimport type { paths } from './api-types.js';\n\n// Re-export generated types\nexport * from './api-types.js';\nexport * from './navigation.js';\nexport * from './observability.js';\nexport * from './email-marketing.js';\nexport * from './payment-gateways.js';\nexport * from './platform-billing.js';\nexport * from './style-center.js';\nexport * from './style-center/presets.js';\nexport * from './storefront-addons.js';\nexport * from './api-error-codes.js';\nexport * from './merchant-safe-errors.js';\nexport * from './manual-gateway-template.js';\nexport * from './redirect-link-template.js';\nexport * from './checkout-api.js';\nexport * from './invoice-wire.js';\nexport * from './developer-webhook.js';\nexport * from './catalog-unit-price.js';\nexport * from './customer-portal-wire.js';\nexport * from './type-assertions.js';\nexport * from './theme-ai-handoff.js';\n\n/**\n * Create a type-safe API client\n *\n * @example\n * const client = createApiClient('https://api.shoppex.io/v1');\n *\n * // Fully typed request and response\n * const { data, error } = await client.GET('/products', {\n * params: { query: { page: 1, limit: 25 } }\n * });\n */\nexport function createApiClient(baseUrl: string, token?: string) {\n return createClient<paths>({\n baseUrl,\n headers: token ? { Authorization: `Bearer ${token}` } : undefined,\n });\n}\n\n// Common response types used across the app\nexport interface ApiResponse<T> {\n status: number;\n data: T | null;\n error: string | null;\n message: string | null;\n env: string;\n}\n\nexport interface PaginatedResponse<T> {\n data: T[];\n meta: {\n total: number;\n page: number;\n perPage: number;\n totalPages: number;\n };\n}\n\nexport interface ApiError {\n status: number;\n error: string;\n message: string;\n}\n","/**\n * Typed OpenAPI client factory.\n *\n * Surfaces the generated `createApiClient` from `@shoppex/contracts` with the\n * SDK's configured `apiBaseUrl`. This lets consumers of `@shoppexio/storefront`\n * call any public Dev API endpoint with full end-to-end types without\n * rebuilding a client from scratch.\n *\n * Prefer the high-level modules (`shoppex.getProducts()` etc.) for common\n * read flows — they handle caching, pagination defaults, and storefront\n * scoping. Drop down to `shoppex.client()` only when you need an endpoint\n * the high-level API does not cover yet.\n */\n\nimport { createApiClient } from '@shoppex/contracts';\nimport { DEFAULT_API_BASE_URL, getConfig } from './config';\n\ntype ApiClient = ReturnType<typeof createApiClient>;\n\nlet cachedClient: ApiClient | null = null;\nlet cachedBaseUrl: string | null = null;\n\n/**\n * Return a typed OpenAPI client bound to the SDK's configured API base URL.\n * The client is cached per base URL and recreated when the SDK is re-initialized\n * against a different host.\n */\nexport function getTypedClient(token?: string): ApiClient {\n const config = getConfig();\n const baseUrl = config.apiBaseUrl ?? DEFAULT_API_BASE_URL;\n\n if (cachedClient && cachedBaseUrl === baseUrl && !token) {\n return cachedClient;\n }\n\n const client = createApiClient(baseUrl, token);\n\n if (!token) {\n cachedClient = client;\n cachedBaseUrl = baseUrl;\n }\n\n return client;\n}\n\n/**\n * Reset the cached client. Called when the SDK is re-initialized so that a new\n * `apiBaseUrl` takes effect immediately on the next `client()` call.\n */\nexport function resetTypedClient(): void {\n cachedClient = null;\n cachedBaseUrl = null;\n}\n","/**\n * SDK Configuration Management\n */\n\nimport type { ShoppexConfig, ShoppexInitOptions } from '../types';\nimport { clearCache } from './cache';\nimport { NotInitializedError } from './errors';\nimport { resetTypedClient } from './typed-client';\n\nexport const DEFAULT_API_BASE_URL = 'https://api.shoppex.io';\n\nlet currentConfig: ShoppexConfig | null = null;\nlet cachedShopId: string | null = null;\n\nexport const DEFAULT_CHECKOUT_BASE_URL = 'https://checkout.shoppex.io';\n\nexport function initConfig(\n storeSlug: string,\n options?: ShoppexInitOptions\n): ShoppexConfig {\n const normalizedShopId = options?.shopId?.trim();\n\n // Reset cached shop id on every init to avoid cross-store leakage\n // when the SDK is re-initialized with a different slug.\n cachedShopId = normalizedShopId ? normalizedShopId : null;\n\n const previousLocale = currentConfig?.locale;\n currentConfig = {\n storeSlug,\n locale: options?.locale,\n currency: options?.currency,\n apiBaseUrl: options?.apiBaseUrl ?? DEFAULT_API_BASE_URL,\n checkoutBaseUrl: options?.checkoutBaseUrl ?? DEFAULT_CHECKOUT_BASE_URL,\n };\n // Response cache keys are locale-agnostic (products:slug, product:id, …) —\n // a locale switch across re-inits must not serve the previous locale's\n // payloads for up to the cache TTL (Codex P2).\n if (previousLocale !== currentConfig.locale) {\n clearCache();\n }\n resetTypedClient();\n return currentConfig;\n}\n\nexport function getConfig(): ShoppexConfig {\n if (!currentConfig) {\n throw new NotInitializedError();\n }\n return currentConfig;\n}\n\nexport function isInitialized(): boolean {\n return currentConfig !== null;\n}\n\nexport function resetConfig(): void {\n currentConfig = null;\n cachedShopId = null;\n resetTypedClient();\n}\n\nexport function setShopId(shopId: string): void {\n cachedShopId = shopId;\n}\n\nexport function getShopId(): string | null {\n return cachedShopId;\n}\n","export interface StorefrontCustomField {\n name: string;\n type: string;\n required: boolean;\n defaultValue: string;\n placeholder: string;\n regex?: string;\n}\n\nfunction parseCustomFieldsSource(raw: unknown): unknown[] {\n if (Array.isArray(raw)) return raw;\n\n if (typeof raw === 'string') {\n try {\n const parsed = JSON.parse(raw) as unknown;\n if (Array.isArray(parsed)) return parsed;\n if (parsed && typeof parsed === 'object') {\n const fields = (parsed as { custom_fields?: unknown[]; customFields?: unknown[] }).custom_fields\n ?? (parsed as { custom_fields?: unknown[]; customFields?: unknown[] }).customFields;\n return Array.isArray(fields) ? fields : [];\n }\n } catch {\n return [];\n }\n\n return [];\n }\n\n if (raw && typeof raw === 'object') {\n const fields = (raw as { custom_fields?: unknown[]; customFields?: unknown[] }).custom_fields\n ?? (raw as { custom_fields?: unknown[]; customFields?: unknown[] }).customFields;\n return Array.isArray(fields) ? fields : [];\n }\n\n return [];\n}\n\nexport function normalizeStorefrontCustomFields(raw: unknown): StorefrontCustomField[] {\n return parseCustomFieldsSource(raw)\n .filter((field): field is Record<string, unknown> => !!field && typeof field === 'object' && !Array.isArray(field))\n .map((field) => {\n const rawType = typeof field.type === 'string' ? field.type.trim().toLowerCase() : 'text';\n const type = rawType.length > 0 ? rawType : 'text';\n const defaultValue = [\n field.default_value,\n field.default,\n field.value,\n ].find((candidate) => typeof candidate === 'string' && candidate.trim().length > 0);\n\n return {\n name: typeof field.name === 'string' ? field.name.trim() : '',\n type,\n required: field.required === true || field.required === 'true' || field.required === 1 || field.required === '1',\n defaultValue: typeof defaultValue === 'string' ? defaultValue : '',\n placeholder: typeof field.placeholder === 'string' ? field.placeholder : '',\n regex: typeof field.regex === 'string' ? field.regex : undefined,\n };\n })\n .filter((field) => field.name.length > 0 && field.type !== 'hidden');\n}\n\nexport function isStorefrontCheckboxCustomFieldValueChecked(value: string | undefined): boolean {\n const normalized = value?.trim().toLowerCase() ?? '';\n return normalized === 'true' || normalized === '1' || normalized === 'yes' || normalized === 'on';\n}\n\nexport function validateStorefrontCustomFieldValue(field: StorefrontCustomField, value: string): string | null {\n if (field.type === 'checkbox') {\n if (field.required && !isStorefrontCheckboxCustomFieldValueChecked(value)) {\n return `${field.name} is required.`;\n }\n return null;\n }\n\n const normalized = value.trim();\n if (field.required && !normalized) {\n return `${field.name} is required.`;\n }\n\n if (field.regex && normalized) {\n try {\n const pattern = new RegExp(field.regex);\n if (!pattern.test(normalized)) {\n return `${field.name} has an invalid format.`;\n }\n } catch {\n return null;\n }\n }\n\n return null;\n}\n\nexport function buildStorefrontCustomFieldPayload(\n fields: StorefrontCustomField[],\n values: Record<string, string>,\n): Record<string, string> {\n const nextValues: Record<string, string> = {};\n\n fields.forEach((field) => {\n const rawValue = values[field.name] ?? field.defaultValue ?? '';\n\n if (field.type === 'checkbox') {\n if (isStorefrontCheckboxCustomFieldValueChecked(rawValue)) {\n nextValues[field.name] = 'true';\n }\n return;\n }\n\n const normalized = rawValue.trim();\n if (normalized.length > 0) {\n nextValues[field.name] = normalized;\n }\n });\n\n return nextValues;\n}\n","import type { Product, PriceVariant, ProductVariant } from '../types/index.js';\n\ntype VariantLike =\n | Pick<ProductVariant, 'stock' | 'orderable' | 'supplier_backed'>\n | Pick<PriceVariant, 'stock' | 'orderable' | 'supplier_backed'>;\n\ntype ProductLike = Pick<Product, 'type' | 'stock' | 'orderable' | 'supplier_backed' | 'on_hold' | 'price_variants' | 'variants'> & {\n onHold?: boolean | number | string | null;\n is_on_hold?: boolean | number | string | null;\n isOnHold?: boolean | number | string | null;\n};\n\n/** The sentinel every predicate in this module already treats as \"unbounded\". */\nconst UNLIMITED_STOCK = -1;\n\n/**\n * Dynamic Delivery (S8): fold `orderable` into the stock value.\n *\n * `orderable` is the backend's authoritative buyability predicate — `local stock\n * covers one unit OR an eligible supplier source can fulfil the line` — and it is\n * exactly what the order-time gates apply. A supplier-backed row holds NO local\n * stock by design, so gating the buyer on `stock` alone renders it \"out of stock\"\n * and the purchase can never happen.\n *\n * Rather than introduce a fourth availability state, a row that is orderable\n * without local units is normalised to the unlimited sentinel — the same value an\n * unlimited row already carries. Every downstream badge, quantity cap, variant\n * gate and CTA then behaves as it already does for unlimited stock.\n *\n * `orderable` alone cannot decide how far to widen: it is also `true` for an\n * ordinary locally-stocked row, whose finite counter must stay finite. That is what\n * `supplier_backed` settles. A supplier-backed row is fulfilled by the supplier\n * purchase and the completion excludes it from the local decrement, so any residual\n * local units bound NOTHING — its cap is unlimited even at `stock: 1`. A row that is\n * NOT supplier-backed keeps its exact finite counter, and only widens from 0 (the\n * product-wide mapping case, where the backend folded the mapping into `orderable`\n * and left `stock` at 0).\n *\n * When `orderable` is absent (an older payload or a cached response shape that\n * predates the field) the raw value is returned UNCHANGED, and an absent\n * `supplier_backed` widens nothing beyond what the previous rule already did. That\n * is the only permitted fallback direction: a missing field must never flip a\n * genuinely sold-out row into a buyable one, nor a finite counter into unlimited.\n */\nfunction applyOrderable(stock: number, orderable: unknown, supplierBacked?: unknown): number {\n if (orderable !== true) {\n return stock;\n }\n // Supplier-backed: local units do not bound the line, at any stock value.\n if (supplierBacked === true) {\n return UNLIMITED_STOCK;\n }\n // Already buyable or already unbounded — nothing to widen.\n if (stock !== 0) {\n return stock;\n }\n return UNLIMITED_STOCK;\n}\n\nfunction normalizeStockValue(value: unknown): number | null {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n return null;\n }\n\n return Math.trunc(value);\n}\n\nfunction isTruthyFlag(value: unknown): boolean {\n if (value === true) return true;\n if (typeof value === 'number' && Number.isFinite(value)) return value !== 0;\n if (typeof value === 'string') {\n const normalized = value.trim().toLowerCase();\n return normalized === 'true' || normalized === '1';\n }\n return false;\n}\n\nfunction isProductOnHold(product: ProductLike | null | undefined): boolean {\n if (!product) return false;\n return isTruthyFlag(product.on_hold)\n || isTruthyFlag(product.onHold)\n || isTruthyFlag(product.is_on_hold)\n || isTruthyFlag(product.isOnHold);\n}\n\nfunction collectVariantStocks(product: ProductLike): number[] {\n const priceVariants = Array.isArray(product.price_variants) ? product.price_variants : [];\n if (priceVariants.length > 0) {\n return priceVariants.map((variant) => resolveVariantStockValue(variant));\n }\n\n const legacyVariants = Array.isArray(product.variants) ? product.variants : [];\n\n return legacyVariants.map((variant) => resolveVariantStockValue(variant));\n}\n\nexport function resolveVariantStockValue(variant: VariantLike | null | undefined): number {\n const normalized = normalizeStockValue(variant?.stock);\n return applyOrderable(normalized ?? UNLIMITED_STOCK, variant?.orderable, variant?.supplier_backed);\n}\n\nexport function resolveDisplayStock(product: ProductLike | null | undefined): number {\n if (!product) {\n return UNLIMITED_STOCK;\n }\n\n if (typeof product.type === 'string' && product.type.toUpperCase() === 'SERIALS') {\n return applyOrderable(\n normalizeStockValue(product.stock) ?? UNLIMITED_STOCK,\n product.orderable,\n product.supplier_backed,\n );\n }\n\n const variantStocks = collectVariantStocks(product);\n if (variantStocks.length > 0) {\n // A single unbounded option (including a supplier-backed one, already folded\n // into the sentinel above) makes the product unbounded — summing finite\n // siblings would understate it.\n if (variantStocks.some((stock) => stock < 0)) {\n return UNLIMITED_STOCK;\n }\n\n const total = variantStocks.reduce((sum, stock) => sum + Math.max(stock, 0), 0);\n // The product-level flag still applies: the backend folds a product-wide\n // supplier mapping into it, and that mapping backs options with no local units.\n return applyOrderable(total, product.orderable, product.supplier_backed);\n }\n\n return applyOrderable(\n normalizeStockValue(product.stock) ?? UNLIMITED_STOCK,\n product.orderable,\n product.supplier_backed,\n );\n}\n\nexport function isProductOutOfStock(product: ProductLike | null | undefined): boolean {\n // `on_hold` is a merchant pause, not a supply signal — it forces unavailable\n // BEFORE any `orderable` widening can apply.\n if (isProductOnHold(product)) return true;\n return resolveDisplayStock(product) === 0;\n}\n\nexport function isProductInStock(product: ProductLike | null | undefined): boolean {\n return !isProductOutOfStock(product);\n}\n\nexport function isVariantOutOfStock(variant: VariantLike | null | undefined): boolean {\n return resolveVariantStockValue(variant) === 0;\n}\n","import type { Product, ProductGroup } from '../types/index.js';\n\nexport function buildStorefrontProductLookup(products: Product[] = []): Map<string, Product> {\n const lookup = new Map<string, Product>();\n for (const product of products) {\n if (!product?.uniqid || lookup.has(product.uniqid)) continue;\n lookup.set(product.uniqid, product);\n }\n return lookup;\n}\n\n// Groups reference their products by uniqid; the objects live once in `products`.\nexport function getStorefrontGroupProducts(\n group: ProductGroup,\n productsOrLookup: Product[] | Map<string, Product> = [],\n): Product[] {\n const lookup = productsOrLookup instanceof Map\n ? productsOrLookup\n : buildStorefrontProductLookup(productsOrLookup);\n return (group.product_uniqids ?? []).flatMap((uniqid) => {\n const product = lookup.get(uniqid);\n return product ? [product] : [];\n });\n}\n\nexport function getMergedStorefrontProducts(products: Product[] = []): Product[] {\n return Array.from(buildStorefrontProductLookup(products).values());\n}\n","import type { Product, ProductGroup } from '../types/index.js';\nimport {\n buildStorefrontProductLookup,\n getMergedStorefrontProducts,\n getStorefrontGroupProducts,\n} from './storefront-catalog.js';\nimport { isProductInStock } from './storefront-stock.js';\n\nexport interface StorefrontSearchFilterOptions {\n hideOutOfStock?: boolean;\n maxResults?: number;\n}\n\nexport type StorefrontCatalogSearchItem =\n | { type: 'product'; product: Product }\n // Groups only carry `product_uniqids`; `products` holds the resolved product\n // objects (in group order) so consumers never re-resolve references themselves.\n | { type: 'group'; group: ProductGroup; products: Product[] };\n\nexport function stripHtmlFromText(value: string | null | undefined): string {\n if (!value) return '';\n return value.replace(/<[^>]*>/g, ' ').replace(/\\s+/g, ' ').trim();\n}\n\nexport function normalizeSearchQuery(query: string): string {\n return query.trim().toLowerCase();\n}\n\nfunction pushSearchPart(parts: string[], value: string | null | undefined): void {\n const normalized = stripHtmlFromText(value).toLowerCase();\n if (normalized) {\n parts.push(normalized);\n }\n}\n\nexport function collectProductSearchHaystack(product: Product): string[] {\n const parts: string[] = [];\n\n pushSearchPart(parts, product.title);\n pushSearchPart(parts, product.slug ?? undefined);\n pushSearchPart(parts, product.description);\n\n for (const highlight of product.product_highlights ?? []) {\n pushSearchPart(parts, highlight);\n }\n\n for (const variant of product.variants ?? []) {\n pushSearchPart(parts, variant.title);\n }\n\n for (const variant of product.price_variants ?? []) {\n pushSearchPart(parts, variant.title ?? variant.label);\n }\n\n return parts;\n}\n\nexport function productMatchesSearchQuery(product: Product, query: string): boolean {\n const normalized = normalizeSearchQuery(query);\n if (!normalized) return false;\n\n return collectProductSearchHaystack(product).some((haystack) => haystack.includes(normalized));\n}\n\nexport function groupMatchesSearchQuery(group: ProductGroup, query: string): boolean {\n const normalized = normalizeSearchQuery(query);\n if (!normalized) return false;\n\n const title = stripHtmlFromText(group.title).toLowerCase();\n const slug = stripHtmlFromText(group.slug ?? group.name ?? undefined).toLowerCase();\n const description = stripHtmlFromText(group.description).toLowerCase();\n\n return title.includes(normalized)\n || slug.includes(normalized)\n || description.includes(normalized);\n}\n\nexport function filterProductsBySearchQuery(\n products: Product[],\n query: string,\n options?: StorefrontSearchFilterOptions,\n): Product[] {\n const normalized = normalizeSearchQuery(query);\n if (!normalized) return [];\n\n let results = products.filter((product) => productMatchesSearchQuery(product, normalized));\n\n if (options?.hideOutOfStock) {\n results = results.filter((product) => isProductInStock(product));\n }\n\n if (options?.maxResults != null) {\n return results.slice(0, options.maxResults);\n }\n\n return results;\n}\n\nfunction groupHasVisibleProducts(\n groupProducts: Product[],\n hideOutOfStock: boolean,\n): boolean {\n if (groupProducts.length === 0) return false;\n if (!hideOutOfStock) return true;\n return groupProducts.some((product) => isProductInStock(product));\n}\n\nexport function searchMergedStorefrontCatalogItems(\n products: Product[],\n groups: ProductGroup[],\n query: string,\n options?: StorefrontSearchFilterOptions,\n): StorefrontCatalogSearchItem[] {\n const normalized = normalizeSearchQuery(query);\n if (!normalized) return [];\n\n const hideOutOfStock = options?.hideOutOfStock === true;\n const coveredProductIds = new Set<string>();\n const coveredGroupIds = new Set<string>();\n const results: StorefrontCatalogSearchItem[] = [];\n // Build the uniqid lookup once per search run; groups resolve against it.\n const lookup = buildStorefrontProductLookup(products);\n\n for (const group of groups) {\n const groupKey = group.uniqid ?? group.id;\n if (!groupKey || coveredGroupIds.has(groupKey)) continue;\n if (!groupMatchesSearchQuery(group, normalized)) continue;\n\n const groupProducts = getStorefrontGroupProducts(group, lookup);\n if (!groupHasVisibleProducts(groupProducts, hideOutOfStock)) continue;\n\n coveredGroupIds.add(groupKey);\n for (const product of groupProducts) {\n if (product?.uniqid) coveredProductIds.add(product.uniqid);\n }\n results.push({ type: 'group', group, products: groupProducts });\n }\n\n const merged = getMergedStorefrontProducts(products);\n for (const product of merged) {\n if (!product?.uniqid || coveredProductIds.has(product.uniqid)) continue;\n if (!productMatchesSearchQuery(product, normalized)) continue;\n if (hideOutOfStock && !isProductInStock(product)) continue;\n coveredProductIds.add(product.uniqid);\n results.push({ type: 'product', product });\n }\n\n if (options?.maxResults != null) {\n return results.slice(0, options.maxResults);\n }\n\n return results;\n}\n\nexport function searchMergedStorefrontCatalog(\n products: Product[],\n groups: ProductGroup[],\n query: string,\n options?: StorefrontSearchFilterOptions,\n): Product[] {\n const items = searchMergedStorefrontCatalogItems(products, groups, query, options);\n const matchedIds = new Set<string>();\n const results: Product[] = [];\n\n const addProduct = (product: Product) => {\n if (!product?.uniqid || matchedIds.has(product.uniqid)) return;\n if (options?.hideOutOfStock && !isProductInStock(product)) return;\n matchedIds.add(product.uniqid);\n results.push(product);\n };\n\n for (const item of items) {\n if (item.type === 'product') {\n addProduct(item.product);\n continue;\n }\n\n for (const product of item.products) {\n addProduct(product);\n }\n }\n\n if (options?.maxResults != null) {\n return results.slice(0, options.maxResults);\n }\n\n return results;\n}\n","import { DEFAULT_API_BASE_URL } from '../core/config';\n\nexport type StorefrontContactTicketInput = {\n shopSlug: string;\n email: string;\n message: string;\n title?: string;\n name?: string;\n invoiceId?: string;\n apiBaseUrl?: string;\n};\n\nexport type StorefrontContactTicketResult = {\n uniqid: string;\n};\n\nfunction isLocalDevHost(host: string): boolean {\n if (host === 'localhost' || host === '127.0.0.1' || host === '::1' || host.endsWith('.localhost')) {\n return true;\n }\n if (/^10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(host)) {\n return true;\n }\n if (/^192\\.168\\.\\d{1,3}\\.\\d{1,3}$/.test(host)) {\n return true;\n }\n const private172 = host.match(/^172\\.(\\d{1,2})\\.\\d{1,3}\\.\\d{1,3}$/);\n if (private172) {\n const octet = Number(private172[1]);\n return octet >= 16 && octet <= 31;\n }\n return false;\n}\n\nexport function resolveStorefrontApiBaseUrl(options?: {\n apiBaseUrl?: string;\n hostname?: string;\n}): string {\n if (options?.apiBaseUrl?.trim()) {\n return options.apiBaseUrl.replace(/\\/+$/, '');\n }\n\n const hostname = options?.hostname\n ?? (typeof window !== 'undefined' ? window.location.hostname : '');\n\n if (hostname && !isLocalDevHost(hostname)) {\n return DEFAULT_API_BASE_URL;\n }\n\n // Edge/njk commerce is a classic IIFE (not an ES module) — import.meta is a syntax error there.\n // Storefront bootstrap sets window.apiBaseUrl; Vite/React callers may pass options.apiBaseUrl.\n if (typeof window !== 'undefined') {\n const bootstrapBase = (window as { apiBaseUrl?: unknown }).apiBaseUrl;\n if (typeof bootstrapBase === 'string' && bootstrapBase.trim()) {\n return bootstrapBase.replace(/\\/+$/, '');\n }\n }\n\n return 'http://localhost:3001'.replace(/\\/+$/, '');\n}\n\nexport function buildStorefrontContactMessage(input: {\n name?: string;\n message: string;\n maxLength?: number;\n}): string {\n const customerName = input.name?.trim() ?? '';\n const baseMessage = input.message.trim();\n const fullMessage = `${customerName ? `Name: ${customerName}\\n\\n` : ''}${baseMessage}`;\n const maxLength = input.maxLength ?? 2000;\n return fullMessage.slice(0, maxLength);\n}\n\nexport async function submitStorefrontContactTicket(\n input: StorefrontContactTicketInput,\n): Promise<StorefrontContactTicketResult> {\n const shopSlug = input.shopSlug.trim();\n if (!shopSlug) {\n throw new Error('Store data is not ready yet. Please try again in a moment.');\n }\n\n const normalizedEmail = input.email.trim().toLowerCase();\n const subject = input.title?.trim() ?? '';\n const title = subject.length >= 2 ? subject.slice(0, 30) : 'Contact Request';\n const message = buildStorefrontContactMessage({\n name: input.name,\n message: input.message,\n });\n const invoiceId = input.invoiceId?.trim() || undefined;\n const apiBaseUrl = resolveStorefrontApiBaseUrl({ apiBaseUrl: input.apiBaseUrl });\n\n const response = await fetch(\n `${apiBaseUrl}/v1/storefront/shops/name/${encodeURIComponent(shopSlug)}/tickets`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n body: JSON.stringify({\n email: normalizedEmail,\n title,\n message,\n ...(invoiceId ? { invoice_id: invoiceId } : {}),\n }),\n },\n );\n\n const payload = await response.json().catch(() => null) as {\n message?: string;\n error?: string;\n data?: { uniqid?: string };\n } | null;\n\n if (!response.ok) {\n throw new Error(payload?.message || payload?.error || 'Failed to send your message.');\n }\n\n const uniqid = payload?.data?.uniqid;\n if (!uniqid) {\n throw new Error('Ticket created, but the response was incomplete.');\n }\n\n return { uniqid };\n}\n\nexport type StorefrontSocialLinks = {\n discord?: string | null;\n telegram?: string | null;\n};\n\nexport function resolveStorefrontSocialLinks(store: {\n discord_link?: string | null;\n telegram_link?: string | null;\n social?: Record<string, string | null | undefined> | null;\n} | null | undefined): StorefrontSocialLinks {\n return {\n discord: store?.discord_link ?? store?.social?.discord ?? null,\n telegram: store?.telegram_link ?? store?.social?.telegram ?? null,\n };\n}\n","const PARAM_PATTERN = /:([A-Za-z0-9_]+)/g;\n\nexport function buildEndpoint(\n template: string,\n params: Record<string, string | number | null | undefined>\n): string {\n return template.replace(PARAM_PATTERN, (_, key: string) => {\n const rawValue = params[key];\n if (rawValue === null || rawValue === undefined) {\n throw new Error(`Missing endpoint param: ${key}`);\n }\n\n const value = String(rawValue).trim();\n if (!value) {\n throw new Error(`Endpoint param \"${key}\" must not be empty`);\n }\n\n return encodeURIComponent(value);\n });\n}\n","/**\n * localStorage Wrapper\n *\n * Handles localStorage access with error handling for\n * environments where localStorage is not available.\n */\n\nconst STORAGE_PREFIX = 'shoppex_';\n\nfunction getKey(key: string): string {\n return `${STORAGE_PREFIX}${key}`;\n}\n\nexport function getItem<T>(key: string): T | null {\n try {\n const item = localStorage.getItem(getKey(key));\n if (!item) return null;\n return JSON.parse(item) as T;\n } catch {\n return null;\n }\n}\n\nexport function setItem<T>(key: string, value: T): void {\n try {\n localStorage.setItem(getKey(key), JSON.stringify(value));\n } catch {\n console.warn('[shoppex] Failed to save to localStorage');\n }\n}\n\nexport function removeItem(key: string): void {\n try {\n localStorage.removeItem(getKey(key));\n } catch {\n // Ignore errors\n }\n}\n","import { getConfig, getShopId, isInitialized } from './config';\nimport { buildEndpoint } from './endpoint';\nimport { getItem, setItem } from '../utils/storage';\n\nconst CONNECTION_ID_STORAGE_PREFIX = 'presence_connection_';\nconst CLIENT_ERROR_DEDUPE_WINDOW_MS = 15_000;\n\ntype VisibilityStateValue = 'hidden' | 'visible' | 'prerender' | 'unloaded';\ntype RequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\nexport interface StorefrontClientErrorPayload {\n endpoint: string;\n method: RequestMethod;\n message: string;\n statusCode?: number;\n source?: 'sdk';\n phase?: 'request';\n attemptCount?: number;\n responseReceived?: boolean;\n pageUrl?: string;\n requestUrl?: string;\n online?: boolean;\n visibilityState?: VisibilityStateValue;\n}\n\nfunction createPresenceConnectionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `spx_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;\n}\n\nexport function getStorefrontConnectionId(storeSlug: string): string | null {\n if (typeof window === 'undefined') return null;\n\n const storageKey = `${CONNECTION_ID_STORAGE_PREFIX}${storeSlug}`;\n const existing = getItem<string>(storageKey);\n if (existing && existing.trim()) {\n return existing;\n }\n\n const nextId = createPresenceConnectionId();\n setItem(storageKey, nextId);\n return nextId;\n}\n\nfunction getRecentClientErrorKey(payload: StorefrontClientErrorPayload): string {\n return [\n payload.method,\n payload.endpoint,\n payload.statusCode ?? 'none',\n payload.message.trim().toLowerCase(),\n payload.responseReceived ? 'response' : 'no-response',\n ].join('|');\n}\n\nfunction shouldSkipDuplicateClientError(payload: StorefrontClientErrorPayload): boolean {\n const dedupeKey = `client_error_${getRecentClientErrorKey(payload)}`;\n const now = Date.now();\n const lastSeenAt = getItem<number>(dedupeKey);\n if (typeof lastSeenAt === 'number' && now - lastSeenAt < CLIENT_ERROR_DEDUPE_WINDOW_MS) {\n return true;\n }\n\n setItem(dedupeKey, now);\n return false;\n}\n\nexport async function reportStorefrontClientError(payload: StorefrontClientErrorPayload): Promise<void> {\n if (!isInitialized()) return;\n if (typeof window === 'undefined') return;\n if (shouldSkipDuplicateClientError(payload)) return;\n\n const config = getConfig();\n const shopId = getShopId();\n const endpoint = shopId\n ? buildEndpoint('/v1/storefront/shops/id/:id/ping', { id: shopId })\n : buildEndpoint('/v1/storefront/shops/:storeSlug/ping', { storeSlug: config.storeSlug });\n const body = JSON.stringify({\n event_type: 'client_error',\n referer: document.referrer || undefined,\n connection_id: getStorefrontConnectionId(config.storeSlug) ?? undefined,\n client_error: {\n source: payload.source ?? 'sdk',\n phase: payload.phase ?? 'request',\n endpoint: payload.endpoint,\n method: payload.method,\n message: payload.message,\n status_code: payload.statusCode,\n attempt_count: payload.attemptCount,\n response_received: payload.responseReceived ?? false,\n page_url: payload.pageUrl ?? window.location.href,\n request_url: payload.requestUrl,\n online: payload.online ?? (typeof navigator !== 'undefined' ? navigator.onLine : undefined),\n visibility_state:\n payload.visibilityState ??\n (typeof document !== 'undefined'\n ? (document.visibilityState as VisibilityStateValue)\n : undefined),\n },\n });\n\n const targetUrl = `${config.apiBaseUrl}${endpoint}`;\n\n try {\n if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {\n const beaconBody = new Blob([body], { type: 'application/json' });\n if (navigator.sendBeacon(targetUrl, beaconBody)) {\n return;\n }\n }\n\n await fetch(targetUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body,\n keepalive: true,\n });\n } catch {\n // Telemetry must never break storefront usage.\n }\n}\n","/**\n * HTTP Client for SDK\n *\n * IMPORTANT: No credentials! SDK runs on external domains,\n * and CORS with wildcard origin doesn't allow credentials.\n * All endpoints are public storefront endpoints.\n */\n\nimport type { ApiResponse, SDKResponse } from '../types';\nimport { getConfig, isInitialized } from './config';\nimport { ApiError, NetworkError, ShoppexError } from './errors';\nimport { getOrFetch, type CacheOptions } from './cache';\nimport { reportStorefrontClientError } from './telemetry';\n\nconst DEFAULT_TIMEOUT = 10000;\nconst MAX_RETRIES = 2;\n\ninterface RequestOptions {\n method?: 'GET' | 'POST' | 'PUT' | 'DELETE';\n body?: unknown;\n timeout?: number;\n retries?: number;\n baseUrl?: string;\n cache?: (CacheOptions & { key?: string }) | false;\n}\n\ninterface ParsedResponsePayload {\n data: unknown | null;\n rawText: string | null;\n}\n\ninterface FailureInfo {\n message: string;\n statusCode?: number;\n isTransport: boolean;\n /** The server's `error_code`, when the failure was a named refusal. */\n code?: string;\n errorParams?: Record<string, unknown>;\n}\n\nasync function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport async function request<T>(\n endpoint: string,\n options: RequestOptions = {}\n): Promise<SDKResponse<T>> {\n const config = options.baseUrl ? null : getConfig();\n // The locale travels with EVERY request of an initialized SDK — a baseUrl\n // override (e.g. resolveStoreByDomain) must not silently drop it back to\n // Accept-Language negotiation (Codex P2).\n const localeConfig = config ?? (isInitialized() ? getConfig() : null);\n const {\n method = 'GET',\n body,\n timeout = DEFAULT_TIMEOUT,\n retries,\n baseUrl,\n cache,\n } = options;\n const retryCount =\n retries ?? (method === 'GET' ? MAX_RETRIES : 0);\n\n const apiBaseUrl = baseUrl ?? config?.apiBaseUrl ?? '';\n const url = `${apiBaseUrl}${endpoint}`;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n };\n // Explicit request locale (ADR-0055): without it the backend would fall\n // back to Accept-Language, detaching catalog content from the page locale.\n if (typeof localeConfig?.locale === 'string' && localeConfig.locale.trim()) {\n headers['x-shoppex-locale'] = localeConfig.locale.trim();\n }\n\n let lastFailure: FailureInfo | null = null;\n\n const executeRequest = async (): Promise<SDKResponse<T>> => {\n for (let attempt = 0; attempt <= retryCount; attempt++) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n const payload = await parseResponsePayload(response);\n\n if (!response.ok) {\n const fallbackHttpMessage = response.statusText\n ? `HTTP ${response.status}: ${response.statusText}`\n : `HTTP ${response.status}`;\n const message =\n (payload.data && typeof payload.data === 'object' && 'error' in payload.data && typeof payload.data.error === 'string'\n ? payload.data.error\n : null) ??\n (payload.data && typeof payload.data === 'object' && 'message' in payload.data && typeof payload.data.message === 'string'\n ? payload.data.message\n : null) ??\n payload.rawText ??\n fallbackHttpMessage;\n\n // A named server refusal keeps its name. Everything else stays a\n // NetworkError, exactly as before.\n const named = readErrorCodeFields(payload.data);\n if (named.code) {\n throw new ApiError(message, named.code, response.status, named.errorParams);\n }\n\n throw new NetworkError(message, response.status);\n }\n\n if (response.status === 204 && payload.data === null) {\n return {\n success: true,\n };\n }\n\n if (!payload.data || typeof payload.data !== 'object' || !('status' in payload.data)) {\n throw new NetworkError('Invalid API response', response.status);\n }\n\n const data = payload.data as ApiResponse<T>;\n\n return mapApiResponse(data);\n } catch (error) {\n let normalizedError = error instanceof Error ? error : new Error(String(error));\n\n if (error instanceof DOMException && error.name === 'AbortError') {\n normalizedError = new NetworkError('Request timeout', 408);\n }\n\n // Read from the base class, not NetworkError: a named ApiError also\n // carries the HTTP status, and losing it would misclassify a 400\n // refusal as a transport failure — retried and reported as an outage.\n const statusCode =\n normalizedError instanceof ShoppexError\n ? normalizedError.statusCode\n : undefined;\n\n lastFailure = {\n message: normalizedError.message,\n statusCode,\n isTransport: statusCode === undefined || statusCode === 408,\n ...(normalizedError instanceof ApiError\n ? {\n code: normalizedError.code,\n ...(normalizedError.errorParams ? { errorParams: normalizedError.errorParams } : {}),\n }\n : {}),\n };\n\n // A named 4xx is the server's decision, not a transport hiccup:\n // `ApiError` only exists when the response carried an error code, and\n // a client-error status means the request itself was refused. Repeating\n // it verbatim cannot change the answer — it just multiplies the load\n // and delays the refusal the caller is waiting on by the full backoff\n // schedule. 408 stays retryable (it is a timeout wearing a 4xx) and\n // every 5xx, network failure and unnamed error retries exactly as\n // before.\n const isNamedClientRefusal =\n normalizedError instanceof ApiError\n && statusCode !== undefined\n && statusCode >= 400\n && statusCode < 500\n && statusCode !== 408;\n\n if (isNamedClientRefusal) {\n break;\n }\n\n if (attempt < retryCount) {\n await sleep(Math.pow(2, attempt) * 500);\n continue;\n }\n }\n }\n\n return {\n success: false,\n message: lastFailure?.message ?? 'Unknown error',\n ...(lastFailure?.code ? { code: lastFailure.code } : {}),\n ...(lastFailure?.errorParams ? { errorParams: lastFailure.errorParams } : {}),\n };\n };\n\n const result =\n method === 'GET' && cache && cache.ttl > 0\n ? await getOrFetch(\n cache.key ?? `GET:${url}`,\n executeRequest,\n { ttl: cache.ttl, staleWhileRevalidate: cache.staleWhileRevalidate },\n (value) => value.success\n )\n : await executeRequest();\n\n const failureForTelemetry = lastFailure as FailureInfo | null;\n\n if (!result.success && failureForTelemetry?.isTransport) {\n\n await reportStorefrontClientError({\n endpoint,\n method,\n message: result.message ?? failureForTelemetry.message,\n statusCode: failureForTelemetry.statusCode,\n attemptCount: retryCount + 1,\n requestUrl: url,\n responseReceived:\n failureForTelemetry.statusCode !== undefined &&\n failureForTelemetry.statusCode !== 408,\n });\n }\n\n return result;\n}\n\nasync function parseResponsePayload(response: Response): Promise<ParsedResponsePayload> {\n const responseWithOptionalMethods = response as Response & {\n text?: () => Promise<string>;\n json?: () => Promise<unknown>;\n };\n\n // Runtime-safe fallback for test mocks that only implement `json()`.\n if (typeof responseWithOptionalMethods.text !== 'function') {\n if (typeof responseWithOptionalMethods.json === 'function') {\n try {\n return {\n data: await responseWithOptionalMethods.json(),\n rawText: null,\n };\n } catch {\n return { data: null, rawText: null };\n }\n }\n return { data: null, rawText: null };\n }\n\n try {\n const rawText = await responseWithOptionalMethods.text();\n if (!rawText) {\n return { data: null, rawText: null };\n }\n\n try {\n return {\n data: JSON.parse(rawText) as unknown,\n rawText: null,\n };\n } catch {\n const normalizedText = rawText.trim();\n return {\n data: null,\n rawText: normalizedText.length > 0 ? normalizedText : null,\n };\n }\n } catch {\n return { data: null, rawText: null };\n }\n}\n\nfunction mapApiResponse<T>(apiResponse: ApiResponse<T>): SDKResponse<T> {\n if (apiResponse.status >= 200 && apiResponse.status < 300) {\n return {\n success: true,\n data: apiResponse.data,\n ...(apiResponse.message ? { message: apiResponse.message } : {}),\n };\n }\n\n return {\n success: false,\n message: apiResponse.error ?? apiResponse.message ?? `Request failed with status ${apiResponse.status}`,\n // The refusal the server actually made, kept machine-readable. Without it\n // a caller can only string-match a localized sentence, which breaks in\n // every locale but one.\n ...readErrorCodeFields(apiResponse),\n };\n}\n\n/**\n * Pull the localized-error envelope (`error_code` / `error_params`) off any\n * server payload shape. Returns an empty object when the payload carries none,\n * so the fields stay absent rather than becoming `undefined` keys.\n */\nfunction readErrorCodeFields(payload: unknown): { code?: string; errorParams?: Record<string, unknown> } {\n if (!payload || typeof payload !== 'object') {\n return {};\n }\n\n const record = payload as Record<string, unknown>;\n const code = typeof record.error_code === 'string' && record.error_code.length > 0\n ? record.error_code\n : null;\n if (!code) {\n return {};\n }\n\n const params = record.error_params;\n return {\n code,\n ...(params && typeof params === 'object' && !Array.isArray(params)\n ? { errorParams: params as Record<string, unknown> }\n : {}),\n };\n}\n\nexport async function get<T>(\n endpoint: string,\n options?: Omit<RequestOptions, 'method' | 'body'>\n): Promise<SDKResponse<T>> {\n return request<T>(endpoint, { ...options, method: 'GET' });\n}\n\nexport async function post<T>(\n endpoint: string,\n body?: unknown,\n options?: Omit<RequestOptions, 'method' | 'body'>\n): Promise<SDKResponse<T>> {\n return request<T>(endpoint, { ...options, method: 'POST', body });\n}\n","/**\n * Store Module\n *\n * API methods for store data.\n */\n\nimport { get } from '../core/client';\nimport { DEFAULT_API_BASE_URL, getConfig, isInitialized, setShopId } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type {\n SDKResponse,\n Shop,\n Product,\n StorefrontData,\n ProductGroup,\n Category,\n StorefrontAddonBootstrap,\n CursorPagination,\n} from '../types';\n\ninterface StoreResponse {\n shop: Shop;\n products?: Product[];\n products_pagination?: CursorPagination | null;\n groups?: ProductGroup[];\n items?: StorefrontData['items'];\n categories?: Category[];\n addons?: StorefrontAddonBootstrap;\n}\n\ninterface StorefrontResponse {\n shop: Shop;\n}\n\nexport interface GetStorefrontOptions {\n productsLimit?: number;\n productsCursor?: string | null;\n}\n\nconst STORE_CACHE_TTL = 5 * 60 * 1000;\n\nexport async function getStore(): Promise<SDKResponse<Shop>> {\n const config = getConfig();\n const response = await get<StoreResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug', {\n storeSlug: config.storeSlug,\n }),\n {\n cache: {\n key: `store:${config.storeSlug}`,\n ttl: STORE_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n // Cache the shopId for slug lookups\n if (response.data.shop?.id) {\n setShopId(response.data.shop.id);\n }\n return {\n success: true,\n data: response.data.shop,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function resolveStoreByDomain(\n domain?: string,\n apiBaseUrl?: string\n): Promise<SDKResponse<Shop>> {\n const resolvedDomain =\n domain ??\n (typeof window !== 'undefined' ? window.location.hostname : '');\n\n if (!resolvedDomain) {\n return {\n success: false,\n message: 'Domain is required to resolve store',\n };\n }\n\n const cleanDomain = resolvedDomain\n .replace(/^https?:\\/\\//, '')\n .split('/')[0]\n .trim();\n\n const baseUrl =\n apiBaseUrl ??\n (isInitialized() ? getConfig().apiBaseUrl : DEFAULT_API_BASE_URL);\n\n const response = await get<StorefrontResponse>(\n buildEndpoint('/v1/storefront/shops/domain/:domain', {\n domain: cleanDomain,\n }),\n {\n baseUrl,\n cache: {\n key: `store:domain:${cleanDomain}`,\n ttl: STORE_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data?.shop) {\n if (response.data.shop.id) {\n setShopId(response.data.shop.id);\n }\n return {\n success: true,\n data: response.data.shop,\n };\n }\n\n return {\n success: false,\n message: response.message ?? 'Failed to resolve store',\n };\n}\n\nexport async function getStorefront(options?: GetStorefrontOptions): Promise<SDKResponse<StorefrontData>> {\n const config = getConfig();\n const query = new URLSearchParams();\n if (Number.isFinite(options?.productsLimit)) {\n query.set('products_limit', String(Math.max(1, Math.floor(options?.productsLimit ?? 0))));\n }\n if (typeof options?.productsCursor === 'string' && options.productsCursor.trim().length > 0) {\n query.set('products_cursor', options.productsCursor);\n }\n const querySuffix = query.size > 0 ? `?${query.toString()}` : '';\n const response = await get<StoreResponse>(\n `${buildEndpoint('/v1/storefront/shops/name/:storeSlug', {\n storeSlug: config.storeSlug,\n })}${querySuffix}`,\n {\n cache: {\n key: `storefront:${config.storeSlug}:${options?.productsLimit ?? 'full'}:${options?.productsCursor ?? 'start'}`,\n ttl: STORE_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n // Cache the shopId for slug lookups\n if (response.data.shop?.id) {\n setShopId(response.data.shop.id);\n }\n return {\n success: true,\n data: {\n shop: response.data.shop,\n products: response.data.products ?? [],\n products_pagination: response.data.products_pagination ?? null,\n groups: response.data.groups ?? [],\n items: response.data.items ?? [],\n categories: response.data.categories ?? [],\n addons: response.data.addons ?? { items: [] },\n },\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function getStoreLogoUrl(): Promise<string | null> {\n const response = await getStore();\n\n if (response.success && response.data?.logo) {\n return response.data.logo;\n }\n\n return null;\n}\n\nexport async function getStoreBannerUrl(): Promise<string | null> {\n const response = await getStore();\n\n if (response.success && response.data?.banner) {\n return response.data.banner;\n }\n\n return null;\n}\n","/**\n * Products Module\n *\n * API methods for product data.\n */\n\nimport { get } from '../core/client';\nimport { getConfig, getShopId } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type {\n SDKResponse,\n Product,\n ProductCategory,\n ProductGroup,\n ProductVariant,\n PriceVariant,\n CursorPagination,\n} from '../types';\nimport { getStore } from './store';\nimport { getMergedStorefrontProducts } from '../utils/storefront-catalog';\n\ninterface ProductsResponse {\n products: Product[];\n groups?: ProductGroup[];\n pagination?: CursorPagination | null;\n}\n\ninterface ProductResponse {\n product: Product;\n}\n\nconst PRODUCTS_CACHE_TTL = 2 * 60 * 1000;\n\nexport interface GetStorefrontProductsPageOptions {\n cursor?: string | null;\n limit?: number;\n sort?: 'featured' | 'newest' | 'price-asc' | 'price-desc' | string | null;\n category?: string | null;\n hideOutOfStock?: boolean;\n}\n\nfunction getStorefrontProductsPageCategoryCacheKey(category: string | null | undefined): string {\n if (category === undefined) return 'category:unset';\n if (category === null) return 'category:null';\n return `category:${category}`;\n}\n\nfunction priceVariantToProductVariant(variant: PriceVariant & { stock?: number }): ProductVariant {\n return {\n id: variant.id,\n title: variant.title ?? variant.label ?? '',\n price: typeof variant.price === 'number' ? variant.price : Number(variant.price) || 0,\n stock: typeof variant.stock === 'number' ? variant.stock : undefined,\n // Dynamic Delivery (S8): carry the availability pair through. A supplier-backed\n // variant reports `stock: 0`, so dropping `orderable` here would make the mapped\n // variant look sold out. Left `undefined` when the source omits it, which keeps\n // the historical stock-only behaviour for payloads that predate the field.\n orderable: typeof variant.orderable === 'boolean' ? variant.orderable : undefined,\n supplier_backed:\n typeof variant.supplier_backed === 'boolean' ? variant.supplier_backed : undefined,\n quantity_min: variant.quantity_min,\n quantity_max: variant.quantity_max,\n quantityMin: variant.quantityMin,\n quantityMax: variant.quantityMax,\n image_id: variant.image_id,\n imageId: variant.imageId,\n cloudflare_image_id: variant.cloudflare_image_id,\n cloudflareImageId: variant.cloudflareImageId,\n image_url: variant.image_url,\n imageUrl: variant.imageUrl,\n };\n}\n\nfunction normalizeProduct(product: Product): Product {\n if (product.variants && product.variants.length > 0) {\n return product;\n }\n\n const priceVariants = product.price_variants;\n if (!Array.isArray(priceVariants) || priceVariants.length === 0) {\n return product;\n }\n\n return {\n ...product,\n variants: priceVariants.map((variant) =>\n priceVariantToProductVariant(variant as PriceVariant & { stock?: number })\n ),\n };\n}\n\nexport async function getProducts(): Promise<SDKResponse<Product[]>> {\n const config = getConfig();\n const response = await get<ProductsResponse>(\n buildEndpoint('/v1/storefront/products/public/:storeSlug', {\n storeSlug: config.storeSlug,\n }),\n {\n cache: {\n key: `products:${config.storeSlug}`,\n ttl: PRODUCTS_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n // The public route returns every public product exactly once in the flat `products` array —\n // group-bound products (e.g. variant-style DYNAMIC products) are included there too, so no\n // group merge is needed anymore. Groups only carry `product_uniqids` references into this\n // list. getMergedStorefrontProducts just dedupes by uniqid (first entry wins).\n return {\n success: true,\n data: getMergedStorefrontProducts(response.data.products.map(normalizeProduct)),\n };\n }\n\n return {\n success: false,\n message: response.message,\n data: [],\n };\n}\n\nexport async function getStorefrontProductsPage(\n options?: GetStorefrontProductsPageOptions,\n): Promise<SDKResponse<{ products: Product[]; pagination: CursorPagination | null }>> {\n const config = getConfig();\n const query = new URLSearchParams();\n if (typeof options?.cursor === 'string' && options.cursor.trim().length > 0) {\n query.set('cursor', options.cursor);\n }\n if (Number.isFinite(options?.limit)) {\n query.set('limit', String(Math.max(1, Math.floor(options?.limit ?? 0))));\n }\n if (typeof options?.sort === 'string' && options.sort.trim().length > 0) {\n query.set('sort', options.sort.trim());\n }\n if (typeof options?.category === 'string' && options.category.trim().length > 0) {\n query.set('category', options.category.trim());\n }\n if (options?.hideOutOfStock === true) {\n query.set('hide_out_of_stock', 'true');\n }\n const querySuffix = query.size > 0 ? `?${query.toString()}` : '';\n\n const response = await get<ProductsResponse>(\n `${buildEndpoint('/v1/storefront/products/shop/:storeSlug', {\n storeSlug: config.storeSlug,\n })}${querySuffix}`,\n {\n cache: {\n key: `products:page:${config.storeSlug}:${options?.limit ?? 'default'}:${options?.cursor ?? 'start'}:${options?.sort ?? 'featured'}:${getStorefrontProductsPageCategoryCacheKey(options?.category)}:${options?.hideOutOfStock === true ? 'in-stock' : 'all-stock'}`,\n ttl: PRODUCTS_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: {\n products: response.data.products.map(normalizeProduct),\n pagination: response.data.pagination ?? null,\n },\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function getProduct(\n idOrSlug: string\n): Promise<SDKResponse<Product>> {\n // Slug lookups need the current shop id. Resolve it lazily so callers do not\n // have to remember to call getStore()/getStorefront() first.\n let shopId = getShopId();\n if (!shopId) {\n const store = await getStore();\n shopId = store.success ? (store.data?.id ?? null) : null;\n }\n\n const queryParams = shopId ? `?slug_shop_id=${encodeURIComponent(shopId)}` : '';\n\n const response = await get<ProductResponse>(\n `${buildEndpoint('/v1/storefront/products/unique/:idOrSlug', { idOrSlug })}${queryParams}`,\n {\n cache: {\n key: `product:${idOrSlug}:${shopId ?? 'no-shop'}`,\n ttl: PRODUCTS_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data?.product) {\n return {\n success: true,\n data: normalizeProduct(response.data.product),\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function getCategories(): Promise<SDKResponse<string[]>> {\n const products = await getProducts();\n\n if (!products.success || !products.data) {\n return {\n success: false,\n message: products.message,\n };\n }\n\n const categories = new Set<string>();\n for (const product of products.data) {\n if (product.categories) {\n for (const category of product.categories) {\n if (typeof category === 'string') {\n categories.add(category);\n } else if (category && typeof category === 'object' && 'uniqid' in category) {\n categories.add((category as ProductCategory).uniqid);\n }\n }\n }\n }\n\n return {\n success: true,\n data: Array.from(categories),\n };\n}\n","import { getConfig, isInitialized } from '../core/config';\nimport { post } from '../core/client';\nimport type { AffiliateValidation, SDKResponse } from '../types';\n\nconst STORAGE_KEY = 'shoppex:affiliate_code:v1';\nconst DEFAULT_TTL_DAYS = 30;\n\ntype StoredAffiliate = {\n code: string;\n expiresAt: number;\n};\n\nfunction nowMs() {\n return Date.now();\n}\n\nfunction ttlMs(days: number) {\n return Math.max(1, days) * 24 * 60 * 60 * 1000;\n}\n\nfunction normalizeAffiliateCode(code: string | null | undefined): string | null {\n const normalized = code?.trim().toLowerCase();\n return normalized ? normalized : null;\n}\n\nfunction safeRead(): StoredAffiliate | null {\n if (typeof window === 'undefined') return null;\n try {\n const raw = window.localStorage.getItem(STORAGE_KEY);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as StoredAffiliate;\n if (!parsed || typeof parsed.code !== 'string' || typeof parsed.expiresAt !== 'number') return null;\n return parsed;\n } catch {\n return null;\n }\n}\n\nfunction safeWrite(value: StoredAffiliate) {\n if (typeof window === 'undefined') return;\n try {\n window.localStorage.setItem(STORAGE_KEY, JSON.stringify(value));\n } catch {\n // ignore\n }\n}\n\nexport function setAffiliateCode(code: string | null | undefined, ttlDays = DEFAULT_TTL_DAYS): string | null {\n const normalized = normalizeAffiliateCode(code);\n if (!normalized) {\n clearAffiliateCode();\n return null;\n }\n\n safeWrite({ code: normalized, expiresAt: nowMs() + ttlMs(ttlDays) });\n return normalized;\n}\n\nexport function clearAffiliateCode(): void {\n if (typeof window === 'undefined') return;\n try {\n window.localStorage.removeItem(STORAGE_KEY);\n } catch {\n // ignore\n }\n}\n\nexport function getAffiliateCode(): string | null {\n const stored = safeRead();\n if (!stored) return null;\n if (stored.expiresAt <= nowMs()) {\n clearAffiliateCode();\n return null;\n }\n return normalizeAffiliateCode(stored.code);\n}\n\nexport async function validateAffiliateCode(code: string): Promise<SDKResponse<AffiliateValidation>> {\n const normalizedCode = normalizeAffiliateCode(code);\n if (!normalizedCode) {\n return {\n success: false,\n data: {\n valid: false,\n affiliate_code: null,\n discount_active: false,\n discount_percent: 0,\n },\n message: 'Affiliate code is required',\n };\n }\n\n const config = getConfig();\n const response = await post<AffiliateValidation>(\n '/v1/storefront/affiliates/resolve',\n {\n shop_slug: config.storeSlug,\n code: normalizedCode,\n },\n { retries: 0 }\n );\n\n if (!response.success) {\n return response;\n }\n\n if (!response.data?.valid || !response.data.affiliate_code) {\n const programDisabled = response.data?.program_enabled === false;\n return {\n success: false,\n data: {\n valid: false,\n ...(response.data?.program_enabled !== undefined ? { program_enabled: response.data.program_enabled } : {}),\n affiliate_code: null,\n discount_active: false,\n discount_percent: 0,\n },\n message: response.message\n ?? (programDisabled ? 'Affiliate program is disabled for this shop.' : 'Invalid affiliate code.'),\n };\n }\n\n return {\n success: true,\n data: {\n valid: true,\n ...(response.data.program_enabled !== undefined ? { program_enabled: response.data.program_enabled } : {}),\n affiliate_code: normalizeAffiliateCode(response.data.affiliate_code),\n discount_active: Boolean(response.data.discount_active),\n discount_percent: Number(response.data.discount_percent ?? 0),\n },\n ...(response.message ? { message: response.message } : {}),\n };\n}\n\nexport async function applyAffiliateCode(code: string): Promise<SDKResponse<AffiliateValidation>> {\n const result = await validateAffiliateCode(code);\n if (result.success && result.data?.affiliate_code) {\n setAffiliateCode(result.data.affiliate_code);\n }\n\n return result;\n}\n\n/**\n * Capture an affiliate code from the current URL and store it for 30 days (last-click).\n *\n * Example:\n * - URL: https://mystore.com/product/abc?ref=deadbeef\n * - captureAffiliateFromUrl() stores \"deadbeef\" and returns it.\n */\nexport async function captureAffiliateFromUrl(param = 'ref'): Promise<string | null> {\n if (typeof window === 'undefined') return null;\n\n let code: string | null = null;\n try {\n const url = new URL(window.location.href);\n const raw = url.searchParams.get(param);\n code = raw ? raw.trim() : null;\n } catch {\n code = null;\n }\n\n code = normalizeAffiliateCode(code);\n if (!code) return null;\n\n // Store immediately so we don't lose it if attribution call fails.\n setAffiliateCode(code);\n\n // Optional: validate + normalize with backend. If invalid, clear it.\n if (isInitialized()) {\n try {\n const config = getConfig();\n const res = await post<{ accepted?: boolean; affiliate_code?: string | null }>(\n '/v1/storefront/affiliates/attribution',\n { shop_slug: config.storeSlug, code },\n { retries: 0 }\n );\n if (!res.success || !res.data?.accepted || !res.data?.affiliate_code) {\n clearAffiliateCode();\n return null;\n }\n setAffiliateCode(res.data.affiliate_code);\n return res.data.affiliate_code;\n } catch {\n // keep stored raw code, from-cart will validate later\n return code;\n }\n }\n\n return code;\n}\n","import type { CartAddon, CartItem } from '../types/cart';\n\nfunction hashString(value: string): string {\n let hash = 2166136261;\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i);\n hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);\n }\n return (hash >>> 0).toString(16);\n}\n\nfunction normalizeAddons(addons: CartAddon[] | undefined): CartAddon[] {\n if (!addons?.length) return [];\n return [...addons]\n .map((addon) => ({ id: addon.id, quantity: addon.quantity ?? 1 }))\n .sort((a, b) => a.id.localeCompare(b.id));\n}\n\nfunction normalizeCustomFields(fields: Record<string, string> | undefined): Record<string, string> {\n if (!fields) return {};\n const entries = Object.entries(fields)\n .filter(([, value]) => typeof value === 'string')\n .sort(([a], [b]) => a.localeCompare(b));\n return Object.fromEntries(entries);\n}\n\nexport type CartLineIdentityInput = Pick<\n CartItem,\n 'product_id' | 'variant_id' | 'price_variant_id' | 'addons' | 'custom_fields' | 'price_data' | 'pay_what_you_want_price'\n>;\n\nexport function computeCartLineId(input: CartLineIdentityInput): string {\n const payload = {\n product_id: input.product_id,\n variant_id: input.variant_id,\n price_variant_id: input.price_variant_id ?? null,\n addons: normalizeAddons(input.addons),\n custom_fields: normalizeCustomFields(input.custom_fields),\n unit_price:\n typeof input.price_data?.unit_price === 'number' && Number.isFinite(input.price_data.unit_price)\n ? input.price_data.unit_price\n : null,\n pay_what_you_want_price:\n typeof input.pay_what_you_want_price === 'number' && Number.isFinite(input.pay_what_you_want_price)\n ? input.pay_what_you_want_price\n : null,\n };\n return hashString(JSON.stringify(payload));\n}\n\nexport function ensureCartLineId(item: CartItem): CartItem {\n if (typeof item.line_id === 'string' && item.line_id.trim()) {\n return item;\n }\n return { ...item, line_id: computeCartLineId(item) };\n}\n","export function normalizeRequestedCurrency(value: string | null | undefined): string | null {\n const normalized = value?.trim().toUpperCase();\n return normalized && /^[A-Z]{3}$/.test(normalized) ? normalized : null;\n}\n\nexport function getRequestedCurrencyFromLocation(): string | null {\n if (typeof window === 'undefined' || !window.location) {\n return null;\n }\n\n const search = typeof window.location.search === 'string' ? window.location.search : '';\n if (search) {\n return normalizeRequestedCurrency(new URLSearchParams(search).get('currency'));\n }\n\n const href = typeof window.location.href === 'string' ? window.location.href : '';\n if (!href) {\n return null;\n }\n\n try {\n return normalizeRequestedCurrency(\n new URL(href, 'https://storefront.shoppex.local').searchParams.get('currency'),\n );\n } catch {\n return null;\n }\n}\n","/**\n * Cart Module\n *\n * localStorage-based cart with support for Shoppex features:\n * - Addons (express shipping, gift wrap, etc.)\n * - Custom Fields (engraving, gift message, etc.)\n * - Price Variants (different pricing tiers)\n */\n\nimport { getItem, setItem, removeItem } from '../utils/storage';\nimport { getConfig } from '../core/config';\nimport { post } from '../core/client';\nimport { CartError } from '../core/errors';\nimport type {\n CartItem,\n CartAddOptions,\n CartItemUpdate,\n CartPayload,\n CartMetadata,\n CartStats,\n CartQuote,\n CartBasketMergeLine,\n CartCodeSource,\n} from '../types';\nimport { getAffiliateCode } from './affiliates';\nimport { computeCartLineId, ensureCartLineId } from '../utils/cart-line-id';\nimport {\n getRequestedCurrencyFromLocation,\n normalizeRequestedCurrency,\n} from '../utils/requested-currency';\nimport { roundPayableAmount } from '@shoppex/contracts/catalog-unit-price';\n\nconst STORAGE_KEYS = {\n cart: 'cart',\n cartBackup: 'cart_backup',\n meta: 'cart_meta',\n metaBackup: 'cart_backup_meta',\n coupon: 'cart_coupon',\n couponBackup: 'cart_coupon_backup',\n} as const;\n\ntype StorageKeyType = keyof typeof STORAGE_KEYS;\n\nfunction getStorageKey(type: StorageKeyType): string {\n return `${STORAGE_KEYS[type]}_${getConfig().storeSlug}`;\n}\n\nfunction hashString(value: string): string {\n let hash = 2166136261;\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i);\n hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);\n }\n return (hash >>> 0).toString(16);\n}\n\nfunction computeChecksum(cart: CartItem[]): string {\n return hashString(JSON.stringify(cart));\n}\n\nfunction normalizeQuantity(value: number): number {\n if (!Number.isFinite(value)) {\n throw new CartError('quantity must be a finite number');\n }\n return Math.floor(value);\n}\n\nfunction normalizeCouponCode(value: string | null | undefined): string | null {\n const normalized = value?.trim().toUpperCase();\n return normalized ? normalized : null;\n}\n\ntype StoredCartCode = {\n code: string;\n source: CartCodeSource;\n};\n\nfunction getStoredCartCode(): StoredCartCode | null {\n const raw = getItem<unknown>(getStorageKey('coupon'));\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {\n return null;\n }\n const record = raw as Record<string, unknown>;\n const code = typeof record.code === 'string' ? normalizeCouponCode(record.code) : null;\n const source = record.source === 'COUPON' || record.source === 'AFFILIATE'\n ? record.source\n : null;\n return code && source ? { code, source } : null;\n}\n\nfunction normalizeCartItems(value: unknown): CartItem[] {\n if (!Array.isArray(value)) return [];\n const normalized: CartItem[] = [];\n for (const entry of value) {\n if (!entry || typeof entry !== 'object') continue;\n const record = entry as Record<string, unknown>;\n const productId = typeof record.product_id === 'string' ? record.product_id.trim() : '';\n const variantId = typeof record.variant_id === 'string' ? record.variant_id.trim() : '';\n const quantity = Number(record.quantity);\n\n if (!productId || !variantId || !Number.isFinite(quantity) || quantity < 1) {\n continue;\n }\n\n const item: CartItem = {\n line_id: '',\n product_id: productId,\n variant_id: variantId,\n quantity: Math.floor(quantity),\n };\n\n if (typeof record.price_variant_id === 'string') {\n item.price_variant_id = record.price_variant_id;\n }\n if (record.price_data && typeof record.price_data === 'object') {\n const priceData = record.price_data as Record<string, unknown>;\n if (typeof priceData.unit_price === 'number' && Number.isFinite(priceData.unit_price)) {\n item.price_data = { unit_price: priceData.unit_price };\n }\n }\n if (typeof record.pay_what_you_want_price === 'number' && Number.isFinite(record.pay_what_you_want_price)) {\n item.pay_what_you_want_price = record.pay_what_you_want_price;\n }\n if (Array.isArray(record.addons)) {\n item.addons = record.addons as CartItem['addons'];\n }\n if (record.custom_fields && typeof record.custom_fields === 'object' && !Array.isArray(record.custom_fields)) {\n item.custom_fields = record.custom_fields as Record<string, string>;\n }\n\n // Preserve the optional display snapshot (title/variant_title/image_url/addon_labels) across the\n // localStorage round-trip so the njk cart drawer/page can render without a product fetch.\n if (typeof record.title === 'string') {\n item.title = record.title;\n }\n if (typeof record.variant_title === 'string') {\n item.variant_title = record.variant_title;\n }\n if (typeof record.image_url === 'string') {\n item.image_url = record.image_url;\n }\n if (Array.isArray(record.addon_labels)) {\n item.addon_labels = record.addon_labels.filter((label): label is string => typeof label === 'string');\n }\n if (typeof record.max_quantity === 'number' && Number.isFinite(record.max_quantity)) {\n item.max_quantity = record.max_quantity;\n }\n if (typeof record.min_quantity === 'number' && Number.isFinite(record.min_quantity)) {\n item.min_quantity = record.min_quantity;\n }\n\n // Self-heal on READ: clamp quantity to the stored [min,max] here, after the bounds are read. This is\n // the single chokepoint every access flows through (getCart -> getCartPayload -> serializeCart/\n // quoteCart -> checkout), so a stale/tampered/restored localStorage line can never reach checkout\n // out of bounds — closing restoreCartFromBackup and direct-localStorage-edit at the root, not just\n // the write paths.\n clampQuantityToBounds(item);\n\n const storedLineId = typeof record.line_id === 'string' ? record.line_id.trim() : '';\n item.line_id = storedLineId || computeCartLineId(item);\n\n normalized.push(ensureCartLineId(item));\n }\n return normalized;\n}\n\nfunction getCartMetadata(): CartMetadata | null {\n return getItem<CartMetadata>(getStorageKey('meta'));\n}\n\nexport function getCartCoupon(): string | null {\n return getStoredCartCode()?.code ?? null;\n}\n\nexport function getCartCouponSource(): CartCodeSource | null {\n return getStoredCartCode()?.source ?? null;\n}\n\nexport function setCartCoupon(\n coupon: string | null | undefined,\n source: CartCodeSource = 'COUPON',\n): string | null {\n const normalizedCoupon = normalizeCouponCode(coupon);\n if (!normalizedCoupon) {\n removeItem(getStorageKey('coupon'));\n return null;\n }\n\n setItem(getStorageKey('coupon'), { code: normalizedCoupon, source });\n return normalizedCoupon;\n}\n\nexport function clearCartCoupon(): void {\n removeItem(getStorageKey('coupon'));\n}\n\nfunction writeCart(cart: CartItem[]): void {\n const normalizedCart = normalizeCartItems(cart);\n setItem(getStorageKey('cart'), normalizedCart);\n const now = Date.now();\n const previous = getCartMetadata();\n const nextMeta: CartMetadata = {\n created_at: previous?.created_at ?? now,\n last_modified: now,\n version: (previous?.version ?? 0) + 1,\n checksum: computeChecksum(normalizedCart),\n };\n setItem(getStorageKey('meta'), nextMeta);\n\n if (normalizedCart.length === 0) {\n clearCartCoupon();\n }\n}\n\nfunction setCartWithMetadata(cart: CartItem[], metadata?: CartMetadata | null): void {\n const normalizedCart = normalizeCartItems(cart);\n setItem(getStorageKey('cart'), normalizedCart);\n const now = Date.now();\n const base = metadata ?? getCartMetadata();\n const nextMeta: CartMetadata = {\n created_at: base?.created_at ?? now,\n last_modified: now,\n version: base?.version ?? 1,\n checksum: computeChecksum(normalizedCart),\n };\n setItem(getStorageKey('meta'), nextMeta);\n}\n\nexport function getCart(): CartItem[] {\n const raw = getItem<unknown>(getStorageKey('cart'));\n return normalizeCartItems(raw);\n}\n\n/** Resolve a cart line_id for product+variant. When multiple configs exist, returns the first line. */\nexport function resolveCartLineId(\n productId: string,\n variantId: string,\n cart: CartItem[] = getCart(),\n): string {\n const matches = cart.filter(\n (item) => item.product_id === productId && item.variant_id === variantId,\n );\n if (matches.length === 0) {\n throw new CartError(`No cart line found for ${productId}/${variantId}`);\n }\n return matches[0].line_id;\n}\n\nexport function getCartItemCount(): number {\n const cart = getCart();\n return cart.reduce((sum, item) => sum + item.quantity, 0);\n}\n\nexport function addToCart(\n productId: string,\n variantId: string,\n quantity: number = 1,\n options?: CartAddOptions\n): void {\n if (!productId || !variantId) {\n throw new CartError('product_id and variant_id are required');\n }\n\n const normalizedQuantity = normalizeQuantity(quantity);\n if (normalizedQuantity < 1) {\n throw new CartError('quantity must be at least 1');\n }\n\n const cart = getCart();\n\n const lineId = computeCartLineId({\n product_id: productId,\n variant_id: variantId,\n addons: options?.addons,\n custom_fields: options?.custom_fields,\n price_variant_id: options?.price_variant_id,\n price_data: options?.price_data,\n pay_what_you_want_price: options?.pay_what_you_want_price,\n });\n\n const existingIndex = cart.findIndex((item) => item.line_id === lineId);\n\n if (existingIndex >= 0) {\n cart[existingIndex].quantity += normalizedQuantity;\n\n if (options?.addons) {\n cart[existingIndex].addons = options.addons;\n }\n if (options?.custom_fields) {\n cart[existingIndex].custom_fields = options.custom_fields;\n }\n if (options?.price_variant_id) {\n cart[existingIndex].price_variant_id = options.price_variant_id;\n }\n if (options?.price_data) {\n cart[existingIndex].price_data = options.price_data;\n }\n if (options?.pay_what_you_want_price !== undefined) {\n cart[existingIndex].pay_what_you_want_price = options.pay_what_you_want_price;\n }\n applyDisplaySnapshot(cart[existingIndex], options);\n clampQuantityToBounds(cart[existingIndex]);\n } else {\n const pushed: CartItem = {\n line_id: lineId,\n product_id: productId,\n variant_id: variantId,\n quantity: normalizedQuantity,\n addons: options?.addons,\n custom_fields: options?.custom_fields,\n price_variant_id: options?.price_variant_id,\n price_data: options?.price_data,\n pay_what_you_want_price: options?.pay_what_you_want_price,\n title: options?.title,\n variant_title: options?.variant_title,\n image_url: options?.image_url,\n addon_labels: options?.addon_labels,\n max_quantity: options?.max_quantity,\n min_quantity: options?.min_quantity,\n };\n clampQuantityToBounds(pushed);\n cart.push(pushed);\n }\n\n writeCart(cart);\n}\n\n// Cart-wide invariant: a line's quantity must stay within its stored [min_quantity, max_quantity]\n// bounds. Every write path routes through this — addToCart (merge+push), setCartItem (merge+push),\n// updateCartItem, mergeBaskets (merge+push), moveBasketItem (merge+push) — AND, crucially, the READ\n// path normalizeCartItems (getCart) clamps too, so a stale/tampered/restored localStorage line is\n// self-healed before it can reach checkout. No entrypoint can persist or serve a quantity outside the\n// purchasable range the backend would reject.\n// Order matters: apply min FIRST, then max — so on the degenerate min>max case (e.g. quantity_min 2 but\n// only 1 in stock) MAX wins and the line is never pushed above the stock cap (over-stock is the harder\n// backend reject than under-min). Never below 1. No-op for the bound(s) that are absent.\nfunction clampQuantityToBounds(item: CartItem): void {\n const min = item.min_quantity;\n if (typeof min === 'number' && Number.isFinite(min) && item.quantity < min) {\n item.quantity = Math.floor(min);\n }\n const max = item.max_quantity;\n if (typeof max === 'number' && Number.isFinite(max) && item.quantity > max) {\n item.quantity = Math.floor(max);\n }\n if (item.quantity < 1) {\n item.quantity = 1;\n }\n}\n\n// Copy the optional display snapshot fields from add-options onto an existing line. Display-only —\n// kept separate from the pricing/identity fields so the snapshot logic is identical for add and set.\nfunction applyDisplaySnapshot(item: CartItem, options?: CartAddOptions): void {\n // Authoritative full re-snapshot (buy-box producer): replace ALL display fields verbatim, including\n // CLEARING ones the new snapshot omits — a removed add-on or a lifted cap must not leave stale data.\n if (options?.replace_display_snapshot) {\n item.title = options.title;\n item.variant_title = options.variant_title;\n item.image_url = options.image_url;\n item.addon_labels = options.addon_labels;\n item.max_quantity = options.max_quantity;\n item.min_quantity = options.min_quantity;\n return;\n }\n // Partial direct SDK call: only overwrite the fields actually provided.\n if (options?.title !== undefined) {\n item.title = options.title;\n }\n if (options?.variant_title !== undefined) {\n item.variant_title = options.variant_title;\n }\n if (options?.image_url !== undefined) {\n item.image_url = options.image_url;\n }\n if (options?.addon_labels !== undefined) {\n item.addon_labels = options.addon_labels;\n }\n if (options?.max_quantity !== undefined) {\n item.max_quantity = options.max_quantity;\n }\n if (options?.min_quantity !== undefined) {\n item.min_quantity = options.min_quantity;\n }\n}\n\nexport function setCartItem(\n productId: string,\n variantId: string,\n quantity: number = 1,\n options?: CartAddOptions\n): void {\n if (!productId || !variantId) {\n throw new CartError('product_id and variant_id are required');\n }\n\n const normalizedQuantity = normalizeQuantity(quantity);\n if (normalizedQuantity < 1) {\n throw new CartError('quantity must be at least 1');\n }\n\n const cart = getCart();\n const lineId = computeCartLineId({\n product_id: productId,\n variant_id: variantId,\n addons: options?.addons,\n custom_fields: options?.custom_fields,\n price_variant_id: options?.price_variant_id,\n price_data: options?.price_data,\n pay_what_you_want_price: options?.pay_what_you_want_price,\n });\n\n // Buy-now / replace semantics: one visible line per (product_id, variant_id). Drop any prior\n // line_ids for that pair so a config change (addons, price_data) does not leave a stale sibling.\n for (let index = cart.length - 1; index >= 0; index -= 1) {\n if (cart[index].product_id === productId && cart[index].variant_id === variantId) {\n cart.splice(index, 1);\n }\n }\n\n const pushed: CartItem = {\n line_id: lineId,\n product_id: productId,\n variant_id: variantId,\n quantity: normalizedQuantity,\n addons: options?.addons,\n custom_fields: options?.custom_fields,\n price_variant_id: options?.price_variant_id,\n price_data: options?.price_data,\n pay_what_you_want_price: options?.pay_what_you_want_price,\n title: options?.title,\n variant_title: options?.variant_title,\n image_url: options?.image_url,\n addon_labels: options?.addon_labels,\n max_quantity: options?.max_quantity,\n min_quantity: options?.min_quantity,\n };\n clampQuantityToBounds(pushed);\n cart.push(pushed);\n\n writeCart(cart);\n}\n\n/**\n * Patch one cart line.\n *\n * TRI-STATE BOUNDS: `min_quantity`/`max_quantity` accept `null` to DELETE the\n * stored bound — see {@link CartItemUpdate}. `undefined` (or an absent key)\n * leaves it alone, which is why a removed ceiling needs its own spelling.\n *\n * NO-OP UPDATES DO NOT WRITE. An update that leaves the cart byte-identical\n * returns without touching storage: no metadata bump, no `version` increment,\n * and — because the storage write is what other tabs observe — no `storage`\n * event. Writing anyway made an ineffective heal indistinguishable from a real\n * cart change, and two tabs healing the same line could hand the event back and\n * forth indefinitely. Line-shape healing of a legacy stored row is NOT this\n * function's job: `normalizeCartItems` clamps and repairs on every READ, which\n * is the chokepoint every access already flows through.\n */\nexport function updateCartItem(\n lineId: string,\n updates: CartItemUpdate\n): void {\n const cart = getCart();\n const normalizedLineId = lineId.trim();\n if (!normalizedLineId) {\n throw new CartError('line_id is required');\n }\n\n const index = cart.findIndex((item) => item.line_id === normalizedLineId);\n\n if (index < 0) {\n throw new CartError('Item not found in cart');\n }\n\n // The exact bytes the result is compared against, taken BEFORE any mutation.\n const before = JSON.stringify(cart);\n\n if (updates.quantity !== undefined) {\n const normalizedQuantity = normalizeQuantity(updates.quantity);\n if (normalizedQuantity < 1) {\n cart.splice(index, 1);\n writeCart(cart);\n return;\n }\n cart[index].quantity = normalizedQuantity;\n }\n\n if (updates.addons !== undefined) {\n cart[index].addons = updates.addons;\n }\n\n if (updates.custom_fields !== undefined) {\n cart[index].custom_fields = updates.custom_fields;\n }\n\n if (updates.price_variant_id !== undefined) {\n cart[index].price_variant_id = updates.price_variant_id;\n }\n if (updates.price_data !== undefined) {\n cart[index].price_data = updates.price_data;\n }\n if (updates.pay_what_you_want_price !== undefined) {\n cart[index].pay_what_you_want_price = updates.pay_what_you_want_price;\n }\n // Tri-state: `null` is the merchant's bound being REMOVED, and it has to\n // delete the stored key — a bound that can only be raised and lowered but\n // never cleared outlives the limit it describes.\n if (updates.max_quantity !== undefined) {\n if (updates.max_quantity === null) delete cart[index].max_quantity;\n else cart[index].max_quantity = updates.max_quantity;\n }\n if (updates.min_quantity !== undefined) {\n if (updates.min_quantity === null) delete cart[index].min_quantity;\n else cart[index].min_quantity = updates.min_quantity;\n }\n clampQuantityToBounds(cart[index]);\n\n // Pricing and configuration fields are part of a cart line's identity.\n // Recompute after every update and merge if the new identity already exists.\n const nextLineId = computeCartLineId(cart[index]);\n const duplicateIndex = cart.findIndex((item, itemIndex) => itemIndex !== index && item.line_id === nextLineId);\n if (duplicateIndex >= 0) {\n cart[duplicateIndex].quantity += cart[index].quantity;\n clampQuantityToBounds(cart[duplicateIndex]);\n cart.splice(index, 1);\n } else {\n cart[index].line_id = nextLineId;\n }\n\n // Nothing moved: writing would bump `version`/`last_modified` and emit a\n // storage event that says the cart changed when it did not.\n if (JSON.stringify(cart) === before) return;\n\n writeCart(cart);\n}\n\nexport function removeFromCart(lineId: string): void {\n const normalizedLineId = lineId.trim();\n if (!normalizedLineId) {\n throw new CartError('line_id is required');\n }\n\n const cart = getCart();\n const filtered = cart.filter((item) => item.line_id !== normalizedLineId);\n writeCart(filtered);\n}\n\n/**\n * Discards the cart entirely — and with it the proof that describes it.\n *\n * PAYMENT PATH. `latestQuoteToken` is evidence about a specific cart, and this\n * is the one mutation after which that cart does not exist in any form. Held\n * across the clear, the proof outlives its subject: a caller that clears and\n * re-adds (Buy Now REPLACES the cart) hands `/from-cart` a token bound to the\n * previous cart's hash, which is refused as `quote_token_stale` — a hand-off\n * dead-ended by a proof nobody asked for. And with no re-quote in between there\n * is nothing to replace it with, so the retry is refused identically.\n *\n * Only this path clears it. Every OTHER mutation turns one cart into another\n * cart, where a proof that no longer matches is the server's to refuse: it\n * answers `quote_token_stale`, the surfaces re-quote, and the buyer approves the\n * new total. Dropping the proof there instead would silently remove the approved\n * -total ceiling from a checkout that raced the re-quote, which is the failure\n * the token exists to prevent.\n */\nexport function clearCart(): void {\n removeItem(getStorageKey('cart'));\n removeItem(getStorageKey('meta'));\n clearCartCoupon();\n clearLatestQuoteToken();\n}\n\nexport function createCartBackup(): void {\n const cart = getCart();\n setItem(getStorageKey('cartBackup'), cart);\n const cartCode = getStoredCartCode();\n if (cartCode) {\n setItem(getStorageKey('couponBackup'), cartCode);\n } else {\n removeItem(getStorageKey('couponBackup'));\n }\n const metadata = getCartMetadata();\n if (metadata) {\n setItem(getStorageKey('metaBackup'), metadata);\n } else {\n const now = Date.now();\n setItem(getStorageKey('metaBackup'), {\n created_at: now,\n last_modified: now,\n version: 1,\n checksum: computeChecksum(cart),\n });\n }\n}\n\nexport function restoreCartFromBackup(): boolean {\n const backupRaw = getItem<unknown>(getStorageKey('cartBackup'));\n const backup = normalizeCartItems(backupRaw);\n const backupMeta = getItem<CartMetadata>(getStorageKey('metaBackup'));\n const backupCoupon = getItem<unknown>(getStorageKey('couponBackup'));\n\n if (backup && backup.length > 0) {\n setCartWithMetadata(backup, backupMeta);\n if (backupCoupon && typeof backupCoupon === 'object' && !Array.isArray(backupCoupon)) {\n const record = backupCoupon as Record<string, unknown>;\n const source = record.source === 'COUPON' || record.source === 'AFFILIATE'\n ? record.source\n : null;\n if (typeof record.code === 'string' && source) {\n setCartCoupon(record.code, source);\n } else {\n clearCartCoupon();\n }\n } else {\n clearCartCoupon();\n }\n return true;\n }\n\n return false;\n}\n\nexport function mergeBaskets(items: CartBasketMergeLine[]): CartItem[] {\n const cart = getCart();\n\n for (const incoming of items) {\n const productId = typeof incoming.product_id === 'string' ? incoming.product_id.trim() : '';\n const variantId = typeof incoming.variant_id === 'string' ? incoming.variant_id.trim() : '';\n if (!productId || !variantId) {\n continue;\n }\n\n let normalizedQuantity: number;\n try {\n normalizedQuantity = normalizeQuantity(incoming.quantity);\n } catch {\n continue;\n }\n\n if (normalizedQuantity < 1) {\n continue;\n }\n\n const mergedLine = ensureCartLineId({\n ...incoming,\n line_id: incoming.line_id ?? computeCartLineId(incoming),\n product_id: productId,\n variant_id: variantId,\n quantity: normalizedQuantity,\n });\n const index = cart.findIndex((item) => item.line_id === mergedLine.line_id);\n\n if (index >= 0) {\n cart[index].quantity = Math.max(cart[index].quantity, normalizedQuantity);\n clampQuantityToBounds(cart[index]);\n } else {\n clampQuantityToBounds(mergedLine);\n cart.push(mergedLine);\n }\n }\n\n writeCart(cart);\n return cart;\n}\n\nexport function moveBasketItem(\n fromProductId: string,\n fromVariantId: string,\n toProductId: string,\n toVariantId: string\n): void {\n const cart = getCart();\n const fromIndex = cart.findIndex(\n (item) => item.product_id === fromProductId && item.variant_id === fromVariantId\n );\n\n if (fromIndex < 0) {\n throw new CartError('Item not found in cart');\n }\n\n const [fromItem] = cart.splice(fromIndex, 1);\n const toLineId = computeCartLineId({\n ...fromItem,\n product_id: toProductId,\n variant_id: toVariantId,\n });\n const toIndex = cart.findIndex((item) => item.line_id === toLineId);\n\n if (toIndex >= 0) {\n cart[toIndex].quantity += fromItem.quantity;\n clampQuantityToBounds(cart[toIndex]);\n } else {\n const moved = ensureCartLineId({\n ...fromItem,\n product_id: toProductId,\n variant_id: toVariantId,\n line_id: toLineId,\n });\n clampQuantityToBounds(moved);\n cart.push(moved);\n }\n\n writeCart(cart);\n}\n\nexport function validateCartIntegrity(): boolean {\n const cart = getCart();\n const metadata = getCartMetadata();\n const checksum = computeChecksum(cart);\n\n if (!metadata) {\n setCartWithMetadata(cart, null);\n return true;\n }\n\n return metadata.checksum === checksum;\n}\n\nexport function getCartStats(): CartStats {\n const cart = getCart();\n const integrityValid = validateCartIntegrity();\n const metadata = getCartMetadata();\n const backup = getItem<CartItem[]>(getStorageKey('cartBackup')) ?? [];\n const hasCompletePriceSnapshots =\n cart.length > 0 &&\n cart.every((item) => typeof item.price_data?.unit_price === 'number');\n const totalPrice = cart.reduce((sum, item) => {\n const unitPrice = item.price_data?.unit_price ?? 0;\n return sum + roundPayableAmount(unitPrice * item.quantity);\n }, 0);\n\n return {\n item_count: cart.length,\n total_quantity: cart.reduce((sum, item) => sum + item.quantity, 0),\n last_modified: metadata?.last_modified ?? 0,\n version: metadata?.version ?? 0,\n has_backup: backup.length > 0,\n integrity_valid: integrityValid,\n total_price: roundPayableAmount(totalPrice),\n total_price_is_estimate: cart.length > 0 && !hasCompletePriceSnapshots,\n };\n}\n\nexport function getCartPayload(coupon?: string): CartPayload {\n const config = getConfig();\n const normalizedCoupon = normalizeCouponCode(coupon) ?? getCartCoupon() ?? undefined;\n return {\n store_slug: config.storeSlug,\n items: getCart(),\n coupon: normalizedCoupon,\n };\n}\n\n/**\n * The ambient referral code checkout() will submit as `affiliate_code`.\n *\n * Read exactly like checkout()'s normalizeAffiliateCode ambient branch: the\n * referral code the cart itself carries (source `AFFILIATE`) takes precedence\n * over the stored `?ref=` attribution. Sending it with the quote is what makes\n * the displayed total equal the amount the invoice will charge — without it a\n * cart holding both a coupon and a `?ref=` attribution quotes high.\n */\nfunction getAmbientAffiliateCodeForQuote(): string | null {\n const storedCode = getCartCoupon();\n const storedSource = getCartCouponSource();\n if (storedSource === 'AFFILIATE' && storedCode) {\n return storedCode.trim().toLowerCase();\n }\n return getAffiliateCode();\n}\n\n/**\n * The proof from the most recent successful quote, held in memory only.\n *\n * Module-scoped rather than persisted: the token is evidence about a cart as\n * it was priced moments ago, and a stale one from a previous page load is\n * simply ignored by the server. Not exported as public API — `checkout()`\n * reads it, callers do not have to know it exists.\n */\nlet latestQuoteToken: string | null = null;\n\n/**\n * Which quote call the held token belongs to.\n *\n * Quote responses settle in ARRIVAL order, not request order: two overlapping\n * `quoteCart` calls (cart A, then cart A+B) can answer with the OLDER one last,\n * and the token stored is then evidence about a cart the buyer no longer has.\n *\n * That is not a mispricing — `/from-cart` binds the token to a hash of the cart\n * content, currency, shop and submitted codes (`isCartQuoteTokenApplicable`),\n * so a superseded token simply fails to apply and is treated as ABSENT, and the\n * proof is a one-directional CEILING that can never lower a price. What it\n * costs is the ceiling itself: the buyer silently loses the protection for the\n * rest of that checkout. Keeping the newest call's answer is what keeps the\n * proof present for the cart actually on screen.\n */\nlet quoteSequence = 0;\n\n/** @internal — read by checkout(); exported only across module boundaries. */\nexport function getLatestQuoteToken(): string | null {\n return latestQuoteToken;\n}\n\n/** @internal — test seam and cart-reset hook. */\nexport function clearLatestQuoteToken(): void {\n latestQuoteToken = null;\n // A quote already in flight must not resurrect the proof this cleared.\n quoteSequence += 1;\n}\n\nexport async function quoteCart(coupon?: string, currency?: string) {\n const sequence = (quoteSequence += 1);\n const payload = getCartPayload(coupon);\n const normalizedCurrency = normalizeRequestedCurrency(currency)\n ?? getRequestedCurrencyFromLocation()\n ?? normalizeRequestedCurrency(getConfig().currency);\n const response = await post<CartQuote>('/v1/storefront/cart/quote', {\n shop_slug: payload.store_slug,\n cart: payload.items,\n coupon: payload.coupon,\n affiliate_code: getAmbientAffiliateCodeForQuote() ?? undefined,\n currency: normalizedCurrency ?? undefined,\n });\n\n // Only a successful quote replaces the held proof — a failed quote must not\n // clear a still-valid one.\n //\n // A SUCCESSFUL quote that carries no token clears it, rather than leaving the\n // previous one in place. The proof is evidence about one specific priced\n // cart, and `/from-cart` refuses a submitted proof it cannot apply\n // (`quote_token_stale` / `_invalid`) instead of ignoring it. So a held token\n // that this quote did not reissue is not a harmless leftover: every later\n // `checkout()` submits it, is refused, and re-quoting never helps because a\n // tokenless answer used to leave it untouched — a dead end the buyer cannot\n // escape from inside the cart.\n //\n // And only the NEWEST call may replace it: a slower earlier quote answering\n // last would otherwise overwrite the current cart's proof with one bound to a\n // cart hash that no longer exists.\n if (sequence !== quoteSequence) return response;\n if (response.success) {\n latestQuoteToken = typeof response.data?.quote_token === 'string'\n ? response.data.quote_token\n : null;\n }\n\n return response;\n}\n\nexport function serializeCart(coupon?: string): string {\n const payload = getCartPayload(coupon);\n const json = JSON.stringify(payload);\n // UTF-8 safe Base64: encodeURIComponent converts to UTF-8, unescape converts percent-encoding to bytes\n if (typeof btoa !== 'undefined') {\n return btoa(unescape(encodeURIComponent(json)));\n }\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(json, 'utf8').toString('base64');\n }\n throw new CartError('Base64 encoding is not available in this environment');\n}\n","/**\n * Checkout Module\n *\n * Creates invoice via backend API and redirects to hosted checkout page.\n * All checkout flows go through: checkout.shoppex.io/invoice/{invoiceId}\n */\n\nimport { getConfig } from '../core/config';\nimport { post } from '../core/client';\nimport { getCart, getCartCoupon, getCartCouponSource, createCartBackup, clearCart, getLatestQuoteToken } from './cart';\nimport { getAffiliateCode } from './affiliates';\nimport type { CartItem, CartAddon } from '../types/cart';\nimport type { BuyerRewards } from '../types/api';\nimport {\n getRequestedCurrencyFromLocation,\n normalizeRequestedCurrency,\n} from '../utils/requested-currency';\n\nexport interface CheckoutOptions {\n autoRedirect?: boolean;\n locale?: string;\n email?: string;\n coupon?: string;\n currency?: string;\n /**\n * Referral (affiliate) code to submit, as a tri-state:\n *\n * - `undefined` — the SDK resolves it from storage (cart-applied referral\n * code first, then the ambient `?ref=` attribution).\n * - `''` — explicitly none: submit no referral code and do NOT re-read\n * storage. This is how a caller pins \"quoted WITHOUT a referral\"; without\n * it a code captured between the quote and the submit would be applied to\n * a total the buyer never saw.\n * - non-empty — pinned: submit exactly this code.\n *\n * `referralCode` is an alias and follows the same rules; `affiliateCode`\n * wins when both are present.\n */\n affiliateCode?: string;\n /** Alias of {@link CheckoutOptions.affiliateCode}, same tri-state. */\n referralCode?: string;\n customerCheckoutPath?: '/dashboard/api/checkout';\n /**\n * The cart this hand-off was approved FOR, as `JSON.stringify(getCart())`.\n *\n * PAYMENT PATH. A caller that writes the cart and reads it back before\n * checking out (Buy Now, which replaces the cart, is the sharp case) verifies\n * a cart it read at one moment, while these functions read storage again on\n * their way into the request — and localStorage is shared with every other\n * tab on the domain. A write landing in that gap is billed without ever\n * having passed the caller's verification.\n *\n * The caller cannot close that itself: any check it makes is one more read\n * BEFORE this one. Pinning the expected bytes moves the comparison to the\n * only place it can be conclusive — against the exact cart the call is about\n * to POST. A mismatch refuses before anything is created or sent.\n *\n * Honoured identically by BOTH invoice-creating entry points, `checkout()`\n * and `buildCheckoutUrl()` — they hit the same endpoint and create the same\n * invoice, so a pin that held on one and not the other would be a promise\n * the caller could not rely on. Only the refusal shape differs, following\n * each function's own success shape: `checkout()` returns\n * `{ success: false }`, `buildCheckoutUrl()` throws.\n *\n * Optional and additive: omitted, nothing changes, and the server is not\n * involved either way.\n */\n expectedCart?: string;\n}\n\nexport interface CheckoutResult {\n success: boolean;\n redirectUrl?: string;\n invoiceId?: string;\n rewards?: BuyerRewards | null;\n message?: string;\n /**\n * The server's machine-readable refusal identifier when the checkout was\n * refused, e.g. `errors.checkout.price_increased_since_quote` or\n * `errors.checkout.affiliate_code_not_applicable`. Branch on this rather\n * than on `message`, which is localized display copy.\n *\n * The quote-proof family — `errors.checkout.quote_token_invalid`,\n * `errors.checkout.quote_token_expired`, `errors.checkout.quote_token_stale`\n * — says the proof this call submitted could not be honoured: not ours, past\n * its window, or priced for a cart/currency/codes that have since moved. The\n * server refuses rather than pricing without the ceiling, so the caller's\n * response is always the same: `quoteCart()` again, show the buyer the new\n * total, and only then retry. A retry with the same stale token is refused\n * identically.\n *\n * Absent for failures the server never named (transport, timeout, an empty\n * cart caught client-side).\n */\n code?: string;\n}\n\ninterface CheckoutApiResponse {\n invoiceId?: string;\n checkoutUrl?: string;\n invoice_id?: string;\n checkout_url?: string;\n uniqid?: string;\n url?: string;\n url_branded?: string;\n rewards?: BuyerRewards | null;\n invoice?: {\n invoiceId?: string;\n checkoutUrl?: string;\n invoice_id?: string;\n checkout_url?: string;\n uniqid?: string;\n url?: string;\n url_branded?: string;\n rewards?: BuyerRewards | null;\n };\n}\n\ninterface NormalizedCheckoutData {\n invoiceId: string;\n checkoutUrl: string;\n rewards: BuyerRewards | null;\n}\n\nconst CHECKOUT_PREFILL_EMAIL_HASH_KEY = 'shoppex_prefill_email';\n\n/**\n * PAYMENT PATH. The single refusal copy for a broken `expectedCart` pin, shared\n * by every entry point that honours the pin so the buyer reads the same\n * sentence whichever one the theme calls. One literal, because two copies drift\n * and the difference would be visible to buyers on the same storefront.\n */\nconst CART_CHANGED_MESSAGE = 'Your cart changed while checkout was starting. Please review it and try again.';\n\n/**\n * PAYMENT PATH. True when the caller pinned a cart and storage no longer holds\n * it — see `CheckoutOptions.expectedCart`. Compared against the exact array the\n * caller is about to bill, which is the only comparison that is conclusive:\n * anything the caller checks itself is one more read BEFORE the read that\n * feeds the request.\n *\n * An omitted pin is not a mismatch. The pin is additive, and a caller that\n * never made the promise is left exactly as it was.\n */\nfunction isExpectedCartMismatch(cart: CartItem[], expectedCart: string | undefined): boolean {\n return expectedCart !== undefined && JSON.stringify(cart) !== expectedCart;\n}\n\nfunction normalizeCoupon(coupon: string | null | undefined): string | null {\n const normalized = coupon?.trim();\n return normalized ? normalized : null;\n}\n\nfunction normalizeEmail(email: string | null | undefined): string | null {\n const normalized = email?.trim();\n return normalized ? normalized : null;\n}\n\nfunction resolveCustomerCheckoutRequestTarget(options: CheckoutOptions): {\n endpoint: string;\n baseUrl?: string;\n} {\n if (\n options.customerCheckoutPath === '/dashboard/api/checkout'\n && typeof window !== 'undefined'\n && typeof window.location?.origin === 'string'\n ) {\n return {\n endpoint: options.customerCheckoutPath,\n baseUrl: window.location.origin,\n };\n }\n\n return { endpoint: '/v1/storefront/invoices/from-cart' };\n}\n\nfunction resolveRequestedCheckoutCurrency(options: CheckoutOptions): string | null {\n return normalizeRequestedCurrency(options.currency)\n ?? getRequestedCurrencyFromLocation()\n ?? normalizeRequestedCurrency(getConfig().currency);\n}\n\nfunction normalizeCheckoutFailureMessage(rawMessage: string | null | undefined): string {\n const message = rawMessage?.trim() ?? '';\n if (!message) {\n return 'Checkout failed. Please try again.';\n }\n\n if (isStaleCartProductError(message)) {\n return 'Your cart is outdated. Please add the products again.';\n }\n\n const httpMatch = message.match(/^HTTP\\s+(\\d{3})(?::\\s*(.*))?$/i);\n if (httpMatch) {\n const status = Number(httpMatch[1]);\n const detail = httpMatch[2]?.trim();\n\n if (detail && detail.length > 0) {\n return `Checkout failed: ${detail}`;\n }\n\n if (status >= 500) {\n return 'Checkout is temporarily unavailable. Please try again.';\n }\n\n if (status === 400) {\n return 'Checkout failed. Please check your details and try again.';\n }\n\n if (status === 401 || status === 403) {\n return 'Checkout is currently unavailable for this request.';\n }\n\n return 'Checkout failed. Please try again.';\n }\n\n if (/^internal server error$/i.test(message)) {\n return 'Checkout is temporarily unavailable. Please try again.';\n }\n\n return message;\n}\n\nfunction isStaleCartProductError(rawMessage: string | null | undefined): boolean {\n const message = rawMessage?.trim().toLowerCase() ?? '';\n if (!message) {\n return false;\n }\n\n return message.includes('product not found')\n || message.includes('product not available')\n || message.includes('products are no longer available')\n || message.includes('outdated product');\n}\n\nfunction validateCheckoutUrl(\n checkoutUrl: string,\n checkoutBaseUrl: string | undefined,\n expectedInvoiceId?: string\n): string | null {\n const expectedBaseUrl = checkoutBaseUrl?.trim();\n if (!expectedBaseUrl) {\n return null;\n }\n\n try {\n const parsedCheckoutUrl = new URL(checkoutUrl);\n const parsedExpectedBaseUrl = new URL(expectedBaseUrl);\n\n if (parsedCheckoutUrl.origin !== parsedExpectedBaseUrl.origin) {\n return null;\n }\n\n const normalizedPath = parsedCheckoutUrl.pathname.replace(/\\/+$/, '');\n const normalizedBasePath = parsedExpectedBaseUrl.pathname.replace(/\\/+$/, '');\n const expectedInvoicePath = `${normalizedBasePath}/invoice/`.replace(/\\/{2,}/g, '/');\n if (!normalizedPath.startsWith(expectedInvoicePath)) {\n return null;\n }\n\n const invoiceIdSegment = normalizedPath.slice(expectedInvoicePath.length);\n if (!invoiceIdSegment || invoiceIdSegment.includes('/')) {\n return null;\n }\n\n if (expectedInvoiceId) {\n const normalizedExpectedInvoiceId = expectedInvoiceId.trim();\n const invoiceIdFromUrl = decodeURIComponent(invoiceIdSegment);\n if (!normalizedExpectedInvoiceId || invoiceIdFromUrl !== normalizedExpectedInvoiceId) {\n return null;\n }\n }\n\n return parsedCheckoutUrl.toString();\n } catch {\n return null;\n }\n}\n\nfunction buildCheckoutUrlFromInvoiceId(\n checkoutBaseUrl: string | undefined,\n invoiceId: string\n): string | null {\n const normalizedBaseUrl = checkoutBaseUrl?.trim();\n if (!normalizedBaseUrl) {\n return null;\n }\n\n try {\n const baseUrl = new URL(normalizedBaseUrl);\n const basePath = baseUrl.pathname.replace(/\\/+$/, '');\n baseUrl.pathname = `${basePath}/invoice/${encodeURIComponent(invoiceId)}`.replace(/\\/{2,}/g, '/');\n baseUrl.search = '';\n baseUrl.hash = '';\n return baseUrl.toString();\n } catch {\n return null;\n }\n}\n\nfunction appendCheckoutUrlOptions(\n checkoutUrl: string,\n options: { email?: string | null; locale?: string },\n): string {\n const normalizedEmail = normalizeEmail(options.email);\n const normalizedLocale = typeof options.locale === 'string' ? options.locale.trim() : '';\n\n if (!normalizedEmail && !normalizedLocale) {\n return checkoutUrl;\n }\n\n try {\n const parsedCheckoutUrl = new URL(checkoutUrl);\n if (normalizedLocale) {\n parsedCheckoutUrl.searchParams.set('locale', normalizedLocale);\n }\n if (normalizedEmail) {\n const hashParams = new URLSearchParams(parsedCheckoutUrl.hash.startsWith('#')\n ? parsedCheckoutUrl.hash.slice(1)\n : parsedCheckoutUrl.hash);\n hashParams.set(CHECKOUT_PREFILL_EMAIL_HASH_KEY, normalizedEmail);\n parsedCheckoutUrl.hash = hashParams.toString();\n }\n return parsedCheckoutUrl.toString();\n } catch {\n return checkoutUrl;\n }\n}\n\nfunction normalizeCheckoutResponse(\n response: CheckoutApiResponse | undefined,\n checkoutBaseUrl: string | undefined\n): NormalizedCheckoutData | null {\n const nestedInvoice = response?.invoice;\n const invoiceId = response?.invoiceId?.trim()\n || response?.invoice_id?.trim()\n || response?.uniqid?.trim()\n || nestedInvoice?.invoiceId?.trim()\n || nestedInvoice?.invoice_id?.trim()\n || nestedInvoice?.uniqid?.trim();\n let checkoutUrl = response?.checkoutUrl?.trim()\n || response?.checkout_url?.trim()\n || response?.url_branded?.trim()\n || response?.url?.trim()\n || nestedInvoice?.checkoutUrl?.trim()\n || nestedInvoice?.checkout_url?.trim()\n || nestedInvoice?.url_branded?.trim()\n || nestedInvoice?.url?.trim();\n\n if (!checkoutUrl && invoiceId && nestedInvoice) {\n checkoutUrl = buildCheckoutUrlFromInvoiceId(checkoutBaseUrl, invoiceId) ?? undefined;\n }\n\n if (!invoiceId || !checkoutUrl) {\n return null;\n }\n\n return {\n invoiceId,\n checkoutUrl,\n rewards: response?.rewards ?? nestedInvoice?.rewards ?? null,\n };\n}\n\nfunction resolveCheckoutOptions(\n couponOrOptions?: string | CheckoutOptions,\n options?: CheckoutOptions\n): CheckoutOptions {\n if (typeof couponOrOptions === 'string') {\n return {\n ...options,\n coupon: couponOrOptions,\n };\n }\n\n return couponOrOptions ?? options ?? {};\n}\n\nfunction normalizeAffiliateCode(options: CheckoutOptions, storedAffiliateCode: string | null): string | null {\n const explicitCode = options.affiliateCode ?? options.referralCode;\n // Tri-state, mirroring `coupon`: an explicit empty string means \"none\" and\n // must suppress the storage re-read. Only `undefined` lets the SDK resolve\n // the code itself — otherwise a referral captured after the quote was\n // rendered would be applied to a total the buyer never saw.\n if (typeof explicitCode === 'string') {\n const normalized = explicitCode.trim().toLowerCase();\n return normalized.length > 0 ? normalized : null;\n }\n\n return storedAffiliateCode?.trim().toLowerCase() ?? getAffiliateCode();\n}\n\nfunction resolveCheckoutCodes(options: CheckoutOptions): {\n coupon: string | null;\n affiliateCode: string | null;\n} {\n const storedCode = getCartCoupon();\n const storedSource = getCartCouponSource();\n const coupon = options.coupon === undefined\n ? (storedSource === 'COUPON' ? storedCode : null)\n : normalizeCoupon(options.coupon);\n const storedAffiliateCode = options.coupon === undefined && storedSource === 'AFFILIATE'\n ? storedCode\n : null;\n\n return {\n coupon,\n affiliateCode: normalizeAffiliateCode(options, storedAffiliateCode),\n };\n}\n\nfunction mapCartItemsForApi(items: CartItem[]) {\n const normalizeVariantIdForApi = (value: string | null | undefined): string | null => {\n const normalized = value?.trim();\n if (!normalized) return null;\n // Themes use \"default\" as a sentinel for \"no variant selected\".\n // Backend expects `null` in that case.\n if (normalized.toLowerCase() === 'default') return null;\n return normalized;\n };\n\n return items.map((item) => ({\n product_id: item.product_id,\n variant_id: normalizeVariantIdForApi(item.variant_id),\n quantity: item.quantity,\n addons: item.addons?.map((a: CartAddon) => ({ id: a.id, quantity: a.quantity ?? 1 })),\n custom_fields: item.custom_fields,\n price_variant_id: item.price_variant_id || null,\n pay_what_you_want_price: item.pay_what_you_want_price,\n }));\n}\n\nexport async function checkout(\n couponOrOptions?: string | CheckoutOptions,\n options?: CheckoutOptions\n): Promise<CheckoutResult> {\n const resolvedOptions = resolveCheckoutOptions(couponOrOptions, options);\n const { autoRedirect = true, email } = resolvedOptions;\n const checkoutCodes = resolveCheckoutCodes(resolvedOptions);\n const normalizedCoupon = checkoutCodes.coupon;\n const normalizedEmail = normalizeEmail(email);\n const normalizedAffiliateCode = checkoutCodes.affiliateCode;\n const requestedCurrency = resolveRequestedCheckoutCurrency(resolvedOptions);\n\n const cart = getCart();\n if (cart.length === 0) {\n return {\n success: false,\n message: 'Cart is empty',\n };\n }\n\n // PAYMENT PATH. The cart the caller approved, compared against the cart this\n // call will actually POST — see `CheckoutOptions.expectedCart`. Refused\n // before the backup and before the request, so a cart that changed under the\n // caller is never billed and nothing is left half-done.\n if (isExpectedCartMismatch(cart, resolvedOptions.expectedCart)) {\n return {\n success: false,\n message: CART_CHANGED_MESSAGE,\n };\n }\n\n createCartBackup();\n\n const config = getConfig();\n const checkoutRequestTarget = resolveCustomerCheckoutRequestTarget(resolvedOptions);\n\n const response = await post<CheckoutApiResponse>(\n checkoutRequestTarget.endpoint,\n {\n shop_slug: config.storeSlug,\n cart: mapCartItemsForApi(cart),\n email: normalizedEmail,\n coupon: normalizedCoupon,\n currency: requestedCurrency,\n affiliate_code: normalizedAffiliateCode,\n // Proof of the total the buyer approved, from the last quoteCart(). Sent\n // automatically so the server can refuse an invoice priced above it.\n // Undefined when nothing has been quoted this session — the endpoint\n // treats that exactly as an older SDK.\n quote_token: getLatestQuoteToken() ?? undefined,\n },\n { retries: 0, baseUrl: checkoutRequestTarget.baseUrl }\n );\n\n if (!response.success || !response.data) {\n if (isStaleCartProductError(response.message)) {\n clearCart();\n }\n return {\n success: false,\n message: normalizeCheckoutFailureMessage(response.message),\n // The server's machine-readable refusal, preserved so callers can react\n // to e.g. `errors.checkout.price_increased_since_quote` without matching\n // localized copy.\n ...(response.code ? { code: response.code } : {}),\n };\n }\n\n const checkoutData = normalizeCheckoutResponse(response.data, config.checkoutBaseUrl);\n if (!checkoutData) {\n return {\n success: false,\n message: 'Failed to create invoice',\n };\n }\n\n const { invoiceId } = checkoutData;\n const safeCheckoutUrl = validateCheckoutUrl(\n checkoutData.checkoutUrl,\n config.checkoutBaseUrl,\n invoiceId\n );\n if (!safeCheckoutUrl) {\n return {\n success: false,\n message: 'Failed to create invoice',\n };\n }\n\n const checkoutUrlWithPrefill = appendCheckoutUrlOptions(safeCheckoutUrl, {\n email: normalizedEmail,\n locale: resolvedOptions.locale ?? config.locale,\n });\n\n if (autoRedirect) {\n if (typeof window !== 'undefined' && window?.location) {\n window.location.href = checkoutUrlWithPrefill;\n clearCart();\n }\n }\n\n return {\n success: true,\n redirectUrl: checkoutUrlWithPrefill,\n invoiceId,\n rewards: checkoutData.rewards,\n };\n}\n\n/**\n * Build checkout URL by creating invoice first.\n * Returns the checkout URL for the created invoice.\n *\n * PAYMENT PATH. \"Build a URL\" names what this returns, not a lighter way to\n * price a cart: it POSTs the same invoice-creating endpoint as `checkout()` and\n * bills whatever storage holds when it reads. It therefore honours\n * `CheckoutOptions.expectedCart` on exactly the same terms — a pinned cart that\n * moved is refused, not invoiced.\n *\n * A refusal throws, like every other refusal on this function: the success\n * shape is a URL string, so there is no in-band value that a caller could\n * mistake for one. The thrown message is the buyer-facing copy, identical to\n * the sentence `checkout()` returns, and callers that already handle the\n * `Cart is empty` throw handle this one unchanged.\n */\nexport async function buildCheckoutUrl(\n couponOrOptions?: string | CheckoutOptions,\n options?: CheckoutOptions\n): Promise<string> {\n const resolvedOptions = resolveCheckoutOptions(couponOrOptions, options);\n const { email } = resolvedOptions;\n const checkoutCodes = resolveCheckoutCodes(resolvedOptions);\n const normalizedCoupon = checkoutCodes.coupon;\n const normalizedEmail = normalizeEmail(email);\n const normalizedAffiliateCode = checkoutCodes.affiliateCode;\n const requestedCurrency = resolveRequestedCheckoutCurrency(resolvedOptions);\n\n const cart = getCart();\n if (cart.length === 0) {\n throw new Error('Cart is empty');\n }\n\n // PAYMENT PATH. Same position `checkout()` puts it in: after the empty-cart\n // check and before anything is created or sent. This path has no cart backup\n // to write, so the request is the first side effect there is — refusing here\n // means a cart that changed under the caller never reaches the endpoint, and\n // the buyer's cart is left exactly as the interfering write left it. It\n // matters most with no quote token in play, because then nothing downstream\n // carries an approved-total ceiling either.\n if (isExpectedCartMismatch(cart, resolvedOptions.expectedCart)) {\n throw new Error(CART_CHANGED_MESSAGE);\n }\n\n const config = getConfig();\n const checkoutRequestTarget = resolveCustomerCheckoutRequestTarget(resolvedOptions);\n\n const response = await post<CheckoutApiResponse>(\n checkoutRequestTarget.endpoint,\n {\n shop_slug: config.storeSlug,\n cart: mapCartItemsForApi(cart),\n email: normalizedEmail,\n coupon: normalizedCoupon,\n currency: requestedCurrency,\n affiliate_code: normalizedAffiliateCode,\n // Same invoice-creating endpoint as `checkout()`, so it carries the same\n // proof of the approved total. \"Build a URL\" describes what this returns\n // to the caller, not a different way to price a cart — omitting the\n // token here left a public path on which the server had nothing to check\n // the invoice against. Same optional semantics: undefined when nothing\n // was quoted this session.\n quote_token: getLatestQuoteToken() ?? undefined,\n },\n { retries: 0, baseUrl: checkoutRequestTarget.baseUrl }\n );\n\n if (!response.success || !response.data) {\n if (isStaleCartProductError(response.message)) {\n clearCart();\n }\n throw new Error(normalizeCheckoutFailureMessage(response.message));\n }\n const checkoutData = normalizeCheckoutResponse(response.data, config.checkoutBaseUrl);\n if (!checkoutData) {\n throw new Error('Failed to create invoice');\n }\n\n const safeCheckoutUrl = validateCheckoutUrl(\n checkoutData.checkoutUrl,\n config.checkoutBaseUrl,\n checkoutData.invoiceId\n );\n if (!safeCheckoutUrl) {\n throw new Error('Failed to create invoice');\n }\n\n return appendCheckoutUrlOptions(safeCheckoutUrl, {\n email: normalizedEmail,\n locale: resolvedOptions.locale ?? config.locale,\n });\n}\n\n/**\n * @deprecated Use buildCheckoutUrl instead.\n * Sync version is no longer supported as invoice creation requires API call.\n */\nexport function buildCheckoutUrlSync(): never {\n throw new Error('buildCheckoutUrlSync is deprecated. Use buildCheckoutUrl (async) instead.');\n}\n","/**\n * Coupons Module\n *\n * Coupon validation before checkout.\n */\n\nimport { post } from '../core/client';\nimport { getShopId } from '../core/config';\nimport { getStore } from './store';\nimport { getCart } from './cart';\nimport type { SDKResponse, CouponValidation, CouponValidationOptions } from '../types';\n\nasync function resolveShopId(): Promise<string | null> {\n const cachedShopId = getShopId();\n if (cachedShopId) {\n return cachedShopId;\n }\n\n const storeResult = await getStore();\n if (!storeResult.success || !storeResult.data?.id) {\n return null;\n }\n\n return storeResult.data.id;\n}\n\nexport async function validateCoupon(\n code: string,\n productOrOptions?: string | CouponValidationOptions\n): Promise<SDKResponse<CouponValidation>> {\n const trimmedCode = code.trim();\n if (!trimmedCode) {\n return {\n success: false,\n message: 'Coupon code is required',\n };\n }\n\n const payload: Record<string, unknown> = {\n code: trimmedCode,\n };\n const productId = typeof productOrOptions === 'string'\n ? productOrOptions\n : productOrOptions?.productId;\n const variantId = typeof productOrOptions === 'string'\n ? undefined\n : productOrOptions?.variantId;\n\n if (variantId && !productId) {\n return {\n success: false,\n message: 'productId is required when variantId is provided',\n };\n }\n\n if (productId) {\n payload.product_id = productId;\n if (variantId) {\n payload.variant_id = variantId;\n }\n } else {\n const cart = getCart();\n if (cart.length === 0) {\n return {\n success: false,\n message: 'Cart is empty',\n };\n }\n\n const shopId = await resolveShopId();\n if (!shopId) {\n return {\n success: false,\n message: 'Failed to resolve store',\n };\n }\n\n payload.cart = JSON.stringify({\n shop_id: shopId,\n products: cart.map((item) => ({\n uniqid: item.product_id,\n quantity: item.quantity,\n variant_id: item.variant_id,\n price_variant_id: item.price_variant_id,\n addons: item.addons?.map((addon) => ({\n id: addon.id,\n quantity: addon.quantity ?? 1,\n })),\n })),\n });\n }\n\n const response = await post<CouponValidation>(\n '/v1/storefront/coupons/check',\n payload\n );\n\n return response;\n}\n","/**\n * Reviews Module\n *\n * Shop-level feedback/reviews.\n * Note: Shoppex has shop-level feedback, not product-level reviews.\n */\n\nimport { get } from '../core/client';\nimport { getConfig } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type { SDKResponse, Feedback, ShopReviewsPage } from '../types';\n\nconst REVIEWS_PAGE_LIMIT = 100;\nconst REVIEWS_CACHE_TTL = 2 * 60 * 1000;\n\nfunction toFiniteNumber(value: unknown): number | null {\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value;\n }\n\n if (typeof value === 'string' && value.trim() !== '') {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : null;\n }\n\n return null;\n}\n\nfunction firstString(...values: unknown[]): string | undefined {\n for (const value of values) {\n if (typeof value === 'string' && value.length > 0) {\n return value;\n }\n }\n\n return undefined;\n}\n\nfunction normalizeFeedback(raw: Feedback, index: number): Feedback {\n const record = raw as Feedback & Record<string, unknown>;\n const rating = toFiniteNumber(record.rating) ?? toFiniteNumber(record.score) ?? 0;\n const comment = firstString(record.comment, record.message);\n const author = firstString(record.author, record.customer_name);\n const createdAt = record.created_at ?? record.createdAt;\n const created_at =\n typeof createdAt === 'number' || typeof createdAt === 'string'\n ? String(createdAt)\n : '';\n const id = firstString(record.id, record.uniqid) ?? `review:${created_at || index}`;\n\n return {\n ...record,\n id,\n rating,\n ...(comment ? { comment } : {}),\n ...(author ? { author } : {}),\n created_at,\n };\n}\n\nexport async function getShopReviewsPage(cursor?: string | null): Promise<SDKResponse<ShopReviewsPage>> {\n const config = getConfig();\n const query = new URLSearchParams();\n query.set('limit', String(REVIEWS_PAGE_LIMIT));\n if (typeof cursor === 'string' && cursor.trim().length > 0) {\n query.set('cursor', cursor);\n }\n const querySuffix = `?${query.toString()}`;\n\n const response = await get<ShopReviewsPage>(\n `${buildEndpoint('/v1/storefront/feedback/shop/:storeSlug', {\n storeSlug: config.storeSlug,\n })}${querySuffix}`,\n {\n cache: {\n key: `reviews:${config.storeSlug}:${cursor ?? 'start'}:${REVIEWS_PAGE_LIMIT}`,\n ttl: REVIEWS_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: {\n ...response.data,\n feedback: response.data.feedback.map(normalizeFeedback),\n },\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport async function getShopReviews(): Promise<SDKResponse<Feedback[]>> {\n const allFeedback: Feedback[] = [];\n const seenCursors = new Set<string>();\n let cursor: string | null = null;\n\n while (true) {\n const response = await getShopReviewsPage(cursor);\n if (!response.success || !response.data) {\n return {\n success: false,\n message: response.message,\n data: [],\n };\n }\n\n allFeedback.push(...response.data.feedback);\n\n const pagination = response.data.pagination;\n if (!pagination?.has_more || !pagination.next_cursor) {\n break;\n }\n\n if (seenCursors.has(pagination.next_cursor)) {\n break;\n }\n\n seenCursors.add(pagination.next_cursor);\n cursor = pagination.next_cursor;\n }\n\n return {\n success: true,\n data: allFeedback,\n };\n}\n","/**\n * Customer Module\n *\n * Authenticated customer account calls for code-lane storefronts. The edge\n * worker owns the HttpOnly session cookie and derives the shop from the host.\n * This module therefore sends neither a session token nor shop identity.\n */\n\nimport {\n customerPortalDashboardSchema,\n customerPortalInvoiceDetailSchema,\n customerPortalPaginatedInvoicesSchema,\n type CustomerPortalDashboardWire,\n type CustomerPortalInvoiceDetailWire,\n type CustomerPortalPaginatedInvoicesWire,\n} from '@shoppex/contracts';\nimport type { SDKResponse } from '../types';\n\nconst CUSTOMER_API_PREFIX = '/api/customer';\n\ntype CustomerMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';\n\n/**\n * A producer-owned schema for the response payload.\n *\n * Only the endpoints whose shape is defined in `@shoppex/contracts` get one.\n * The rest stay `unknown` on purpose: inventing a type here would assert a wire\n * shape the producer never promised, which is the pattern the retired portal's\n * 544-line hand-written type file demonstrates the cost of.\n */\ninterface CustomerPayloadSchema<T> {\n safeParse(value: unknown): { success: true; data: T } | { success: false };\n}\n\ninterface CustomerRequestOptions<T> {\n method?: CustomerMethod;\n body?: unknown;\n /** Multipart payload. Mutually exclusive with `body`; the browser sets the boundary. */\n formData?: FormData;\n schema?: CustomerPayloadSchema<T>;\n}\n\nexport interface CustomerOrdersQuery {\n page?: number;\n limit?: number;\n /**\n * Invoice status filter, verbatim from the producer's enum. Anything else is\n * answered with a 400 rather than quietly ignored, so pass what the buyer\n * actually chose.\n */\n status?: string;\n /** Partial invoice-id search. The producer trims it to 64 characters. */\n search?: string;\n}\n\ninterface CustomerApiEnvelope {\n status: number;\n data: unknown;\n error?: unknown;\n message?: unknown;\n error_code?: unknown;\n error_params?: unknown;\n}\n\nexport interface CustomerTicketPayload {\n title?: string;\n message: string;\n invoice_id?: string;\n}\n\nexport interface CustomerProfilePatch {\n name: string;\n}\n\nexport interface CustomerSubscriptionCancelOptions {\n cancel_at_period_end?: boolean;\n reason?: string | null;\n}\n\nexport interface CustomerEmailPreferencesPatch {\n global_unsubscribed?: boolean;\n list_subscriptions?: Array<{ list_id: string; subscribed: boolean }>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction narrowEnvelope(value: unknown): CustomerApiEnvelope | null {\n if (!isRecord(value) || typeof value.status !== 'number' || !('data' in value)) {\n return null;\n }\n\n return value as unknown as CustomerApiEnvelope;\n}\n\nfunction readMessage(envelope: CustomerApiEnvelope, response: Response): string {\n if (typeof envelope.error === 'string' && envelope.error.length > 0) {\n return envelope.error;\n }\n\n if (typeof envelope.message === 'string' && envelope.message.length > 0) {\n return envelope.message;\n }\n\n return response.statusText\n ? `HTTP ${response.status}: ${response.statusText}`\n : `HTTP ${response.status}`;\n}\n\nfunction readErrorFields(envelope: CustomerApiEnvelope): Pick<SDKResponse<unknown>, 'code' | 'errorParams'> {\n const code = typeof envelope.error_code === 'string' && envelope.error_code.length > 0\n ? envelope.error_code\n : null;\n\n if (!code) {\n return {};\n }\n\n return {\n code,\n ...(isRecord(envelope.error_params) ? { errorParams: envelope.error_params } : {}),\n };\n}\n\nasync function requestCustomer<T = unknown>(\n path: string,\n options: CustomerRequestOptions<T> = {},\n): Promise<SDKResponse<T>> {\n const method = options.method ?? 'GET';\n const headers: Record<string, string> = {\n Accept: 'application/json',\n };\n\n if (options.body !== undefined) {\n headers['Content-Type'] = 'application/json';\n }\n\n // FormData carries its own multipart boundary in the Content-Type the browser\n // generates; setting the header here would produce a body the server cannot parse.\n const payload = options.formData ?? (options.body !== undefined ? JSON.stringify(options.body) : undefined);\n\n try {\n const response = await fetch(`${CUSTOMER_API_PREFIX}${path}`, {\n method,\n headers,\n body: payload,\n credentials: 'same-origin',\n cache: 'no-store',\n });\n\n if (response.status === 204) {\n return response.ok\n ? { success: true, status: response.status }\n : {\n success: false,\n status: response.status,\n message: readMessage({ status: response.status, data: null }, response),\n };\n }\n\n let rawEnvelope: unknown;\n try {\n rawEnvelope = await response.json();\n } catch {\n return { success: false, status: response.status, message: 'Invalid customer API response' };\n }\n\n const envelope = narrowEnvelope(rawEnvelope);\n if (!envelope) {\n return { success: false, status: response.status, message: 'Invalid customer API response' };\n }\n\n if (!response.ok || envelope.status < 200 || envelope.status >= 300) {\n return {\n success: false,\n // The transport status, not the envelope's: a caller deciding whether\n // the buyer is signed out must not be steered by a body the edge may\n // never have produced.\n status: response.status,\n message: readMessage(envelope, response),\n ...readErrorFields(envelope),\n };\n }\n\n const message = typeof envelope.message === 'string' && envelope.message.length > 0\n ? { message: envelope.message }\n : {};\n\n if (!options.schema) {\n return { success: true, data: envelope.data as T, ...message };\n }\n\n const parsed = options.schema.safeParse(envelope.data);\n if (!parsed.success) {\n // Fail loudly instead of handing back a payload that does not match what\n // the producer promised. A silently reshaped or partially-read response\n // is how a contract drift reaches the buyer's screen as wrong data.\n return { success: false, message: 'Customer API response did not match the expected contract' };\n }\n\n return { success: true, data: parsed.data, ...message };\n } catch (error) {\n return {\n success: false,\n message: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/** One basket line for a QUOTE. `variant_id` is omitted, never null, when a product has no variants. */\nexport interface ResellerOrderItem {\n product_id: string;\n variant_id?: string;\n quantity: number;\n}\n\nexport interface ResellerCatalogQuery {\n search?: string;\n page?: number;\n per_page?: number;\n}\n\nexport interface ResellerOrdersQuery {\n page?: number;\n per_page?: number;\n}\n\nexport function requestOtp(email: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/auth/otp/request', {\n method: 'POST',\n body: { email },\n });\n}\n\n/**\n * The wire field is `otp`, not `code` — `CustomerOtpVerifyBodySchema` in\n * `apps/backend-elysia/src/routes/v1/customer/schemas.ts` requires it under that\n * name, and a `code` body is rejected with 400.\n */\nexport function verifyOtp(email: string, otp: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/auth/otp/verify', {\n method: 'POST',\n body: { email, otp },\n });\n}\n\nexport function logout(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/auth/logout', { method: 'POST' });\n}\n\nexport function me(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/me');\n}\n\nexport function dashboard(): Promise<SDKResponse<CustomerPortalDashboardWire>> {\n return requestCustomer('/dashboard', { schema: customerPortalDashboardSchema });\n}\n\n/**\n * Paginated order history.\n *\n * Page-based, matching the producer: `invoices.routes.ts` reads `page` and\n * `limit` and answers with a `has_more` envelope. A cursor parameter would be\n * ignored upstream and silently return page one forever.\n *\n * `status` and `search` are filtered SERVER-side, which is why they belong\n * here rather than in the caller: `/invoices` is paged, and a filter applied\n * to the page in hand would filter only the rows that page happens to hold.\n * The producer spells the search `q`.\n */\nexport function orders(options: CustomerOrdersQuery = {}): Promise<SDKResponse<CustomerPortalPaginatedInvoicesWire>> {\n const query = new URLSearchParams();\n if (options.page !== undefined) query.set('page', String(options.page));\n if (options.limit !== undefined) query.set('limit', String(options.limit));\n if (options.status) query.set('status', options.status);\n if (options.search) query.set('q', options.search);\n\n const suffix = query.size > 0 ? `?${query.toString()}` : '';\n return requestCustomer(`/invoices${suffix}`, { schema: customerPortalPaginatedInvoicesSchema });\n}\n\nexport function order(id: string): Promise<SDKResponse<CustomerPortalInvoiceDetailWire>> {\n return requestCustomer(`/invoice/${encodeURIComponent(id)}`, {\n schema: customerPortalInvoiceDetailSchema,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Licenses, subscriptions and tickets have NO collection route.\n//\n// Those three lists arrive inside `/dashboard` — `licenses.routes.ts`,\n// `subscriptions.routes.ts` and `tickets.routes.ts` expose per-item routes only.\n// A `GET /licenses` here would 404 on every call, which is what the earlier\n// spelling of this module did.\n// ---------------------------------------------------------------------------\n\nexport function resetLicenseHwid(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/licenses/${encodeURIComponent(uniqid)}/reset-hwid`, {\n method: 'POST',\n body: {},\n });\n}\n\nexport function subscriptionBillingHistory(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/subscriptions/${encodeURIComponent(uniqid)}/billing-history`);\n}\n\nexport function cancelSubscription(\n uniqid: string,\n options: CustomerSubscriptionCancelOptions = {},\n): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/subscriptions/${encodeURIComponent(uniqid)}/cancel`, {\n method: 'POST',\n body: {\n ...(options.cancel_at_period_end !== undefined\n ? { cancel_at_period_end: options.cancel_at_period_end }\n : {}),\n ...(options.reason !== undefined ? { reason: options.reason } : {}),\n },\n });\n}\n\nexport function pauseSubscription(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/subscriptions/${encodeURIComponent(uniqid)}/pause`, {\n method: 'POST',\n body: {},\n });\n}\n\nexport function resumeSubscription(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/subscriptions/${encodeURIComponent(uniqid)}/resume`, {\n method: 'POST',\n body: {},\n });\n}\n\nexport function favorites(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/favorites');\n}\n\n/** Idempotent upstream, and a PUT — `customer-favorites.ts` has no POST route. */\nexport function addFavorite(productUniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/favorites/${encodeURIComponent(productUniqid)}`, { method: 'PUT' });\n}\n\nexport function removeFavorite(productUniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/favorites/${encodeURIComponent(productUniqid)}`, { method: 'DELETE' });\n}\n\nexport function affiliate(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/affiliate');\n}\n\nexport function createTicket(payload: CustomerTicketPayload): Promise<SDKResponse<unknown>> {\n return requestCustomer('/tickets', {\n method: 'POST',\n body: {\n ...(payload.title !== undefined ? { title: payload.title } : {}),\n message: payload.message,\n ...(payload.invoice_id !== undefined ? { invoice_id: payload.invoice_id } : {}),\n },\n });\n}\n\nexport function ticket(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/tickets/${encodeURIComponent(uniqid)}`);\n}\n\nexport function replyToTicket(uniqid: string, message: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/tickets/${encodeURIComponent(uniqid)}/reply`, {\n method: 'POST',\n body: { message },\n });\n}\n\n/**\n * The producer is `POST /v1/customer/profile`, not PATCH.\n *\n * There is no `GET /profile` to pair with it — the buyer's own record comes from\n * `/me` and `/dashboard`.\n */\nexport function updateProfile(patch: CustomerProfilePatch): Promise<SDKResponse<unknown>> {\n return requestCustomer('/profile', {\n method: 'POST',\n body: { name: patch.name },\n });\n}\n\nexport function updateAvatar(file: File): Promise<SDKResponse<unknown>> {\n const form = new FormData();\n form.append('file', file);\n return requestCustomer('/profile/avatar', { method: 'POST', formData: form });\n}\n\nexport function removeAvatar(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/profile/avatar', { method: 'DELETE' });\n}\n\nexport function emailPreferences(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/email-marketing/preferences');\n}\n\nexport function updateEmailPreferences(\n patch: CustomerEmailPreferencesPatch,\n): Promise<SDKResponse<unknown>> {\n return requestCustomer('/email-marketing/preferences', {\n method: 'PATCH',\n body: {\n ...(patch.global_unsubscribed !== undefined\n ? { global_unsubscribed: patch.global_unsubscribed }\n : {}),\n ...(patch.list_subscriptions !== undefined\n ? { list_subscriptions: patch.list_subscriptions }\n : {}),\n },\n });\n}\n\nexport function sessions(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/sessions');\n}\n\nexport function revokeSession(id: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/sessions/${encodeURIComponent(id)}`, { method: 'DELETE' });\n}\n\n/**\n * Ends every session except this one.\n *\n * `others=true` is required, not decorative: `RevokeOtherSessionsQuerySchema`\n * declares it as a literal, so the route answers 400 without it. The selector\n * is explicit on purpose — \"revoke sessions\" with no qualifier is one typo away\n * from signing the buyer out of the device they are holding.\n */\nexport function revokeAllSessions(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/sessions?others=true', { method: 'DELETE' });\n}\n\n// ---------------------------------------------------------------------------\n// Store credit\n//\n// `topup` creates an UNPAID invoice and answers with its hosted-checkout URL.\n// Nothing is credited here: the balance moves when that invoice completes. The\n// shop's enablement toggles, the amount bounds and the check that the credited\n// result still fits under the shop's maximum balance all live in\n// `WalletTopupService`, which is why a storefront may ask for this at all.\n// ---------------------------------------------------------------------------\n\n/** Whether the shop takes top-ups, between which amounts, and its bonus teaser. */\nexport function walletTopupQuote(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/wallet/topup-quote');\n}\n\n/**\n * Starts a top-up. `amount` is a decimal string with at most two places — the\n * producer's schema rejects anything else rather than rounding it.\n */\nexport function walletTopup(amount: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/wallet/topup', { method: 'POST', body: { amount } });\n}\n\n// ---------------------------------------------------------------------------\n// Wholesale (reseller program)\n//\n// A second program on the same account: its own way in, its own prepaid\n// balance, its own prices. Every route re-checks \"program enabled AND this\n// reseller is ACTIVE\" server-side, so nothing a storefront caches can widen\n// what a buyer may do here.\n//\n// Two writes are deliberately absent, and adding them back would be adding\n// methods that answer 404: the storefront worker refuses them. On a code\n// storefront the JavaScript on this origin is the MERCHANT's and it holds the\n// buyer's cookie, so the edge's same-origin check proves that script sent the\n// request, never that the buyer wanted it.\n// - placing a wholesale order debits the buyer's prepaid balance; a purchase\n// needs a boundary the merchant does not control\n// - minting an API key hands back a plaintext credential that keeps\n// authorizing orders after the session ends\n// Pricing a basket stays, because it writes nothing.\n// ---------------------------------------------------------------------------\n\n/** The program's state and this buyer's place in it. Null reseller means not enrolled. */\nexport function reseller(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller');\n}\n\n/** `APPLICATION` mode. The note is optional unless the shop requires one. */\nexport function applyForReseller(note?: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/apply', {\n method: 'POST',\n body: note === undefined ? {} : { note },\n });\n}\n\n/** `OPEN` mode: no application, the buyer is a reseller when they say so. */\nexport function enrollAsReseller(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/enroll', { method: 'POST', body: {} });\n}\n\n/** `MANUAL` mode: the merchant invited this buyer and gave them a token. */\nexport function acceptResellerInvite(token: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/accept-invite', { method: 'POST', body: { token } });\n}\n\n/** The buyer's own tier prices. Page-based, like the order history. */\nexport function resellerCatalog(options: ResellerCatalogQuery = {}): Promise<SDKResponse<unknown>> {\n const query = new URLSearchParams();\n if (options.search !== undefined) query.set('search', options.search);\n if (options.page !== undefined) query.set('page', String(options.page));\n if (options.per_page !== undefined) query.set('per_page', String(options.per_page));\n\n const suffix = query.size > 0 ? `?${query.toString()}` : '';\n return requestCustomer(`/reseller/catalog${suffix}`);\n}\n\n/**\n * Prices a basket and writes nothing.\n *\n * The volume discount cannot be derived from the catalog — it only reports that\n * one exists — so a storefront that adds up unit prices itself shows a total\n * the shop will not charge. This is the number to display.\n */\nexport function quoteResellerOrder(items: ResellerOrderItem[]): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/orders/quote', { method: 'POST', body: { items } });\n}\n\nexport function resellerOrders(options: ResellerOrdersQuery = {}): Promise<SDKResponse<unknown>> {\n const query = new URLSearchParams();\n if (options.page !== undefined) query.set('page', String(options.page));\n if (options.per_page !== undefined) query.set('per_page', String(options.per_page));\n\n const suffix = query.size > 0 ? `?${query.toString()}` : '';\n return requestCustomer(`/reseller/orders${suffix}`);\n}\n\n/** One order with its lines, delivery state and delivered serials. */\nexport function resellerOrder(uniqid: string): Promise<SDKResponse<unknown>> {\n return requestCustomer(`/reseller/orders/${encodeURIComponent(uniqid)}`);\n}\n\n/** The prepaid balance the wholesale orders are paid from. */\nexport function resellerWallet(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/wallet');\n}\n\n/**\n * Top-up bounds in the WHOLESALE context.\n *\n * Not interchangeable with `walletTopupQuote`: the retail one advertises bonus\n * tiers the rewards pipeline never grants on wholesale float, and its `enabled`\n * flag mirrors the retail wallet toggles while the wholesale gate is the\n * reseller program itself.\n */\nexport function resellerTopupQuote(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/wallet/topup-quote');\n}\n\n/** Creates an UNPAID invoice for wholesale float and answers with its URL. */\nexport function resellerTopup(amount: string): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/wallet/topup', { method: 'POST', body: { amount } });\n}\n\nexport function resellerApiKeys(): Promise<SDKResponse<unknown>> {\n return requestCustomer('/reseller/api-keys');\n}\n\n/*\n * There is no `revokeResellerApiKey`. Revoking is irreversible and stops\n * whatever the key was driving, and this SDK is the transport for code\n * storefronts — merchant-authored JavaScript running with the buyer's session,\n * where a confirmation proves nothing because the merchant renders it. The\n * edge omits the DELETE from `CUSTOMER_API_ALLOWLIST`\n * (`workers/storefront/src/customer-api.ts`), so exporting a method for it\n * would advertise a call that always answers 404.\n */\n","import { getStorefront } from './store.js';\nimport { isInitialized } from '../core/config.js';\nimport {\n searchMergedStorefrontCatalog,\n searchMergedStorefrontCatalogItems,\n type StorefrontCatalogSearchItem,\n} from '../utils/storefront-search.js';\nimport type { SDKResponse, Product } from '../types/index.js';\n\nexport interface SearchOptions {\n hideOutOfStock?: boolean;\n maxResults?: number;\n}\n\nexport type { StorefrontCatalogSearchItem };\n\nexport async function searchCatalogItems(\n query: string,\n options?: SearchOptions,\n): Promise<SDKResponse<StorefrontCatalogSearchItem[]>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n\n const trimmed = query.trim();\n if (!trimmed) {\n return { success: true, data: [] };\n }\n\n const storefront = await getStorefront();\n if (!storefront.success || !storefront.data) {\n return {\n success: false,\n message: storefront.message ?? 'Failed to fetch storefront catalog',\n };\n }\n\n const results = searchMergedStorefrontCatalogItems(\n storefront.data.products ?? [],\n storefront.data.groups ?? [],\n trimmed,\n {\n hideOutOfStock: options?.hideOutOfStock,\n maxResults: options?.maxResults,\n },\n );\n\n return { success: true, data: results };\n}\n\nexport async function searchProducts(\n query: string,\n options?: SearchOptions,\n): Promise<SDKResponse<Product[]>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n\n const trimmed = query.trim();\n if (!trimmed) {\n return { success: true, data: [] };\n }\n\n const storefront = await getStorefront();\n if (!storefront.success || !storefront.data) {\n return {\n success: false,\n message: storefront.message ?? 'Failed to fetch storefront catalog',\n };\n }\n\n const results = searchMergedStorefrontCatalog(\n storefront.data.products ?? [],\n storefront.data.groups ?? [],\n trimmed,\n {\n hideOutOfStock: options?.hideOutOfStock,\n maxResults: options?.maxResults,\n },\n );\n\n return { success: true, data: results };\n}\n","/**\n * Invoices Module\n *\n * Invoice status checking after payment.\n */\n\nimport { get } from '../core/client';\nimport { buildEndpoint } from '../core/endpoint';\nimport type { SDKResponse, Invoice } from '../types';\n\nfunction normalizeInvoiceId(invoiceId: string): string | null {\n const normalized = invoiceId.trim();\n if (!normalized) {\n return null;\n }\n return normalized;\n}\n\nexport async function getInvoice(\n invoiceId: string\n): Promise<SDKResponse<Invoice>> {\n const normalizedInvoiceId = normalizeInvoiceId(invoiceId);\n if (!normalizedInvoiceId) {\n return {\n success: false,\n message: 'Invoice ID is required',\n };\n }\n\n const response = await get<{ invoice: Invoice }>(\n buildEndpoint('/v1/storefront/invoices/unique/:invoiceId', {\n invoiceId: normalizedInvoiceId,\n })\n );\n if (!response.success) {\n return {\n success: false,\n message: response.message,\n };\n }\n\n if (!response.data?.invoice) {\n return {\n success: false,\n message: 'Invalid invoice response',\n };\n }\n\n return {\n success: true,\n data: response.data.invoice,\n };\n}\n\nexport async function getInvoiceStatus(\n invoiceId: string\n): Promise<SDKResponse<{ status: string }>> {\n const normalizedInvoiceId = normalizeInvoiceId(invoiceId);\n if (!normalizedInvoiceId) {\n return {\n success: false,\n message: 'Invoice ID is required',\n };\n }\n\n const response = await get<{ invoice: { status: string } }>(\n buildEndpoint('/v1/storefront/invoices/status/:invoiceId', {\n invoiceId: normalizedInvoiceId,\n })\n );\n if (!response.success) {\n return {\n success: false,\n message: response.message,\n };\n }\n\n if (!response.data?.invoice?.status) {\n return {\n success: false,\n message: 'Invalid invoice status response',\n };\n }\n\n return {\n success: true,\n data: { status: response.data.invoice.status },\n };\n}\n","/**\n * Pages Module\n *\n * API methods for public pages.\n */\n\nimport { get } from '../core/client';\nimport { getConfig } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type { SDKResponse, Page } from '../types';\n\ninterface PagesResponse {\n pages: Page[];\n}\n\ninterface PageResponse {\n page: Page;\n}\n\nconst PAGES_CACHE_TTL = 5 * 60 * 1000;\n\n/**\n * Get all public pages for the store\n */\nexport async function getPages(): Promise<SDKResponse<Page[]>> {\n const config = getConfig();\n const response = await get<PagesResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/pages', {\n storeSlug: config.storeSlug,\n }),\n {\n cache: {\n key: `pages:${config.storeSlug}`,\n ttl: PAGES_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.pages,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\n/**\n * Get a public page by slug\n */\nexport async function getPage(slug: string): Promise<SDKResponse<Page>> {\n const config = getConfig();\n const response = await get<PageResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/pages/:slug', {\n storeSlug: config.storeSlug,\n slug,\n }),\n {\n cache: {\n key: `page:${config.storeSlug}:${slug}`,\n ttl: PAGES_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.page,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n","/**\n * Navigation Module\n *\n * API methods for menus and navigation.\n */\n\nimport { get } from '../core/client';\nimport { getConfig } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport type { SDKResponse, Menu } from '../types';\nimport type { NavigationMenuSlot } from '@shoppex/contracts/navigation';\nimport { getNavigationMenuTitles } from '@shoppex/contracts/navigation';\n\ninterface MenusResponse {\n menus: Menu[];\n}\n\ninterface MenuResponse {\n menu: Menu;\n}\n\nconst NAVIGATION_CACHE_TTL = 5 * 60 * 1000;\n\n/**\n * Get all menus for the store\n */\nexport async function getMenus(): Promise<SDKResponse<Menu[]>> {\n const config = getConfig();\n const response = await get<MenusResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/menus', {\n storeSlug: config.storeSlug,\n }),\n {\n cache: {\n key: `menus:${config.storeSlug}`,\n ttl: NAVIGATION_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.menus,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\n/**\n * Get a menu by its exact title.\n */\nexport async function getMenuByTitle(title: string): Promise<SDKResponse<Menu>> {\n const config = getConfig();\n const response = await get<MenuResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/menus/:title', {\n storeSlug: config.storeSlug,\n title,\n }),\n {\n cache: {\n key: `menu:${config.storeSlug}:${title}`,\n ttl: NAVIGATION_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.menu,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\n/**\n * Get a menu by its exact title.\n */\nexport async function getMenu(title: string): Promise<SDKResponse<Menu>> {\n return getMenuByTitle(title);\n}\n\n/**\n * Get a menu by canonical slot. The backend resolves legacy menu titles too.\n */\nexport async function getMenuBySlot(slot: NavigationMenuSlot): Promise<SDKResponse<Menu>> {\n const config = getConfig();\n const response = await get<MenuResponse>(\n buildEndpoint('/v1/storefront/shops/name/:storeSlug/menus/:title', {\n storeSlug: config.storeSlug,\n title: slot,\n }),\n {\n cache: {\n key: `menu-slot:${config.storeSlug}:${slot}`,\n ttl: NAVIGATION_CACHE_TTL,\n staleWhileRevalidate: true,\n },\n }\n );\n\n if (response.success && response.data) {\n return {\n success: true,\n data: response.data.menu,\n };\n }\n\n return {\n success: false,\n message: response.message,\n };\n}\n\nexport function getMenuSlotTitles(slot: NavigationMenuSlot): string[] {\n return getNavigationMenuTitles(slot);\n}\n","/**\n * UTM attribution for storefront page views.\n *\n * Campaign parameters only appear on the landing URL, but a visitor usually\n * browses several pages before doing anything interesting. Without persistence\n * every page after the first would be attributed to \"direct\" and the numbers\n * would understate every campaign.\n *\n * Last-touch: a fresh set of parameters replaces the stored one, matching what\n * merchants expect from analytics tools — the most recent campaign gets credit.\n * Navigating without parameters keeps whatever was stored.\n */\n\nconst STORAGE_PREFIX = 'shoppex:utm:';\nconst TTL_MS = 30 * 24 * 60 * 60 * 1000;\n\nconst UTM_KEYS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'] as const;\n\ntype UtmKey = (typeof UTM_KEYS)[number];\n\nexport type UtmParameters = Partial<Record<UtmKey, string>>;\n\ninterface StoredAttribution {\n utm: UtmParameters;\n /** Epoch ms of the last touch, used for TTL expiry. */\n at: number;\n}\n\n/** Values are merchant-supplied and land in a text column; keep them bounded. */\nconst MAX_VALUE_LENGTH = 255;\n\nfunction readFromUrl(search: string): UtmParameters {\n let params: URLSearchParams;\n try {\n params = new URLSearchParams(search);\n } catch {\n return {};\n }\n\n const utm: UtmParameters = {};\n for (const key of UTM_KEYS) {\n const value = params.get(key)?.trim();\n if (value) {\n utm[key] = value.slice(0, MAX_VALUE_LENGTH);\n }\n }\n return utm;\n}\n\nfunction storageKey(storeSlug: string): string {\n return `${STORAGE_PREFIX}${storeSlug}`;\n}\n\nfunction readStored(storeSlug: string): UtmParameters {\n try {\n const raw = window.localStorage.getItem(storageKey(storeSlug));\n if (!raw) return {};\n\n const parsed = JSON.parse(raw) as StoredAttribution;\n if (!parsed || typeof parsed.at !== 'number' || typeof parsed.utm !== 'object') return {};\n if (Date.now() - parsed.at > TTL_MS) {\n window.localStorage.removeItem(storageKey(storeSlug));\n return {};\n }\n\n const utm: UtmParameters = {};\n for (const key of UTM_KEYS) {\n const value = parsed.utm?.[key];\n if (typeof value === 'string' && value.length > 0) {\n utm[key] = value.slice(0, MAX_VALUE_LENGTH);\n }\n }\n return utm;\n } catch {\n // Private mode, quota errors, corrupt JSON — attribution is best-effort and\n // must never break a page view.\n return {};\n }\n}\n\nfunction writeStored(storeSlug: string, utm: UtmParameters): void {\n try {\n const payload: StoredAttribution = { utm, at: Date.now() };\n window.localStorage.setItem(storageKey(storeSlug), JSON.stringify(payload));\n } catch {\n // Ignore: the current page view still reports the parameters it just read.\n }\n}\n\n/**\n * Resolves the UTM parameters to report for the current page view.\n *\n * Reads the current URL first; when it carries any campaign parameter that set\n * wins and is persisted. Otherwise the stored set is returned unchanged.\n *\n * @returns the parameters, or undefined when there is nothing to report\n */\nexport function resolveUtmParameters(storeSlug: string): UtmParameters | undefined {\n if (typeof window === 'undefined' || typeof window.location === 'undefined') {\n return undefined;\n }\n\n const fromUrl = readFromUrl(window.location.search);\n if (Object.keys(fromUrl).length > 0) {\n writeStored(storeSlug, fromUrl);\n return fromUrl;\n }\n\n const stored = readStored(storeSlug);\n return Object.keys(stored).length > 0 ? stored : undefined;\n}\n","import { isInitialized, getConfig } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport { getStorefrontConnectionId } from '../core/telemetry';\nimport { resolveUtmParameters } from '../core/attribution';\n\nexport async function trackPageView(cartValue?: number, itemCount?: number): Promise<void> {\n if (!isInitialized()) return;\n if (typeof document === 'undefined') return;\n\n const config = getConfig();\n const connectionId = getStorefrontConnectionId(config.storeSlug);\n\n try {\n const endpoint = buildEndpoint('/v1/storefront/shops/:storeSlug/ping', {\n storeSlug: config.storeSlug,\n });\n await fetch(`${config.apiBaseUrl}${endpoint}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n referer: document.referrer || undefined,\n cart_value: cartValue ?? undefined,\n item_count: itemCount ?? undefined,\n connection_id: connectionId ?? undefined,\n utm: resolveUtmParameters(config.storeSlug),\n }),\n });\n } catch {\n // Intentionally silent - analytics should never block the user experience\n }\n}\n","import { get, post } from '../core/client';\nimport { getConfig, getShopId, isInitialized } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport { getStorefrontConnectionId } from '../core/telemetry';\nimport { resolveUtmParameters } from '../core/attribution';\nimport type { SDKResponse, StorefrontOnlineUsers, StorefrontRecentSales } from '../types';\n\n/**\n * Anonymized recent-sales feed for storefront social proof (product title +\n * relative age only — never buyer identity). Empty items when the shop has no\n * recent completed orders.\n */\nexport async function getStorefrontRecentSales(): Promise<SDKResponse<StorefrontRecentSales>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n\n const config = getConfig();\n const shopId = getShopId();\n const endpoint = shopId\n ? buildEndpoint('/v1/storefront/shops/id/:id/recent-sales', { id: shopId })\n : buildEndpoint('/v1/storefront/shops/:storeSlug/recent-sales', {\n storeSlug: config.storeSlug,\n });\n\n return get<StorefrontRecentSales>(endpoint, {\n cache: false,\n retries: 0,\n timeout: 5000,\n });\n}\n\nexport async function getStorefrontOnlineUsers(): Promise<SDKResponse<StorefrontOnlineUsers>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n\n const config = getConfig();\n const shopId = getShopId();\n const endpoint = shopId\n ? buildEndpoint('/v1/storefront/shops/id/:id/online-users', { id: shopId })\n : buildEndpoint('/v1/storefront/shops/:storeSlug/online-users', {\n storeSlug: config.storeSlug,\n });\n\n return get<StorefrontOnlineUsers>(endpoint, {\n cache: false,\n retries: 0,\n timeout: 5000,\n });\n}\n\nexport async function touchStorefrontPresence(): Promise<SDKResponse<{ pong: string }>> {\n if (!isInitialized()) {\n return { success: false, message: 'SDK not initialized' };\n }\n if (typeof document === 'undefined') {\n return { success: false, message: 'Document is not available' };\n }\n\n const config = getConfig();\n const shopId = getShopId();\n const endpoint = shopId\n ? buildEndpoint('/v1/storefront/shops/id/:id/ping', { id: shopId })\n : buildEndpoint('/v1/storefront/shops/:storeSlug/ping', {\n storeSlug: config.storeSlug,\n });\n\n return post<{ pong: string }>(\n endpoint,\n {\n referer: document.referrer || undefined,\n connection_id: getStorefrontConnectionId(config.storeSlug) ?? undefined,\n utm: resolveUtmParameters(config.storeSlug),\n },\n {\n retries: 0,\n timeout: 5000,\n },\n );\n}\n","/**\n * Formatting Utilities\n */\n\nimport { getConfig } from '../core/config';\nimport { CATALOG_UNIT_PRICE_FORMAT_OPTIONS } from '@shoppex/contracts/catalog-unit-price';\n\nexport function createFormatter(\n currency?: string,\n locale?: string\n): Intl.NumberFormat {\n const config = getConfig();\n\n return new Intl.NumberFormat(locale ?? config.locale ?? 'en-US', {\n style: 'currency',\n currency: currency ?? config.currency ?? 'USD',\n ...CATALOG_UNIT_PRICE_FORMAT_OPTIONS,\n });\n}\n\nexport function formatPrice(\n amount: number | string,\n currency?: string,\n locale?: string\n): string {\n const numericAmount = typeof amount === 'string' ? parseFloat(amount) : amount;\n if (Number.isNaN(numericAmount)) {\n return createFormatter(currency, locale).format(0);\n }\n return createFormatter(currency, locale).format(numericAmount);\n}\n","import type { ThemeConfig, ResolvedThemeSettings } from '../types/theme-config';\nimport { get } from '../core/client';\nimport { buildEndpoint } from '../core/endpoint';\n\ntype JsonRecord = Record<string, unknown>;\n\nexport interface PublishedBuilderSettings {\n version: number;\n revision: number;\n theme: {\n content: JsonRecord;\n layout: JsonRecord;\n style_slots: JsonRecord;\n pages?: unknown[];\n terms?: JsonRecord;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\nexport interface PublishedThemeSettingsPayload {\n settings: ResolvedThemeSettings;\n builder_settings: PublishedBuilderSettings | null;\n content: JsonRecord;\n style_slots: JsonRecord;\n}\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction normalizePublishedBuilderSettings(value: unknown): PublishedBuilderSettings | null {\n if (!isRecord(value) || !isRecord(value.theme)) {\n return null;\n }\n\n return {\n ...value,\n version: typeof value.version === 'number' ? value.version : 0,\n revision: typeof value.revision === 'number' ? value.revision : 0,\n theme: {\n ...value.theme,\n content: isRecord(value.theme.content) ? value.theme.content : {},\n layout: isRecord(value.theme.layout) ? value.theme.layout : {},\n style_slots: isRecord(value.theme.style_slots) ? value.theme.style_slots : {},\n ...(Array.isArray(value.theme.pages) ? { pages: value.theme.pages } : {}),\n ...(isRecord(value.theme.terms) ? { terms: value.theme.terms } : {}),\n },\n };\n}\n\nfunction normalizePublishedThemeSettingsPayload(value: unknown): PublishedThemeSettingsPayload | null {\n if (!isRecord(value)) {\n return null;\n }\n\n return {\n settings: isRecord(value.settings) ? value.settings as ResolvedThemeSettings : {},\n builder_settings: normalizePublishedBuilderSettings(value.builder_settings),\n content: isRecord(value.content) ? value.content : {},\n style_slots: isRecord(value.style_slots) ? value.style_slots : {},\n };\n}\n\nexport async function fetchPublishedBuilderSettings(\n shopSlug: string\n): Promise<PublishedThemeSettingsPayload | null> {\n const result = await get<PublishedThemeSettingsPayload>(\n buildEndpoint('/v1/storefront/themes/builder/published/:shopSlug', { shopSlug })\n );\n\n return result.success && result.data ? normalizePublishedThemeSettingsPayload(result.data) : null;\n}\n\nexport async function fetchPublishedThemeSettings(\n shopSlug: string\n): Promise<ResolvedThemeSettings | null> {\n const payload = await fetchPublishedBuilderSettings(shopSlug);\n return payload ? payload.settings : null;\n}\n\nexport function resolveDefaults(config: ThemeConfig): ResolvedThemeSettings {\n const resolved: ResolvedThemeSettings = {};\n for (const [category, fields] of Object.entries(config.settings)) {\n resolved[category] = {};\n for (const [key, field] of Object.entries(fields)) {\n resolved[category][key] = field.default;\n }\n }\n return resolved;\n}\n\nexport function mergeSettings(\n defaults: ResolvedThemeSettings,\n overrides: Partial<ResolvedThemeSettings>\n): ResolvedThemeSettings {\n const merged = { ...defaults };\n for (const [category, fields] of Object.entries(overrides)) {\n if (fields) {\n merged[category] = { ...merged[category], ...fields };\n }\n }\n return merged;\n}\n","/**\n * Shoppex Storefront SDK\n *\n * Usage:\n * ```html\n * <script src=\"https://cdn.shoppex.io/sdk/v1.0/shoppex.umd.js\"></script>\n * <script>\n * shoppex.init('my-store');\n *\n * shoppex.getStore().then(store => console.log(store));\n * shoppex.addToCart('product-id', 'variant-id', 2);\n * shoppex.checkout();\n * </script>\n * ```\n */\n\nimport { initConfig, isInitialized, getConfig } from './core/config';\nimport { getTypedClient } from './core/typed-client';\nimport type { ShoppexInitOptions } from './types';\n\n// Re-export types\nexport * from './types';\nexport * from './core/errors';\nexport {\n buildStorefrontCustomFieldPayload,\n isStorefrontCheckboxCustomFieldValueChecked,\n normalizeStorefrontCustomFields,\n validateStorefrontCustomFieldValue,\n} from './utils/storefront-custom-fields';\nexport type { StorefrontCustomField } from './utils/storefront-custom-fields';\nexport {\n isProductInStock,\n isProductOutOfStock,\n isVariantOutOfStock,\n resolveDisplayStock,\n resolveVariantStockValue,\n} from './utils/storefront-stock';\nexport {\n buildStorefrontProductLookup,\n getMergedStorefrontProducts,\n getStorefrontGroupProducts,\n} from './utils/storefront-catalog';\nexport {\n stripHtmlFromText,\n normalizeSearchQuery,\n collectProductSearchHaystack,\n productMatchesSearchQuery,\n groupMatchesSearchQuery,\n filterProductsBySearchQuery,\n searchMergedStorefrontCatalog,\n searchMergedStorefrontCatalogItems,\n} from './utils/storefront-search';\nexport type { StorefrontSearchFilterOptions, StorefrontCatalogSearchItem } from './utils/storefront-search';\nexport {\n buildStorefrontContactMessage,\n resolveStorefrontApiBaseUrl,\n resolveStorefrontSocialLinks,\n submitStorefrontContactTicket,\n} from './utils/storefront-contact';\nexport type {\n StorefrontContactTicketInput,\n StorefrontContactTicketResult,\n StorefrontSocialLinks,\n} from './utils/storefront-contact';\nexport type {\n BlockDefinition,\n BlockInstance,\n PageLayout,\n ThemeConfig,\n ThemeBlockManifest,\n SettingField,\n SectionDefinition,\n ResolvedThemeSettings,\n} from './types/theme-config';\nexport type { PublishedBuilderSettings, PublishedThemeSettingsPayload } from './modules/theme';\nexport type { NavigationMenuSlot } from '@shoppex/contracts/navigation';\nexport {\n CATALOG_UNIT_PRICE_DECIMAL_PLACES,\n CATALOG_UNIT_PRICE_FORMAT_OPTIONS,\n PAYABLE_AMOUNT_DECIMAL_PLACES,\n roundPayableAmount,\n} from '@shoppex/contracts/catalog-unit-price';\n\n// Store module\nimport {\n getStore,\n getStorefront,\n getStoreLogoUrl,\n getStoreBannerUrl,\n resolveStoreByDomain,\n} from './modules/store';\n\n// Products module\nimport { getProducts, getProduct, getCategories, getStorefrontProductsPage } from './modules/products';\n\n// Cart module\nimport {\n getCart,\n getCartItemCount,\n getCartCoupon,\n getCartCouponSource,\n setCartCoupon,\n clearCartCoupon,\n addToCart,\n setCartItem,\n updateCartItem,\n removeFromCart,\n clearCart,\n createCartBackup,\n restoreCartFromBackup,\n mergeBaskets,\n moveBasketItem,\n getCartStats,\n validateCartIntegrity,\n quoteCart,\n resolveCartLineId,\n} from './modules/cart';\n// resolveCartLineId is re-exported on the default shoppex object below (not only type-only).\nexport { computeCartLineId, ensureCartLineId } from './utils/cart-line-id';\nexport type { CartLineIdentityInput } from './utils/cart-line-id';\n\n// Checkout module\nimport { checkout, buildCheckoutUrl, buildCheckoutUrlSync } from './modules/checkout';\nexport type { CheckoutOptions, CheckoutResult } from './modules/checkout';\nexport type { SearchOptions } from './modules/search';\n\n// Affiliate module\nimport {\n applyAffiliateCode,\n captureAffiliateFromUrl,\n getAffiliateCode,\n setAffiliateCode,\n clearAffiliateCode,\n validateAffiliateCode,\n} from './modules/affiliates';\n\n// Coupons module\nimport { validateCoupon } from './modules/coupons';\n\n// Reviews module\nimport { getShopReviews, getShopReviewsPage } from './modules/reviews';\nexport { getShopReviewsPage } from './modules/reviews';\n\n// Customer module\nimport {\n requestOtp,\n verifyOtp,\n logout,\n me,\n dashboard,\n orders,\n order,\n resetLicenseHwid,\n subscriptionBillingHistory,\n cancelSubscription,\n pauseSubscription,\n resumeSubscription,\n favorites,\n addFavorite,\n removeFavorite,\n affiliate,\n createTicket,\n ticket,\n replyToTicket,\n updateProfile,\n updateAvatar,\n removeAvatar,\n emailPreferences,\n updateEmailPreferences,\n sessions,\n revokeSession,\n revokeAllSessions,\n walletTopupQuote,\n walletTopup,\n reseller,\n applyForReseller,\n enrollAsReseller,\n acceptResellerInvite,\n resellerCatalog,\n quoteResellerOrder,\n resellerOrders,\n resellerOrder,\n resellerWallet,\n resellerTopupQuote,\n resellerTopup,\n resellerApiKeys,\n} from './modules/customer';\nexport {\n requestOtp,\n verifyOtp,\n logout,\n me,\n dashboard,\n orders,\n order,\n resetLicenseHwid,\n subscriptionBillingHistory,\n cancelSubscription,\n pauseSubscription,\n resumeSubscription,\n favorites,\n addFavorite,\n removeFavorite,\n affiliate,\n createTicket,\n ticket,\n replyToTicket,\n updateProfile,\n updateAvatar,\n removeAvatar,\n emailPreferences,\n updateEmailPreferences,\n sessions,\n revokeSession,\n revokeAllSessions,\n walletTopupQuote,\n walletTopup,\n reseller,\n applyForReseller,\n enrollAsReseller,\n acceptResellerInvite,\n resellerCatalog,\n quoteResellerOrder,\n resellerOrders,\n resellerOrder,\n resellerWallet,\n resellerTopupQuote,\n resellerTopup,\n resellerApiKeys,\n} from './modules/customer';\nexport type {\n CustomerTicketPayload,\n CustomerProfilePatch,\n CustomerSubscriptionCancelOptions,\n CustomerEmailPreferencesPatch,\n ResellerOrderItem,\n ResellerCatalogQuery,\n ResellerOrdersQuery,\n} from './modules/customer';\n\n// Search module\nimport { searchProducts, searchCatalogItems } from './modules/search';\n\n// Invoices module\nimport { getInvoice, getInvoiceStatus } from './modules/invoices';\n\n// Pages module\nimport { getPages, getPage } from './modules/pages';\n\n// Navigation module\nimport { getMenus, getMenu, getMenuBySlot, getMenuByTitle, getMenuSlotTitles } from './modules/navigation';\n\n// Analytics module\nimport { trackPageView } from './modules/analytics';\nimport { getStorefrontOnlineUsers, getStorefrontRecentSales, touchStorefrontPresence } from './modules/presence';\n\n// Format utilities\nimport { createFormatter, formatPrice } from './utils/format';\nimport { clearCache, invalidateCache, getCacheStats } from './core/cache';\nimport { fetchPublishedBuilderSettings, fetchPublishedThemeSettings, resolveDefaults, mergeSettings } from './modules/theme';\n\nexport { fetchPublishedBuilderSettings, fetchPublishedThemeSettings, resolveDefaults, mergeSettings } from './modules/theme';\nexport { trackPageView } from './modules/analytics';\nexport { getStorefrontOnlineUsers, getStorefrontRecentSales, touchStorefrontPresence } from './modules/presence';\nexport { getMenus, getMenu, getMenuBySlot, getMenuByTitle, getMenuSlotTitles } from './modules/navigation';\n\n/**\n * Initialize the SDK with a store slug\n */\nfunction init(storeSlug: string, options?: ShoppexInitOptions): void;\nfunction init(options: ShoppexInitOptions & { storeId: string }): void;\nfunction init(\n storeSlugOrOptions: string | (ShoppexInitOptions & { storeId: string }),\n options?: ShoppexInitOptions\n): void {\n if (typeof storeSlugOrOptions === 'string') {\n initConfig(storeSlugOrOptions, options);\n } else {\n initConfig(storeSlugOrOptions.storeId, storeSlugOrOptions);\n }\n}\n\n/**\n * Shoppex SDK instance\n */\nexport const shoppex = {\n // Initialization\n init,\n isInitialized,\n getConfig,\n\n // Typed OpenAPI client — drop to this when you need an endpoint the\n // high-level modules below do not cover yet.\n client: getTypedClient,\n\n // Store\n getStore,\n getStorefront,\n getStoreLogoUrl,\n getStoreBannerUrl,\n resolveStoreByDomain,\n\n // Products\n getProducts,\n getStorefrontProductsPage,\n getProduct,\n getCategories,\n\n // Cart\n getCart,\n getCartItemCount,\n getCartCoupon,\n getCartCouponSource,\n setCartCoupon,\n clearCartCoupon,\n addToCart,\n setCartItem,\n updateCartItem,\n removeFromCart,\n clearCart,\n createCartBackup,\n restoreCartFromBackup,\n mergeBaskets,\n moveBasketItem,\n getCartStats,\n validateCartIntegrity,\n quoteCart,\n resolveCartLineId,\n\n // Checkout\n checkout,\n buildCheckoutUrl,\n buildCheckoutUrlSync,\n\n // Affiliates\n captureAffiliateFromUrl,\n validateAffiliateCode,\n applyAffiliateCode,\n getAffiliateCode,\n setAffiliateCode,\n clearAffiliateCode,\n\n // Coupons\n validateCoupon,\n\n // Reviews\n getShopReviews,\n getShopReviewsPage,\n\n // Customer account\n requestOtp,\n verifyOtp,\n logout,\n me,\n dashboard,\n orders,\n order,\n resetLicenseHwid,\n subscriptionBillingHistory,\n cancelSubscription,\n pauseSubscription,\n resumeSubscription,\n favorites,\n addFavorite,\n removeFavorite,\n affiliate,\n createTicket,\n ticket,\n replyToTicket,\n updateProfile,\n updateAvatar,\n removeAvatar,\n emailPreferences,\n updateEmailPreferences,\n sessions,\n revokeSession,\n revokeAllSessions,\n walletTopupQuote,\n walletTopup,\n reseller,\n applyForReseller,\n enrollAsReseller,\n acceptResellerInvite,\n resellerCatalog,\n quoteResellerOrder,\n resellerOrders,\n resellerOrder,\n resellerWallet,\n resellerTopupQuote,\n resellerTopup,\n resellerApiKeys,\n\n // Search\n searchProducts,\n searchCatalogItems,\n\n // Invoices\n getInvoice,\n getInvoiceStatus,\n\n // Pages\n getPages,\n getPage,\n\n // Navigation\n getMenus,\n getMenu,\n getMenuBySlot,\n getMenuByTitle,\n getMenuSlotTitles,\n\n // Analytics\n trackPageView,\n getStorefrontOnlineUsers,\n getStorefrontRecentSales,\n touchStorefrontPresence,\n\n // Formatting\n createFormatter,\n formatPrice,\n\n // Cache\n clearCache,\n invalidateCache,\n getCacheStats,\n\n // Theme settings helpers\n fetchPublishedBuilderSettings,\n fetchPublishedThemeSettings,\n resolveDefaults,\n mergeSettings,\n};\n\n// Default export for ES modules\nexport default shoppex;\n\n// UMD global exposure — never clobber an already-initialized client. Theme\n// artifacts can load multiple SDK chunks; a late bundle must not reset init.\nif (typeof window !== 'undefined') {\n const w = window as unknown as { shoppex?: typeof shoppex };\n if (!w.shoppex?.isInitialized?.()) {\n w.shoppex = shoppex;\n }\n}\n"],"x_google_ignoreList":[2,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21],"mappings":"0TAuBA,IA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