@eloquentai/chat-sdk 0.34.4-dev.3 → 0.34.4
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/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../src/instrumentation.ts","../src/components/embed/chat-bubble.tsx","../src/components/embed/iframe.tsx","../src/components/embed/portal.tsx","../src/components/embed/proactive-message.tsx","../src/lib/cookies.ts","../src/components/chat/hooks/use-interface-props.ts","../src/hooks/use-latest-ref.ts","../src/lib/http.ts","../src/lib/url-params.ts","../src/components/chat/hooks/use-persistence.ts","../src/lib/appsync-events-client.ts","../node_modules/zod/v4/core/util.js","../node_modules/zod/v4/core/core.js","../node_modules/zod/v4/core/errors.js","../node_modules/zod/v4/core/parse.js","../node_modules/zod/v4/core/regexes.js","../node_modules/zod/v4/core/versions.js","../node_modules/zod/v4/core/schemas.js","../node_modules/zod/v4/core/api.js","../node_modules/zod/v4/mini/schemas.js","../src/components/chat/validations.ts","../src/components/chat/hooks/use-realtime-socket.ts","../src/components/chat/message-mapping.ts","../src/components/chat/hooks/use-message-events.ts","../src/lib/config.ts","../src/lib/eloquent-ai-api-client.ts","../src/lib/wrap-promise.ts","../src/lib/retry.ts","../src/hooks/use-fetch.ts","../src/components/chat/hooks/use-user-identity.ts","../src/components/chat/hooks/use-sdk-initialization.ts","../src/components/chat/hooks/use-ui-initialization.ts","../src/components/chat/hooks/use-chat.ts","../src/components/chat/hooks/use-keyboard-inset.ts","../src/components/chat/hooks/use-scroll-lock.ts","../src/contexts/agent-cognition/use-agent-cognition.ts","../src/contexts/agent-cognition/agent-cognition-provider.tsx","../src/contexts/error-handling/error-provider.tsx","../src/components/chat/chat.tsx","../src/components/embed/render-chat.tsx"],"sourcesContent":["// Only initialize Sentry on the client side\nif (typeof window !== \"undefined\") {\n // Transform Vite environment values to Sentry format\n // Access import.meta.env only on the client side to avoid SSR issues\n const viteEnv = import.meta.env.VITE_ENVIRONMENT as string | undefined;\n const environment = viteEnv === \"prod\" ? \"production\" : \"development\";\n const isLocal = viteEnv === \"local\";\n\n // Dynamically import Sentry to avoid SSR issues. Destructure only `init`:\n // holding the whole namespace would keep every barrel export (replay,\n // feedback, canvas integrations — hundreds of KB) alive in the bundle.\n import(\"@sentry/react\").then(({ init }) => {\n init({\n dsn: import.meta.env.VITE_SENTRY_DSN,\n environment,\n sendDefaultPii: false,\n debug: false,\n enabled: !isLocal,\n beforeSend(event) {\n const sensitiveHeaders = new Set([\n \"authorization\",\n \"cookie\",\n \"x-api-key\",\n \"x-auth-token\",\n ]);\n const headers = event.request?.headers as\n | Record<string, string>\n | undefined;\n if (headers) {\n for (const key of Object.keys(headers)) {\n if (sensitiveHeaders.has(key.toLowerCase())) {\n headers[key] = \"[Filtered]\";\n }\n }\n }\n if (event.request) {\n event.request.data = \"[Filtered]\";\n }\n return event;\n },\n });\n });\n}\n","\"use client\";\n\nimport { cn } from \"@/lib/utils\";\n\nimport { Logo } from \"@/components/logo\";\n\nexport function ChatBubble({\n toggleBubble,\n isDarkMode = false,\n}: {\n isOpen: boolean;\n toggleBubble: () => void;\n /** Renders in its own iframe (no `.dark` ancestor), so the mode arrives as a prop. */\n isDarkMode?: boolean;\n}) {\n const bubbleBackground = isDarkMode ? \"#fff\" : \"#000\";\n const logoForeground = isDarkMode ? \"#000000\" : \"#ffffff\";\n\n return (\n <div className=\"eloq:absolute eloq:inset-0 eloq:m-auto eloq:flex eloq:items-center eloq:justify-center eloq:overflow-hidden\">\n <div\n className={cn(\n \"eloq:chat-bubble eloq:relative eloq:flex eloq:items-center eloq:justify-center eloq:w-12 eloq:h-12 eloq:rounded-full eloq:cursor-pointer\",\n // Inverted in dark mode: a black launcher disappears on dark pages.\n isDarkMode\n ? \"eloq:bg-[#fff] eloq:text-[#000]\"\n : \"eloq:bg-[#000] eloq:text-[#fff]\",\n )}\n onClick={toggleBubble}\n >\n <div className=\"eloq:absolute eloq:inset-0 eloq:flex eloq:justify-center eloq:items-center eloq:m-auto\">\n <Logo bgColor={bubbleBackground} fgColor={logoForeground} />\n </div>\n </div>\n </div>\n );\n}\n","import { HTMLAttributes, PropsWithChildren, ReactNode, useState } from \"react\";\nimport { createPortal } from \"react-dom\";\n\ntype IframeProps = PropsWithChildren<HTMLAttributes<HTMLIFrameElement>> & {\n head: ReactNode;\n};\n\nexport function Iframe({ children, head, ...props }: IframeProps) {\n const [contentRef, setContentRef] = useState<HTMLIFrameElement | null>(null);\n const headNode = contentRef?.contentWindow?.document?.head;\n const bodyNode = contentRef?.contentWindow?.document?.body;\n return (\n <iframe {...props} ref={setContentRef}>\n {headNode && createPortal(head, headNode)}\n {bodyNode && createPortal(children, bodyNode)}\n </iframe>\n );\n}\n","\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport { createPortal } from \"react-dom\";\n\ninterface PortalProps {\n children: ReactNode;\n container: HTMLElement;\n}\n\nexport function Portal({ children, container }: PortalProps) {\n return createPortal(children, container);\n}\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport { X } from \"lucide-react\";\n\nimport { getContrastingTextColor } from \"@/lib/color-contrast\";\nimport { cn } from \"@/lib/utils\";\nimport { useTheme } from \"@/contexts/theme.context\";\n\nexport interface ProactiveMessageProps {\n message: string;\n isVisible: boolean;\n onDismiss: () => void;\n onMessageClick?: () => void;\n autoHideDelay?: number;\n}\n\nexport function ProactiveMessage({\n message,\n isVisible,\n onDismiss,\n onMessageClick,\n autoHideDelay,\n}: ProactiveMessageProps) {\n const [shouldRender, setShouldRender] = useState(false);\n const [animationState, setAnimationState] = useState<\n \"entering\" | \"visible\" | \"exiting\"\n >(\"entering\");\n const theme = useTheme();\n\n useEffect(() => {\n if (isVisible) {\n setShouldRender(true);\n setAnimationState(\"entering\");\n\n // Start entrance animation\n const enterTimer = setTimeout(() => {\n setAnimationState(\"visible\");\n }, 50);\n\n let exitTimer: ReturnType<typeof setTimeout> | undefined;\n const hideTimer = setTimeout(() => {\n setAnimationState(\"exiting\");\n // Start exit animation\n exitTimer = setTimeout(() => {\n onDismiss();\n }, 300);\n }, autoHideDelay);\n\n return () => {\n clearTimeout(enterTimer);\n clearTimeout(hideTimer);\n clearTimeout(exitTimer);\n };\n } else {\n setAnimationState(\"exiting\");\n // Delay hiding to allow for exit animation\n const timer = setTimeout(() => {\n setShouldRender(false);\n setAnimationState(\"entering\"); // Reset for next time\n }, 300);\n\n return () => clearTimeout(timer);\n }\n }, [isVisible, onDismiss, autoHideDelay]);\n\n if (!shouldRender) {\n return null;\n }\n\n return (\n <div\n className={cn(\n // right-16 leaves a ~7px gap between the tail tip and the launcher\n // circle's edge — the tail points at it without sliding underneath.\n \"eloq:absolute eloq:right-16 eloq:bottom-0 eloq:max-w-xs eloq:transform eloq:transition-all eloq:duration-500 eloq:ease-out\",\n animationState === \"entering\" &&\n \"eloq:translate-x-8 eloq:opacity-0 eloq:scale-95\",\n animationState === \"visible\" &&\n \"eloq:translate-x-0 eloq:opacity-100 eloq:scale-100\",\n animationState === \"exiting\" &&\n \"eloq:translate-x-8 eloq:opacity-0 eloq:scale-95\",\n )}\n >\n {/* drop-shadow (not box-shadow) so the shadow follows the combined\n silhouette of the bubble AND its tail as one continuous shape. */}\n <div className=\"eloq:relative eloq:drop-shadow-lg eloq:hover:drop-shadow-xl eloq:transition-all eloq:duration-300\">\n {/* Message bubble */}\n <div\n className=\"eloq:relative eloq:rounded-lg eloq:border eloq:p-3 eloq:cursor-pointer\"\n style={{\n backgroundColor: theme.botBubbleColor,\n }}\n onClick={onMessageClick}\n >\n {/* Tail: the original curved wedge, stroked so it carries the same\n 1px outline as the bubble (vector-effect keeps the stroke at\n real 1px despite the viewBox scaling). The cover rect hides the\n stroke along the attachment edge inside the bubble, so tail and\n bubble outlines merge into one shape. The SVG is mirrored\n (-scale-x-100), so low viewBox x is the outward tip and high x\n the attachment side. */}\n <svg\n aria-hidden\n className=\"eloq:absolute eloq:bottom-1 eloq:-right-[9px] eloq:h-4 eloq:w-4 eloq:-scale-x-100\"\n viewBox=\"0 0 10.54 11.14\"\n >\n {/* strokeWidth 2, not 1: SVG strokes are centered on the path, so\n half sits under the fill — 2 leaves exactly 1px visible\n outside, matching the bubble's 1px CSS border. */}\n <path\n d=\"M5.75,0s0,.36,0,.51c-.09,4.52-5.74,10.64-5.74,10.64,8.19.02,10.54-2.26,10.54-2.26h0c-1.6-2.96-3.19-5.92-4.79-8.88Z\"\n fill={theme.botBubbleColor}\n strokeWidth={2}\n vectorEffect=\"non-scaling-stroke\"\n style={{ stroke: \"hsl(var(--border))\" }}\n />\n <rect\n x=\"6.2\"\n y=\"-1\"\n width=\"6\"\n height=\"14\"\n fill={theme.botBubbleColor}\n />\n </svg>\n {/* The corner-pinned X is absolutely positioned and ignores the\n text flow entirely; pr-4 (16px, on top of the bubble's own\n 12px padding) keeps the text clear of the X's glyph. */}\n <p\n className=\"eloq:text-sm eloq:leading-relaxed eloq:pr-4\"\n style={{\n color:\n theme.botBubbleTextColor ||\n getContrastingTextColor(theme.botBubbleColor),\n }}\n >\n {message}\n </p>\n <button\n aria-label=\"Dismiss message\"\n onClick={(e) => {\n e.stopPropagation();\n onDismiss();\n }}\n // Pinned to the bubble's top-right corner, outside the text\n // flow — a flex-row placement can't tuck the glyph into the\n // padding area. p-1.5 keeps a 24px hit area around the 12px\n // icon; top/right-0.5 leaves the glyph ~8px from the edges.\n className=\"eloq:absolute eloq:top-0.5 eloq:right-0.5 eloq:p-1.5 eloq:opacity-50 eloq:hover:opacity-100 eloq:hover:bg-black/5 eloq:dark:hover:bg-white/10 eloq:rounded-full eloq:transition-all eloq:duration-200\"\n style={{\n // Follows the bubble's computed text colour, so the X blends\n // with the message on any bubble background (and dark mode).\n color:\n theme.botBubbleTextColor ||\n getContrastingTextColor(theme.botBubbleColor),\n }}\n >\n <X className=\"eloq:w-2.5 eloq:h-2.5\" strokeWidth={1.75} />\n </button>\n </div>\n </div>\n </div>\n );\n}\n","/**\n * Read a cookie value by name.\n * @returns The decoded cookie value, or null if it doesn't exist or there's no document.\n */\nexport function getCookie(name: string): string | null {\n if (typeof document === \"undefined\") return null;\n const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));\n return match ? decodeURIComponent(match[1]) : null;\n}\n\n/**\n * Set a cookie with a given name, value, and TTL in hours.\n */\nexport function setCookie(name: string, value: string, hours: number) {\n if (typeof document === \"undefined\") return;\n const expires = new Date(Date.now() + hours * 60 * 60 * 1000).toUTCString();\n document.cookie = `${name}=${encodeURIComponent(value)}; expires=${expires}; path=/; SameSite=Lax`;\n}\n\n/**\n * Delete a cookie by name.\n */\nexport function deleteCookie(name: string) {\n if (typeof document === \"undefined\") return;\n document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;\n}\n","\"use client\";\n\nimport { useMemo } from \"react\";\n\nimport type { BootResponse } from \"@/lib/eloquent-ai-api-client\";\n\nimport { ChatInterfaceProps } from \"@/components/chat-interface\";\n\nexport interface UseInterfacePropsParams {\n chatProps?: Partial<ChatInterfaceProps>;\n chatSettings: BootResponse[\"chat_settings\"] | null;\n}\n\n/**\n * Hook to handle chat interface properties generation\n * Combines user-provided props with server-provided settings\n */\nexport function useInterfaceProps({\n chatProps,\n chatSettings,\n}: UseInterfacePropsParams): Partial<ChatInterfaceProps> {\n const chatInterfaceProps = useMemo(() => {\n if (!chatSettings) return chatProps as Partial<ChatInterfaceProps>;\n\n return {\n assistantName: chatSettings.agent_name,\n assistantLogo: chatSettings.avatar_url || undefined,\n theme: {\n ...chatProps?.theme,\n mode: chatSettings.theme ?? \"light\",\n userBubbleColor:\n chatSettings.user_bubble_color || chatProps?.theme?.userBubbleColor,\n botBubbleColor:\n chatSettings.bot_bubble_color || chatProps?.theme?.botBubbleColor,\n suggestedMessageBubbleColor:\n chatSettings.suggested_message_bubble_color ||\n chatProps?.theme?.suggestedMessageBubbleColor,\n userBubbleTextColor:\n chatSettings.user_bubble_text_color ||\n chatProps?.theme?.userBubbleTextColor,\n botBubbleTextColor:\n chatSettings.bot_bubble_text_color ||\n chatProps?.theme?.botBubbleTextColor,\n suggestedMessageBubbleTextColor:\n chatSettings.suggested_message_bubble_text_color ||\n chatProps?.theme?.suggestedMessageBubbleTextColor,\n },\n welcomeMessage: chatSettings.welcome_message || undefined,\n legalText: chatSettings.footer_html || undefined,\n suggestedMessages: chatSettings.suggested_messages,\n suggestedMessageTexts: chatSettings.suggested_message_texts ?? undefined,\n // Boot value wins when the server sends one (?? so an explicit false\n // still wins); the host-app prop is the fallback.\n hasSuggestedMessageAura:\n chatSettings.suggested_message_aura ??\n chatProps?.hasSuggestedMessageAura,\n hasSuggestedMessageShine:\n chatSettings.suggested_message_shine ??\n chatProps?.hasSuggestedMessageShine,\n displayWelcomeMessages: chatSettings.auto_display_welcome_message,\n collectUserFeedback: chatSettings.collect_user_feedback,\n title: chatSettings.title || \"responds instantly\",\n subtitle: chatSettings.subtitle || \"Ask me anything\",\n };\n }, [chatProps, chatSettings]);\n\n return chatInterfaceProps;\n}\n","import { useEffect, useRef } from \"react\";\n\n/**\n * Returns a ref that always holds the latest `value`, updated after every\n * render. The \"latest ref\" pattern: long-lived closures (timers, socket\n * subscriptions) read `ref.current` at call time instead of capturing a\n * stale value, without needing the value in any dependency array.\n */\nexport function useLatestRef<Type>(value: Type): { readonly current: Type } {\n const reference = useRef(value);\n\n useEffect(() => {\n reference.current = value;\n });\n\n return reference;\n}\n","// Custom error class for network errors (CORS, fetch failures)\nexport class NetworkError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"NetworkError\";\n }\n}\n\n// Custom error class for server errors\nexport class ServerError extends Error {\n status: number;\n response: Record<string, Record<string, string | number>[]>;\n\n constructor(\n status: number,\n message: string,\n response: Record<string, Record<string, string | number>[]>,\n ) {\n super(message);\n this.name = \"ServerError\";\n this.status = status;\n this.response = response;\n }\n}\n\nexport interface HttpClientConfig {\n baseURL: string;\n appId: string;\n userId?: string;\n}\n\nconst CHAT_TOKEN_HEADER = \"x-elo-chat-token\";\nconst CHAT_TOKEN_RENEWED_HEADER = \"x-elo-chat-token-renewed\";\n\nexport class HttpClient {\n private baseURL: string;\n private headers: HeadersInit;\n private region: string | null = null;\n private chatToken: string | null = null;\n\n constructor(config: HttpClientConfig) {\n this.baseURL = config.baseURL;\n\n this.headers = {\n \"Content-Type\": \"application/json\",\n \"ELO-APP-ID\": config.appId,\n Origin: typeof window !== \"undefined\" ? window.location.origin : \"\",\n };\n }\n\n setRegion(region: string): void {\n this.region = region;\n }\n\n setChatToken(token: string | null): void {\n this.chatToken = token;\n }\n\n getChatToken(): string | null {\n return this.chatToken;\n }\n\n private async request<T>(url: string, options: RequestInit = {}): Promise<T> {\n const regionHeader: Record<string, string> = this.region\n ? { \"X-Region\": this.region }\n : {};\n const chatTokenHeader: Record<string, string> = this.chatToken\n ? { [CHAT_TOKEN_HEADER]: this.chatToken }\n : {};\n\n let response: Response;\n try {\n response = await fetch(`${this.baseURL}${url}`, {\n ...options,\n headers: {\n ...this.headers,\n ...regionHeader,\n ...chatTokenHeader,\n ...options.headers,\n },\n });\n } catch (error) {\n if (error instanceof TypeError) {\n throw new NetworkError(error.message);\n }\n throw error;\n }\n\n const renewedToken = response.headers.get(CHAT_TOKEN_RENEWED_HEADER);\n if (renewedToken) {\n this.chatToken = renewedToken;\n }\n\n let responseData;\n try {\n responseData = await response.json();\n } catch (e) {\n console.error(\"Error parsing JSON response:\", e);\n }\n\n if (!response.ok) {\n // Check for server errors (500 range)\n if (response.status >= 500) {\n throw new ServerError(response.status, \"API error\", responseData);\n }\n throw new ServerError(response.status, \"HTTP error\", responseData);\n }\n\n return responseData;\n }\n\n async get<T>(url: string) {\n return this.request<T>(url, { method: \"GET\" });\n }\n\n async post<T, D>(url: string, data: D): Promise<T> {\n return this.request<T>(url, {\n method: \"POST\",\n body: JSON.stringify(data),\n });\n }\n\n async put<T, D>(url: string, data: D): Promise<T> {\n return this.request<T>(url, {\n method: \"PUT\",\n body: JSON.stringify(data),\n });\n }\n\n /**\n * External GET request without default headers or credentials\n * Used for cross-origin requests that don't need authentication\n */\n async getExternal<T>(url: string): Promise<T> {\n const response = await fetch(url, {\n method: \"GET\",\n credentials: \"omit\",\n });\n\n let responseData;\n try {\n responseData = await response.json();\n } catch (e) {\n console.error(\"Error parsing JSON response:\", e);\n }\n\n if (!response.ok) {\n // Check for server errors (500 range)\n if (response.status >= 500) {\n throw new ServerError(response.status, \"API error\", responseData);\n }\n throw new ServerError(response.status, \"HTTP error\", responseData);\n }\n\n return responseData;\n }\n}\n","/**\n * Reads the current page URL search params from the host website.\n * Returns an empty object during SSR or when there are no query params.\n */\nexport function getCurrentUrlSearchParams(): Record<string, string> {\n if (typeof window === \"undefined\") {\n return {};\n }\n\n const params = new URLSearchParams(window.location.search);\n const result: Record<string, string> = {};\n\n params.forEach((value, key) => {\n result[key] = value;\n });\n\n return result;\n}\n","\"use client\";\n\nimport { useCallback, useMemo } from \"react\";\n\nimport { Message } from \"@/types/message\";\n\n// Single key for localStorage\nconst STORAGE_NAMESPACE = \"eloquent-ai::conversation-data\";\n\nconst isClient = typeof window !== \"undefined\";\n\n// 30 minutes in milliseconds\nconst CHAT_EXPIRY_TIME = 30 * 60 * 1000;\n\nexport interface ChatData {\n conversationId: string | null;\n userId: string | null;\n externalId?: string | null;\n deviceId: string | null;\n messages: Message[];\n lastActivity?: number;\n isChatClosed?: boolean;\n chatToken?: string | null;\n}\n\n/**\n * Hook to manage persistence of chat data, including conversation ID, user ID, last activity time, and messages.\n * @returns An object containing the conversation data and functions to set and clear the data.\n */\nexport function usePersistence({ appId }: { appId: string }) {\n const STORAGE_KEY = useMemo(() => `${STORAGE_NAMESPACE}-${appId}`, [appId]);\n const defaultObject = useMemo(\n () => ({\n conversationId: null,\n userId: null,\n deviceId: null,\n messages: [],\n }),\n [],\n );\n\n /**\n * Get saved conversation data from localStorage\n */\n const getSavedChatData = useCallback((): ChatData => {\n try {\n if (!isClient) return defaultObject;\n const storedData = localStorage.getItem(STORAGE_KEY);\n if (!storedData) {\n return defaultObject;\n }\n return JSON.parse(storedData) as ChatData;\n } catch (error) {\n console.error(\n \"Error retrieving conversation data from localStorage:\",\n error,\n );\n return defaultObject;\n }\n }, [STORAGE_KEY, defaultObject]);\n\n /**\n * Check if the current conversation has expired (inactive for more than 30 minutes)\n */\n const isChatExpired = useCallback((): boolean => {\n try {\n const data = getSavedChatData();\n if (!data.lastActivity) return true;\n\n const currentTime = Date.now();\n return currentTime - data.lastActivity > CHAT_EXPIRY_TIME;\n } catch (error) {\n console.error(\"Error checking conversation expiration:\", error);\n return true;\n }\n }, [getSavedChatData]);\n\n /**\n * Save conversation data to localStorage\n */\n const saveChatData = useCallback(\n (\n conversationId: string,\n userId: string,\n messages: Message[],\n deviceId: string,\n chatToken?: string | null,\n ) => {\n try {\n if (!isClient) return;\n const chatData: ChatData = {\n conversationId,\n userId,\n deviceId,\n messages,\n lastActivity: Date.now(),\n chatToken,\n };\n\n localStorage.setItem(STORAGE_KEY, JSON.stringify(chatData));\n } catch (error) {\n console.error(\"Error saving conversation data to localStorage:\", error);\n }\n },\n [STORAGE_KEY],\n );\n\n /**\n * Mark the current conversation as closed, so a page refresh still shows\n * the \"Start a new conversation\" screen instead of resetting it.\n */\n const markChatClosed = useCallback(() => {\n try {\n if (!isClient) return;\n const data = getSavedChatData();\n localStorage.setItem(\n STORAGE_KEY,\n JSON.stringify({ ...data, isChatClosed: true }),\n );\n } catch (error) {\n console.error(\n \"Error marking conversation as closed in localStorage:\",\n error,\n );\n }\n }, [STORAGE_KEY, getSavedChatData]);\n\n /**\n * Clear only conversationId, messages, and lastActivity from localStorage, preserving userId and deviceId\n */\n const clearChatData = useCallback(() => {\n try {\n if (!isClient) return;\n const stored = localStorage.getItem(STORAGE_KEY);\n if (stored) {\n const data = JSON.parse(stored);\n localStorage.setItem(\n STORAGE_KEY,\n JSON.stringify({\n ...defaultObject,\n deviceId: data.deviceId,\n userId: data.userId,\n }),\n );\n }\n } catch (error) {\n console.error(\n \"Error clearing conversation data from localStorage:\",\n error,\n );\n }\n }, [STORAGE_KEY, defaultObject]);\n\n /**\n * Update the last activity timestamp\n */\n const updateLastActivity = useCallback(() => {\n try {\n if (!isClient) return;\n const data = getSavedChatData();\n if (data.conversationId) {\n data.lastActivity = Date.now();\n localStorage.setItem(STORAGE_KEY, JSON.stringify(data));\n }\n } catch (error) {\n console.error(\"Error updating last activity timestamp:\", error);\n }\n }, [getSavedChatData, STORAGE_KEY]);\n\n return {\n isChatExpired,\n saveChatData,\n clearChatData,\n getSavedChatData,\n updateLastActivity,\n markChatClosed,\n };\n}\n","// Minimal AWS AppSync Events API real-time client — a hand-rolled\n// replacement for aws-amplify's `events.connect`, which carried ~160KB of\n// dependencies (amplify core, rxjs, graphql) for the tiny surface this SDK\n// uses: subscribe to one channel, deliver events, detect disconnects.\n//\n// Protocol reference: AWS \"Event API WebSocket protocol\" docs, cross-checked\n// against @aws-amplify/api-graphql's AWSAppSyncEventsProvider implementation\n// (subprotocol names, header encoding, keep-alive semantics, timeouts).\n//\n// Wire flow:\n// 1. Open a WebSocket to the realtime endpoint with two subprotocols:\n// \"aws-appsync-event-ws\" and \"header-<base64url(auth JSON)>\"\n// 2. Send {\"type\":\"connection_init\"}, await connection_ack (carries\n// connectionTimeoutMs — the keep-alive death window)\n// 3. Send subscribe with the SAME authorization embedded in the message\n// (per-operation auth is required by the protocol, not just per-connect)\n// 4. Receive {\"type\":\"data\", \"event\":\"<JSON string>\"} per published event\n// 5. Server sends {\"type\":\"ka\"} every ~60s; if neither ka nor data arrives\n// within connectionTimeoutMs, the connection is dead.\n\n/** Lambda-authorizer token (the chat token) or the API key fallback. */\nexport type AppSyncEventsAuth =\n | { authorizationToken: string }\n | { apiKey: string };\n\nexport type AppSyncEventsConnection = {\n /** Sends unsubscribe, closes the socket, and suppresses onDisconnect. */\n close: () => void;\n};\n\nexport type WebSocketLike = {\n readyState: number;\n send: (data: string) => void;\n close: () => void;\n addEventListener: (\n type: \"open\" | \"message\" | \"close\" | \"error\",\n listener: (event: { data?: unknown }) => void,\n ) => void;\n};\n\nexport type ConnectAppSyncEventsOptions = {\n /** The HTTP Events endpoint from boot settings (chat_settings.app_sync_url). */\n httpEndpoint: string;\n auth: AppSyncEventsAuth;\n /** Channel path, e.g. \"/default/chat/<chatId>\". */\n channel: string;\n /** Called once per published event, with the payload already JSON-parsed. */\n onEvent: (event: unknown) => void;\n /**\n * Called exactly once when an established connection dies (server close,\n * network drop, keep-alive timeout). NOT called after close(), and not\n * called for connections that never established (connect() rejects there).\n */\n onDisconnect: (reason: string) => void;\n /** Injectable for tests; defaults to the global WebSocket constructor. */\n createWebSocket?: (url: string, protocols: string[]) => WebSocketLike;\n};\n\nexport const APPSYNC_EVENTS_SUBPROTOCOL = \"aws-appsync-event-ws\";\n\n/** connection_init → connection_ack and subscribe → subscribe_success wait. */\nexport const HANDSHAKE_TIMEOUT_MILLISECONDS = 15000;\n/** Fallback keep-alive death window when the ack doesn't carry one. */\nexport const DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS = 300000;\n/** How often the keep-alive clock is checked. */\nexport const KEEP_ALIVE_CHECK_INTERVAL_MILLISECONDS = 5000;\n\nconst WEB_SOCKET_OPEN_STATE = 1;\n\n/**\n * Derives the realtime WebSocket URL from the HTTP Events endpoint.\n * Standard AWS domains swap the service subdomain; custom domains keep the\n * host and only append the path.\n * https://xxx.appsync-api.us-east-1.amazonaws.com/event\n * → wss://xxx.appsync-realtime-api.us-east-1.amazonaws.com/event/realtime\n * https://events.example.com/event\n * → wss://events.example.com/event/realtime\n */\nexport function deriveRealtimeUrl(httpEndpoint: string): string {\n const url = new URL(httpEndpoint);\n const isStandardAwsDomain =\n /\\.appsync-api\\.[\\w-]+\\.amazonaws\\.com(\\.cn)?$/.test(url.hostname);\n if (isStandardAwsDomain) {\n url.hostname = url.hostname.replace(\n \".appsync-api.\",\n \".appsync-realtime-api.\",\n );\n }\n url.protocol = \"wss:\";\n url.pathname = `${url.pathname.replace(/\\/$/, \"\")}/realtime`;\n return url.toString();\n}\n\n/**\n * The authorization object embedded both in the connect subprotocol header\n * and in every subscribe message. `host` is always the HTTP endpoint's host\n * (not the realtime host), per the protocol.\n */\nexport function buildAuthorization(\n httpEndpoint: string,\n auth: AppSyncEventsAuth,\n): Record<string, string> {\n const host = new URL(httpEndpoint).host;\n if (\"authorizationToken\" in auth) {\n return { Authorization: auth.authorizationToken, host };\n }\n return { \"x-api-key\": auth.apiKey, host };\n}\n\n/**\n * Encodes the authorization object into the `header-…` subprotocol value:\n * base64url (`+`→`-`, `/`→`_`) with padding stripped — `=` is not a legal\n * character in a Sec-WebSocket-Protocol token and fails the handshake.\n */\nexport function encodeAuthProtocol(\n authorization: Record<string, string>,\n): string {\n const base64 = btoa(JSON.stringify(authorization));\n return `header-${base64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\")}`;\n}\n\ntype ServerMessage = {\n type?: string;\n id?: string;\n event?: unknown;\n connectionTimeoutMs?: number;\n errors?: { errorType?: string; message?: string }[];\n};\n\nfunction formatErrors(errors: ServerMessage[\"errors\"]): string {\n if (!errors || errors.length === 0) return \"unknown error\";\n return errors\n .map((error) => `${error.errorType ?? \"Error\"}: ${error.message ?? \"\"}`)\n .join(\"; \");\n}\n\n/**\n * Opens a connection and subscribes to one channel. Resolves once the\n * subscription is confirmed; rejects if any handshake step fails or times\n * out (the socket is closed in that case). After resolution, connection\n * death is reported via onDisconnect exactly once.\n */\nexport function connectAppSyncEvents(\n options: ConnectAppSyncEventsOptions,\n): Promise<AppSyncEventsConnection> {\n const {\n httpEndpoint,\n auth,\n channel,\n onEvent,\n onDisconnect,\n createWebSocket = (url, protocols) =>\n new WebSocket(url, protocols) as WebSocketLike,\n } = options;\n\n const authorization = buildAuthorization(httpEndpoint, auth);\n const realtimeUrl = deriveRealtimeUrl(httpEndpoint);\n const subscriptionId = crypto.randomUUID();\n\n return new Promise<AppSyncEventsConnection>((resolve, reject) => {\n let socket: WebSocketLike;\n try {\n socket = createWebSocket(realtimeUrl, [\n APPSYNC_EVENTS_SUBPROTOCOL,\n encodeAuthProtocol(authorization),\n ]);\n } catch (error) {\n reject(error instanceof Error ? error : new Error(String(error)));\n return;\n }\n\n let phase: \"connecting\" | \"subscribing\" | \"established\" | \"closed\" =\n \"connecting\";\n let isClosedByClient = false;\n let connectionTimeoutMilliseconds = DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS;\n let lastLivenessTimestamp = Date.now();\n\n let handshakeTimer: ReturnType<typeof setTimeout> | null = null;\n let keepAliveTimer: ReturnType<typeof setInterval> | null = null;\n\n const clearTimers = () => {\n if (handshakeTimer) {\n clearTimeout(handshakeTimer);\n handshakeTimer = null;\n }\n if (keepAliveTimer) {\n clearInterval(keepAliveTimer);\n keepAliveTimer = null;\n }\n };\n\n /** Single funnel for connection death, in any phase. */\n const terminate = (reason: string) => {\n if (phase === \"closed\") return;\n const wasEstablished = phase === \"established\";\n phase = \"closed\";\n clearTimers();\n try {\n socket.close();\n } catch {\n // Already closed/closing.\n }\n if (isClosedByClient) return;\n if (wasEstablished) {\n onDisconnect(reason);\n } else {\n reject(new Error(reason));\n }\n };\n\n const send = (message: Record<string, unknown>) => {\n if (socket.readyState !== WEB_SOCKET_OPEN_STATE) return;\n socket.send(JSON.stringify(message));\n };\n\n const startHandshakeTimer = (step: string) => {\n if (handshakeTimer) clearTimeout(handshakeTimer);\n handshakeTimer = setTimeout(() => {\n terminate(`Timed out waiting for ${step}`);\n }, HANDSHAKE_TIMEOUT_MILLISECONDS);\n };\n\n socket.addEventListener(\"open\", () => {\n if (phase === \"closed\") return;\n send({ type: \"connection_init\" });\n startHandshakeTimer(\"connection_ack\");\n });\n\n socket.addEventListener(\"message\", (event) => {\n if (phase === \"closed\") return;\n\n let message: ServerMessage;\n try {\n message = JSON.parse(String(event.data)) as ServerMessage;\n } catch {\n console.warn(\"[EloquentChatSDK] Unparseable realtime frame ignored\");\n return;\n }\n\n switch (message.type) {\n case \"connection_ack\": {\n if (phase !== \"connecting\") return;\n phase = \"subscribing\";\n if (typeof message.connectionTimeoutMs === \"number\") {\n connectionTimeoutMilliseconds = message.connectionTimeoutMs;\n }\n send({\n type: \"subscribe\",\n id: subscriptionId,\n channel,\n authorization,\n });\n startHandshakeTimer(\"subscribe_success\");\n return;\n }\n case \"connection_error\": {\n terminate(`Connection error: ${formatErrors(message.errors)}`);\n return;\n }\n case \"subscribe_success\": {\n if (phase !== \"subscribing\" || message.id !== subscriptionId) return;\n phase = \"established\";\n if (handshakeTimer) {\n clearTimeout(handshakeTimer);\n handshakeTimer = null;\n }\n lastLivenessTimestamp = Date.now();\n keepAliveTimer = setInterval(() => {\n if (\n Date.now() - lastLivenessTimestamp >\n connectionTimeoutMilliseconds\n ) {\n terminate(\"Keep-alive timeout\");\n }\n }, KEEP_ALIVE_CHECK_INTERVAL_MILLISECONDS);\n resolve({\n close: () => {\n isClosedByClient = true;\n send({ type: \"unsubscribe\", id: subscriptionId });\n terminate(\"Closed by client\");\n },\n });\n return;\n }\n case \"subscribe_error\": {\n if (message.id !== subscriptionId) return;\n terminate(`Subscribe error: ${formatErrors(message.errors)}`);\n return;\n }\n case \"ka\": {\n lastLivenessTimestamp = Date.now();\n return;\n }\n case \"data\": {\n if (message.id !== subscriptionId) return;\n // A busy channel can delay ka frames; data proves liveness too\n // (mirrors the amplify client).\n lastLivenessTimestamp = Date.now();\n // The event field is a JSON *string* per the protocol.\n let payload: unknown = message.event;\n if (typeof payload === \"string\") {\n try {\n payload = JSON.parse(payload);\n } catch {\n console.warn(\n \"[EloquentChatSDK] Unparseable realtime event ignored\",\n );\n return;\n }\n }\n onEvent(payload);\n return;\n }\n case \"broadcast_error\": {\n console.warn(\n \"[EloquentChatSDK] Realtime broadcast error:\",\n formatErrors(message.errors),\n );\n return;\n }\n default:\n // unsubscribe_success and unknown/future frame types.\n return;\n }\n });\n\n socket.addEventListener(\"close\", () => {\n terminate(\"WebSocket closed\");\n });\n\n socket.addEventListener(\"error\", () => {\n // A close event follows an error; terminate here anyway so failures\n // that never fire close (some environments) still reject/notify.\n terminate(\"WebSocket error\");\n });\n });\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 toZod() {\n return (schema) => schema;\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}\n// the accessor lives on a shared prototype: an own accessor makes every box a dictionary-mode object (~360 B and a slow load per read against ~100 B and an inlined getter here)\nclass Cached {\n constructor(getter) {\n this._getter = getter;\n this._value = undefined;\n }\n get value() {\n const getter = this._getter;\n if (getter !== undefined) {\n this._value = getter();\n this._getter = undefined;\n }\n return this._value;\n }\n}\nexport function cached(getter) {\n return new Cached(getter);\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 // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin.\n const tolerance = 4 * 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}\n/**\n * Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it.\n *\n * Its keys and descriptors read without invoking anything, which is what lets a discriminated union check its discriminator, and the cycle walk read a shape, without resolving a getter that references the schema being constructed. A def that answers `shape` from an accessor of its own has none.\n */\nexport function rawShape(def) {\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n return desc?.get ? desc.get.raw : desc?.value;\n}\n// where a builder reads its source's keys and descriptors, resolving only a shape a def answers for itself. A shape resolves by object spread, so only its enumerable keys are ever part of it.\nfunction sourceShape(schema) {\n return rawShape(schema._zod.def) ?? schema._zod.def.shape;\n}\n// a key whose value is not settled yet, self-caching so every read after the first gets the same one\nfunction deferProp(target, key, getter) {\n Object.defineProperty(target, key, {\n get() {\n const value = getter();\n assignProp(this, key, value);\n return value;\n },\n enumerable: true,\n configurable: true,\n });\n}\n// Writes a settled key. A plain assignment is much cheaper than `defineProperty` and produces the same descriptor, but it runs whatever setter already answers to the key — an accessor this shape deferred, or an inherited one, which `__proto__` has on every object and prototype pollution can add for any name.\nfunction putProp(target, key, value) {\n if (key in target)\n assignProp(target, key, value);\n else\n target[key] = value;\n}\n/**\n * Copies `keys` of `source`'s shape onto `target`, each value passed through `wrap`.\n *\n * A key the source has resolved is copied through now, so the derived shape states it outright and nothing has to resolve it to learn what it holds. A key the source still defers stays deferred, and reads back through the source's own `shape`, so it resolves once and both shapes get that one schema.\n */\nfunction mirrorShape(target, source, keys, wrap) {\n const raw = sourceShape(source);\n for (const key of keys) {\n const desc = Object.getOwnPropertyDescriptor(raw, key);\n if (!desc.enumerable)\n continue;\n if (desc.get) {\n deferProp(target, key, () => {\n const value = source._zod.def.shape[key];\n return wrap ? wrap(value, key) : value;\n });\n }\n else\n putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);\n }\n}\n// same, for a plain shape a caller passed rather than a schema's\nfunction mirrorProps(target, source) {\n for (const key of Reflect.ownKeys(source)) {\n const desc = Object.getOwnPropertyDescriptor(source, key);\n if (!desc.enumerable)\n continue;\n if (desc.get)\n deferProp(target, key, () => source[key]);\n else\n putProp(target, key, desc.value);\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` 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 !== undefined && shape[k]._zod.optout === \"optional\";\n });\n}\n// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle.\nexport const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({\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 newShape = {};\n mirrorShape(newShape, schema, maskedKeys(schema, mask));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\n// the mask keys that select something, checked against the source's shape without resolving it\nfunction maskedKeys(schema, mask) {\n const raw = sourceShape(schema);\n const keys = [];\n // `for...in` skips symbols, so a symbol in the mask would select nothing\n for (const key of Reflect.ownKeys(mask)) {\n if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) {\n throw new Error(`Unrecognized key: \"${String(key)}\"`);\n }\n if (mask[key])\n keys.push(key);\n }\n return keys;\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 omitted = new Set(maskedKeys(schema, mask));\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key)));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\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. Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = sourceShape(schema);\n for (const key of Reflect.ownKeys(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 return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\n// the source's keys, then the caller's overlaid on top\nfunction extended(schema, shape) {\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));\n mirrorProps(newShape, shape);\n return newShape;\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\nexport function merge(a, b) {\n if (!b?._zod?.def) {\n throw new Error(\"Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.\");\n }\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 newShape = {};\n mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a)));\n mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b)));\n const def = mergeDefs(a._zod.def, {\n shape: newShape,\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, name = \"partial\") {\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(`.${name}() cannot be used on object schemas containing refinements`);\n }\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class &&\n ((value, key) => (selected && !selected.has(key) ? value : new Class({ type: \"optional\", innerType: value }))));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] }));\n}\nexport function required(Class, schema, mask) {\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => \n // overwrite with non-optional\n selected && !selected.has(key) ? value : new Class({ type: \"nonoptional\", innerType: value }));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape }));\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). 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}\n/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */\n/** The leading size checks of `defChecks` that set an upper bound, each paired with it. */\nexport function sizeCaps(defChecks) {\n const caps = [];\n for (const ch of defChecks ?? []) {\n const d = ch._zod.def;\n // a later check may rewrite the value\n if (!/_(length|size)$|_equals$/.test(d.check))\n break;\n const max = d.maximum ?? d.length ?? d.size;\n if (max >= 0)\n caps.push([max, ch]);\n }\n return caps;\n}\nexport function attachSchema(issues, start, inst) {\n var _a;\n for (let i = start; i < issues.length; i++) {\n (_a = issues[i]).schema ?? (_a.schema = inst);\n }\n}\nexport function finalizeIssue(iss, ctx, config) {\n var _a;\n // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead.\n const traits = iss.inst?._zod?.traits;\n if (traits?.has(\"$ZodType\")) {\n if (traits.has(\"$ZodCheck\"))\n (_a = iss).schema ?? (_a.schema = iss.inst);\n else\n iss.schema = iss.inst;\n }\n // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's.\n const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(schemaError?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n // an explicit own-key copy beats object rest with excluded keys, which v8 routes through a generic runtime call; Object.keys rather than for-in so an issue pushed with a prototype does not leak inherited keys, and an own __proto__ key is dropped rather than assigned through the setter\n const full = {};\n for (const k of Object.keys(iss)) {\n if (k === \"inst\" || k === \"schema\" || k === \"continue\" || k === \"input\" || k === \"__proto__\")\n continue;\n full[k] = iss[k];\n }\n full.path ?? (full.path = []);\n full.message = message;\n if (ctx?.reportInput) {\n full.input = iss.input;\n }\n return full;\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}\nconst highSurrogate = /[\\uD800-\\uDBFF]/;\n// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters.\nexport function codePointLength(str) {\n const units = str.length;\n if (!highSurrogate.test(str))\n return units;\n let count = units;\n for (let i = 0; i < units - 1; i++) {\n if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n count--;\n i++;\n }\n }\n return count;\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////////// PROTOTYPE INSTALLERS //////////\n//\n// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see \"The three axes\" in AGENTS.md.\n/**\n * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working.\n *\n * Call this from a `proto` initializer, which runs once per prototype — never per instance.\n */\nexport function members(proto, table) {\n for (const key in table) {\n const desc = Object.getOwnPropertyDescriptor(table, key);\n // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was\n if (desc.get)\n Object.defineProperty(proto, key, { ...desc, enumerable: false });\n // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()`\n else\n defineBound(proto, key, desc.value);\n }\n}\n/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */\nexport function own(inst, key, value, enumerable = true) {\n Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });\n return value;\n}\n/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */\nexport function hide(inst, key, value) {\n return own(inst, key, value, false);\n}\n/** Adds members a table derives from the instance: each builds on first read and shadows as own data, and assignment shadows the same way, as when these were own properties. */\nexport /*@__NO_SIDE_EFFECTS__*/ function derived(computes, table) {\n for (const key in computes) {\n const compute = computes[key];\n // an object literal's accessor is configurable and enumerable, and `members` copies the descriptor as written\n Object.defineProperty(table, key, {\n configurable: true,\n enumerable: true,\n get() {\n return own(this, key, compute(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n }\n return table;\n}\nfunction defineBound(proto, key, fn) {\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method\n return this == null ? fn : own(this, key, fn.bind(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n}\n/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */\nfunction claim(inst, sentinel) {\n const proto = Object.getPrototypeOf(inst);\n // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines.\n return sentinel in proto ? undefined : proto;\n}\n// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped.\nlet installing;\n// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation.\nlet broke = false;\nconst breaker = {\n configurable: true,\n get() {\n broke = true;\n return undefined;\n },\n};\n/**\n * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s\n * constructor, computed from the internals object itself and cached there on\n * first read. One accessor per constructor rather than one per instance.\n */\nexport function defineLazyInternal(inst, key, compute) {\n const proto = Object.getPrototypeOf(inst._zod);\n if (key in proto && installing !== inst._zod) {\n // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type.\n installing = undefined;\n return;\n }\n installing = inst._zod;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again.\n Object.defineProperty(this, key, breaker);\n const outer = broke;\n broke = false;\n try {\n const value = compute(this);\n // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included.\n if (broke)\n delete this[key];\n else\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n broke = broke || outer;\n return value;\n }\n catch (err) {\n // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read.\n delete this[key];\n broke = broke || outer;\n throw err;\n }\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n },\n });\n}\n/**\n * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own\n * data property. One accessor per constructor rather than one per instance, because an own accessor\n * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel.\n */\nexport function installLazyProp(inst, key, make, enumerable) {\n const proto = claim(inst, key);\n if (!proto)\n return;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid.\n const desc = { configurable: true, writable: true, enumerable, value: undefined };\n Object.defineProperty(this, key, desc);\n // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches\n desc.value = make(this);\n Object.defineProperty(this, key, desc);\n return desc.value;\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });\n },\n });\n}\n/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */\nexport const CONSTANT_CATCH = \"~constantCatch\";\n/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */\nexport function constantCatch(value) {\n const fn = () => value;\n fn[CONSTANT_CATCH] = true;\n return fn;\n}\n","var _a;\nimport { members as installMembers } from \"./util.js\";\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\n/* Shared descriptor for installing `_zod`; defineProperty reads it\n * synchronously, so reusing one object avoids a per-instance allocation. */\nconst _zodDesc = { value: undefined, enumerable: false };\n// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error\nlet _E = \"captureStackTrace\" in Error ? Error : null;\n// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot\nfunction newError(Definition) {\n const E = _E;\n if (E) {\n const saved = E.stackTraceLimit;\n if (typeof saved === \"number\") {\n try {\n E.stackTraceLimit = 0;\n }\n catch {\n _E = null;\n return new Definition();\n }\n try {\n return new Definition();\n }\n finally {\n E.stackTraceLimit = saved;\n }\n }\n }\n return new Definition();\n}\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, \n/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */\nproto, params) {\n // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance.\n const zodProto = {};\n // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy.\n function Internals(def) {\n this.def = def;\n this.constr = _;\n this.traits = new Set();\n }\n Internals.prototype = zodProto;\n const protoMembers = proto;\n // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait.\n const initialized = protoMembers && new WeakSet();\n function init(inst, def) {\n if (!inst._zod) {\n _zodDesc.value = new Internals(def);\n try {\n Object.defineProperty(inst, \"_zod\", _zodDesc);\n }\n finally {\n // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next.\n _zodDesc.value = undefined;\n }\n }\n else if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n if (initialized) {\n // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before.\n const own = Object.getPrototypeOf(inst);\n const ctorProto = inst._zod.constr.prototype;\n let up = own;\n while (up && up !== ctorProto)\n up = Object.getPrototypeOf(up);\n const target = up ?? own;\n if (!initialized.has(target)) {\n initialized.add(target);\n installMembers(target, protoMembers);\n }\n }\n // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype\n const proto = _.prototype;\n for (const k in proto) {\n if (!Object.prototype.hasOwnProperty.call(proto, k))\n continue;\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 const inst = params?.Parent ? newError(Definition) : this;\n init(inst, def);\n const deferred = inst._zod.deferred;\n if (deferred) {\n for (const fn of deferred) {\n fn();\n }\n // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime.\n inst._zod.deferred = undefined;\n }\n // Global post-processor hook. Internal: installed by `import \"zod/compile\"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation.\n const pp = globalThis.__zod_globalConfig?.postProcessor;\n if (pp)\n pp(inst);\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 = /*@__PURE__*/ 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 { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\n/* Computing the message eagerly is expensive (pretty-printed JSON of all\n * issues), so defer it until first read. The accessor functions and\n * descriptors are shared across instances to keep error construction\n * cheap; the computed message is cached on the internals object. The\n * setter preserves plain assignment semantics for consumers that\n * overwrite `message`. */\nfunction _getMessage() {\n const internals = this._zod;\n internals.message ?? (internals.message = JSON.stringify(internals.def, util.jsonStringifyReplacer, 2));\n return internals.message;\n}\nfunction _setMessage(value) {\n this._zod.message = value;\n}\nconst _messageDesc = {\n get: _getMessage,\n set: _setMessage,\n enumerable: true,\n configurable: true,\n};\nconst _issuesDesc = { value: undefined, enumerable: false };\n/* Prototypes that already carry the lazy `toString`. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n // `_zod` is already non-enumerable: $constructor's init defined it with this same descriptor\n _issuesDesc.value = def;\n Object.defineProperty(inst, \"issues\", _issuesDesc);\n // Clear the shared slot; a retained `value` pins the last error's issues.\n _issuesDesc.value = undefined;\n Object.defineProperty(inst, \"message\", _messageDesc);\n /* `toString` lives as a non-enumerable lazy getter on the shared\n * prototype; on first access it caches a per-instance closure so\n * detached usage still works. */\n const proto = Object.getPrototypeOf(inst);\n if (!_installedToString.has(proto)) {\n _installedToString.add(proto);\n Object.defineProperty(proto, \"toString\", {\n configurable: true,\n enumerable: false,\n get() {\n const value = () => this.message;\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n },\n });\n }\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, undefined, {\n Parent: Error,\n});\n/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member\n * (\"toString\", \"constructor\") would otherwise read through to the prototype, and assigning\n * \"__proto__\" would hit the setter instead of creating a key. */\nfunction node(obj, key, make) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) {\n if (key === \"__proto__\") {\n Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });\n }\n else {\n obj[key] = make();\n }\n }\n return obj[key];\n}\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 node(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 // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child.\n if (el === \"_errors\") {\n if (terminal)\n curr._errors.push(mapper(issue));\n i++;\n continue;\n }\n // A path element may collide with an inherited property name such as\n // \"__proto__\" or \"constructor\". Truthiness checks read the prototype\n // (so no node is created, then ._errors.push throws), and bracket\n // assignment of \"__proto__\" hits the setter instead of creating an\n // own key. Guard the read with hasOwnProperty and create the node\n // with defineProperty so any path element becomes a real own key.\n if (!Object.prototype.hasOwnProperty.call(curr, el)) {\n Object.defineProperty(curr, el, {\n value: { _errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n const node = curr[el];\n if (terminal) {\n node._errors.push(mapper(issue));\n }\n curr = node;\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;\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 // el may collide with an inherited property name (\"__proto__\",\n // \"constructor\", ...); ??= reads the prototype so the node is never\n // created and curr.errors.push throws. Guard with hasOwnProperty and\n // create the node with defineProperty so \"__proto__\" becomes a real\n // own key rather than invoking the prototype setter.\n if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) {\n Object.defineProperty(curr.properties, el, {\n value: { errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_a = curr.items)[el] ?? (_a[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\";\n// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two.\nfunction finalizeParams(callee, params) {\n return { callee: params?.callee ?? callee, Err: params?.Err };\n}\nexport const _parse = (_Err) => {\n const fn = (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 ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => {\n const fn = 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 ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\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 ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\n// the error is built on the first read of `error`: finalizing the issues and constructing the instance is most of a failing parse, and a caller that only branches on `success` never pays it. a getter in the literal keeps this small; the alternative, one shared accessor descriptor plus a hidden state slot, reads ~15% faster but costs ~75 B gzipped in every bundle\nfunction failure(Err, issues, ctx) {\n let error;\n return {\n success: false,\n get error() {\n if (!error) {\n error = new Err(issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n // finalizeIssue drops `input`, so the built error holds nothing; keeping the raw issues past this point pins the parsed value for the life of the result\n issues = undefined;\n ctx = undefined;\n }\n return error;\n },\n set error(e) {\n error = e;\n // a replacement makes the getter's branch unreachable, so the captures have to go here too\n issues = undefined;\n ctx = undefined;\n },\n };\n}\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 ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\n// registry mirrors of the compiler's sentinels, so this module never imports the compiler\nconst COMPILE_INVALID = /* @__PURE__ */ Symbol.for(\"zod.compile.invalid\");\nconst COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for(\"zod.compile.fallback\");\n// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema.\nexport const validate = ((schema, value, _ctx) => {\n const validator = schema._zod.bag.validator;\n if (validator !== undefined) {\n if (validator(value) !== COMPILE_INVALID)\n return true;\n // a definite sentinel means the runtime would reject, so skip the re-parse; a ctx can still change the answer\n if (validator.definite === true && _ctx === undefined)\n return false;\n }\n return validateFallback(schema, value, _ctx);\n});\nfunction validateFallback(schema, value, _ctx) {\n const ctx = _ctx\n ? { ..._ctx, async: false, abortEarly: true }\n : { async: false, abortEarly: true };\n const fallbackRun = schema._zod.bag.fallbackRun;\n let result;\n if (fallbackRun) {\n // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound\n ctx[COMPILE_FALLBACK] = true;\n result = fallbackRun({ value, issues: [] }, ctx);\n }\n else {\n result = schema._zod.run({ value, issues: [] }, ctx);\n }\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length === 0;\n}\n// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw\nexport const validateAsync = async (schema, value, _ctx) => {\n const ctx = _ctx\n ? { ..._ctx, async: true, abortEarly: true }\n : { async: true, abortEarly: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length === 0;\n};\nexport const _encode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return parse(schema, value, ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n return parse(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params)));\n };\n return fn;\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\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-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\nexport function nanoidOfLength(length) {\n return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);\n}\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-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\n// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. The leading lookahead then demands one anchor — a pictograph, a regional indicator, or the enclosing keycap — because `\\p{Emoji_Component}` on its own covers ASCII digits, `#`, `*`, ZWJ, variation selectors and skin tone modifiers, none of which is an emoji without a base.\nconst _emoji = `^(?=[\\\\s\\\\S]*[\\\\p{Extended_Pictographic}\\\\p{Regional_Indicator}\\\\u20E3])[\\\\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}:){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}|:))\\/(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_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;\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 = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,63}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro).\nexport const creditCard = /^\\d(?:[ -]?\\d){11,18}$/;\n// ISO 4217 alpha codes from the SIX list, regenerated by scripts/update-iso-4217.ts\nexport const currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/;\n// iban electronic format: 2-letter country, check digits 02-98 (the only values `98 - remainder` can produce), 11-30 bban characters\nexport const iban = /^[A-Z]{2}(?!00|01|99)\\d{2}[A-Z0-9]{11,30}$/;\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])))`;\n/** Anchors a pattern source. The interpolation lives here rather than at the call site because\n * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it\n * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */\nfunction anchor(source) {\n return new RegExp(`^${source}$`);\n}\nexport const date = /*@__PURE__*/ anchor(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 : args.seconds\n ? `${hhmm}:[0-5]\\\\d(?:\\\\.\\\\d+)?`\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 opts = [\"Z\"];\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 // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them\n const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join(\"|\")})`;\n const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\n// the unbounded form of `string()` as a literal, so every plain string shares one instance instead of building its own\nexport const anyString = /^[\\s\\S]{0,}$/;\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","export const version = {\n major: 4,\n minor: 6,\n patch: 7,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync } 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 defChecks = inst._zod.def.checks;\n // if inst is itself a checks.$ZodCheck, run it as a check\n const checks = inst._zod.traits.has(\"$ZodCheck\")\n ? [inst, ...(defChecks ?? [])]\n : defChecks?.length\n ? [...defChecks]\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 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 if (payload.memo)\n return payload;\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 util.attachSchema(payload.issues, currLen, inst);\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 util.attachSchema(payload.issues, currLen, inst);\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 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}, {\n // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", standardProps(this));\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n});\n/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */\n// a Standard Schema result only reports issues, so a failure finalizes them straight off the raw payload: no ZodError, and no lazy result to read through\nconst toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())) } : { value: r.value };\nasync function validateAsync(inst, value) {\n const ctx = { async: true };\n return toStandardResult((await inst._zod.run({ value, issues: [] }, ctx)), ctx);\n}\nexport function standardProps(inst) {\n return {\n validate: (value) => {\n const ctx = { async: false };\n try {\n const r = inst._zod.run({ value, issues: [] }, ctx);\n if (!(r instanceof Promise))\n return toStandardResult(r, ctx);\n }\n catch (_) { }\n // async function so a synchronously throwing check rejects instead of escaping validate\n return validateAsync(inst, value);\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 // a format's own pattern, else unbounded; a template literal derives the check-aware form itself\n inst._zod.pattern = def.pattern ?? regexes.anyString;\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});\n/** The `://` guard rejected the input before the URL constructor saw it. */\nexport const URL_BAD_FORMAT = 1;\n/** The URL parser rejected the input. */\nexport const URL_UNPARSEABLE = 2;\nexport function canParseURL(input) {\n try {\n if (typeof URL !== \"undefined\" && typeof URL.canParse === \"function\")\n return URL.canParse(input);\n new URL(input);\n return true;\n }\n catch {\n return false;\n }\n}\nexport function validateURL(trimmed, def) {\n if (!(\"normalize\" in def) && !(\"hostname\" in def) && !(\"protocol\" in def)) {\n return canParseURL(trimmed) || URL_UNPARSEABLE;\n }\n return parseURLObject(trimmed, def);\n}\n/** Parses a URL while preserving the non-normalizing HTTP guard. */\nexport function parseURLObject(trimmed, def) {\n // When normalize is off, require :// for http/https URLs. This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source && !/^https?:\\/\\//i.test(trimmed)) {\n return URL_BAD_FORMAT;\n }\n try {\n if (typeof URL !== \"undefined\") {\n const URLStatic = URL;\n if (typeof URLStatic.parse === \"function\")\n return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;\n }\n // @ts-ignore\n return new URL(trimmed);\n }\n catch {\n return URL_UNPARSEABLE;\n }\n}\nconst asciiTabOrNewline = /[\\t\\n\\r]/g;\n/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL(\"https://exa\\nmple.com\")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */\nexport function stripTabAndNewline(value) {\n return value.replace(asciiTabOrNewline, \"\");\n}\nexport function urlHostnameOk(url, hostname) {\n hostname.lastIndex = 0;\n return hostname.test(url.hostname);\n}\nexport function urlProtocolOk(url, protocol) {\n protocol.lastIndex = 0;\n return protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol);\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 const url = validateURL(trimmed, def);\n if (url === URL_BAD_FORMAT) {\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 if (url === URL_UNPARSEABLE) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === true) {\n payload.value = stripTabAndNewline(trimmed);\n return;\n }\n if (def.hostname && !urlHostnameOk(url, def.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 if (def.protocol && !urlProtocolOk(url, def.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 // Set the output value based on normalize flag\n payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);\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 if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))\n throw new Error(`Invalid nanoid length: ${def.length}`);\n def.pattern ?? (def.pattern = def.length === undefined ? regexes.nanoid : regexes.nanoidOfLength(def.length));\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});\n/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL(\"http://[...]\")` parses an authority, not an address, so `@` and `\\` re-delimit it and `\"::@1\\\\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `\"::1\\n\"` validated as `::1`. */\nconst ipv6Alphabet = /^[0-9a-fA-F:.]+$/;\nexport function isValidIPv6(value) {\n if (!ipv6Alphabet.test(value))\n return false;\n return canParseURL(`http://[${value}]`);\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.check = (payload) => {\n if (!isValidIPv6(payload.value)) {\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});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport function isValidCIDRv6(value) {\n const parts = value.split(\"/\");\n if (parts.length !== 2)\n return false;\n const [address, prefix] = parts;\n if (!prefix)\n return false;\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n return false;\n if (prefixNum < 0 || prefixNum > 128)\n return false;\n return isValidIPv6(address);\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 if (!isValidCIDRv6(payload.value)) {\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}\n// lax on purpose: the quantified regexes.base64 overflows the regex stack on multi-MB input and its leading ^$| alternation leaks through template-literal composition; isValidBase64 enforces length and padding\nexport const base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = base64Charset);\n $ZodStringFormat.init(inst, def);\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////////////////////////////// ZodBase64URL //////////////////////////////\n// lax on purpose: the quantified regexes.base64url overflows the regex stack on multi-MB input; isValidBase64 enforces length on the padded string\nexport const base64urlCharset = /^[A-Za-z0-9_-]*$/;\nexport function isValidBase64URL(data) {\n if (!base64urlCharset.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 = base64urlCharset);\n $ZodStringFormat.init(inst, def);\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////////////////////////////// ZodCreditCard //////////////////////////////\nconst CC_SANITIZE = /[- ]/g;\n/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */\nfunction isLuhnAlgo(digits) {\n let length = digits.length;\n let bit = 1;\n let sum = 0;\n while (length) {\n const value = digits.charCodeAt(--length) - 48;\n bit ^= 1;\n sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value;\n }\n return sum % 10 === 0;\n}\nexport function isValidCreditCard(input) {\n if (!regexes.creditCard.test(input))\n return false;\n return isLuhnAlgo(input.replace(CC_SANITIZE, \"\"));\n}\nexport const $ZodCreditCard = /*@__PURE__*/ core.$constructor(\"$ZodCreditCard\", (inst, def) => {\n // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone.\n def.pattern ?? (def.pattern = regexes.creditCard);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidCreditCard(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"credit_card\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodIBAN //////////////////////////////\n// iso 7064 mod 97-10 checksum without BigInt\nfunction isIso7064Mod97(iban) {\n let remainder = 0;\n const len = iban.length;\n for (let i = 4; i < len; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n for (let i = 0; i < 4; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n return remainder === 1;\n}\nexport function isValidIBAN(input) {\n if (!regexes.iban.test(input))\n return false;\n return isIso7064Mod97(input);\n}\nexport const $ZodIBAN = /*@__PURE__*/ core.$constructor(\"$ZodIBAN\", (inst, def) => {\n // shape only — checksum is not expressible as a pattern\n def.pattern ?? (def.pattern = regexes.iban);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidIBAN(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"iban\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\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 = 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 ? String(input)\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});\n// an oversized container fails its leading size checks before any element is parsed\nfunction capSize(inst, size) {\n const caps = util.sizeCaps(inst._zod.def.checks);\n if (!caps.length)\n return;\n const cap = Math.min(...caps.map((c) => c[0]));\n const parse = inst._zod.parse;\n inst._zod.parse = (payload, ctx) => {\n const n = size(payload.value);\n if (n > cap && !ctx?.skipChecks && ctx?.direction !== \"backward\") {\n for (const [max, ch] of util.sizeCaps(inst._zod.def.checks)) {\n if (n > max && ch._zod.def.when(payload)) {\n const start = payload.issues.length;\n ch._zod.check(payload);\n // the value is still the raw input, so no later check may read it\n payload.issues[start].continue = false;\n util.attachSchema(payload.issues, start, inst);\n return payload;\n }\n }\n }\n return parse(payload, ctx);\n };\n}\nconst arraySize = (input) => (Array.isArray(input) ? input.length : -1);\nconst mapSize = (input) => (input instanceof Map ? input.size : -1);\nconst setSize = (input) => (input instanceof Set ? input.size : -1);\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 const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\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 = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);\n const proms = [];\n const abortEarly = ctx?.abortEarly;\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 // the element's payload is authoritative here, since handleArrayResult forwards every issue; an object's is not, because it drops a failed absent optional\n if (abortEarly && result.issues.length !== 0 && util.aborted(result))\n break;\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n capSize(inst, arraySize);\n});\nfunction handlePropertyResult(result, final, key, input, optin, optout) {\n const isPresent = key in input;\n const isOptionalOut = optout === \"optional\";\n // The middle rung means \"absence permitted, nothing supplied in its place\", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key.\n if (!isPresent && isOptionalOut && optin === \"optional\") {\n return;\n }\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (optin !== undefined && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && optin === undefined) {\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 || (optin === \"defaulted\" && !isOptionalOut)) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\n// one shared instance; a fresh [] per schema cost 56 bytes retained\nconst NO_SYMBOL_KEYS = [];\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n const ownSymbols = Object.getOwnPropertySymbols(def.shape);\n const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;\n // aliases `keys` when there are no symbols, so a string-only shape keeps one array\n const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;\n for (const k of allKeys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${String(k)}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n allKeys,\n symbolKeys,\n // string-only: handleCatchall matches it against `for...in`, which never yields a symbol\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const optin = _catchall.optin;\n const optout = _catchall.optout;\n // starts at 0, not the current length: the shape phase already ran and may have aborted\n let seen = 0;\n for (const key in input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output.\n if (keySet.has(key))\n continue;\n // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping.\n if (key === \"__proto__\") {\n if (t === \"never\")\n unrecognized.push(key);\n continue;\n }\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, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand.\n continue: true,\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 desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n // a cloned def carries its source's accessor, which knows the shape it answers from; adopting that keeps the clone's keys readable without running it\n const sh = desc?.get ? desc.get.raw : (def.shape ?? {});\n if (sh) {\n // Freezes the shape on first read, so its getters resolve once and every later read sees the same schemas.\n const get = () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", { value: newSh });\n get.raw = newSh;\n return newSh;\n };\n get.raw = sh;\n Object.defineProperty(def, \"shape\", { get });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const shape = zod.def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n if (!Object.prototype.hasOwnProperty.call(propValues, key)) {\n util.assignProp(propValues, key, new Set());\n }\n for (const v of field.values)\n propValues[key].add(v);\n // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it.\n if (field.optin !== undefined)\n propValues[key].add(undefined);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\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 = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const proms = [];\n const shape = value.shape;\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const key of value.allKeys) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n if (key === \"__proto__\")\n continue;\n const el = shape[key];\n const optin = el._zod.optin;\n const optout = el._zod.optout;\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, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\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, abortEarly === true);\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 memo = core.globalConfig.memoizer;\n const generateFastpass = (shape) => {\n const normalized = _normalized.value;\n const syms = normalized.symbolKeys;\n // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope\n const doc = new Doc([\"payload\", \"ctx\"], { shape, inst, memo, syms });\n const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n // prefixes in place, like util.prefixIssues. newResult must land before the early return: a catchall runs after this and would otherwise write onto the caller's input\n const prefixStr = (id, k) => `\n let ${id}_ab = false;\n for (let i = 0; i < ${id}.issues.length; i++) {\n const iss = ${id}.issues[i];\n iss.path = iss.path ? [${k}, ...iss.path] : [${k}];\n payload.issues.push(iss);\n if (iss.continue !== true) ${id}_ab = true;\n }\n if (${id}_ab && ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }`;\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.allKeys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);\n for (const key of normalized.allKeys) {\n if (key === \"__proto__\")\n continue;\n const id = ids[key];\n const k = typeof key === \"symbol\" ? `syms[${syms.indexOf(key)}]` : util.esc(key);\n const isPresent = `${k} in input`;\n const schema = shape[key];\n const optin = schema?._zod?.optin;\n const isOptionalIn = optin !== undefined;\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(k)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all.\n const assign = optin === \"optional\" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;\n doc.write(`\n const ${id}_present = ${isPresent};\n if (!${id}.issues.length || ${id}_present) {\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n\n if (${assign}) {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${isPresent};\n if (${id}.issues.length) {${prefixStr(id, k)}\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 if (ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }\n }\n\n if (${id}_present) {\n newResult[${k}] = ${id}.value;\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n `);\n if (optin === \"defaulted\") {\n doc.write(`newResult[${k}] = ${id}.value;`);\n }\n else {\n doc.write(`\n if (${id}.value !== undefined || ${isPresent}) {\n newResult[${k}] = ${id}.value;\n }\n `);\n }\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone\n return doc.compile();\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, ctx?.abortEarly === true);\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.defineLazyInternal(inst, \"optin\", (zod) => zod.def.options.some((o) => o._zod.optin === \"defaulted\")\n ? \"defaulted\"\n : zod.def.options.some((o) => o._zod.optin !== undefined)\n ? \"optional\"\n : undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n if (zod.def.options.every((o) => o._zod.values)) {\n return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n if (zod.def.options.every((o) => o._zod.pattern)) {\n const patterns = zod.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 matches = [];\n for (let i = 0; i < results.length; i++) {\n if (results[i].issues.length === 0)\n matches.push(i);\n }\n if (matches.length === 1) {\n final.value = results[matches[0]].value;\n return final;\n }\n if (matches.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 matches,\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});\n/** Returns the option whose discriminator claims `value`, or throws if ambiguous. */\nexport function getDiscriminatedOption(union, value) {\n const internals = union._zod;\n let map = internals.bag.optionsMap;\n if (!map) {\n map = discriminatorMap(internals.def);\n internals.bag.optionsMap = map;\n }\n const option = map.get(value);\n if (option === null)\n throw new Error(`Ambiguous discriminator value \"${String(value)}\"`);\n return option;\n}\nfunction discriminatorMap(def) {\n const map = new Map();\n for (const option of def.options) {\n const values = option._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const value of values) {\n if (map.has(value)) {\n if (value !== undefined)\n throw new Error(`Duplicate discriminator value \"${String(value)}\"`);\n // keep the collision marked so a later member cannot reclaim it\n map.set(value, null);\n }\n else {\n map.set(value, option);\n }\n }\n }\n return map;\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.defineLazyInternal(inst, \"propValues\", (zod) => {\n const propValues = {};\n let undefinedCount = 0;\n for (const option of zod.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 \"${zod.def.options.indexOf(option)}\"`);\n if (pv[zod.def.discriminator]?.has(undefined))\n undefinedCount++;\n for (const [k, v] of Object.entries(pv)) {\n if (!Object.prototype.hasOwnProperty.call(propValues, k)) {\n util.assignProp(propValues, k, new Set());\n }\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n if (!zod.def.unionFallback && undefinedCount > 1)\n propValues[zod.def.discriminator]?.delete(undefined);\n return propValues;\n });\n // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes and lazies — are left to the map.\n def.options.forEach((option, i) => {\n const propShape = util.rawShape(option._zod.def);\n if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {\n throw new Error(`Invalid discriminated union option at index \"${i}\"`);\n }\n });\n const disc = util.cached(() => discriminatorMap(def));\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 value = input?.[def.discriminator];\n const opt = disc.value.get(value);\n // forward metadata cannot choose an encoder for an absent tag\n if (opt && (value !== undefined || ctx.direction !== \"backward\")) {\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 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()).filter((value) => disc.value.get(value) !== null),\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});\nexport function 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 if (Object.prototype.hasOwnProperty.call(newObj, \"__proto__\"))\n delete newObj.__proto__;\n for (const key of sharedKeys) {\n if (key === \"__proto__\")\n continue;\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) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key.\n const unrecKeys = new Map();\n let unrecIssue;\n const keyIssues = new Map();\n const collect = (iss, side) => {\n let keys;\n if (iss.code === \"unrecognized_keys\" && !iss.path?.length) {\n unrecIssue ?? (unrecIssue = iss);\n keys = iss.keys;\n }\n else if (iss.code === \"invalid_key\" && iss.origin === \"record\" && iss.path?.length === 1) {\n const k = String(iss.path[0]);\n if (!keyIssues.has(k))\n keyIssues.set(k, iss);\n keys = [k];\n }\n else {\n return false;\n }\n for (const k of keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k)[side] = true;\n }\n return true;\n };\n for (const iss of left.issues) {\n if (!collect(iss, \"l\"))\n result.issues.push(iss);\n }\n for (const iss of right.issues) {\n if (!collect(iss, \"r\"))\n result.issues.push(iss);\n }\n // Report only keys rejected by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length) {\n const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];\n if (aggregated.length)\n result.issues.push({ ...unrecIssue, keys: aggregated });\n for (const k of bothKeys) {\n if (!aggregated.includes(k) && keyIssues.has(k))\n result.issues.push(keyIssues.get(k));\n }\n }\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n if (util.aborted(result))\n return result;\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 const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\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 = memo ? memo.alloc(inst, payload, [], ctx) : [];\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 array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n // only tracked when there is a rest loop to skip\n const abortEarly = def.rest ? ctx?.abortEarly : undefined;\n let itemAborted = false;\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 if (abortEarly && !itemAborted && r.issues.length)\n itemAborted = util.aborted(r);\n }\n }\n // sound because rest is non-empty exactly when every fixed index is present, the one case handleTupleResults cannot discard an item's issues\n if (def.rest && !itemAborted) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n let seen = payload.issues.length;\n for (const el of rest) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\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 // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued.\n const omittable = key === \"optin\" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === \"optional\";\n if (!omittable)\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 rule, but only after `optoutStart`: the first index where the output 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 // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`.\n if (!isPresent && i >= optoutStart && items[i]._zod.optin === \"optional\") {\n final.value.length = i;\n break;\n }\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 const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\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 // no guard in either loop below: a record's invalid_key aborts but an enclosing intersection can reconcile it, so a stopped loop hides keys the sibling does not own and the intersection then rejects nothing\n const proms = [];\n const values = def.keyType._zod.values;\n if (values && !def.partial) {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\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 // A declared __proto__ is stripped but is not an unrecognized key.\n if (key === \"__proto__\")\n continue;\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 if (outKey === \"__proto__\")\n continue;\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 if (def.mode === \"loose\") {\n // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n payload.value[key] = input[key];\n }\n else {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n else {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection.\n let unrecognized;\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). 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 if (values) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(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 // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\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 if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\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 const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\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 = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const [key, value] of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\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 capSize(inst, mapSize);\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 const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\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 = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const item of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\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 capSize(inst, setSize);\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 util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const patternValues = util.getEnumValues(zod.def.entries).filter((k) => util.propertyKeyTypes.has(typeof k));\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(patternValues.length ? `^(${patternValues.map((o) => util.escapeRegex(o.toString())).join(\"|\")})$` : \"^[^\\\\s\\\\S]$\");\n });\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 const values = new Set(def.values);\n inst._zod.values = values;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const vals = zod.def.values;\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(vals.length\n ? `^(${vals\n .map((o) => typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o))\n .join(\"|\")})$`\n : \"^[^\\\\s\\\\S]$\");\n });\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 core.globalConfig.memoizer?.guard(inst);\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 return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(payload, result) {\n // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it.\n payload.value = result.issues.length ? undefined : result.value;\n return payload;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung.\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n inst._zod.optout = \"optional\";\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const values = zod.def.innerType._zod.values;\n return values ? new Set([...values, undefined]) : undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (payload.value === undefined) {\n // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means.\n if (def.innerType._zod.optin !== \"defaulted\")\n return payload;\n // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it.\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise)\n return result.then((result) => handleOptionalResult(payload, result));\n return handleOptionalResult(payload, result);\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.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.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.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazyInternal(inst, \"values\", (zod) => {\n return zod.def.innerType._zod.values ? new Set([...zod.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 = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.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 = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.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.defineLazyInternal(inst, \"values\", (zod) => {\n const v = zod.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});\nfunction handleCatchResult(payload, result, def, ctx) {\n if (!result.issues.length) {\n payload.value = result.value;\n // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property.\n if (result.memo)\n payload.memo = true;\n return payload;\n }\n // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call.\n payload.value = def.catchValue({\n ...result,\n value: payload.value,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n return payload;\n}\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.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({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleCatchResult(payload, result, def, ctx));\n }\n return handleCatchResult(payload, result, def, ctx);\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.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.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 // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it.\n if (left.issues.some((iss) => iss.code !== \"unrecognized_keys\")) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.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.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.innerType._zod.propValues);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType?._zod?.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.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 // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign.\n if (!payload.memo)\n payload.value = Object.freeze(payload.value);\n return payload;\n}\n// a leaf's pattern source with its own checks folded in: the last pattern-carrying check wins, else length bounds narrow the catch-all, else an integer format narrows the number form. the fold lives here instead of on `_zod.pattern` so a bundle without template literals never pays for it\nfunction leafPattern(schema) {\n const def = schema._zod.def;\n let pattern = def.pattern;\n let isInt = !!def.format?.includes(\"int\");\n let minimum;\n let maximum;\n for (const ch of def.checks ?? []) {\n const d = ch._zod.def;\n if (d.pattern)\n pattern = d.pattern;\n isInt || (isInt = !!d.format?.includes(\"int\"));\n const lo = d.minimum ?? d.length;\n const hi = d.maximum ?? d.length;\n if (lo !== undefined && (minimum === undefined || lo > minimum))\n minimum = lo;\n if (hi !== undefined && (maximum === undefined || hi < maximum))\n maximum = hi;\n }\n if (pattern)\n return pattern.source;\n // an empty range matches nothing at runtime, and `{8,5}` is not a legal quantifier\n if (minimum !== undefined && maximum !== undefined && minimum > maximum)\n return \"(?!)\";\n if (minimum !== undefined || maximum !== undefined)\n return regexes.string({ minimum, maximum }).source;\n const own = schema._zod.pattern;\n return (isInt && own === regexes.number ? regexes.integer : own)?.source;\n}\n// a part's pattern source. a wrapper's pattern embeds its inner pattern's source verbatim, so the folded form is substituted in place without knowing the wrapper's own composition; a union's options are joined the way the union builds its own pattern\nfunction partPattern(schema) {\n const def = schema._zod.def;\n const own = schema._zod.pattern?.source;\n // lazy resolves its inner on the internals, not the def\n const inner = def.innerType ?? schema._zod.innerType;\n if (inner) {\n const before = inner._zod.pattern?.source;\n const after = partPattern(inner);\n if (own && before && after && after !== before) {\n return own.replace(util.cleanRegex(before), () => util.cleanRegex(after));\n }\n return own;\n }\n if (def.options) {\n const sources = def.options.map(partPattern);\n if (sources.every(Boolean))\n return `^(${sources.map((s) => util.cleanRegex(s)).join(\"|\")})$`;\n }\n return leafPattern(schema);\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 const source = partPattern(part);\n if (!source) {\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n regexParts.push(util.cleanRegex(source));\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 // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter.\n Object.defineProperty(inst, \"_def\", { value: 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 // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function.\n return Object.defineProperty(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 }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return Object.defineProperty(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 }, \"_zod\", { value: inst._zod, enumerable: false });\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 lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, 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.defineLazyInternal(inst, \"pattern\", (zod) => zod.innerType?._zod?.pattern);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.innerType?._zod?.propValues);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.innerType?._zod?.optin ?? undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => 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","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\nfunction snapshotChecks(def) {\n if (def.checks)\n def.checks = [...def.checks];\n return def;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", coerce: true, ...util.normalizeParams(params) }));\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 _creditCard(Class, params) {\n return new Class({\n type: \"string\",\n format: \"credit_card\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _iban(Class, params) {\n return new Class({\n type: \"string\",\n format: \"iban\",\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(snapshotChecks({ type: \"number\", checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", coerce: true, checks: [], ...util.normalizeParams(params) }));\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 _properties(shape, params) {\n return new checks.$ZodCheckProperties({\n check: \"properties\",\n shape,\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: 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 : util.constantCatch(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 if (!(\"input\" in _issue))\n _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 codec._zod.bag.truthy = truthyArray;\n codec._zod.bag.falsy = falsyArray;\n codec._zod.bag.case = params.case ?? \"insensitive\";\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 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 * as core from \"../core/index.js\";\nimport * as regexes from \"../core/regexes.js\";\nimport * as util from \"../core/util.js\";\nimport * as parse from \"./parse.js\";\nexport const ZodMiniType = /*@__PURE__*/ core.$constructor(\"ZodMiniType\", (inst, def) => {\n if (!inst._zod)\n throw new Error(\"Uninitialized schema in ZodMiniType.\");\n core.$ZodType.init(inst, def);\n inst.def = def;\n inst.type = def.type;\n}, {\n // `with` is an alias for `check`: the same function object, not a wrapper.\n get with() {\n return this.check;\n },\n set with(value) {\n util.own(this, \"with\", value);\n },\n parse(data, params) {\n return parse.parse(this, data, params, { callee: this.parse });\n },\n parseAsync(data, params) {\n return parse.parseAsync(this, data, params, { callee: this.parseAsync });\n },\n safeParse(data, params) {\n return parse.safeParse(this, data, params);\n },\n safeParseAsync(data, params) {\n return parse.safeParseAsync(this, data, params);\n },\n check(...checks) {\n const def = this.def;\n return this.clone({\n ...def,\n checks: [\n ...(def.checks ?? []),\n ...checks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }, { parent: true });\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 apply(fn, ...args) {\n return args.length === 0 ? fn(this) : fn(this, ...args);\n },\n});\nexport const ZodMiniString = /*@__PURE__*/ core.$constructor(\"ZodMiniString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function string(params) {\n return core._string(ZodMiniString, params);\n}\nexport const ZodMiniStringFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n ZodMiniString.init(inst, def);\n});\nexport const ZodMiniEmail = /*@__PURE__*/ core.$constructor(\"ZodMiniEmail\", (inst, def) => {\n core.$ZodEmail.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function email(params) {\n return core._email(ZodMiniEmail, params);\n}\nexport const ZodMiniGUID = /*@__PURE__*/ core.$constructor(\"ZodMiniGUID\", (inst, def) => {\n core.$ZodGUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function guid(params) {\n return core._guid(ZodMiniGUID, params);\n}\nexport const ZodMiniUUID = /*@__PURE__*/ core.$constructor(\"ZodMiniUUID\", (inst, def) => {\n core.$ZodUUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function uuid(params) {\n return core._uuid(ZodMiniUUID, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function uuidv4(params) {\n return core._uuidv4(ZodMiniUUID, params);\n}\n// ZodMiniUUIDv6\n// @__NO_SIDE_EFFECTS__\nexport function uuidv6(params) {\n return core._uuidv6(ZodMiniUUID, params);\n}\n// ZodMiniUUIDv7\n// @__NO_SIDE_EFFECTS__\nexport function uuidv7(params) {\n return core._uuidv7(ZodMiniUUID, params);\n}\nexport const ZodMiniURL = /*@__PURE__*/ core.$constructor(\"ZodMiniURL\", (inst, def) => {\n core.$ZodURL.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function url(params) {\n return core._url(ZodMiniURL, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function httpUrl(params) {\n return core._url(ZodMiniURL, {\n protocol: regexes.httpProtocol,\n hostname: regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniEmoji = /*@__PURE__*/ core.$constructor(\"ZodMiniEmoji\", (inst, def) => {\n core.$ZodEmoji.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function emoji(params) {\n return core._emoji(ZodMiniEmoji, params);\n}\nexport const ZodMiniNanoID = /*@__PURE__*/ core.$constructor(\"ZodMiniNanoID\", (inst, def) => {\n core.$ZodNanoID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nanoid(params) {\n return core._nanoid(ZodMiniNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodMiniCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodMiniCUID = /*@__PURE__*/ core.$constructor(\"ZodMiniCUID\", (inst, def) => {\n core.$ZodCUID.init(inst, def);\n ZodMiniStringFormat.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 */\n// @__NO_SIDE_EFFECTS__\nexport function cuid(params) {\n return core._cuid(ZodMiniCUID, params);\n}\nexport const ZodMiniCUID2 = /*@__PURE__*/ core.$constructor(\"ZodMiniCUID2\", (inst, def) => {\n core.$ZodCUID2.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cuid2(params) {\n return core._cuid2(ZodMiniCUID2, params);\n}\nexport const ZodMiniULID = /*@__PURE__*/ core.$constructor(\"ZodMiniULID\", (inst, def) => {\n core.$ZodULID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ulid(params) {\n return core._ulid(ZodMiniULID, params);\n}\nexport const ZodMiniXID = /*@__PURE__*/ core.$constructor(\"ZodMiniXID\", (inst, def) => {\n core.$ZodXID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function xid(params) {\n return core._xid(ZodMiniXID, params);\n}\nexport const ZodMiniKSUID = /*@__PURE__*/ core.$constructor(\"ZodMiniKSUID\", (inst, def) => {\n core.$ZodKSUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ksuid(params) {\n return core._ksuid(ZodMiniKSUID, params);\n}\nexport const ZodMiniIPv4 = /*@__PURE__*/ core.$constructor(\"ZodMiniIPv4\", (inst, def) => {\n core.$ZodIPv4.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ipv4(params) {\n return core._ipv4(ZodMiniIPv4, params);\n}\nexport const ZodMiniIPv6 = /*@__PURE__*/ core.$constructor(\"ZodMiniIPv6\", (inst, def) => {\n core.$ZodIPv6.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ipv6(params) {\n return core._ipv6(ZodMiniIPv6, params);\n}\nexport const ZodMiniCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodMiniCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cidrv4(params) {\n return core._cidrv4(ZodMiniCIDRv4, params);\n}\nexport const ZodMiniCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodMiniCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cidrv6(params) {\n return core._cidrv6(ZodMiniCIDRv6, params);\n}\nexport const ZodMiniMAC = /*@__PURE__*/ core.$constructor(\"ZodMiniMAC\", (inst, def) => {\n core.$ZodMAC.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function mac(params) {\n return core._mac(ZodMiniMAC, params);\n}\nexport const ZodMiniBase64 = /*@__PURE__*/ core.$constructor(\"ZodMiniBase64\", (inst, def) => {\n core.$ZodBase64.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function base64(params) {\n return core._base64(ZodMiniBase64, params);\n}\nexport const ZodMiniBase64URL = /*@__PURE__*/ core.$constructor(\"ZodMiniBase64URL\", (inst, def) => {\n core.$ZodBase64URL.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function base64url(params) {\n return core._base64url(ZodMiniBase64URL, params);\n}\nexport const ZodMiniE164 = /*@__PURE__*/ core.$constructor(\"ZodMiniE164\", (inst, def) => {\n core.$ZodE164.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function e164(params) {\n return core._e164(ZodMiniE164, params);\n}\nexport const ZodMiniCreditCard = /*@__PURE__*/ core.$constructor(\"ZodMiniCreditCard\", (inst, def) => {\n core.$ZodCreditCard.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function creditCard(params) {\n return core._creditCard(ZodMiniCreditCard, params);\n}\nexport const ZodMiniIBAN = /*@__PURE__*/ core.$constructor(\"ZodMiniIBAN\", (inst, def) => {\n core.$ZodIBAN.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function iban(params) {\n return core._iban(ZodMiniIBAN, params);\n}\nexport const ZodMiniJWT = /*@__PURE__*/ core.$constructor(\"ZodMiniJWT\", (inst, def) => {\n core.$ZodJWT.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function jwt(params) {\n return core._jwt(ZodMiniJWT, params);\n}\nexport const ZodMiniCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniCustomStringFormat\", (inst, def) => {\n core.$ZodCustomStringFormat.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodMiniCustomStringFormat, format, fnOrRegex, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hostname(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"hostname\", regexes.hostname, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hex(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"hex\", regexes.hex, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function currencyCode(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"currency_code\", regexes.currencyCode, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n // check for unrecognized format\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodMiniCustomStringFormat, format, regex, params);\n}\nexport const ZodMiniNumber = /*@__PURE__*/ core.$constructor(\"ZodMiniNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function number(params) {\n return core._number(ZodMiniNumber, params);\n}\nexport const ZodMiniNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodMiniNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodMiniNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodMiniNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodMiniNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodMiniNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodMiniNumberFormat, params);\n}\nexport const ZodMiniBoolean = /*@__PURE__*/ core.$constructor(\"ZodMiniBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function boolean(params) {\n return core._boolean(ZodMiniBoolean, params);\n}\nexport const ZodMiniBigInt = /*@__PURE__*/ core.$constructor(\"ZodMiniBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function bigint(params) {\n return core._bigint(ZodMiniBigInt, params);\n}\nexport const ZodMiniBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodMiniBigInt.init(inst, def);\n});\nexport function int64(params) {\n return core._int64(ZodMiniBigIntFormat, params);\n}\nexport function uint64(params) {\n return core._uint64(ZodMiniBigIntFormat, params);\n}\nexport const ZodMiniSymbol = /*@__PURE__*/ core.$constructor(\"ZodMiniSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function symbol(params) {\n return core._symbol(ZodMiniSymbol, params);\n}\nexport const ZodMiniUndefined = /*@__PURE__*/ core.$constructor(\"ZodMiniUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _undefined(params) {\n return core._undefined(ZodMiniUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodMiniNull = /*@__PURE__*/ core.$constructor(\"ZodMiniNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _null(params) {\n return core._null(ZodMiniNull, params);\n}\nexport { _null as null };\nexport const ZodMiniAny = /*@__PURE__*/ core.$constructor(\"ZodMiniAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function any() {\n return core._any(ZodMiniAny);\n}\nexport const ZodMiniUnknown = /*@__PURE__*/ core.$constructor(\"ZodMiniUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function unknown() {\n return core._unknown(ZodMiniUnknown);\n}\nexport const ZodMiniNever = /*@__PURE__*/ core.$constructor(\"ZodMiniNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function never(params) {\n return core._never(ZodMiniNever, params);\n}\nexport const ZodMiniVoid = /*@__PURE__*/ core.$constructor(\"ZodMiniVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _void(params) {\n return core._void(ZodMiniVoid, params);\n}\nexport { _void as void };\nexport const ZodMiniDate = /*@__PURE__*/ core.$constructor(\"ZodMiniDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function date(params) {\n return core._date(ZodMiniDate, params);\n}\nexport const ZodMiniArray = /*@__PURE__*/ core.$constructor(\"ZodMiniArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function array(element, params) {\n return new ZodMiniArray({\n type: \"array\",\n element: element,\n ...util.normalizeParams(params),\n });\n}\n// .keyof\n// @__NO_SIDE_EFFECTS__\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodMiniObject = /*@__PURE__*/ core.$constructor(\"ZodMiniObject\", (inst, def) => {\n core.$ZodObject.init(inst, def);\n ZodMiniType.init(inst, def);\n util.installLazyProp(inst, \"shape\", (self) => self._zod.def.shape, false);\n});\n// @__NO_SIDE_EFFECTS__\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodMiniObject(def);\n}\n// strictObject\n// @__NO_SIDE_EFFECTS__\nexport function strictObject(shape, params) {\n return new ZodMiniObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\n// @__NO_SIDE_EFFECTS__\nexport function looseObject(shape, params) {\n return new ZodMiniObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\n// object methods\n// @__NO_SIDE_EFFECTS__\nexport function extend(schema, shape) {\n return util.extend(schema, shape);\n}\n// @__NO_SIDE_EFFECTS__\nexport function safeExtend(schema, shape) {\n return util.safeExtend(schema, shape);\n}\n/**\n * @deprecated Use [`z.extend(A, B.shape)`](https://zod.dev/api?id=extend) instead.\n */\n// @__NO_SIDE_EFFECTS__\nexport function merge(a, b) {\n return util.merge(a, b);\n}\n// @__NO_SIDE_EFFECTS__\nexport function pick(schema, mask) {\n return util.pick(schema, mask);\n}\n// .omit\n// @__NO_SIDE_EFFECTS__\nexport function omit(schema, mask) {\n return util.omit(schema, mask);\n}\n// @__NO_SIDE_EFFECTS__\nexport function partial(schema, mask) {\n const def = schema._zod.def;\n if (def.type !== \"tuple\")\n return util.partial(ZodMiniOptional, schema, mask);\n // a refinement was authored against the full arity; partialing would run it on a shorter array\n if (def.checks?.length)\n throw new Error(\".partial() cannot be used on tuple schemas containing refinements\");\n return util.clone(schema, {\n ...def,\n items: def.items.map((item) => new ZodMiniOptional({ type: \"optional\", innerType: item })),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function exactPartial(schema, mask) {\n return util.partial(ZodMiniExactOptional, schema, mask, \"exactPartial\");\n}\n// @__NO_SIDE_EFFECTS__\nexport function required(schema, mask) {\n return util.required(ZodMiniNonOptional, schema, mask);\n}\n// @__NO_SIDE_EFFECTS__\nexport function catchall(inst, catchall) {\n // `mergeDefs` rather than a spread: spreading reads `shape`, and resolving it can mint a whole fresh subtree\n return inst.clone(util.mergeDefs(inst._zod.def, { catchall: catchall }));\n}\nexport const ZodMiniUnion = /*@__PURE__*/ core.$constructor(\"ZodMiniUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function union(options, params) {\n return new ZodMiniUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniXor = /*@__PURE__*/ core.$constructor(\"ZodMiniXor\", (inst, def) => {\n ZodMiniUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\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 ZodMiniXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodMiniDiscriminatedUnion\", (inst, def) => {\n core.$ZodDiscriminatedUnion.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function discriminatedUnion(discriminator, options, params) {\n return new ZodMiniDiscriminatedUnion({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniIntersection = /*@__PURE__*/ core.$constructor(\"ZodMiniIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function intersection(left, right) {\n return new ZodMiniIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodMiniTuple = /*@__PURE__*/ core.$constructor(\"ZodMiniTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\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 ZodMiniTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniRecord = /*@__PURE__*/ core.$constructor(\"ZodMiniRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\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 ZodMiniRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function partialRecord(keyType, valueType, params) {\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n partial: true,\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniMap = /*@__PURE__*/ core.$constructor(\"ZodMiniMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function map(keyType, valueType, params) {\n return new ZodMiniMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniSet = /*@__PURE__*/ core.$constructor(\"ZodMiniSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function set(valueType, params) {\n return new ZodMiniSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniEnum = /*@__PURE__*/ core.$constructor(\"ZodMiniEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodMiniType.init(inst, def);\n // reuse the parsed value set so a numeric TS enum's reverse-mapping keys stay out\n inst.options = [...inst._zod.values];\n});\n// @__NO_SIDE_EFFECTS__\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodMiniEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\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(entries, params) {\n return new ZodMiniEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniLiteral = /*@__PURE__*/ core.$constructor(\"ZodMiniLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function literal(value, params) {\n return new ZodMiniLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniFile = /*@__PURE__*/ core.$constructor(\"ZodMiniFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function file(params) {\n return core._file(ZodMiniFile, params);\n}\nexport const ZodMiniTransform = /*@__PURE__*/ core.$constructor(\"ZodMiniTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function transform(fn) {\n return new ZodMiniTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodMiniOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function optional(innerType) {\n return new ZodMiniOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodMiniExactOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function exactOptional(innerType) {\n return new ZodMiniExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodMiniNullable = /*@__PURE__*/ core.$constructor(\"ZodMiniNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nullable(innerType) {\n return new ZodMiniNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\n// @__NO_SIDE_EFFECTS__\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodMiniDefault = /*@__PURE__*/ core.$constructor(\"ZodMiniDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function _default(innerType, defaultValue) {\n return new ZodMiniDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodMiniPrefault = /*@__PURE__*/ core.$constructor(\"ZodMiniPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function prefault(innerType, defaultValue) {\n return new ZodMiniPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodMiniNonOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nonoptional(innerType, params) {\n return new ZodMiniNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniSuccess = /*@__PURE__*/ core.$constructor(\"ZodMiniSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function success(innerType) {\n return new ZodMiniSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodMiniCatch = /*@__PURE__*/ core.$constructor(\"ZodMiniCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _catch(innerType, catchValue) {\n return new ZodMiniCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : core.util.constantCatch(catchValue)),\n });\n}\nexport { _catch as catch };\nexport const ZodMiniNaN = /*@__PURE__*/ core.$constructor(\"ZodMiniNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nan(params) {\n return core._nan(ZodMiniNaN, params);\n}\nexport const ZodMiniPipe = /*@__PURE__*/ core.$constructor(\"ZodMiniPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function pipe(in_, out) {\n return new ZodMiniPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n });\n}\nexport const ZodMiniCodec = /*@__PURE__*/ core.$constructor(\"ZodMiniCodec\", (inst, def) => {\n ZodMiniPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function codec(in_, out, params) {\n return new ZodMiniCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodMiniCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodMiniReadonly = /*@__PURE__*/ core.$constructor(\"ZodMiniReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function readonly(innerType) {\n return new ZodMiniReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodMiniTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodMiniTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function templateLiteral(parts, params) {\n return new ZodMiniTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniLazy = /*@__PURE__*/ core.$constructor(\"ZodMiniLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// export function lazy<T extends object>(getter: () => T): T {\n// return util.createTransparentProxy<T>(getter);\n// }\n// @__NO_SIDE_EFFECTS__\nfunction _lazy(getter) {\n return new ZodMiniLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport { _lazy as lazy };\nexport const ZodMiniPromise = /*@__PURE__*/ core.$constructor(\"ZodMiniPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function promise(innerType) {\n return new ZodMiniPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodMiniCustom = /*@__PURE__*/ core.$constructor(\"ZodMiniCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// custom checks\n// @__NO_SIDE_EFFECTS__\nexport function check(fn, params) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// ZodCustom custom schema\n// @__NO_SIDE_EFFECTS__\nexport function custom(fn, _params) {\n return core._custom(ZodMiniCustom, fn ?? (() => true), _params);\n}\n// refine\n// @__NO_SIDE_EFFECTS__\nexport function refine(fn, _params = {}) {\n return core._refine(ZodMiniCustom, fn, _params);\n}\n// superRefine\n// @__NO_SIDE_EFFECTS__\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;\n// instanceof\nclass Class {\n constructor(..._args) { }\n}\n// @__NO_SIDE_EFFECTS__\nfunction _instanceof(cls, params = {}) {\n const inst = custom((data) => data instanceof cls, params);\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: ZodMiniCodec,\n Boolean: ZodMiniBoolean,\n String: ZodMiniString,\n}, ...args);\n// @__NO_SIDE_EFFECTS__\nexport function json() {\n const jsonSchema = _lazy(() => {\n return union([string(), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\nexport const ZodMiniFunction = /*@__PURE__*/ core.$constructor(\"ZodMiniFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function _function(params) {\n return new ZodMiniFunction({\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 };\n","// `zod/mini` (tree-shakable functional API) instead of the full `zod` entry:\n// the widget only needs object/string/literal/union/nullable, and the mini\n// build keeps roughly 40KB of parser/refinement code out of the bundle.\nimport * as z from \"zod/mini\";\nimport { config as zodConfig } from \"zod/v4/core\";\n\n// Disable Zod's JIT-compiled fast path: it probes `Function(\"\")` at runtime,\n// which host pages with a strict Content-Security-Policy (no 'unsafe-eval')\n// block and report as a CSP violation on every widget load. Validation\n// behaves identically in jitless mode, just without eval-based codegen.\nzodConfig({ jitless: true });\n\nconst utteranceSchema = z.object({\n type: z.literal(\"utterance\"),\n content: z.string(),\n role: z.string(),\n});\n\nconst agentCognitionSchema = z.object({\n type: z.literal(\"agent_cognition\"),\n content: z.string(),\n});\n\nconst chatClosedExpiredSchema = z.object({\n type: z.literal(\"chat_closed_expired\"),\n content: z.string(),\n});\n\nconst agentCapturedUrlSchema = z.object({\n type: z.literal(\"agent_captured_url\"),\n content: z.string(),\n});\n\nconst agentTopicSchema = z.object({\n type: z.literal(\"agent_topic\"),\n content: z.string(),\n});\n\nconst agentSummarySchema = z.object({\n type: z.literal(\"agent_summary\"),\n content: z.string(),\n});\n\nconst chatRatingSchema = z.object({\n type: z.literal(\"chat_rating\"),\n content: z.string(),\n});\n\nconst breadcrumbSchema = z.object({\n type: z.literal(\"breadcrumb\"),\n content: z.string(),\n});\n\nconst chatEscalatedSchema = z.object({\n type: z.literal(\"chat_escalated\"),\n content: z.null(),\n});\n\nconst errorSchema = z.object({\n type: z.literal(\"error\"),\n code: z.string(),\n});\n\nconst utteranceApiResponseSchema = z.object({\n message_id: z.nullable(z.string()),\n created_at: z.string(),\n data: utteranceSchema,\n});\n\nconst errorApiResponseSchema = z.object({\n created_at: z.string(),\n data: errorSchema,\n});\n\nconst agentCognitionApiResponseSchema = z.object({\n created_at: z.string(),\n data: agentCognitionSchema,\n});\n\nconst chatClosedExpiredApiResponseSchema = z.object({\n message_id: z.nullable(z.string()),\n created_at: z.string(),\n data: chatClosedExpiredSchema,\n});\n\nconst agentCapturedUrlApiResponseSchema = z.object({\n created_at: z.string(),\n data: agentCapturedUrlSchema,\n});\n\nconst agentTopicApiResponseSchema = z.object({\n created_at: z.string(),\n data: agentTopicSchema,\n});\n\nconst agentSummaryApiResponseSchema = z.object({\n created_at: z.string(),\n data: agentSummarySchema,\n});\n\nconst chatRatingApiResponseSchema = z.object({\n created_at: z.string(),\n data: chatRatingSchema,\n});\n\nconst breadcrumbApiResponseSchema = z.object({\n created_at: z.string(),\n data: breadcrumbSchema,\n});\n\nconst chatEscalatedApiResponseSchema = z.object({\n message_id: z.nullable(z.string()),\n created_at: z.string(),\n data: chatEscalatedSchema,\n});\n\nexport const chatResponseApiSchema = z.union([\n utteranceApiResponseSchema,\n errorApiResponseSchema,\n agentCognitionApiResponseSchema,\n agentCapturedUrlApiResponseSchema,\n agentTopicApiResponseSchema,\n agentSummaryApiResponseSchema,\n chatClosedExpiredApiResponseSchema,\n chatRatingApiResponseSchema,\n breadcrumbApiResponseSchema,\n chatEscalatedApiResponseSchema,\n]);\n\nexport type ChatResponseApi = z.infer<typeof chatResponseApiSchema>;\n\ntype NotificationData = ChatResponseApi[\"data\"];\n\nexport type UtteranceNotification = {\n message_id: string | null;\n created_at: string;\n data: Extract<NotificationData, { type: \"utterance\" }>;\n};\n\nexport type ErrorNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"error\" }>;\n};\n\nexport type AgentCognitionNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"agent_cognition\" }>;\n};\n\nexport type AgentCapturedUrlNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"agent_captured_url\" }>;\n};\n\nexport type AgentTopicNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"agent_topic\" }>;\n};\n\nexport type AgentSummaryNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"agent_summary\" }>;\n};\n\nexport const chatResponseSchema = z.object({\n message_id: z.string(), // message_id from api schema\n response: z.object({\n id: z.string(), // message_id from api schema\n type: z.string(),\n content: z.string(),\n }),\n});\n\nexport type ChatResponse = z.infer<typeof chatResponseSchema>;\n","import { useCallback, useEffect, useRef } from \"react\";\n\nimport { useErrorContext } from \"@/contexts/error-handling/error-context\";\nimport { getErrorMessage } from \"@/contexts/error-handling/error-messages\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\nimport {\n connectAppSyncEvents,\n type AppSyncEventsConnection,\n} from \"@/lib/appsync-events-client\";\nimport { BootResponse, MessageResponse } from \"@/lib/eloquent-ai-api-client\";\nimport { Message } from \"@/types/message\";\n\nimport {\n AgentCapturedUrlNotification,\n AgentCognitionNotification,\n AgentSummaryNotification,\n AgentTopicNotification,\n ChatResponse,\n chatResponseApiSchema,\n ErrorNotification,\n UtteranceNotification,\n} from \"../validations\";\n\nconst INITIAL_RECONNECT_DELAY_MS = 500;\nconst MAX_RECONNECT_DELAY_MS = 30000;\nconst DEFAULT_BACKUP_POLL_INTERVAL_MS = 60000;\n\nexport type UseRealtimeSocketOptions = {\n chatSettings: BootResponse[\"chat_settings\"] | null;\n chatId: string | null;\n messages: Message[];\n onMessage: (response: ChatResponse, chatId: string) => void;\n onCognition: (content: string) => void;\n onCognitionComplete: () => void;\n onError?: () => void;\n onChatClosed?: () => void;\n onAgentCapturedUrl?: (content: string) => void;\n onAgentTopic?: (content: string) => void;\n onAgentSummary?: (content: string) => void;\n onRatingRequest?: () => void;\n onBreadcrumb?: () => void;\n fetchHistory: (chatId: string) => Promise<MessageResponse[]>;\n getChatToken: () => string | null;\n backupPollingInterval?: number;\n};\n\nexport type UseRealtimeSocketReturn = {\n connect: (chatId: string) => Promise<void>;\n disconnect: () => void;\n clearProcessedIds: () => void;\n};\n\nexport function useRealtimeSocket({\n chatSettings,\n chatId,\n messages,\n onMessage,\n onCognition,\n onCognitionComplete,\n onError,\n onChatClosed,\n onAgentCapturedUrl,\n onAgentTopic,\n onAgentSummary,\n onRatingRequest,\n onBreadcrumb,\n fetchHistory,\n getChatToken,\n backupPollingInterval = DEFAULT_BACKUP_POLL_INTERVAL_MS,\n}: UseRealtimeSocketOptions): UseRealtimeSocketReturn {\n const processedIdsRef = useRef<Set<string>>(new Set());\n\n useEffect(() => {\n for (const msg of messages) {\n if (msg.id) processedIdsRef.current.add(msg.id);\n }\n }, [messages]);\n\n const eventChannelRef = useRef<AppSyncEventsConnection | null>(null);\n const activeChatIdRef = useRef<string | null>(null);\n const reconnectAttemptsRef = useRef(0);\n const reconnectTimerRef = useRef<NodeJS.Timeout | null>(null);\n const backupPollIntervalRef = useRef<NodeJS.Timeout | null>(null);\n const shouldReconnectRef = useRef(false);\n const isReconnectingRef = useRef(false);\n\n // Keep all mutable callbacks as latest-refs to avoid stale closures in\n // timers/intervals and the long-lived socket subscription.\n const onMessageRef = useLatestRef(onMessage);\n const onCognitionRef = useLatestRef(onCognition);\n const onCognitionCompleteRef = useLatestRef(onCognitionComplete);\n const onErrorRef = useLatestRef(onError);\n const onChatClosedRef = useLatestRef(onChatClosed);\n const onAgentCapturedUrlRef = useLatestRef(onAgentCapturedUrl);\n const onAgentTopicRef = useLatestRef(onAgentTopic);\n const onAgentSummaryRef = useLatestRef(onAgentSummary);\n const onRatingRequestRef = useLatestRef(onRatingRequest);\n const onBreadcrumbRef = useLatestRef(onBreadcrumb);\n const fetchHistoryRef = useLatestRef(fetchHistory);\n const getChatTokenRef = useLatestRef(getChatToken);\n\n const { publishError } = useErrorContext();\n\n const appSyncUrl = chatSettings?.app_sync_url;\n const appSyncApiKey = chatSettings?.app_sync_api_key;\n // The client is configuration-free (no Amplify.configure singleton) —\n // connections are ready as soon as boot settings provide the endpoint.\n const isSocketConfigReady = Boolean(appSyncUrl && appSyncApiKey);\n const appSyncUrlRef = useLatestRef(appSyncUrl);\n const appSyncApiKeyRef = useLatestRef(appSyncApiKey);\n\n const closeChannel = useCallback(() => {\n if (eventChannelRef.current) {\n eventChannelRef.current.close();\n eventChannelRef.current = null;\n }\n }, []);\n\n const stopBackupPoll = useCallback(() => {\n if (backupPollIntervalRef.current) {\n clearInterval(backupPollIntervalRef.current);\n backupPollIntervalRef.current = null;\n }\n }, []);\n\n const clearReconnectTimer = useCallback(() => {\n if (reconnectTimerRef.current) {\n clearTimeout(reconnectTimerRef.current);\n reconnectTimerRef.current = null;\n }\n }, []);\n\n // Forward-declared: connectChannel's onDisconnect needs scheduleReconnect,\n // which itself needs connectChannel — the ref breaks the cycle. Synced to\n // the latest scheduleReconnect below.\n const scheduleReconnectRef = useRef<() => void>(() => {});\n\n // Opens an AppSync Events channel and subscribes to real-time events\n const connectChannel = useCallback(\n async (chatIdToConnect: string): Promise<void> => {\n closeChannel();\n const httpEndpoint = appSyncUrlRef.current;\n const apiKey = appSyncApiKeyRef.current;\n if (!httpEndpoint || !apiKey) {\n throw new Error(\"Cannot connect: AppSync settings not available\");\n }\n const chatToken = getChatTokenRef.current();\n\n const connection = await connectAppSyncEvents({\n httpEndpoint,\n auth: chatToken ? { authorizationToken: chatToken } : { apiKey },\n channel: `/default/chat/${chatIdToConnect}`,\n onDisconnect: () => {\n eventChannelRef.current = null;\n scheduleReconnectRef.current();\n },\n onEvent: (event) => {\n const parseResult = chatResponseApiSchema.safeParse(event);\n if (!parseResult.success) {\n console.error(\"Invalid conversation response:\", parseResult.error);\n return;\n }\n\n const notification = parseResult.data;\n switch (notification.data.type) {\n case \"utterance\": {\n const utterance = notification as UtteranceNotification;\n const messageId = utterance.message_id ?? crypto.randomUUID();\n if (processedIdsRef.current.has(messageId)) {\n return;\n }\n processedIdsRef.current.add(messageId);\n onCognitionCompleteRef.current();\n onMessageRef.current(\n {\n message_id: messageId,\n response: {\n id: messageId,\n type: utterance.data.type,\n content: utterance.data.content,\n },\n },\n chatIdToConnect,\n );\n return;\n }\n case \"error\": {\n const errorNotif = notification as ErrorNotification;\n const code = parseInt(errorNotif.data.code);\n publishError({ code, message: getErrorMessage(code) });\n onErrorRef.current?.();\n return;\n }\n case \"agent_cognition\": {\n const cognition = notification as AgentCognitionNotification;\n onCognitionRef.current(cognition.data.content);\n return;\n }\n case \"agent_captured_url\": {\n const capturedUrl = notification as AgentCapturedUrlNotification;\n onAgentCapturedUrlRef.current?.(capturedUrl.data.content);\n return;\n }\n case \"agent_topic\": {\n const topic = notification as AgentTopicNotification;\n onAgentTopicRef.current?.(topic.data.content);\n return;\n }\n case \"agent_summary\": {\n const summary = notification as AgentSummaryNotification;\n onAgentSummaryRef.current?.(summary.data.content);\n return;\n }\n case \"chat_closed_expired\": {\n onChatClosedRef.current?.();\n onRatingRequestRef.current?.();\n return;\n }\n case \"chat_rating\": {\n onRatingRequestRef.current?.();\n return;\n }\n case \"breadcrumb\": {\n onBreadcrumbRef.current?.();\n return;\n }\n case \"chat_escalated\": {\n onChatClosedRef.current?.();\n onRatingRequestRef.current?.();\n return;\n }\n default:\n console.warn(\n \"Unknown notification type:\",\n (notification as { data: { type: string } }).data.type,\n );\n }\n },\n });\n\n eventChannelRef.current = connection;\n },\n // The *Ref entries are latest-refs (stable identities); listed to satisfy\n // exhaustive-deps, which can't see that useLatestRef returns a ref.\n [\n closeChannel,\n publishError,\n appSyncUrlRef,\n appSyncApiKeyRef,\n getChatTokenRef,\n onMessageRef,\n onCognitionRef,\n onCognitionCompleteRef,\n onErrorRef,\n onChatClosedRef,\n onAgentCapturedUrlRef,\n onAgentTopicRef,\n onAgentSummaryRef,\n onRatingRequestRef,\n onBreadcrumbRef,\n ],\n );\n\n // Fetches history and delivers any unseen assistant messages via onMessage\n const runBackupPoll = useCallback(\n async (chatIdToPoll: string) => {\n try {\n const history = await fetchHistoryRef.current(chatIdToPoll);\n for (const msg of history) {\n if (\n msg.role !== \"assistant\" ||\n !msg.message_id ||\n processedIdsRef.current.has(msg.message_id)\n ) {\n continue;\n }\n processedIdsRef.current.add(msg.message_id);\n onMessageRef.current(\n { message_id: msg.message_id, response: msg.response },\n chatIdToPoll,\n );\n }\n } catch (err) {\n console.warn(\"Backup poll failed:\", err);\n }\n },\n [fetchHistoryRef, onMessageRef],\n );\n\n const startBackupPoll = useCallback(\n (chatIdToPoll: string) => {\n stopBackupPoll();\n backupPollIntervalRef.current = setInterval(\n () => runBackupPoll(chatIdToPoll),\n backupPollingInterval,\n );\n },\n [stopBackupPoll, runBackupPoll, backupPollingInterval],\n );\n\n // Named function expression so the setTimeout callback can re-schedule\n // itself on failure without a circular ref dependency.\n const scheduleReconnect = useCallback(\n function scheduleReconnectSelf() {\n if (\n !shouldReconnectRef.current ||\n isReconnectingRef.current ||\n reconnectTimerRef.current\n ) {\n return;\n }\n const chatIdToReconnect = activeChatIdRef.current;\n if (!chatIdToReconnect) return;\n\n const delay = Math.min(\n INITIAL_RECONNECT_DELAY_MS * Math.pow(2, reconnectAttemptsRef.current),\n MAX_RECONNECT_DELAY_MS,\n );\n reconnectAttemptsRef.current += 1;\n\n reconnectTimerRef.current = setTimeout(async () => {\n reconnectTimerRef.current = null;\n isReconnectingRef.current = true;\n try {\n await connectChannel(chatIdToReconnect);\n reconnectAttemptsRef.current = 0;\n isReconnectingRef.current = false;\n await runBackupPoll(chatIdToReconnect);\n } catch {\n isReconnectingRef.current = false;\n scheduleReconnectSelf();\n }\n }, delay);\n },\n [connectChannel, runBackupPoll],\n );\n\n // Keep the forward-declared ref pointing at the latest scheduleReconnect\n // (same semantics as useLatestRef, but the ref had to exist earlier for\n // connectChannel's onDisconnect).\n useEffect(() => {\n scheduleReconnectRef.current = scheduleReconnect;\n });\n\n const connect = useCallback(\n async (chatIdToConnect: string): Promise<void> => {\n if (!isSocketConfigReady || !chatIdToConnect) {\n throw new Error(\n \"Cannot connect: AppSync settings not ready or missing chatId\",\n );\n }\n clearReconnectTimer();\n shouldReconnectRef.current = true;\n activeChatIdRef.current = chatIdToConnect;\n reconnectAttemptsRef.current = 0;\n // Start polling before the socket connect attempt, not after — if\n // connectChannel throws (e.g. the AppSync channel is unreachable),\n // polling must still run so messages keep arriving via history\n // instead of being lost entirely until a reconnect succeeds.\n startBackupPoll(chatIdToConnect);\n await connectChannel(chatIdToConnect);\n },\n [isSocketConfigReady, clearReconnectTimer, connectChannel, startBackupPoll],\n );\n\n const disconnect = useCallback((): void => {\n shouldReconnectRef.current = false;\n activeChatIdRef.current = null;\n reconnectAttemptsRef.current = 0;\n clearReconnectTimer();\n stopBackupPoll();\n closeChannel();\n }, [clearReconnectTimer, stopBackupPoll, closeChannel]);\n\n const clearProcessedIds = useCallback(() => {\n processedIdsRef.current.clear();\n }, []);\n\n // Eagerly connect when chatId becomes available (e.g., restored from localStorage on mount)\n useEffect(() => {\n if (!chatId || !isSocketConfigReady || activeChatIdRef.current === chatId)\n return;\n\n connect(chatId).catch((err) => {\n console.error(\"Failed to eagerly connect:\", err);\n activeChatIdRef.current = chatId;\n shouldReconnectRef.current = true;\n scheduleReconnectRef.current();\n });\n }, [chatId, isSocketConfigReady, connect]);\n\n // Disconnect detection lives inside connectAppSyncEvents (socket close and\n // keep-alive timeout both invoke connectChannel's onDisconnect), replacing\n // the amplify Hub connection-state listener.\n\n useEffect(() => {\n return () => {\n disconnect();\n };\n }, [disconnect]);\n\n return { connect, disconnect, clearProcessedIds };\n}\n","import type { ChatResponse } from \"@/components/chat/validations\";\nimport type { Message } from \"@/types/message\";\n\n/**\n * The single place where API/wire shapes become domain `Message`s.\n *\n * Everything here is a pure function: the hooks own state and timing, this\n * module owns shape. A backend field change should only ever touch this file\n * (and validations.ts), not the hooks.\n */\n\n/** A realtime/polled assistant reply, as appended to the transcript. */\nexport function messageFromChatResponse(response: ChatResponse): Message {\n return {\n id: response.message_id,\n content: response.response.content ?? \"\",\n sender: \"assistant\",\n timestamp: new Date().toISOString(),\n };\n}\n\n/** The configured welcome message, shown before any conversation exists. */\nexport function createWelcomeMessage(content: string): Message {\n return {\n id: crypto.randomUUID(),\n content,\n sender: \"assistant\",\n timestamp: new Date().toISOString(),\n isWelcomeMessage: true,\n };\n}\n\n/** The star-rating prompt appended when the server requests feedback. */\nexport function createRatingRequestMessage(): Message {\n return {\n id: crypto.randomUUID(),\n content: \"\",\n sender: \"assistant\",\n timestamp: new Date().toISOString(),\n isRatingRequest: true,\n };\n}\n\n/** The notice shown when the user writes into a closed conversation. */\nexport function createChatClosedNoticeMessage(): Message {\n return {\n id: crypto.randomUUID(),\n content: \"This conversation is closed, please start a new chat.\",\n sender: \"assistant\",\n timestamp: new Date().toISOString(),\n };\n}\n","\"use client\";\nimport {\n useCallback,\n useEffect,\n type Dispatch,\n type SetStateAction,\n} from \"react\";\n\nimport { Message, MessageData } from \"@/types/message\";\n\nimport {\n BootResponse,\n EloquentAiApiClient,\n} from \"@/lib/eloquent-ai-api-client\";\n\nimport { useErrorContext } from \"@/contexts/error-handling/error-context\";\nimport { useAgentCognitionContext } from \"@/contexts/agent-cognition/use-agent-cognition-context\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\nimport { NetworkError, ServerError } from \"@/lib/http\";\nimport { getCurrentUrlSearchParams } from \"@/lib/url-params\";\nimport { usePersistence } from \"./use-persistence\";\nimport { useRealtimeSocket } from \"./use-realtime-socket\";\nimport {\n createChatClosedNoticeMessage,\n createRatingRequestMessage,\n messageFromChatResponse,\n} from \"../message-mapping\";\nimport { ChatResponse } from \"../validations\";\n\nexport interface UseMessageEventsProps {\n appId: string;\n userId: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n externalId?: string | null;\n deviceId: string;\n apiClient: EloquentAiApiClient | null;\n chatSettings: BootResponse[\"chat_settings\"] | null;\n messages: Message[];\n setMessages: Dispatch<SetStateAction<Message[]>>;\n currentChat: { id: string } | null;\n setCurrentChat: Dispatch<SetStateAction<{ id: string } | null>>;\n onChatClosed?: () => void;\n isChatClosed?: boolean;\n}\n\nexport interface UseMessageEventsReturn {\n onCleanMessages: () => void;\n onSendMessage: (data: MessageData) => Promise<void>;\n onRateChat: (rating: number) => Promise<void>;\n}\n\n/**\n * Hook to handle message events like sending and cleaning\n */\nexport function useMessageEvents({\n appId,\n userId,\n userName,\n userData,\n externalId,\n deviceId,\n apiClient,\n chatSettings,\n messages,\n setMessages,\n currentChat,\n setCurrentChat,\n onChatClosed,\n isChatClosed,\n}: UseMessageEventsProps): UseMessageEventsReturn {\n const { saveChatData, clearChatData, updateLastActivity, markChatClosed } =\n usePersistence({\n appId,\n });\n\n const { publishApiError, publishNetworkError } = useErrorContext();\n const { showCognition, hideCognition } = useAgentCognitionContext();\n\n // Keep apiClient in a ref so stable callbacks always use the latest instance\n const apiClientRef = useLatestRef(apiClient);\n\n /**\n * Handles receiving messages from the server.\n * Called by the WebSocket and backup poll — deduplication\n * is handled inside useRealtimeSocket via processedIds.\n */\n const onReceiveMessage = useCallback(\n (response: ChatResponse, chatId: string) => {\n if (!response.response.content) return;\n\n setMessages((prev) => {\n if (prev.some((msg) => msg.isRatingRequest)) return prev;\n // Ignore the message if it matches the configured welcome message\n if (\n chatSettings?.welcome_message &&\n response.response.content === chatSettings.welcome_message\n )\n return prev;\n const filteredMessages = prev.filter((msg) => !msg.isThinking);\n const updatedMessages: Message[] = [\n ...filteredMessages,\n messageFromChatResponse(response),\n ];\n saveChatData(\n chatId,\n userId,\n updatedMessages,\n deviceId,\n apiClientRef.current?.getChatToken(),\n );\n return updatedMessages;\n });\n },\n [chatSettings, deviceId, saveChatData, setMessages, userId, apiClientRef],\n );\n\n const handleRealTimeError = useCallback(() => {\n hideCognition();\n setMessages((prev) => prev.filter((msg) => !msg.isThinking));\n }, [setMessages, hideCognition]);\n\n const handleRatingRequest = useCallback(() => {\n setMessages((prev) => {\n const filtered = prev.filter((msg) => !msg.isRatingRequest);\n return [...filtered, createRatingRequestMessage()];\n });\n }, [setMessages]);\n\n useEffect(() => {\n if (import.meta.env.DEV) {\n const w = window as unknown as Record<string, unknown>;\n w.EloquentAI_TriggerChatRating = handleRatingRequest;\n return () => {\n delete w.EloquentAI_TriggerChatRating;\n };\n }\n }, [handleRatingRequest]);\n\n const fetchHistory = useCallback(\n (chatId: string) => {\n if (!apiClientRef.current) return Promise.resolve([]);\n return apiClientRef.current.getChatHistory(chatId);\n },\n [apiClientRef],\n );\n\n const getChatToken = useCallback(() => {\n return apiClientRef.current?.getChatToken() ?? null;\n }, [apiClientRef]);\n\n const handleChatClosed = useCallback(() => {\n markChatClosed();\n onChatClosed?.();\n }, [markChatClosed, onChatClosed]);\n\n const { connect, disconnect, clearProcessedIds } = useRealtimeSocket({\n chatSettings,\n chatId: currentChat?.id ?? null,\n messages,\n onMessage: onReceiveMessage,\n onCognition: showCognition,\n onCognitionComplete: hideCognition,\n onError: handleRealTimeError,\n onChatClosed: handleChatClosed,\n onRatingRequest: handleRatingRequest,\n onBreadcrumb: handleChatClosed,\n fetchHistory,\n getChatToken,\n });\n\n const onCleanMessages = useCallback(() => {\n hideCognition();\n disconnect();\n clearProcessedIds();\n setMessages((prev) =>\n prev.filter((message) => {\n if (Array.isArray(message)) return false;\n return message.isWelcomeMessage;\n }),\n );\n clearChatData();\n setCurrentChat(null);\n }, [\n hideCognition,\n disconnect,\n clearProcessedIds,\n clearChatData,\n setMessages,\n setCurrentChat,\n ]);\n\n /**\n * Handles sending messages to the server\n */\n const onSendMessage = useCallback(\n async (message: MessageData) => {\n if (!apiClient) return;\n\n if (messages.some((msg) => msg.isRatingRequest)) return;\n\n if (isChatClosed) {\n setMessages((prev) => [...prev, createChatClosedNoticeMessage()]);\n return;\n }\n\n const userMessage = {\n ...message,\n id: crypto.randomUUID(),\n isNew: true,\n };\n\n showCognition();\n const newMessages = [...messages, userMessage];\n setMessages(newMessages);\n updateLastActivity();\n\n try {\n let chatId = currentChat?.id;\n if (!chatId) {\n const response = await apiClient.createConversation({\n userId: externalId || userId,\n deviceId,\n userName,\n userData,\n externalMetadata: {\n searchParams: getCurrentUrlSearchParams(),\n },\n });\n chatId = response.chat_id;\n setCurrentChat({ id: chatId });\n try {\n await connect(chatId);\n } catch (connectError) {\n console.warn(\n \"Failed to connect realtime channel, continuing with REST-only delivery:\",\n connectError,\n );\n }\n }\n\n const response = await apiClient.replyToConversation({\n text: message.content,\n conversationId: chatId,\n userId: externalId || userId,\n deviceId,\n userName,\n userData,\n });\n\n // Update user message with real server ID\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === userMessage.id\n ? { ...msg, id: response.message_id, isNew: false }\n : msg,\n ),\n );\n } catch (error) {\n hideCognition();\n\n setMessages((prev) => prev.filter((msg) => !msg.isThinking));\n\n if (\n error instanceof NetworkError ||\n (error instanceof ServerError && error.status === 403)\n ) {\n publishNetworkError();\n throw error;\n }\n\n publishApiError(error as ServerError);\n\n if (\n error instanceof ServerError &&\n // A 401 here means the chat's session token is invalid/expired\n // (or the chat closed) — treat it the same as a client-side\n // expired chat: drop the stale session and let the next send\n // start a fresh one, instead of surfacing an error.\n (error.status >= 500 || error.status === 401)\n ) {\n setCurrentChat(null);\n clearChatData();\n setMessages((prev) => prev.slice(0, -1));\n apiClient.reset();\n } else {\n // Mark the user message as failed\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === userMessage.id ? { ...msg, isFailed: true } : msg,\n ),\n );\n }\n\n throw error;\n }\n },\n [\n apiClient,\n isChatClosed,\n showCognition,\n messages,\n setMessages,\n updateLastActivity,\n currentChat?.id,\n externalId,\n userId,\n deviceId,\n setCurrentChat,\n connect,\n hideCognition,\n publishApiError,\n publishNetworkError,\n clearChatData,\n userName,\n userData,\n ],\n );\n\n const onRateChat = useCallback(\n async (rating: number) => {\n const chatId = currentChat?.id;\n if (!apiClientRef.current || !chatId) return;\n await apiClientRef.current.addRating(chatId, rating);\n },\n [currentChat?.id, apiClientRef],\n );\n\n return {\n onCleanMessages,\n onSendMessage,\n onRateChat,\n };\n}\n","// Helper to safely access import.meta.env in SSR environments\nfunction getEnvVariable(key: string): string {\n // Check if we're in a browser or if import.meta is available\n if (typeof window === \"undefined\" || typeof import.meta === \"undefined\") {\n return \"\";\n }\n return (import.meta.env[key] as string) || \"\";\n}\n\n// Define environment-specific constants that will be replaced during build\nconst ENV_API_URL = getEnvVariable(\"VITE_API_URL\");\nconst ENV_REGION_API_URL = getEnvVariable(\"VITE_REGION_API_URL\");\n\n/**\n * Returns the API URL based on the provided custom URL or the default API URL.\n * @returns The API URL.\n */\nexport function getApiUrl(): string {\n return ENV_API_URL || \"\";\n}\n\n/**\n * Returns the Region API URL based on the environment.\n * @returns The Region API URL.\n */\nexport function getRegionApiUrl(): string {\n return ENV_REGION_API_URL || \"\";\n}\n","import { getRegionApiUrl } from \"./config\";\nimport { HttpClient, HttpClientConfig } from \"./http\";\n\ninterface UserData {\n device_id: string;\n user_id?: string;\n user_name?: string;\n external_id?: string;\n user_data?: Record<string, string | number | boolean>;\n}\n\ninterface Message {\n text: string;\n user_data: UserData;\n}\n\nexport interface ConversationApiResponse {\n chat_id: string;\n message_id: string;\n response: {\n id: string;\n type: string;\n content: string;\n };\n}\n\nexport interface CreateConversationApiResponse {\n chat_id: string;\n chat_token: string;\n}\n\nexport interface IdentifyUserApiResponse {\n result: string;\n}\n\nexport interface MessageResponse {\n response: {\n id: string;\n type: string;\n content: string;\n };\n message_id: string;\n message_number: number;\n created_at: string;\n previousMessage?: MessageResponse;\n role: \"user\" | \"assistant\" | \"system\";\n}\n\nexport interface AddRatingApiResponse {\n result: string;\n}\n\nexport interface OrganizationResponse {\n region: string;\n}\n\nexport interface ExternalMetadata {\n [key: string]: string | ExternalMetadata;\n}\n\nexport interface BootResponse {\n chat_settings: {\n agent_name: string;\n welcome_message?: string | null;\n footer_html?: string | null;\n suggested_messages: boolean;\n suggested_message_texts?: string[] | null;\n suggested_message_aura?: boolean | null;\n suggested_message_shine?: boolean | null;\n auto_display_welcome_message: boolean;\n collect_user_feedback: boolean;\n theme: \"light\" | \"dark\";\n avatar_url?: string | null;\n user_bubble_color?: string | null;\n bot_bubble_color?: string | null;\n suggested_message_bubble_color?: string | null;\n user_bubble_text_color?: string | null;\n bot_bubble_text_color?: string | null;\n suggested_message_bubble_text_color?: string | null;\n app_sync_api_key: string;\n app_sync_url: string;\n app_sync_region: string;\n title?: string;\n subtitle?: string;\n is_active?: boolean;\n /** Open the chat window on load (desktop only). Wins over the isInitiallyOpen prop, but a `true` here never overrides the user's closed-cookie. */\n initial_open?: boolean | null;\n /** Show the close (X) button in the chat header. Always wins over the hasCloseButton prop. */\n close_button?: boolean | null;\n /** Show the clear-conversation button in the chat header. Always wins over the hasCleanChatButton prop. */\n clean_chat_button?: boolean | null;\n /** Auto-hide delay for the proactive message, in milliseconds. Always wins over the proactiveMessageHideDelay prop. */\n proactive_message_hide_delay?: number | null;\n };\n}\n\nexport class EloquentAiApiClient {\n private httpClient: HttpClient;\n private userId: string | null = null;\n private conversationId: string | null = null;\n\n constructor(config: HttpClientConfig) {\n this.userId = config.userId || null;\n this.httpClient = new HttpClient(config);\n }\n\n getUserData() {\n return {\n userId: this.userId,\n conversationId: this.conversationId,\n };\n }\n\n /**\n * Reset API client by clearing all stored state\n */\n reset() {\n this.conversationId = null;\n this.httpClient.setChatToken(null);\n }\n\n setRegion(region: string): void {\n this.httpClient.setRegion(region);\n }\n\n getChatToken(): string | null {\n return this.httpClient.getChatToken();\n }\n\n setChatToken(token: string | null): void {\n this.httpClient.setChatToken(token);\n }\n\n /**\n * Get organization data by app ID\n */\n async getOrganizationByAppId(appId: string) {\n const regionApiUrl = getRegionApiUrl();\n const response = await this.httpClient.getExternal<OrganizationResponse>(\n `${regionApiUrl}/by-app-id/${appId}`,\n );\n return response;\n }\n\n async boot() {\n const response = await this.httpClient.get<{ data: BootResponse }>(\n \"/v1/sdk/boot\",\n );\n return response.data;\n }\n\n async addRating(chatId: string, rating: number) {\n const response = await this.httpClient.put<\n { data: AddRatingApiResponse },\n { rating: number }\n >(`/v1/chat/${chatId}/rating`, { rating: rating });\n return response.data;\n }\n\n async createConversation(options: {\n userId: string;\n deviceId: string;\n userName?: string;\n externalId?: string;\n userData?: Record<string, string | number | boolean>;\n externalMetadata?: ExternalMetadata;\n }) {\n const response = await this.httpClient.post<\n { data: CreateConversationApiResponse },\n { user_data: UserData; external_metadata?: ExternalMetadata }\n >(\"/v2/chat\", {\n user_data: {\n user_id: options.userId,\n device_id: options.deviceId,\n user_name: options.userName,\n external_id: options.externalId,\n user_data: options.userData,\n },\n ...(options.externalMetadata &&\n Object.keys(options.externalMetadata).length > 0\n ? { external_metadata: options.externalMetadata }\n : {}),\n });\n\n const { data } = response;\n this.httpClient.setChatToken(data.chat_token);\n\n return data;\n }\n\n async replyToConversation(options: {\n text: string;\n conversationId: string;\n userId: string;\n deviceId: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n }) {\n const message: Message = {\n text: options.text,\n user_data: {\n device_id: options.deviceId,\n user_id: options.userId,\n user_name: options.userName,\n user_data: options.userData,\n },\n };\n\n const { data } = await this.httpClient.post<\n { data: ConversationApiResponse },\n Message\n >(`/v3/chat/${options.conversationId}`, message);\n\n return data;\n }\n\n async identifyUser(options: {\n conversationId: string;\n userId: string;\n deviceId: string;\n userName?: string;\n externalId?: string;\n userData?: Record<string, string | number | boolean>;\n }) {\n const message: UserData = {\n device_id: options.deviceId,\n user_id: options.userId,\n user_name: options.userName,\n external_id: options.externalId,\n user_data: options.userData,\n };\n\n const { data } = await this.httpClient.post<\n { data: IdentifyUserApiResponse },\n UserData\n >(`/v1/chat/${options.conversationId}/identify`, message);\n\n return data;\n }\n\n async getChatHistory(conversationId: string) {\n const response = await this.httpClient.get<{ data: MessageResponse[] }>(\n `/v1/chat/${conversationId}/history`,\n );\n return response.data;\n }\n}\n","import { ServerError } from \"@/lib/http\";\n\n/**\n * Wraps a Promise and returns a tuple containing the result or error\n * @param promise Promise to wrap\n * @returns [result, error] - result is null if error occurred, error is null if no error occurred\n */\nexport async function wrapPromise<T, E = ServerError>(\n promise: Promise<T>,\n): Promise<[T, null] | [null, E]> {\n try {\n return [await promise, null] as const;\n } catch (error) {\n return [null, error as E] as const;\n }\n}\n","import { NetworkError, ServerError } from \"./http\";\n\ninterface WithRetryOptions {\n retries?: number;\n minDelayMs?: number;\n maxDelayMs?: number;\n factor?: number;\n}\n\nconst DEFAULT_OPTIONS: Required<WithRetryOptions> = {\n retries: 3,\n minDelayMs: 200,\n maxDelayMs: 1_000,\n factor: 2,\n};\n\n/** Retries on network errors and 5xx/429 responses; other errors bail immediately. */\nexport function isRetryableError(error: unknown): boolean {\n if (error instanceof NetworkError) return true;\n if (error instanceof ServerError) {\n return error.status === 429 || error.status >= 500;\n }\n return false;\n}\n\n/** Exponential backoff with full jitter, mirroring the retry shape used in chat-api's http-retry.util.ts. */\nfunction getDelayMs(\n attempt: number,\n options: Required<WithRetryOptions>,\n): number {\n const exponentialDelay = options.minDelayMs * options.factor ** attempt;\n const cappedDelay = Math.min(exponentialDelay, options.maxDelayMs);\n return Math.random() * cappedDelay;\n}\n\nexport async function withRetry<T>(\n operation: () => Promise<T>,\n options: WithRetryOptions = {},\n): Promise<T> {\n const opts = { ...DEFAULT_OPTIONS, ...options };\n\n for (let attempt = 0; ; attempt++) {\n try {\n return await operation();\n } catch (error) {\n if (attempt >= opts.retries || !isRetryableError(error)) {\n throw error;\n }\n await new Promise((resolve) =>\n setTimeout(resolve, getDelayMs(attempt, opts)),\n );\n }\n }\n}\n","import { useErrorContext } from \"@/contexts/error-handling/error-context\";\nimport { NetworkError, ServerError } from \"@/lib/http\";\nimport { useCallback, useRef, useState } from \"react\";\n\n// Module-level cache and in-flight promise tracker\nconst cache = new Map<string, unknown>();\nconst inflight = new Map<string, Promise<unknown>>();\n\ninterface UseFetchOptions {\n dedupe?: boolean;\n}\n\ninterface UseFetchResult<T, E> {\n data: T | undefined;\n error: E | undefined;\n isLoading: boolean;\n fetch: () => Promise<T>;\n}\n\n/**\n * useFetch hook that deduplicates requests and prevents double-fetching.\n * Fetch is triggered by calling the returned fetch function, not automatically.\n * @param key Unique key for the resource (should uniquely identify the request)\n * @param fetcher Function that returns a promise for the data\n * @param options Options object (dedupe: boolean)\n */\nexport function useFetch<T, E = Error>(\n key: string,\n fetcher: () => Promise<T | undefined>,\n options?: UseFetchOptions,\n): UseFetchResult<T, E> {\n const dedupe = options?.dedupe !== false; // default to true\n const [data, setData] = useState<T | undefined>(\n () => cache.get(key) as T | undefined,\n );\n const { publishApiError, publishNetworkError } = useErrorContext();\n\n const [error, setError] = useState<E | undefined>(undefined);\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const mountedRef = useRef(true);\n\n // Clean up on unmount\n useRef(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n });\n\n const fetch = useCallback(async (): Promise<T> => {\n if (cache.has(key)) {\n const cachedData = cache.get(key) as T;\n setData(cachedData);\n return cachedData;\n }\n\n setIsLoading(true);\n setError(undefined);\n\n try {\n // If we have an in-flight request and dedupe is enabled, use that\n if (dedupe && inflight.has(key)) {\n return (await inflight.get(key)) as Promise<T>;\n }\n\n // Otherwise, create a new request\n const promise = fetcher();\n\n // Track it if deduplication is enabled\n if (dedupe) {\n inflight.set(key, promise);\n }\n\n // Await the result directly\n const result = await promise;\n\n // Update cache and state\n cache.set(key, result);\n if (mountedRef.current) {\n setData(result);\n }\n\n return result as T;\n } catch (err) {\n if (\n err instanceof NetworkError ||\n (err instanceof ServerError && err.status === 403)\n ) {\n publishNetworkError();\n } else {\n publishApiError(err as ServerError);\n }\n if (mountedRef.current) {\n setError(err as E);\n }\n throw err;\n } finally {\n // Clean up\n if (dedupe) {\n inflight.delete(key);\n }\n if (mountedRef.current) {\n setIsLoading(false);\n }\n }\n }, [key, dedupe, fetcher, publishApiError, publishNetworkError]);\n\n return { data, error, isLoading, fetch };\n}\n","import { useState } from \"react\";\nimport { usePersistence, type ChatData } from \"./use-persistence\";\n\ntype UserIdentityOptions = { appId: string; initialUserId?: string };\n\ntype UserIdentityReturn = {\n userId: string;\n deviceId: string;\n isReady: boolean;\n externalId?: string | null;\n};\n\ntype ResolvedIdentity = {\n userId: string;\n deviceId: string;\n externalId?: string | null;\n};\n\nfunction resolveUserIdentity(\n savedData: ChatData,\n initialUserId?: string,\n): ResolvedIdentity {\n const deviceId = savedData?.deviceId || crypto.randomUUID();\n\n if (!savedData?.userId) {\n if (initialUserId) {\n // TODO should we have an internal userId and a different externalId?\n return { userId: initialUserId, externalId: initialUserId, deviceId };\n }\n return { userId: crypto.randomUUID(), externalId: null, deviceId };\n }\n if (savedData.externalId !== initialUserId) {\n // If the externalId is the same as the initialUserId, we can use the saved userId\n return { userId: savedData.userId, externalId: initialUserId, deviceId };\n }\n return {\n userId: savedData.userId,\n externalId: savedData.externalId,\n deviceId,\n };\n}\n\n/**\n * Hook that manage to generate the userId and deviceId, this should be the source of truth when dealing with user identity\n * @returns\n */\nexport function useUserIdentity(\n options: UserIdentityOptions,\n): UserIdentityReturn {\n const { appId, initialUserId } = options;\n\n const { getSavedChatData } = usePersistence({ appId });\n\n // Resolved synchronously (localStorage reads are synchronous) so dependents\n // — the SDK boot effect — can start on the first commit instead of waiting\n // an extra render for a mount effect to fill the identity in.\n const [identity, setIdentity] = useState<ResolvedIdentity>(() =>\n resolveUserIdentity(getSavedChatData(), initialUserId),\n );\n\n // Host apps may pass `userId` late (e.g. after an async login). Re-resolve\n // during render (React's alternative to a mirror effect).\n const [prevInitialUserId, setPrevInitialUserId] = useState(initialUserId);\n if (prevInitialUserId !== initialUserId) {\n setPrevInitialUserId(initialUserId);\n setIdentity(resolveUserIdentity(getSavedChatData(), initialUserId));\n }\n\n return {\n // Identity is available synchronously; kept in the contract because\n // consumers (SDK boot) still key off it.\n isReady: true,\n userId: identity.userId,\n deviceId: identity.deviceId,\n externalId: identity.externalId,\n };\n}\n","\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\n\nimport { Message } from \"@/types/message\";\n\nimport { getApiUrl } from \"@/lib/config\";\nimport {\n BootResponse,\n EloquentAiApiClient,\n} from \"@/lib/eloquent-ai-api-client\";\nimport { wrapPromise } from \"@/lib/wrap-promise\";\nimport { withRetry } from \"@/lib/retry\";\n\nimport { useFetch } from \"@/hooks/use-fetch\";\n\nimport { createWelcomeMessage } from \"../message-mapping\";\nimport { usePersistence } from \"./use-persistence\";\nimport { useUserIdentity } from \"./use-user-identity\";\n\nexport interface UseSdkInitializationProps {\n environment: \"test\" | \"live\";\n apiUrl?: string;\n appId: string;\n initialUserId?: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n}\n\nexport interface UseSdkInitializationReturn {\n userId: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n externalId?: string | null;\n deviceId: string;\n apiClient: EloquentAiApiClient | null;\n chatSettings: BootResponse[\"chat_settings\"] | null;\n currentChat: { id: string } | null;\n messages: Message[];\n isReady: boolean;\n isChatClosed: boolean;\n isChatActive: boolean;\n}\n\n/**\n * Hook to handle SDK initialization for the EloquentAI Chat SDK\n * Handles API client initialization, saved conversation restoration, and SDK boot\n */\nexport function useSdkInitialization({\n apiUrl: apiUrlOverride,\n appId,\n initialUserId,\n userName,\n userData,\n}: UseSdkInitializationProps): UseSdkInitializationReturn {\n // Get a pair of userId and deviceId\n const {\n userId,\n externalId,\n deviceId,\n isReady: isUserIdentityReady,\n } = useUserIdentity({ appId, initialUserId });\n\n const { isChatExpired, clearChatData, getSavedChatData } = usePersistence({\n appId,\n });\n\n const { current: apiUrl } = useRef(apiUrlOverride || getApiUrl());\n const [apiClient] = useState<EloquentAiApiClient>(\n new EloquentAiApiClient({\n baseURL: apiUrl,\n appId: appId,\n }),\n );\n const [chatSettings, setChatSettings] = useState<\n BootResponse[\"chat_settings\"] | null\n >(null);\n const [currentChat, setCurrentChat] = useState<{\n id: string;\n } | null>(null);\n const [messages, setMessages] = useState<Message[]>([]);\n const [isReady, setIsReady] = useState(false);\n const [isChatClosed, setIsChatClosed] = useState(false);\n const [isChatActive, setIsChatActive] = useState(true);\n\n // Use a unique key to differentiate between Chat SDK instances with different appIds\n const sdkBoot = useFetch(`sdk-boot-${appId}`, () => apiClient.boot());\n const sdkBootFetch = sdkBoot.fetch;\n\n // Initialize API client on the client side only\n useEffect(() => {\n // Check if there's an existing conversation and if it's not expired\n if (!isChatExpired()) {\n const {\n conversationId: chatId,\n userId,\n messages: savedMessages,\n isChatClosed: savedIsChatClosed,\n chatToken: savedChatToken,\n } = getSavedChatData();\n\n if (chatId && userId) {\n setCurrentChat({\n id: chatId,\n });\n apiClient.setChatToken(savedChatToken ?? null);\n\n // If we have saved messages, use them\n if (savedMessages && savedMessages.length > 0) {\n setMessages(savedMessages);\n }\n\n if (savedIsChatClosed) {\n setIsChatClosed(true);\n }\n }\n } else {\n // Clear expired conversation data\n clearChatData();\n // The next API call will automatically generate a new device ID\n }\n }, [getSavedChatData, isChatExpired, clearChatData, apiClient]);\n\n // Boot the SDK exactly once, when the user identity becomes available. The\n // ref guard (rather than deps alone) keeps re-renders from re-firing the\n // org + boot requests: sdkBootFetch gets a new identity every render, so\n // without the guard the effect would re-run constantly.\n const hasBootedRef = useRef(false);\n useEffect(() => {\n if (!isUserIdentityReady || hasBootedRef.current) return;\n hasBootedRef.current = true;\n\n const bootSDK = async () => {\n // Step 1: Fetch organization data to get region\n const [orgResponse, orgError] = await wrapPromise(\n withRetry(() => apiClient.getOrganizationByAppId(appId)),\n );\n\n if (orgError) {\n console.error(\"Failed to fetch organization data:\", orgError);\n setIsChatActive(false);\n setIsReady(true);\n return;\n }\n\n // Step 2: Store region for subsequent API calls\n apiClient.setRegion(orgResponse.region);\n\n // Step 3: Now call boot endpoint\n const [response, error] = await wrapPromise(withRetry(sdkBootFetch));\n\n if (error) {\n setIsChatActive(false);\n setIsReady(true);\n return;\n }\n\n const welcomeMessage = response.chat_settings.welcome_message;\n\n setChatSettings(response.chat_settings);\n setIsChatActive(response.chat_settings.is_active ?? true);\n\n // Only set welcome message if we don't already have one (functional update to avoid race conditions)\n if (welcomeMessage) {\n setMessages((prev) => {\n if (prev.length > 0 || prev.some((m) => m.isWelcomeMessage))\n return prev;\n return [createWelcomeMessage(welcomeMessage)];\n });\n }\n\n setIsReady(true);\n };\n\n bootSDK();\n }, [isUserIdentityReady, apiClient, appId, sdkBootFetch]);\n\n return {\n userId,\n userName,\n userData,\n externalId,\n deviceId,\n apiClient,\n chatSettings,\n currentChat,\n messages,\n isReady,\n isChatClosed,\n isChatActive,\n };\n}\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n// Matches Tailwind's `sm` breakpoint; kept in sync with the mobile-only CSS rules.\nconst MOBILE_MEDIA_QUERY = \"(max-width: 640px)\";\n\n// matchMedia (not window.innerWidth) so the check reflects the actual visual\n// viewport used for layout on mobile browsers (browser chrome, pinch-zoom,\n// display-zoom accessibility settings), and computed lazily so the very first\n// render already reflects the real device instead of defaulting to desktop.\nfunction getIsMobileScreen(): boolean {\n if (typeof window === \"undefined\") return false;\n return window.matchMedia(MOBILE_MEDIA_QUERY).matches;\n}\n\n/**\n * Hook to handle UI initialization for the chat component\n * Handles mobile detection and portal container creation\n */\nexport function useUiInitialization(propIsMobile?: boolean): {\n isMobileScreen: boolean;\n isMobile: boolean;\n portalContainer: HTMLElement | null;\n} {\n const [isMobileScreen, setIsMobileScreen] = useState(getIsMobileScreen);\n const [portalContainer, setPortalContainer] = useState<HTMLElement | null>(\n null,\n );\n\n // Determine if mobile based on prop or screen size\n const isMobile = propIsMobile ?? isMobileScreen;\n\n const isSSR = typeof window === \"undefined\";\n\n // Check if the screen is mobile, and keep it in sync as the viewport changes\n useEffect(() => {\n if (isSSR) return;\n\n const mediaQueryList = window.matchMedia(MOBILE_MEDIA_QUERY);\n const handleChange = (event: MediaQueryList | MediaQueryListEvent) => {\n setIsMobileScreen(event.matches);\n };\n\n handleChange(mediaQueryList);\n mediaQueryList.addEventListener(\"change\", handleChange);\n return () => mediaQueryList.removeEventListener(\"change\", handleChange);\n }, [isSSR]);\n\n // Create a container for the chat interface\n useEffect(() => {\n if (isSSR) return;\n\n const container = document.createElement(\"div\");\n container.className = \"eloquent-ai-chat-portal\";\n container.style.position = \"relative\";\n container.style.zIndex = \"30\";\n document.body.appendChild(container);\n setPortalContainer(container);\n\n return () => {\n if (container.parentElement) {\n container.parentElement.removeChild(container);\n }\n };\n }, [isSSR]);\n\n return {\n isMobileScreen,\n isMobile,\n portalContainer,\n };\n}\n","\"use client\";\n\nimport { useDebounce } from \"@/hooks/use-debounce\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { Message, MessageData } from \"@/types/message\";\n\nimport { ThemeContextType } from \"@/contexts/theme.context\";\n\nimport { ChatInterfaceProps } from \"@/components/chat-interface\";\n\nimport { deleteCookie, getCookie, setCookie } from \"@/lib/cookies\";\n\nimport { useInterfaceProps } from \"./use-interface-props\";\nimport { useMessageEvents } from \"./use-message-events\";\nimport { useSdkInitialization } from \"./use-sdk-initialization\";\nimport { useUiInitialization } from \"./use-ui-initialization\";\n\n// How long we remember that the user closed the chat widget\nconst CHAT_CLOSED_COOKIE_TTL_HOURS = 2;\nconst getChatClosedCookieName = (appId: string) =>\n `eloquent-ai:chat-widget-closed-${appId}`;\n\nexport interface UseChatProps {\n appId: string;\n userId?: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n theme?: Partial<ThemeContextType>;\n chatProps?: Partial<ChatInterfaceProps>;\n isMobile?: boolean;\n /** Show the close (X) button in the chat header. */\n hasCloseButton?: boolean;\n /** Show the clear-conversation button in the chat header. */\n hasCleanChatButton?: boolean;\n /** Open the chat window on load (desktop only). */\n isInitiallyOpen?: boolean;\n /** @deprecated Use `hasCloseButton` instead. Ignored when `hasCloseButton` is set. */\n closeButton?: boolean;\n /** @deprecated Use `hasCleanChatButton` instead. Ignored when `hasCleanChatButton` is set. */\n cleanChatButton?: boolean;\n /** @deprecated Use `isInitiallyOpen` instead. Ignored when `isInitiallyOpen` is set. */\n initialOpen?: boolean;\n proactiveMessageHideDelay?: number;\n}\n\nexport interface UseChatReturn {\n isReady: boolean;\n isChatActive: boolean;\n /** Effective initial-open (boot chat_settings.initial_open ?? prop). */\n isInitiallyOpen: boolean;\n /** Effective close-button visibility (boot chat_settings.close_button ?? prop). */\n hasCloseButton: boolean;\n /** Effective clear-chat-button visibility (boot chat_settings.clean_chat_button ?? prop). */\n hasCleanChatButton: boolean;\n isMobile: boolean;\n chatInterfaceProps: Partial<ChatInterfaceProps>;\n chatOpen: boolean;\n chatOpenDebounced: boolean;\n messages: Message[];\n portalContainer: HTMLElement | null;\n onSendMessage: (message: MessageData) => Promise<void>;\n setChatOpen: (value: boolean | ((prev: boolean) => boolean)) => void;\n onCleanMessages: () => void;\n proactiveMessage?: {\n text: string;\n isVisible: boolean;\n autoHideDelay: number;\n };\n hideProactiveMessage: () => void;\n isChatClosed: boolean;\n onStartNewChat: () => void;\n onRateChat: (rating: number) => Promise<void>;\n}\n\n/**\n * The primary chat hook, responsible for managing the chat state and operations.\n * @param options The hook parameters\n * @returns The chat hook return type\n */\nexport function useChat({\n environment,\n apiUrl,\n appId,\n userId: initialUserId,\n userName,\n userData,\n chatProps,\n isMobile: propIsMobile,\n isInitiallyOpen: propIsInitiallyOpen,\n hasCloseButton: propHasCloseButton,\n hasCleanChatButton: propHasCleanChatButton,\n // Deprecated aliases, kept until hosts migrate to the is/has names above.\n initialOpen: deprecatedInitialOpen,\n closeButton: deprecatedCloseButton,\n cleanChatButton: deprecatedCleanChatButton,\n proactiveMessageHideDelay: propProactiveMessageHideDelay = 5000,\n isAlwaysOpen = false,\n hasCleanChatButtonOverride,\n}: Readonly<\n Partial<UseChatProps> & {\n environment: \"test\" | \"live\";\n apiUrl?: string;\n appId: string;\n /**\n * Internal-only kill-switch (INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON): when\n * set, wins over both the boot `chat_settings.clean_chat_button` and the\n * `hasCleanChatButton` prop. Leave undefined for the normal boot ?? prop\n * resolution.\n */\n hasCleanChatButtonOverride?: boolean;\n /**\n * Embedded mode (INTERNAL_ONLY_CHAT_INTERFACE_ONLY): the interface is the\n * page content and there is no launcher bubble to reopen a closed chat, so\n * open/close state does not apply — not the isInitiallyOpen prop, not the\n * boot `chat_settings.initial_open`, and not the closed-cookie. Without\n * this, a boot `initial_open: false` closes the widget from under the\n * host page a moment after it renders.\n */\n isAlwaysOpen?: boolean;\n }\n>): UseChatReturn {\n // Use UI initialization hook for mobile detection and portal container\n const { isMobile, portalContainer } = useUiInitialization(propIsMobile);\n\n // Use SDK initialization hook for API client, chat settings and conversation state\n const {\n userId,\n externalId,\n deviceId,\n apiClient,\n chatSettings,\n currentChat: initialChat,\n messages: initialMessages,\n isReady,\n isChatClosed: initialIsChatClosed,\n isChatActive,\n } = useSdkInitialization({\n environment,\n apiUrl,\n appId,\n initialUserId,\n userName,\n userData,\n });\n\n // Generate chat interface props\n const chatInterfaceProps = useInterfaceProps({ chatProps, chatSettings });\n\n // The is/has names are canonical; the deprecated aliases only apply when\n // the new name is absent.\n const propInitialOpen = propIsInitiallyOpen ?? deprecatedInitialOpen ?? false;\n const propCloseButton = propHasCloseButton ?? deprecatedCloseButton ?? true;\n const propCleanChatButton =\n propHasCleanChatButton ?? deprecatedCleanChatButton ?? true;\n\n const chatClosedCookieName = getChatClosedCookieName(appId);\n\n const [chatOpen, setChatOpenState] = useState(() => {\n if (isAlwaysOpen) return true;\n if (getCookie(chatClosedCookieName) === \"true\") return false;\n return isMobile ? false : (propInitialOpen ?? isMobile);\n });\n\n // The server can also drive the initial open (chat_settings.initial_open).\n // The boot value wins over the prop, but NOT over the user's 2-hour\n // closed-cookie: if the user explicitly closed the widget, a boot `true`\n // must not reopen it on the next page. A boot `false` still applies (the\n // server force-closing never fights the user). Boot resolves after mount,\n // so apply it once when settings arrive. The mobile guard also remains (a\n // full-screen overlay opening uninvited on mobile is too disruptive). Uses\n // the raw setter so a server-driven open/close never writes the closed\n // cookie itself.\n const [hasAppliedBootInitialOpen, setHasAppliedBootInitialOpen] =\n useState(false);\n useEffect(() => {\n if (!isReady || hasAppliedBootInitialOpen) return;\n setHasAppliedBootInitialOpen(true);\n\n if (isAlwaysOpen) return;\n const bootInitialOpen = chatSettings?.initial_open;\n if (bootInitialOpen == null) return;\n if (isMobile) return;\n if (bootInitialOpen && getCookie(chatClosedCookieName) === \"true\") return;\n setChatOpenState(bootInitialOpen);\n }, [\n isReady,\n hasAppliedBootInitialOpen,\n chatSettings?.initial_open,\n isMobile,\n chatClosedCookieName,\n isAlwaysOpen,\n ]);\n\n // Effective value (boot ?? prop) — e.g. the proactive message is\n // suppressed when the chat starts open.\n const isInitiallyOpen = chatSettings?.initial_open ?? propInitialOpen;\n\n // Same server-wins pattern for the header buttons and the proactive\n // message delay: an explicit boot value (including false) beats the prop.\n const hasCloseButton = chatSettings?.close_button ?? propCloseButton;\n // The internal-only override (when set) beats both boot and prop.\n const hasCleanChatButton =\n hasCleanChatButtonOverride ??\n chatSettings?.clean_chat_button ??\n propCleanChatButton;\n const proactiveMessageHideDelay =\n chatSettings?.proactive_message_hide_delay ?? propProactiveMessageHideDelay;\n\n // Wrap the setter so that closing the chat widget is remembered for 2\n // hours, and reopening it clears that memory. In always-open (embedded)\n // mode the widget cannot close at all, and must not write the closed-cookie\n // — it would leak into the real launcher widget for the same appId.\n const setChatOpen = useCallback<\n (value: boolean | ((prev: boolean) => boolean)) => void\n >(\n (value) => {\n if (isAlwaysOpen) return;\n setChatOpenState((prev) => {\n const next = typeof value === \"function\" ? value(prev) : value;\n if (next) {\n deleteCookie(chatClosedCookieName);\n } else {\n setCookie(chatClosedCookieName, \"true\", CHAT_CLOSED_COOKIE_TTL_HOURS);\n }\n return next;\n });\n },\n [chatClosedCookieName, isAlwaysOpen],\n );\n\n const chatOpenDebounced = useDebounce(chatOpen, 400);\n const [messages, setMessages] = useState<Message[]>(\n chatProps?.messages ?? [],\n );\n const [currentChat, setCurrentChat] = useState<{\n id: string;\n } | null>(initialChat);\n\n const [isChatClosed, setIsChatClosed] = useState(false);\n\n // Adopt values arriving asynchronously from SDK initialization (localStorage\n // restore, boot welcome message) into the locally-owned state. setState\n // during render instead of mirror effects: React restarts the render\n // immediately, so consumers never see the stale value for a frame.\n const [prevInitialMessages, setPrevInitialMessages] =\n useState(initialMessages);\n if (prevInitialMessages !== initialMessages) {\n setPrevInitialMessages(initialMessages);\n if (initialMessages.length > 0) setMessages(initialMessages);\n }\n\n const [prevInitialChat, setPrevInitialChat] = useState(initialChat);\n if (prevInitialChat !== initialChat) {\n setPrevInitialChat(initialChat);\n if (initialChat) setCurrentChat(initialChat);\n }\n\n // Restore the \"chat closed\" state saved to localStorage, so it survives a\n // page refresh.\n const [prevInitialIsChatClosed, setPrevInitialIsChatClosed] =\n useState(initialIsChatClosed);\n if (prevInitialIsChatClosed !== initialIsChatClosed) {\n setPrevInitialIsChatClosed(initialIsChatClosed);\n if (initialIsChatClosed) setIsChatClosed(true);\n }\n\n const handleChatClosed = useCallback(() => {\n setIsChatClosed(true);\n }, []);\n\n // The proactive (welcome) bubble is fully derived from boot settings; the\n // only real state is whether the user dismissed it.\n const [hasDismissedProactiveMessage, setHasDismissedProactiveMessage] =\n useState(false);\n const proactiveMessageText =\n isReady &&\n chatSettings?.auto_display_welcome_message &&\n chatSettings?.welcome_message\n ? chatSettings.welcome_message\n : \"\";\n const proactiveMessage = {\n text: proactiveMessageText,\n isVisible: proactiveMessageText !== \"\" && !hasDismissedProactiveMessage,\n autoHideDelay: proactiveMessageHideDelay,\n };\n\n // Use message events hook for sending and cleaning messages\n const { onSendMessage, onCleanMessages, onRateChat } = useMessageEvents({\n appId,\n userId,\n userName,\n userData,\n externalId,\n deviceId,\n apiClient,\n chatSettings,\n setMessages,\n messages,\n currentChat,\n setCurrentChat,\n onChatClosed: handleChatClosed,\n isChatClosed,\n });\n\n // Sync with initialMessages when they change (from SDK initialization)\n useEffect(() => {\n if (initialMessages.length > 0) {\n setMessages(initialMessages);\n }\n }, [initialMessages]);\n\n useEffect(() => {\n if (initialChat) {\n setCurrentChat(initialChat);\n }\n }, [initialChat]);\n\n // Identify the user once per distinct payload. Host apps often recreate the\n // `userData` object every render, so comparing by value (not identity)\n // prevents a duplicate network call per re-render.\n const lastIdentifyKeyRef = useRef<string | null>(null);\n useEffect(() => {\n if (!currentChat || !externalId || !apiClient) return;\n\n const identifyPayload = {\n userId,\n userName,\n userData,\n externalId,\n deviceId,\n conversationId: currentChat.id,\n };\n const identifyKey = JSON.stringify(identifyPayload);\n if (lastIdentifyKeyRef.current === identifyKey) return;\n lastIdentifyKeyRef.current = identifyKey;\n\n apiClient.identifyUser(identifyPayload);\n }, [\n externalId,\n userId,\n userName,\n userData,\n deviceId,\n currentChat,\n apiClient,\n ]);\n\n const onStartNewChat = useCallback(() => {\n onCleanMessages();\n setIsChatClosed(false);\n }, [onCleanMessages]);\n\n const hideProactiveMessage = useCallback(() => {\n setHasDismissedProactiveMessage(true);\n }, []);\n\n return {\n isReady,\n isChatActive,\n isInitiallyOpen,\n hasCloseButton,\n hasCleanChatButton,\n isMobile,\n chatInterfaceProps,\n chatOpen,\n chatOpenDebounced,\n messages,\n portalContainer,\n onSendMessage,\n setChatOpen,\n onCleanMessages,\n proactiveMessage,\n hideProactiveMessage,\n isChatClosed,\n onStartNewChat,\n onRateChat,\n };\n}\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n/**\n * Tracks how much the on-screen keyboard overlaps the layout viewport, using\n * the VisualViewport API. Used to lift the chat input above the keyboard\n * without moving/resizing the rest of the chat window.\n */\nexport function useKeyboardInset(enabled: boolean): number {\n const [inset, setInset] = useState(0);\n\n useEffect(() => {\n const viewport = window.visualViewport;\n if (!enabled || !viewport) {\n setInset(0);\n return;\n }\n\n const update = () => {\n const overlap = window.innerHeight - viewport.height - viewport.offsetTop;\n setInset(Math.max(0, Math.round(overlap)));\n };\n\n update();\n viewport.addEventListener(\"resize\", update);\n viewport.addEventListener(\"scroll\", update);\n\n return () => {\n viewport.removeEventListener(\"resize\", update);\n viewport.removeEventListener(\"scroll\", update);\n setInset(0);\n };\n }, [enabled]);\n\n return inset;\n}\n","\"use client\";\n\nimport { useEffect } from \"react\";\n\n/**\n * Locks scrolling on the host page while active. Uses the fixed-body trick\n * (rather than plain `overflow: hidden`) so it also holds on iOS Safari,\n * which otherwise still allows background scroll/bounce behind the chat.\n */\nexport function useScrollLock(locked: boolean) {\n useEffect(() => {\n if (!locked) return;\n\n const { body } = document;\n const scrollY = window.scrollY;\n const previousStyle = {\n position: body.style.position,\n top: body.style.top,\n left: body.style.left,\n right: body.style.right,\n overflow: body.style.overflow,\n };\n\n body.style.position = \"fixed\";\n body.style.top = `-${scrollY}px`;\n body.style.left = \"0\";\n body.style.right = \"0\";\n body.style.overflow = \"hidden\";\n\n return () => {\n body.style.position = previousStyle.position;\n body.style.top = previousStyle.top;\n body.style.left = previousStyle.left;\n body.style.right = previousStyle.right;\n body.style.overflow = previousStyle.overflow;\n window.scrollTo(0, scrollY);\n };\n }, [locked]);\n}\n","import { useCallback, useRef, useState } from \"react\";\n\nexport interface UseAgentCognitionReturn {\n isVisible: boolean;\n content: string | null;\n showCognition: (content?: string) => void;\n hideCognition: () => void;\n}\n\nexport function useAgentCognition(): UseAgentCognitionReturn {\n const [isVisible, setIsVisible] = useState(false);\n const [content, setContent] = useState<string | null>(null);\n const timerRef = useRef<NodeJS.Timeout | null>(null);\n const pendingContentRef = useRef<string | null>(null);\n\n const showCognition = useCallback((newContent = \"...\") => {\n const updateCognition = () => {\n setContent(newContent);\n setIsVisible(true);\n pendingContentRef.current = null;\n\n // Clear existing timer\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n }\n\n // Set timer to allow updates after 1 second minimum display time\n timerRef.current = setTimeout(() => {\n timerRef.current = null;\n\n // If there's pending content, show it immediately\n if (pendingContentRef.current) {\n updateCognition();\n }\n }, 1000);\n };\n\n // If no timer is active, update immediately\n if (!timerRef.current) {\n updateCognition();\n } else {\n // Timer is active, queue the new content\n pendingContentRef.current = newContent;\n }\n }, []);\n\n const hideCognition = useCallback(() => {\n // Clear timer and pending content\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n timerRef.current = null;\n }\n pendingContentRef.current = null;\n\n // Hide cognition\n setIsVisible(false);\n setContent(null);\n }, []);\n\n return {\n isVisible,\n content,\n showCognition,\n hideCognition,\n };\n}\n","import { ReactNode } from \"react\";\nimport { useAgentCognition } from \"@/contexts/agent-cognition/use-agent-cognition\";\nimport { AgentCognitionContext } from \"./agent-cognition-context\";\n\ninterface AgentCognitionProviderProps {\n children: ReactNode;\n}\n\nexport function AgentCognitionProvider({\n children,\n}: AgentCognitionProviderProps) {\n const cognition = useAgentCognition();\n\n return (\n <AgentCognitionContext.Provider value={cognition}>\n {children}\n </AgentCognitionContext.Provider>\n );\n}\n","import { useState, type ReactNode } from \"react\";\nimport { ErrorContext, SdkError, createPublishApiError } from \"./error-context\";\n\nexport const ErrorProvider = ({ children }: { children: ReactNode }) => {\n const [error, setError] = useState<SdkError | null>(null);\n const [hideSdk, setHideSdk] = useState(false);\n\n const publishApiError = createPublishApiError(setError);\n const publishError = (error: SdkError) => setError(error);\n const publishNetworkError = () => setHideSdk(true);\n const clearError = () => setError(null);\n\n const contextValue = {\n error,\n hideSdk,\n publishApiError,\n publishError,\n publishNetworkError,\n clearError,\n };\n\n return (\n <ErrorContext.Provider value={contextValue}>\n {children}\n </ErrorContext.Provider>\n );\n};\n","\"use client\";\n\nimport { type CSSProperties } from \"react\";\n\nimport mainCSS from \"@/index.css?inline\";\nimport wrapperCSS from \"@/wrapper.css?inline\";\n\nimport { Message } from \"@/types/message\";\n\nimport { cn } from \"@/lib/utils\";\n\nimport { ChatBubble } from \"@/components/embed/chat-bubble\";\nimport { ChatInterface } from \"@/components/chat-interface\";\nimport { SkeletonChatInterface } from \"@/components/chat-interface/skeleton\";\nimport { Iframe } from \"@/components/embed/iframe\";\nimport { Portal } from \"@/components/embed/portal\";\nimport { ProactiveMessage } from \"@/components/embed/proactive-message\";\n\nimport { useChat, type UseChatProps } from \"@/components/chat/hooks/use-chat\";\nimport { useKeyboardInset } from \"@/components/chat/hooks/use-keyboard-inset\";\nimport { useScrollLock } from \"@/components/chat/hooks/use-scroll-lock\";\nimport { AgentCognitionProvider } from \"@/contexts/agent-cognition/agent-cognition-provider\";\nimport { ErrorProvider } from \"@/contexts/error-handling/error-provider\";\nimport { useErrorContext } from \"@/contexts/error-handling/error-context\";\nimport { ThemeProvider } from \"@/contexts/theme.context\";\n\n/** Viewport inset (px) used to cap desktop chat height so it doesn’t overflow. */\nconst CHAT_DESKTOP_VIEWPORT_INSET_PX = 100;\n\n/** @internal */\ntype InternalChatProps = {\n INTERNAL_ONLY_CHAT_INTERFACE_ONLY?: boolean;\n INTERNAL_ONLY_BLOCK_STYLE?: boolean;\n /**\n * Force the clear-chat button on or off, winning over both the boot\n * `chat_settings.clean_chat_button` and the public `hasCleanChatButton`\n * prop. Leave unset to keep the normal boot ?? prop resolution.\n */\n INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON?: boolean;\n /** Show the copy-message button on assistant messages (default false). */\n INTERNAL_ONLY_SHOW_COPY_BUTTON?: boolean;\n INTERNAL_ONLY_ENVIRONMENT?: \"test\" | \"live\";\n INTERNAL_ONLY_API_URL?: string;\n INTERNAL_ONLY_FEATURE_MESSAGE_CLICK?: (message: Message) => void;\n INTERNAL_ONLY_FEATURE_CLEAR_CHAT_CLICK?: () => void;\n};\n\nexport type ChatProps = UseChatProps & InternalChatProps;\n\nfunction InternalChat({\n appId,\n userId,\n userName,\n userData,\n chatProps,\n proactiveMessageHideDelay = 5000,\n isMobile: propIsMobile,\n hasCloseButton: propHasCloseButton,\n hasCleanChatButton: propHasCleanChatButton,\n isInitiallyOpen: propIsInitiallyOpen,\n // Deprecated aliases, resolved in useChat (new name wins).\n closeButton: deprecatedCloseButton,\n cleanChatButton: deprecatedCleanChatButton,\n initialOpen: deprecatedInitialOpen,\n INTERNAL_ONLY_CHAT_INTERFACE_ONLY = false,\n INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON = undefined,\n INTERNAL_ONLY_BLOCK_STYLE = false,\n INTERNAL_ONLY_FEATURE_MESSAGE_CLICK = undefined,\n INTERNAL_ONLY_FEATURE_CLEAR_CHAT_CLICK = undefined,\n INTERNAL_ONLY_SHOW_COPY_BUTTON = false,\n INTERNAL_ONLY_ENVIRONMENT = \"live\",\n INTERNAL_ONLY_API_URL,\n}: Readonly<UseChatProps & InternalChatProps>) {\n const { hideSdk } = useErrorContext();\n\n const {\n isReady,\n isChatActive,\n isInitiallyOpen,\n hasCloseButton,\n hasCleanChatButton,\n isMobile,\n chatOpen,\n chatInterfaceProps,\n chatOpenDebounced,\n messages,\n portalContainer,\n onSendMessage,\n setChatOpen,\n proactiveMessage,\n hideProactiveMessage,\n isChatClosed,\n onStartNewChat,\n onRateChat,\n } = useChat({\n environment: INTERNAL_ONLY_ENVIRONMENT,\n apiUrl: INTERNAL_ONLY_API_URL,\n appId,\n userId,\n userName,\n userData,\n chatProps,\n isMobile: propIsMobile,\n isInitiallyOpen: propIsInitiallyOpen,\n hasCloseButton: propHasCloseButton,\n hasCleanChatButton: propHasCleanChatButton,\n initialOpen: deprecatedInitialOpen,\n closeButton: deprecatedCloseButton,\n cleanChatButton: deprecatedCleanChatButton,\n proactiveMessageHideDelay,\n // Embedded: the interface is the page content with no launcher to reopen\n // it, so nothing (boot initial_open, closed-cookie, props) may close it.\n isAlwaysOpen: INTERNAL_ONLY_CHAT_INTERFACE_ONLY,\n hasCleanChatButtonOverride: INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON,\n });\n\n const keyboardInset = useKeyboardInset(isMobile && chatOpen);\n useScrollLock(isMobile && chatOpen);\n\n const isBooting = !isReady;\n\n if (hideSdk) return null;\n // The launcher widget renders nothing until boot decides what to show. In\n // embedded mode the widget IS the page content: rendering null while a\n // remount boots (project/environment switch in the host app) collapses the\n // layout and flashes an empty hole — show the skeleton in place instead.\n if (isBooting && !INTERNAL_ONLY_CHAT_INTERFACE_ONLY) return null;\n if (!isBooting && !isChatActive) return null;\n\n const renderContent = () => {\n return (\n <div\n style={{\n WebkitTouchCallout: \"none\" /* iOS Safari */,\n WebkitUserSelect: \"none\" /* Safari */,\n KhtmlUserSelect: \"none\" /* Konqueror HTML */,\n MozUserSelect: \"none\" /* Old versions of Firefox */,\n msUserSelect: \"none\" /* Internet Explorer/Edge */,\n userSelect: \"none\" /* Chrome, Edge, Opera and Firefox */,\n position: \"fixed\",\n right: 12,\n bottom: 4,\n ...(INTERNAL_ONLY_BLOCK_STYLE\n ? { position: \"relative\", inset: 0, width: \"100%\", height: \"100%\" }\n : {}),\n }}\n >\n <style>{wrapperCSS}</style>\n <Iframe\n className=\"eloquentai-chat-messaging\"\n head={\n <>\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\" />\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" />\n <link\n href=\"https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap\"\n rel=\"stylesheet\"\n />\n <style>{mainCSS}</style>\n </>\n }\n style={\n {\n display: chatOpen\n ? \"block\"\n : chatOpenDebounced\n ? \"block\"\n : \"none\",\n width: isMobile ? \"100vw\" : \"400px\",\n // 100dvh accounts for mobile browser chrome (e.g. address bar); 100vh fallback for older browsers\n \"--chat-mobile-viewport-height\": \"100dvh\",\n height: isMobile\n ? \"var(--chat-mobile-viewport-height, 100vh)\"\n : \"700px\",\n maxHeight: isMobile\n ? \"var(--chat-mobile-viewport-height, 100vh)\"\n : `calc(100% - ${CHAT_DESKTOP_VIEWPORT_INSET_PX}px)`,\n border: \"none\",\n zIndex: 2147483000,\n position: \"fixed\",\n top: isMobile ? 0 : undefined,\n left: isMobile ? 0 : undefined,\n right: isMobile ? 0 : 16,\n bottom: isMobile ? 0 : 16,\n ...(INTERNAL_ONLY_BLOCK_STYLE\n ? {\n position: \"relative\",\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n width: \"100%\",\n height: \"100%\",\n maxHeight: \"100%\",\n zIndex: 0,\n }\n : {}),\n } as CSSProperties\n }\n >\n {isBooting ? (\n // Only reachable in embedded mode (the launcher returns null while\n // booting): hold the widget's frame with a skeleton so a remount —\n // project/environment switch in the host app — doesn't flash an\n // empty hole where the chat was.\n <SkeletonChatInterface isOpen isMobile={isMobile} skipAnimation />\n ) : (\n <ChatInterface\n {...chatInterfaceProps}\n // Embedded (interface-only) mode renders as page content: no\n // popup-style panel entrance.\n hasIntroAnimation={!INTERNAL_ONLY_CHAT_INTERFACE_ONLY}\n // Caution stripe: a session against the test agent must never be\n // mistaken for the production one.\n isTestMode={INTERNAL_ONLY_ENVIRONMENT === \"test\"}\n isOpen={chatOpen}\n keyboardInset={keyboardInset}\n messages={messages}\n onSendMessage={onSendMessage}\n onMessageClick={INTERNAL_ONLY_FEATURE_MESSAGE_CLICK}\n isMobile={isMobile}\n hasCloseButton={hasCloseButton}\n hasCleanChatButton={hasCleanChatButton}\n hasCopyButton={INTERNAL_ONLY_SHOW_COPY_BUTTON}\n isChatClosed={isChatClosed}\n onStartNewChat={onStartNewChat}\n onRateChat={onRateChat}\n onClose={() => setChatOpen(false)}\n onCleanChat={() => {\n onStartNewChat();\n INTERNAL_ONLY_FEATURE_CLEAR_CHAT_CLICK?.();\n }}\n />\n )}\n </Iframe>\n {!INTERNAL_ONLY_CHAT_INTERFACE_ONLY && (\n <Iframe\n className=\"eloquentai-chat-launcher\"\n head={<style>{mainCSS}</style>}\n style={{\n position: \"fixed\",\n bottom: 17,\n right: 17,\n display: \"block\",\n width: 48,\n height: 48,\n border: \"none\",\n zIndex: isMobile ? 2147482999 : 2147483000,\n opacity: chatOpen ? 0 : 1,\n pointerEvents: chatOpen ? \"none\" : \"auto\",\n transition: chatOpen\n ? \"opacity 100ms ease-in\"\n : \"opacity 200ms ease-out 320ms\",\n }}\n >\n <ChatBubble\n isOpen={chatOpen}\n toggleBubble={() => setChatOpen((prev) => !prev)}\n isDarkMode={chatInterfaceProps?.theme?.mode === \"dark\"}\n />\n </Iframe>\n )}\n {chatInterfaceProps?.displayWelcomeMessages ? (\n <Iframe\n className=\"eloquentai-chat-proactive-message\"\n head={<style>{mainCSS}</style>}\n style={{\n position: \"fixed\",\n // Aligns the bubble's tail with the launcher's center: the\n // launcher circle is 48px tall at bottom:17, so its center is\n // ~41px up; the tail sits ~16px above this iframe's bottom.\n bottom: 24,\n right: 17,\n }}\n >\n <ThemeProvider {...(chatInterfaceProps?.theme ?? {})}>\n {/* This iframe is outside the chat interface's dark-classed\n <main>, so dark: utilities need their own ancestor here. */}\n <div\n className={cn(\"eloq:w-full eloq:h-full\", {\n dark: chatInterfaceProps?.theme?.mode === \"dark\",\n })}\n >\n {proactiveMessage && !isInitiallyOpen && (\n <ProactiveMessage\n message={proactiveMessage.text}\n isVisible={proactiveMessage.isVisible}\n onDismiss={hideProactiveMessage}\n onMessageClick={() => {\n setChatOpen(true);\n hideProactiveMessage();\n }}\n autoHideDelay={proactiveMessage.autoHideDelay}\n />\n )}\n </div>\n </ThemeProvider>\n </Iframe>\n ) : null}\n </div>\n );\n };\n\n const renderChat = () => {\n if (INTERNAL_ONLY_BLOCK_STYLE) {\n return renderContent();\n }\n\n if (portalContainer) {\n return <Portal container={portalContainer}>{renderContent()}</Portal>;\n }\n\n return null;\n };\n\n return <>{renderChat()}</>;\n}\n\nexport function Chat(props: Readonly<ChatProps>) {\n return (\n <ErrorProvider>\n <AgentCognitionProvider>\n <InternalChat {...props} />\n </AgentCognitionProvider>\n </ErrorProvider>\n );\n}\n","import type { ComponentType } from \"react\";\nimport ReactDOMClient from \"react-dom/client\";\n\nimport { Chat, type ChatProps } from \"@/components/chat\";\n\ntype UnmountFunction = () => void;\n\nexport function renderChat(\n container: HTMLElement,\n props: ChatProps,\n): UnmountFunction {\n const render = (\n Component: ComponentType<ChatProps>,\n container: HTMLElement,\n props: ChatProps,\n ) => {\n const root = ReactDOMClient.createRoot(container);\n root.render(<Component {...props} />);\n return root.unmount;\n };\n return render(Chat, container, props);\n}\n"],"names":["environment","init","event","sensitiveHeaders","headers","key","ChatBubble","toggleBubble","isDarkMode","bubbleBackground","logoForeground","jsx","cn","Logo","Iframe","children","head","props","contentRef","setContentRef","useState","headNode","bodyNode","jsxs","createPortal","Portal","container","ProactiveMessage","message","isVisible","onDismiss","onMessageClick","autoHideDelay","shouldRender","setShouldRender","animationState","setAnimationState","theme","useTheme","useEffect","enterTimer","exitTimer","hideTimer","timer","getContrastingTextColor","e","X","getCookie","name","match","setCookie","value","hours","expires","deleteCookie","useInterfaceProps","chatProps","chatSettings","useMemo","useLatestRef","reference","useRef","NetworkError","ServerError","status","response","CHAT_TOKEN_HEADER","CHAT_TOKEN_RENEWED_HEADER","HttpClient","config","region","token","url","options","regionHeader","chatTokenHeader","error","renewedToken","responseData","data","getCurrentUrlSearchParams","params","result","STORAGE_NAMESPACE","isClient","CHAT_EXPIRY_TIME","usePersistence","appId","STORAGE_KEY","defaultObject","getSavedChatData","useCallback","storedData","isChatExpired","saveChatData","conversationId","userId","messages","deviceId","chatToken","chatData","markChatClosed","clearChatData","stored","updateLastActivity","APPSYNC_EVENTS_SUBPROTOCOL","HANDSHAKE_TIMEOUT_MILLISECONDS","DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS","KEEP_ALIVE_CHECK_INTERVAL_MILLISECONDS","WEB_SOCKET_OPEN_STATE","deriveRealtimeUrl","httpEndpoint","buildAuthorization","auth","host","encodeAuthProtocol","authorization","formatErrors","errors","connectAppSyncEvents","channel","onEvent","onDisconnect","createWebSocket","protocols","realtimeUrl","subscriptionId","resolve","reject","socket","phase","isClosedByClient","connectionTimeoutMilliseconds","lastLivenessTimestamp","handshakeTimer","keepAliveTimer","clearTimers","terminate","reason","wasEstablished","send","startHandshakeTimer","step","payload","jsonStringifyReplacer","_","Cached","getter","cached","cleanRegex","source","start","end","assignProp","target","prop","captureStackTrace","_args","isObject","escapeRegex","str","clone","inst","def","cl","normalizeParams","_params","optionalKeys","shape","k","aborted","x","startIndex","i","explicitlyAborted","prefixIssues","path","issues","iss","_a","unwrapMessage","attachSchema","finalizeIssue","ctx","traits","schemaError","full","members","proto","table","desc","defineBound","own","enumerable","hide","fn","claim","sentinel","installing","broke","breaker","defineLazyInternal","compute","outer","err","installLazyProp","make","_zodDesc","_E","newError","Definition","E","saved","$constructor","initializer","zodProto","Internals","protoMembers","initialized","ctorProto","up","installMembers","Parent","deferred","pp","$ZodAsyncError","globalConfig","newConfig","_getMessage","internals","util.jsonStringifyReplacer","_setMessage","_messageDesc","_issuesDesc","_installedToString","$ZodRealError","_parse","_Err","schema","_ctx","core.$ZodAsyncError","util.finalizeIssue","core.config","util.captureStackTrace","parse","errors.$ZodRealError","_parseAsync","parseAsync","_safeParse","failure","safeParse","Err","_safeParseAsync","safeParseAsync","anyString","_null","version","$ZodType","core.$constructor","defChecks","checks","ch","runChecks","isAborted","util.aborted","asyncResult","util.explicitlyAborted","currLen","util.attachSchema","handleCanaryResult","canary","checkResult","util.hide","standardProps","util.own","toStandardResult","r","validateAsync","$ZodString","regexes.anyString","$ZodNull","regexes.null","input","handlePropertyResult","final","optin","optout","isPresent","isOptionalOut","util.prefixIssues","NO_SYMBOL_KEYS","normalizeDef","keys","ownSymbols","symbolKeys","allKeys","okeys","util.optionalKeys","handleCatchall","proms","abortEarly","unrecognized","keySet","_catchall","t","seen","$ZodObject","sh","get","newSh","_normalized","util.cached","util.defineLazyInternal","zod","propValues","field","util.assignProp","v","util.isObject","catchall","memo","core.globalConfig","el","handleUnionResults","results","nonaborted","$ZodUnion","o","option","patterns","p","util.cleanRegex","first","async","$ZodLiteral","values","vals","util.escapeRegex","$ZodNullable","pattern","snapshotChecks","_string","Class","util.normalizeParams","ZodMiniType","core.$ZodType","parse.parse","parse.parseAsync","parse.safeParse","parse.safeParseAsync","_def","core.clone","reg","meta","args","ZodMiniString","core.$ZodString","string","core._string","ZodMiniNull","core.$ZodNull","core._null","ZodMiniObject","core.$ZodObject","util.installLazyProp","self","object","ZodMiniUnion","core.$ZodUnion","union","ZodMiniLiteral","core.$ZodLiteral","literal","ZodMiniNullable","core.$ZodNullable","nullable","innerType","zodConfig","utteranceSchema","z.object","z.literal","z.string","agentCognitionSchema","chatClosedExpiredSchema","agentCapturedUrlSchema","agentTopicSchema","agentSummarySchema","chatRatingSchema","breadcrumbSchema","chatEscalatedSchema","z.null","errorSchema","utteranceApiResponseSchema","z.nullable","errorApiResponseSchema","agentCognitionApiResponseSchema","chatClosedExpiredApiResponseSchema","agentCapturedUrlApiResponseSchema","agentTopicApiResponseSchema","agentSummaryApiResponseSchema","chatRatingApiResponseSchema","breadcrumbApiResponseSchema","chatEscalatedApiResponseSchema","chatResponseApiSchema","z.union","INITIAL_RECONNECT_DELAY_MS","MAX_RECONNECT_DELAY_MS","DEFAULT_BACKUP_POLL_INTERVAL_MS","useRealtimeSocket","chatId","onMessage","onCognition","onCognitionComplete","onError","onChatClosed","onAgentCapturedUrl","onAgentTopic","onAgentSummary","onRatingRequest","onBreadcrumb","fetchHistory","getChatToken","backupPollingInterval","processedIdsRef","msg","eventChannelRef","activeChatIdRef","reconnectAttemptsRef","reconnectTimerRef","backupPollIntervalRef","shouldReconnectRef","isReconnectingRef","onMessageRef","onCognitionRef","onCognitionCompleteRef","onErrorRef","onChatClosedRef","onAgentCapturedUrlRef","onAgentTopicRef","onAgentSummaryRef","onRatingRequestRef","onBreadcrumbRef","fetchHistoryRef","getChatTokenRef","publishError","useErrorContext","appSyncUrl","appSyncApiKey","isSocketConfigReady","appSyncUrlRef","appSyncApiKeyRef","closeChannel","stopBackupPoll","clearReconnectTimer","scheduleReconnectRef","connectChannel","chatIdToConnect","apiKey","connection","parseResult","notification","utterance","messageId","code","getErrorMessage","cognition","capturedUrl","topic","summary","runBackupPoll","chatIdToPoll","history","startBackupPoll","scheduleReconnect","scheduleReconnectSelf","chatIdToReconnect","delay","connect","disconnect","clearProcessedIds","messageFromChatResponse","createWelcomeMessage","content","createRatingRequestMessage","createChatClosedNoticeMessage","useMessageEvents","userName","userData","externalId","apiClient","setMessages","currentChat","setCurrentChat","isChatClosed","publishApiError","publishNetworkError","showCognition","hideCognition","useAgentCognitionContext","apiClientRef","onReceiveMessage","prev","updatedMessages","handleRealTimeError","handleRatingRequest","handleChatClosed","onCleanMessages","onSendMessage","userMessage","newMessages","connectError","onRateChat","rating","getEnvVariable","__vite_import_meta_env__","ENV_API_URL","ENV_REGION_API_URL","getApiUrl","getRegionApiUrl","EloquentAiApiClient","regionApiUrl","wrapPromise","promise","DEFAULT_OPTIONS","isRetryableError","getDelayMs","attempt","exponentialDelay","cappedDelay","withRetry","operation","opts","cache","inflight","useFetch","fetcher","dedupe","setData","setError","isLoading","setIsLoading","mountedRef","fetch","cachedData","resolveUserIdentity","savedData","initialUserId","useUserIdentity","identity","setIdentity","prevInitialUserId","setPrevInitialUserId","useSdkInitialization","apiUrlOverride","isUserIdentityReady","apiUrl","setChatSettings","isReady","setIsReady","setIsChatClosed","isChatActive","setIsChatActive","sdkBootFetch","savedMessages","savedIsChatClosed","savedChatToken","hasBootedRef","orgResponse","orgError","welcomeMessage","m","MOBILE_MEDIA_QUERY","getIsMobileScreen","useUiInitialization","propIsMobile","isMobileScreen","setIsMobileScreen","portalContainer","setPortalContainer","isMobile","isSSR","mediaQueryList","handleChange","CHAT_CLOSED_COOKIE_TTL_HOURS","getChatClosedCookieName","useChat","propIsInitiallyOpen","propHasCloseButton","propHasCleanChatButton","deprecatedInitialOpen","deprecatedCloseButton","deprecatedCleanChatButton","propProactiveMessageHideDelay","isAlwaysOpen","hasCleanChatButtonOverride","initialChat","initialMessages","initialIsChatClosed","chatInterfaceProps","propInitialOpen","propCloseButton","propCleanChatButton","chatClosedCookieName","chatOpen","setChatOpenState","hasAppliedBootInitialOpen","setHasAppliedBootInitialOpen","bootInitialOpen","isInitiallyOpen","hasCloseButton","hasCleanChatButton","proactiveMessageHideDelay","setChatOpen","next","chatOpenDebounced","useDebounce","prevInitialMessages","setPrevInitialMessages","prevInitialChat","setPrevInitialChat","prevInitialIsChatClosed","setPrevInitialIsChatClosed","hasDismissedProactiveMessage","setHasDismissedProactiveMessage","proactiveMessageText","proactiveMessage","lastIdentifyKeyRef","identifyPayload","identifyKey","onStartNewChat","hideProactiveMessage","useKeyboardInset","enabled","inset","setInset","viewport","update","overlap","useScrollLock","locked","body","scrollY","previousStyle","useAgentCognition","setIsVisible","setContent","timerRef","pendingContentRef","newContent","updateCognition","AgentCognitionProvider","AgentCognitionContext","ErrorProvider","hideSdk","setHideSdk","createPublishApiError","contextValue","ErrorContext","CHAT_DESKTOP_VIEWPORT_INSET_PX","InternalChat","INTERNAL_ONLY_CHAT_INTERFACE_ONLY","INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON","INTERNAL_ONLY_BLOCK_STYLE","INTERNAL_ONLY_FEATURE_MESSAGE_CLICK","INTERNAL_ONLY_FEATURE_CLEAR_CHAT_CLICK","INTERNAL_ONLY_SHOW_COPY_BUTTON","INTERNAL_ONLY_ENVIRONMENT","INTERNAL_ONLY_API_URL","keyboardInset","isBooting","renderContent","wrapperCSS","Fragment","mainCSS","SkeletonChatInterface","ChatInterface","ThemeProvider","Chat","renderChat","Component","root","ReactDOMClient"],"mappings":";;;;;;;;;;;AACA,IAAI,OAAO,SAAW,KAAa;AAIjC,QAAMA,IAAkD;AAMxD,SAAO,qBAAe,EAAE,KAAK,CAAC,EAAE,MAAAC,QAAW;AACzC,IAAAA,EAAK;AAAA,MACH,KAAK;AAAA,MACL,aAAAD;AAAA,MACA,gBAAgB;AAAA,MAChB,OAAO;AAAA,MACP,SAAS;AAAA,MACT,WAAWE,GAAO;AAChB,cAAMC,wBAAuB,IAAI;AAAA,UAC/B;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QAAA,CACD,GACKC,IAAUF,EAAM,SAAS;AAG/B,YAAIE;AACF,qBAAWC,KAAO,OAAO,KAAKD,CAAO;AACnC,YAAID,EAAiB,IAAIE,EAAI,YAAA,CAAa,MACxCD,EAAQC,CAAG,IAAI;AAIrB,eAAIH,EAAM,YACRA,EAAM,QAAQ,OAAO,eAEhBA;AAAA,MACT;AAAA,IAAA,CACD;AAAA,EACH,CAAC;AACH;;ACpCO,SAASI,GAAW;AAAA,EACzB,cAAAC;AAAA,EACA,YAAAC,IAAa;AACf,GAKG;AACD,QAAMC,IAAmBD,IAAa,SAAS,QACzCE,IAAiBF,IAAa,YAAY;AAEhD,SACE,gBAAAG,EAAC,OAAA,EAAI,WAAU,+GACb,UAAA,gBAAAA;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,WAAWC;AAAA,QACT;AAAA;AAAA,QAEAJ,I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,20]}
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../src/instrumentation.ts","../src/components/embed/chat-bubble.tsx","../src/components/embed/iframe.tsx","../src/components/embed/portal.tsx","../src/components/embed/proactive-message.tsx","../src/lib/cookies.ts","../src/components/chat/hooks/use-interface-props.ts","../src/hooks/use-latest-ref.ts","../src/lib/http.ts","../src/lib/url-params.ts","../src/components/chat/hooks/use-persistence.ts","../src/lib/appsync-events-client.ts","../node_modules/zod/v4/core/util.js","../node_modules/zod/v4/core/core.js","../node_modules/zod/v4/core/errors.js","../node_modules/zod/v4/core/parse.js","../node_modules/zod/v4/core/regexes.js","../node_modules/zod/v4/core/versions.js","../node_modules/zod/v4/core/schemas.js","../node_modules/zod/v4/core/api.js","../node_modules/zod/v4/mini/schemas.js","../src/components/chat/validations.ts","../src/components/chat/hooks/use-realtime-socket.ts","../src/components/chat/message-mapping.ts","../src/components/chat/hooks/use-message-events.ts","../src/lib/config.ts","../src/lib/eloquent-ai-api-client.ts","../src/lib/wrap-promise.ts","../src/lib/retry.ts","../src/hooks/use-fetch.ts","../src/components/chat/hooks/use-user-identity.ts","../src/components/chat/hooks/use-sdk-initialization.ts","../src/components/chat/hooks/use-ui-initialization.ts","../src/components/chat/hooks/use-chat.ts","../src/components/chat/hooks/use-keyboard-inset.ts","../src/components/chat/hooks/use-scroll-lock.ts","../src/contexts/agent-cognition/use-agent-cognition.ts","../src/contexts/agent-cognition/agent-cognition-provider.tsx","../src/contexts/error-handling/error-provider.tsx","../src/components/chat/chat.tsx","../src/components/embed/render-chat.tsx"],"sourcesContent":["// Only initialize Sentry on the client side\nif (typeof window !== \"undefined\") {\n // Transform Vite environment values to Sentry format\n // Access import.meta.env only on the client side to avoid SSR issues\n const viteEnv = import.meta.env.VITE_ENVIRONMENT as string | undefined;\n const environment = viteEnv === \"prod\" ? \"production\" : \"development\";\n const isLocal = viteEnv === \"local\";\n\n // Dynamically import Sentry to avoid SSR issues. Destructure only `init`:\n // holding the whole namespace would keep every barrel export (replay,\n // feedback, canvas integrations — hundreds of KB) alive in the bundle.\n import(\"@sentry/react\").then(({ init }) => {\n init({\n dsn: import.meta.env.VITE_SENTRY_DSN,\n environment,\n sendDefaultPii: false,\n debug: false,\n enabled: !isLocal,\n beforeSend(event) {\n const sensitiveHeaders = new Set([\n \"authorization\",\n \"cookie\",\n \"x-api-key\",\n \"x-auth-token\",\n ]);\n const headers = event.request?.headers as\n | Record<string, string>\n | undefined;\n if (headers) {\n for (const key of Object.keys(headers)) {\n if (sensitiveHeaders.has(key.toLowerCase())) {\n headers[key] = \"[Filtered]\";\n }\n }\n }\n if (event.request) {\n event.request.data = \"[Filtered]\";\n }\n return event;\n },\n });\n });\n}\n","\"use client\";\n\nimport { cn } from \"@/lib/utils\";\n\nimport { Logo } from \"@/components/logo\";\n\nexport function ChatBubble({\n toggleBubble,\n isDarkMode = false,\n}: {\n isOpen: boolean;\n toggleBubble: () => void;\n /** Renders in its own iframe (no `.dark` ancestor), so the mode arrives as a prop. */\n isDarkMode?: boolean;\n}) {\n const bubbleBackground = isDarkMode ? \"#fff\" : \"#000\";\n const logoForeground = isDarkMode ? \"#000000\" : \"#ffffff\";\n\n return (\n <div className=\"eloq:absolute eloq:inset-0 eloq:m-auto eloq:flex eloq:items-center eloq:justify-center eloq:overflow-hidden\">\n <div\n className={cn(\n \"eloq:chat-bubble eloq:relative eloq:flex eloq:items-center eloq:justify-center eloq:w-12 eloq:h-12 eloq:rounded-full eloq:cursor-pointer\",\n // Inverted in dark mode: a black launcher disappears on dark pages.\n isDarkMode\n ? \"eloq:bg-[#fff] eloq:text-[#000]\"\n : \"eloq:bg-[#000] eloq:text-[#fff]\",\n )}\n onClick={toggleBubble}\n >\n <div className=\"eloq:absolute eloq:inset-0 eloq:flex eloq:justify-center eloq:items-center eloq:m-auto\">\n <Logo bgColor={bubbleBackground} fgColor={logoForeground} />\n </div>\n </div>\n </div>\n );\n}\n","import { HTMLAttributes, PropsWithChildren, ReactNode, useState } from \"react\";\nimport { createPortal } from \"react-dom\";\n\ntype IframeProps = PropsWithChildren<HTMLAttributes<HTMLIFrameElement>> & {\n head: ReactNode;\n};\n\nexport function Iframe({ children, head, ...props }: IframeProps) {\n const [contentRef, setContentRef] = useState<HTMLIFrameElement | null>(null);\n const headNode = contentRef?.contentWindow?.document?.head;\n const bodyNode = contentRef?.contentWindow?.document?.body;\n return (\n <iframe {...props} ref={setContentRef}>\n {headNode && createPortal(head, headNode)}\n {bodyNode && createPortal(children, bodyNode)}\n </iframe>\n );\n}\n","\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport { createPortal } from \"react-dom\";\n\ninterface PortalProps {\n children: ReactNode;\n container: HTMLElement;\n}\n\nexport function Portal({ children, container }: PortalProps) {\n return createPortal(children, container);\n}\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport { X } from \"lucide-react\";\n\nimport { getContrastingTextColor } from \"@/lib/color-contrast\";\nimport { cn } from \"@/lib/utils\";\nimport { useTheme } from \"@/contexts/theme.context\";\n\nexport interface ProactiveMessageProps {\n message: string;\n isVisible: boolean;\n onDismiss: () => void;\n onMessageClick?: () => void;\n autoHideDelay?: number;\n}\n\nexport function ProactiveMessage({\n message,\n isVisible,\n onDismiss,\n onMessageClick,\n autoHideDelay,\n}: ProactiveMessageProps) {\n const [shouldRender, setShouldRender] = useState(false);\n const [animationState, setAnimationState] = useState<\n \"entering\" | \"visible\" | \"exiting\"\n >(\"entering\");\n const theme = useTheme();\n\n useEffect(() => {\n if (isVisible) {\n setShouldRender(true);\n setAnimationState(\"entering\");\n\n // Start entrance animation\n const enterTimer = setTimeout(() => {\n setAnimationState(\"visible\");\n }, 50);\n\n let exitTimer: ReturnType<typeof setTimeout> | undefined;\n const hideTimer = setTimeout(() => {\n setAnimationState(\"exiting\");\n // Start exit animation\n exitTimer = setTimeout(() => {\n onDismiss();\n }, 300);\n }, autoHideDelay);\n\n return () => {\n clearTimeout(enterTimer);\n clearTimeout(hideTimer);\n clearTimeout(exitTimer);\n };\n } else {\n setAnimationState(\"exiting\");\n // Delay hiding to allow for exit animation\n const timer = setTimeout(() => {\n setShouldRender(false);\n setAnimationState(\"entering\"); // Reset for next time\n }, 300);\n\n return () => clearTimeout(timer);\n }\n }, [isVisible, onDismiss, autoHideDelay]);\n\n if (!shouldRender) {\n return null;\n }\n\n return (\n <div\n className={cn(\n // right-16 leaves a ~7px gap between the tail tip and the launcher\n // circle's edge — the tail points at it without sliding underneath.\n \"eloq:absolute eloq:right-16 eloq:bottom-0 eloq:max-w-xs eloq:transform eloq:transition-all eloq:duration-500 eloq:ease-out\",\n animationState === \"entering\" &&\n \"eloq:translate-x-8 eloq:opacity-0 eloq:scale-95\",\n animationState === \"visible\" &&\n \"eloq:translate-x-0 eloq:opacity-100 eloq:scale-100\",\n animationState === \"exiting\" &&\n \"eloq:translate-x-8 eloq:opacity-0 eloq:scale-95\",\n )}\n >\n {/* drop-shadow (not box-shadow) so the shadow follows the combined\n silhouette of the bubble AND its tail as one continuous shape. */}\n <div className=\"eloq:relative eloq:drop-shadow-lg eloq:hover:drop-shadow-xl eloq:transition-all eloq:duration-300\">\n {/* Message bubble */}\n <div\n className=\"eloq:relative eloq:rounded-lg eloq:border eloq:p-3 eloq:cursor-pointer\"\n style={{\n backgroundColor: theme.botBubbleColor,\n }}\n onClick={onMessageClick}\n >\n {/* Tail: the original curved wedge, stroked so it carries the same\n 1px outline as the bubble (vector-effect keeps the stroke at\n real 1px despite the viewBox scaling). The cover rect hides the\n stroke along the attachment edge inside the bubble, so tail and\n bubble outlines merge into one shape. The SVG is mirrored\n (-scale-x-100), so low viewBox x is the outward tip and high x\n the attachment side. */}\n <svg\n aria-hidden\n className=\"eloq:absolute eloq:bottom-1 eloq:-right-[9px] eloq:h-4 eloq:w-4 eloq:-scale-x-100\"\n viewBox=\"0 0 10.54 11.14\"\n >\n {/* strokeWidth 2, not 1: SVG strokes are centered on the path, so\n half sits under the fill — 2 leaves exactly 1px visible\n outside, matching the bubble's 1px CSS border. */}\n <path\n d=\"M5.75,0s0,.36,0,.51c-.09,4.52-5.74,10.64-5.74,10.64,8.19.02,10.54-2.26,10.54-2.26h0c-1.6-2.96-3.19-5.92-4.79-8.88Z\"\n fill={theme.botBubbleColor}\n strokeWidth={2}\n vectorEffect=\"non-scaling-stroke\"\n style={{ stroke: \"hsl(var(--border))\" }}\n />\n <rect\n x=\"6.2\"\n y=\"-1\"\n width=\"6\"\n height=\"14\"\n fill={theme.botBubbleColor}\n />\n </svg>\n {/* The corner-pinned X is absolutely positioned and ignores the\n text flow entirely; pr-4 (16px, on top of the bubble's own\n 12px padding) keeps the text clear of the X's glyph. */}\n <p\n className=\"eloq:text-sm eloq:leading-relaxed eloq:pr-4\"\n style={{\n color:\n theme.botBubbleTextColor ||\n getContrastingTextColor(theme.botBubbleColor),\n }}\n >\n {message}\n </p>\n <button\n aria-label=\"Dismiss message\"\n onClick={(e) => {\n e.stopPropagation();\n onDismiss();\n }}\n // Pinned to the bubble's top-right corner, outside the text\n // flow — a flex-row placement can't tuck the glyph into the\n // padding area. p-1.5 keeps a 24px hit area around the 12px\n // icon; top/right-0.5 leaves the glyph ~8px from the edges.\n className=\"eloq:absolute eloq:top-0.5 eloq:right-0.5 eloq:p-1.5 eloq:opacity-50 eloq:hover:opacity-100 eloq:hover:bg-black/5 eloq:dark:hover:bg-white/10 eloq:rounded-full eloq:transition-all eloq:duration-200\"\n style={{\n // Follows the bubble's computed text colour, so the X blends\n // with the message on any bubble background (and dark mode).\n color:\n theme.botBubbleTextColor ||\n getContrastingTextColor(theme.botBubbleColor),\n }}\n >\n <X className=\"eloq:w-2.5 eloq:h-2.5\" strokeWidth={1.75} />\n </button>\n </div>\n </div>\n </div>\n );\n}\n","/**\n * Read a cookie value by name.\n * @returns The decoded cookie value, or null if it doesn't exist or there's no document.\n */\nexport function getCookie(name: string): string | null {\n if (typeof document === \"undefined\") return null;\n const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));\n return match ? decodeURIComponent(match[1]) : null;\n}\n\n/**\n * Set a cookie with a given name, value, and TTL in hours.\n */\nexport function setCookie(name: string, value: string, hours: number) {\n if (typeof document === \"undefined\") return;\n const expires = new Date(Date.now() + hours * 60 * 60 * 1000).toUTCString();\n document.cookie = `${name}=${encodeURIComponent(value)}; expires=${expires}; path=/; SameSite=Lax`;\n}\n\n/**\n * Delete a cookie by name.\n */\nexport function deleteCookie(name: string) {\n if (typeof document === \"undefined\") return;\n document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;\n}\n","\"use client\";\n\nimport { useMemo } from \"react\";\n\nimport type { BootResponse } from \"@/lib/eloquent-ai-api-client\";\n\nimport { ChatInterfaceProps } from \"@/components/chat-interface\";\n\nexport interface UseInterfacePropsParams {\n chatProps?: Partial<ChatInterfaceProps>;\n chatSettings: BootResponse[\"chat_settings\"] | null;\n}\n\n/**\n * Hook to handle chat interface properties generation\n * Combines user-provided props with server-provided settings\n */\nexport function useInterfaceProps({\n chatProps,\n chatSettings,\n}: UseInterfacePropsParams): Partial<ChatInterfaceProps> {\n const chatInterfaceProps = useMemo(() => {\n if (!chatSettings) return chatProps as Partial<ChatInterfaceProps>;\n\n return {\n assistantName: chatSettings.agent_name,\n assistantLogo: chatSettings.avatar_url || undefined,\n theme: {\n ...chatProps?.theme,\n mode: chatSettings.theme ?? \"light\",\n userBubbleColor:\n chatSettings.user_bubble_color || chatProps?.theme?.userBubbleColor,\n botBubbleColor:\n chatSettings.bot_bubble_color || chatProps?.theme?.botBubbleColor,\n suggestedMessageBubbleColor:\n chatSettings.suggested_message_bubble_color ||\n chatProps?.theme?.suggestedMessageBubbleColor,\n userBubbleTextColor:\n chatSettings.user_bubble_text_color ||\n chatProps?.theme?.userBubbleTextColor,\n botBubbleTextColor:\n chatSettings.bot_bubble_text_color ||\n chatProps?.theme?.botBubbleTextColor,\n suggestedMessageBubbleTextColor:\n chatSettings.suggested_message_bubble_text_color ||\n chatProps?.theme?.suggestedMessageBubbleTextColor,\n },\n welcomeMessage: chatSettings.welcome_message || undefined,\n legalText: chatSettings.footer_html || undefined,\n suggestedMessages: chatSettings.suggested_messages,\n suggestedMessageTexts: chatSettings.suggested_message_texts ?? undefined,\n // Boot value wins when the server sends one (?? so an explicit false\n // still wins); the host-app prop is the fallback.\n hasSuggestedMessageAura:\n chatSettings.suggested_message_aura ??\n chatProps?.hasSuggestedMessageAura,\n hasSuggestedMessageShine:\n chatSettings.suggested_message_shine ??\n chatProps?.hasSuggestedMessageShine,\n displayWelcomeMessages: chatSettings.auto_display_welcome_message,\n collectUserFeedback: chatSettings.collect_user_feedback,\n title: chatSettings.title || \"responds instantly\",\n subtitle: chatSettings.subtitle || \"Ask me anything\",\n };\n }, [chatProps, chatSettings]);\n\n return chatInterfaceProps;\n}\n","import { useEffect, useRef } from \"react\";\n\n/**\n * Returns a ref that always holds the latest `value`, updated after every\n * render. The \"latest ref\" pattern: long-lived closures (timers, socket\n * subscriptions) read `ref.current` at call time instead of capturing a\n * stale value, without needing the value in any dependency array.\n */\nexport function useLatestRef<Type>(value: Type): { readonly current: Type } {\n const reference = useRef(value);\n\n useEffect(() => {\n reference.current = value;\n });\n\n return reference;\n}\n","// Custom error class for network errors (CORS, fetch failures)\nexport class NetworkError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"NetworkError\";\n }\n}\n\n// Custom error class for server errors\nexport class ServerError extends Error {\n status: number;\n response: Record<string, Record<string, string | number>[]>;\n\n constructor(\n status: number,\n message: string,\n response: Record<string, Record<string, string | number>[]>,\n ) {\n super(message);\n this.name = \"ServerError\";\n this.status = status;\n this.response = response;\n }\n}\n\nexport interface HttpClientConfig {\n baseURL: string;\n appId: string;\n userId?: string;\n}\n\nconst CHAT_TOKEN_HEADER = \"x-elo-chat-token\";\nconst CHAT_TOKEN_RENEWED_HEADER = \"x-elo-chat-token-renewed\";\n\nexport class HttpClient {\n private baseURL: string;\n private headers: HeadersInit;\n private region: string | null = null;\n private chatToken: string | null = null;\n\n constructor(config: HttpClientConfig) {\n this.baseURL = config.baseURL;\n\n this.headers = {\n \"Content-Type\": \"application/json\",\n \"ELO-APP-ID\": config.appId,\n Origin: typeof window !== \"undefined\" ? window.location.origin : \"\",\n };\n }\n\n setRegion(region: string): void {\n this.region = region;\n }\n\n setChatToken(token: string | null): void {\n this.chatToken = token;\n }\n\n getChatToken(): string | null {\n return this.chatToken;\n }\n\n private async request<T>(url: string, options: RequestInit = {}): Promise<T> {\n const regionHeader: Record<string, string> = this.region\n ? { \"X-Region\": this.region }\n : {};\n const chatTokenHeader: Record<string, string> = this.chatToken\n ? { [CHAT_TOKEN_HEADER]: this.chatToken }\n : {};\n\n let response: Response;\n try {\n response = await fetch(`${this.baseURL}${url}`, {\n ...options,\n headers: {\n ...this.headers,\n ...regionHeader,\n ...chatTokenHeader,\n ...options.headers,\n },\n });\n } catch (error) {\n if (error instanceof TypeError) {\n throw new NetworkError(error.message);\n }\n throw error;\n }\n\n const renewedToken = response.headers.get(CHAT_TOKEN_RENEWED_HEADER);\n if (renewedToken) {\n this.chatToken = renewedToken;\n }\n\n let responseData;\n try {\n responseData = await response.json();\n } catch (e) {\n console.error(\"Error parsing JSON response:\", e);\n }\n\n if (!response.ok) {\n // Check for server errors (500 range)\n if (response.status >= 500) {\n throw new ServerError(response.status, \"API error\", responseData);\n }\n throw new ServerError(response.status, \"HTTP error\", responseData);\n }\n\n return responseData;\n }\n\n async get<T>(url: string) {\n return this.request<T>(url, { method: \"GET\" });\n }\n\n async post<T, D>(url: string, data: D): Promise<T> {\n return this.request<T>(url, {\n method: \"POST\",\n body: JSON.stringify(data),\n });\n }\n\n async put<T, D>(url: string, data: D): Promise<T> {\n return this.request<T>(url, {\n method: \"PUT\",\n body: JSON.stringify(data),\n });\n }\n\n /**\n * External GET request without default headers or credentials\n * Used for cross-origin requests that don't need authentication\n */\n async getExternal<T>(url: string): Promise<T> {\n const response = await fetch(url, {\n method: \"GET\",\n credentials: \"omit\",\n });\n\n let responseData;\n try {\n responseData = await response.json();\n } catch (e) {\n console.error(\"Error parsing JSON response:\", e);\n }\n\n if (!response.ok) {\n // Check for server errors (500 range)\n if (response.status >= 500) {\n throw new ServerError(response.status, \"API error\", responseData);\n }\n throw new ServerError(response.status, \"HTTP error\", responseData);\n }\n\n return responseData;\n }\n}\n","/**\n * Reads the current page URL search params from the host website.\n * Returns an empty object during SSR or when there are no query params.\n */\nexport function getCurrentUrlSearchParams(): Record<string, string> {\n if (typeof window === \"undefined\") {\n return {};\n }\n\n const params = new URLSearchParams(window.location.search);\n const result: Record<string, string> = {};\n\n params.forEach((value, key) => {\n result[key] = value;\n });\n\n return result;\n}\n","\"use client\";\n\nimport { useCallback, useMemo } from \"react\";\n\nimport { Message } from \"@/types/message\";\n\n// Single key for localStorage\nconst STORAGE_NAMESPACE = \"eloquent-ai::conversation-data\";\n\nconst isClient = typeof window !== \"undefined\";\n\n// 30 minutes in milliseconds\nconst CHAT_EXPIRY_TIME = 30 * 60 * 1000;\n\nexport interface ChatData {\n conversationId: string | null;\n userId: string | null;\n externalId?: string | null;\n deviceId: string | null;\n messages: Message[];\n lastActivity?: number;\n isChatClosed?: boolean;\n chatToken?: string | null;\n}\n\n/**\n * Hook to manage persistence of chat data, including conversation ID, user ID, last activity time, and messages.\n * @returns An object containing the conversation data and functions to set and clear the data.\n */\nexport function usePersistence({ appId }: { appId: string }) {\n const STORAGE_KEY = useMemo(() => `${STORAGE_NAMESPACE}-${appId}`, [appId]);\n const defaultObject = useMemo(\n () => ({\n conversationId: null,\n userId: null,\n deviceId: null,\n messages: [],\n }),\n [],\n );\n\n /**\n * Get saved conversation data from localStorage\n */\n const getSavedChatData = useCallback((): ChatData => {\n try {\n if (!isClient) return defaultObject;\n const storedData = localStorage.getItem(STORAGE_KEY);\n if (!storedData) {\n return defaultObject;\n }\n return JSON.parse(storedData) as ChatData;\n } catch (error) {\n console.error(\n \"Error retrieving conversation data from localStorage:\",\n error,\n );\n return defaultObject;\n }\n }, [STORAGE_KEY, defaultObject]);\n\n /**\n * Check if the current conversation has expired (inactive for more than 30 minutes)\n */\n const isChatExpired = useCallback((): boolean => {\n try {\n const data = getSavedChatData();\n if (!data.lastActivity) return true;\n\n const currentTime = Date.now();\n return currentTime - data.lastActivity > CHAT_EXPIRY_TIME;\n } catch (error) {\n console.error(\"Error checking conversation expiration:\", error);\n return true;\n }\n }, [getSavedChatData]);\n\n /**\n * Save conversation data to localStorage\n */\n const saveChatData = useCallback(\n (\n conversationId: string,\n userId: string,\n messages: Message[],\n deviceId: string,\n chatToken?: string | null,\n ) => {\n try {\n if (!isClient) return;\n const chatData: ChatData = {\n conversationId,\n userId,\n deviceId,\n messages,\n lastActivity: Date.now(),\n chatToken,\n };\n\n localStorage.setItem(STORAGE_KEY, JSON.stringify(chatData));\n } catch (error) {\n console.error(\"Error saving conversation data to localStorage:\", error);\n }\n },\n [STORAGE_KEY],\n );\n\n /**\n * Mark the current conversation as closed, so a page refresh still shows\n * the \"Start a new conversation\" screen instead of resetting it.\n */\n const markChatClosed = useCallback(() => {\n try {\n if (!isClient) return;\n const data = getSavedChatData();\n localStorage.setItem(\n STORAGE_KEY,\n JSON.stringify({ ...data, isChatClosed: true }),\n );\n } catch (error) {\n console.error(\n \"Error marking conversation as closed in localStorage:\",\n error,\n );\n }\n }, [STORAGE_KEY, getSavedChatData]);\n\n /**\n * Clear only conversationId, messages, and lastActivity from localStorage, preserving userId and deviceId\n */\n const clearChatData = useCallback(() => {\n try {\n if (!isClient) return;\n const stored = localStorage.getItem(STORAGE_KEY);\n if (stored) {\n const data = JSON.parse(stored);\n localStorage.setItem(\n STORAGE_KEY,\n JSON.stringify({\n ...defaultObject,\n deviceId: data.deviceId,\n userId: data.userId,\n }),\n );\n }\n } catch (error) {\n console.error(\n \"Error clearing conversation data from localStorage:\",\n error,\n );\n }\n }, [STORAGE_KEY, defaultObject]);\n\n /**\n * Update the last activity timestamp\n */\n const updateLastActivity = useCallback(() => {\n try {\n if (!isClient) return;\n const data = getSavedChatData();\n if (data.conversationId) {\n data.lastActivity = Date.now();\n localStorage.setItem(STORAGE_KEY, JSON.stringify(data));\n }\n } catch (error) {\n console.error(\"Error updating last activity timestamp:\", error);\n }\n }, [getSavedChatData, STORAGE_KEY]);\n\n return {\n isChatExpired,\n saveChatData,\n clearChatData,\n getSavedChatData,\n updateLastActivity,\n markChatClosed,\n };\n}\n","// Minimal AWS AppSync Events API real-time client — a hand-rolled\n// replacement for aws-amplify's `events.connect`, which carried ~160KB of\n// dependencies (amplify core, rxjs, graphql) for the tiny surface this SDK\n// uses: subscribe to one channel, deliver events, detect disconnects.\n//\n// Protocol reference: AWS \"Event API WebSocket protocol\" docs, cross-checked\n// against @aws-amplify/api-graphql's AWSAppSyncEventsProvider implementation\n// (subprotocol names, header encoding, keep-alive semantics, timeouts).\n//\n// Wire flow:\n// 1. Open a WebSocket to the realtime endpoint with two subprotocols:\n// \"aws-appsync-event-ws\" and \"header-<base64url(auth JSON)>\"\n// 2. Send {\"type\":\"connection_init\"}, await connection_ack (carries\n// connectionTimeoutMs — the keep-alive death window)\n// 3. Send subscribe with the SAME authorization embedded in the message\n// (per-operation auth is required by the protocol, not just per-connect)\n// 4. Receive {\"type\":\"data\", \"event\":\"<JSON string>\"} per published event\n// 5. Server sends {\"type\":\"ka\"} every ~60s; if neither ka nor data arrives\n// within connectionTimeoutMs, the connection is dead.\n\n/** Lambda-authorizer token (the chat token) or the API key fallback. */\nexport type AppSyncEventsAuth =\n | { authorizationToken: string }\n | { apiKey: string };\n\nexport type AppSyncEventsConnection = {\n /** Sends unsubscribe, closes the socket, and suppresses onDisconnect. */\n close: () => void;\n};\n\nexport type WebSocketLike = {\n readyState: number;\n send: (data: string) => void;\n close: () => void;\n addEventListener: (\n type: \"open\" | \"message\" | \"close\" | \"error\",\n listener: (event: { data?: unknown }) => void,\n ) => void;\n};\n\nexport type ConnectAppSyncEventsOptions = {\n /** The HTTP Events endpoint from boot settings (chat_settings.app_sync_url). */\n httpEndpoint: string;\n auth: AppSyncEventsAuth;\n /** Channel path, e.g. \"/default/chat/<chatId>\". */\n channel: string;\n /** Called once per published event, with the payload already JSON-parsed. */\n onEvent: (event: unknown) => void;\n /**\n * Called exactly once when an established connection dies (server close,\n * network drop, keep-alive timeout). NOT called after close(), and not\n * called for connections that never established (connect() rejects there).\n */\n onDisconnect: (reason: string) => void;\n /** Injectable for tests; defaults to the global WebSocket constructor. */\n createWebSocket?: (url: string, protocols: string[]) => WebSocketLike;\n};\n\nexport const APPSYNC_EVENTS_SUBPROTOCOL = \"aws-appsync-event-ws\";\n\n/** connection_init → connection_ack and subscribe → subscribe_success wait. */\nexport const HANDSHAKE_TIMEOUT_MILLISECONDS = 15000;\n/** Fallback keep-alive death window when the ack doesn't carry one. */\nexport const DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS = 300000;\n/** How often the keep-alive clock is checked. */\nexport const KEEP_ALIVE_CHECK_INTERVAL_MILLISECONDS = 5000;\n\nconst WEB_SOCKET_OPEN_STATE = 1;\n\n/**\n * Derives the realtime WebSocket URL from the HTTP Events endpoint.\n * Standard AWS domains swap the service subdomain; custom domains keep the\n * host and only append the path.\n * https://xxx.appsync-api.us-east-1.amazonaws.com/event\n * → wss://xxx.appsync-realtime-api.us-east-1.amazonaws.com/event/realtime\n * https://events.example.com/event\n * → wss://events.example.com/event/realtime\n */\nexport function deriveRealtimeUrl(httpEndpoint: string): string {\n const url = new URL(httpEndpoint);\n const isStandardAwsDomain =\n /\\.appsync-api\\.[\\w-]+\\.amazonaws\\.com(\\.cn)?$/.test(url.hostname);\n if (isStandardAwsDomain) {\n url.hostname = url.hostname.replace(\n \".appsync-api.\",\n \".appsync-realtime-api.\",\n );\n }\n url.protocol = \"wss:\";\n url.pathname = `${url.pathname.replace(/\\/$/, \"\")}/realtime`;\n return url.toString();\n}\n\n/**\n * The authorization object embedded both in the connect subprotocol header\n * and in every subscribe message. `host` is always the HTTP endpoint's host\n * (not the realtime host), per the protocol.\n */\nexport function buildAuthorization(\n httpEndpoint: string,\n auth: AppSyncEventsAuth,\n): Record<string, string> {\n const host = new URL(httpEndpoint).host;\n if (\"authorizationToken\" in auth) {\n return { Authorization: auth.authorizationToken, host };\n }\n return { \"x-api-key\": auth.apiKey, host };\n}\n\n/**\n * Encodes the authorization object into the `header-…` subprotocol value:\n * base64url (`+`→`-`, `/`→`_`) with padding stripped — `=` is not a legal\n * character in a Sec-WebSocket-Protocol token and fails the handshake.\n */\nexport function encodeAuthProtocol(\n authorization: Record<string, string>,\n): string {\n const base64 = btoa(JSON.stringify(authorization));\n return `header-${base64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\")}`;\n}\n\ntype ServerMessage = {\n type?: string;\n id?: string;\n event?: unknown;\n connectionTimeoutMs?: number;\n errors?: { errorType?: string; message?: string }[];\n};\n\nfunction formatErrors(errors: ServerMessage[\"errors\"]): string {\n if (!errors || errors.length === 0) return \"unknown error\";\n return errors\n .map((error) => `${error.errorType ?? \"Error\"}: ${error.message ?? \"\"}`)\n .join(\"; \");\n}\n\n/**\n * Opens a connection and subscribes to one channel. Resolves once the\n * subscription is confirmed; rejects if any handshake step fails or times\n * out (the socket is closed in that case). After resolution, connection\n * death is reported via onDisconnect exactly once.\n */\nexport function connectAppSyncEvents(\n options: ConnectAppSyncEventsOptions,\n): Promise<AppSyncEventsConnection> {\n const {\n httpEndpoint,\n auth,\n channel,\n onEvent,\n onDisconnect,\n createWebSocket = (url, protocols) =>\n new WebSocket(url, protocols) as WebSocketLike,\n } = options;\n\n const authorization = buildAuthorization(httpEndpoint, auth);\n const realtimeUrl = deriveRealtimeUrl(httpEndpoint);\n const subscriptionId = crypto.randomUUID();\n\n return new Promise<AppSyncEventsConnection>((resolve, reject) => {\n let socket: WebSocketLike;\n try {\n socket = createWebSocket(realtimeUrl, [\n APPSYNC_EVENTS_SUBPROTOCOL,\n encodeAuthProtocol(authorization),\n ]);\n } catch (error) {\n reject(error instanceof Error ? error : new Error(String(error)));\n return;\n }\n\n let phase: \"connecting\" | \"subscribing\" | \"established\" | \"closed\" =\n \"connecting\";\n let isClosedByClient = false;\n let connectionTimeoutMilliseconds = DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS;\n let lastLivenessTimestamp = Date.now();\n\n let handshakeTimer: ReturnType<typeof setTimeout> | null = null;\n let keepAliveTimer: ReturnType<typeof setInterval> | null = null;\n\n const clearTimers = () => {\n if (handshakeTimer) {\n clearTimeout(handshakeTimer);\n handshakeTimer = null;\n }\n if (keepAliveTimer) {\n clearInterval(keepAliveTimer);\n keepAliveTimer = null;\n }\n };\n\n /** Single funnel for connection death, in any phase. */\n const terminate = (reason: string) => {\n if (phase === \"closed\") return;\n const wasEstablished = phase === \"established\";\n phase = \"closed\";\n clearTimers();\n try {\n socket.close();\n } catch {\n // Already closed/closing.\n }\n if (isClosedByClient) return;\n if (wasEstablished) {\n onDisconnect(reason);\n } else {\n reject(new Error(reason));\n }\n };\n\n const send = (message: Record<string, unknown>) => {\n if (socket.readyState !== WEB_SOCKET_OPEN_STATE) return;\n socket.send(JSON.stringify(message));\n };\n\n const startHandshakeTimer = (step: string) => {\n if (handshakeTimer) clearTimeout(handshakeTimer);\n handshakeTimer = setTimeout(() => {\n terminate(`Timed out waiting for ${step}`);\n }, HANDSHAKE_TIMEOUT_MILLISECONDS);\n };\n\n socket.addEventListener(\"open\", () => {\n if (phase === \"closed\") return;\n send({ type: \"connection_init\" });\n startHandshakeTimer(\"connection_ack\");\n });\n\n socket.addEventListener(\"message\", (event) => {\n if (phase === \"closed\") return;\n\n let message: ServerMessage;\n try {\n message = JSON.parse(String(event.data)) as ServerMessage;\n } catch {\n console.warn(\"[EloquentChatSDK] Unparseable realtime frame ignored\");\n return;\n }\n\n switch (message.type) {\n case \"connection_ack\": {\n if (phase !== \"connecting\") return;\n phase = \"subscribing\";\n if (typeof message.connectionTimeoutMs === \"number\") {\n connectionTimeoutMilliseconds = message.connectionTimeoutMs;\n }\n send({\n type: \"subscribe\",\n id: subscriptionId,\n channel,\n authorization,\n });\n startHandshakeTimer(\"subscribe_success\");\n return;\n }\n case \"connection_error\": {\n terminate(`Connection error: ${formatErrors(message.errors)}`);\n return;\n }\n case \"subscribe_success\": {\n if (phase !== \"subscribing\" || message.id !== subscriptionId) return;\n phase = \"established\";\n if (handshakeTimer) {\n clearTimeout(handshakeTimer);\n handshakeTimer = null;\n }\n lastLivenessTimestamp = Date.now();\n keepAliveTimer = setInterval(() => {\n if (\n Date.now() - lastLivenessTimestamp >\n connectionTimeoutMilliseconds\n ) {\n terminate(\"Keep-alive timeout\");\n }\n }, KEEP_ALIVE_CHECK_INTERVAL_MILLISECONDS);\n resolve({\n close: () => {\n isClosedByClient = true;\n send({ type: \"unsubscribe\", id: subscriptionId });\n terminate(\"Closed by client\");\n },\n });\n return;\n }\n case \"subscribe_error\": {\n if (message.id !== subscriptionId) return;\n terminate(`Subscribe error: ${formatErrors(message.errors)}`);\n return;\n }\n case \"ka\": {\n lastLivenessTimestamp = Date.now();\n return;\n }\n case \"data\": {\n if (message.id !== subscriptionId) return;\n // A busy channel can delay ka frames; data proves liveness too\n // (mirrors the amplify client).\n lastLivenessTimestamp = Date.now();\n // The event field is a JSON *string* per the protocol.\n let payload: unknown = message.event;\n if (typeof payload === \"string\") {\n try {\n payload = JSON.parse(payload);\n } catch {\n console.warn(\n \"[EloquentChatSDK] Unparseable realtime event ignored\",\n );\n return;\n }\n }\n onEvent(payload);\n return;\n }\n case \"broadcast_error\": {\n console.warn(\n \"[EloquentChatSDK] Realtime broadcast error:\",\n formatErrors(message.errors),\n );\n return;\n }\n default:\n // unsubscribe_success and unknown/future frame types.\n return;\n }\n });\n\n socket.addEventListener(\"close\", () => {\n terminate(\"WebSocket closed\");\n });\n\n socket.addEventListener(\"error\", () => {\n // A close event follows an error; terminate here anyway so failures\n // that never fire close (some environments) still reject/notify.\n terminate(\"WebSocket error\");\n });\n });\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 toZod() {\n return (schema) => schema;\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}\n// the accessor lives on a shared prototype: an own accessor makes every box a dictionary-mode object (~360 B and a slow load per read against ~100 B and an inlined getter here)\nclass Cached {\n constructor(getter) {\n this._getter = getter;\n this._value = undefined;\n }\n get value() {\n const getter = this._getter;\n if (getter !== undefined) {\n this._value = getter();\n this._getter = undefined;\n }\n return this._value;\n }\n}\nexport function cached(getter) {\n return new Cached(getter);\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 // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin.\n const tolerance = 4 * 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}\n/**\n * Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it.\n *\n * Its keys and descriptors read without invoking anything, which is what lets a discriminated union check its discriminator, and the cycle walk read a shape, without resolving a getter that references the schema being constructed. A def that answers `shape` from an accessor of its own has none.\n */\nexport function rawShape(def) {\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n return desc?.get ? desc.get.raw : desc?.value;\n}\n// where a builder reads its source's keys and descriptors, resolving only a shape a def answers for itself. A shape resolves by object spread, so only its enumerable keys are ever part of it.\nfunction sourceShape(schema) {\n return rawShape(schema._zod.def) ?? schema._zod.def.shape;\n}\n// a key whose value is not settled yet, self-caching so every read after the first gets the same one\nfunction deferProp(target, key, getter) {\n Object.defineProperty(target, key, {\n get() {\n const value = getter();\n assignProp(this, key, value);\n return value;\n },\n enumerable: true,\n configurable: true,\n });\n}\n// Writes a settled key. A plain assignment is much cheaper than `defineProperty` and produces the same descriptor, but it runs whatever setter already answers to the key — an accessor this shape deferred, or an inherited one, which `__proto__` has on every object and prototype pollution can add for any name.\nfunction putProp(target, key, value) {\n if (key in target)\n assignProp(target, key, value);\n else\n target[key] = value;\n}\n/**\n * Copies `keys` of `source`'s shape onto `target`, each value passed through `wrap`.\n *\n * A key the source has resolved is copied through now, so the derived shape states it outright and nothing has to resolve it to learn what it holds. A key the source still defers stays deferred, and reads back through the source's own `shape`, so it resolves once and both shapes get that one schema.\n */\nfunction mirrorShape(target, source, keys, wrap) {\n const raw = sourceShape(source);\n for (const key of keys) {\n const desc = Object.getOwnPropertyDescriptor(raw, key);\n if (!desc.enumerable)\n continue;\n if (desc.get) {\n deferProp(target, key, () => {\n const value = source._zod.def.shape[key];\n return wrap ? wrap(value, key) : value;\n });\n }\n else\n putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);\n }\n}\n// same, for a plain shape a caller passed rather than a schema's\nfunction mirrorProps(target, source) {\n for (const key of Reflect.ownKeys(source)) {\n const desc = Object.getOwnPropertyDescriptor(source, key);\n if (!desc.enumerable)\n continue;\n if (desc.get)\n deferProp(target, key, () => source[key]);\n else\n putProp(target, key, desc.value);\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` 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 !== undefined && shape[k]._zod.optout === \"optional\";\n });\n}\n// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle.\nexport const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({\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 newShape = {};\n mirrorShape(newShape, schema, maskedKeys(schema, mask));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\n// the mask keys that select something, checked against the source's shape without resolving it\nfunction maskedKeys(schema, mask) {\n const raw = sourceShape(schema);\n const keys = [];\n // `for...in` skips symbols, so a symbol in the mask would select nothing\n for (const key of Reflect.ownKeys(mask)) {\n if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) {\n throw new Error(`Unrecognized key: \"${String(key)}\"`);\n }\n if (mask[key])\n keys.push(key);\n }\n return keys;\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 omitted = new Set(maskedKeys(schema, mask));\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key)));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\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. Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = sourceShape(schema);\n for (const key of Reflect.ownKeys(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 return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\n// the source's keys, then the caller's overlaid on top\nfunction extended(schema, shape) {\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));\n mirrorProps(newShape, shape);\n return newShape;\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\nexport function merge(a, b) {\n if (!b?._zod?.def) {\n throw new Error(\"Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.\");\n }\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 newShape = {};\n mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a)));\n mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b)));\n const def = mergeDefs(a._zod.def, {\n shape: newShape,\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, name = \"partial\") {\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(`.${name}() cannot be used on object schemas containing refinements`);\n }\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class &&\n ((value, key) => (selected && !selected.has(key) ? value : new Class({ type: \"optional\", innerType: value }))));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] }));\n}\nexport function required(Class, schema, mask) {\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => \n // overwrite with non-optional\n selected && !selected.has(key) ? value : new Class({ type: \"nonoptional\", innerType: value }));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape }));\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). 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}\n/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */\n/** The leading size checks of `defChecks` that set an upper bound, each paired with it. */\nexport function sizeCaps(defChecks) {\n const caps = [];\n for (const ch of defChecks ?? []) {\n const d = ch._zod.def;\n // a later check may rewrite the value\n if (!/_(length|size)$|_equals$/.test(d.check))\n break;\n const max = d.maximum ?? d.length ?? d.size;\n if (max >= 0)\n caps.push([max, ch]);\n }\n return caps;\n}\nexport function attachSchema(issues, start, inst) {\n var _a;\n for (let i = start; i < issues.length; i++) {\n (_a = issues[i]).schema ?? (_a.schema = inst);\n }\n}\nexport function finalizeIssue(iss, ctx, config) {\n var _a;\n // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead.\n const traits = iss.inst?._zod?.traits;\n if (traits?.has(\"$ZodType\")) {\n if (traits.has(\"$ZodCheck\"))\n (_a = iss).schema ?? (_a.schema = iss.inst);\n else\n iss.schema = iss.inst;\n }\n // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's.\n const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(schemaError?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n // an explicit own-key copy beats object rest with excluded keys, which v8 routes through a generic runtime call; Object.keys rather than for-in so an issue pushed with a prototype does not leak inherited keys, and an own __proto__ key is dropped rather than assigned through the setter\n const full = {};\n for (const k of Object.keys(iss)) {\n if (k === \"inst\" || k === \"schema\" || k === \"continue\" || k === \"input\" || k === \"__proto__\")\n continue;\n full[k] = iss[k];\n }\n full.path ?? (full.path = []);\n full.message = message;\n if (ctx?.reportInput) {\n full.input = iss.input;\n }\n return full;\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}\nconst highSurrogate = /[\\uD800-\\uDBFF]/;\n// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters.\nexport function codePointLength(str) {\n const units = str.length;\n if (!highSurrogate.test(str))\n return units;\n let count = units;\n for (let i = 0; i < units - 1; i++) {\n if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n count--;\n i++;\n }\n }\n return count;\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////////// PROTOTYPE INSTALLERS //////////\n//\n// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see \"The three axes\" in AGENTS.md.\n/**\n * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working.\n *\n * Call this from a `proto` initializer, which runs once per prototype — never per instance.\n */\nexport function members(proto, table) {\n for (const key in table) {\n const desc = Object.getOwnPropertyDescriptor(table, key);\n // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was\n if (desc.get)\n Object.defineProperty(proto, key, { ...desc, enumerable: false });\n // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()`\n else\n defineBound(proto, key, desc.value);\n }\n}\n/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */\nexport function own(inst, key, value, enumerable = true) {\n Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });\n return value;\n}\n/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */\nexport function hide(inst, key, value) {\n return own(inst, key, value, false);\n}\n/** Adds members a table derives from the instance: each builds on first read and shadows as own data, and assignment shadows the same way, as when these were own properties. */\nexport /*@__NO_SIDE_EFFECTS__*/ function derived(computes, table) {\n for (const key in computes) {\n const compute = computes[key];\n // an object literal's accessor is configurable and enumerable, and `members` copies the descriptor as written\n Object.defineProperty(table, key, {\n configurable: true,\n enumerable: true,\n get() {\n return own(this, key, compute(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n }\n return table;\n}\nfunction defineBound(proto, key, fn) {\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method\n return this == null ? fn : own(this, key, fn.bind(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n}\n/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */\nfunction claim(inst, sentinel) {\n const proto = Object.getPrototypeOf(inst);\n // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines.\n return sentinel in proto ? undefined : proto;\n}\n// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped.\nlet installing;\n// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation.\nlet broke = false;\nconst breaker = {\n configurable: true,\n get() {\n broke = true;\n return undefined;\n },\n};\n/**\n * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s\n * constructor, computed from the internals object itself and cached there on\n * first read. One accessor per constructor rather than one per instance.\n */\nexport function defineLazyInternal(inst, key, compute) {\n const proto = Object.getPrototypeOf(inst._zod);\n if (key in proto && installing !== inst._zod) {\n // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type.\n installing = undefined;\n return;\n }\n installing = inst._zod;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again.\n Object.defineProperty(this, key, breaker);\n const outer = broke;\n broke = false;\n try {\n const value = compute(this);\n // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included.\n if (broke)\n delete this[key];\n else\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n broke = broke || outer;\n return value;\n }\n catch (err) {\n // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read.\n delete this[key];\n broke = broke || outer;\n throw err;\n }\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n },\n });\n}\n/**\n * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own\n * data property. One accessor per constructor rather than one per instance, because an own accessor\n * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel.\n */\nexport function installLazyProp(inst, key, make, enumerable) {\n const proto = claim(inst, key);\n if (!proto)\n return;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid.\n const desc = { configurable: true, writable: true, enumerable, value: undefined };\n Object.defineProperty(this, key, desc);\n // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches\n desc.value = make(this);\n Object.defineProperty(this, key, desc);\n return desc.value;\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });\n },\n });\n}\n/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */\nexport const CONSTANT_CATCH = \"~constantCatch\";\n/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */\nexport function constantCatch(value) {\n const fn = () => value;\n fn[CONSTANT_CATCH] = true;\n return fn;\n}\n","var _a;\nimport { members as installMembers } from \"./util.js\";\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\n/* Shared descriptor for installing `_zod`; defineProperty reads it\n * synchronously, so reusing one object avoids a per-instance allocation. */\nconst _zodDesc = { value: undefined, enumerable: false };\n// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error\nlet _E = \"captureStackTrace\" in Error ? Error : null;\n// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot\nfunction newError(Definition) {\n const E = _E;\n if (E) {\n const saved = E.stackTraceLimit;\n if (typeof saved === \"number\") {\n try {\n E.stackTraceLimit = 0;\n }\n catch {\n _E = null;\n return new Definition();\n }\n try {\n return new Definition();\n }\n finally {\n E.stackTraceLimit = saved;\n }\n }\n }\n return new Definition();\n}\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, \n/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */\nproto, params) {\n // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance.\n const zodProto = {};\n // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy.\n function Internals(def) {\n this.def = def;\n this.constr = _;\n this.traits = new Set();\n }\n Internals.prototype = zodProto;\n const protoMembers = proto;\n // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait.\n const initialized = protoMembers && new WeakSet();\n function init(inst, def) {\n if (!inst._zod) {\n _zodDesc.value = new Internals(def);\n try {\n Object.defineProperty(inst, \"_zod\", _zodDesc);\n }\n finally {\n // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next.\n _zodDesc.value = undefined;\n }\n }\n else if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n if (initialized) {\n // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before.\n const own = Object.getPrototypeOf(inst);\n const ctorProto = inst._zod.constr.prototype;\n let up = own;\n while (up && up !== ctorProto)\n up = Object.getPrototypeOf(up);\n const target = up ?? own;\n if (!initialized.has(target)) {\n initialized.add(target);\n installMembers(target, protoMembers);\n }\n }\n // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype\n const proto = _.prototype;\n for (const k in proto) {\n if (!Object.prototype.hasOwnProperty.call(proto, k))\n continue;\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 const inst = params?.Parent ? newError(Definition) : this;\n init(inst, def);\n const deferred = inst._zod.deferred;\n if (deferred) {\n for (const fn of deferred) {\n fn();\n }\n // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime.\n inst._zod.deferred = undefined;\n }\n // Global post-processor hook. Internal: installed by `import \"zod/compile\"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation.\n const pp = globalThis.__zod_globalConfig?.postProcessor;\n if (pp)\n pp(inst);\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 = /*@__PURE__*/ 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 { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\n/* Computing the message eagerly is expensive (pretty-printed JSON of all\n * issues), so defer it until first read. The accessor functions and\n * descriptors are shared across instances to keep error construction\n * cheap; the computed message is cached on the internals object. The\n * setter preserves plain assignment semantics for consumers that\n * overwrite `message`. */\nfunction _getMessage() {\n const internals = this._zod;\n internals.message ?? (internals.message = JSON.stringify(internals.def, util.jsonStringifyReplacer, 2));\n return internals.message;\n}\nfunction _setMessage(value) {\n this._zod.message = value;\n}\nconst _messageDesc = {\n get: _getMessage,\n set: _setMessage,\n enumerable: true,\n configurable: true,\n};\nconst _issuesDesc = { value: undefined, enumerable: false };\n/* Prototypes that already carry the lazy `toString`. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n // `_zod` is already non-enumerable: $constructor's init defined it with this same descriptor\n _issuesDesc.value = def;\n Object.defineProperty(inst, \"issues\", _issuesDesc);\n // Clear the shared slot; a retained `value` pins the last error's issues.\n _issuesDesc.value = undefined;\n Object.defineProperty(inst, \"message\", _messageDesc);\n /* `toString` lives as a non-enumerable lazy getter on the shared\n * prototype; on first access it caches a per-instance closure so\n * detached usage still works. */\n const proto = Object.getPrototypeOf(inst);\n if (!_installedToString.has(proto)) {\n _installedToString.add(proto);\n Object.defineProperty(proto, \"toString\", {\n configurable: true,\n enumerable: false,\n get() {\n const value = () => this.message;\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n },\n });\n }\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, undefined, {\n Parent: Error,\n});\n/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member\n * (\"toString\", \"constructor\") would otherwise read through to the prototype, and assigning\n * \"__proto__\" would hit the setter instead of creating a key. */\nfunction node(obj, key, make) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) {\n if (key === \"__proto__\") {\n Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });\n }\n else {\n obj[key] = make();\n }\n }\n return obj[key];\n}\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 node(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 // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child.\n if (el === \"_errors\") {\n if (terminal)\n curr._errors.push(mapper(issue));\n i++;\n continue;\n }\n // A path element may collide with an inherited property name such as\n // \"__proto__\" or \"constructor\". Truthiness checks read the prototype\n // (so no node is created, then ._errors.push throws), and bracket\n // assignment of \"__proto__\" hits the setter instead of creating an\n // own key. Guard the read with hasOwnProperty and create the node\n // with defineProperty so any path element becomes a real own key.\n if (!Object.prototype.hasOwnProperty.call(curr, el)) {\n Object.defineProperty(curr, el, {\n value: { _errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n const node = curr[el];\n if (terminal) {\n node._errors.push(mapper(issue));\n }\n curr = node;\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;\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 // el may collide with an inherited property name (\"__proto__\",\n // \"constructor\", ...); ??= reads the prototype so the node is never\n // created and curr.errors.push throws. Guard with hasOwnProperty and\n // create the node with defineProperty so \"__proto__\" becomes a real\n // own key rather than invoking the prototype setter.\n if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) {\n Object.defineProperty(curr.properties, el, {\n value: { errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_a = curr.items)[el] ?? (_a[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\";\n// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two.\nfunction finalizeParams(callee, params) {\n return { callee: params?.callee ?? callee, Err: params?.Err };\n}\nexport const _parse = (_Err) => {\n const fn = (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 ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => {\n const fn = 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 ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\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 ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\n// the error is built on the first read of `error`: finalizing the issues and constructing the instance is most of a failing parse, and a caller that only branches on `success` never pays it. a getter in the literal keeps this small; the alternative, one shared accessor descriptor plus a hidden state slot, reads ~15% faster but costs ~75 B gzipped in every bundle\nfunction failure(Err, issues, ctx) {\n let error;\n return {\n success: false,\n get error() {\n if (!error) {\n error = new Err(issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n // finalizeIssue drops `input`, so the built error holds nothing; keeping the raw issues past this point pins the parsed value for the life of the result\n issues = undefined;\n ctx = undefined;\n }\n return error;\n },\n set error(e) {\n error = e;\n // a replacement makes the getter's branch unreachable, so the captures have to go here too\n issues = undefined;\n ctx = undefined;\n },\n };\n}\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 ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\n// registry mirrors of the compiler's sentinels, so this module never imports the compiler\nconst COMPILE_INVALID = /* @__PURE__ */ Symbol.for(\"zod.compile.invalid\");\nconst COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for(\"zod.compile.fallback\");\n// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema.\nexport const validate = ((schema, value, _ctx) => {\n const validator = schema._zod.bag.validator;\n if (validator !== undefined) {\n if (validator(value) !== COMPILE_INVALID)\n return true;\n // a definite sentinel means the runtime would reject, so skip the re-parse; a ctx can still change the answer\n if (validator.definite === true && _ctx === undefined)\n return false;\n }\n return validateFallback(schema, value, _ctx);\n});\nfunction validateFallback(schema, value, _ctx) {\n const ctx = _ctx\n ? { ..._ctx, async: false, abortEarly: true }\n : { async: false, abortEarly: true };\n const fallbackRun = schema._zod.bag.fallbackRun;\n let result;\n if (fallbackRun) {\n // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound\n ctx[COMPILE_FALLBACK] = true;\n result = fallbackRun({ value, issues: [] }, ctx);\n }\n else {\n result = schema._zod.run({ value, issues: [] }, ctx);\n }\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length === 0;\n}\n// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw\nexport const validateAsync = async (schema, value, _ctx) => {\n const ctx = _ctx\n ? { ..._ctx, async: true, abortEarly: true }\n : { async: true, abortEarly: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length === 0;\n};\nexport const _encode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return parse(schema, value, ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n return parse(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params)));\n };\n return fn;\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\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-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\nexport function nanoidOfLength(length) {\n return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);\n}\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-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\n// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. The leading lookahead then demands one anchor — a pictograph, a regional indicator, or the enclosing keycap — because `\\p{Emoji_Component}` on its own covers ASCII digits, `#`, `*`, ZWJ, variation selectors and skin tone modifiers, none of which is an emoji without a base.\nconst _emoji = `^(?=[\\\\s\\\\S]*[\\\\p{Extended_Pictographic}\\\\p{Regional_Indicator}\\\\u20E3])[\\\\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}:){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}|:))\\/(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_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;\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 = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,63}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro).\nexport const creditCard = /^\\d(?:[ -]?\\d){11,18}$/;\n// ISO 4217 alpha codes from the SIX list, regenerated by scripts/update-iso-4217.ts\nexport const currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/;\n// iban electronic format: 2-letter country, check digits 02-98 (the only values `98 - remainder` can produce), 11-30 bban characters\nexport const iban = /^[A-Z]{2}(?!00|01|99)\\d{2}[A-Z0-9]{11,30}$/;\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])))`;\n/** Anchors a pattern source. The interpolation lives here rather than at the call site because\n * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it\n * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */\nfunction anchor(source) {\n return new RegExp(`^${source}$`);\n}\nexport const date = /*@__PURE__*/ anchor(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 : args.seconds\n ? `${hhmm}:[0-5]\\\\d(?:\\\\.\\\\d+)?`\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 opts = [\"Z\"];\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 // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them\n const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join(\"|\")})`;\n const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\n// the unbounded form of `string()` as a literal, so every plain string shares one instance instead of building its own\nexport const anyString = /^[\\s\\S]{0,}$/;\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","export const version = {\n major: 4,\n minor: 6,\n patch: 7,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync } 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 defChecks = inst._zod.def.checks;\n // if inst is itself a checks.$ZodCheck, run it as a check\n const checks = inst._zod.traits.has(\"$ZodCheck\")\n ? [inst, ...(defChecks ?? [])]\n : defChecks?.length\n ? [...defChecks]\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 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 if (payload.memo)\n return payload;\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 util.attachSchema(payload.issues, currLen, inst);\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 util.attachSchema(payload.issues, currLen, inst);\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 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}, {\n // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", standardProps(this));\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n});\n/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */\n// a Standard Schema result only reports issues, so a failure finalizes them straight off the raw payload: no ZodError, and no lazy result to read through\nconst toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())) } : { value: r.value };\nasync function validateAsync(inst, value) {\n const ctx = { async: true };\n return toStandardResult((await inst._zod.run({ value, issues: [] }, ctx)), ctx);\n}\nexport function standardProps(inst) {\n return {\n validate: (value) => {\n const ctx = { async: false };\n try {\n const r = inst._zod.run({ value, issues: [] }, ctx);\n if (!(r instanceof Promise))\n return toStandardResult(r, ctx);\n }\n catch (_) { }\n // async function so a synchronously throwing check rejects instead of escaping validate\n return validateAsync(inst, value);\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 // a format's own pattern, else unbounded; a template literal derives the check-aware form itself\n inst._zod.pattern = def.pattern ?? regexes.anyString;\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});\n/** The `://` guard rejected the input before the URL constructor saw it. */\nexport const URL_BAD_FORMAT = 1;\n/** The URL parser rejected the input. */\nexport const URL_UNPARSEABLE = 2;\nexport function canParseURL(input) {\n try {\n if (typeof URL !== \"undefined\" && typeof URL.canParse === \"function\")\n return URL.canParse(input);\n new URL(input);\n return true;\n }\n catch {\n return false;\n }\n}\nexport function validateURL(trimmed, def) {\n if (!(\"normalize\" in def) && !(\"hostname\" in def) && !(\"protocol\" in def)) {\n return canParseURL(trimmed) || URL_UNPARSEABLE;\n }\n return parseURLObject(trimmed, def);\n}\n/** Parses a URL while preserving the non-normalizing HTTP guard. */\nexport function parseURLObject(trimmed, def) {\n // When normalize is off, require :// for http/https URLs. This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source && !/^https?:\\/\\//i.test(trimmed)) {\n return URL_BAD_FORMAT;\n }\n try {\n if (typeof URL !== \"undefined\") {\n const URLStatic = URL;\n if (typeof URLStatic.parse === \"function\")\n return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;\n }\n // @ts-ignore\n return new URL(trimmed);\n }\n catch {\n return URL_UNPARSEABLE;\n }\n}\nconst asciiTabOrNewline = /[\\t\\n\\r]/g;\n/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL(\"https://exa\\nmple.com\")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */\nexport function stripTabAndNewline(value) {\n return value.replace(asciiTabOrNewline, \"\");\n}\nexport function urlHostnameOk(url, hostname) {\n hostname.lastIndex = 0;\n return hostname.test(url.hostname);\n}\nexport function urlProtocolOk(url, protocol) {\n protocol.lastIndex = 0;\n return protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol);\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 const url = validateURL(trimmed, def);\n if (url === URL_BAD_FORMAT) {\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 if (url === URL_UNPARSEABLE) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === true) {\n payload.value = stripTabAndNewline(trimmed);\n return;\n }\n if (def.hostname && !urlHostnameOk(url, def.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 if (def.protocol && !urlProtocolOk(url, def.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 // Set the output value based on normalize flag\n payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);\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 if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))\n throw new Error(`Invalid nanoid length: ${def.length}`);\n def.pattern ?? (def.pattern = def.length === undefined ? regexes.nanoid : regexes.nanoidOfLength(def.length));\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});\n/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL(\"http://[...]\")` parses an authority, not an address, so `@` and `\\` re-delimit it and `\"::@1\\\\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `\"::1\\n\"` validated as `::1`. */\nconst ipv6Alphabet = /^[0-9a-fA-F:.]+$/;\nexport function isValidIPv6(value) {\n if (!ipv6Alphabet.test(value))\n return false;\n return canParseURL(`http://[${value}]`);\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.check = (payload) => {\n if (!isValidIPv6(payload.value)) {\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});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport function isValidCIDRv6(value) {\n const parts = value.split(\"/\");\n if (parts.length !== 2)\n return false;\n const [address, prefix] = parts;\n if (!prefix)\n return false;\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n return false;\n if (prefixNum < 0 || prefixNum > 128)\n return false;\n return isValidIPv6(address);\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 if (!isValidCIDRv6(payload.value)) {\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}\n// lax on purpose: the quantified regexes.base64 overflows the regex stack on multi-MB input and its leading ^$| alternation leaks through template-literal composition; isValidBase64 enforces length and padding\nexport const base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = base64Charset);\n $ZodStringFormat.init(inst, def);\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////////////////////////////// ZodBase64URL //////////////////////////////\n// lax on purpose: the quantified regexes.base64url overflows the regex stack on multi-MB input; isValidBase64 enforces length on the padded string\nexport const base64urlCharset = /^[A-Za-z0-9_-]*$/;\nexport function isValidBase64URL(data) {\n if (!base64urlCharset.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 = base64urlCharset);\n $ZodStringFormat.init(inst, def);\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////////////////////////////// ZodCreditCard //////////////////////////////\nconst CC_SANITIZE = /[- ]/g;\n/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */\nfunction isLuhnAlgo(digits) {\n let length = digits.length;\n let bit = 1;\n let sum = 0;\n while (length) {\n const value = digits.charCodeAt(--length) - 48;\n bit ^= 1;\n sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value;\n }\n return sum % 10 === 0;\n}\nexport function isValidCreditCard(input) {\n if (!regexes.creditCard.test(input))\n return false;\n return isLuhnAlgo(input.replace(CC_SANITIZE, \"\"));\n}\nexport const $ZodCreditCard = /*@__PURE__*/ core.$constructor(\"$ZodCreditCard\", (inst, def) => {\n // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone.\n def.pattern ?? (def.pattern = regexes.creditCard);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidCreditCard(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"credit_card\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodIBAN //////////////////////////////\n// iso 7064 mod 97-10 checksum without BigInt\nfunction isIso7064Mod97(iban) {\n let remainder = 0;\n const len = iban.length;\n for (let i = 4; i < len; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n for (let i = 0; i < 4; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n return remainder === 1;\n}\nexport function isValidIBAN(input) {\n if (!regexes.iban.test(input))\n return false;\n return isIso7064Mod97(input);\n}\nexport const $ZodIBAN = /*@__PURE__*/ core.$constructor(\"$ZodIBAN\", (inst, def) => {\n // shape only — checksum is not expressible as a pattern\n def.pattern ?? (def.pattern = regexes.iban);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidIBAN(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"iban\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\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 = 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 ? String(input)\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});\n// an oversized container fails its leading size checks before any element is parsed\nfunction capSize(inst, size) {\n const caps = util.sizeCaps(inst._zod.def.checks);\n if (!caps.length)\n return;\n const cap = Math.min(...caps.map((c) => c[0]));\n const parse = inst._zod.parse;\n inst._zod.parse = (payload, ctx) => {\n const n = size(payload.value);\n if (n > cap && !ctx?.skipChecks && ctx?.direction !== \"backward\") {\n for (const [max, ch] of util.sizeCaps(inst._zod.def.checks)) {\n if (n > max && ch._zod.def.when(payload)) {\n const start = payload.issues.length;\n ch._zod.check(payload);\n // the value is still the raw input, so no later check may read it\n payload.issues[start].continue = false;\n util.attachSchema(payload.issues, start, inst);\n return payload;\n }\n }\n }\n return parse(payload, ctx);\n };\n}\nconst arraySize = (input) => (Array.isArray(input) ? input.length : -1);\nconst mapSize = (input) => (input instanceof Map ? input.size : -1);\nconst setSize = (input) => (input instanceof Set ? input.size : -1);\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 const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\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 = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);\n const proms = [];\n const abortEarly = ctx?.abortEarly;\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 // the element's payload is authoritative here, since handleArrayResult forwards every issue; an object's is not, because it drops a failed absent optional\n if (abortEarly && result.issues.length !== 0 && util.aborted(result))\n break;\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n capSize(inst, arraySize);\n});\nfunction handlePropertyResult(result, final, key, input, optin, optout) {\n const isPresent = key in input;\n const isOptionalOut = optout === \"optional\";\n // The middle rung means \"absence permitted, nothing supplied in its place\", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key.\n if (!isPresent && isOptionalOut && optin === \"optional\") {\n return;\n }\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (optin !== undefined && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && optin === undefined) {\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 || (optin === \"defaulted\" && !isOptionalOut)) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\n// one shared instance; a fresh [] per schema cost 56 bytes retained\nconst NO_SYMBOL_KEYS = [];\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n const ownSymbols = Object.getOwnPropertySymbols(def.shape);\n const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;\n // aliases `keys` when there are no symbols, so a string-only shape keeps one array\n const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;\n for (const k of allKeys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${String(k)}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n allKeys,\n symbolKeys,\n // string-only: handleCatchall matches it against `for...in`, which never yields a symbol\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const optin = _catchall.optin;\n const optout = _catchall.optout;\n // starts at 0, not the current length: the shape phase already ran and may have aborted\n let seen = 0;\n for (const key in input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output.\n if (keySet.has(key))\n continue;\n // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping.\n if (key === \"__proto__\") {\n if (t === \"never\")\n unrecognized.push(key);\n continue;\n }\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, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand.\n continue: true,\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 desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n // a cloned def carries its source's accessor, which knows the shape it answers from; adopting that keeps the clone's keys readable without running it\n const sh = desc?.get ? desc.get.raw : (def.shape ?? {});\n if (sh) {\n // Freezes the shape on first read, so its getters resolve once and every later read sees the same schemas.\n const get = () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", { value: newSh });\n get.raw = newSh;\n return newSh;\n };\n get.raw = sh;\n Object.defineProperty(def, \"shape\", { get });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const shape = zod.def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n if (!Object.prototype.hasOwnProperty.call(propValues, key)) {\n util.assignProp(propValues, key, new Set());\n }\n for (const v of field.values)\n propValues[key].add(v);\n // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it.\n if (field.optin !== undefined)\n propValues[key].add(undefined);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\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 = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const proms = [];\n const shape = value.shape;\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const key of value.allKeys) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n if (key === \"__proto__\")\n continue;\n const el = shape[key];\n const optin = el._zod.optin;\n const optout = el._zod.optout;\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, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\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, abortEarly === true);\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 memo = core.globalConfig.memoizer;\n const generateFastpass = (shape) => {\n const normalized = _normalized.value;\n const syms = normalized.symbolKeys;\n // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope\n const doc = new Doc([\"payload\", \"ctx\"], { shape, inst, memo, syms });\n const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n // prefixes in place, like util.prefixIssues. newResult must land before the early return: a catchall runs after this and would otherwise write onto the caller's input\n const prefixStr = (id, k) => `\n let ${id}_ab = false;\n for (let i = 0; i < ${id}.issues.length; i++) {\n const iss = ${id}.issues[i];\n iss.path = iss.path ? [${k}, ...iss.path] : [${k}];\n payload.issues.push(iss);\n if (iss.continue !== true) ${id}_ab = true;\n }\n if (${id}_ab && ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }`;\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.allKeys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);\n for (const key of normalized.allKeys) {\n if (key === \"__proto__\")\n continue;\n const id = ids[key];\n const k = typeof key === \"symbol\" ? `syms[${syms.indexOf(key)}]` : util.esc(key);\n const isPresent = `${k} in input`;\n const schema = shape[key];\n const optin = schema?._zod?.optin;\n const isOptionalIn = optin !== undefined;\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(k)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all.\n const assign = optin === \"optional\" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;\n doc.write(`\n const ${id}_present = ${isPresent};\n if (!${id}.issues.length || ${id}_present) {\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n\n if (${assign}) {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${isPresent};\n if (${id}.issues.length) {${prefixStr(id, k)}\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 if (ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }\n }\n\n if (${id}_present) {\n newResult[${k}] = ${id}.value;\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n `);\n if (optin === \"defaulted\") {\n doc.write(`newResult[${k}] = ${id}.value;`);\n }\n else {\n doc.write(`\n if (${id}.value !== undefined || ${isPresent}) {\n newResult[${k}] = ${id}.value;\n }\n `);\n }\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone\n return doc.compile();\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, ctx?.abortEarly === true);\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.defineLazyInternal(inst, \"optin\", (zod) => zod.def.options.some((o) => o._zod.optin === \"defaulted\")\n ? \"defaulted\"\n : zod.def.options.some((o) => o._zod.optin !== undefined)\n ? \"optional\"\n : undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n if (zod.def.options.every((o) => o._zod.values)) {\n return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n if (zod.def.options.every((o) => o._zod.pattern)) {\n const patterns = zod.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 matches = [];\n for (let i = 0; i < results.length; i++) {\n if (results[i].issues.length === 0)\n matches.push(i);\n }\n if (matches.length === 1) {\n final.value = results[matches[0]].value;\n return final;\n }\n if (matches.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 matches,\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});\n/** Returns the option whose discriminator claims `value`, or throws if ambiguous. */\nexport function getDiscriminatedOption(union, value) {\n const internals = union._zod;\n let map = internals.bag.optionsMap;\n if (!map) {\n map = discriminatorMap(internals.def);\n internals.bag.optionsMap = map;\n }\n const option = map.get(value);\n if (option === null)\n throw new Error(`Ambiguous discriminator value \"${String(value)}\"`);\n return option;\n}\nfunction discriminatorMap(def) {\n const map = new Map();\n for (const option of def.options) {\n const values = option._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const value of values) {\n if (map.has(value)) {\n if (value !== undefined)\n throw new Error(`Duplicate discriminator value \"${String(value)}\"`);\n // keep the collision marked so a later member cannot reclaim it\n map.set(value, null);\n }\n else {\n map.set(value, option);\n }\n }\n }\n return map;\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.defineLazyInternal(inst, \"propValues\", (zod) => {\n const propValues = {};\n let undefinedCount = 0;\n for (const option of zod.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 \"${zod.def.options.indexOf(option)}\"`);\n if (pv[zod.def.discriminator]?.has(undefined))\n undefinedCount++;\n for (const [k, v] of Object.entries(pv)) {\n if (!Object.prototype.hasOwnProperty.call(propValues, k)) {\n util.assignProp(propValues, k, new Set());\n }\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n if (!zod.def.unionFallback && undefinedCount > 1)\n propValues[zod.def.discriminator]?.delete(undefined);\n return propValues;\n });\n // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes and lazies — are left to the map.\n def.options.forEach((option, i) => {\n const propShape = util.rawShape(option._zod.def);\n if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {\n throw new Error(`Invalid discriminated union option at index \"${i}\"`);\n }\n });\n const disc = util.cached(() => discriminatorMap(def));\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 value = input?.[def.discriminator];\n const opt = disc.value.get(value);\n // forward metadata cannot choose an encoder for an absent tag\n if (opt && (value !== undefined || ctx.direction !== \"backward\")) {\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 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()).filter((value) => disc.value.get(value) !== null),\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});\nexport function 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 if (Object.prototype.hasOwnProperty.call(newObj, \"__proto__\"))\n delete newObj.__proto__;\n for (const key of sharedKeys) {\n if (key === \"__proto__\")\n continue;\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) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key.\n const unrecKeys = new Map();\n let unrecIssue;\n const keyIssues = new Map();\n const collect = (iss, side) => {\n let keys;\n if (iss.code === \"unrecognized_keys\" && !iss.path?.length) {\n unrecIssue ?? (unrecIssue = iss);\n keys = iss.keys;\n }\n else if (iss.code === \"invalid_key\" && iss.origin === \"record\" && iss.path?.length === 1) {\n const k = String(iss.path[0]);\n if (!keyIssues.has(k))\n keyIssues.set(k, iss);\n keys = [k];\n }\n else {\n return false;\n }\n for (const k of keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k)[side] = true;\n }\n return true;\n };\n for (const iss of left.issues) {\n if (!collect(iss, \"l\"))\n result.issues.push(iss);\n }\n for (const iss of right.issues) {\n if (!collect(iss, \"r\"))\n result.issues.push(iss);\n }\n // Report only keys rejected by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length) {\n const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];\n if (aggregated.length)\n result.issues.push({ ...unrecIssue, keys: aggregated });\n for (const k of bothKeys) {\n if (!aggregated.includes(k) && keyIssues.has(k))\n result.issues.push(keyIssues.get(k));\n }\n }\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n if (util.aborted(result))\n return result;\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 const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\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 = memo ? memo.alloc(inst, payload, [], ctx) : [];\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 array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n // only tracked when there is a rest loop to skip\n const abortEarly = def.rest ? ctx?.abortEarly : undefined;\n let itemAborted = false;\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 if (abortEarly && !itemAborted && r.issues.length)\n itemAborted = util.aborted(r);\n }\n }\n // sound because rest is non-empty exactly when every fixed index is present, the one case handleTupleResults cannot discard an item's issues\n if (def.rest && !itemAborted) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n let seen = payload.issues.length;\n for (const el of rest) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\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 // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued.\n const omittable = key === \"optin\" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === \"optional\";\n if (!omittable)\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 rule, but only after `optoutStart`: the first index where the output 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 // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`.\n if (!isPresent && i >= optoutStart && items[i]._zod.optin === \"optional\") {\n final.value.length = i;\n break;\n }\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 const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\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 // no guard in either loop below: a record's invalid_key aborts but an enclosing intersection can reconcile it, so a stopped loop hides keys the sibling does not own and the intersection then rejects nothing\n const proms = [];\n const values = def.keyType._zod.values;\n if (values && !def.partial) {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\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 // A declared __proto__ is stripped but is not an unrecognized key.\n if (key === \"__proto__\")\n continue;\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 if (outKey === \"__proto__\")\n continue;\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 if (def.mode === \"loose\") {\n // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n payload.value[key] = input[key];\n }\n else {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n else {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection.\n let unrecognized;\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). 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 if (values) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(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 // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\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 if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\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 const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\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 = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const [key, value] of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\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 capSize(inst, mapSize);\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 const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\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 = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const item of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\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 capSize(inst, setSize);\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 util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const patternValues = util.getEnumValues(zod.def.entries).filter((k) => util.propertyKeyTypes.has(typeof k));\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(patternValues.length ? `^(${patternValues.map((o) => util.escapeRegex(o.toString())).join(\"|\")})$` : \"^[^\\\\s\\\\S]$\");\n });\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 const values = new Set(def.values);\n inst._zod.values = values;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const vals = zod.def.values;\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(vals.length\n ? `^(${vals\n .map((o) => typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o))\n .join(\"|\")})$`\n : \"^[^\\\\s\\\\S]$\");\n });\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 core.globalConfig.memoizer?.guard(inst);\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 return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(payload, result) {\n // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it.\n payload.value = result.issues.length ? undefined : result.value;\n return payload;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung.\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n inst._zod.optout = \"optional\";\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const values = zod.def.innerType._zod.values;\n return values ? new Set([...values, undefined]) : undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (payload.value === undefined) {\n // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means.\n if (def.innerType._zod.optin !== \"defaulted\")\n return payload;\n // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it.\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise)\n return result.then((result) => handleOptionalResult(payload, result));\n return handleOptionalResult(payload, result);\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.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.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.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazyInternal(inst, \"values\", (zod) => {\n return zod.def.innerType._zod.values ? new Set([...zod.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 = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.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 = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.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.defineLazyInternal(inst, \"values\", (zod) => {\n const v = zod.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});\nfunction handleCatchResult(payload, result, def, ctx) {\n if (!result.issues.length) {\n payload.value = result.value;\n // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property.\n if (result.memo)\n payload.memo = true;\n return payload;\n }\n // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call.\n payload.value = def.catchValue({\n ...result,\n value: payload.value,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n return payload;\n}\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.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({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleCatchResult(payload, result, def, ctx));\n }\n return handleCatchResult(payload, result, def, ctx);\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.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.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 // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it.\n if (left.issues.some((iss) => iss.code !== \"unrecognized_keys\")) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.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.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.innerType._zod.propValues);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType?._zod?.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.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 // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign.\n if (!payload.memo)\n payload.value = Object.freeze(payload.value);\n return payload;\n}\n// a leaf's pattern source with its own checks folded in: the last pattern-carrying check wins, else length bounds narrow the catch-all, else an integer format narrows the number form. the fold lives here instead of on `_zod.pattern` so a bundle without template literals never pays for it\nfunction leafPattern(schema) {\n const def = schema._zod.def;\n let pattern = def.pattern;\n let isInt = !!def.format?.includes(\"int\");\n let minimum;\n let maximum;\n for (const ch of def.checks ?? []) {\n const d = ch._zod.def;\n if (d.pattern)\n pattern = d.pattern;\n isInt || (isInt = !!d.format?.includes(\"int\"));\n const lo = d.minimum ?? d.length;\n const hi = d.maximum ?? d.length;\n if (lo !== undefined && (minimum === undefined || lo > minimum))\n minimum = lo;\n if (hi !== undefined && (maximum === undefined || hi < maximum))\n maximum = hi;\n }\n if (pattern)\n return pattern.source;\n // an empty range matches nothing at runtime, and `{8,5}` is not a legal quantifier\n if (minimum !== undefined && maximum !== undefined && minimum > maximum)\n return \"(?!)\";\n if (minimum !== undefined || maximum !== undefined)\n return regexes.string({ minimum, maximum }).source;\n const own = schema._zod.pattern;\n return (isInt && own === regexes.number ? regexes.integer : own)?.source;\n}\n// a part's pattern source. a wrapper's pattern embeds its inner pattern's source verbatim, so the folded form is substituted in place without knowing the wrapper's own composition; a union's options are joined the way the union builds its own pattern\nfunction partPattern(schema) {\n const def = schema._zod.def;\n const own = schema._zod.pattern?.source;\n // lazy resolves its inner on the internals, not the def\n const inner = def.innerType ?? schema._zod.innerType;\n if (inner) {\n const before = inner._zod.pattern?.source;\n const after = partPattern(inner);\n if (own && before && after && after !== before) {\n return own.replace(util.cleanRegex(before), () => util.cleanRegex(after));\n }\n return own;\n }\n if (def.options) {\n const sources = def.options.map(partPattern);\n if (sources.every(Boolean))\n return `^(${sources.map((s) => util.cleanRegex(s)).join(\"|\")})$`;\n }\n return leafPattern(schema);\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 const source = partPattern(part);\n if (!source) {\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n regexParts.push(util.cleanRegex(source));\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 // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter.\n Object.defineProperty(inst, \"_def\", { value: 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 // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function.\n return Object.defineProperty(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 }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return Object.defineProperty(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 }, \"_zod\", { value: inst._zod, enumerable: false });\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 lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, 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.defineLazyInternal(inst, \"pattern\", (zod) => zod.innerType?._zod?.pattern);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.innerType?._zod?.propValues);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.innerType?._zod?.optin ?? undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => 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","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\nfunction snapshotChecks(def) {\n if (def.checks)\n def.checks = [...def.checks];\n return def;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", coerce: true, ...util.normalizeParams(params) }));\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 _creditCard(Class, params) {\n return new Class({\n type: \"string\",\n format: \"credit_card\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _iban(Class, params) {\n return new Class({\n type: \"string\",\n format: \"iban\",\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(snapshotChecks({ type: \"number\", checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", coerce: true, checks: [], ...util.normalizeParams(params) }));\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 _properties(shape, params) {\n return new checks.$ZodCheckProperties({\n check: \"properties\",\n shape,\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: 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 : util.constantCatch(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 if (!(\"input\" in _issue))\n _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 codec._zod.bag.truthy = truthyArray;\n codec._zod.bag.falsy = falsyArray;\n codec._zod.bag.case = params.case ?? \"insensitive\";\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 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 * as core from \"../core/index.js\";\nimport * as regexes from \"../core/regexes.js\";\nimport * as util from \"../core/util.js\";\nimport * as parse from \"./parse.js\";\nexport const ZodMiniType = /*@__PURE__*/ core.$constructor(\"ZodMiniType\", (inst, def) => {\n if (!inst._zod)\n throw new Error(\"Uninitialized schema in ZodMiniType.\");\n core.$ZodType.init(inst, def);\n inst.def = def;\n inst.type = def.type;\n}, {\n // `with` is an alias for `check`: the same function object, not a wrapper.\n get with() {\n return this.check;\n },\n set with(value) {\n util.own(this, \"with\", value);\n },\n parse(data, params) {\n return parse.parse(this, data, params, { callee: this.parse });\n },\n parseAsync(data, params) {\n return parse.parseAsync(this, data, params, { callee: this.parseAsync });\n },\n safeParse(data, params) {\n return parse.safeParse(this, data, params);\n },\n safeParseAsync(data, params) {\n return parse.safeParseAsync(this, data, params);\n },\n check(...checks) {\n const def = this.def;\n return this.clone({\n ...def,\n checks: [\n ...(def.checks ?? []),\n ...checks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }, { parent: true });\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 apply(fn, ...args) {\n return args.length === 0 ? fn(this) : fn(this, ...args);\n },\n});\nexport const ZodMiniString = /*@__PURE__*/ core.$constructor(\"ZodMiniString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function string(params) {\n return core._string(ZodMiniString, params);\n}\nexport const ZodMiniStringFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n ZodMiniString.init(inst, def);\n});\nexport const ZodMiniEmail = /*@__PURE__*/ core.$constructor(\"ZodMiniEmail\", (inst, def) => {\n core.$ZodEmail.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function email(params) {\n return core._email(ZodMiniEmail, params);\n}\nexport const ZodMiniGUID = /*@__PURE__*/ core.$constructor(\"ZodMiniGUID\", (inst, def) => {\n core.$ZodGUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function guid(params) {\n return core._guid(ZodMiniGUID, params);\n}\nexport const ZodMiniUUID = /*@__PURE__*/ core.$constructor(\"ZodMiniUUID\", (inst, def) => {\n core.$ZodUUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function uuid(params) {\n return core._uuid(ZodMiniUUID, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function uuidv4(params) {\n return core._uuidv4(ZodMiniUUID, params);\n}\n// ZodMiniUUIDv6\n// @__NO_SIDE_EFFECTS__\nexport function uuidv6(params) {\n return core._uuidv6(ZodMiniUUID, params);\n}\n// ZodMiniUUIDv7\n// @__NO_SIDE_EFFECTS__\nexport function uuidv7(params) {\n return core._uuidv7(ZodMiniUUID, params);\n}\nexport const ZodMiniURL = /*@__PURE__*/ core.$constructor(\"ZodMiniURL\", (inst, def) => {\n core.$ZodURL.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function url(params) {\n return core._url(ZodMiniURL, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function httpUrl(params) {\n return core._url(ZodMiniURL, {\n protocol: regexes.httpProtocol,\n hostname: regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniEmoji = /*@__PURE__*/ core.$constructor(\"ZodMiniEmoji\", (inst, def) => {\n core.$ZodEmoji.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function emoji(params) {\n return core._emoji(ZodMiniEmoji, params);\n}\nexport const ZodMiniNanoID = /*@__PURE__*/ core.$constructor(\"ZodMiniNanoID\", (inst, def) => {\n core.$ZodNanoID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nanoid(params) {\n return core._nanoid(ZodMiniNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodMiniCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodMiniCUID = /*@__PURE__*/ core.$constructor(\"ZodMiniCUID\", (inst, def) => {\n core.$ZodCUID.init(inst, def);\n ZodMiniStringFormat.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 */\n// @__NO_SIDE_EFFECTS__\nexport function cuid(params) {\n return core._cuid(ZodMiniCUID, params);\n}\nexport const ZodMiniCUID2 = /*@__PURE__*/ core.$constructor(\"ZodMiniCUID2\", (inst, def) => {\n core.$ZodCUID2.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cuid2(params) {\n return core._cuid2(ZodMiniCUID2, params);\n}\nexport const ZodMiniULID = /*@__PURE__*/ core.$constructor(\"ZodMiniULID\", (inst, def) => {\n core.$ZodULID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ulid(params) {\n return core._ulid(ZodMiniULID, params);\n}\nexport const ZodMiniXID = /*@__PURE__*/ core.$constructor(\"ZodMiniXID\", (inst, def) => {\n core.$ZodXID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function xid(params) {\n return core._xid(ZodMiniXID, params);\n}\nexport const ZodMiniKSUID = /*@__PURE__*/ core.$constructor(\"ZodMiniKSUID\", (inst, def) => {\n core.$ZodKSUID.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ksuid(params) {\n return core._ksuid(ZodMiniKSUID, params);\n}\nexport const ZodMiniIPv4 = /*@__PURE__*/ core.$constructor(\"ZodMiniIPv4\", (inst, def) => {\n core.$ZodIPv4.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ipv4(params) {\n return core._ipv4(ZodMiniIPv4, params);\n}\nexport const ZodMiniIPv6 = /*@__PURE__*/ core.$constructor(\"ZodMiniIPv6\", (inst, def) => {\n core.$ZodIPv6.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function ipv6(params) {\n return core._ipv6(ZodMiniIPv6, params);\n}\nexport const ZodMiniCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodMiniCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cidrv4(params) {\n return core._cidrv4(ZodMiniCIDRv4, params);\n}\nexport const ZodMiniCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodMiniCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function cidrv6(params) {\n return core._cidrv6(ZodMiniCIDRv6, params);\n}\nexport const ZodMiniMAC = /*@__PURE__*/ core.$constructor(\"ZodMiniMAC\", (inst, def) => {\n core.$ZodMAC.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function mac(params) {\n return core._mac(ZodMiniMAC, params);\n}\nexport const ZodMiniBase64 = /*@__PURE__*/ core.$constructor(\"ZodMiniBase64\", (inst, def) => {\n core.$ZodBase64.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function base64(params) {\n return core._base64(ZodMiniBase64, params);\n}\nexport const ZodMiniBase64URL = /*@__PURE__*/ core.$constructor(\"ZodMiniBase64URL\", (inst, def) => {\n core.$ZodBase64URL.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function base64url(params) {\n return core._base64url(ZodMiniBase64URL, params);\n}\nexport const ZodMiniE164 = /*@__PURE__*/ core.$constructor(\"ZodMiniE164\", (inst, def) => {\n core.$ZodE164.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function e164(params) {\n return core._e164(ZodMiniE164, params);\n}\nexport const ZodMiniCreditCard = /*@__PURE__*/ core.$constructor(\"ZodMiniCreditCard\", (inst, def) => {\n core.$ZodCreditCard.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function creditCard(params) {\n return core._creditCard(ZodMiniCreditCard, params);\n}\nexport const ZodMiniIBAN = /*@__PURE__*/ core.$constructor(\"ZodMiniIBAN\", (inst, def) => {\n core.$ZodIBAN.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function iban(params) {\n return core._iban(ZodMiniIBAN, params);\n}\nexport const ZodMiniJWT = /*@__PURE__*/ core.$constructor(\"ZodMiniJWT\", (inst, def) => {\n core.$ZodJWT.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function jwt(params) {\n return core._jwt(ZodMiniJWT, params);\n}\nexport const ZodMiniCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniCustomStringFormat\", (inst, def) => {\n core.$ZodCustomStringFormat.init(inst, def);\n ZodMiniStringFormat.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodMiniCustomStringFormat, format, fnOrRegex, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hostname(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"hostname\", regexes.hostname, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hex(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"hex\", regexes.hex, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function currencyCode(_params) {\n return core._stringFormat(ZodMiniCustomStringFormat, \"currency_code\", regexes.currencyCode, _params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n // check for unrecognized format\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodMiniCustomStringFormat, format, regex, params);\n}\nexport const ZodMiniNumber = /*@__PURE__*/ core.$constructor(\"ZodMiniNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function number(params) {\n return core._number(ZodMiniNumber, params);\n}\nexport const ZodMiniNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodMiniNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodMiniNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodMiniNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodMiniNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodMiniNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodMiniNumberFormat, params);\n}\nexport const ZodMiniBoolean = /*@__PURE__*/ core.$constructor(\"ZodMiniBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function boolean(params) {\n return core._boolean(ZodMiniBoolean, params);\n}\nexport const ZodMiniBigInt = /*@__PURE__*/ core.$constructor(\"ZodMiniBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function bigint(params) {\n return core._bigint(ZodMiniBigInt, params);\n}\nexport const ZodMiniBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodMiniBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodMiniBigInt.init(inst, def);\n});\nexport function int64(params) {\n return core._int64(ZodMiniBigIntFormat, params);\n}\nexport function uint64(params) {\n return core._uint64(ZodMiniBigIntFormat, params);\n}\nexport const ZodMiniSymbol = /*@__PURE__*/ core.$constructor(\"ZodMiniSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function symbol(params) {\n return core._symbol(ZodMiniSymbol, params);\n}\nexport const ZodMiniUndefined = /*@__PURE__*/ core.$constructor(\"ZodMiniUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _undefined(params) {\n return core._undefined(ZodMiniUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodMiniNull = /*@__PURE__*/ core.$constructor(\"ZodMiniNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _null(params) {\n return core._null(ZodMiniNull, params);\n}\nexport { _null as null };\nexport const ZodMiniAny = /*@__PURE__*/ core.$constructor(\"ZodMiniAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function any() {\n return core._any(ZodMiniAny);\n}\nexport const ZodMiniUnknown = /*@__PURE__*/ core.$constructor(\"ZodMiniUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function unknown() {\n return core._unknown(ZodMiniUnknown);\n}\nexport const ZodMiniNever = /*@__PURE__*/ core.$constructor(\"ZodMiniNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function never(params) {\n return core._never(ZodMiniNever, params);\n}\nexport const ZodMiniVoid = /*@__PURE__*/ core.$constructor(\"ZodMiniVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _void(params) {\n return core._void(ZodMiniVoid, params);\n}\nexport { _void as void };\nexport const ZodMiniDate = /*@__PURE__*/ core.$constructor(\"ZodMiniDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function date(params) {\n return core._date(ZodMiniDate, params);\n}\nexport const ZodMiniArray = /*@__PURE__*/ core.$constructor(\"ZodMiniArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function array(element, params) {\n return new ZodMiniArray({\n type: \"array\",\n element: element,\n ...util.normalizeParams(params),\n });\n}\n// .keyof\n// @__NO_SIDE_EFFECTS__\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodMiniObject = /*@__PURE__*/ core.$constructor(\"ZodMiniObject\", (inst, def) => {\n core.$ZodObject.init(inst, def);\n ZodMiniType.init(inst, def);\n util.installLazyProp(inst, \"shape\", (self) => self._zod.def.shape, false);\n});\n// @__NO_SIDE_EFFECTS__\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodMiniObject(def);\n}\n// strictObject\n// @__NO_SIDE_EFFECTS__\nexport function strictObject(shape, params) {\n return new ZodMiniObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\n// @__NO_SIDE_EFFECTS__\nexport function looseObject(shape, params) {\n return new ZodMiniObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\n// object methods\n// @__NO_SIDE_EFFECTS__\nexport function extend(schema, shape) {\n return util.extend(schema, shape);\n}\n// @__NO_SIDE_EFFECTS__\nexport function safeExtend(schema, shape) {\n return util.safeExtend(schema, shape);\n}\n/**\n * @deprecated Use [`z.extend(A, B.shape)`](https://zod.dev/api?id=extend) instead.\n */\n// @__NO_SIDE_EFFECTS__\nexport function merge(a, b) {\n return util.merge(a, b);\n}\n// @__NO_SIDE_EFFECTS__\nexport function pick(schema, mask) {\n return util.pick(schema, mask);\n}\n// .omit\n// @__NO_SIDE_EFFECTS__\nexport function omit(schema, mask) {\n return util.omit(schema, mask);\n}\n// @__NO_SIDE_EFFECTS__\nexport function partial(schema, mask) {\n const def = schema._zod.def;\n if (def.type !== \"tuple\")\n return util.partial(ZodMiniOptional, schema, mask);\n // a refinement was authored against the full arity; partialing would run it on a shorter array\n if (def.checks?.length)\n throw new Error(\".partial() cannot be used on tuple schemas containing refinements\");\n return util.clone(schema, {\n ...def,\n items: def.items.map((item) => new ZodMiniOptional({ type: \"optional\", innerType: item })),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function exactPartial(schema, mask) {\n return util.partial(ZodMiniExactOptional, schema, mask, \"exactPartial\");\n}\n// @__NO_SIDE_EFFECTS__\nexport function required(schema, mask) {\n return util.required(ZodMiniNonOptional, schema, mask);\n}\n// @__NO_SIDE_EFFECTS__\nexport function catchall(inst, catchall) {\n // `mergeDefs` rather than a spread: spreading reads `shape`, and resolving it can mint a whole fresh subtree\n return inst.clone(util.mergeDefs(inst._zod.def, { catchall: catchall }));\n}\nexport const ZodMiniUnion = /*@__PURE__*/ core.$constructor(\"ZodMiniUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function union(options, params) {\n return new ZodMiniUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniXor = /*@__PURE__*/ core.$constructor(\"ZodMiniXor\", (inst, def) => {\n ZodMiniUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\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 ZodMiniXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodMiniDiscriminatedUnion\", (inst, def) => {\n core.$ZodDiscriminatedUnion.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function discriminatedUnion(discriminator, options, params) {\n return new ZodMiniDiscriminatedUnion({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniIntersection = /*@__PURE__*/ core.$constructor(\"ZodMiniIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function intersection(left, right) {\n return new ZodMiniIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodMiniTuple = /*@__PURE__*/ core.$constructor(\"ZodMiniTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\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 ZodMiniTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniRecord = /*@__PURE__*/ core.$constructor(\"ZodMiniRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\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 ZodMiniRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function partialRecord(keyType, valueType, params) {\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n partial: true,\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodMiniRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniMap = /*@__PURE__*/ core.$constructor(\"ZodMiniMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function map(keyType, valueType, params) {\n return new ZodMiniMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniSet = /*@__PURE__*/ core.$constructor(\"ZodMiniSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function set(valueType, params) {\n return new ZodMiniSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniEnum = /*@__PURE__*/ core.$constructor(\"ZodMiniEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodMiniType.init(inst, def);\n // reuse the parsed value set so a numeric TS enum's reverse-mapping keys stay out\n inst.options = [...inst._zod.values];\n});\n// @__NO_SIDE_EFFECTS__\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodMiniEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\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(entries, params) {\n return new ZodMiniEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniLiteral = /*@__PURE__*/ core.$constructor(\"ZodMiniLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function literal(value, params) {\n return new ZodMiniLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniFile = /*@__PURE__*/ core.$constructor(\"ZodMiniFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function file(params) {\n return core._file(ZodMiniFile, params);\n}\nexport const ZodMiniTransform = /*@__PURE__*/ core.$constructor(\"ZodMiniTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function transform(fn) {\n return new ZodMiniTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodMiniOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function optional(innerType) {\n return new ZodMiniOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodMiniExactOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function exactOptional(innerType) {\n return new ZodMiniExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodMiniNullable = /*@__PURE__*/ core.$constructor(\"ZodMiniNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nullable(innerType) {\n return new ZodMiniNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\n// @__NO_SIDE_EFFECTS__\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodMiniDefault = /*@__PURE__*/ core.$constructor(\"ZodMiniDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function _default(innerType, defaultValue) {\n return new ZodMiniDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodMiniPrefault = /*@__PURE__*/ core.$constructor(\"ZodMiniPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function prefault(innerType, defaultValue) {\n return new ZodMiniPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodMiniNonOptional = /*@__PURE__*/ core.$constructor(\"ZodMiniNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nonoptional(innerType, params) {\n return new ZodMiniNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniSuccess = /*@__PURE__*/ core.$constructor(\"ZodMiniSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function success(innerType) {\n return new ZodMiniSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodMiniCatch = /*@__PURE__*/ core.$constructor(\"ZodMiniCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nfunction _catch(innerType, catchValue) {\n return new ZodMiniCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : core.util.constantCatch(catchValue)),\n });\n}\nexport { _catch as catch };\nexport const ZodMiniNaN = /*@__PURE__*/ core.$constructor(\"ZodMiniNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function nan(params) {\n return core._nan(ZodMiniNaN, params);\n}\nexport const ZodMiniPipe = /*@__PURE__*/ core.$constructor(\"ZodMiniPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function pipe(in_, out) {\n return new ZodMiniPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n });\n}\nexport const ZodMiniCodec = /*@__PURE__*/ core.$constructor(\"ZodMiniCodec\", (inst, def) => {\n ZodMiniPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function codec(in_, out, params) {\n return new ZodMiniCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodMiniCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodMiniReadonly = /*@__PURE__*/ core.$constructor(\"ZodMiniReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function readonly(innerType) {\n return new ZodMiniReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodMiniTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodMiniTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function templateLiteral(parts, params) {\n return new ZodMiniTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMiniLazy = /*@__PURE__*/ core.$constructor(\"ZodMiniLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// export function lazy<T extends object>(getter: () => T): T {\n// return util.createTransparentProxy<T>(getter);\n// }\n// @__NO_SIDE_EFFECTS__\nfunction _lazy(getter) {\n return new ZodMiniLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport { _lazy as lazy };\nexport const ZodMiniPromise = /*@__PURE__*/ core.$constructor(\"ZodMiniPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function promise(innerType) {\n return new ZodMiniPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodMiniCustom = /*@__PURE__*/ core.$constructor(\"ZodMiniCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// custom checks\n// @__NO_SIDE_EFFECTS__\nexport function check(fn, params) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// ZodCustom custom schema\n// @__NO_SIDE_EFFECTS__\nexport function custom(fn, _params) {\n return core._custom(ZodMiniCustom, fn ?? (() => true), _params);\n}\n// refine\n// @__NO_SIDE_EFFECTS__\nexport function refine(fn, _params = {}) {\n return core._refine(ZodMiniCustom, fn, _params);\n}\n// superRefine\n// @__NO_SIDE_EFFECTS__\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;\n// instanceof\nclass Class {\n constructor(..._args) { }\n}\n// @__NO_SIDE_EFFECTS__\nfunction _instanceof(cls, params = {}) {\n const inst = custom((data) => data instanceof cls, params);\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: ZodMiniCodec,\n Boolean: ZodMiniBoolean,\n String: ZodMiniString,\n}, ...args);\n// @__NO_SIDE_EFFECTS__\nexport function json() {\n const jsonSchema = _lazy(() => {\n return union([string(), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\nexport const ZodMiniFunction = /*@__PURE__*/ core.$constructor(\"ZodMiniFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodMiniType.init(inst, def);\n});\n// @__NO_SIDE_EFFECTS__\nexport function _function(params) {\n return new ZodMiniFunction({\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 };\n","// `zod/mini` (tree-shakable functional API) instead of the full `zod` entry:\n// the widget only needs object/string/literal/union/nullable, and the mini\n// build keeps roughly 40KB of parser/refinement code out of the bundle.\nimport * as z from \"zod/mini\";\nimport { config as zodConfig } from \"zod/v4/core\";\n\n// Disable Zod's JIT-compiled fast path: it probes `Function(\"\")` at runtime,\n// which host pages with a strict Content-Security-Policy (no 'unsafe-eval')\n// block and report as a CSP violation on every widget load. Validation\n// behaves identically in jitless mode, just without eval-based codegen.\nzodConfig({ jitless: true });\n\nconst utteranceSchema = z.object({\n type: z.literal(\"utterance\"),\n content: z.string(),\n role: z.string(),\n});\n\nconst agentCognitionSchema = z.object({\n type: z.literal(\"agent_cognition\"),\n content: z.string(),\n});\n\nconst chatClosedExpiredSchema = z.object({\n type: z.literal(\"chat_closed_expired\"),\n content: z.string(),\n});\n\nconst agentCapturedUrlSchema = z.object({\n type: z.literal(\"agent_captured_url\"),\n content: z.string(),\n});\n\nconst agentTopicSchema = z.object({\n type: z.literal(\"agent_topic\"),\n content: z.string(),\n});\n\nconst agentSummarySchema = z.object({\n type: z.literal(\"agent_summary\"),\n content: z.string(),\n});\n\nconst chatRatingSchema = z.object({\n type: z.literal(\"chat_rating\"),\n content: z.string(),\n});\n\nconst breadcrumbSchema = z.object({\n type: z.literal(\"breadcrumb\"),\n content: z.string(),\n});\n\nconst chatEscalatedSchema = z.object({\n type: z.literal(\"chat_escalated\"),\n content: z.null(),\n});\n\nconst errorSchema = z.object({\n type: z.literal(\"error\"),\n code: z.string(),\n});\n\nconst utteranceApiResponseSchema = z.object({\n message_id: z.nullable(z.string()),\n created_at: z.string(),\n data: utteranceSchema,\n});\n\nconst errorApiResponseSchema = z.object({\n created_at: z.string(),\n data: errorSchema,\n});\n\nconst agentCognitionApiResponseSchema = z.object({\n created_at: z.string(),\n data: agentCognitionSchema,\n});\n\nconst chatClosedExpiredApiResponseSchema = z.object({\n message_id: z.nullable(z.string()),\n created_at: z.string(),\n data: chatClosedExpiredSchema,\n});\n\nconst agentCapturedUrlApiResponseSchema = z.object({\n created_at: z.string(),\n data: agentCapturedUrlSchema,\n});\n\nconst agentTopicApiResponseSchema = z.object({\n created_at: z.string(),\n data: agentTopicSchema,\n});\n\nconst agentSummaryApiResponseSchema = z.object({\n created_at: z.string(),\n data: agentSummarySchema,\n});\n\nconst chatRatingApiResponseSchema = z.object({\n created_at: z.string(),\n data: chatRatingSchema,\n});\n\nconst breadcrumbApiResponseSchema = z.object({\n created_at: z.string(),\n data: breadcrumbSchema,\n});\n\nconst chatEscalatedApiResponseSchema = z.object({\n message_id: z.nullable(z.string()),\n created_at: z.string(),\n data: chatEscalatedSchema,\n});\n\nexport const chatResponseApiSchema = z.union([\n utteranceApiResponseSchema,\n errorApiResponseSchema,\n agentCognitionApiResponseSchema,\n agentCapturedUrlApiResponseSchema,\n agentTopicApiResponseSchema,\n agentSummaryApiResponseSchema,\n chatClosedExpiredApiResponseSchema,\n chatRatingApiResponseSchema,\n breadcrumbApiResponseSchema,\n chatEscalatedApiResponseSchema,\n]);\n\nexport type ChatResponseApi = z.infer<typeof chatResponseApiSchema>;\n\ntype NotificationData = ChatResponseApi[\"data\"];\n\nexport type UtteranceNotification = {\n message_id: string | null;\n created_at: string;\n data: Extract<NotificationData, { type: \"utterance\" }>;\n};\n\nexport type ErrorNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"error\" }>;\n};\n\nexport type AgentCognitionNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"agent_cognition\" }>;\n};\n\nexport type AgentCapturedUrlNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"agent_captured_url\" }>;\n};\n\nexport type AgentTopicNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"agent_topic\" }>;\n};\n\nexport type AgentSummaryNotification = {\n created_at: string;\n data: Extract<NotificationData, { type: \"agent_summary\" }>;\n};\n\nexport const chatResponseSchema = z.object({\n message_id: z.string(), // message_id from api schema\n response: z.object({\n id: z.string(), // message_id from api schema\n type: z.string(),\n content: z.string(),\n }),\n});\n\nexport type ChatResponse = z.infer<typeof chatResponseSchema>;\n","import { useCallback, useEffect, useRef } from \"react\";\n\nimport { useErrorContext } from \"@/contexts/error-handling/error-context\";\nimport { getErrorMessage } from \"@/contexts/error-handling/error-messages\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\nimport {\n connectAppSyncEvents,\n type AppSyncEventsConnection,\n} from \"@/lib/appsync-events-client\";\nimport { BootResponse, MessageResponse } from \"@/lib/eloquent-ai-api-client\";\nimport { Message } from \"@/types/message\";\n\nimport {\n AgentCapturedUrlNotification,\n AgentCognitionNotification,\n AgentSummaryNotification,\n AgentTopicNotification,\n ChatResponse,\n chatResponseApiSchema,\n ErrorNotification,\n UtteranceNotification,\n} from \"../validations\";\n\nconst INITIAL_RECONNECT_DELAY_MS = 500;\nconst MAX_RECONNECT_DELAY_MS = 30000;\nconst DEFAULT_BACKUP_POLL_INTERVAL_MS = 60000;\n\nexport type UseRealtimeSocketOptions = {\n chatSettings: BootResponse[\"chat_settings\"] | null;\n chatId: string | null;\n messages: Message[];\n onMessage: (response: ChatResponse, chatId: string) => void;\n onCognition: (content: string) => void;\n onCognitionComplete: () => void;\n onError?: () => void;\n onChatClosed?: () => void;\n onAgentCapturedUrl?: (content: string) => void;\n onAgentTopic?: (content: string) => void;\n onAgentSummary?: (content: string) => void;\n onRatingRequest?: () => void;\n onBreadcrumb?: () => void;\n fetchHistory: (chatId: string) => Promise<MessageResponse[]>;\n getChatToken: () => string | null;\n backupPollingInterval?: number;\n};\n\nexport type UseRealtimeSocketReturn = {\n connect: (chatId: string) => Promise<void>;\n disconnect: () => void;\n clearProcessedIds: () => void;\n};\n\nexport function useRealtimeSocket({\n chatSettings,\n chatId,\n messages,\n onMessage,\n onCognition,\n onCognitionComplete,\n onError,\n onChatClosed,\n onAgentCapturedUrl,\n onAgentTopic,\n onAgentSummary,\n onRatingRequest,\n onBreadcrumb,\n fetchHistory,\n getChatToken,\n backupPollingInterval = DEFAULT_BACKUP_POLL_INTERVAL_MS,\n}: UseRealtimeSocketOptions): UseRealtimeSocketReturn {\n const processedIdsRef = useRef<Set<string>>(new Set());\n\n useEffect(() => {\n for (const msg of messages) {\n if (msg.id) processedIdsRef.current.add(msg.id);\n }\n }, [messages]);\n\n const eventChannelRef = useRef<AppSyncEventsConnection | null>(null);\n const activeChatIdRef = useRef<string | null>(null);\n const reconnectAttemptsRef = useRef(0);\n const reconnectTimerRef = useRef<NodeJS.Timeout | null>(null);\n const backupPollIntervalRef = useRef<NodeJS.Timeout | null>(null);\n const shouldReconnectRef = useRef(false);\n const isReconnectingRef = useRef(false);\n\n // Keep all mutable callbacks as latest-refs to avoid stale closures in\n // timers/intervals and the long-lived socket subscription.\n const onMessageRef = useLatestRef(onMessage);\n const onCognitionRef = useLatestRef(onCognition);\n const onCognitionCompleteRef = useLatestRef(onCognitionComplete);\n const onErrorRef = useLatestRef(onError);\n const onChatClosedRef = useLatestRef(onChatClosed);\n const onAgentCapturedUrlRef = useLatestRef(onAgentCapturedUrl);\n const onAgentTopicRef = useLatestRef(onAgentTopic);\n const onAgentSummaryRef = useLatestRef(onAgentSummary);\n const onRatingRequestRef = useLatestRef(onRatingRequest);\n const onBreadcrumbRef = useLatestRef(onBreadcrumb);\n const fetchHistoryRef = useLatestRef(fetchHistory);\n const getChatTokenRef = useLatestRef(getChatToken);\n\n const { publishError } = useErrorContext();\n\n const appSyncUrl = chatSettings?.app_sync_url;\n const appSyncApiKey = chatSettings?.app_sync_api_key;\n // The client is configuration-free (no Amplify.configure singleton) —\n // connections are ready as soon as boot settings provide the endpoint.\n const isSocketConfigReady = Boolean(appSyncUrl && appSyncApiKey);\n const appSyncUrlRef = useLatestRef(appSyncUrl);\n const appSyncApiKeyRef = useLatestRef(appSyncApiKey);\n\n const closeChannel = useCallback(() => {\n if (eventChannelRef.current) {\n eventChannelRef.current.close();\n eventChannelRef.current = null;\n }\n }, []);\n\n const stopBackupPoll = useCallback(() => {\n if (backupPollIntervalRef.current) {\n clearInterval(backupPollIntervalRef.current);\n backupPollIntervalRef.current = null;\n }\n }, []);\n\n const clearReconnectTimer = useCallback(() => {\n if (reconnectTimerRef.current) {\n clearTimeout(reconnectTimerRef.current);\n reconnectTimerRef.current = null;\n }\n }, []);\n\n // Forward-declared: connectChannel's onDisconnect needs scheduleReconnect,\n // which itself needs connectChannel — the ref breaks the cycle. Synced to\n // the latest scheduleReconnect below.\n const scheduleReconnectRef = useRef<() => void>(() => {});\n\n // Opens an AppSync Events channel and subscribes to real-time events\n const connectChannel = useCallback(\n async (chatIdToConnect: string): Promise<void> => {\n closeChannel();\n const httpEndpoint = appSyncUrlRef.current;\n const apiKey = appSyncApiKeyRef.current;\n if (!httpEndpoint || !apiKey) {\n throw new Error(\"Cannot connect: AppSync settings not available\");\n }\n const chatToken = getChatTokenRef.current();\n\n const connection = await connectAppSyncEvents({\n httpEndpoint,\n auth: chatToken ? { authorizationToken: chatToken } : { apiKey },\n channel: `/default/chat/${chatIdToConnect}`,\n onDisconnect: () => {\n eventChannelRef.current = null;\n scheduleReconnectRef.current();\n },\n onEvent: (event) => {\n const parseResult = chatResponseApiSchema.safeParse(event);\n if (!parseResult.success) {\n console.error(\"Invalid conversation response:\", parseResult.error);\n return;\n }\n\n const notification = parseResult.data;\n switch (notification.data.type) {\n case \"utterance\": {\n const utterance = notification as UtteranceNotification;\n const messageId = utterance.message_id ?? crypto.randomUUID();\n if (processedIdsRef.current.has(messageId)) {\n return;\n }\n processedIdsRef.current.add(messageId);\n onCognitionCompleteRef.current();\n onMessageRef.current(\n {\n message_id: messageId,\n response: {\n id: messageId,\n type: utterance.data.type,\n content: utterance.data.content,\n },\n },\n chatIdToConnect,\n );\n return;\n }\n case \"error\": {\n const errorNotif = notification as ErrorNotification;\n const code = parseInt(errorNotif.data.code);\n publishError({ code, message: getErrorMessage(code) });\n onErrorRef.current?.();\n return;\n }\n case \"agent_cognition\": {\n const cognition = notification as AgentCognitionNotification;\n onCognitionRef.current(cognition.data.content);\n return;\n }\n case \"agent_captured_url\": {\n const capturedUrl = notification as AgentCapturedUrlNotification;\n onAgentCapturedUrlRef.current?.(capturedUrl.data.content);\n return;\n }\n case \"agent_topic\": {\n const topic = notification as AgentTopicNotification;\n onAgentTopicRef.current?.(topic.data.content);\n return;\n }\n case \"agent_summary\": {\n const summary = notification as AgentSummaryNotification;\n onAgentSummaryRef.current?.(summary.data.content);\n return;\n }\n case \"chat_closed_expired\": {\n onChatClosedRef.current?.();\n onRatingRequestRef.current?.();\n return;\n }\n case \"chat_rating\": {\n onRatingRequestRef.current?.();\n return;\n }\n case \"breadcrumb\": {\n onBreadcrumbRef.current?.();\n return;\n }\n case \"chat_escalated\": {\n onChatClosedRef.current?.();\n onRatingRequestRef.current?.();\n return;\n }\n default:\n console.warn(\n \"Unknown notification type:\",\n (notification as { data: { type: string } }).data.type,\n );\n }\n },\n });\n\n eventChannelRef.current = connection;\n },\n // The *Ref entries are latest-refs (stable identities); listed to satisfy\n // exhaustive-deps, which can't see that useLatestRef returns a ref.\n [\n closeChannel,\n publishError,\n appSyncUrlRef,\n appSyncApiKeyRef,\n getChatTokenRef,\n onMessageRef,\n onCognitionRef,\n onCognitionCompleteRef,\n onErrorRef,\n onChatClosedRef,\n onAgentCapturedUrlRef,\n onAgentTopicRef,\n onAgentSummaryRef,\n onRatingRequestRef,\n onBreadcrumbRef,\n ],\n );\n\n // Fetches history and delivers any unseen assistant messages via onMessage\n const runBackupPoll = useCallback(\n async (chatIdToPoll: string) => {\n try {\n const history = await fetchHistoryRef.current(chatIdToPoll);\n for (const msg of history) {\n if (\n msg.role !== \"assistant\" ||\n !msg.message_id ||\n processedIdsRef.current.has(msg.message_id)\n ) {\n continue;\n }\n processedIdsRef.current.add(msg.message_id);\n onMessageRef.current(\n { message_id: msg.message_id, response: msg.response },\n chatIdToPoll,\n );\n }\n } catch (err) {\n console.warn(\"Backup poll failed:\", err);\n }\n },\n [fetchHistoryRef, onMessageRef],\n );\n\n const startBackupPoll = useCallback(\n (chatIdToPoll: string) => {\n stopBackupPoll();\n backupPollIntervalRef.current = setInterval(\n () => runBackupPoll(chatIdToPoll),\n backupPollingInterval,\n );\n },\n [stopBackupPoll, runBackupPoll, backupPollingInterval],\n );\n\n // Named function expression so the setTimeout callback can re-schedule\n // itself on failure without a circular ref dependency.\n const scheduleReconnect = useCallback(\n function scheduleReconnectSelf() {\n if (\n !shouldReconnectRef.current ||\n isReconnectingRef.current ||\n reconnectTimerRef.current\n ) {\n return;\n }\n const chatIdToReconnect = activeChatIdRef.current;\n if (!chatIdToReconnect) return;\n\n const delay = Math.min(\n INITIAL_RECONNECT_DELAY_MS * Math.pow(2, reconnectAttemptsRef.current),\n MAX_RECONNECT_DELAY_MS,\n );\n reconnectAttemptsRef.current += 1;\n\n reconnectTimerRef.current = setTimeout(async () => {\n reconnectTimerRef.current = null;\n isReconnectingRef.current = true;\n try {\n await connectChannel(chatIdToReconnect);\n reconnectAttemptsRef.current = 0;\n isReconnectingRef.current = false;\n await runBackupPoll(chatIdToReconnect);\n } catch {\n isReconnectingRef.current = false;\n scheduleReconnectSelf();\n }\n }, delay);\n },\n [connectChannel, runBackupPoll],\n );\n\n // Keep the forward-declared ref pointing at the latest scheduleReconnect\n // (same semantics as useLatestRef, but the ref had to exist earlier for\n // connectChannel's onDisconnect).\n useEffect(() => {\n scheduleReconnectRef.current = scheduleReconnect;\n });\n\n const connect = useCallback(\n async (chatIdToConnect: string): Promise<void> => {\n if (!isSocketConfigReady || !chatIdToConnect) {\n throw new Error(\n \"Cannot connect: AppSync settings not ready or missing chatId\",\n );\n }\n clearReconnectTimer();\n shouldReconnectRef.current = true;\n activeChatIdRef.current = chatIdToConnect;\n reconnectAttemptsRef.current = 0;\n // Start polling before the socket connect attempt, not after — if\n // connectChannel throws (e.g. the AppSync channel is unreachable),\n // polling must still run so messages keep arriving via history\n // instead of being lost entirely until a reconnect succeeds.\n startBackupPoll(chatIdToConnect);\n await connectChannel(chatIdToConnect);\n },\n [isSocketConfigReady, clearReconnectTimer, connectChannel, startBackupPoll],\n );\n\n const disconnect = useCallback((): void => {\n shouldReconnectRef.current = false;\n activeChatIdRef.current = null;\n reconnectAttemptsRef.current = 0;\n clearReconnectTimer();\n stopBackupPoll();\n closeChannel();\n }, [clearReconnectTimer, stopBackupPoll, closeChannel]);\n\n const clearProcessedIds = useCallback(() => {\n processedIdsRef.current.clear();\n }, []);\n\n // Eagerly connect when chatId becomes available (e.g., restored from localStorage on mount)\n useEffect(() => {\n if (!chatId || !isSocketConfigReady || activeChatIdRef.current === chatId)\n return;\n\n connect(chatId).catch((err) => {\n console.error(\"Failed to eagerly connect:\", err);\n activeChatIdRef.current = chatId;\n shouldReconnectRef.current = true;\n scheduleReconnectRef.current();\n });\n }, [chatId, isSocketConfigReady, connect]);\n\n // Disconnect detection lives inside connectAppSyncEvents (socket close and\n // keep-alive timeout both invoke connectChannel's onDisconnect), replacing\n // the amplify Hub connection-state listener.\n\n useEffect(() => {\n return () => {\n disconnect();\n };\n }, [disconnect]);\n\n return { connect, disconnect, clearProcessedIds };\n}\n","import type { ChatResponse } from \"@/components/chat/validations\";\nimport type { Message } from \"@/types/message\";\n\n/**\n * The single place where API/wire shapes become domain `Message`s.\n *\n * Everything here is a pure function: the hooks own state and timing, this\n * module owns shape. A backend field change should only ever touch this file\n * (and validations.ts), not the hooks.\n */\n\n/** A realtime/polled assistant reply, as appended to the transcript. */\nexport function messageFromChatResponse(response: ChatResponse): Message {\n return {\n id: response.message_id,\n content: response.response.content ?? \"\",\n sender: \"assistant\",\n timestamp: new Date().toISOString(),\n };\n}\n\n/** The configured welcome message, shown before any conversation exists. */\nexport function createWelcomeMessage(content: string): Message {\n return {\n id: crypto.randomUUID(),\n content,\n sender: \"assistant\",\n timestamp: new Date().toISOString(),\n isWelcomeMessage: true,\n };\n}\n\n/** The star-rating prompt appended when the server requests feedback. */\nexport function createRatingRequestMessage(): Message {\n return {\n id: crypto.randomUUID(),\n content: \"\",\n sender: \"assistant\",\n timestamp: new Date().toISOString(),\n isRatingRequest: true,\n };\n}\n\n/** The notice shown when the user writes into a closed conversation. */\nexport function createChatClosedNoticeMessage(): Message {\n return {\n id: crypto.randomUUID(),\n content: \"This conversation is closed, please start a new chat.\",\n sender: \"assistant\",\n timestamp: new Date().toISOString(),\n };\n}\n","\"use client\";\nimport {\n useCallback,\n useEffect,\n type Dispatch,\n type SetStateAction,\n} from \"react\";\n\nimport { Message, MessageData } from \"@/types/message\";\n\nimport {\n BootResponse,\n EloquentAiApiClient,\n} from \"@/lib/eloquent-ai-api-client\";\n\nimport { useErrorContext } from \"@/contexts/error-handling/error-context\";\nimport { useAgentCognitionContext } from \"@/contexts/agent-cognition/use-agent-cognition-context\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\nimport { NetworkError, ServerError } from \"@/lib/http\";\nimport { getCurrentUrlSearchParams } from \"@/lib/url-params\";\nimport { usePersistence } from \"./use-persistence\";\nimport { useRealtimeSocket } from \"./use-realtime-socket\";\nimport {\n createChatClosedNoticeMessage,\n createRatingRequestMessage,\n messageFromChatResponse,\n} from \"../message-mapping\";\nimport { ChatResponse } from \"../validations\";\n\nexport interface UseMessageEventsProps {\n appId: string;\n userId: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n externalId?: string | null;\n deviceId: string;\n apiClient: EloquentAiApiClient | null;\n chatSettings: BootResponse[\"chat_settings\"] | null;\n messages: Message[];\n setMessages: Dispatch<SetStateAction<Message[]>>;\n currentChat: { id: string } | null;\n setCurrentChat: Dispatch<SetStateAction<{ id: string } | null>>;\n onChatClosed?: () => void;\n isChatClosed?: boolean;\n}\n\nexport interface UseMessageEventsReturn {\n onCleanMessages: () => void;\n onSendMessage: (data: MessageData) => Promise<void>;\n onRateChat: (rating: number) => Promise<void>;\n}\n\n/**\n * Hook to handle message events like sending and cleaning\n */\nexport function useMessageEvents({\n appId,\n userId,\n userName,\n userData,\n externalId,\n deviceId,\n apiClient,\n chatSettings,\n messages,\n setMessages,\n currentChat,\n setCurrentChat,\n onChatClosed,\n isChatClosed,\n}: UseMessageEventsProps): UseMessageEventsReturn {\n const { saveChatData, clearChatData, updateLastActivity, markChatClosed } =\n usePersistence({\n appId,\n });\n\n const { publishApiError, publishNetworkError } = useErrorContext();\n const { showCognition, hideCognition } = useAgentCognitionContext();\n\n // Keep apiClient in a ref so stable callbacks always use the latest instance\n const apiClientRef = useLatestRef(apiClient);\n\n /**\n * Handles receiving messages from the server.\n * Called by the WebSocket and backup poll — deduplication\n * is handled inside useRealtimeSocket via processedIds.\n */\n const onReceiveMessage = useCallback(\n (response: ChatResponse, chatId: string) => {\n if (!response.response.content) return;\n\n setMessages((prev) => {\n if (prev.some((msg) => msg.isRatingRequest)) return prev;\n // Ignore the message if it matches the configured welcome message\n if (\n chatSettings?.welcome_message &&\n response.response.content === chatSettings.welcome_message\n )\n return prev;\n const filteredMessages = prev.filter((msg) => !msg.isThinking);\n const updatedMessages: Message[] = [\n ...filteredMessages,\n messageFromChatResponse(response),\n ];\n saveChatData(\n chatId,\n userId,\n updatedMessages,\n deviceId,\n apiClientRef.current?.getChatToken(),\n );\n return updatedMessages;\n });\n },\n [chatSettings, deviceId, saveChatData, setMessages, userId, apiClientRef],\n );\n\n const handleRealTimeError = useCallback(() => {\n hideCognition();\n setMessages((prev) => prev.filter((msg) => !msg.isThinking));\n }, [setMessages, hideCognition]);\n\n const handleRatingRequest = useCallback(() => {\n setMessages((prev) => {\n const filtered = prev.filter((msg) => !msg.isRatingRequest);\n return [...filtered, createRatingRequestMessage()];\n });\n }, [setMessages]);\n\n useEffect(() => {\n if (import.meta.env.DEV) {\n const w = window as unknown as Record<string, unknown>;\n w.EloquentAI_TriggerChatRating = handleRatingRequest;\n return () => {\n delete w.EloquentAI_TriggerChatRating;\n };\n }\n }, [handleRatingRequest]);\n\n const fetchHistory = useCallback(\n (chatId: string) => {\n if (!apiClientRef.current) return Promise.resolve([]);\n return apiClientRef.current.getChatHistory(chatId);\n },\n [apiClientRef],\n );\n\n const getChatToken = useCallback(() => {\n return apiClientRef.current?.getChatToken() ?? null;\n }, [apiClientRef]);\n\n const handleChatClosed = useCallback(() => {\n markChatClosed();\n onChatClosed?.();\n }, [markChatClosed, onChatClosed]);\n\n const { connect, disconnect, clearProcessedIds } = useRealtimeSocket({\n chatSettings,\n chatId: currentChat?.id ?? null,\n messages,\n onMessage: onReceiveMessage,\n onCognition: showCognition,\n onCognitionComplete: hideCognition,\n onError: handleRealTimeError,\n onChatClosed: handleChatClosed,\n onRatingRequest: handleRatingRequest,\n onBreadcrumb: handleChatClosed,\n fetchHistory,\n getChatToken,\n });\n\n const onCleanMessages = useCallback(() => {\n hideCognition();\n disconnect();\n clearProcessedIds();\n setMessages((prev) =>\n prev.filter((message) => {\n if (Array.isArray(message)) return false;\n return message.isWelcomeMessage;\n }),\n );\n clearChatData();\n setCurrentChat(null);\n }, [\n hideCognition,\n disconnect,\n clearProcessedIds,\n clearChatData,\n setMessages,\n setCurrentChat,\n ]);\n\n /**\n * Handles sending messages to the server\n */\n const onSendMessage = useCallback(\n async (message: MessageData) => {\n if (!apiClient) return;\n\n if (messages.some((msg) => msg.isRatingRequest)) return;\n\n if (isChatClosed) {\n setMessages((prev) => [...prev, createChatClosedNoticeMessage()]);\n return;\n }\n\n const userMessage = {\n ...message,\n id: crypto.randomUUID(),\n isNew: true,\n };\n\n showCognition();\n const newMessages = [...messages, userMessage];\n setMessages(newMessages);\n updateLastActivity();\n\n try {\n let chatId = currentChat?.id;\n if (!chatId) {\n const response = await apiClient.createConversation({\n userId: externalId || userId,\n deviceId,\n userName,\n userData,\n externalMetadata: {\n searchParams: getCurrentUrlSearchParams(),\n },\n });\n chatId = response.chat_id;\n setCurrentChat({ id: chatId });\n try {\n await connect(chatId);\n } catch (connectError) {\n console.warn(\n \"Failed to connect realtime channel, continuing with REST-only delivery:\",\n connectError,\n );\n }\n }\n\n const response = await apiClient.replyToConversation({\n text: message.content,\n conversationId: chatId,\n userId: externalId || userId,\n deviceId,\n userName,\n userData,\n });\n\n // Update user message with real server ID\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === userMessage.id\n ? { ...msg, id: response.message_id, isNew: false }\n : msg,\n ),\n );\n } catch (error) {\n hideCognition();\n\n setMessages((prev) => prev.filter((msg) => !msg.isThinking));\n\n if (\n error instanceof NetworkError ||\n (error instanceof ServerError && error.status === 403)\n ) {\n publishNetworkError();\n throw error;\n }\n\n publishApiError(error as ServerError);\n\n if (\n error instanceof ServerError &&\n // A 401 here means the chat's session token is invalid/expired\n // (or the chat closed) — treat it the same as a client-side\n // expired chat: drop the stale session and let the next send\n // start a fresh one, instead of surfacing an error.\n (error.status >= 500 || error.status === 401)\n ) {\n setCurrentChat(null);\n clearChatData();\n setMessages((prev) => prev.slice(0, -1));\n apiClient.reset();\n } else {\n // Mark the user message as failed\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === userMessage.id ? { ...msg, isFailed: true } : msg,\n ),\n );\n }\n\n throw error;\n }\n },\n [\n apiClient,\n isChatClosed,\n showCognition,\n messages,\n setMessages,\n updateLastActivity,\n currentChat?.id,\n externalId,\n userId,\n deviceId,\n setCurrentChat,\n connect,\n hideCognition,\n publishApiError,\n publishNetworkError,\n clearChatData,\n userName,\n userData,\n ],\n );\n\n const onRateChat = useCallback(\n async (rating: number) => {\n const chatId = currentChat?.id;\n if (!apiClientRef.current || !chatId) return;\n await apiClientRef.current.addRating(chatId, rating);\n },\n [currentChat?.id, apiClientRef],\n );\n\n return {\n onCleanMessages,\n onSendMessage,\n onRateChat,\n };\n}\n","// Helper to safely access import.meta.env in SSR environments\nfunction getEnvVariable(key: string): string {\n // Check if we're in a browser or if import.meta is available\n if (typeof window === \"undefined\" || typeof import.meta === \"undefined\") {\n return \"\";\n }\n return (import.meta.env[key] as string) || \"\";\n}\n\n// Define environment-specific constants that will be replaced during build\nconst ENV_API_URL = getEnvVariable(\"VITE_API_URL\");\nconst ENV_REGION_API_URL = getEnvVariable(\"VITE_REGION_API_URL\");\n\n/**\n * Returns the API URL based on the provided custom URL or the default API URL.\n * @returns The API URL.\n */\nexport function getApiUrl(): string {\n return ENV_API_URL || \"\";\n}\n\n/**\n * Returns the Region API URL based on the environment.\n * @returns The Region API URL.\n */\nexport function getRegionApiUrl(): string {\n return ENV_REGION_API_URL || \"\";\n}\n","import { getRegionApiUrl } from \"./config\";\nimport { HttpClient, HttpClientConfig } from \"./http\";\n\ninterface UserData {\n device_id: string;\n user_id?: string;\n user_name?: string;\n external_id?: string;\n user_data?: Record<string, string | number | boolean>;\n}\n\ninterface Message {\n text: string;\n user_data: UserData;\n}\n\nexport interface ConversationApiResponse {\n chat_id: string;\n message_id: string;\n response: {\n id: string;\n type: string;\n content: string;\n };\n}\n\nexport interface CreateConversationApiResponse {\n chat_id: string;\n chat_token: string;\n}\n\nexport interface IdentifyUserApiResponse {\n result: string;\n}\n\nexport interface MessageResponse {\n response: {\n id: string;\n type: string;\n content: string;\n };\n message_id: string;\n message_number: number;\n created_at: string;\n previousMessage?: MessageResponse;\n role: \"user\" | \"assistant\" | \"system\";\n}\n\nexport interface AddRatingApiResponse {\n result: string;\n}\n\nexport interface OrganizationResponse {\n region: string;\n}\n\nexport interface ExternalMetadata {\n [key: string]: string | ExternalMetadata;\n}\n\nexport interface BootResponse {\n chat_settings: {\n agent_name: string;\n welcome_message?: string | null;\n footer_html?: string | null;\n suggested_messages: boolean;\n suggested_message_texts?: string[] | null;\n suggested_message_aura?: boolean | null;\n suggested_message_shine?: boolean | null;\n auto_display_welcome_message: boolean;\n collect_user_feedback: boolean;\n theme: \"light\" | \"dark\";\n avatar_url?: string | null;\n user_bubble_color?: string | null;\n bot_bubble_color?: string | null;\n suggested_message_bubble_color?: string | null;\n user_bubble_text_color?: string | null;\n bot_bubble_text_color?: string | null;\n suggested_message_bubble_text_color?: string | null;\n app_sync_api_key: string;\n app_sync_url: string;\n app_sync_region: string;\n title?: string;\n subtitle?: string;\n is_active?: boolean;\n /** Open the chat window on load (desktop only). Wins over the isInitiallyOpen prop, but a `true` here never overrides the user's closed-cookie. */\n initial_open?: boolean | null;\n /** Show the close (X) button in the chat header. Always wins over the hasCloseButton prop. */\n close_button?: boolean | null;\n /** Show the clear-conversation button in the chat header. Always wins over the hasCleanChatButton prop. */\n clean_chat_button?: boolean | null;\n /** Auto-hide delay for the proactive message, in milliseconds. Always wins over the proactiveMessageHideDelay prop. */\n proactive_message_hide_delay?: number | null;\n };\n}\n\nexport class EloquentAiApiClient {\n private httpClient: HttpClient;\n private userId: string | null = null;\n private conversationId: string | null = null;\n\n constructor(config: HttpClientConfig) {\n this.userId = config.userId || null;\n this.httpClient = new HttpClient(config);\n }\n\n getUserData() {\n return {\n userId: this.userId,\n conversationId: this.conversationId,\n };\n }\n\n /**\n * Reset API client by clearing all stored state\n */\n reset() {\n this.conversationId = null;\n this.httpClient.setChatToken(null);\n }\n\n setRegion(region: string): void {\n this.httpClient.setRegion(region);\n }\n\n getChatToken(): string | null {\n return this.httpClient.getChatToken();\n }\n\n setChatToken(token: string | null): void {\n this.httpClient.setChatToken(token);\n }\n\n /**\n * Get organization data by app ID\n */\n async getOrganizationByAppId(appId: string) {\n const regionApiUrl = getRegionApiUrl();\n const response = await this.httpClient.getExternal<OrganizationResponse>(\n `${regionApiUrl}/by-app-id/${appId}`,\n );\n return response;\n }\n\n async boot() {\n const response = await this.httpClient.get<{ data: BootResponse }>(\n \"/v1/sdk/boot\",\n );\n return response.data;\n }\n\n async addRating(chatId: string, rating: number) {\n const response = await this.httpClient.put<\n { data: AddRatingApiResponse },\n { rating: number }\n >(`/v1/chat/${chatId}/rating`, { rating: rating });\n return response.data;\n }\n\n async createConversation(options: {\n userId: string;\n deviceId: string;\n userName?: string;\n externalId?: string;\n userData?: Record<string, string | number | boolean>;\n externalMetadata?: ExternalMetadata;\n }) {\n const response = await this.httpClient.post<\n { data: CreateConversationApiResponse },\n { user_data: UserData; external_metadata?: ExternalMetadata }\n >(\"/v2/chat\", {\n user_data: {\n user_id: options.userId,\n device_id: options.deviceId,\n user_name: options.userName,\n external_id: options.externalId,\n user_data: options.userData,\n },\n ...(options.externalMetadata &&\n Object.keys(options.externalMetadata).length > 0\n ? { external_metadata: options.externalMetadata }\n : {}),\n });\n\n const { data } = response;\n this.httpClient.setChatToken(data.chat_token);\n\n return data;\n }\n\n async replyToConversation(options: {\n text: string;\n conversationId: string;\n userId: string;\n deviceId: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n }) {\n const message: Message = {\n text: options.text,\n user_data: {\n device_id: options.deviceId,\n user_id: options.userId,\n user_name: options.userName,\n user_data: options.userData,\n },\n };\n\n const { data } = await this.httpClient.post<\n { data: ConversationApiResponse },\n Message\n >(`/v3/chat/${options.conversationId}`, message);\n\n return data;\n }\n\n async identifyUser(options: {\n conversationId: string;\n userId: string;\n deviceId: string;\n userName?: string;\n externalId?: string;\n userData?: Record<string, string | number | boolean>;\n }) {\n const message: UserData = {\n device_id: options.deviceId,\n user_id: options.userId,\n user_name: options.userName,\n external_id: options.externalId,\n user_data: options.userData,\n };\n\n const { data } = await this.httpClient.post<\n { data: IdentifyUserApiResponse },\n UserData\n >(`/v1/chat/${options.conversationId}/identify`, message);\n\n return data;\n }\n\n async getChatHistory(conversationId: string) {\n const response = await this.httpClient.get<{ data: MessageResponse[] }>(\n `/v1/chat/${conversationId}/history`,\n );\n return response.data;\n }\n}\n","import { ServerError } from \"@/lib/http\";\n\n/**\n * Wraps a Promise and returns a tuple containing the result or error\n * @param promise Promise to wrap\n * @returns [result, error] - result is null if error occurred, error is null if no error occurred\n */\nexport async function wrapPromise<T, E = ServerError>(\n promise: Promise<T>,\n): Promise<[T, null] | [null, E]> {\n try {\n return [await promise, null] as const;\n } catch (error) {\n return [null, error as E] as const;\n }\n}\n","import { NetworkError, ServerError } from \"./http\";\n\ninterface WithRetryOptions {\n retries?: number;\n minDelayMs?: number;\n maxDelayMs?: number;\n factor?: number;\n}\n\nconst DEFAULT_OPTIONS: Required<WithRetryOptions> = {\n retries: 3,\n minDelayMs: 200,\n maxDelayMs: 1_000,\n factor: 2,\n};\n\n/** Retries on network errors and 5xx/429 responses; other errors bail immediately. */\nexport function isRetryableError(error: unknown): boolean {\n if (error instanceof NetworkError) return true;\n if (error instanceof ServerError) {\n return error.status === 429 || error.status >= 500;\n }\n return false;\n}\n\n/** Exponential backoff with full jitter, mirroring the retry shape used in chat-api's http-retry.util.ts. */\nfunction getDelayMs(\n attempt: number,\n options: Required<WithRetryOptions>,\n): number {\n const exponentialDelay = options.minDelayMs * options.factor ** attempt;\n const cappedDelay = Math.min(exponentialDelay, options.maxDelayMs);\n return Math.random() * cappedDelay;\n}\n\nexport async function withRetry<T>(\n operation: () => Promise<T>,\n options: WithRetryOptions = {},\n): Promise<T> {\n const opts = { ...DEFAULT_OPTIONS, ...options };\n\n for (let attempt = 0; ; attempt++) {\n try {\n return await operation();\n } catch (error) {\n if (attempt >= opts.retries || !isRetryableError(error)) {\n throw error;\n }\n await new Promise((resolve) =>\n setTimeout(resolve, getDelayMs(attempt, opts)),\n );\n }\n }\n}\n","import { useErrorContext } from \"@/contexts/error-handling/error-context\";\nimport { NetworkError, ServerError } from \"@/lib/http\";\nimport { useCallback, useRef, useState } from \"react\";\n\n// Module-level cache and in-flight promise tracker\nconst cache = new Map<string, unknown>();\nconst inflight = new Map<string, Promise<unknown>>();\n\ninterface UseFetchOptions {\n dedupe?: boolean;\n}\n\ninterface UseFetchResult<T, E> {\n data: T | undefined;\n error: E | undefined;\n isLoading: boolean;\n fetch: () => Promise<T>;\n}\n\n/**\n * useFetch hook that deduplicates requests and prevents double-fetching.\n * Fetch is triggered by calling the returned fetch function, not automatically.\n * @param key Unique key for the resource (should uniquely identify the request)\n * @param fetcher Function that returns a promise for the data\n * @param options Options object (dedupe: boolean)\n */\nexport function useFetch<T, E = Error>(\n key: string,\n fetcher: () => Promise<T | undefined>,\n options?: UseFetchOptions,\n): UseFetchResult<T, E> {\n const dedupe = options?.dedupe !== false; // default to true\n const [data, setData] = useState<T | undefined>(\n () => cache.get(key) as T | undefined,\n );\n const { publishApiError, publishNetworkError } = useErrorContext();\n\n const [error, setError] = useState<E | undefined>(undefined);\n const [isLoading, setIsLoading] = useState<boolean>(false);\n const mountedRef = useRef(true);\n\n // Clean up on unmount\n useRef(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n });\n\n const fetch = useCallback(async (): Promise<T> => {\n if (cache.has(key)) {\n const cachedData = cache.get(key) as T;\n setData(cachedData);\n return cachedData;\n }\n\n setIsLoading(true);\n setError(undefined);\n\n try {\n // If we have an in-flight request and dedupe is enabled, use that\n if (dedupe && inflight.has(key)) {\n return (await inflight.get(key)) as Promise<T>;\n }\n\n // Otherwise, create a new request\n const promise = fetcher();\n\n // Track it if deduplication is enabled\n if (dedupe) {\n inflight.set(key, promise);\n }\n\n // Await the result directly\n const result = await promise;\n\n // Update cache and state\n cache.set(key, result);\n if (mountedRef.current) {\n setData(result);\n }\n\n return result as T;\n } catch (err) {\n if (\n err instanceof NetworkError ||\n (err instanceof ServerError && err.status === 403)\n ) {\n publishNetworkError();\n } else {\n publishApiError(err as ServerError);\n }\n if (mountedRef.current) {\n setError(err as E);\n }\n throw err;\n } finally {\n // Clean up\n if (dedupe) {\n inflight.delete(key);\n }\n if (mountedRef.current) {\n setIsLoading(false);\n }\n }\n }, [key, dedupe, fetcher, publishApiError, publishNetworkError]);\n\n return { data, error, isLoading, fetch };\n}\n","import { useState } from \"react\";\nimport { usePersistence, type ChatData } from \"./use-persistence\";\n\ntype UserIdentityOptions = { appId: string; initialUserId?: string };\n\ntype UserIdentityReturn = {\n userId: string;\n deviceId: string;\n isReady: boolean;\n externalId?: string | null;\n};\n\ntype ResolvedIdentity = {\n userId: string;\n deviceId: string;\n externalId?: string | null;\n};\n\nfunction resolveUserIdentity(\n savedData: ChatData,\n initialUserId?: string,\n): ResolvedIdentity {\n const deviceId = savedData?.deviceId || crypto.randomUUID();\n\n if (!savedData?.userId) {\n if (initialUserId) {\n // TODO should we have an internal userId and a different externalId?\n return { userId: initialUserId, externalId: initialUserId, deviceId };\n }\n return { userId: crypto.randomUUID(), externalId: null, deviceId };\n }\n if (savedData.externalId !== initialUserId) {\n // If the externalId is the same as the initialUserId, we can use the saved userId\n return { userId: savedData.userId, externalId: initialUserId, deviceId };\n }\n return {\n userId: savedData.userId,\n externalId: savedData.externalId,\n deviceId,\n };\n}\n\n/**\n * Hook that manage to generate the userId and deviceId, this should be the source of truth when dealing with user identity\n * @returns\n */\nexport function useUserIdentity(\n options: UserIdentityOptions,\n): UserIdentityReturn {\n const { appId, initialUserId } = options;\n\n const { getSavedChatData } = usePersistence({ appId });\n\n // Resolved synchronously (localStorage reads are synchronous) so dependents\n // — the SDK boot effect — can start on the first commit instead of waiting\n // an extra render for a mount effect to fill the identity in.\n const [identity, setIdentity] = useState<ResolvedIdentity>(() =>\n resolveUserIdentity(getSavedChatData(), initialUserId),\n );\n\n // Host apps may pass `userId` late (e.g. after an async login). Re-resolve\n // during render (React's alternative to a mirror effect).\n const [prevInitialUserId, setPrevInitialUserId] = useState(initialUserId);\n if (prevInitialUserId !== initialUserId) {\n setPrevInitialUserId(initialUserId);\n setIdentity(resolveUserIdentity(getSavedChatData(), initialUserId));\n }\n\n return {\n // Identity is available synchronously; kept in the contract because\n // consumers (SDK boot) still key off it.\n isReady: true,\n userId: identity.userId,\n deviceId: identity.deviceId,\n externalId: identity.externalId,\n };\n}\n","\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\n\nimport { Message } from \"@/types/message\";\n\nimport { getApiUrl } from \"@/lib/config\";\nimport {\n BootResponse,\n EloquentAiApiClient,\n} from \"@/lib/eloquent-ai-api-client\";\nimport { wrapPromise } from \"@/lib/wrap-promise\";\nimport { withRetry } from \"@/lib/retry\";\n\nimport { useFetch } from \"@/hooks/use-fetch\";\n\nimport { createWelcomeMessage } from \"../message-mapping\";\nimport { usePersistence } from \"./use-persistence\";\nimport { useUserIdentity } from \"./use-user-identity\";\n\nexport interface UseSdkInitializationProps {\n environment: \"test\" | \"live\";\n apiUrl?: string;\n appId: string;\n initialUserId?: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n}\n\nexport interface UseSdkInitializationReturn {\n userId: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n externalId?: string | null;\n deviceId: string;\n apiClient: EloquentAiApiClient | null;\n chatSettings: BootResponse[\"chat_settings\"] | null;\n currentChat: { id: string } | null;\n messages: Message[];\n isReady: boolean;\n isChatClosed: boolean;\n isChatActive: boolean;\n}\n\n/**\n * Hook to handle SDK initialization for the EloquentAI Chat SDK\n * Handles API client initialization, saved conversation restoration, and SDK boot\n */\nexport function useSdkInitialization({\n apiUrl: apiUrlOverride,\n appId,\n initialUserId,\n userName,\n userData,\n}: UseSdkInitializationProps): UseSdkInitializationReturn {\n // Get a pair of userId and deviceId\n const {\n userId,\n externalId,\n deviceId,\n isReady: isUserIdentityReady,\n } = useUserIdentity({ appId, initialUserId });\n\n const { isChatExpired, clearChatData, getSavedChatData } = usePersistence({\n appId,\n });\n\n const { current: apiUrl } = useRef(apiUrlOverride || getApiUrl());\n const [apiClient] = useState<EloquentAiApiClient>(\n new EloquentAiApiClient({\n baseURL: apiUrl,\n appId: appId,\n }),\n );\n const [chatSettings, setChatSettings] = useState<\n BootResponse[\"chat_settings\"] | null\n >(null);\n const [currentChat, setCurrentChat] = useState<{\n id: string;\n } | null>(null);\n const [messages, setMessages] = useState<Message[]>([]);\n const [isReady, setIsReady] = useState(false);\n const [isChatClosed, setIsChatClosed] = useState(false);\n const [isChatActive, setIsChatActive] = useState(true);\n\n // Use a unique key to differentiate between Chat SDK instances with different appIds\n const sdkBoot = useFetch(`sdk-boot-${appId}`, () => apiClient.boot());\n const sdkBootFetch = sdkBoot.fetch;\n\n // Initialize API client on the client side only\n useEffect(() => {\n // Check if there's an existing conversation and if it's not expired\n if (!isChatExpired()) {\n const {\n conversationId: chatId,\n userId,\n messages: savedMessages,\n isChatClosed: savedIsChatClosed,\n chatToken: savedChatToken,\n } = getSavedChatData();\n\n if (chatId && userId) {\n setCurrentChat({\n id: chatId,\n });\n apiClient.setChatToken(savedChatToken ?? null);\n\n // If we have saved messages, use them\n if (savedMessages && savedMessages.length > 0) {\n setMessages(savedMessages);\n }\n\n if (savedIsChatClosed) {\n setIsChatClosed(true);\n }\n }\n } else {\n // Clear expired conversation data\n clearChatData();\n // The next API call will automatically generate a new device ID\n }\n }, [getSavedChatData, isChatExpired, clearChatData, apiClient]);\n\n // Boot the SDK exactly once, when the user identity becomes available. The\n // ref guard (rather than deps alone) keeps re-renders from re-firing the\n // org + boot requests: sdkBootFetch gets a new identity every render, so\n // without the guard the effect would re-run constantly.\n const hasBootedRef = useRef(false);\n useEffect(() => {\n if (!isUserIdentityReady || hasBootedRef.current) return;\n hasBootedRef.current = true;\n\n const bootSDK = async () => {\n // Step 1: Fetch organization data to get region\n const [orgResponse, orgError] = await wrapPromise(\n withRetry(() => apiClient.getOrganizationByAppId(appId)),\n );\n\n if (orgError) {\n console.error(\"Failed to fetch organization data:\", orgError);\n setIsChatActive(false);\n setIsReady(true);\n return;\n }\n\n // Step 2: Store region for subsequent API calls\n apiClient.setRegion(orgResponse.region);\n\n // Step 3: Now call boot endpoint\n const [response, error] = await wrapPromise(withRetry(sdkBootFetch));\n\n if (error) {\n setIsChatActive(false);\n setIsReady(true);\n return;\n }\n\n const welcomeMessage = response.chat_settings.welcome_message;\n\n setChatSettings(response.chat_settings);\n setIsChatActive(response.chat_settings.is_active ?? true);\n\n // Only set welcome message if we don't already have one (functional update to avoid race conditions)\n if (welcomeMessage) {\n setMessages((prev) => {\n if (prev.length > 0 || prev.some((m) => m.isWelcomeMessage))\n return prev;\n return [createWelcomeMessage(welcomeMessage)];\n });\n }\n\n setIsReady(true);\n };\n\n bootSDK();\n }, [isUserIdentityReady, apiClient, appId, sdkBootFetch]);\n\n return {\n userId,\n userName,\n userData,\n externalId,\n deviceId,\n apiClient,\n chatSettings,\n currentChat,\n messages,\n isReady,\n isChatClosed,\n isChatActive,\n };\n}\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n// Matches Tailwind's `sm` breakpoint; kept in sync with the mobile-only CSS rules.\nconst MOBILE_MEDIA_QUERY = \"(max-width: 640px)\";\n\n// matchMedia (not window.innerWidth) so the check reflects the actual visual\n// viewport used for layout on mobile browsers (browser chrome, pinch-zoom,\n// display-zoom accessibility settings), and computed lazily so the very first\n// render already reflects the real device instead of defaulting to desktop.\nfunction getIsMobileScreen(): boolean {\n if (typeof window === \"undefined\") return false;\n return window.matchMedia(MOBILE_MEDIA_QUERY).matches;\n}\n\n/**\n * Hook to handle UI initialization for the chat component\n * Handles mobile detection and portal container creation\n */\nexport function useUiInitialization(propIsMobile?: boolean): {\n isMobileScreen: boolean;\n isMobile: boolean;\n portalContainer: HTMLElement | null;\n} {\n const [isMobileScreen, setIsMobileScreen] = useState(getIsMobileScreen);\n const [portalContainer, setPortalContainer] = useState<HTMLElement | null>(\n null,\n );\n\n // Determine if mobile based on prop or screen size\n const isMobile = propIsMobile ?? isMobileScreen;\n\n const isSSR = typeof window === \"undefined\";\n\n // Check if the screen is mobile, and keep it in sync as the viewport changes\n useEffect(() => {\n if (isSSR) return;\n\n const mediaQueryList = window.matchMedia(MOBILE_MEDIA_QUERY);\n const handleChange = (event: MediaQueryList | MediaQueryListEvent) => {\n setIsMobileScreen(event.matches);\n };\n\n handleChange(mediaQueryList);\n mediaQueryList.addEventListener(\"change\", handleChange);\n return () => mediaQueryList.removeEventListener(\"change\", handleChange);\n }, [isSSR]);\n\n // Create a container for the chat interface\n useEffect(() => {\n if (isSSR) return;\n\n const container = document.createElement(\"div\");\n container.className = \"eloquent-ai-chat-portal\";\n container.style.position = \"relative\";\n container.style.zIndex = \"30\";\n document.body.appendChild(container);\n setPortalContainer(container);\n\n return () => {\n if (container.parentElement) {\n container.parentElement.removeChild(container);\n }\n };\n }, [isSSR]);\n\n return {\n isMobileScreen,\n isMobile,\n portalContainer,\n };\n}\n","\"use client\";\n\nimport { useDebounce } from \"@/hooks/use-debounce\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { Message, MessageData } from \"@/types/message\";\n\nimport { ThemeContextType } from \"@/contexts/theme.context\";\n\nimport { ChatInterfaceProps } from \"@/components/chat-interface\";\n\nimport { deleteCookie, getCookie, setCookie } from \"@/lib/cookies\";\n\nimport { useInterfaceProps } from \"./use-interface-props\";\nimport { useMessageEvents } from \"./use-message-events\";\nimport { useSdkInitialization } from \"./use-sdk-initialization\";\nimport { useUiInitialization } from \"./use-ui-initialization\";\n\n// How long we remember that the user closed the chat widget\nconst CHAT_CLOSED_COOKIE_TTL_HOURS = 2;\nconst getChatClosedCookieName = (appId: string) =>\n `eloquent-ai:chat-widget-closed-${appId}`;\n\nexport interface UseChatProps {\n appId: string;\n userId?: string;\n userName?: string;\n userData?: Record<string, string | number | boolean>;\n theme?: Partial<ThemeContextType>;\n chatProps?: Partial<ChatInterfaceProps>;\n isMobile?: boolean;\n /** Show the close (X) button in the chat header. */\n hasCloseButton?: boolean;\n /** Show the clear-conversation button in the chat header. */\n hasCleanChatButton?: boolean;\n /** Open the chat window on load (desktop only). */\n isInitiallyOpen?: boolean;\n /** @deprecated Use `hasCloseButton` instead. Ignored when `hasCloseButton` is set. */\n closeButton?: boolean;\n /** @deprecated Use `hasCleanChatButton` instead. Ignored when `hasCleanChatButton` is set. */\n cleanChatButton?: boolean;\n /** @deprecated Use `isInitiallyOpen` instead. Ignored when `isInitiallyOpen` is set. */\n initialOpen?: boolean;\n proactiveMessageHideDelay?: number;\n}\n\nexport interface UseChatReturn {\n isReady: boolean;\n isChatActive: boolean;\n /** Effective initial-open (boot chat_settings.initial_open ?? prop). */\n isInitiallyOpen: boolean;\n /** Effective close-button visibility (boot chat_settings.close_button ?? prop). */\n hasCloseButton: boolean;\n /** Effective clear-chat-button visibility (boot chat_settings.clean_chat_button ?? prop). */\n hasCleanChatButton: boolean;\n isMobile: boolean;\n chatInterfaceProps: Partial<ChatInterfaceProps>;\n chatOpen: boolean;\n chatOpenDebounced: boolean;\n messages: Message[];\n portalContainer: HTMLElement | null;\n onSendMessage: (message: MessageData) => Promise<void>;\n setChatOpen: (value: boolean | ((prev: boolean) => boolean)) => void;\n onCleanMessages: () => void;\n proactiveMessage?: {\n text: string;\n isVisible: boolean;\n autoHideDelay: number;\n };\n hideProactiveMessage: () => void;\n isChatClosed: boolean;\n onStartNewChat: () => void;\n onRateChat: (rating: number) => Promise<void>;\n}\n\n/**\n * The primary chat hook, responsible for managing the chat state and operations.\n * @param options The hook parameters\n * @returns The chat hook return type\n */\nexport function useChat({\n environment,\n apiUrl,\n appId,\n userId: initialUserId,\n userName,\n userData,\n chatProps,\n isMobile: propIsMobile,\n isInitiallyOpen: propIsInitiallyOpen,\n hasCloseButton: propHasCloseButton,\n hasCleanChatButton: propHasCleanChatButton,\n // Deprecated aliases, kept until hosts migrate to the is/has names above.\n initialOpen: deprecatedInitialOpen,\n closeButton: deprecatedCloseButton,\n cleanChatButton: deprecatedCleanChatButton,\n proactiveMessageHideDelay: propProactiveMessageHideDelay = 5000,\n isAlwaysOpen = false,\n hasCleanChatButtonOverride,\n}: Readonly<\n Partial<UseChatProps> & {\n environment: \"test\" | \"live\";\n apiUrl?: string;\n appId: string;\n /**\n * Internal-only kill-switch (INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON): when\n * set, wins over both the boot `chat_settings.clean_chat_button` and the\n * `hasCleanChatButton` prop. Leave undefined for the normal boot ?? prop\n * resolution.\n */\n hasCleanChatButtonOverride?: boolean;\n /**\n * Embedded mode (INTERNAL_ONLY_CHAT_INTERFACE_ONLY): the interface is the\n * page content and there is no launcher bubble to reopen a closed chat, so\n * open/close state does not apply — not the isInitiallyOpen prop, not the\n * boot `chat_settings.initial_open`, and not the closed-cookie. Without\n * this, a boot `initial_open: false` closes the widget from under the\n * host page a moment after it renders.\n */\n isAlwaysOpen?: boolean;\n }\n>): UseChatReturn {\n // Use UI initialization hook for mobile detection and portal container\n const { isMobile, portalContainer } = useUiInitialization(propIsMobile);\n\n // Use SDK initialization hook for API client, chat settings and conversation state\n const {\n userId,\n externalId,\n deviceId,\n apiClient,\n chatSettings,\n currentChat: initialChat,\n messages: initialMessages,\n isReady,\n isChatClosed: initialIsChatClosed,\n isChatActive,\n } = useSdkInitialization({\n environment,\n apiUrl,\n appId,\n initialUserId,\n userName,\n userData,\n });\n\n // Generate chat interface props\n const chatInterfaceProps = useInterfaceProps({ chatProps, chatSettings });\n\n // The is/has names are canonical; the deprecated aliases only apply when\n // the new name is absent.\n const propInitialOpen = propIsInitiallyOpen ?? deprecatedInitialOpen ?? false;\n const propCloseButton = propHasCloseButton ?? deprecatedCloseButton ?? true;\n const propCleanChatButton =\n propHasCleanChatButton ?? deprecatedCleanChatButton ?? true;\n\n const chatClosedCookieName = getChatClosedCookieName(appId);\n\n const [chatOpen, setChatOpenState] = useState(() => {\n if (isAlwaysOpen) return true;\n if (getCookie(chatClosedCookieName) === \"true\") return false;\n return isMobile ? false : (propInitialOpen ?? isMobile);\n });\n\n // The server can also drive the initial open (chat_settings.initial_open).\n // The boot value wins over the prop, but NOT over the user's 2-hour\n // closed-cookie: if the user explicitly closed the widget, a boot `true`\n // must not reopen it on the next page. A boot `false` still applies (the\n // server force-closing never fights the user). Boot resolves after mount,\n // so apply it once when settings arrive. The mobile guard also remains (a\n // full-screen overlay opening uninvited on mobile is too disruptive). Uses\n // the raw setter so a server-driven open/close never writes the closed\n // cookie itself.\n const [hasAppliedBootInitialOpen, setHasAppliedBootInitialOpen] =\n useState(false);\n useEffect(() => {\n if (!isReady || hasAppliedBootInitialOpen) return;\n setHasAppliedBootInitialOpen(true);\n\n if (isAlwaysOpen) return;\n const bootInitialOpen = chatSettings?.initial_open;\n if (bootInitialOpen == null) return;\n if (isMobile) return;\n if (bootInitialOpen && getCookie(chatClosedCookieName) === \"true\") return;\n setChatOpenState(bootInitialOpen);\n }, [\n isReady,\n hasAppliedBootInitialOpen,\n chatSettings?.initial_open,\n isMobile,\n chatClosedCookieName,\n isAlwaysOpen,\n ]);\n\n // Effective value (boot ?? prop) — e.g. the proactive message is\n // suppressed when the chat starts open.\n const isInitiallyOpen = chatSettings?.initial_open ?? propInitialOpen;\n\n // Same server-wins pattern for the header buttons and the proactive\n // message delay: an explicit boot value (including false) beats the prop.\n const hasCloseButton = chatSettings?.close_button ?? propCloseButton;\n // The internal-only override (when set) beats both boot and prop.\n const hasCleanChatButton =\n hasCleanChatButtonOverride ??\n chatSettings?.clean_chat_button ??\n propCleanChatButton;\n const proactiveMessageHideDelay =\n chatSettings?.proactive_message_hide_delay ?? propProactiveMessageHideDelay;\n\n // Wrap the setter so that closing the chat widget is remembered for 2\n // hours, and reopening it clears that memory. In always-open (embedded)\n // mode the widget cannot close at all, and must not write the closed-cookie\n // — it would leak into the real launcher widget for the same appId.\n const setChatOpen = useCallback<\n (value: boolean | ((prev: boolean) => boolean)) => void\n >(\n (value) => {\n if (isAlwaysOpen) return;\n setChatOpenState((prev) => {\n const next = typeof value === \"function\" ? value(prev) : value;\n if (next) {\n deleteCookie(chatClosedCookieName);\n } else {\n setCookie(chatClosedCookieName, \"true\", CHAT_CLOSED_COOKIE_TTL_HOURS);\n }\n return next;\n });\n },\n [chatClosedCookieName, isAlwaysOpen],\n );\n\n const chatOpenDebounced = useDebounce(chatOpen, 400);\n const [messages, setMessages] = useState<Message[]>(\n chatProps?.messages ?? [],\n );\n const [currentChat, setCurrentChat] = useState<{\n id: string;\n } | null>(initialChat);\n\n const [isChatClosed, setIsChatClosed] = useState(false);\n\n // Adopt values arriving asynchronously from SDK initialization (localStorage\n // restore, boot welcome message) into the locally-owned state. setState\n // during render instead of mirror effects: React restarts the render\n // immediately, so consumers never see the stale value for a frame.\n const [prevInitialMessages, setPrevInitialMessages] =\n useState(initialMessages);\n if (prevInitialMessages !== initialMessages) {\n setPrevInitialMessages(initialMessages);\n if (initialMessages.length > 0) setMessages(initialMessages);\n }\n\n const [prevInitialChat, setPrevInitialChat] = useState(initialChat);\n if (prevInitialChat !== initialChat) {\n setPrevInitialChat(initialChat);\n if (initialChat) setCurrentChat(initialChat);\n }\n\n // Restore the \"chat closed\" state saved to localStorage, so it survives a\n // page refresh.\n const [prevInitialIsChatClosed, setPrevInitialIsChatClosed] =\n useState(initialIsChatClosed);\n if (prevInitialIsChatClosed !== initialIsChatClosed) {\n setPrevInitialIsChatClosed(initialIsChatClosed);\n if (initialIsChatClosed) setIsChatClosed(true);\n }\n\n const handleChatClosed = useCallback(() => {\n setIsChatClosed(true);\n }, []);\n\n // The proactive (welcome) bubble is fully derived from boot settings; the\n // only real state is whether the user dismissed it.\n const [hasDismissedProactiveMessage, setHasDismissedProactiveMessage] =\n useState(false);\n const proactiveMessageText =\n isReady &&\n chatSettings?.auto_display_welcome_message &&\n chatSettings?.welcome_message\n ? chatSettings.welcome_message\n : \"\";\n const proactiveMessage = {\n text: proactiveMessageText,\n isVisible: proactiveMessageText !== \"\" && !hasDismissedProactiveMessage,\n autoHideDelay: proactiveMessageHideDelay,\n };\n\n // Use message events hook for sending and cleaning messages\n const { onSendMessage, onCleanMessages, onRateChat } = useMessageEvents({\n appId,\n userId,\n userName,\n userData,\n externalId,\n deviceId,\n apiClient,\n chatSettings,\n setMessages,\n messages,\n currentChat,\n setCurrentChat,\n onChatClosed: handleChatClosed,\n isChatClosed,\n });\n\n // Sync with initialMessages when they change (from SDK initialization)\n useEffect(() => {\n if (initialMessages.length > 0) {\n setMessages(initialMessages);\n }\n }, [initialMessages]);\n\n useEffect(() => {\n if (initialChat) {\n setCurrentChat(initialChat);\n }\n }, [initialChat]);\n\n // Identify the user once per distinct payload. Host apps often recreate the\n // `userData` object every render, so comparing by value (not identity)\n // prevents a duplicate network call per re-render.\n const lastIdentifyKeyRef = useRef<string | null>(null);\n useEffect(() => {\n if (!currentChat || !externalId || !apiClient) return;\n\n const identifyPayload = {\n userId,\n userName,\n userData,\n externalId,\n deviceId,\n conversationId: currentChat.id,\n };\n const identifyKey = JSON.stringify(identifyPayload);\n if (lastIdentifyKeyRef.current === identifyKey) return;\n lastIdentifyKeyRef.current = identifyKey;\n\n apiClient.identifyUser(identifyPayload);\n }, [\n externalId,\n userId,\n userName,\n userData,\n deviceId,\n currentChat,\n apiClient,\n ]);\n\n const onStartNewChat = useCallback(() => {\n onCleanMessages();\n setIsChatClosed(false);\n }, [onCleanMessages]);\n\n const hideProactiveMessage = useCallback(() => {\n setHasDismissedProactiveMessage(true);\n }, []);\n\n return {\n isReady,\n isChatActive,\n isInitiallyOpen,\n hasCloseButton,\n hasCleanChatButton,\n isMobile,\n chatInterfaceProps,\n chatOpen,\n chatOpenDebounced,\n messages,\n portalContainer,\n onSendMessage,\n setChatOpen,\n onCleanMessages,\n proactiveMessage,\n hideProactiveMessage,\n isChatClosed,\n onStartNewChat,\n onRateChat,\n };\n}\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n/**\n * Tracks how much the on-screen keyboard overlaps the layout viewport, using\n * the VisualViewport API. Used to lift the chat input above the keyboard\n * without moving/resizing the rest of the chat window.\n */\nexport function useKeyboardInset(enabled: boolean): number {\n const [inset, setInset] = useState(0);\n\n useEffect(() => {\n const viewport = window.visualViewport;\n if (!enabled || !viewport) {\n setInset(0);\n return;\n }\n\n const update = () => {\n const overlap = window.innerHeight - viewport.height - viewport.offsetTop;\n setInset(Math.max(0, Math.round(overlap)));\n };\n\n update();\n viewport.addEventListener(\"resize\", update);\n viewport.addEventListener(\"scroll\", update);\n\n return () => {\n viewport.removeEventListener(\"resize\", update);\n viewport.removeEventListener(\"scroll\", update);\n setInset(0);\n };\n }, [enabled]);\n\n return inset;\n}\n","\"use client\";\n\nimport { useEffect } from \"react\";\n\n/**\n * Locks scrolling on the host page while active. Uses the fixed-body trick\n * (rather than plain `overflow: hidden`) so it also holds on iOS Safari,\n * which otherwise still allows background scroll/bounce behind the chat.\n */\nexport function useScrollLock(locked: boolean) {\n useEffect(() => {\n if (!locked) return;\n\n const { body } = document;\n const scrollY = window.scrollY;\n const previousStyle = {\n position: body.style.position,\n top: body.style.top,\n left: body.style.left,\n right: body.style.right,\n overflow: body.style.overflow,\n };\n\n body.style.position = \"fixed\";\n body.style.top = `-${scrollY}px`;\n body.style.left = \"0\";\n body.style.right = \"0\";\n body.style.overflow = \"hidden\";\n\n return () => {\n body.style.position = previousStyle.position;\n body.style.top = previousStyle.top;\n body.style.left = previousStyle.left;\n body.style.right = previousStyle.right;\n body.style.overflow = previousStyle.overflow;\n window.scrollTo(0, scrollY);\n };\n }, [locked]);\n}\n","import { useCallback, useRef, useState } from \"react\";\n\nexport interface UseAgentCognitionReturn {\n isVisible: boolean;\n content: string | null;\n showCognition: (content?: string) => void;\n hideCognition: () => void;\n}\n\nexport function useAgentCognition(): UseAgentCognitionReturn {\n const [isVisible, setIsVisible] = useState(false);\n const [content, setContent] = useState<string | null>(null);\n const timerRef = useRef<NodeJS.Timeout | null>(null);\n const pendingContentRef = useRef<string | null>(null);\n\n const showCognition = useCallback((newContent = \"...\") => {\n const updateCognition = () => {\n setContent(newContent);\n setIsVisible(true);\n pendingContentRef.current = null;\n\n // Clear existing timer\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n }\n\n // Set timer to allow updates after 1 second minimum display time\n timerRef.current = setTimeout(() => {\n timerRef.current = null;\n\n // If there's pending content, show it immediately\n if (pendingContentRef.current) {\n updateCognition();\n }\n }, 1000);\n };\n\n // If no timer is active, update immediately\n if (!timerRef.current) {\n updateCognition();\n } else {\n // Timer is active, queue the new content\n pendingContentRef.current = newContent;\n }\n }, []);\n\n const hideCognition = useCallback(() => {\n // Clear timer and pending content\n if (timerRef.current) {\n clearTimeout(timerRef.current);\n timerRef.current = null;\n }\n pendingContentRef.current = null;\n\n // Hide cognition\n setIsVisible(false);\n setContent(null);\n }, []);\n\n return {\n isVisible,\n content,\n showCognition,\n hideCognition,\n };\n}\n","import { ReactNode } from \"react\";\nimport { useAgentCognition } from \"@/contexts/agent-cognition/use-agent-cognition\";\nimport { AgentCognitionContext } from \"./agent-cognition-context\";\n\ninterface AgentCognitionProviderProps {\n children: ReactNode;\n}\n\nexport function AgentCognitionProvider({\n children,\n}: AgentCognitionProviderProps) {\n const cognition = useAgentCognition();\n\n return (\n <AgentCognitionContext.Provider value={cognition}>\n {children}\n </AgentCognitionContext.Provider>\n );\n}\n","import { useState, type ReactNode } from \"react\";\nimport { ErrorContext, SdkError, createPublishApiError } from \"./error-context\";\n\nexport const ErrorProvider = ({ children }: { children: ReactNode }) => {\n const [error, setError] = useState<SdkError | null>(null);\n const [hideSdk, setHideSdk] = useState(false);\n\n const publishApiError = createPublishApiError(setError);\n const publishError = (error: SdkError) => setError(error);\n const publishNetworkError = () => setHideSdk(true);\n const clearError = () => setError(null);\n\n const contextValue = {\n error,\n hideSdk,\n publishApiError,\n publishError,\n publishNetworkError,\n clearError,\n };\n\n return (\n <ErrorContext.Provider value={contextValue}>\n {children}\n </ErrorContext.Provider>\n );\n};\n","\"use client\";\n\nimport { type CSSProperties } from \"react\";\n\nimport mainCSS from \"@/index.css?inline\";\nimport wrapperCSS from \"@/wrapper.css?inline\";\n\nimport { Message } from \"@/types/message\";\n\nimport { cn } from \"@/lib/utils\";\n\nimport { ChatBubble } from \"@/components/embed/chat-bubble\";\nimport { ChatInterface } from \"@/components/chat-interface\";\nimport { SkeletonChatInterface } from \"@/components/chat-interface/skeleton\";\nimport { Iframe } from \"@/components/embed/iframe\";\nimport { Portal } from \"@/components/embed/portal\";\nimport { ProactiveMessage } from \"@/components/embed/proactive-message\";\n\nimport { useChat, type UseChatProps } from \"@/components/chat/hooks/use-chat\";\nimport { useKeyboardInset } from \"@/components/chat/hooks/use-keyboard-inset\";\nimport { useScrollLock } from \"@/components/chat/hooks/use-scroll-lock\";\nimport { AgentCognitionProvider } from \"@/contexts/agent-cognition/agent-cognition-provider\";\nimport { ErrorProvider } from \"@/contexts/error-handling/error-provider\";\nimport { useErrorContext } from \"@/contexts/error-handling/error-context\";\nimport { ThemeProvider } from \"@/contexts/theme.context\";\n\n/** Viewport inset (px) used to cap desktop chat height so it doesn’t overflow. */\nconst CHAT_DESKTOP_VIEWPORT_INSET_PX = 100;\n\n/** @internal */\ntype InternalChatProps = {\n INTERNAL_ONLY_CHAT_INTERFACE_ONLY?: boolean;\n INTERNAL_ONLY_BLOCK_STYLE?: boolean;\n /**\n * Force the clear-chat button on or off, winning over both the boot\n * `chat_settings.clean_chat_button` and the public `hasCleanChatButton`\n * prop. Leave unset to keep the normal boot ?? prop resolution.\n */\n INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON?: boolean;\n /** Show the copy-message button on assistant messages (default false). */\n INTERNAL_ONLY_SHOW_COPY_BUTTON?: boolean;\n INTERNAL_ONLY_ENVIRONMENT?: \"test\" | \"live\";\n INTERNAL_ONLY_API_URL?: string;\n INTERNAL_ONLY_FEATURE_MESSAGE_CLICK?: (message: Message) => void;\n INTERNAL_ONLY_FEATURE_CLEAR_CHAT_CLICK?: () => void;\n};\n\nexport type ChatProps = UseChatProps & InternalChatProps;\n\nfunction InternalChat({\n appId,\n userId,\n userName,\n userData,\n chatProps,\n proactiveMessageHideDelay = 5000,\n isMobile: propIsMobile,\n hasCloseButton: propHasCloseButton,\n hasCleanChatButton: propHasCleanChatButton,\n isInitiallyOpen: propIsInitiallyOpen,\n // Deprecated aliases, resolved in useChat (new name wins).\n closeButton: deprecatedCloseButton,\n cleanChatButton: deprecatedCleanChatButton,\n initialOpen: deprecatedInitialOpen,\n INTERNAL_ONLY_CHAT_INTERFACE_ONLY = false,\n INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON = undefined,\n INTERNAL_ONLY_BLOCK_STYLE = false,\n INTERNAL_ONLY_FEATURE_MESSAGE_CLICK = undefined,\n INTERNAL_ONLY_FEATURE_CLEAR_CHAT_CLICK = undefined,\n INTERNAL_ONLY_SHOW_COPY_BUTTON = false,\n INTERNAL_ONLY_ENVIRONMENT = \"live\",\n INTERNAL_ONLY_API_URL,\n}: Readonly<UseChatProps & InternalChatProps>) {\n const { hideSdk } = useErrorContext();\n\n const {\n isReady,\n isChatActive,\n isInitiallyOpen,\n hasCloseButton,\n hasCleanChatButton,\n isMobile,\n chatOpen,\n chatInterfaceProps,\n chatOpenDebounced,\n messages,\n portalContainer,\n onSendMessage,\n setChatOpen,\n proactiveMessage,\n hideProactiveMessage,\n isChatClosed,\n onStartNewChat,\n onRateChat,\n } = useChat({\n environment: INTERNAL_ONLY_ENVIRONMENT,\n apiUrl: INTERNAL_ONLY_API_URL,\n appId,\n userId,\n userName,\n userData,\n chatProps,\n isMobile: propIsMobile,\n isInitiallyOpen: propIsInitiallyOpen,\n hasCloseButton: propHasCloseButton,\n hasCleanChatButton: propHasCleanChatButton,\n initialOpen: deprecatedInitialOpen,\n closeButton: deprecatedCloseButton,\n cleanChatButton: deprecatedCleanChatButton,\n proactiveMessageHideDelay,\n // Embedded: the interface is the page content with no launcher to reopen\n // it, so nothing (boot initial_open, closed-cookie, props) may close it.\n isAlwaysOpen: INTERNAL_ONLY_CHAT_INTERFACE_ONLY,\n hasCleanChatButtonOverride: INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON,\n });\n\n const keyboardInset = useKeyboardInset(isMobile && chatOpen);\n useScrollLock(isMobile && chatOpen);\n\n const isBooting = !isReady;\n\n if (hideSdk) return null;\n // The launcher widget renders nothing until boot decides what to show. In\n // embedded mode the widget IS the page content: rendering null while a\n // remount boots (project/environment switch in the host app) collapses the\n // layout and flashes an empty hole — show the skeleton in place instead.\n if (isBooting && !INTERNAL_ONLY_CHAT_INTERFACE_ONLY) return null;\n if (!isBooting && !isChatActive) return null;\n\n const renderContent = () => {\n return (\n <div\n style={{\n WebkitTouchCallout: \"none\" /* iOS Safari */,\n WebkitUserSelect: \"none\" /* Safari */,\n KhtmlUserSelect: \"none\" /* Konqueror HTML */,\n MozUserSelect: \"none\" /* Old versions of Firefox */,\n msUserSelect: \"none\" /* Internet Explorer/Edge */,\n userSelect: \"none\" /* Chrome, Edge, Opera and Firefox */,\n position: \"fixed\",\n right: 12,\n bottom: 4,\n ...(INTERNAL_ONLY_BLOCK_STYLE\n ? { position: \"relative\", inset: 0, width: \"100%\", height: \"100%\" }\n : {}),\n }}\n >\n <style>{wrapperCSS}</style>\n <Iframe\n className=\"eloquentai-chat-messaging\"\n head={\n <>\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\" />\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" />\n <link\n href=\"https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap\"\n rel=\"stylesheet\"\n />\n <style>{mainCSS}</style>\n </>\n }\n style={\n {\n display: chatOpen\n ? \"block\"\n : chatOpenDebounced\n ? \"block\"\n : \"none\",\n width: isMobile ? \"100vw\" : \"400px\",\n // 100dvh accounts for mobile browser chrome (e.g. address bar); 100vh fallback for older browsers\n \"--chat-mobile-viewport-height\": \"100dvh\",\n height: isMobile\n ? \"var(--chat-mobile-viewport-height, 100vh)\"\n : \"700px\",\n maxHeight: isMobile\n ? \"var(--chat-mobile-viewport-height, 100vh)\"\n : `calc(100% - ${CHAT_DESKTOP_VIEWPORT_INSET_PX}px)`,\n border: \"none\",\n zIndex: 2147483000,\n position: \"fixed\",\n top: isMobile ? 0 : undefined,\n left: isMobile ? 0 : undefined,\n right: isMobile ? 0 : 16,\n bottom: isMobile ? 0 : 16,\n ...(INTERNAL_ONLY_BLOCK_STYLE\n ? {\n position: \"relative\",\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n width: \"100%\",\n height: \"100%\",\n maxHeight: \"100%\",\n zIndex: 0,\n }\n : {}),\n } as CSSProperties\n }\n >\n {isBooting ? (\n // Only reachable in embedded mode (the launcher returns null while\n // booting): hold the widget's frame with a skeleton so a remount —\n // project/environment switch in the host app — doesn't flash an\n // empty hole where the chat was.\n <SkeletonChatInterface isOpen isMobile={isMobile} skipAnimation />\n ) : (\n <ChatInterface\n {...chatInterfaceProps}\n // Embedded (interface-only) mode renders as page content: no\n // popup-style panel entrance.\n hasIntroAnimation={!INTERNAL_ONLY_CHAT_INTERFACE_ONLY}\n // Caution stripe: a session against the test agent must never be\n // mistaken for the production one.\n isTestMode={INTERNAL_ONLY_ENVIRONMENT === \"test\"}\n isOpen={chatOpen}\n keyboardInset={keyboardInset}\n messages={messages}\n onSendMessage={onSendMessage}\n onMessageClick={INTERNAL_ONLY_FEATURE_MESSAGE_CLICK}\n isMobile={isMobile}\n hasCloseButton={hasCloseButton}\n hasCleanChatButton={hasCleanChatButton}\n hasCopyButton={INTERNAL_ONLY_SHOW_COPY_BUTTON}\n isChatClosed={isChatClosed}\n onStartNewChat={onStartNewChat}\n onRateChat={onRateChat}\n onClose={() => setChatOpen(false)}\n onCleanChat={() => {\n onStartNewChat();\n INTERNAL_ONLY_FEATURE_CLEAR_CHAT_CLICK?.();\n }}\n />\n )}\n </Iframe>\n {!INTERNAL_ONLY_CHAT_INTERFACE_ONLY && (\n <Iframe\n className=\"eloquentai-chat-launcher\"\n head={<style>{mainCSS}</style>}\n style={{\n position: \"fixed\",\n bottom: 17,\n right: 17,\n display: \"block\",\n width: 48,\n height: 48,\n border: \"none\",\n zIndex: isMobile ? 2147482999 : 2147483000,\n opacity: chatOpen ? 0 : 1,\n pointerEvents: chatOpen ? \"none\" : \"auto\",\n transition: chatOpen\n ? \"opacity 100ms ease-in\"\n : \"opacity 200ms ease-out 320ms\",\n }}\n >\n <ChatBubble\n isOpen={chatOpen}\n toggleBubble={() => setChatOpen((prev) => !prev)}\n isDarkMode={chatInterfaceProps?.theme?.mode === \"dark\"}\n />\n </Iframe>\n )}\n {chatInterfaceProps?.displayWelcomeMessages ? (\n <Iframe\n className=\"eloquentai-chat-proactive-message\"\n head={<style>{mainCSS}</style>}\n style={{\n position: \"fixed\",\n // Aligns the bubble's tail with the launcher's center: the\n // launcher circle is 48px tall at bottom:17, so its center is\n // ~41px up; the tail sits ~16px above this iframe's bottom.\n bottom: 24,\n right: 17,\n }}\n >\n <ThemeProvider {...(chatInterfaceProps?.theme ?? {})}>\n {/* This iframe is outside the chat interface's dark-classed\n <main>, so dark: utilities need their own ancestor here. */}\n <div\n className={cn(\"eloq:w-full eloq:h-full\", {\n dark: chatInterfaceProps?.theme?.mode === \"dark\",\n })}\n >\n {proactiveMessage && !isInitiallyOpen && (\n <ProactiveMessage\n message={proactiveMessage.text}\n isVisible={proactiveMessage.isVisible}\n onDismiss={hideProactiveMessage}\n onMessageClick={() => {\n setChatOpen(true);\n hideProactiveMessage();\n }}\n autoHideDelay={proactiveMessage.autoHideDelay}\n />\n )}\n </div>\n </ThemeProvider>\n </Iframe>\n ) : null}\n </div>\n );\n };\n\n const renderChat = () => {\n if (INTERNAL_ONLY_BLOCK_STYLE) {\n return renderContent();\n }\n\n if (portalContainer) {\n return <Portal container={portalContainer}>{renderContent()}</Portal>;\n }\n\n return null;\n };\n\n return <>{renderChat()}</>;\n}\n\nexport function Chat(props: Readonly<ChatProps>) {\n return (\n <ErrorProvider>\n <AgentCognitionProvider>\n <InternalChat {...props} />\n </AgentCognitionProvider>\n </ErrorProvider>\n );\n}\n","import type { ComponentType } from \"react\";\nimport ReactDOMClient from \"react-dom/client\";\n\nimport { Chat, type ChatProps } from \"@/components/chat\";\n\ntype UnmountFunction = () => void;\n\nexport function renderChat(\n container: HTMLElement,\n props: ChatProps,\n): UnmountFunction {\n const render = (\n Component: ComponentType<ChatProps>,\n container: HTMLElement,\n props: ChatProps,\n ) => {\n const root = ReactDOMClient.createRoot(container);\n root.render(<Component {...props} />);\n return root.unmount;\n };\n return render(Chat, container, props);\n}\n"],"names":["environment","init","event","sensitiveHeaders","headers","key","ChatBubble","toggleBubble","isDarkMode","bubbleBackground","logoForeground","jsx","cn","Logo","Iframe","children","head","props","contentRef","setContentRef","useState","headNode","bodyNode","jsxs","createPortal","Portal","container","ProactiveMessage","message","isVisible","onDismiss","onMessageClick","autoHideDelay","shouldRender","setShouldRender","animationState","setAnimationState","theme","useTheme","useEffect","enterTimer","exitTimer","hideTimer","timer","getContrastingTextColor","e","X","getCookie","name","match","setCookie","value","hours","expires","deleteCookie","useInterfaceProps","chatProps","chatSettings","useMemo","useLatestRef","reference","useRef","NetworkError","ServerError","status","response","CHAT_TOKEN_HEADER","CHAT_TOKEN_RENEWED_HEADER","HttpClient","config","region","token","url","options","regionHeader","chatTokenHeader","error","renewedToken","responseData","data","getCurrentUrlSearchParams","params","result","STORAGE_NAMESPACE","isClient","CHAT_EXPIRY_TIME","usePersistence","appId","STORAGE_KEY","defaultObject","getSavedChatData","useCallback","storedData","isChatExpired","saveChatData","conversationId","userId","messages","deviceId","chatToken","chatData","markChatClosed","clearChatData","stored","updateLastActivity","APPSYNC_EVENTS_SUBPROTOCOL","HANDSHAKE_TIMEOUT_MILLISECONDS","DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS","KEEP_ALIVE_CHECK_INTERVAL_MILLISECONDS","WEB_SOCKET_OPEN_STATE","deriveRealtimeUrl","httpEndpoint","buildAuthorization","auth","host","encodeAuthProtocol","authorization","formatErrors","errors","connectAppSyncEvents","channel","onEvent","onDisconnect","createWebSocket","protocols","realtimeUrl","subscriptionId","resolve","reject","socket","phase","isClosedByClient","connectionTimeoutMilliseconds","lastLivenessTimestamp","handshakeTimer","keepAliveTimer","clearTimers","terminate","reason","wasEstablished","send","startHandshakeTimer","step","payload","jsonStringifyReplacer","_","Cached","getter","cached","cleanRegex","source","start","end","assignProp","target","prop","captureStackTrace","_args","isObject","escapeRegex","str","clone","inst","def","cl","normalizeParams","_params","optionalKeys","shape","k","aborted","x","startIndex","i","explicitlyAborted","prefixIssues","path","issues","iss","_a","unwrapMessage","attachSchema","finalizeIssue","ctx","traits","schemaError","full","members","proto","table","desc","defineBound","own","enumerable","hide","fn","claim","sentinel","installing","broke","breaker","defineLazyInternal","compute","outer","err","installLazyProp","make","_zodDesc","_E","newError","Definition","E","saved","$constructor","initializer","zodProto","Internals","protoMembers","initialized","ctorProto","up","installMembers","Parent","deferred","pp","$ZodAsyncError","globalConfig","newConfig","_getMessage","internals","util.jsonStringifyReplacer","_setMessage","_messageDesc","_issuesDesc","_installedToString","$ZodRealError","_parse","_Err","schema","_ctx","core.$ZodAsyncError","util.finalizeIssue","core.config","util.captureStackTrace","parse","errors.$ZodRealError","_parseAsync","parseAsync","_safeParse","failure","safeParse","Err","_safeParseAsync","safeParseAsync","anyString","_null","version","$ZodType","core.$constructor","defChecks","checks","ch","runChecks","isAborted","util.aborted","asyncResult","util.explicitlyAborted","currLen","util.attachSchema","handleCanaryResult","canary","checkResult","util.hide","standardProps","util.own","toStandardResult","r","validateAsync","$ZodString","regexes.anyString","$ZodNull","regexes.null","input","handlePropertyResult","final","optin","optout","isPresent","isOptionalOut","util.prefixIssues","NO_SYMBOL_KEYS","normalizeDef","keys","ownSymbols","symbolKeys","allKeys","okeys","util.optionalKeys","handleCatchall","proms","abortEarly","unrecognized","keySet","_catchall","t","seen","$ZodObject","sh","get","newSh","_normalized","util.cached","util.defineLazyInternal","zod","propValues","field","util.assignProp","v","util.isObject","catchall","memo","core.globalConfig","el","handleUnionResults","results","nonaborted","$ZodUnion","o","option","patterns","p","util.cleanRegex","first","async","$ZodLiteral","values","vals","util.escapeRegex","$ZodNullable","pattern","snapshotChecks","_string","Class","util.normalizeParams","ZodMiniType","core.$ZodType","parse.parse","parse.parseAsync","parse.safeParse","parse.safeParseAsync","_def","core.clone","reg","meta","args","ZodMiniString","core.$ZodString","string","core._string","ZodMiniNull","core.$ZodNull","core._null","ZodMiniObject","core.$ZodObject","util.installLazyProp","self","object","ZodMiniUnion","core.$ZodUnion","union","ZodMiniLiteral","core.$ZodLiteral","literal","ZodMiniNullable","core.$ZodNullable","nullable","innerType","zodConfig","utteranceSchema","z.object","z.literal","z.string","agentCognitionSchema","chatClosedExpiredSchema","agentCapturedUrlSchema","agentTopicSchema","agentSummarySchema","chatRatingSchema","breadcrumbSchema","chatEscalatedSchema","z.null","errorSchema","utteranceApiResponseSchema","z.nullable","errorApiResponseSchema","agentCognitionApiResponseSchema","chatClosedExpiredApiResponseSchema","agentCapturedUrlApiResponseSchema","agentTopicApiResponseSchema","agentSummaryApiResponseSchema","chatRatingApiResponseSchema","breadcrumbApiResponseSchema","chatEscalatedApiResponseSchema","chatResponseApiSchema","z.union","INITIAL_RECONNECT_DELAY_MS","MAX_RECONNECT_DELAY_MS","DEFAULT_BACKUP_POLL_INTERVAL_MS","useRealtimeSocket","chatId","onMessage","onCognition","onCognitionComplete","onError","onChatClosed","onAgentCapturedUrl","onAgentTopic","onAgentSummary","onRatingRequest","onBreadcrumb","fetchHistory","getChatToken","backupPollingInterval","processedIdsRef","msg","eventChannelRef","activeChatIdRef","reconnectAttemptsRef","reconnectTimerRef","backupPollIntervalRef","shouldReconnectRef","isReconnectingRef","onMessageRef","onCognitionRef","onCognitionCompleteRef","onErrorRef","onChatClosedRef","onAgentCapturedUrlRef","onAgentTopicRef","onAgentSummaryRef","onRatingRequestRef","onBreadcrumbRef","fetchHistoryRef","getChatTokenRef","publishError","useErrorContext","appSyncUrl","appSyncApiKey","isSocketConfigReady","appSyncUrlRef","appSyncApiKeyRef","closeChannel","stopBackupPoll","clearReconnectTimer","scheduleReconnectRef","connectChannel","chatIdToConnect","apiKey","connection","parseResult","notification","utterance","messageId","code","getErrorMessage","cognition","capturedUrl","topic","summary","runBackupPoll","chatIdToPoll","history","startBackupPoll","scheduleReconnect","scheduleReconnectSelf","chatIdToReconnect","delay","connect","disconnect","clearProcessedIds","messageFromChatResponse","createWelcomeMessage","content","createRatingRequestMessage","createChatClosedNoticeMessage","useMessageEvents","userName","userData","externalId","apiClient","setMessages","currentChat","setCurrentChat","isChatClosed","publishApiError","publishNetworkError","showCognition","hideCognition","useAgentCognitionContext","apiClientRef","onReceiveMessage","prev","updatedMessages","handleRealTimeError","handleRatingRequest","handleChatClosed","onCleanMessages","onSendMessage","userMessage","newMessages","connectError","onRateChat","rating","getEnvVariable","__vite_import_meta_env__","ENV_API_URL","ENV_REGION_API_URL","getApiUrl","getRegionApiUrl","EloquentAiApiClient","regionApiUrl","wrapPromise","promise","DEFAULT_OPTIONS","isRetryableError","getDelayMs","attempt","exponentialDelay","cappedDelay","withRetry","operation","opts","cache","inflight","useFetch","fetcher","dedupe","setData","setError","isLoading","setIsLoading","mountedRef","fetch","cachedData","resolveUserIdentity","savedData","initialUserId","useUserIdentity","identity","setIdentity","prevInitialUserId","setPrevInitialUserId","useSdkInitialization","apiUrlOverride","isUserIdentityReady","apiUrl","setChatSettings","isReady","setIsReady","setIsChatClosed","isChatActive","setIsChatActive","sdkBootFetch","savedMessages","savedIsChatClosed","savedChatToken","hasBootedRef","orgResponse","orgError","welcomeMessage","m","MOBILE_MEDIA_QUERY","getIsMobileScreen","useUiInitialization","propIsMobile","isMobileScreen","setIsMobileScreen","portalContainer","setPortalContainer","isMobile","isSSR","mediaQueryList","handleChange","CHAT_CLOSED_COOKIE_TTL_HOURS","getChatClosedCookieName","useChat","propIsInitiallyOpen","propHasCloseButton","propHasCleanChatButton","deprecatedInitialOpen","deprecatedCloseButton","deprecatedCleanChatButton","propProactiveMessageHideDelay","isAlwaysOpen","hasCleanChatButtonOverride","initialChat","initialMessages","initialIsChatClosed","chatInterfaceProps","propInitialOpen","propCloseButton","propCleanChatButton","chatClosedCookieName","chatOpen","setChatOpenState","hasAppliedBootInitialOpen","setHasAppliedBootInitialOpen","bootInitialOpen","isInitiallyOpen","hasCloseButton","hasCleanChatButton","proactiveMessageHideDelay","setChatOpen","next","chatOpenDebounced","useDebounce","prevInitialMessages","setPrevInitialMessages","prevInitialChat","setPrevInitialChat","prevInitialIsChatClosed","setPrevInitialIsChatClosed","hasDismissedProactiveMessage","setHasDismissedProactiveMessage","proactiveMessageText","proactiveMessage","lastIdentifyKeyRef","identifyPayload","identifyKey","onStartNewChat","hideProactiveMessage","useKeyboardInset","enabled","inset","setInset","viewport","update","overlap","useScrollLock","locked","body","scrollY","previousStyle","useAgentCognition","setIsVisible","setContent","timerRef","pendingContentRef","newContent","updateCognition","AgentCognitionProvider","AgentCognitionContext","ErrorProvider","hideSdk","setHideSdk","createPublishApiError","contextValue","ErrorContext","CHAT_DESKTOP_VIEWPORT_INSET_PX","InternalChat","INTERNAL_ONLY_CHAT_INTERFACE_ONLY","INTERNAL_ONLY_SHOW_CLEAN_CHAT_BUTTON","INTERNAL_ONLY_BLOCK_STYLE","INTERNAL_ONLY_FEATURE_MESSAGE_CLICK","INTERNAL_ONLY_FEATURE_CLEAR_CHAT_CLICK","INTERNAL_ONLY_SHOW_COPY_BUTTON","INTERNAL_ONLY_ENVIRONMENT","INTERNAL_ONLY_API_URL","keyboardInset","isBooting","renderContent","wrapperCSS","Fragment","mainCSS","SkeletonChatInterface","ChatInterface","ThemeProvider","Chat","renderChat","Component","root","ReactDOMClient"],"mappings":";;;;;;;;;;;AACA,IAAI,OAAO,SAAW,KAAa;AAIjC,QAAMA,IAAmC;AAMzC,SAAO,qBAAe,EAAE,KAAK,CAAC,EAAE,MAAAC,QAAW;AACzC,IAAAA,EAAK;AAAA,MACH,KAAK;AAAA,MACL,aAAAD;AAAA,MACA,gBAAgB;AAAA,MAChB,OAAO;AAAA,MACP,SAAS;AAAA,MACT,WAAWE,GAAO;AAChB,cAAMC,wBAAuB,IAAI;AAAA,UAC/B;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QAAA,CACD,GACKC,IAAUF,EAAM,SAAS;AAG/B,YAAIE;AACF,qBAAWC,KAAO,OAAO,KAAKD,CAAO;AACnC,YAAID,EAAiB,IAAIE,EAAI,YAAA,CAAa,MACxCD,EAAQC,CAAG,IAAI;AAIrB,eAAIH,EAAM,YACRA,EAAM,QAAQ,OAAO,eAEhBA;AAAA,MACT;AAAA,IAAA,CACD;AAAA,EACH,CAAC;AACH;;ACpCO,SAASI,GAAW;AAAA,EACzB,cAAAC;AAAA,EACA,YAAAC,IAAa;AACf,GAKG;AACD,QAAMC,IAAmBD,IAAa,SAAS,QACzCE,IAAiBF,IAAa,YAAY;AAEhD,SACE,gBAAAG,EAAC,OAAA,EAAI,WAAU,+GACb,UAAA,gBAAAA;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,WAAWC;AAAA,QACT;AAAA;AAAA,QAEAJ,IACI,oCACA;AAAA,MAAA;AAAA,MAEN,SAASD;AAAA,MAET,UAAA,gBAAAI,EAAC,OAAA,EAAI,WAAU,0FACb,UAAA,gBAAAA,EAACE,MAAK,SAASJ,GAAkB,SAASC,EAAA,CAAgB,EAA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