@shoppexio/storefront 0.3.9 → 0.3.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/__tests__/storefront-contact.test.d.ts +2 -0
- package/dist/__tests__/storefront-contact.test.d.ts.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/shoppex.esm.js +2 -2
- package/dist/shoppex.esm.js.map +1 -1
- package/dist/shoppex.umd.js +1 -1
- package/dist/shoppex.umd.js.map +1 -1
- package/dist/types/api.d.ts +2 -0
- package/dist/types/api.d.ts.map +1 -1
- package/dist/utils/storefront-contact.d.ts +32 -0
- package/dist/utils/storefront-contact.d.ts.map +1 -0
- package/package.json +2 -2
package/dist/shoppex.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shoppex.esm.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/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/index.ts","../src/core/typed-client.ts","../src/core/config.ts","../src/utils/storefront-custom-fields.ts","../src/utils/storefront-stock.ts","../src/core/cache.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/cart.ts","../src/modules/affiliates.ts","../src/modules/checkout.ts","../src/modules/coupons.ts","../src/modules/reviews.ts","../src/modules/search.ts","../src/modules/invoices.ts","../src/modules/pages.ts","../src/modules/navigation.ts","../src/modules/analytics.ts","../src/modules/presence.ts","../src/utils/format.ts","../src/modules/theme.ts","../src/index.ts"],"sourcesContent":["/**\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\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 { z } from 'zod';\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 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 'SQUARE',\n 'SUMUP',\n 'SHOPIFY',\n 'SUBY',\n 'PANDABASE',\n 'STORRIK',\n 'VENPAYR',\n 'MONEYMOTION',\n 'WHOP',\n 'DODO',\n 'MAVERICK',\n 'CASHAPP',\n 'VENMO',\n 'CRYPTO',\n 'CUSTOMER_BALANCE',\n 'MANUAL',\n] as const;\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 SQUARE: 'SQUARE',\n SUMUP: 'SUMUP',\n SHOPIFY: 'SHOPIFY',\n SUBY: 'SUBY',\n PANDABASE: 'PANDABASE',\n STORRIK: 'STORRIK',\n VENPAYR: 'VENPAYR',\n MONEYMOTION: 'MONEYMOTION',\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 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}\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\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 (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 '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 'VENPAYR':\n return 'VenPayr';\n case 'MONEYMOTION':\n return 'MoneyMotion';\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 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);\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>;\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.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] 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 — fonts the storefront ships locally so they render\n// without an external request. Order matters: it drives both the dropdown\n// in the 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 }).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\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] 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] 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 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};\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} 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\nexport const StorefrontAddonCreateSchema = z.discriminatedUnion('type', [\n AnnouncementBarDraftSchema,\n CountdownBarDraftSchema,\n PromoInfoCardDraftSchema,\n RecentPurchasePopupDraftSchema,\n CouponPopupModalDraftSchema,\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]);\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\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 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\nexport interface StorefrontAddonBootstrap {\n items: ResolvedStorefrontAddon[];\n}\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 './style-center.js';\nexport * from './style-center/presets.js';\nexport * from './storefront-addons.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 { 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 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 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 = Pick<ProductVariant, 'stock'> | Pick<PriceVariant, 'stock'>;\n\ntype ProductLike = Pick<Product, 'type' | 'stock' | 'price_variants' | 'variants'>;\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 collectVariantStocks(product: ProductLike): Array<number | null> {\n const priceVariantStocks = Array.isArray(product.price_variants)\n ? product.price_variants.map((variant) => normalizeStockValue(variant.stock))\n : [];\n if (priceVariantStocks.length > 0) {\n return priceVariantStocks;\n }\n\n const legacyVariantStocks = Array.isArray(product.variants)\n ? product.variants.map((variant) => normalizeStockValue(variant.stock))\n : [];\n\n return legacyVariantStocks;\n}\n\nexport function resolveDisplayStock(product: ProductLike | null | undefined): number {\n if (!product) {\n return -1;\n }\n\n if (typeof product.type === 'string' && product.type.toUpperCase() === 'SERIALS') {\n return normalizeStockValue(product.stock) ?? -1;\n }\n\n const variantStocks = collectVariantStocks(product);\n if (variantStocks.length > 0) {\n if (variantStocks.some((stock) => stock === null || stock < 0)) {\n return -1;\n }\n\n return variantStocks\n .filter((stock): stock is number => stock !== null)\n .reduce((sum, stock) => sum + Math.max(stock, 0), 0);\n }\n\n return normalizeStockValue(product.stock) ?? -1;\n}\n\nexport function isProductOutOfStock(product: ProductLike | null | undefined): boolean {\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 normalizeStockValue(variant?.stock) === 0;\n}\n\nexport function resolveVariantStockValue(variant: VariantLike | null | undefined): number {\n return normalizeStockValue(variant?.stock) ?? -1;\n}\n","/**\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","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 } from './config';\nimport { NetworkError } 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}\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 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\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 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 const statusCode =\n normalizedError instanceof NetworkError\n ? normalizedError.statusCode\n : undefined;\n\n lastFailure = {\n message: normalizedError.message,\n statusCode,\n isTransport: statusCode === undefined || statusCode === 408,\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 };\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 };\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 ProductVariant,\n PriceVariant,\n CursorPagination,\n} from '../types';\nimport { getStore } from './store';\n\ninterface ProductsResponse {\n products: Product[];\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 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 return {\n success: true,\n data: 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","/**\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 CartPayload,\n CartMetadata,\n CartStats,\n CartQuote,\n} from '../types';\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\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 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 (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 normalized.push(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 const raw = getItem<unknown>(getStorageKey('coupon'));\n if (typeof raw !== 'string') {\n return null;\n }\n return normalizeCouponCode(raw);\n}\n\nexport function setCartCoupon(coupon: string | null | undefined): string | null {\n const normalizedCoupon = normalizeCouponCode(coupon);\n if (!normalizedCoupon) {\n removeItem(getStorageKey('coupon'));\n return null;\n }\n\n setItem(getStorageKey('coupon'), normalizedCoupon);\n return normalizedCoupon;\n}\n\nexport function clearCartCoupon(): void {\n removeItem(getStorageKey('coupon'));\n}\n\nfunction writeCart(cart: CartItem[]): void {\n setItem(getStorageKey('cart'), cart);\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(cart),\n };\n setItem(getStorageKey('meta'), nextMeta);\n\n if (cart.length === 0) {\n clearCartCoupon();\n }\n}\n\nfunction setCartWithMetadata(cart: CartItem[], metadata?: CartMetadata | null): void {\n setItem(getStorageKey('cart'), cart);\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(cart),\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\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 existingIndex = cart.findIndex(\n (item) => item.product_id === productId && item.variant_id === variantId\n );\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 } else {\n cart.push({\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 });\n }\n\n writeCart(cart);\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 existingIndex = cart.findIndex(\n (item) => item.product_id === productId && item.variant_id === variantId\n );\n\n if (existingIndex >= 0) {\n cart[existingIndex].quantity = normalizedQuantity;\n\n if (options?.addons !== undefined) {\n cart[existingIndex].addons = options.addons;\n }\n if (options?.custom_fields !== undefined) {\n cart[existingIndex].custom_fields = options.custom_fields;\n }\n if (options?.price_variant_id !== undefined) {\n cart[existingIndex].price_variant_id = options.price_variant_id;\n }\n if (options?.price_data !== undefined) {\n cart[existingIndex].price_data = options.price_data;\n }\n } else {\n cart.push({\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 });\n }\n\n writeCart(cart);\n}\n\nexport function updateCartItem(\n productId: string,\n variantId: string,\n updates: Partial<Omit<CartItem, 'product_id' | 'variant_id'>>\n): void {\n const cart = getCart();\n\n const index = cart.findIndex(\n (item) => item.product_id === productId && item.variant_id === variantId\n );\n\n if (index < 0) {\n throw new CartError('Item not found in cart');\n }\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\n writeCart(cart);\n}\n\nexport function removeFromCart(productId: string, variantId: string): void {\n const cart = getCart();\n\n const filtered = cart.filter(\n (item) => !(item.product_id === productId && item.variant_id === variantId)\n );\n\n writeCart(filtered);\n}\n\nexport function clearCart(): void {\n removeItem(getStorageKey('cart'));\n removeItem(getStorageKey('meta'));\n clearCartCoupon();\n}\n\nexport function createCartBackup(): void {\n const cart = getCart();\n setItem(getStorageKey('cartBackup'), cart);\n const coupon = getCartCoupon();\n if (coupon) {\n setItem(getStorageKey('couponBackup'), coupon);\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 (typeof backupCoupon === 'string') {\n setCartCoupon(backupCoupon);\n } else {\n clearCartCoupon();\n }\n return true;\n }\n\n return false;\n}\n\nexport function mergeBaskets(items: CartItem[]): 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 index = cart.findIndex(\n (item) =>\n item.product_id === productId &&\n item.variant_id === variantId\n );\n\n if (index >= 0) {\n cart[index].quantity = Math.max(cart[index].quantity, normalizedQuantity);\n } else {\n cart.push({\n ...incoming,\n product_id: productId,\n variant_id: variantId,\n quantity: normalizedQuantity,\n });\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 toIndex = cart.findIndex(\n (item) => item.product_id === toProductId && item.variant_id === toVariantId\n );\n\n if (toIndex >= 0) {\n cart[toIndex].quantity += fromItem.quantity;\n } else {\n cart.push({\n ...fromItem,\n product_id: toProductId,\n variant_id: toVariantId,\n });\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 + (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: 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\nexport async function quoteCart(coupon?: string) {\n const payload = getCartPayload(coupon);\n return post<CartQuote>('/v1/storefront/cart/quote', {\n shop_slug: payload.store_slug,\n cart: payload.items,\n coupon: payload.coupon,\n });\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","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","/**\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, createCartBackup, clearCart } from './cart';\nimport { getAffiliateCode } from './affiliates';\nimport type { CartItem, CartAddon } from '../types/cart';\nimport type { BuyerRewards } from '../types/api';\n\nexport interface CheckoutOptions {\n autoRedirect?: boolean;\n locale?: string;\n email?: string;\n coupon?: string;\n affiliateCode?: string;\n referralCode?: string;\n}\n\nexport interface CheckoutResult {\n success: boolean;\n redirectUrl?: string;\n invoiceId?: string;\n rewards?: BuyerRewards | null;\n message?: 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\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 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): string | null {\n const explicitCode = options.affiliateCode ?? options.referralCode;\n if (typeof explicitCode === 'string' && explicitCode.trim().length > 0) {\n return explicitCode.trim().toLowerCase();\n }\n\n return getAffiliateCode();\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 }));\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, coupon } = resolvedOptions;\n const normalizedCoupon = coupon === undefined\n ? getCartCoupon()\n : normalizeCoupon(coupon);\n const normalizedEmail = normalizeEmail(email);\n const normalizedAffiliateCode = normalizeAffiliateCode(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 createCartBackup();\n\n const config = getConfig();\n\n let response = await post<CheckoutApiResponse>('/v1/storefront/invoices/from-cart', {\n shop_slug: config.storeSlug,\n cart: mapCartItemsForApi(cart),\n email: normalizedEmail,\n coupon: normalizedCoupon,\n affiliate_code: normalizedAffiliateCode,\n }, { retries: 0 });\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 };\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,\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 */\nexport async function buildCheckoutUrl(\n couponOrOptions?: string | CheckoutOptions,\n options?: CheckoutOptions\n): Promise<string> {\n const resolvedOptions = resolveCheckoutOptions(couponOrOptions, options);\n const { email, coupon } = resolvedOptions;\n const normalizedCoupon = coupon === undefined\n ? getCartCoupon()\n : normalizeCoupon(coupon);\n const normalizedEmail = normalizeEmail(email);\n const normalizedAffiliateCode = normalizeAffiliateCode(resolvedOptions);\n\n const cart = getCart();\n if (cart.length === 0) {\n throw new Error('Cart is empty');\n }\n\n const config = getConfig();\n\n let response = await post<CheckoutApiResponse>('/v1/storefront/invoices/from-cart', {\n shop_slug: config.storeSlug,\n cart: mapCartItemsForApi(cart),\n email: normalizedEmail,\n coupon: normalizedCoupon,\n affiliate_code: normalizedAffiliateCode,\n }, { retries: 0 });\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,\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, CursorPagination } from '../types';\n\ninterface FeedbackResponse {\n feedback: Feedback[];\n pagination?: CursorPagination | null;\n}\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\nasync function getShopReviewsPage(cursor?: string | null): Promise<SDKResponse<FeedbackResponse>> {\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<FeedbackResponse>(\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: response.data,\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 ?? []).map((item, index) =>\n normalizeFeedback(item, allFeedback.length + index)\n ));\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","import { getProducts } from './products.js';\nimport { isInitialized } from '../core/config.js';\nimport { isProductInStock } from '../utils/storefront-stock.js';\nimport type { SDKResponse, Product } from '../types/index.js';\n\nexport interface SearchOptions {\n hideOutOfStock?: boolean;\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().toLowerCase();\n if (!trimmed) {\n return { success: true, data: [] };\n }\n\n const products = await getProducts();\n if (!products.success || !products.data) {\n return { success: false, message: products.message ?? 'Failed to fetch products' };\n }\n\n let results = products.data.filter(\n (p) =>\n p.title.toLowerCase().includes(trimmed) ||\n (p.description?.toLowerCase().includes(trimmed) ?? false)\n );\n\n if (options?.hideOutOfStock) {\n results = results.filter((p) => isProductInStock(p));\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","import { isInitialized, getConfig } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport { getStorefrontConnectionId } from '../core/telemetry';\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 }),\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 type { SDKResponse, StorefrontOnlineUsers } from '../types';\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 },\n {\n retries: 0,\n timeout: 5000,\n },\n );\n}\n","/**\n * Formatting Utilities\n */\n\nimport { getConfig } from '../core/config';\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 });\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/v0.3/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 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';\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 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} from './modules/cart';\n\n// Checkout module\nimport { checkout, buildCheckoutUrl, buildCheckoutUrlSync } from './modules/checkout';\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 } from './modules/reviews';\n\n// Search module\nimport { searchProducts } 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, 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, 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 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\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\n // Search\n searchProducts,\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 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\nif (typeof window !== 'undefined') {\n (window as unknown as { shoppex: typeof shoppex }).shoppex = shoppex;\n}\n"],"x_google_ignoreList":[1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],"mappings":"AAIA,IAAa,EAAb,MAAa,UAAqB,MAIhC,WAAA,CAAY,EAAiB,EAAc,GACzC,MAAM,GACN,KAAK,KAAO,eACZ,KAAK,KAAO,EACZ,KAAK,WAAa,EAClB,OAAO,eAAe,KAAM,EAAa,aAIhC,EAAb,MAAa,UAA4B,EACvC,WAAA,GACE,MACE,kDACA,mBAEF,KAAK,KAAO,sBACZ,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,EAAS,KACxB,CACL,SAAS,EACT,KAAM,EAAS,KAAK,MAIjB,CACL,SAAS,EACT,QAAS,EAAS,UM4IpB,YACA,WACA,iBACA,kBACA,qBAGA,iBACA,4BACA,2BAGA,mBACA,YFvNF,SACE,EACA,EACA,GAEA,MAAM,EAAkC,iBAAX,EAAsB,WAAW,GAAU,EACxE,OAAI,OAAO,MAAM,GACR,GAAgB,EAAU,GAAQ,OAAO,GAE3C,GAAgB,EAAU,GAAQ,OAAO,IEiNhD,WpBhMF,WACE,GAAM,QACN,GAAQ,SoB+LR,gBpB5LF,SAAgC,GAC9B,IAAK,MAAM,KAAO,GAAM,QAClB,IAAQ,GAAe,EAAI,WAAW,KACxC,GAAM,OAAO,IoB0LjB,cpB3MF,WACE,MAAO,CACL,KAAM,GAAM,KACZ,OAAQ,GAAM,OACd,gBAAiB,GAAQ,KACzB,QAAS,GAAM,OoByMjB,iCACA,+BACA,mBACA,kBAOoB,oBAAX,SACT,OAAmD,QAAU"}
|
|
1
|
+
{"version":3,"file":"shoppex.esm.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/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/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-contact.ts","../src/core/cache.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/cart.ts","../src/modules/affiliates.ts","../src/modules/checkout.ts","../src/modules/coupons.ts","../src/modules/reviews.ts","../src/modules/search.ts","../src/modules/invoices.ts","../src/modules/pages.ts","../src/modules/navigation.ts","../src/modules/analytics.ts","../src/modules/presence.ts","../src/utils/format.ts","../src/modules/theme.ts","../src/index.ts"],"sourcesContent":["/**\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\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 { z } from 'zod';\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 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 'SQUARE',\n 'SUMUP',\n 'SHOPIFY',\n 'SUBY',\n 'PANDABASE',\n 'STORRIK',\n 'VENPAYR',\n 'MONEYMOTION',\n 'WHOP',\n 'DODO',\n 'MAVERICK',\n 'CASHAPP',\n 'VENMO',\n 'CRYPTO',\n 'CUSTOMER_BALANCE',\n 'MANUAL',\n] as const;\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 SQUARE: 'SQUARE',\n SUMUP: 'SUMUP',\n SHOPIFY: 'SHOPIFY',\n SUBY: 'SUBY',\n PANDABASE: 'PANDABASE',\n STORRIK: 'STORRIK',\n VENPAYR: 'VENPAYR',\n MONEYMOTION: 'MONEYMOTION',\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 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}\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\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 (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 '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 'VENPAYR':\n return 'VenPayr';\n case 'MONEYMOTION':\n return 'MoneyMotion';\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 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);\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>;\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.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] 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 — fonts the storefront ships locally so they render\n// without an external request. Order matters: it drives both the dropdown\n// in the 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 }).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\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] 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] 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 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};\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} 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\nexport const StorefrontAddonCreateSchema = z.discriminatedUnion('type', [\n AnnouncementBarDraftSchema,\n CountdownBarDraftSchema,\n PromoInfoCardDraftSchema,\n RecentPurchasePopupDraftSchema,\n CouponPopupModalDraftSchema,\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]);\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\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 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\nexport interface StorefrontAddonBootstrap {\n items: ResolvedStorefrontAddon[];\n}\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 './style-center.js';\nexport * from './style-center/presets.js';\nexport * from './storefront-addons.js';\nexport * from './api-error-codes.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 { 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 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 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 = Pick<ProductVariant, 'stock'> | Pick<PriceVariant, 'stock'>;\n\ntype ProductLike = Pick<Product, 'type' | 'stock' | 'price_variants' | 'variants'>;\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 collectVariantStocks(product: ProductLike): Array<number | null> {\n const priceVariantStocks = Array.isArray(product.price_variants)\n ? product.price_variants.map((variant) => normalizeStockValue(variant.stock))\n : [];\n if (priceVariantStocks.length > 0) {\n return priceVariantStocks;\n }\n\n const legacyVariantStocks = Array.isArray(product.variants)\n ? product.variants.map((variant) => normalizeStockValue(variant.stock))\n : [];\n\n return legacyVariantStocks;\n}\n\nexport function resolveDisplayStock(product: ProductLike | null | undefined): number {\n if (!product) {\n return -1;\n }\n\n if (typeof product.type === 'string' && product.type.toUpperCase() === 'SERIALS') {\n return normalizeStockValue(product.stock) ?? -1;\n }\n\n const variantStocks = collectVariantStocks(product);\n if (variantStocks.length > 0) {\n if (variantStocks.some((stock) => stock === null || stock < 0)) {\n return -1;\n }\n\n return variantStocks\n .filter((stock): stock is number => stock !== null)\n .reduce((sum, stock) => sum + Math.max(stock, 0), 0);\n }\n\n return normalizeStockValue(product.stock) ?? -1;\n}\n\nexport function isProductOutOfStock(product: ProductLike | null | undefined): boolean {\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 normalizeStockValue(variant?.stock) === 0;\n}\n\nexport function resolveVariantStockValue(variant: VariantLike | null | undefined): number {\n return normalizeStockValue(variant?.stock) ?? -1;\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 const envBaseUrl = typeof import.meta !== 'undefined'\n && typeof (import.meta as ImportMeta & { env?: Record<string, string | undefined> }).env?.VITE_API_BASE_URL === 'string'\n ? (import.meta as ImportMeta & { env?: Record<string, string | undefined> }).env?.VITE_API_BASE_URL\n : undefined;\n\n return (envBaseUrl || '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","/**\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","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 } from './config';\nimport { NetworkError } 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}\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 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\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 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 const statusCode =\n normalizedError instanceof NetworkError\n ? normalizedError.statusCode\n : undefined;\n\n lastFailure = {\n message: normalizedError.message,\n statusCode,\n isTransport: statusCode === undefined || statusCode === 408,\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 };\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 };\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 ProductVariant,\n PriceVariant,\n CursorPagination,\n} from '../types';\nimport { getStore } from './store';\n\ninterface ProductsResponse {\n products: Product[];\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 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 return {\n success: true,\n data: 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","/**\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 CartPayload,\n CartMetadata,\n CartStats,\n CartQuote,\n} from '../types';\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\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 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 (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 normalized.push(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 const raw = getItem<unknown>(getStorageKey('coupon'));\n if (typeof raw !== 'string') {\n return null;\n }\n return normalizeCouponCode(raw);\n}\n\nexport function setCartCoupon(coupon: string | null | undefined): string | null {\n const normalizedCoupon = normalizeCouponCode(coupon);\n if (!normalizedCoupon) {\n removeItem(getStorageKey('coupon'));\n return null;\n }\n\n setItem(getStorageKey('coupon'), normalizedCoupon);\n return normalizedCoupon;\n}\n\nexport function clearCartCoupon(): void {\n removeItem(getStorageKey('coupon'));\n}\n\nfunction writeCart(cart: CartItem[]): void {\n setItem(getStorageKey('cart'), cart);\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(cart),\n };\n setItem(getStorageKey('meta'), nextMeta);\n\n if (cart.length === 0) {\n clearCartCoupon();\n }\n}\n\nfunction setCartWithMetadata(cart: CartItem[], metadata?: CartMetadata | null): void {\n setItem(getStorageKey('cart'), cart);\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(cart),\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\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 existingIndex = cart.findIndex(\n (item) => item.product_id === productId && item.variant_id === variantId\n );\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 } else {\n cart.push({\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 });\n }\n\n writeCart(cart);\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 existingIndex = cart.findIndex(\n (item) => item.product_id === productId && item.variant_id === variantId\n );\n\n if (existingIndex >= 0) {\n cart[existingIndex].quantity = normalizedQuantity;\n\n if (options?.addons !== undefined) {\n cart[existingIndex].addons = options.addons;\n }\n if (options?.custom_fields !== undefined) {\n cart[existingIndex].custom_fields = options.custom_fields;\n }\n if (options?.price_variant_id !== undefined) {\n cart[existingIndex].price_variant_id = options.price_variant_id;\n }\n if (options?.price_data !== undefined) {\n cart[existingIndex].price_data = options.price_data;\n }\n } else {\n cart.push({\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 });\n }\n\n writeCart(cart);\n}\n\nexport function updateCartItem(\n productId: string,\n variantId: string,\n updates: Partial<Omit<CartItem, 'product_id' | 'variant_id'>>\n): void {\n const cart = getCart();\n\n const index = cart.findIndex(\n (item) => item.product_id === productId && item.variant_id === variantId\n );\n\n if (index < 0) {\n throw new CartError('Item not found in cart');\n }\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\n writeCart(cart);\n}\n\nexport function removeFromCart(productId: string, variantId: string): void {\n const cart = getCart();\n\n const filtered = cart.filter(\n (item) => !(item.product_id === productId && item.variant_id === variantId)\n );\n\n writeCart(filtered);\n}\n\nexport function clearCart(): void {\n removeItem(getStorageKey('cart'));\n removeItem(getStorageKey('meta'));\n clearCartCoupon();\n}\n\nexport function createCartBackup(): void {\n const cart = getCart();\n setItem(getStorageKey('cartBackup'), cart);\n const coupon = getCartCoupon();\n if (coupon) {\n setItem(getStorageKey('couponBackup'), coupon);\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 (typeof backupCoupon === 'string') {\n setCartCoupon(backupCoupon);\n } else {\n clearCartCoupon();\n }\n return true;\n }\n\n return false;\n}\n\nexport function mergeBaskets(items: CartItem[]): 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 index = cart.findIndex(\n (item) =>\n item.product_id === productId &&\n item.variant_id === variantId\n );\n\n if (index >= 0) {\n cart[index].quantity = Math.max(cart[index].quantity, normalizedQuantity);\n } else {\n cart.push({\n ...incoming,\n product_id: productId,\n variant_id: variantId,\n quantity: normalizedQuantity,\n });\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 toIndex = cart.findIndex(\n (item) => item.product_id === toProductId && item.variant_id === toVariantId\n );\n\n if (toIndex >= 0) {\n cart[toIndex].quantity += fromItem.quantity;\n } else {\n cart.push({\n ...fromItem,\n product_id: toProductId,\n variant_id: toVariantId,\n });\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 + (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: 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\nexport async function quoteCart(coupon?: string) {\n const payload = getCartPayload(coupon);\n return post<CartQuote>('/v1/storefront/cart/quote', {\n shop_slug: payload.store_slug,\n cart: payload.items,\n coupon: payload.coupon,\n });\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","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","/**\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, createCartBackup, clearCart } from './cart';\nimport { getAffiliateCode } from './affiliates';\nimport type { CartItem, CartAddon } from '../types/cart';\nimport type { BuyerRewards } from '../types/api';\n\nexport interface CheckoutOptions {\n autoRedirect?: boolean;\n locale?: string;\n email?: string;\n coupon?: string;\n affiliateCode?: string;\n referralCode?: string;\n}\n\nexport interface CheckoutResult {\n success: boolean;\n redirectUrl?: string;\n invoiceId?: string;\n rewards?: BuyerRewards | null;\n message?: 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\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 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): string | null {\n const explicitCode = options.affiliateCode ?? options.referralCode;\n if (typeof explicitCode === 'string' && explicitCode.trim().length > 0) {\n return explicitCode.trim().toLowerCase();\n }\n\n return getAffiliateCode();\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 }));\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, coupon } = resolvedOptions;\n const normalizedCoupon = coupon === undefined\n ? getCartCoupon()\n : normalizeCoupon(coupon);\n const normalizedEmail = normalizeEmail(email);\n const normalizedAffiliateCode = normalizeAffiliateCode(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 createCartBackup();\n\n const config = getConfig();\n\n let response = await post<CheckoutApiResponse>('/v1/storefront/invoices/from-cart', {\n shop_slug: config.storeSlug,\n cart: mapCartItemsForApi(cart),\n email: normalizedEmail,\n coupon: normalizedCoupon,\n affiliate_code: normalizedAffiliateCode,\n }, { retries: 0 });\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 };\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,\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 */\nexport async function buildCheckoutUrl(\n couponOrOptions?: string | CheckoutOptions,\n options?: CheckoutOptions\n): Promise<string> {\n const resolvedOptions = resolveCheckoutOptions(couponOrOptions, options);\n const { email, coupon } = resolvedOptions;\n const normalizedCoupon = coupon === undefined\n ? getCartCoupon()\n : normalizeCoupon(coupon);\n const normalizedEmail = normalizeEmail(email);\n const normalizedAffiliateCode = normalizeAffiliateCode(resolvedOptions);\n\n const cart = getCart();\n if (cart.length === 0) {\n throw new Error('Cart is empty');\n }\n\n const config = getConfig();\n\n let response = await post<CheckoutApiResponse>('/v1/storefront/invoices/from-cart', {\n shop_slug: config.storeSlug,\n cart: mapCartItemsForApi(cart),\n email: normalizedEmail,\n coupon: normalizedCoupon,\n affiliate_code: normalizedAffiliateCode,\n }, { retries: 0 });\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,\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, CursorPagination } from '../types';\n\ninterface FeedbackResponse {\n feedback: Feedback[];\n pagination?: CursorPagination | null;\n}\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\nasync function getShopReviewsPage(cursor?: string | null): Promise<SDKResponse<FeedbackResponse>> {\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<FeedbackResponse>(\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: response.data,\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 ?? []).map((item, index) =>\n normalizeFeedback(item, allFeedback.length + index)\n ));\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","import { getProducts } from './products.js';\nimport { isInitialized } from '../core/config.js';\nimport { isProductInStock } from '../utils/storefront-stock.js';\nimport type { SDKResponse, Product } from '../types/index.js';\n\nexport interface SearchOptions {\n hideOutOfStock?: boolean;\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().toLowerCase();\n if (!trimmed) {\n return { success: true, data: [] };\n }\n\n const products = await getProducts();\n if (!products.success || !products.data) {\n return { success: false, message: products.message ?? 'Failed to fetch products' };\n }\n\n let results = products.data.filter(\n (p) =>\n p.title.toLowerCase().includes(trimmed) ||\n (p.description?.toLowerCase().includes(trimmed) ?? false)\n );\n\n if (options?.hideOutOfStock) {\n results = results.filter((p) => isProductInStock(p));\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","import { isInitialized, getConfig } from '../core/config';\nimport { buildEndpoint } from '../core/endpoint';\nimport { getStorefrontConnectionId } from '../core/telemetry';\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 }),\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 type { SDKResponse, StorefrontOnlineUsers } from '../types';\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 },\n {\n retries: 0,\n timeout: 5000,\n },\n );\n}\n","/**\n * Formatting Utilities\n */\n\nimport { getConfig } from '../core/config';\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 });\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/v0.3/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 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';\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 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} from './modules/cart';\n\n// Checkout module\nimport { checkout, buildCheckoutUrl, buildCheckoutUrlSync } from './modules/checkout';\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 } from './modules/reviews';\n\n// Search module\nimport { searchProducts } 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, 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, 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 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\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\n // Search\n searchProducts,\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 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":[1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],"mappings":"AAIA,IAAa,EAAb,MAAa,UAAqB,MAIhC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