@eloquentai/chat-sdk 0.33.7-dev → 0.33.9-dev

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;"}
1
+ {"version":3,"file":"index.mjs","sources":["../src/instrumentation.ts","../src/components/chat-bubble.tsx","../src/components/iframe.tsx","../src/components/portal.tsx","../src/components/chat/proactive-message.tsx","../src/components/chat/interface-props.hook.ts","../src/lib/http.ts","../src/lib/url-params.ts","../src/components/chat/persistence.hook.ts","../node_modules/@aws-amplify/core/dist/esm/constants.mjs","../node_modules/@aws-amplify/core/dist/esm/Logger/types.mjs","../node_modules/@aws-amplify/core/dist/esm/Logger/ConsoleLogger.mjs","../node_modules/@aws-amplify/core/dist/esm/errors/AmplifyError.mjs","../node_modules/@aws-amplify/core/dist/esm/Hub/index.mjs","../node_modules/@aws-amplify/core/dist/esm/utils/globalHelpers/index.mjs","../node_modules/@aws-amplify/core/dist/esm/utils/retry/isNonRetryableError.mjs","../node_modules/@aws-amplify/core/dist/esm/utils/retry/retry.mjs","../node_modules/@aws-amplify/core/dist/esm/utils/deepFreeze.mjs","../node_modules/@aws-amplify/core/dist/esm/parseAWSExports.mjs","../node_modules/@aws-amplify/core/dist/esm/singleton/constants.mjs","../node_modules/uuid/dist/esm-browser/stringify.js","../node_modules/uuid/dist/esm-browser/rng.js","../node_modules/uuid/dist/esm-browser/native.js","../node_modules/uuid/dist/esm-browser/v4.js","../node_modules/@aws-amplify/core/dist/esm/parseAmplifyOutputs.mjs","../node_modules/@aws-amplify/core/dist/esm/utils/parseAmplifyConfig.mjs","../node_modules/@aws-crypto/sha256-js/build/module/constants.js","../node_modules/@aws-crypto/sha256-js/build/module/RawSha256.js","../node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js","../node_modules/@aws-crypto/util/build/module/convertToBuffer.js","../node_modules/@aws-crypto/util/build/module/isEmptyData.js","../node_modules/@aws-crypto/sha256-js/build/module/jsSha256.js","../node_modules/@smithy/util-hex-encoding/dist-es/index.js","../node_modules/@aws-amplify/core/dist/esm/Platform/types.mjs","../node_modules/@aws-amplify/core/dist/esm/Platform/version.mjs","../node_modules/@aws-amplify/core/dist/esm/Platform/detection/helpers.mjs","../node_modules/@aws-amplify/core/dist/esm/Platform/detection/React.mjs","../node_modules/@aws-amplify/core/dist/esm/Platform/detection/Vue.mjs","../node_modules/@aws-amplify/core/dist/esm/Platform/detection/Svelte.mjs","../node_modules/@aws-amplify/core/dist/esm/Platform/detection/Next.mjs","../node_modules/@aws-amplify/core/dist/esm/Platform/detection/Nuxt.mjs","../node_modules/@aws-amplify/core/dist/esm/Platform/detection/Angular.mjs","../node_modules/@aws-amplify/core/dist/esm/Platform/detection/ReactNative.mjs","../node_modules/@aws-amplify/core/dist/esm/Platform/detection/Expo.mjs","../node_modules/@aws-amplify/core/dist/esm/Platform/detection/Web.mjs","../node_modules/@aws-amplify/core/dist/esm/Platform/detection/index.mjs","../node_modules/@aws-amplify/core/dist/esm/Platform/detectFramework.mjs","../node_modules/@aws-amplify/core/dist/esm/Platform/customUserAgent.mjs","../node_modules/@aws-amplify/core/dist/esm/Platform/index.mjs","../node_modules/rxjs/dist/esm5/internal/util/isFunction.js","../node_modules/rxjs/dist/esm5/internal/util/createErrorClass.js","../node_modules/rxjs/dist/esm5/internal/util/UnsubscriptionError.js","../node_modules/rxjs/dist/esm5/internal/util/arrRemove.js","../node_modules/rxjs/dist/esm5/internal/Subscription.js","../node_modules/rxjs/dist/esm5/internal/config.js","../node_modules/rxjs/dist/esm5/internal/scheduler/timeoutProvider.js","../node_modules/rxjs/dist/esm5/internal/util/reportUnhandledError.js","../node_modules/rxjs/dist/esm5/internal/util/noop.js","../node_modules/rxjs/dist/esm5/internal/util/errorContext.js","../node_modules/rxjs/dist/esm5/internal/Subscriber.js","../node_modules/rxjs/dist/esm5/internal/symbol/observable.js","../node_modules/rxjs/dist/esm5/internal/util/identity.js","../node_modules/rxjs/dist/esm5/internal/util/pipe.js","../node_modules/rxjs/dist/esm5/internal/Observable.js","../node_modules/rxjs/dist/esm5/internal/util/lift.js","../node_modules/rxjs/dist/esm5/internal/operators/OperatorSubscriber.js","../node_modules/rxjs/dist/esm5/internal/util/isArrayLike.js","../node_modules/rxjs/dist/esm5/internal/util/isPromise.js","../node_modules/rxjs/dist/esm5/internal/util/isInteropObservable.js","../node_modules/rxjs/dist/esm5/internal/util/isAsyncIterable.js","../node_modules/rxjs/dist/esm5/internal/util/throwUnobservableError.js","../node_modules/rxjs/dist/esm5/internal/symbol/iterator.js","../node_modules/rxjs/dist/esm5/internal/util/isIterable.js","../node_modules/rxjs/dist/esm5/internal/util/isReadableStreamLike.js","../node_modules/rxjs/dist/esm5/internal/observable/innerFrom.js","../node_modules/rxjs/dist/esm5/internal/util/executeSchedule.js","../node_modules/rxjs/dist/esm5/internal/operators/observeOn.js","../node_modules/rxjs/dist/esm5/internal/operators/subscribeOn.js","../node_modules/rxjs/dist/esm5/internal/scheduled/scheduleObservable.js","../node_modules/rxjs/dist/esm5/internal/scheduled/schedulePromise.js","../node_modules/rxjs/dist/esm5/internal/scheduled/scheduleArray.js","../node_modules/rxjs/dist/esm5/internal/scheduled/scheduleIterable.js","../node_modules/rxjs/dist/esm5/internal/scheduled/scheduleAsyncIterable.js","../node_modules/rxjs/dist/esm5/internal/scheduled/scheduleReadableStreamLike.js","../node_modules/rxjs/dist/esm5/internal/scheduled/scheduled.js","../node_modules/rxjs/dist/esm5/internal/observable/from.js","../node_modules/rxjs/dist/esm5/internal/operators/map.js","../node_modules/rxjs/dist/esm5/internal/operators/filter.js","../node_modules/@aws-amplify/core/dist/esm/utils/isWebWorker.mjs","../node_modules/@aws-amplify/core/dist/esm/Reachability/Reachability.mjs","../node_modules/@aws-amplify/core/dist/esm/singleton/Auth/index.mjs","../node_modules/@aws-amplify/core/dist/esm/singleton/Amplify.mjs","../node_modules/@aws-amplify/core/dist/esm/singleton/apis/internal/fetchAuthSession.mjs","../node_modules/@aws-amplify/core/dist/esm/singleton/apis/fetchAuthSession.mjs","../node_modules/@aws-amplify/core/dist/esm/utils/retry/constants.mjs","../node_modules/@aws-amplify/core/dist/esm/utils/retry/jitteredBackoff.mjs","../node_modules/@aws-amplify/core/dist/esm/utils/amplifyUuid/index.mjs","../node_modules/@aws-amplify/core/dist/esm/utils/amplifyUrl/index.mjs","../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getSignedHeaders.mjs","../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/constants.mjs","../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getCredentialScope.mjs","../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getFormattedDates.mjs","../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getSigningValues.mjs","../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/dataHashHelpers.mjs","../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getCanonicalHeaders.mjs","../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getCanonicalQueryString.mjs","../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getCanonicalUri.mjs","../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getHashedPayload.mjs","../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getCanonicalRequest.mjs","../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getSigningKey.mjs","../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getStringToSign.mjs","../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getSignature.mjs","../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/signRequest.mjs","../node_modules/graphql/jsutils/isObjectLike.mjs","../node_modules/graphql/polyfills/symbols.mjs","../node_modules/graphql/language/location.mjs","../node_modules/graphql/language/printLocation.mjs","../node_modules/graphql/error/GraphQLError.mjs","../node_modules/@aws-amplify/core/dist/esm/utils/retry/NonRetryableError.mjs","../node_modules/@aws-amplify/core/dist/esm/utils/retry/jitteredExponentialRetry.mjs","../node_modules/@aws-amplify/core/dist/esm/utils/convert/base64/bytesToString.mjs","../node_modules/@aws-amplify/core/dist/esm/utils/convert/base64/base64Encoder.mjs","../node_modules/@aws-amplify/api-graphql/dist/esm/Providers/constants.mjs","../node_modules/@aws-amplify/api-graphql/dist/esm/types/PubSub.mjs","../node_modules/@aws-amplify/api-graphql/dist/esm/utils/ReachabilityMonitor/index.mjs","../node_modules/@aws-amplify/api-graphql/dist/esm/utils/ConnectionStateMonitor.mjs","../node_modules/@aws-amplify/api-graphql/dist/esm/utils/ReconnectionMonitor.mjs","../node_modules/@aws-amplify/api-graphql/dist/esm/Providers/AWSWebSocketProvider/appsyncUrl.mjs","../node_modules/@aws-amplify/api-graphql/dist/esm/Providers/AWSWebSocketProvider/authHeaders.mjs","../node_modules/@aws-amplify/api-graphql/dist/esm/Providers/AWSWebSocketProvider/index.mjs","../node_modules/@aws-amplify/api-graphql/dist/esm/internals/events/utils.mjs","../node_modules/@aws-amplify/api-graphql/dist/esm/Providers/AWSAppSyncEventsProvider/index.mjs","../node_modules/@aws-amplify/api-graphql/dist/esm/internals/events/index.mjs","../node_modules/zod/v4/core/core.js","../node_modules/zod/v4/core/util.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/checks.js","../node_modules/zod/v4/core/doc.js","../node_modules/zod/v4/core/versions.js","../node_modules/zod/v4/core/schemas.js","../node_modules/zod/v4/core/registries.js","../node_modules/zod/v4/core/api.js","../node_modules/zod/v4/core/to-json-schema.js","../node_modules/zod/v4/core/json-schema-processors.js","../node_modules/zod/v4/classic/iso.js","../node_modules/zod/v4/classic/errors.js","../node_modules/zod/v4/classic/parse.js","../node_modules/zod/v4/classic/schemas.js","../src/components/chat/validations.ts","../src/components/chat/realtime-socket.hook.ts","../src/components/chat/message-events.hook.ts","../src/lib/eloquent-ai-api-client.ts","../src/lib/retry.ts","../src/hooks/useFetch.ts","../src/components/chat/user-identity.hook.ts","../src/components/chat/sdk-initialization.hook.ts","../src/components/chat/ui-initialization.hook.ts","../src/components/chat/chat.hook.ts","../src/components/chat/keyboard-inset.hook.ts","../src/components/chat/scroll-lock.hook.ts","../src/hooks/use-agent-cognition.ts","../src/contexts/agent-cognition.context.tsx","../src/contexts/error-handling.context.tsx","../src/components/chat/index.tsx","../src/components/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\n import(\"@sentry/react\").then((Sentry) => {\n Sentry.init({\n dsn: import.meta.env.VITE_SENTRY_DSN,\n environment,\n sendDefaultPii: false,\n integrations: [Sentry.replayIntegration()],\n tracesSampleRate: 1,\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0,\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 const hideTimer = setTimeout(() => {\n setAnimationState(\"exiting\");\n // Start exit animation\n setTimeout(() => {\n onDismiss();\n }, 300);\n }, autoHideDelay);\n\n return () => {\n clearTimeout(enterTimer);\n clearTimeout(hideTimer);\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","\"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","// 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 \"@/type\";\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","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Logging constants\nconst AWS_CLOUDWATCH_CATEGORY = 'Logging';\nconst USER_AGENT_HEADER = 'x-amz-user-agent';\n// Error exception code constants\nconst NO_HUBCALLBACK_PROVIDED_EXCEPTION = 'NoHubcallbackProvidedException';\n\nexport { AWS_CLOUDWATCH_CATEGORY, NO_HUBCALLBACK_PROVIDED_EXCEPTION, USER_AGENT_HEADER };\n//# sourceMappingURL=constants.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nvar LogType;\n(function (LogType) {\n LogType[\"DEBUG\"] = \"DEBUG\";\n LogType[\"ERROR\"] = \"ERROR\";\n LogType[\"INFO\"] = \"INFO\";\n LogType[\"WARN\"] = \"WARN\";\n LogType[\"VERBOSE\"] = \"VERBOSE\";\n LogType[\"NONE\"] = \"NONE\";\n})(LogType || (LogType = {}));\n\nexport { LogType };\n//# sourceMappingURL=types.mjs.map\n","import { AWS_CLOUDWATCH_CATEGORY } from '../constants.mjs';\nimport { LogType } from './types.mjs';\n\n/* eslint-disable no-console */\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst LOG_LEVELS = {\n VERBOSE: 1,\n DEBUG: 2,\n INFO: 3,\n WARN: 4,\n ERROR: 5,\n NONE: 6,\n};\n/**\n * Write logs\n * @class Logger\n */\nclass ConsoleLogger {\n /**\n * @constructor\n * @param {string} name - Name of the logger\n */\n constructor(name, level = LogType.WARN) {\n this.name = name;\n this.level = level;\n this._pluggables = [];\n }\n _padding(n) {\n return n < 10 ? '0' + n : '' + n;\n }\n _ts() {\n const dt = new Date();\n return ([this._padding(dt.getMinutes()), this._padding(dt.getSeconds())].join(':') +\n '.' +\n dt.getMilliseconds());\n }\n configure(config) {\n if (!config)\n return this._config;\n this._config = config;\n return this._config;\n }\n /**\n * Write log\n * @method\n * @memeberof Logger\n * @param {LogType|string} type - log type, default INFO\n * @param {string|object} msg - Logging message or object\n */\n _log(type, ...msg) {\n let loggerLevelName = this.level;\n if (ConsoleLogger.LOG_LEVEL) {\n loggerLevelName = ConsoleLogger.LOG_LEVEL;\n }\n if (typeof window !== 'undefined' && window.LOG_LEVEL) {\n loggerLevelName = window.LOG_LEVEL;\n }\n const loggerLevel = LOG_LEVELS[loggerLevelName];\n const typeLevel = LOG_LEVELS[type];\n if (!(typeLevel >= loggerLevel)) {\n // Do nothing if type is not greater than or equal to logger level (handle undefined)\n return;\n }\n let log = console.log.bind(console);\n if (type === LogType.ERROR && console.error) {\n log = console.error.bind(console);\n }\n if (type === LogType.WARN && console.warn) {\n log = console.warn.bind(console);\n }\n if (ConsoleLogger.BIND_ALL_LOG_LEVELS) {\n if (type === LogType.INFO && console.info) {\n log = console.info.bind(console);\n }\n if (type === LogType.DEBUG && console.debug) {\n log = console.debug.bind(console);\n }\n }\n const prefix = `[${type}] ${this._ts()} ${this.name}`;\n let message = '';\n if (msg.length === 1 && typeof msg[0] === 'string') {\n message = `${prefix} - ${msg[0]}`;\n log(message);\n }\n else if (msg.length === 1) {\n message = `${prefix} ${msg[0]}`;\n log(prefix, msg[0]);\n }\n else if (typeof msg[0] === 'string') {\n let obj = msg.slice(1);\n if (obj.length === 1) {\n obj = obj[0];\n }\n message = `${prefix} - ${msg[0]} ${obj}`;\n log(`${prefix} - ${msg[0]}`, obj);\n }\n else {\n message = `${prefix} ${msg}`;\n log(prefix, msg);\n }\n for (const plugin of this._pluggables) {\n const logEvent = { message, timestamp: Date.now() };\n plugin.pushLogs([logEvent]);\n }\n }\n /**\n * Write General log. Default to INFO\n * @method\n * @memeberof Logger\n * @param {string|object} msg - Logging message or object\n */\n log(...msg) {\n this._log(LogType.INFO, ...msg);\n }\n /**\n * Write INFO log\n * @method\n * @memeberof Logger\n * @param {string|object} msg - Logging message or object\n */\n info(...msg) {\n this._log(LogType.INFO, ...msg);\n }\n /**\n * Write WARN log\n * @method\n * @memeberof Logger\n * @param {string|object} msg - Logging message or object\n */\n warn(...msg) {\n this._log(LogType.WARN, ...msg);\n }\n /**\n * Write ERROR log\n * @method\n * @memeberof Logger\n * @param {string|object} msg - Logging message or object\n */\n error(...msg) {\n this._log(LogType.ERROR, ...msg);\n }\n /**\n * Write DEBUG log\n * @method\n * @memeberof Logger\n * @param {string|object} msg - Logging message or object\n */\n debug(...msg) {\n this._log(LogType.DEBUG, ...msg);\n }\n /**\n * Write VERBOSE log\n * @method\n * @memeberof Logger\n * @param {string|object} msg - Logging message or object\n */\n verbose(...msg) {\n this._log(LogType.VERBOSE, ...msg);\n }\n addPluggable(pluggable) {\n if (pluggable && pluggable.getCategoryName() === AWS_CLOUDWATCH_CATEGORY) {\n this._pluggables.push(pluggable);\n pluggable.configure(this._config);\n }\n }\n listPluggables() {\n return this._pluggables;\n }\n}\nConsoleLogger.LOG_LEVEL = null;\nConsoleLogger.BIND_ALL_LOG_LEVELS = false;\n\nexport { ConsoleLogger };\n//# sourceMappingURL=ConsoleLogger.mjs.map\n","class AmplifyError extends Error {\n /**\n * Constructs an AmplifyError.\n *\n * @param message text that describes the main problem.\n * @param underlyingError the underlying cause of the error.\n * @param recoverySuggestion suggestion to recover from the error.\n *\n */\n constructor({ message, name, recoverySuggestion, underlyingError, metadata, }) {\n super(message);\n this.name = name;\n this.underlyingError = underlyingError;\n this.recoverySuggestion = recoverySuggestion;\n if (metadata) {\n // If metadata exists, explicitly only record the following properties.\n const { extendedRequestId, httpStatusCode, requestId } = metadata;\n this.metadata = { extendedRequestId, httpStatusCode, requestId };\n }\n // Hack for making the custom error class work when transpiled to es5\n // TODO: Delete the following 2 lines after we change the build target to >= es2015\n this.constructor = AmplifyError;\n Object.setPrototypeOf(this, AmplifyError.prototype);\n }\n}\n\nexport { AmplifyError };\n//# sourceMappingURL=AmplifyError.mjs.map\n","import { ConsoleLogger } from '../Logger/ConsoleLogger.mjs';\nimport { NO_HUBCALLBACK_PROVIDED_EXCEPTION } from '../constants.mjs';\nimport { AmplifyError } from '../errors/AmplifyError.mjs';\nimport '../types/errors.mjs';\nimport '../errors/errorHelpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst AMPLIFY_SYMBOL = (typeof Symbol !== 'undefined'\n ? Symbol('amplify_default')\n : '@@amplify_default');\nconst logger = new ConsoleLogger('Hub');\nclass HubClass {\n constructor(name) {\n this.listeners = new Map();\n this.protectedChannels = [\n 'core',\n 'auth',\n 'api',\n 'analytics',\n 'interactions',\n 'pubsub',\n 'storage',\n 'ui',\n 'xr',\n ];\n this.name = name;\n }\n /**\n * Used internally to remove a Hub listener.\n *\n * @remarks\n * This private method is for internal use only. Instead of calling Hub.remove, call the result of Hub.listen.\n */\n _remove(channel, listener) {\n const holder = this.listeners.get(channel);\n if (!holder) {\n logger.warn(`No listeners for ${channel}`);\n return;\n }\n this.listeners.set(channel, [\n ...holder.filter(({ callback }) => callback !== listener),\n ]);\n }\n dispatch(channel, payload, source, ampSymbol) {\n if (typeof channel === 'string' &&\n this.protectedChannels.indexOf(channel) > -1) {\n const hasAccess = ampSymbol === AMPLIFY_SYMBOL;\n if (!hasAccess) {\n logger.warn(`WARNING: ${channel} is protected and dispatching on it can have unintended consequences`);\n }\n }\n const capsule = {\n channel,\n payload: { ...payload },\n source,\n patternInfo: [],\n };\n try {\n this._toListeners(capsule);\n }\n catch (e) {\n logger.error(e);\n }\n }\n listen(channel, callback, listenerName = 'noname') {\n let cb;\n if (typeof callback !== 'function') {\n throw new AmplifyError({\n name: NO_HUBCALLBACK_PROVIDED_EXCEPTION,\n message: 'No callback supplied to Hub',\n });\n }\n else {\n // Needs to be casted as a more generic type\n cb = callback;\n }\n let holder = this.listeners.get(channel);\n if (!holder) {\n holder = [];\n this.listeners.set(channel, holder);\n }\n holder.push({\n name: listenerName,\n callback: cb,\n });\n return () => {\n this._remove(channel, cb);\n };\n }\n _toListeners(capsule) {\n const { channel, payload } = capsule;\n const holder = this.listeners.get(channel);\n if (holder) {\n holder.forEach(listener => {\n logger.debug(`Dispatching to ${channel} with `, payload);\n try {\n listener.callback(capsule);\n }\n catch (e) {\n logger.error(e);\n }\n });\n }\n }\n}\n/* We export a __default__ instance of HubClass to use it as a\npseudo Singleton for the main messaging bus, however you can still create\nyour own instance of HubClass() for a separate \"private bus\" of events. */\nconst Hub = new HubClass('__default__');\n/**\n * @internal\n *\n * Internal hub used for core Amplify functionality. Not intended for use outside of Amplify.\n *\n */\nconst HubInternal = new HubClass('internal-hub');\n\nexport { AMPLIFY_SYMBOL, Hub, HubClass, HubInternal };\n//# sourceMappingURL=index.mjs.map\n","import { AmplifyError } from '../../errors/AmplifyError.mjs';\nimport '../../types/errors.mjs';\nimport '../../errors/errorHelpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst getCrypto = () => {\n if (typeof window === 'object' && typeof window.crypto === 'object') {\n return window.crypto;\n }\n // Next.js global polyfill\n if (typeof crypto === 'object') {\n return crypto;\n }\n throw new AmplifyError({\n name: 'MissingPolyfill',\n message: 'Cannot resolve the `crypto` function from the environment.',\n });\n};\nconst getBtoa = () => {\n // browser\n if (typeof window !== 'undefined' && typeof window.btoa === 'function') {\n return window.btoa;\n }\n // Next.js global polyfill\n if (typeof btoa === 'function') {\n return btoa;\n }\n throw new AmplifyError({\n name: 'Base64EncoderError',\n message: 'Cannot resolve the `btoa` function from the environment.',\n });\n};\nconst getAtob = () => {\n // browser\n if (typeof window !== 'undefined' && typeof window.atob === 'function') {\n return window.atob;\n }\n // Next.js global polyfill\n if (typeof atob === 'function') {\n return atob;\n }\n throw new AmplifyError({\n name: 'Base64EncoderError',\n message: 'Cannot resolve the `atob` function from the environment.',\n });\n};\n\nexport { getAtob, getBtoa, getCrypto };\n//# sourceMappingURL=index.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst isNonRetryableError = (obj) => {\n const key = 'nonRetryable';\n return obj && obj[key];\n};\n\nexport { isNonRetryableError };\n//# sourceMappingURL=isNonRetryableError.mjs.map\n","import { ConsoleLogger } from '../../Logger/ConsoleLogger.mjs';\nimport { isNonRetryableError } from './isNonRetryableError.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst logger = new ConsoleLogger('retryUtil');\n/**\n * @private\n * Internal use of Amplify only\n */\nasync function retry(functionToRetry, args, delayFn, onTerminate) {\n if (typeof functionToRetry !== 'function') {\n throw Error('functionToRetry must be a function');\n }\n // TODO(eslint): remove this linter suppression with refactoring.\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n let attempt = 0;\n let terminated = false;\n let timeout;\n let wakeUp = () => {\n // no-op\n }; // will be replaced with a resolver()\n // used after the loop if terminated while waiting for a timer.\n let lastError;\n onTerminate &&\n onTerminate.then(() => {\n // signal not to try anymore.\n terminated = true;\n // stop sleeping if we're sleeping.\n clearTimeout(timeout);\n wakeUp();\n });\n // TODO(eslint): remove this linter suppression with refactoring.\n // eslint-disable-next-line no-unmodified-loop-condition\n while (!terminated) {\n attempt++;\n logger.debug(`${functionToRetry.name} attempt #${attempt} with this vars: ${JSON.stringify(args)}`);\n try {\n resolve(await functionToRetry(...args));\n return;\n }\n catch (err) {\n lastError = err;\n logger.debug(`error on ${functionToRetry.name}`, err);\n if (isNonRetryableError(err)) {\n logger.debug(`${functionToRetry.name} non retryable error`, err);\n reject(err);\n return;\n }\n const retryIn = delayFn(attempt, args, err);\n logger.debug(`${functionToRetry.name} retrying in ${retryIn} ms`);\n // we check `terminated` again here because it could have flipped\n // in the time it took `functionToRetry` to return.\n if (retryIn === false || terminated) {\n reject(err);\n return;\n }\n else {\n await new Promise(_resolve => {\n wakeUp = _resolve; // export wakeUp for onTerminate handling\n timeout = setTimeout(wakeUp, retryIn);\n });\n }\n }\n }\n // reached if terminated while waiting for a timer.\n reject(lastError);\n });\n}\n\nexport { retry };\n//# sourceMappingURL=retry.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst deepFreeze = (object) => {\n const propNames = Reflect.ownKeys(object);\n for (const name of propNames) {\n const value = object[name];\n if ((value && typeof value === 'object') || typeof value === 'function') {\n deepFreeze(value);\n }\n }\n return Object.freeze(object);\n};\n\nexport { deepFreeze };\n//# sourceMappingURL=deepFreeze.mjs.map\n","import { ConsoleLogger } from './Logger/ConsoleLogger.mjs';\nimport { AmplifyError } from './errors/AmplifyError.mjs';\nimport './types/errors.mjs';\nimport './errors/errorHelpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst logger = new ConsoleLogger('parseAWSExports');\nconst authTypeMapping = {\n API_KEY: 'apiKey',\n AWS_IAM: 'iam',\n AMAZON_COGNITO_USER_POOLS: 'userPool',\n OPENID_CONNECT: 'oidc',\n NONE: 'none',\n AWS_LAMBDA: 'lambda',\n // `LAMBDA` is an incorrect value that was added during the v6 rewrite.\n // Keeping it as a valid value until v7 to prevent breaking customers who might\n // be relying on it as a workaround.\n // ref: https://github.com/aws-amplify/amplify-js/pull/12922\n // TODO: @v7 remove next line\n LAMBDA: 'lambda',\n};\n/**\n * Converts the object imported from `aws-exports.js` or `amplifyconfiguration.json` files generated by\n * the Amplify CLI into an object that conforms to the {@link ResourcesConfig}.\n *\n * @param config A configuration object imported from `aws-exports.js` or `amplifyconfiguration.json`.\n *\n * @returns An object that conforms to the {@link ResourcesConfig} .\n */\nconst parseAWSExports = (config = {}) => {\n if (!Object.prototype.hasOwnProperty.call(config, 'aws_project_region')) {\n throw new AmplifyError({\n name: 'InvalidParameterException',\n message: 'Invalid config parameter.',\n recoverySuggestion: 'Ensure passing the config object imported from `amplifyconfiguration.json`.',\n });\n }\n const { aws_appsync_apiKey, aws_appsync_authenticationType, aws_appsync_graphqlEndpoint, aws_appsync_region, aws_bots_config, aws_cognito_identity_pool_id, aws_cognito_sign_up_verification_method, aws_cognito_mfa_configuration, aws_cognito_mfa_types, aws_cognito_password_protection_settings, aws_cognito_verification_mechanisms, aws_cognito_signup_attributes, aws_cognito_social_providers, aws_cognito_username_attributes, aws_mandatory_sign_in, aws_mobile_analytics_app_id, aws_mobile_analytics_app_region, aws_user_files_s3_bucket, aws_user_files_s3_bucket_region, aws_user_files_s3_dangerously_connect_to_http_endpoint_for_testing, aws_user_pools_id, aws_user_pools_web_client_id, geo, oauth, predictions, aws_cloud_logic_custom, Notifications, modelIntrospection, } = config;\n const amplifyConfig = {};\n // Analytics\n if (aws_mobile_analytics_app_id) {\n amplifyConfig.Analytics = {\n Pinpoint: {\n appId: aws_mobile_analytics_app_id,\n region: aws_mobile_analytics_app_region,\n },\n };\n }\n // Notifications\n const { InAppMessaging, Push } = Notifications ?? {};\n if (InAppMessaging?.AWSPinpoint || Push?.AWSPinpoint) {\n if (InAppMessaging?.AWSPinpoint) {\n const { appId, region } = InAppMessaging.AWSPinpoint;\n amplifyConfig.Notifications = {\n InAppMessaging: {\n Pinpoint: {\n appId,\n region,\n },\n },\n };\n }\n if (Push?.AWSPinpoint) {\n const { appId, region } = Push.AWSPinpoint;\n amplifyConfig.Notifications = {\n ...amplifyConfig.Notifications,\n PushNotification: {\n Pinpoint: {\n appId,\n region,\n },\n },\n };\n }\n }\n // Interactions\n if (Array.isArray(aws_bots_config)) {\n amplifyConfig.Interactions = {\n LexV1: Object.fromEntries(aws_bots_config.map(bot => [bot.name, bot])),\n };\n }\n // API\n if (aws_appsync_graphqlEndpoint) {\n const defaultAuthMode = authTypeMapping[aws_appsync_authenticationType];\n if (!defaultAuthMode) {\n logger.debug(`Invalid authentication type ${aws_appsync_authenticationType}. Falling back to IAM.`);\n }\n amplifyConfig.API = {\n GraphQL: {\n endpoint: aws_appsync_graphqlEndpoint,\n apiKey: aws_appsync_apiKey,\n region: aws_appsync_region,\n defaultAuthMode: defaultAuthMode ?? 'iam',\n },\n };\n if (modelIntrospection) {\n amplifyConfig.API.GraphQL.modelIntrospection = modelIntrospection;\n }\n }\n // Auth\n const mfaConfig = aws_cognito_mfa_configuration\n ? {\n status: aws_cognito_mfa_configuration &&\n aws_cognito_mfa_configuration.toLowerCase(),\n totpEnabled: aws_cognito_mfa_types?.includes('TOTP') ?? false,\n smsEnabled: aws_cognito_mfa_types?.includes('SMS') ?? false,\n }\n : undefined;\n const passwordFormatConfig = aws_cognito_password_protection_settings\n ? {\n minLength: aws_cognito_password_protection_settings.passwordPolicyMinLength,\n requireLowercase: aws_cognito_password_protection_settings.passwordPolicyCharacters?.includes('REQUIRES_LOWERCASE') ?? false,\n requireUppercase: aws_cognito_password_protection_settings.passwordPolicyCharacters?.includes('REQUIRES_UPPERCASE') ?? false,\n requireNumbers: aws_cognito_password_protection_settings.passwordPolicyCharacters?.includes('REQUIRES_NUMBERS') ?? false,\n requireSpecialCharacters: aws_cognito_password_protection_settings.passwordPolicyCharacters?.includes('REQUIRES_SYMBOLS') ?? false,\n }\n : undefined;\n const mergedUserAttributes = Array.from(new Set([\n ...(aws_cognito_verification_mechanisms ?? []),\n ...(aws_cognito_signup_attributes ?? []),\n ]));\n const userAttributes = mergedUserAttributes.reduce((attributes, key) => ({\n ...attributes,\n // All user attributes generated by the CLI are required\n [key.toLowerCase()]: { required: true },\n }), {});\n const loginWithEmailEnabled = aws_cognito_username_attributes?.includes('EMAIL') ?? false;\n const loginWithPhoneEnabled = aws_cognito_username_attributes?.includes('PHONE_NUMBER') ?? false;\n if (aws_cognito_identity_pool_id || aws_user_pools_id) {\n amplifyConfig.Auth = {\n Cognito: {\n identityPoolId: aws_cognito_identity_pool_id,\n allowGuestAccess: aws_mandatory_sign_in !== 'enable',\n signUpVerificationMethod: aws_cognito_sign_up_verification_method,\n userAttributes,\n userPoolClientId: aws_user_pools_web_client_id,\n userPoolId: aws_user_pools_id,\n mfa: mfaConfig,\n passwordFormat: passwordFormatConfig,\n loginWith: {\n username: !(loginWithEmailEnabled || loginWithPhoneEnabled),\n email: loginWithEmailEnabled,\n phone: loginWithPhoneEnabled,\n },\n },\n };\n }\n const hasOAuthConfig = oauth ? Object.keys(oauth).length > 0 : false;\n const hasSocialProviderConfig = aws_cognito_social_providers\n ? aws_cognito_social_providers.length > 0\n : false;\n if (amplifyConfig.Auth && hasOAuthConfig) {\n amplifyConfig.Auth.Cognito.loginWith = {\n ...amplifyConfig.Auth.Cognito.loginWith,\n oauth: {\n ...getOAuthConfig(oauth),\n ...(hasSocialProviderConfig && {\n providers: parseSocialProviders(aws_cognito_social_providers),\n }),\n },\n };\n }\n // Storage\n if (aws_user_files_s3_bucket) {\n amplifyConfig.Storage = {\n S3: {\n bucket: aws_user_files_s3_bucket,\n region: aws_user_files_s3_bucket_region,\n dangerouslyConnectToHttpEndpointForTesting: aws_user_files_s3_dangerously_connect_to_http_endpoint_for_testing,\n },\n };\n }\n // Geo\n if (geo) {\n const { amazon_location_service } = geo;\n amplifyConfig.Geo = {\n LocationService: {\n maps: amazon_location_service.maps,\n geofenceCollections: amazon_location_service.geofenceCollections,\n searchIndices: amazon_location_service.search_indices,\n region: amazon_location_service.region,\n },\n };\n }\n // REST API\n if (aws_cloud_logic_custom) {\n amplifyConfig.API = {\n ...amplifyConfig.API,\n REST: aws_cloud_logic_custom.reduce((acc, api) => {\n const { name, endpoint, region, service } = api;\n return {\n ...acc,\n [name]: {\n endpoint,\n ...(service ? { service } : undefined),\n ...(region ? { region } : undefined),\n },\n };\n }, {}),\n };\n }\n // Predictions\n if (predictions) {\n // map VoiceId from speechGenerator defaults to voiceId\n const { VoiceId: voiceId } = predictions?.convert?.speechGenerator?.defaults ?? {};\n amplifyConfig.Predictions = voiceId\n ? {\n ...predictions,\n convert: {\n ...predictions.convert,\n speechGenerator: {\n ...predictions.convert.speechGenerator,\n defaults: { voiceId },\n },\n },\n }\n : predictions;\n }\n return amplifyConfig;\n};\nconst getRedirectUrl = (redirectStr) => redirectStr?.split(',') ?? [];\nconst getOAuthConfig = ({ domain, scope, redirectSignIn, redirectSignOut, responseType, }) => ({\n domain,\n scopes: scope,\n redirectSignIn: getRedirectUrl(redirectSignIn),\n redirectSignOut: getRedirectUrl(redirectSignOut),\n responseType,\n});\nconst parseSocialProviders = (aws_cognito_social_providers) => {\n return aws_cognito_social_providers.map((provider) => {\n const updatedProvider = provider.toLowerCase();\n return updatedProvider.charAt(0).toUpperCase() + updatedProvider.slice(1);\n });\n};\n\nexport { parseAWSExports };\n//# sourceMappingURL=parseAWSExports.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst ADD_OAUTH_LISTENER = Symbol('oauth-listener');\n\nexport { ADD_OAUTH_LISTENER };\n//# sourceMappingURL=constants.mjs.map\n","import validate from './validate.js';\nconst byteToHex = [];\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nexport function unsafeStringify(arr, offset = 0) {\n return (byteToHex[arr[offset + 0]] +\n byteToHex[arr[offset + 1]] +\n byteToHex[arr[offset + 2]] +\n byteToHex[arr[offset + 3]] +\n '-' +\n byteToHex[arr[offset + 4]] +\n byteToHex[arr[offset + 5]] +\n '-' +\n byteToHex[arr[offset + 6]] +\n byteToHex[arr[offset + 7]] +\n '-' +\n byteToHex[arr[offset + 8]] +\n byteToHex[arr[offset + 9]] +\n '-' +\n byteToHex[arr[offset + 10]] +\n byteToHex[arr[offset + 11]] +\n byteToHex[arr[offset + 12]] +\n byteToHex[arr[offset + 13]] +\n byteToHex[arr[offset + 14]] +\n byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset);\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nexport default stringify;\n","let getRandomValues;\nconst rnds8 = new Uint8Array(16);\nexport default function rng() {\n if (!getRandomValues) {\n if (typeof crypto === 'undefined' || !crypto.getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n getRandomValues = crypto.getRandomValues.bind(crypto);\n }\n return getRandomValues(rnds8);\n}\n","const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);\nexport default { randomUUID };\n","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n options = options || {};\n const rnds = options.random ?? options.rng?.() ?? rng();\n if (rnds.length < 16) {\n throw new Error('Random bytes length must be >= 16');\n }\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n if (buf) {\n offset = offset || 0;\n if (offset < 0 || offset + 16 > buf.length) {\n throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);\n }\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n return buf;\n }\n return unsafeStringify(rnds);\n}\nexport default v4;\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction isAmplifyOutputs(config) {\n // version format initially will be '1' but is expected to be something like x.y where x is major and y minor version\n const { version } = config;\n if (!version) {\n return false;\n }\n return version.startsWith('1');\n}\nfunction parseStorage(amplifyOutputsStorageProperties) {\n if (!amplifyOutputsStorageProperties) {\n return undefined;\n }\n const { bucket_name, aws_region, buckets } = amplifyOutputsStorageProperties;\n return {\n S3: {\n bucket: bucket_name,\n region: aws_region,\n buckets: buckets && createBucketInfoMap(buckets),\n },\n };\n}\nfunction parseAuth(amplifyOutputsAuthProperties) {\n if (!amplifyOutputsAuthProperties) {\n return undefined;\n }\n const { user_pool_id, user_pool_client_id, identity_pool_id, password_policy, mfa_configuration, mfa_methods, unauthenticated_identities_enabled, oauth, username_attributes, standard_required_attributes, groups, passwordless, } = amplifyOutputsAuthProperties;\n const authConfig = {\n Cognito: {\n userPoolId: user_pool_id,\n userPoolClientId: user_pool_client_id,\n groups,\n },\n };\n if (identity_pool_id) {\n authConfig.Cognito = {\n ...authConfig.Cognito,\n identityPoolId: identity_pool_id,\n };\n }\n if (password_policy) {\n authConfig.Cognito.passwordFormat = {\n requireLowercase: password_policy.require_lowercase,\n requireNumbers: password_policy.require_numbers,\n requireUppercase: password_policy.require_uppercase,\n requireSpecialCharacters: password_policy.require_symbols,\n minLength: password_policy.min_length ?? 6,\n };\n }\n if (mfa_configuration) {\n authConfig.Cognito.mfa = {\n status: getMfaStatus(mfa_configuration),\n smsEnabled: mfa_methods?.includes('SMS'),\n totpEnabled: mfa_methods?.includes('TOTP'),\n };\n }\n if (unauthenticated_identities_enabled) {\n authConfig.Cognito.allowGuestAccess = unauthenticated_identities_enabled;\n }\n if (oauth) {\n authConfig.Cognito.loginWith = {\n oauth: {\n domain: oauth.domain,\n redirectSignIn: oauth.redirect_sign_in_uri,\n redirectSignOut: oauth.redirect_sign_out_uri,\n responseType: oauth.response_type === 'token' ? 'token' : 'code',\n scopes: oauth.scopes,\n providers: getOAuthProviders(oauth.identity_providers),\n },\n };\n }\n if (username_attributes) {\n authConfig.Cognito.loginWith = {\n ...authConfig.Cognito.loginWith,\n email: username_attributes.includes('email'),\n phone: username_attributes.includes('phone_number'),\n // Signing in with a username is not currently supported in Gen2, this should always evaluate to false\n username: username_attributes.includes('username'),\n };\n }\n if (standard_required_attributes) {\n authConfig.Cognito.userAttributes = standard_required_attributes.reduce((acc, curr) => ({ ...acc, [curr]: { required: true } }), {});\n }\n if (passwordless) {\n authConfig.Cognito.passwordless = {\n emailOtpEnabled: passwordless.email_otp_enabled,\n smsOtpEnabled: passwordless.sms_otp_enabled,\n webAuthn: passwordless.web_authn\n ? {\n relyingPartyId: passwordless.web_authn.relying_party_id,\n userVerification: passwordless.web_authn.user_verification,\n }\n : undefined,\n preferredChallenge: passwordless.preferred_challenge,\n };\n }\n return authConfig;\n}\nfunction parseAnalytics(amplifyOutputsAnalyticsProperties) {\n if (!amplifyOutputsAnalyticsProperties?.amazon_pinpoint) {\n return undefined;\n }\n const { amazon_pinpoint } = amplifyOutputsAnalyticsProperties;\n return {\n Pinpoint: {\n appId: amazon_pinpoint.app_id,\n region: amazon_pinpoint.aws_region,\n },\n };\n}\nfunction parseGeo(amplifyOutputsAnalyticsProperties) {\n if (!amplifyOutputsAnalyticsProperties) {\n return undefined;\n }\n const { aws_region, geofence_collections, maps, search_indices } = amplifyOutputsAnalyticsProperties;\n return {\n LocationService: {\n region: aws_region,\n searchIndices: search_indices,\n geofenceCollections: geofence_collections,\n maps,\n },\n };\n}\nfunction parseData(amplifyOutputsDataProperties) {\n if (!amplifyOutputsDataProperties) {\n return undefined;\n }\n const { aws_region, default_authorization_type, url, api_key, model_introspection, } = amplifyOutputsDataProperties;\n const GraphQL = {\n endpoint: url,\n defaultAuthMode: getGraphQLAuthMode(default_authorization_type),\n region: aws_region,\n apiKey: api_key,\n modelIntrospection: model_introspection,\n };\n return {\n GraphQL,\n };\n}\nfunction parseCustom(amplifyOutputsCustomProperties) {\n if (!amplifyOutputsCustomProperties?.events) {\n return undefined;\n }\n const { url, aws_region, api_key, default_authorization_type } = amplifyOutputsCustomProperties.events;\n const Events = {\n endpoint: url,\n defaultAuthMode: getGraphQLAuthMode(default_authorization_type),\n region: aws_region,\n apiKey: api_key,\n };\n return {\n Events,\n };\n}\nfunction parseNotifications(amplifyOutputsNotificationsProperties) {\n if (!amplifyOutputsNotificationsProperties) {\n return undefined;\n }\n const { aws_region, channels, amazon_pinpoint_app_id, amazon_connect } = amplifyOutputsNotificationsProperties;\n const supportedChannels = channels ?? [];\n const hasInAppMessaging = supportedChannels.includes('IN_APP_MESSAGING');\n const hasPushNotification = supportedChannels.includes('APNS') || supportedChannels.includes('FCM');\n const hasCustomerProfilesPush = !!amazon_connect;\n if (!(hasInAppMessaging || hasPushNotification || hasCustomerProfilesPush)) {\n return undefined;\n }\n // At this point, we know the Amplify outputs contains at least one supported channel\n const notificationsConfig = {};\n if (hasInAppMessaging && amazon_pinpoint_app_id && aws_region) {\n notificationsConfig.InAppMessaging = {\n Pinpoint: {\n appId: amazon_pinpoint_app_id,\n region: aws_region,\n },\n };\n }\n // Push device registration can be backed by Amazon Pinpoint and/or Amazon\n // Connect Customer Profiles. Each provider is emitted independently when its\n // configuration is present, mirroring how analytics is parsed.\n const pushNotificationConfig = {};\n if (hasPushNotification && amazon_pinpoint_app_id && aws_region) {\n pushNotificationConfig.Pinpoint = {\n appId: amazon_pinpoint_app_id,\n region: aws_region,\n };\n }\n if (amazon_connect) {\n pushNotificationConfig.CustomerProfiles = {\n endpoint: amazon_connect.endpoint,\n region: amazon_connect.aws_region,\n };\n }\n if (Object.keys(pushNotificationConfig).length > 0) {\n notificationsConfig.PushNotification =\n pushNotificationConfig;\n }\n return notificationsConfig;\n}\nfunction parseAmplifyOutputs(amplifyOutputs) {\n const resourcesConfig = {};\n if (amplifyOutputs.storage) {\n resourcesConfig.Storage = parseStorage(amplifyOutputs.storage);\n }\n if (amplifyOutputs.auth) {\n resourcesConfig.Auth = parseAuth(amplifyOutputs.auth);\n }\n if (amplifyOutputs.analytics) {\n resourcesConfig.Analytics = parseAnalytics(amplifyOutputs.analytics);\n }\n if (amplifyOutputs.geo) {\n resourcesConfig.Geo = parseGeo(amplifyOutputs.geo);\n }\n if (amplifyOutputs.data) {\n resourcesConfig.API = parseData(amplifyOutputs.data);\n }\n if (amplifyOutputs.custom) {\n const customConfig = parseCustom(amplifyOutputs.custom);\n if (customConfig && 'Events' in customConfig) {\n resourcesConfig.API = { ...resourcesConfig.API, ...customConfig };\n }\n }\n if (amplifyOutputs.notifications) {\n resourcesConfig.Notifications = parseNotifications(amplifyOutputs.notifications);\n }\n return resourcesConfig;\n}\nconst authModeNames = {\n AMAZON_COGNITO_USER_POOLS: 'userPool',\n API_KEY: 'apiKey',\n AWS_IAM: 'iam',\n AWS_LAMBDA: 'lambda',\n OPENID_CONNECT: 'oidc',\n};\nfunction getGraphQLAuthMode(authType) {\n return authModeNames[authType];\n}\nconst providerNames = {\n GOOGLE: 'Google',\n LOGIN_WITH_AMAZON: 'Amazon',\n FACEBOOK: 'Facebook',\n SIGN_IN_WITH_APPLE: 'Apple',\n};\nfunction getOAuthProviders(providers = []) {\n return providers.reduce((oAuthProviders, provider) => {\n if (providerNames[provider] !== undefined) {\n oAuthProviders.push(providerNames[provider]);\n }\n return oAuthProviders;\n }, []);\n}\nfunction getMfaStatus(mfaConfiguration) {\n if (mfaConfiguration === 'OPTIONAL')\n return 'optional';\n if (mfaConfiguration === 'REQUIRED')\n return 'on';\n return 'off';\n}\nfunction createBucketInfoMap(buckets) {\n const mappedBuckets = {};\n buckets.forEach(({ name, bucket_name: bucketName, aws_region: region, paths }) => {\n if (name in mappedBuckets) {\n throw new Error(`Duplicate friendly name found: ${name}. Name must be unique.`);\n }\n const sanitizedPaths = paths\n ? Object.entries(paths).reduce((acc, [key, value]) => {\n if (value !== undefined) {\n acc[key] = value;\n }\n return acc;\n }, {})\n : undefined;\n mappedBuckets[name] = {\n bucketName,\n region,\n paths: sanitizedPaths,\n };\n });\n return mappedBuckets;\n}\n\nexport { isAmplifyOutputs, parseAmplifyOutputs, parseAnalytics };\n//# sourceMappingURL=parseAmplifyOutputs.mjs.map\n","import { parseAWSExports } from '../parseAWSExports.mjs';\nimport { isAmplifyOutputs, parseAmplifyOutputs } from '../parseAmplifyOutputs.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Parses the variety of configuration shapes that Amplify can accept into a ResourcesConfig.\n *\n * @param amplifyConfig An Amplify configuration object conforming to one of the supported schemas.\n * @return A ResourcesConfig for the provided configuration object.\n */\nconst parseAmplifyConfig = (amplifyConfig) => {\n if (Object.keys(amplifyConfig).some(key => key.startsWith('aws_'))) {\n return parseAWSExports(amplifyConfig);\n }\n else if (isAmplifyOutputs(amplifyConfig)) {\n return parseAmplifyOutputs(amplifyConfig);\n }\n else {\n return amplifyConfig;\n }\n};\n\nexport { parseAmplifyConfig };\n//# sourceMappingURL=parseAmplifyConfig.mjs.map\n","/**\n * @internal\n */\nexport var BLOCK_SIZE = 64;\n/**\n * @internal\n */\nexport var DIGEST_LENGTH = 32;\n/**\n * @internal\n */\nexport var KEY = new Uint32Array([\n 0x428a2f98,\n 0x71374491,\n 0xb5c0fbcf,\n 0xe9b5dba5,\n 0x3956c25b,\n 0x59f111f1,\n 0x923f82a4,\n 0xab1c5ed5,\n 0xd807aa98,\n 0x12835b01,\n 0x243185be,\n 0x550c7dc3,\n 0x72be5d74,\n 0x80deb1fe,\n 0x9bdc06a7,\n 0xc19bf174,\n 0xe49b69c1,\n 0xefbe4786,\n 0x0fc19dc6,\n 0x240ca1cc,\n 0x2de92c6f,\n 0x4a7484aa,\n 0x5cb0a9dc,\n 0x76f988da,\n 0x983e5152,\n 0xa831c66d,\n 0xb00327c8,\n 0xbf597fc7,\n 0xc6e00bf3,\n 0xd5a79147,\n 0x06ca6351,\n 0x14292967,\n 0x27b70a85,\n 0x2e1b2138,\n 0x4d2c6dfc,\n 0x53380d13,\n 0x650a7354,\n 0x766a0abb,\n 0x81c2c92e,\n 0x92722c85,\n 0xa2bfe8a1,\n 0xa81a664b,\n 0xc24b8b70,\n 0xc76c51a3,\n 0xd192e819,\n 0xd6990624,\n 0xf40e3585,\n 0x106aa070,\n 0x19a4c116,\n 0x1e376c08,\n 0x2748774c,\n 0x34b0bcb5,\n 0x391c0cb3,\n 0x4ed8aa4a,\n 0x5b9cca4f,\n 0x682e6ff3,\n 0x748f82ee,\n 0x78a5636f,\n 0x84c87814,\n 0x8cc70208,\n 0x90befffa,\n 0xa4506ceb,\n 0xbef9a3f7,\n 0xc67178f2\n]);\n/**\n * @internal\n */\nexport var INIT = [\n 0x6a09e667,\n 0xbb67ae85,\n 0x3c6ef372,\n 0xa54ff53a,\n 0x510e527f,\n 0x9b05688c,\n 0x1f83d9ab,\n 0x5be0cd19\n];\n/**\n * @internal\n */\nexport var MAX_HASHABLE_LENGTH = Math.pow(2, 53) - 1;\n//# sourceMappingURL=constants.js.map","import { BLOCK_SIZE, DIGEST_LENGTH, INIT, KEY, MAX_HASHABLE_LENGTH } from \"./constants\";\n/**\n * @internal\n */\nvar RawSha256 = /** @class */ (function () {\n function RawSha256() {\n this.state = Int32Array.from(INIT);\n this.temp = new Int32Array(64);\n this.buffer = new Uint8Array(64);\n this.bufferLength = 0;\n this.bytesHashed = 0;\n /**\n * @internal\n */\n this.finished = false;\n }\n RawSha256.prototype.update = function (data) {\n if (this.finished) {\n throw new Error(\"Attempted to update an already finished hash.\");\n }\n var position = 0;\n var byteLength = data.byteLength;\n this.bytesHashed += byteLength;\n if (this.bytesHashed * 8 > MAX_HASHABLE_LENGTH) {\n throw new Error(\"Cannot hash more than 2^53 - 1 bits\");\n }\n while (byteLength > 0) {\n this.buffer[this.bufferLength++] = data[position++];\n byteLength--;\n if (this.bufferLength === BLOCK_SIZE) {\n this.hashBuffer();\n this.bufferLength = 0;\n }\n }\n };\n RawSha256.prototype.digest = function () {\n if (!this.finished) {\n var bitsHashed = this.bytesHashed * 8;\n var bufferView = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);\n var undecoratedLength = this.bufferLength;\n bufferView.setUint8(this.bufferLength++, 0x80);\n // Ensure the final block has enough room for the hashed length\n if (undecoratedLength % BLOCK_SIZE >= BLOCK_SIZE - 8) {\n for (var i = this.bufferLength; i < BLOCK_SIZE; i++) {\n bufferView.setUint8(i, 0);\n }\n this.hashBuffer();\n this.bufferLength = 0;\n }\n for (var i = this.bufferLength; i < BLOCK_SIZE - 8; i++) {\n bufferView.setUint8(i, 0);\n }\n bufferView.setUint32(BLOCK_SIZE - 8, Math.floor(bitsHashed / 0x100000000), true);\n bufferView.setUint32(BLOCK_SIZE - 4, bitsHashed);\n this.hashBuffer();\n this.finished = true;\n }\n // The value in state is little-endian rather than big-endian, so flip\n // each word into a new Uint8Array\n var out = new Uint8Array(DIGEST_LENGTH);\n for (var i = 0; i < 8; i++) {\n out[i * 4] = (this.state[i] >>> 24) & 0xff;\n out[i * 4 + 1] = (this.state[i] >>> 16) & 0xff;\n out[i * 4 + 2] = (this.state[i] >>> 8) & 0xff;\n out[i * 4 + 3] = (this.state[i] >>> 0) & 0xff;\n }\n return out;\n };\n RawSha256.prototype.hashBuffer = function () {\n var _a = this, buffer = _a.buffer, state = _a.state;\n var state0 = state[0], state1 = state[1], state2 = state[2], state3 = state[3], state4 = state[4], state5 = state[5], state6 = state[6], state7 = state[7];\n for (var i = 0; i < BLOCK_SIZE; i++) {\n if (i < 16) {\n this.temp[i] =\n ((buffer[i * 4] & 0xff) << 24) |\n ((buffer[i * 4 + 1] & 0xff) << 16) |\n ((buffer[i * 4 + 2] & 0xff) << 8) |\n (buffer[i * 4 + 3] & 0xff);\n }\n else {\n var u = this.temp[i - 2];\n var t1_1 = ((u >>> 17) | (u << 15)) ^ ((u >>> 19) | (u << 13)) ^ (u >>> 10);\n u = this.temp[i - 15];\n var t2_1 = ((u >>> 7) | (u << 25)) ^ ((u >>> 18) | (u << 14)) ^ (u >>> 3);\n this.temp[i] =\n ((t1_1 + this.temp[i - 7]) | 0) + ((t2_1 + this.temp[i - 16]) | 0);\n }\n var t1 = ((((((state4 >>> 6) | (state4 << 26)) ^\n ((state4 >>> 11) | (state4 << 21)) ^\n ((state4 >>> 25) | (state4 << 7))) +\n ((state4 & state5) ^ (~state4 & state6))) |\n 0) +\n ((state7 + ((KEY[i] + this.temp[i]) | 0)) | 0)) |\n 0;\n var t2 = ((((state0 >>> 2) | (state0 << 30)) ^\n ((state0 >>> 13) | (state0 << 19)) ^\n ((state0 >>> 22) | (state0 << 10))) +\n ((state0 & state1) ^ (state0 & state2) ^ (state1 & state2))) |\n 0;\n state7 = state6;\n state6 = state5;\n state5 = state4;\n state4 = (state3 + t1) | 0;\n state3 = state2;\n state2 = state1;\n state1 = state0;\n state0 = (t1 + t2) | 0;\n }\n state[0] += state0;\n state[1] += state1;\n state[2] += state2;\n state[3] += state3;\n state[4] += state4;\n state[5] += state5;\n state[6] += state6;\n state[7] += state7;\n };\n return RawSha256;\n}());\nexport { RawSha256 };\n//# sourceMappingURL=RawSha256.js.map","export const fromUtf8 = (input) => new TextEncoder().encode(input);\n","// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { fromUtf8 as fromUtf8Browser } from \"@smithy/util-utf8\";\n// Quick polyfill\nvar fromUtf8 = typeof Buffer !== \"undefined\" && Buffer.from\n ? function (input) { return Buffer.from(input, \"utf8\"); }\n : fromUtf8Browser;\nexport function convertToBuffer(data) {\n // Already a Uint8, do nothing\n if (data instanceof Uint8Array)\n return data;\n if (typeof data === \"string\") {\n return fromUtf8(data);\n }\n if (ArrayBuffer.isView(data)) {\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);\n }\n return new Uint8Array(data);\n}\n//# sourceMappingURL=convertToBuffer.js.map","// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport function isEmptyData(data) {\n if (typeof data === \"string\") {\n return data.length === 0;\n }\n return data.byteLength === 0;\n}\n//# sourceMappingURL=isEmptyData.js.map","import { __awaiter, __generator } from \"tslib\";\nimport { BLOCK_SIZE } from \"./constants\";\nimport { RawSha256 } from \"./RawSha256\";\nimport { isEmptyData, convertToBuffer } from \"@aws-crypto/util\";\nvar Sha256 = /** @class */ (function () {\n function Sha256(secret) {\n this.secret = secret;\n this.hash = new RawSha256();\n this.reset();\n }\n Sha256.prototype.update = function (toHash) {\n if (isEmptyData(toHash) || this.error) {\n return;\n }\n try {\n this.hash.update(convertToBuffer(toHash));\n }\n catch (e) {\n this.error = e;\n }\n };\n /* This synchronous method keeps compatibility\n * with the v2 aws-sdk.\n */\n Sha256.prototype.digestSync = function () {\n if (this.error) {\n throw this.error;\n }\n if (this.outer) {\n if (!this.outer.finished) {\n this.outer.update(this.hash.digest());\n }\n return this.outer.digest();\n }\n return this.hash.digest();\n };\n /* The underlying digest method here is synchronous.\n * To keep the same interface with the other hash functions\n * the default is to expose this as an async method.\n * However, it can sometimes be useful to have a sync method.\n */\n Sha256.prototype.digest = function () {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n return [2 /*return*/, this.digestSync()];\n });\n });\n };\n Sha256.prototype.reset = function () {\n this.hash = new RawSha256();\n if (this.secret) {\n this.outer = new RawSha256();\n var inner = bufferFromSecret(this.secret);\n var outer = new Uint8Array(BLOCK_SIZE);\n outer.set(inner);\n for (var i = 0; i < BLOCK_SIZE; i++) {\n inner[i] ^= 0x36;\n outer[i] ^= 0x5c;\n }\n this.hash.update(inner);\n this.outer.update(outer);\n // overwrite the copied key in memory\n for (var i = 0; i < inner.byteLength; i++) {\n inner[i] = 0;\n }\n }\n };\n return Sha256;\n}());\nexport { Sha256 };\nfunction bufferFromSecret(secret) {\n var input = convertToBuffer(secret);\n if (input.byteLength > BLOCK_SIZE) {\n var bufferHash = new RawSha256();\n bufferHash.update(input);\n input = bufferHash.digest();\n }\n var buffer = new Uint8Array(BLOCK_SIZE);\n buffer.set(input);\n return buffer;\n}\n//# sourceMappingURL=jsSha256.js.map","const SHORT_TO_HEX = {};\nconst HEX_TO_SHORT = {};\nfor (let i = 0; i < 256; i++) {\n let encodedByte = i.toString(16).toLowerCase();\n if (encodedByte.length === 1) {\n encodedByte = `0${encodedByte}`;\n }\n SHORT_TO_HEX[i] = encodedByte;\n HEX_TO_SHORT[encodedByte] = i;\n}\nexport function fromHex(encoded) {\n if (encoded.length % 2 !== 0) {\n throw new Error(\"Hex encoded strings must have an even number length\");\n }\n const out = new Uint8Array(encoded.length / 2);\n for (let i = 0; i < encoded.length; i += 2) {\n const encodedByte = encoded.slice(i, i + 2).toLowerCase();\n if (encodedByte in HEX_TO_SHORT) {\n out[i / 2] = HEX_TO_SHORT[encodedByte];\n }\n else {\n throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);\n }\n }\n return out;\n}\nexport function toHex(bytes) {\n let out = \"\";\n for (let i = 0; i < bytes.byteLength; i++) {\n out += SHORT_TO_HEX[bytes[i]];\n }\n return out;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nvar Framework;\n(function (Framework) {\n // < 100 - Web frameworks\n Framework[\"WebUnknown\"] = \"0\";\n Framework[\"React\"] = \"1\";\n Framework[\"NextJs\"] = \"2\";\n Framework[\"Angular\"] = \"3\";\n Framework[\"VueJs\"] = \"4\";\n Framework[\"Nuxt\"] = \"5\";\n Framework[\"Svelte\"] = \"6\";\n // 100s - Server side frameworks\n Framework[\"ServerSideUnknown\"] = \"100\";\n Framework[\"ReactSSR\"] = \"101\";\n Framework[\"NextJsSSR\"] = \"102\";\n Framework[\"AngularSSR\"] = \"103\";\n Framework[\"VueJsSSR\"] = \"104\";\n Framework[\"NuxtSSR\"] = \"105\";\n Framework[\"SvelteSSR\"] = \"106\";\n // 200s - Mobile framework\n Framework[\"ReactNative\"] = \"201\";\n Framework[\"Expo\"] = \"202\";\n})(Framework || (Framework = {}));\nvar Category;\n(function (Category) {\n Category[\"AI\"] = \"ai\";\n Category[\"API\"] = \"api\";\n Category[\"Auth\"] = \"auth\";\n Category[\"Analytics\"] = \"analytics\";\n Category[\"DataStore\"] = \"datastore\";\n Category[\"Geo\"] = \"geo\";\n Category[\"InAppMessaging\"] = \"inappmessaging\";\n Category[\"Interactions\"] = \"interactions\";\n Category[\"Predictions\"] = \"predictions\";\n Category[\"PubSub\"] = \"pubsub\";\n Category[\"PushNotification\"] = \"pushnotification\";\n Category[\"Storage\"] = \"storage\";\n})(Category || (Category = {}));\nvar AiAction;\n(function (AiAction) {\n AiAction[\"CreateConversation\"] = \"1\";\n AiAction[\"GetConversation\"] = \"2\";\n AiAction[\"ListConversations\"] = \"3\";\n AiAction[\"DeleteConversation\"] = \"4\";\n AiAction[\"SendMessage\"] = \"5\";\n AiAction[\"ListMessages\"] = \"6\";\n AiAction[\"OnMessage\"] = \"7\";\n AiAction[\"Generation\"] = \"8\";\n AiAction[\"UpdateConversation\"] = \"9\";\n})(AiAction || (AiAction = {}));\nvar AnalyticsAction;\n(function (AnalyticsAction) {\n AnalyticsAction[\"Record\"] = \"1\";\n AnalyticsAction[\"IdentifyUser\"] = \"2\";\n})(AnalyticsAction || (AnalyticsAction = {}));\nvar ApiAction;\n(function (ApiAction) {\n ApiAction[\"GraphQl\"] = \"1\";\n ApiAction[\"Get\"] = \"2\";\n ApiAction[\"Post\"] = \"3\";\n ApiAction[\"Put\"] = \"4\";\n ApiAction[\"Patch\"] = \"5\";\n ApiAction[\"Del\"] = \"6\";\n ApiAction[\"Head\"] = \"7\";\n})(ApiAction || (ApiAction = {}));\nvar AuthAction;\n(function (AuthAction) {\n AuthAction[\"SignUp\"] = \"1\";\n AuthAction[\"ConfirmSignUp\"] = \"2\";\n AuthAction[\"ResendSignUpCode\"] = \"3\";\n AuthAction[\"SignIn\"] = \"4\";\n AuthAction[\"FetchMFAPreference\"] = \"6\";\n AuthAction[\"UpdateMFAPreference\"] = \"7\";\n AuthAction[\"SetUpTOTP\"] = \"10\";\n AuthAction[\"VerifyTOTPSetup\"] = \"11\";\n AuthAction[\"ConfirmSignIn\"] = \"12\";\n AuthAction[\"DeleteUserAttributes\"] = \"15\";\n AuthAction[\"DeleteUser\"] = \"16\";\n AuthAction[\"UpdateUserAttributes\"] = \"17\";\n AuthAction[\"FetchUserAttributes\"] = \"18\";\n AuthAction[\"ConfirmUserAttribute\"] = \"22\";\n AuthAction[\"SignOut\"] = \"26\";\n AuthAction[\"UpdatePassword\"] = \"27\";\n AuthAction[\"ResetPassword\"] = \"28\";\n AuthAction[\"ConfirmResetPassword\"] = \"29\";\n AuthAction[\"FederatedSignIn\"] = \"30\";\n AuthAction[\"RememberDevice\"] = \"32\";\n AuthAction[\"ForgetDevice\"] = \"33\";\n AuthAction[\"FetchDevices\"] = \"34\";\n AuthAction[\"SendUserAttributeVerificationCode\"] = \"35\";\n AuthAction[\"SignInWithRedirect\"] = \"36\";\n AuthAction[\"StartWebAuthnRegistration\"] = \"37\";\n AuthAction[\"CompleteWebAuthnRegistration\"] = \"38\";\n AuthAction[\"ListWebAuthnCredentials\"] = \"39\";\n AuthAction[\"DeleteWebAuthnCredential\"] = \"40\";\n})(AuthAction || (AuthAction = {}));\nvar DataStoreAction;\n(function (DataStoreAction) {\n DataStoreAction[\"Subscribe\"] = \"1\";\n DataStoreAction[\"GraphQl\"] = \"2\";\n})(DataStoreAction || (DataStoreAction = {}));\nvar GeoAction;\n(function (GeoAction) {\n GeoAction[\"SearchByText\"] = \"0\";\n GeoAction[\"SearchByCoordinates\"] = \"1\";\n GeoAction[\"SearchForSuggestions\"] = \"2\";\n GeoAction[\"SearchByPlaceId\"] = \"3\";\n GeoAction[\"SaveGeofences\"] = \"4\";\n GeoAction[\"GetGeofence\"] = \"5\";\n GeoAction[\"ListGeofences\"] = \"6\";\n GeoAction[\"DeleteGeofences\"] = \"7\";\n})(GeoAction || (GeoAction = {}));\nvar InAppMessagingAction;\n(function (InAppMessagingAction) {\n InAppMessagingAction[\"SyncMessages\"] = \"1\";\n InAppMessagingAction[\"IdentifyUser\"] = \"2\";\n InAppMessagingAction[\"NotifyMessageInteraction\"] = \"3\";\n})(InAppMessagingAction || (InAppMessagingAction = {}));\nvar InteractionsAction;\n(function (InteractionsAction) {\n InteractionsAction[\"None\"] = \"0\";\n})(InteractionsAction || (InteractionsAction = {}));\nvar PredictionsAction;\n(function (PredictionsAction) {\n PredictionsAction[\"Convert\"] = \"1\";\n PredictionsAction[\"Identify\"] = \"2\";\n PredictionsAction[\"Interpret\"] = \"3\";\n})(PredictionsAction || (PredictionsAction = {}));\nvar PubSubAction;\n(function (PubSubAction) {\n PubSubAction[\"Subscribe\"] = \"1\";\n})(PubSubAction || (PubSubAction = {}));\nvar PushNotificationAction;\n(function (PushNotificationAction) {\n PushNotificationAction[\"InitializePushNotifications\"] = \"1\";\n PushNotificationAction[\"IdentifyUser\"] = \"2\";\n PushNotificationAction[\"RegisterDevice\"] = \"3\";\n PushNotificationAction[\"RemoveDevice\"] = \"4\";\n})(PushNotificationAction || (PushNotificationAction = {}));\nvar StorageAction;\n(function (StorageAction) {\n StorageAction[\"UploadData\"] = \"1\";\n StorageAction[\"DownloadData\"] = \"2\";\n StorageAction[\"List\"] = \"3\";\n StorageAction[\"Copy\"] = \"4\";\n StorageAction[\"Remove\"] = \"5\";\n StorageAction[\"GetProperties\"] = \"6\";\n StorageAction[\"GetUrl\"] = \"7\";\n StorageAction[\"GetDataAccess\"] = \"8\";\n StorageAction[\"ListCallerAccessGrants\"] = \"9\";\n})(StorageAction || (StorageAction = {}));\n\nexport { AiAction, AnalyticsAction, ApiAction, AuthAction, Category, DataStoreAction, Framework, GeoAction, InAppMessagingAction, InteractionsAction, PredictionsAction, PubSubAction, PushNotificationAction, StorageAction };\n//# sourceMappingURL=types.mjs.map\n","// generated by genversion\nconst version = '6.20.0';\n\nexport { version };\n//# sourceMappingURL=version.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst globalExists = () => {\n return typeof global !== 'undefined';\n};\nconst globalThisExists = () => {\n return typeof globalThis !== 'undefined';\n};\nconst windowExists = () => {\n return typeof window !== 'undefined';\n};\nconst documentExists = () => {\n return typeof document !== 'undefined';\n};\nconst processExists = () => {\n return typeof process !== 'undefined';\n};\nconst keyPrefixMatch = (object, prefix) => {\n return !!Object.keys(object).find(key => key.startsWith(prefix));\n};\n\nexport { documentExists, globalExists, globalThisExists, keyPrefixMatch, processExists, windowExists };\n//# sourceMappingURL=helpers.mjs.map\n","import { documentExists, processExists } from './helpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Tested with react 18.2 - built using Vite\nfunction reactWebDetect() {\n const elementKeyPrefixedWithReact = (key) => {\n return key.startsWith('_react') || key.startsWith('__react');\n };\n const elementIsReactEnabled = (element) => {\n return Object.keys(element).find(elementKeyPrefixedWithReact);\n };\n const allElementsWithId = () => Array.from(document.querySelectorAll('[id]'));\n return documentExists() && allElementsWithId().some(elementIsReactEnabled);\n}\nfunction reactSSRDetect() {\n return (processExists() &&\n typeof process.env !== 'undefined' &&\n !!Object.keys(process.env).find(key => key.includes('react')));\n}\n// use the some\n\nexport { reactSSRDetect, reactWebDetect };\n//# sourceMappingURL=React.mjs.map\n","import { windowExists, keyPrefixMatch, globalExists } from './helpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Tested with vue 3.3.2\nfunction vueWebDetect() {\n return windowExists() && keyPrefixMatch(window, '__VUE');\n}\nfunction vueSSRDetect() {\n return globalExists() && keyPrefixMatch(global, '__VUE');\n}\n\nexport { vueSSRDetect, vueWebDetect };\n//# sourceMappingURL=Vue.mjs.map\n","import { windowExists, keyPrefixMatch, processExists } from './helpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Tested with svelte 3.59\nfunction svelteWebDetect() {\n return windowExists() && keyPrefixMatch(window, '__SVELTE');\n}\nfunction svelteSSRDetect() {\n return (processExists() &&\n typeof process.env !== 'undefined' &&\n !!Object.keys(process.env).find(key => key.includes('svelte')));\n}\n\nexport { svelteSSRDetect, svelteWebDetect };\n//# sourceMappingURL=Svelte.mjs.map\n","import { windowExists, globalExists, keyPrefixMatch } from './helpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Tested with next 13.4 / react 18.2\nfunction nextWebDetect() {\n return (windowExists() &&\n window.next &&\n typeof window.next === 'object');\n}\nfunction nextSSRDetect() {\n return (globalExists() &&\n (keyPrefixMatch(global, '__next') || keyPrefixMatch(global, '__NEXT')));\n}\n\nexport { nextSSRDetect, nextWebDetect };\n//# sourceMappingURL=Next.mjs.map\n","import { windowExists, globalExists } from './helpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Tested with nuxt 2.15 / vue 2.7\nfunction nuxtWebDetect() {\n return (windowExists() &&\n (window.__NUXT__ !== undefined ||\n window.$nuxt !== undefined));\n}\nfunction nuxtSSRDetect() {\n return (globalExists() && typeof global.__NUXT_PATHS__ !== 'undefined');\n}\n\nexport { nuxtSSRDetect, nuxtWebDetect };\n//# sourceMappingURL=Nuxt.mjs.map\n","import { documentExists, processExists, windowExists } from './helpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Tested with @angular/core 16.0.0\nfunction angularWebDetect() {\n const angularVersionSetInDocument = Boolean(documentExists() && document.querySelector('[ng-version]'));\n const angularContentSetInWindow = Boolean(windowExists() && typeof window.ng !== 'undefined');\n return angularVersionSetInDocument || angularContentSetInWindow;\n}\nfunction angularSSRDetect() {\n return ((processExists() &&\n typeof process.env === 'object' &&\n process.env.npm_lifecycle_script?.startsWith('ng ')) ||\n false);\n}\n\nexport { angularSSRDetect, angularWebDetect };\n//# sourceMappingURL=Angular.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Tested with react-native 0.17.7\nfunction reactNativeDetect() {\n return (typeof navigator !== 'undefined' &&\n typeof navigator.product !== 'undefined' &&\n navigator.product === 'ReactNative');\n}\n\nexport { reactNativeDetect };\n//# sourceMappingURL=ReactNative.mjs.map\n","import { globalExists } from './helpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Tested with expo 48 / react-native 0.71.3\nfunction expoDetect() {\n return globalExists() && typeof global.expo !== 'undefined';\n}\n\nexport { expoDetect };\n//# sourceMappingURL=Expo.mjs.map\n","import { windowExists } from './helpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction webDetect() {\n return windowExists();\n}\n\nexport { webDetect };\n//# sourceMappingURL=Web.mjs.map\n","import { Framework } from '../types.mjs';\nimport { reactWebDetect, reactSSRDetect } from './React.mjs';\nimport { vueWebDetect, vueSSRDetect } from './Vue.mjs';\nimport { svelteWebDetect, svelteSSRDetect } from './Svelte.mjs';\nimport { nextWebDetect, nextSSRDetect } from './Next.mjs';\nimport { nuxtWebDetect, nuxtSSRDetect } from './Nuxt.mjs';\nimport { angularWebDetect, angularSSRDetect } from './Angular.mjs';\nimport { reactNativeDetect } from './ReactNative.mjs';\nimport { expoDetect } from './Expo.mjs';\nimport { webDetect } from './Web.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// These are in the order of detection where when both are detectable, the early Framework will be reported\nconst detectionMap = [\n // First, detect mobile\n { platform: Framework.Expo, detectionMethod: expoDetect },\n { platform: Framework.ReactNative, detectionMethod: reactNativeDetect },\n // Next, detect web frameworks\n { platform: Framework.NextJs, detectionMethod: nextWebDetect },\n { platform: Framework.Nuxt, detectionMethod: nuxtWebDetect },\n { platform: Framework.Angular, detectionMethod: angularWebDetect },\n { platform: Framework.React, detectionMethod: reactWebDetect },\n { platform: Framework.VueJs, detectionMethod: vueWebDetect },\n { platform: Framework.Svelte, detectionMethod: svelteWebDetect },\n { platform: Framework.WebUnknown, detectionMethod: webDetect },\n // Last, detect ssr frameworks\n { platform: Framework.NextJsSSR, detectionMethod: nextSSRDetect },\n { platform: Framework.NuxtSSR, detectionMethod: nuxtSSRDetect },\n { platform: Framework.ReactSSR, detectionMethod: reactSSRDetect },\n { platform: Framework.VueJsSSR, detectionMethod: vueSSRDetect },\n { platform: Framework.AngularSSR, detectionMethod: angularSSRDetect },\n { platform: Framework.SvelteSSR, detectionMethod: svelteSSRDetect },\n];\nfunction detect() {\n return (detectionMap.find(detectionEntry => detectionEntry.detectionMethod())\n ?.platform || Framework.ServerSideUnknown);\n}\n\nexport { detect };\n//# sourceMappingURL=index.mjs.map\n","import { Framework } from './types.mjs';\nimport { detect } from './detection/index.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// We want to cache detection since the framework won't change\nlet frameworkCache;\nconst frameworkChangeObservers = [];\n// Setup the detection reset tracking / timeout delays\nlet resetTriggered = false;\nconst SSR_RESET_TIMEOUT = 10; // ms\nconst WEB_RESET_TIMEOUT = 10; // ms\nconst PRIME_FRAMEWORK_DELAY = 1000; // ms\nconst detectFramework = () => {\n if (!frameworkCache) {\n frameworkCache = detect();\n if (resetTriggered) {\n // The final run of detectFramework:\n // Starting from this point, the `frameworkCache` becomes \"final\".\n // So we don't need to notify the observers again so the observer\n // can be removed after the final notice.\n while (frameworkChangeObservers.length) {\n frameworkChangeObservers.pop()?.();\n }\n }\n else {\n // The first run of detectFramework:\n // Every time we update the cache, call each observer function\n frameworkChangeObservers.forEach(fcn => {\n fcn();\n });\n }\n // Retry once for either Unknown type after a delay (explained below)\n resetTimeout(Framework.ServerSideUnknown, SSR_RESET_TIMEOUT);\n resetTimeout(Framework.WebUnknown, WEB_RESET_TIMEOUT);\n }\n return frameworkCache;\n};\n/**\n * @internal Setup observer callback that will be called everytime the framework changes\n */\nconst observeFrameworkChanges = (fcn) => {\n // When the `frameworkCache` won't be updated again, we ignore all incoming\n // observers.\n if (resetTriggered) {\n return;\n }\n frameworkChangeObservers.push(fcn);\n};\nfunction clearCache() {\n frameworkCache = undefined;\n}\n// For a framework type and a delay amount, setup the event to re-detect\n// During the runtime boot, it is possible that framework detection will\n// be triggered before the framework has made modifications to the\n// global/window/etc needed for detection. When no framework is detected\n// we will reset and try again to ensure we don't use a cached\n// non-framework detection result for all requests.\nfunction resetTimeout(framework, delay) {\n if (frameworkCache === framework && !resetTriggered) {\n setTimeout(() => {\n clearCache();\n resetTriggered = true;\n setTimeout(detectFramework, PRIME_FRAMEWORK_DELAY);\n }, delay);\n }\n}\n\nexport { clearCache, detectFramework, frameworkChangeObservers, observeFrameworkChanges };\n//# sourceMappingURL=detectFramework.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Maintains custom user-agent state set by external consumers.\nconst customUserAgentState = {};\n/**\n * Sets custom user agent state which will be appended to applicable requests. Returns a function that can be used to\n * clean up any custom state set with this API.\n *\n * @note\n * This API operates globally. Calling this API multiple times will result in the most recently set values for a\n * particular API being used.\n *\n * @note\n * This utility IS NOT compatible with SSR.\n *\n * @param input - SetCustomUserAgentInput that defines custom state to apply to the specified APIs.\n */\nconst setCustomUserAgent = (input) => {\n // Save custom user-agent state & increment reference counter\n // TODO Remove `any` when we upgrade to TypeScript 5.2, see: https://github.com/microsoft/TypeScript/issues/44373\n customUserAgentState[input.category] = input.apis.reduce((acc, api) => ({\n ...acc,\n [api]: {\n refCount: acc[api]?.refCount ? acc[api].refCount + 1 : 1,\n additionalDetails: input.additionalDetails,\n },\n }), customUserAgentState[input.category] ?? {});\n // Callback that cleans up state for APIs recorded by this call\n let cleanUpCallbackCalled = false;\n const cleanUpCallback = () => {\n // Only allow the cleanup callback to be called once\n if (cleanUpCallbackCalled) {\n return;\n }\n cleanUpCallbackCalled = true;\n input.apis.forEach(api => {\n const apiRefCount = customUserAgentState[input.category][api].refCount;\n if (apiRefCount > 1) {\n customUserAgentState[input.category][api].refCount = apiRefCount - 1;\n }\n else {\n delete customUserAgentState[input.category][api];\n // Clean up category if no more APIs set\n if (!Object.keys(customUserAgentState[input.category]).length) {\n delete customUserAgentState[input.category];\n }\n }\n });\n };\n return cleanUpCallback;\n};\nconst getCustomUserAgent = (category, api) => customUserAgentState[category]?.[api]?.additionalDetails;\n\nexport { getCustomUserAgent, setCustomUserAgent };\n//# sourceMappingURL=customUserAgent.mjs.map\n","import { Framework } from './types.mjs';\nimport { version } from './version.mjs';\nimport { detectFramework, observeFrameworkChanges } from './detectFramework.mjs';\nimport { getCustomUserAgent } from './customUserAgent.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst BASE_USER_AGENT = `aws-amplify`;\n/** Sanitize Amplify version string be removing special character + and character post the special character */\nconst sanitizeAmplifyVersion = (amplifyVersion) => amplifyVersion.replace(/\\+.*/, '');\nclass PlatformBuilder {\n constructor() {\n this.userAgent = `${BASE_USER_AGENT}/${sanitizeAmplifyVersion(version)}`;\n }\n get framework() {\n return detectFramework();\n }\n get isReactNative() {\n return (this.framework === Framework.ReactNative ||\n this.framework === Framework.Expo);\n }\n observeFrameworkChanges(fcn) {\n observeFrameworkChanges(fcn);\n }\n}\nconst Platform = new PlatformBuilder();\nconst getAmplifyUserAgentObject = ({ category, action, } = {}) => {\n const userAgent = [\n [BASE_USER_AGENT, sanitizeAmplifyVersion(version)],\n ];\n if (category) {\n userAgent.push([category, action]);\n }\n userAgent.push(['framework', detectFramework()]);\n if (category && action) {\n const customState = getCustomUserAgent(category, action);\n if (customState) {\n customState.forEach(state => {\n userAgent.push(state);\n });\n }\n }\n return userAgent;\n};\nconst getAmplifyUserAgent = (customUserAgentDetails) => {\n const userAgent = getAmplifyUserAgentObject(customUserAgentDetails);\n const userAgentString = userAgent\n .map(([agentKey, agentValue]) => agentKey && agentValue ? `${agentKey}/${agentValue}` : agentKey)\n .join(' ');\n return userAgentString;\n};\n\nexport { Platform, getAmplifyUserAgent, getAmplifyUserAgentObject, sanitizeAmplifyVersion };\n//# sourceMappingURL=index.mjs.map\n","export function isFunction(value) {\n return typeof value === 'function';\n}\n//# sourceMappingURL=isFunction.js.map","export function createErrorClass(createImpl) {\n var _super = function (instance) {\n Error.call(instance);\n instance.stack = new Error().stack;\n };\n var ctorFunc = createImpl(_super);\n ctorFunc.prototype = Object.create(Error.prototype);\n ctorFunc.prototype.constructor = ctorFunc;\n return ctorFunc;\n}\n//# sourceMappingURL=createErrorClass.js.map","import { createErrorClass } from './createErrorClass';\nexport var UnsubscriptionError = createErrorClass(function (_super) {\n return function UnsubscriptionErrorImpl(errors) {\n _super(this);\n this.message = errors\n ? errors.length + \" errors occurred during unsubscription:\\n\" + errors.map(function (err, i) { return i + 1 + \") \" + err.toString(); }).join('\\n ')\n : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n };\n});\n//# sourceMappingURL=UnsubscriptionError.js.map","export function arrRemove(arr, item) {\n if (arr) {\n var index = arr.indexOf(item);\n 0 <= index && arr.splice(index, 1);\n }\n}\n//# sourceMappingURL=arrRemove.js.map","import { __read, __spreadArray, __values } from \"tslib\";\nimport { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nimport { arrRemove } from './util/arrRemove';\nvar Subscription = (function () {\n function Subscription(initialTeardown) {\n this.initialTeardown = initialTeardown;\n this.closed = false;\n this._parentage = null;\n this._finalizers = null;\n }\n Subscription.prototype.unsubscribe = function () {\n var e_1, _a, e_2, _b;\n var errors;\n if (!this.closed) {\n this.closed = true;\n var _parentage = this._parentage;\n if (_parentage) {\n this._parentage = null;\n if (Array.isArray(_parentage)) {\n try {\n for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {\n var parent_1 = _parentage_1_1.value;\n parent_1.remove(this);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n }\n else {\n _parentage.remove(this);\n }\n }\n var initialFinalizer = this.initialTeardown;\n if (isFunction(initialFinalizer)) {\n try {\n initialFinalizer();\n }\n catch (e) {\n errors = e instanceof UnsubscriptionError ? e.errors : [e];\n }\n }\n var _finalizers = this._finalizers;\n if (_finalizers) {\n this._finalizers = null;\n try {\n for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {\n var finalizer = _finalizers_1_1.value;\n try {\n execFinalizer(finalizer);\n }\n catch (err) {\n errors = errors !== null && errors !== void 0 ? errors : [];\n if (err instanceof UnsubscriptionError) {\n errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));\n }\n else {\n errors.push(err);\n }\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);\n }\n finally { if (e_2) throw e_2.error; }\n }\n }\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n }\n };\n Subscription.prototype.add = function (teardown) {\n var _a;\n if (teardown && teardown !== this) {\n if (this.closed) {\n execFinalizer(teardown);\n }\n else {\n if (teardown instanceof Subscription) {\n if (teardown.closed || teardown._hasParent(this)) {\n return;\n }\n teardown._addParent(this);\n }\n (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);\n }\n }\n };\n Subscription.prototype._hasParent = function (parent) {\n var _parentage = this._parentage;\n return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));\n };\n Subscription.prototype._addParent = function (parent) {\n var _parentage = this._parentage;\n this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;\n };\n Subscription.prototype._removeParent = function (parent) {\n var _parentage = this._parentage;\n if (_parentage === parent) {\n this._parentage = null;\n }\n else if (Array.isArray(_parentage)) {\n arrRemove(_parentage, parent);\n }\n };\n Subscription.prototype.remove = function (teardown) {\n var _finalizers = this._finalizers;\n _finalizers && arrRemove(_finalizers, teardown);\n if (teardown instanceof Subscription) {\n teardown._removeParent(this);\n }\n };\n Subscription.EMPTY = (function () {\n var empty = new Subscription();\n empty.closed = true;\n return empty;\n })();\n return Subscription;\n}());\nexport { Subscription };\nexport var EMPTY_SUBSCRIPTION = Subscription.EMPTY;\nexport function isSubscription(value) {\n return (value instanceof Subscription ||\n (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe)));\n}\nfunction execFinalizer(finalizer) {\n if (isFunction(finalizer)) {\n finalizer();\n }\n else {\n finalizer.unsubscribe();\n }\n}\n//# sourceMappingURL=Subscription.js.map","export var config = {\n onUnhandledError: null,\n onStoppedNotification: null,\n Promise: undefined,\n useDeprecatedSynchronousErrorHandling: false,\n useDeprecatedNextContext: false,\n};\n//# sourceMappingURL=config.js.map","import { __read, __spreadArray } from \"tslib\";\nexport var timeoutProvider = {\n setTimeout: function (handler, timeout) {\n var args = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n args[_i - 2] = arguments[_i];\n }\n var delegate = timeoutProvider.delegate;\n if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) {\n return delegate.setTimeout.apply(delegate, __spreadArray([handler, timeout], __read(args)));\n }\n return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));\n },\n clearTimeout: function (handle) {\n var delegate = timeoutProvider.delegate;\n return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);\n },\n delegate: undefined,\n};\n//# sourceMappingURL=timeoutProvider.js.map","import { config } from '../config';\nimport { timeoutProvider } from '../scheduler/timeoutProvider';\nexport function reportUnhandledError(err) {\n timeoutProvider.setTimeout(function () {\n var onUnhandledError = config.onUnhandledError;\n if (onUnhandledError) {\n onUnhandledError(err);\n }\n else {\n throw err;\n }\n });\n}\n//# sourceMappingURL=reportUnhandledError.js.map","export function noop() { }\n//# sourceMappingURL=noop.js.map","import { config } from '../config';\nvar context = null;\nexport function errorContext(cb) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n var isRoot = !context;\n if (isRoot) {\n context = { errorThrown: false, error: null };\n }\n cb();\n if (isRoot) {\n var _a = context, errorThrown = _a.errorThrown, error = _a.error;\n context = null;\n if (errorThrown) {\n throw error;\n }\n }\n }\n else {\n cb();\n }\n}\nexport function captureError(err) {\n if (config.useDeprecatedSynchronousErrorHandling && context) {\n context.errorThrown = true;\n context.error = err;\n }\n}\n//# sourceMappingURL=errorContext.js.map","import { __extends } from \"tslib\";\nimport { isFunction } from './util/isFunction';\nimport { isSubscription, Subscription } from './Subscription';\nimport { config } from './config';\nimport { reportUnhandledError } from './util/reportUnhandledError';\nimport { noop } from './util/noop';\nimport { nextNotification, errorNotification, COMPLETE_NOTIFICATION } from './NotificationFactories';\nimport { timeoutProvider } from './scheduler/timeoutProvider';\nimport { captureError } from './util/errorContext';\nvar Subscriber = (function (_super) {\n __extends(Subscriber, _super);\n function Subscriber(destination) {\n var _this = _super.call(this) || this;\n _this.isStopped = false;\n if (destination) {\n _this.destination = destination;\n if (isSubscription(destination)) {\n destination.add(_this);\n }\n }\n else {\n _this.destination = EMPTY_OBSERVER;\n }\n return _this;\n }\n Subscriber.create = function (next, error, complete) {\n return new SafeSubscriber(next, error, complete);\n };\n Subscriber.prototype.next = function (value) {\n if (this.isStopped) {\n handleStoppedNotification(nextNotification(value), this);\n }\n else {\n this._next(value);\n }\n };\n Subscriber.prototype.error = function (err) {\n if (this.isStopped) {\n handleStoppedNotification(errorNotification(err), this);\n }\n else {\n this.isStopped = true;\n this._error(err);\n }\n };\n Subscriber.prototype.complete = function () {\n if (this.isStopped) {\n handleStoppedNotification(COMPLETE_NOTIFICATION, this);\n }\n else {\n this.isStopped = true;\n this._complete();\n }\n };\n Subscriber.prototype.unsubscribe = function () {\n if (!this.closed) {\n this.isStopped = true;\n _super.prototype.unsubscribe.call(this);\n this.destination = null;\n }\n };\n Subscriber.prototype._next = function (value) {\n this.destination.next(value);\n };\n Subscriber.prototype._error = function (err) {\n try {\n this.destination.error(err);\n }\n finally {\n this.unsubscribe();\n }\n };\n Subscriber.prototype._complete = function () {\n try {\n this.destination.complete();\n }\n finally {\n this.unsubscribe();\n }\n };\n return Subscriber;\n}(Subscription));\nexport { Subscriber };\nvar _bind = Function.prototype.bind;\nfunction bind(fn, thisArg) {\n return _bind.call(fn, thisArg);\n}\nvar ConsumerObserver = (function () {\n function ConsumerObserver(partialObserver) {\n this.partialObserver = partialObserver;\n }\n ConsumerObserver.prototype.next = function (value) {\n var partialObserver = this.partialObserver;\n if (partialObserver.next) {\n try {\n partialObserver.next(value);\n }\n catch (error) {\n handleUnhandledError(error);\n }\n }\n };\n ConsumerObserver.prototype.error = function (err) {\n var partialObserver = this.partialObserver;\n if (partialObserver.error) {\n try {\n partialObserver.error(err);\n }\n catch (error) {\n handleUnhandledError(error);\n }\n }\n else {\n handleUnhandledError(err);\n }\n };\n ConsumerObserver.prototype.complete = function () {\n var partialObserver = this.partialObserver;\n if (partialObserver.complete) {\n try {\n partialObserver.complete();\n }\n catch (error) {\n handleUnhandledError(error);\n }\n }\n };\n return ConsumerObserver;\n}());\nvar SafeSubscriber = (function (_super) {\n __extends(SafeSubscriber, _super);\n function SafeSubscriber(observerOrNext, error, complete) {\n var _this = _super.call(this) || this;\n var partialObserver;\n if (isFunction(observerOrNext) || !observerOrNext) {\n partialObserver = {\n next: (observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined),\n error: error !== null && error !== void 0 ? error : undefined,\n complete: complete !== null && complete !== void 0 ? complete : undefined,\n };\n }\n else {\n var context_1;\n if (_this && config.useDeprecatedNextContext) {\n context_1 = Object.create(observerOrNext);\n context_1.unsubscribe = function () { return _this.unsubscribe(); };\n partialObserver = {\n next: observerOrNext.next && bind(observerOrNext.next, context_1),\n error: observerOrNext.error && bind(observerOrNext.error, context_1),\n complete: observerOrNext.complete && bind(observerOrNext.complete, context_1),\n };\n }\n else {\n partialObserver = observerOrNext;\n }\n }\n _this.destination = new ConsumerObserver(partialObserver);\n return _this;\n }\n return SafeSubscriber;\n}(Subscriber));\nexport { SafeSubscriber };\nfunction handleUnhandledError(error) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n captureError(error);\n }\n else {\n reportUnhandledError(error);\n }\n}\nfunction defaultErrorHandler(err) {\n throw err;\n}\nfunction handleStoppedNotification(notification, subscriber) {\n var onStoppedNotification = config.onStoppedNotification;\n onStoppedNotification && timeoutProvider.setTimeout(function () { return onStoppedNotification(notification, subscriber); });\n}\nexport var EMPTY_OBSERVER = {\n closed: true,\n next: noop,\n error: defaultErrorHandler,\n complete: noop,\n};\n//# sourceMappingURL=Subscriber.js.map","export var observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })();\n//# sourceMappingURL=observable.js.map","export function identity(x) {\n return x;\n}\n//# sourceMappingURL=identity.js.map","import { identity } from './identity';\nexport function pipe() {\n var fns = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n fns[_i] = arguments[_i];\n }\n return pipeFromArray(fns);\n}\nexport function pipeFromArray(fns) {\n if (fns.length === 0) {\n return identity;\n }\n if (fns.length === 1) {\n return fns[0];\n }\n return function piped(input) {\n return fns.reduce(function (prev, fn) { return fn(prev); }, input);\n };\n}\n//# sourceMappingURL=pipe.js.map","import { SafeSubscriber, Subscriber } from './Subscriber';\nimport { isSubscription } from './Subscription';\nimport { observable as Symbol_observable } from './symbol/observable';\nimport { pipeFromArray } from './util/pipe';\nimport { config } from './config';\nimport { isFunction } from './util/isFunction';\nimport { errorContext } from './util/errorContext';\nvar Observable = (function () {\n function Observable(subscribe) {\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n Observable.prototype.lift = function (operator) {\n var observable = new Observable();\n observable.source = this;\n observable.operator = operator;\n return observable;\n };\n Observable.prototype.subscribe = function (observerOrNext, error, complete) {\n var _this = this;\n var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);\n errorContext(function () {\n var _a = _this, operator = _a.operator, source = _a.source;\n subscriber.add(operator\n ?\n operator.call(subscriber, source)\n : source\n ?\n _this._subscribe(subscriber)\n :\n _this._trySubscribe(subscriber));\n });\n return subscriber;\n };\n Observable.prototype._trySubscribe = function (sink) {\n try {\n return this._subscribe(sink);\n }\n catch (err) {\n sink.error(err);\n }\n };\n Observable.prototype.forEach = function (next, promiseCtor) {\n var _this = this;\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor(function (resolve, reject) {\n var subscriber = new SafeSubscriber({\n next: function (value) {\n try {\n next(value);\n }\n catch (err) {\n reject(err);\n subscriber.unsubscribe();\n }\n },\n error: reject,\n complete: resolve,\n });\n _this.subscribe(subscriber);\n });\n };\n Observable.prototype._subscribe = function (subscriber) {\n var _a;\n return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);\n };\n Observable.prototype[Symbol_observable] = function () {\n return this;\n };\n Observable.prototype.pipe = function () {\n var operations = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n operations[_i] = arguments[_i];\n }\n return pipeFromArray(operations)(this);\n };\n Observable.prototype.toPromise = function (promiseCtor) {\n var _this = this;\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor(function (resolve, reject) {\n var value;\n _this.subscribe(function (x) { return (value = x); }, function (err) { return reject(err); }, function () { return resolve(value); });\n });\n };\n Observable.create = function (subscribe) {\n return new Observable(subscribe);\n };\n return Observable;\n}());\nexport { Observable };\nfunction getPromiseCtor(promiseCtor) {\n var _a;\n return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;\n}\nfunction isObserver(value) {\n return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);\n}\nfunction isSubscriber(value) {\n return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));\n}\n//# sourceMappingURL=Observable.js.map","import { isFunction } from './isFunction';\nexport function hasLift(source) {\n return isFunction(source === null || source === void 0 ? void 0 : source.lift);\n}\nexport function operate(init) {\n return function (source) {\n if (hasLift(source)) {\n return source.lift(function (liftedSource) {\n try {\n return init(liftedSource, this);\n }\n catch (err) {\n this.error(err);\n }\n });\n }\n throw new TypeError('Unable to lift unknown Observable type');\n };\n}\n//# sourceMappingURL=lift.js.map","import { __extends } from \"tslib\";\nimport { Subscriber } from '../Subscriber';\nexport function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {\n return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);\n}\nvar OperatorSubscriber = (function (_super) {\n __extends(OperatorSubscriber, _super);\n function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {\n var _this = _super.call(this, destination) || this;\n _this.onFinalize = onFinalize;\n _this.shouldUnsubscribe = shouldUnsubscribe;\n _this._next = onNext\n ? function (value) {\n try {\n onNext(value);\n }\n catch (err) {\n destination.error(err);\n }\n }\n : _super.prototype._next;\n _this._error = onError\n ? function (err) {\n try {\n onError(err);\n }\n catch (err) {\n destination.error(err);\n }\n finally {\n this.unsubscribe();\n }\n }\n : _super.prototype._error;\n _this._complete = onComplete\n ? function () {\n try {\n onComplete();\n }\n catch (err) {\n destination.error(err);\n }\n finally {\n this.unsubscribe();\n }\n }\n : _super.prototype._complete;\n return _this;\n }\n OperatorSubscriber.prototype.unsubscribe = function () {\n var _a;\n if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {\n var closed_1 = this.closed;\n _super.prototype.unsubscribe.call(this);\n !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));\n }\n };\n return OperatorSubscriber;\n}(Subscriber));\nexport { OperatorSubscriber };\n//# sourceMappingURL=OperatorSubscriber.js.map","export var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });\n//# sourceMappingURL=isArrayLike.js.map","import { isFunction } from \"./isFunction\";\nexport function isPromise(value) {\n return isFunction(value === null || value === void 0 ? void 0 : value.then);\n}\n//# sourceMappingURL=isPromise.js.map","import { observable as Symbol_observable } from '../symbol/observable';\nimport { isFunction } from './isFunction';\nexport function isInteropObservable(input) {\n return isFunction(input[Symbol_observable]);\n}\n//# sourceMappingURL=isInteropObservable.js.map","import { isFunction } from './isFunction';\nexport function isAsyncIterable(obj) {\n return Symbol.asyncIterator && isFunction(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]);\n}\n//# sourceMappingURL=isAsyncIterable.js.map","export function createInvalidObservableTypeError(input) {\n return new TypeError(\"You provided \" + (input !== null && typeof input === 'object' ? 'an invalid object' : \"'\" + input + \"'\") + \" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.\");\n}\n//# sourceMappingURL=throwUnobservableError.js.map","export function getSymbolIterator() {\n if (typeof Symbol !== 'function' || !Symbol.iterator) {\n return '@@iterator';\n }\n return Symbol.iterator;\n}\nexport var iterator = getSymbolIterator();\n//# sourceMappingURL=iterator.js.map","import { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { isFunction } from './isFunction';\nexport function isIterable(input) {\n return isFunction(input === null || input === void 0 ? void 0 : input[Symbol_iterator]);\n}\n//# sourceMappingURL=isIterable.js.map","import { __asyncGenerator, __await, __generator } from \"tslib\";\nimport { isFunction } from './isFunction';\nexport function readableStreamLikeToAsyncGenerator(readableStream) {\n return __asyncGenerator(this, arguments, function readableStreamLikeToAsyncGenerator_1() {\n var reader, _a, value, done;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n reader = readableStream.getReader();\n _b.label = 1;\n case 1:\n _b.trys.push([1, , 9, 10]);\n _b.label = 2;\n case 2:\n if (!true) return [3, 8];\n return [4, __await(reader.read())];\n case 3:\n _a = _b.sent(), value = _a.value, done = _a.done;\n if (!done) return [3, 5];\n return [4, __await(void 0)];\n case 4: return [2, _b.sent()];\n case 5: return [4, __await(value)];\n case 6: return [4, _b.sent()];\n case 7:\n _b.sent();\n return [3, 2];\n case 8: return [3, 10];\n case 9:\n reader.releaseLock();\n return [7];\n case 10: return [2];\n }\n });\n });\n}\nexport function isReadableStreamLike(obj) {\n return isFunction(obj === null || obj === void 0 ? void 0 : obj.getReader);\n}\n//# sourceMappingURL=isReadableStreamLike.js.map","import { __asyncValues, __awaiter, __generator, __values } from \"tslib\";\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isPromise } from '../util/isPromise';\nimport { Observable } from '../Observable';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isAsyncIterable } from '../util/isAsyncIterable';\nimport { createInvalidObservableTypeError } from '../util/throwUnobservableError';\nimport { isIterable } from '../util/isIterable';\nimport { isReadableStreamLike, readableStreamLikeToAsyncGenerator } from '../util/isReadableStreamLike';\nimport { isFunction } from '../util/isFunction';\nimport { reportUnhandledError } from '../util/reportUnhandledError';\nimport { observable as Symbol_observable } from '../symbol/observable';\nexport function innerFrom(input) {\n if (input instanceof Observable) {\n return input;\n }\n if (input != null) {\n if (isInteropObservable(input)) {\n return fromInteropObservable(input);\n }\n if (isArrayLike(input)) {\n return fromArrayLike(input);\n }\n if (isPromise(input)) {\n return fromPromise(input);\n }\n if (isAsyncIterable(input)) {\n return fromAsyncIterable(input);\n }\n if (isIterable(input)) {\n return fromIterable(input);\n }\n if (isReadableStreamLike(input)) {\n return fromReadableStreamLike(input);\n }\n }\n throw createInvalidObservableTypeError(input);\n}\nexport function fromInteropObservable(obj) {\n return new Observable(function (subscriber) {\n var obs = obj[Symbol_observable]();\n if (isFunction(obs.subscribe)) {\n return obs.subscribe(subscriber);\n }\n throw new TypeError('Provided object does not correctly implement Symbol.observable');\n });\n}\nexport function fromArrayLike(array) {\n return new Observable(function (subscriber) {\n for (var i = 0; i < array.length && !subscriber.closed; i++) {\n subscriber.next(array[i]);\n }\n subscriber.complete();\n });\n}\nexport function fromPromise(promise) {\n return new Observable(function (subscriber) {\n promise\n .then(function (value) {\n if (!subscriber.closed) {\n subscriber.next(value);\n subscriber.complete();\n }\n }, function (err) { return subscriber.error(err); })\n .then(null, reportUnhandledError);\n });\n}\nexport function fromIterable(iterable) {\n return new Observable(function (subscriber) {\n var e_1, _a;\n try {\n for (var iterable_1 = __values(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) {\n var value = iterable_1_1.value;\n subscriber.next(value);\n if (subscriber.closed) {\n return;\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) _a.call(iterable_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n subscriber.complete();\n });\n}\nexport function fromAsyncIterable(asyncIterable) {\n return new Observable(function (subscriber) {\n process(asyncIterable, subscriber).catch(function (err) { return subscriber.error(err); });\n });\n}\nexport function fromReadableStreamLike(readableStream) {\n return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));\n}\nfunction process(asyncIterable, subscriber) {\n var asyncIterable_1, asyncIterable_1_1;\n var e_2, _a;\n return __awaiter(this, void 0, void 0, function () {\n var value, e_2_1;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n _b.trys.push([0, 5, 6, 11]);\n asyncIterable_1 = __asyncValues(asyncIterable);\n _b.label = 1;\n case 1: return [4, asyncIterable_1.next()];\n case 2:\n if (!(asyncIterable_1_1 = _b.sent(), !asyncIterable_1_1.done)) return [3, 4];\n value = asyncIterable_1_1.value;\n subscriber.next(value);\n if (subscriber.closed) {\n return [2];\n }\n _b.label = 3;\n case 3: return [3, 1];\n case 4: return [3, 11];\n case 5:\n e_2_1 = _b.sent();\n e_2 = { error: e_2_1 };\n return [3, 11];\n case 6:\n _b.trys.push([6, , 9, 10]);\n if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return))) return [3, 8];\n return [4, _a.call(asyncIterable_1)];\n case 7:\n _b.sent();\n _b.label = 8;\n case 8: return [3, 10];\n case 9:\n if (e_2) throw e_2.error;\n return [7];\n case 10: return [7];\n case 11:\n subscriber.complete();\n return [2];\n }\n });\n });\n}\n//# sourceMappingURL=innerFrom.js.map","export function executeSchedule(parentSubscription, scheduler, work, delay, repeat) {\n if (delay === void 0) { delay = 0; }\n if (repeat === void 0) { repeat = false; }\n var scheduleSubscription = scheduler.schedule(function () {\n work();\n if (repeat) {\n parentSubscription.add(this.schedule(null, delay));\n }\n else {\n this.unsubscribe();\n }\n }, delay);\n parentSubscription.add(scheduleSubscription);\n if (!repeat) {\n return scheduleSubscription;\n }\n}\n//# sourceMappingURL=executeSchedule.js.map","import { executeSchedule } from '../util/executeSchedule';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function observeOn(scheduler, delay) {\n if (delay === void 0) { delay = 0; }\n return operate(function (source, subscriber) {\n source.subscribe(createOperatorSubscriber(subscriber, function (value) { return executeSchedule(subscriber, scheduler, function () { return subscriber.next(value); }, delay); }, function () { return executeSchedule(subscriber, scheduler, function () { return subscriber.complete(); }, delay); }, function (err) { return executeSchedule(subscriber, scheduler, function () { return subscriber.error(err); }, delay); }));\n });\n}\n//# sourceMappingURL=observeOn.js.map","import { operate } from '../util/lift';\nexport function subscribeOn(scheduler, delay) {\n if (delay === void 0) { delay = 0; }\n return operate(function (source, subscriber) {\n subscriber.add(scheduler.schedule(function () { return source.subscribe(subscriber); }, delay));\n });\n}\n//# sourceMappingURL=subscribeOn.js.map","import { innerFrom } from '../observable/innerFrom';\nimport { observeOn } from '../operators/observeOn';\nimport { subscribeOn } from '../operators/subscribeOn';\nexport function scheduleObservable(input, scheduler) {\n return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));\n}\n//# sourceMappingURL=scheduleObservable.js.map","import { innerFrom } from '../observable/innerFrom';\nimport { observeOn } from '../operators/observeOn';\nimport { subscribeOn } from '../operators/subscribeOn';\nexport function schedulePromise(input, scheduler) {\n return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));\n}\n//# sourceMappingURL=schedulePromise.js.map","import { Observable } from '../Observable';\nexport function scheduleArray(input, scheduler) {\n return new Observable(function (subscriber) {\n var i = 0;\n return scheduler.schedule(function () {\n if (i === input.length) {\n subscriber.complete();\n }\n else {\n subscriber.next(input[i++]);\n if (!subscriber.closed) {\n this.schedule();\n }\n }\n });\n });\n}\n//# sourceMappingURL=scheduleArray.js.map","import { Observable } from '../Observable';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { isFunction } from '../util/isFunction';\nimport { executeSchedule } from '../util/executeSchedule';\nexport function scheduleIterable(input, scheduler) {\n return new Observable(function (subscriber) {\n var iterator;\n executeSchedule(subscriber, scheduler, function () {\n iterator = input[Symbol_iterator]();\n executeSchedule(subscriber, scheduler, function () {\n var _a;\n var value;\n var done;\n try {\n (_a = iterator.next(), value = _a.value, done = _a.done);\n }\n catch (err) {\n subscriber.error(err);\n return;\n }\n if (done) {\n subscriber.complete();\n }\n else {\n subscriber.next(value);\n }\n }, 0, true);\n });\n return function () { return isFunction(iterator === null || iterator === void 0 ? void 0 : iterator.return) && iterator.return(); };\n });\n}\n//# sourceMappingURL=scheduleIterable.js.map","import { Observable } from '../Observable';\nimport { executeSchedule } from '../util/executeSchedule';\nexport function scheduleAsyncIterable(input, scheduler) {\n if (!input) {\n throw new Error('Iterable cannot be null');\n }\n return new Observable(function (subscriber) {\n executeSchedule(subscriber, scheduler, function () {\n var iterator = input[Symbol.asyncIterator]();\n executeSchedule(subscriber, scheduler, function () {\n iterator.next().then(function (result) {\n if (result.done) {\n subscriber.complete();\n }\n else {\n subscriber.next(result.value);\n }\n });\n }, 0, true);\n });\n });\n}\n//# sourceMappingURL=scheduleAsyncIterable.js.map","import { scheduleAsyncIterable } from './scheduleAsyncIterable';\nimport { readableStreamLikeToAsyncGenerator } from '../util/isReadableStreamLike';\nexport function scheduleReadableStreamLike(input, scheduler) {\n return scheduleAsyncIterable(readableStreamLikeToAsyncGenerator(input), scheduler);\n}\n//# sourceMappingURL=scheduleReadableStreamLike.js.map","import { scheduleObservable } from './scheduleObservable';\nimport { schedulePromise } from './schedulePromise';\nimport { scheduleArray } from './scheduleArray';\nimport { scheduleIterable } from './scheduleIterable';\nimport { scheduleAsyncIterable } from './scheduleAsyncIterable';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isPromise } from '../util/isPromise';\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isIterable } from '../util/isIterable';\nimport { isAsyncIterable } from '../util/isAsyncIterable';\nimport { createInvalidObservableTypeError } from '../util/throwUnobservableError';\nimport { isReadableStreamLike } from '../util/isReadableStreamLike';\nimport { scheduleReadableStreamLike } from './scheduleReadableStreamLike';\nexport function scheduled(input, scheduler) {\n if (input != null) {\n if (isInteropObservable(input)) {\n return scheduleObservable(input, scheduler);\n }\n if (isArrayLike(input)) {\n return scheduleArray(input, scheduler);\n }\n if (isPromise(input)) {\n return schedulePromise(input, scheduler);\n }\n if (isAsyncIterable(input)) {\n return scheduleAsyncIterable(input, scheduler);\n }\n if (isIterable(input)) {\n return scheduleIterable(input, scheduler);\n }\n if (isReadableStreamLike(input)) {\n return scheduleReadableStreamLike(input, scheduler);\n }\n }\n throw createInvalidObservableTypeError(input);\n}\n//# sourceMappingURL=scheduled.js.map","import { scheduled } from '../scheduled/scheduled';\nimport { innerFrom } from './innerFrom';\nexport function from(input, scheduler) {\n return scheduler ? scheduled(input, scheduler) : innerFrom(input);\n}\n//# sourceMappingURL=from.js.map","import { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function map(project, thisArg) {\n return operate(function (source, subscriber) {\n var index = 0;\n source.subscribe(createOperatorSubscriber(subscriber, function (value) {\n subscriber.next(project.call(thisArg, value, index++));\n }));\n });\n}\n//# sourceMappingURL=map.js.map","import { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function filter(predicate, thisArg) {\n return operate(function (source, subscriber) {\n var index = 0;\n source.subscribe(createOperatorSubscriber(subscriber, function (value) { return predicate.call(thisArg, value, index++) && subscriber.next(value); }));\n });\n}\n//# sourceMappingURL=filter.js.map","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst isWebWorker = () => {\n if (typeof self === 'undefined') {\n return false;\n }\n const selfContext = self;\n return (typeof selfContext.WorkerGlobalScope !== 'undefined' &&\n self instanceof selfContext.WorkerGlobalScope);\n};\n\nexport { isWebWorker };\n//# sourceMappingURL=isWebWorker.mjs.map\n","import { from, Observable } from 'rxjs';\nimport '../types/errors.mjs';\nimport '../errors/errorHelpers.mjs';\nimport '../utils/getClientInfo/getClientInfo.mjs';\nimport { isWebWorker } from '../utils/isWebWorker.mjs';\nimport '../utils/retry/retry.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nclass Reachability {\n networkMonitor(_) {\n const globalObj = isWebWorker()\n ? self\n : typeof window !== 'undefined' && window;\n if (!globalObj) {\n return from([{ online: true }]);\n }\n return new Observable(observer => {\n observer.next({ online: globalObj.navigator.onLine });\n const notifyOnline = () => {\n observer.next({ online: true });\n };\n const notifyOffline = () => {\n observer.next({ online: false });\n };\n globalObj.addEventListener('online', notifyOnline);\n globalObj.addEventListener('offline', notifyOffline);\n Reachability._observers.push(observer);\n return () => {\n globalObj.removeEventListener('online', notifyOnline);\n globalObj.removeEventListener('offline', notifyOffline);\n Reachability._observers = Reachability._observers.filter(_observer => _observer !== observer);\n };\n });\n }\n // expose observers to simulate offline mode for integration testing\n static _observerOverride(status) {\n for (const observer of this._observers) {\n if (observer.closed) {\n this._observers = this._observers.filter(_observer => _observer !== observer);\n continue;\n }\n observer?.next && observer.next(status);\n }\n }\n}\nReachability._observers = [];\n\nexport { Reachability };\n//# sourceMappingURL=Reachability.mjs.map\n","import { ConsoleLogger } from '../../Logger/ConsoleLogger.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst logger = new ConsoleLogger('Auth');\nclass AuthClass {\n /**\n * Configure Auth category\n *\n * @internal\n *\n * @param authResourcesConfig - Resources configurations required by Auth providers.\n * @param authOptions - Client options used by library\n *\n * @returns void\n */\n configure(authResourcesConfig, authOptions) {\n this.authConfig = authResourcesConfig;\n this.authOptions = authOptions;\n if (authResourcesConfig && authResourcesConfig.Cognito?.userPoolEndpoint) {\n logger.warn(getCustomEndpointWarningMessage('Amazon Cognito User Pool'));\n }\n if (authResourcesConfig &&\n authResourcesConfig.Cognito?.identityPoolEndpoint) {\n logger.warn(getCustomEndpointWarningMessage('Amazon Cognito Identity Pool'));\n }\n }\n /**\n * Fetch the auth tokens, and the temporary AWS credentials and identity if they are configured. By default it\n * will automatically refresh expired auth tokens if a valid refresh token is present. You can force a refresh\n * of non-expired tokens with `{ forceRefresh: true }` input.\n *\n * @param options - Options configuring the fetch behavior.\n *\n * @returns Promise of current auth session {@link AuthSession}.\n */\n async fetchAuthSession(options = {}) {\n let credentialsAndIdentityId;\n let userSub;\n // Get tokens will throw if session cannot be refreshed (network or service error) or return null if not available\n const tokens = await this.getTokens(options);\n if (tokens) {\n userSub = tokens.accessToken?.payload?.sub;\n // getCredentialsAndIdentityId will throw if cannot get credentials (network or service error)\n credentialsAndIdentityId =\n await this.authOptions?.credentialsProvider?.getCredentialsAndIdentityId({\n authConfig: this.authConfig,\n tokens,\n authenticated: true,\n forceRefresh: options.forceRefresh,\n });\n }\n else {\n // getCredentialsAndIdentityId will throw if cannot get credentials (network or service error)\n credentialsAndIdentityId =\n await this.authOptions?.credentialsProvider?.getCredentialsAndIdentityId({\n authConfig: this.authConfig,\n authenticated: false,\n forceRefresh: options.forceRefresh,\n });\n }\n return {\n tokens,\n credentials: credentialsAndIdentityId?.credentials,\n identityId: credentialsAndIdentityId?.identityId,\n userSub,\n };\n }\n async clearCredentials() {\n await this.authOptions?.credentialsProvider?.clearCredentialsAndIdentityId();\n }\n async getTokens(options) {\n return ((await this.authOptions?.tokenProvider?.getTokens(options)) ?? undefined);\n }\n}\nconst getCustomEndpointWarningMessage = (target) => `You are using a custom Amazon ${target} endpoint, ensure the endpoint is correct.`;\n\nexport { AuthClass };\n//# sourceMappingURL=index.mjs.map\n","import { Hub, AMPLIFY_SYMBOL } from '../Hub/index.mjs';\nimport '../types/errors.mjs';\nimport '../errors/errorHelpers.mjs';\nimport '../utils/getClientInfo/getClientInfo.mjs';\nimport '../utils/retry/retry.mjs';\nimport { deepFreeze } from '../utils/deepFreeze.mjs';\nimport '../parseAWSExports.mjs';\nimport { ADD_OAUTH_LISTENER } from './constants.mjs';\nimport 'uuid';\nimport { parseAmplifyConfig } from '../utils/parseAmplifyConfig.mjs';\nimport './Auth/utils/errorHelpers.mjs';\nimport '@aws-crypto/sha256-js';\nimport '@smithy/util-hex-encoding';\nimport '../Platform/index.mjs';\nimport '../Platform/types.mjs';\nimport '../BackgroundProcessManager/types.mjs';\nimport '../Reachability/Reachability.mjs';\nimport '../utils/sessionListener/index.mjs';\nimport { AuthClass } from './Auth/index.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nclass AmplifyClass {\n constructor() {\n this.oAuthListener = undefined;\n this.isConfigured = false;\n this.resourcesConfig = {};\n this.libraryOptions = {};\n this.Auth = new AuthClass();\n }\n /**\n * Configures Amplify for use with your back-end resources.\n *\n * @remarks\n * This API does not perform any merging of either `resourcesConfig` or `libraryOptions`. The most recently\n * provided values will be used after configuration.\n *\n * @remarks\n * `configure` can be used to specify additional library options where available for supported categories.\n *\n * @param resourceConfig - Back-end resource configuration. Typically provided via the `aws-exports.js` file.\n * @param libraryOptions - Additional options for customizing the behavior of the library.\n */\n configure(resourcesConfig, libraryOptions) {\n const resolvedResourceConfig = parseAmplifyConfig(resourcesConfig);\n this.resourcesConfig = resolvedResourceConfig;\n if (libraryOptions) {\n this.libraryOptions = libraryOptions;\n }\n // Make resource config immutable\n this.resourcesConfig = deepFreeze(this.resourcesConfig);\n this.Auth.configure(this.resourcesConfig.Auth, this.libraryOptions.Auth);\n // Warn if Pinpoint is configured\n if (this.resourcesConfig.Analytics?.Pinpoint ||\n this.resourcesConfig.Notifications?.InAppMessaging?.Pinpoint ||\n this.resourcesConfig.Notifications?.PushNotification?.Pinpoint) {\n // eslint-disable-next-line no-console\n console.warn('AWS will end support for Amazon Pinpoint on October 30, 2026. ' +\n 'The guidance is to use AWS End User Messaging for push notifications and SMS, ' +\n 'Amazon Simple Email Service for sending emails, Amazon Connect for campaigns, journeys, endpoints, and engagement analytics. ' +\n 'Pinpoint recommends Amazon Kinesis for event collection and mobile analytics.');\n }\n Hub.dispatch('core', {\n event: 'configure',\n data: this.resourcesConfig,\n }, 'Configure', AMPLIFY_SYMBOL);\n this.notifyOAuthListener();\n this.isConfigured = true;\n }\n /**\n * Provides access to the current back-end resource configuration for the Library.\n *\n * @returns Returns the immutable back-end resource configuration.\n */\n getConfig() {\n if (!this.isConfigured) {\n // eslint-disable-next-line no-console\n console.warn(`Amplify has not been configured. Please call Amplify.configure() before using this service.`);\n }\n return this.resourcesConfig;\n }\n /** @internal */\n [ADD_OAUTH_LISTENER](listener) {\n if (this.resourcesConfig.Auth?.Cognito.loginWith?.oauth) {\n // when Amplify has been configured with a valid OAuth config while adding the listener, run it directly\n listener(this.resourcesConfig.Auth?.Cognito);\n }\n else {\n // otherwise register the listener and run it later when Amplify gets configured with a valid oauth config\n this.oAuthListener = listener;\n }\n }\n notifyOAuthListener() {\n if (!this.resourcesConfig.Auth?.Cognito.loginWith?.oauth ||\n !this.oAuthListener) {\n return;\n }\n this.oAuthListener(this.resourcesConfig.Auth?.Cognito);\n // the listener should only be notified once with a valid oauth config\n this.oAuthListener = undefined;\n }\n}\n/**\n * The `Amplify` utility is used to configure the library.\n *\n * @remarks\n * `Amplify` orchestrates cross-category communication within the library.\n */\nconst Amplify = new AmplifyClass();\n\nexport { Amplify, AmplifyClass };\n//# sourceMappingURL=Amplify.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst fetchAuthSession = (amplify, options) => {\n return amplify.Auth.fetchAuthSession(options);\n};\n\nexport { fetchAuthSession };\n//# sourceMappingURL=fetchAuthSession.mjs.map\n","import { Amplify } from '../Amplify.mjs';\nimport { fetchAuthSession as fetchAuthSession$1 } from './internal/fetchAuthSession.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Fetch the auth session including the tokens and credentials if they are available. By default it\n * will automatically refresh expired auth tokens if a valid refresh token is present. You can force a refresh\n * of non-expired tokens with `{ forceRefresh: true }` input.\n *\n * @param options - Options configuring the fetch behavior.\n * @throws {@link AuthError} - Throws error when session information cannot be refreshed.\n * @returns Promise<AuthSession>\n */\nconst fetchAuthSession = (options) => {\n return fetchAuthSession$1(Amplify, options);\n};\n\nexport { fetchAuthSession };\n//# sourceMappingURL=fetchAuthSession.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst MAX_DELAY_MS = 5 * 60 * 1000;\n\nexport { MAX_DELAY_MS };\n//# sourceMappingURL=constants.mjs.map\n","import { MAX_DELAY_MS } from './constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * @private\n * Internal use of Amplify only\n */\nfunction jitteredBackoff(maxDelayMs = MAX_DELAY_MS) {\n const BASE_TIME_MS = 100;\n const JITTER_FACTOR = 100;\n return attempt => {\n const delay = 2 ** attempt * BASE_TIME_MS + JITTER_FACTOR * Math.random();\n return delay > maxDelayMs ? false : delay;\n };\n}\n\nexport { jitteredBackoff };\n//# sourceMappingURL=jitteredBackoff.mjs.map\n","import { v4 } from 'uuid';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst amplifyUuid = v4;\n\nexport { amplifyUuid };\n//# sourceMappingURL=index.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst AmplifyUrl = URL;\nconst AmplifyUrlSearchParams = URLSearchParams;\n\nexport { AmplifyUrl, AmplifyUrlSearchParams };\n//# sourceMappingURL=index.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns signed headers.\n *\n * @param headers `headers` from the request.\n * @returns List of headers included in canonical headers, separated by semicolons (;). This indicates which headers\n * are part of the signing process. Header names must use lowercase characters and must appear in alphabetical order.\n *\n * @internal\n */\nconst getSignedHeaders = (headers) => Object.keys(headers)\n .map(key => key.toLowerCase())\n .sort()\n .join(';');\n\nexport { getSignedHeaders };\n//# sourceMappingURL=getSignedHeaders.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// query params\nconst ALGORITHM_QUERY_PARAM = 'X-Amz-Algorithm';\nconst AMZ_DATE_QUERY_PARAM = 'X-Amz-Date';\nconst CREDENTIAL_QUERY_PARAM = 'X-Amz-Credential';\nconst EXPIRES_QUERY_PARAM = 'X-Amz-Expires';\nconst REGION_SET_PARAM = 'X-Amz-Region-Set';\nconst SIGNATURE_QUERY_PARAM = 'X-Amz-Signature';\nconst SIGNED_HEADERS_QUERY_PARAM = 'X-Amz-SignedHeaders';\nconst TOKEN_QUERY_PARAM = 'X-Amz-Security-Token';\n// headers\nconst AUTH_HEADER = 'authorization';\nconst HOST_HEADER = 'host';\nconst AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase();\nconst TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase();\n// identifiers\nconst KEY_TYPE_IDENTIFIER = 'aws4_request';\nconst SHA256_ALGORITHM_IDENTIFIER = 'AWS4-HMAC-SHA256';\nconst SIGNATURE_IDENTIFIER = 'AWS4';\n// preset values\nconst EMPTY_HASH = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';\nconst UNSIGNED_PAYLOAD = 'UNSIGNED-PAYLOAD';\n\nexport { ALGORITHM_QUERY_PARAM, AMZ_DATE_HEADER, AMZ_DATE_QUERY_PARAM, AUTH_HEADER, CREDENTIAL_QUERY_PARAM, EMPTY_HASH, EXPIRES_QUERY_PARAM, HOST_HEADER, KEY_TYPE_IDENTIFIER, REGION_SET_PARAM, SHA256_ALGORITHM_IDENTIFIER, SIGNATURE_IDENTIFIER, SIGNATURE_QUERY_PARAM, SIGNED_HEADERS_QUERY_PARAM, TOKEN_HEADER, TOKEN_QUERY_PARAM, UNSIGNED_PAYLOAD };\n//# sourceMappingURL=constants.mjs.map\n","import { KEY_TYPE_IDENTIFIER } from '../constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns the credential scope which restricts the resulting signature to the specified region and service.\n *\n * @param date Current date in the format 'YYYYMMDD'.\n * @param region AWS region in which the service resides.\n * @param service Service to which the signed request is being sent.\n *\n * @returns A string representing the credential scope with format 'YYYYMMDD/region/service/aws4_request'.\n *\n * @internal\n */\nconst getCredentialScope = (date, region, service) => `${date}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`;\n\nexport { getCredentialScope };\n//# sourceMappingURL=getCredentialScope.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns expected date strings to be used in signing.\n *\n * @param date JavaScript `Date` object.\n * @returns `FormattedDates` object containing the following:\n * - longDate: A date string in 'YYYYMMDDThhmmssZ' format\n * - shortDate: A date string in 'YYYYMMDD' format\n *\n * @internal\n */\nconst getFormattedDates = (date) => {\n const longDate = date.toISOString().replace(/[:-]|\\.\\d{3}/g, '');\n return {\n longDate,\n shortDate: longDate.slice(0, 8),\n };\n};\n\nexport { getFormattedDates };\n//# sourceMappingURL=getFormattedDates.mjs.map\n","import { getCredentialScope } from './getCredentialScope.mjs';\nimport { getFormattedDates } from './getFormattedDates.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Extracts common values used for signing both requests and urls.\n *\n * @param options `SignRequestOptions` object containing values used to construct the signature.\n * @returns Common `SigningValues` used for signing.\n *\n * @internal\n */\nconst getSigningValues = ({ credentials, signingDate = new Date(), signingRegion, signingService, uriEscapePath = true, }) => {\n // get properties from credentials\n const { accessKeyId, secretAccessKey, sessionToken } = credentials;\n // get formatted dates for signing\n const { longDate, shortDate } = getFormattedDates(signingDate);\n // copy header and set signing properties\n const credentialScope = getCredentialScope(shortDate, signingRegion, signingService);\n return {\n accessKeyId,\n credentialScope,\n longDate,\n secretAccessKey,\n sessionToken,\n shortDate,\n signingRegion,\n signingService,\n uriEscapePath,\n };\n};\n\nexport { getSigningValues };\n//# sourceMappingURL=getSigningValues.mjs.map\n","import { Sha256 } from '@aws-crypto/sha256-js';\nimport { toHex } from '@smithy/util-hex-encoding';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// TODO: V6 update to different crypto dependency?\n/**\n * Returns the hashed data a `Uint8Array`.\n *\n * @param key `SourceData` to be used as hashing key.\n * @param data Hashable `SourceData`.\n * @returns `Uint8Array` created from the data as input to a hash function.\n */\nconst getHashedData = (key, data) => {\n const sha256 = new Sha256(key ?? undefined);\n sha256.update(data);\n // TODO: V6 flip to async digest\n const hashedData = sha256.digestSync();\n return hashedData;\n};\n/**\n * Returns the hashed data as a hex string.\n *\n * @param key `SourceData` to be used as hashing key.\n * @param data Hashable `SourceData`.\n * @returns String using lowercase hexadecimal characters created from the data as input to a hash function.\n *\n * @internal\n */\nconst getHashedDataAsHex = (key, data) => {\n const hashedData = getHashedData(key, data);\n return toHex(hashedData);\n};\n\nexport { getHashedData, getHashedDataAsHex };\n//# sourceMappingURL=dataHashHelpers.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns canonical headers.\n *\n * @param headers Headers from the request.\n * @returns Request headers that will be signed, and their values, separated by newline characters. Header names must\n * use lowercase characters, must appear in alphabetical order, and must be followed by a colon (:). For the values,\n * trim any leading or trailing spaces, convert sequential spaces to a single space, and separate the values\n * for a multi-value header using commas.\n *\n * @internal\n */\nconst getCanonicalHeaders = (headers) => Object.entries(headers)\n .map(([key, value]) => ({\n key: key.toLowerCase(),\n value: value?.trim().replace(/\\s+/g, ' ') ?? '',\n}))\n .sort((a, b) => (a.key < b.key ? -1 : 1))\n .map(entry => `${entry.key}:${entry.value}\\n`)\n .join('');\n\nexport { getCanonicalHeaders };\n//# sourceMappingURL=getCanonicalHeaders.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns a canonical query string.\n *\n * @param searchParams `searchParams` from the request url.\n * @returns URL-encoded query string parameters, separated by ampersands (&). Percent-encode reserved characters,\n * including the space character. Encode names and values separately. If there are empty parameters, append the equals\n * sign to the parameter name before encoding. After encoding, sort the parameters alphabetically by key name. If there\n * is no query string, use an empty string (\"\").\n *\n * @internal\n */\nconst getCanonicalQueryString = (searchParams) => Array.from(searchParams)\n .sort(([keyA, valA], [keyB, valB]) => {\n if (keyA === keyB) {\n return valA < valB ? -1 : 1;\n }\n return keyA < keyB ? -1 : 1;\n})\n .map(([key, val]) => `${escapeUri(key)}=${escapeUri(val)}`)\n .join('&');\nconst escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode);\nconst hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`;\n\nexport { getCanonicalQueryString };\n//# sourceMappingURL=getCanonicalQueryString.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns a canonical uri.\n *\n * @param pathname `pathname` from request url.\n * @param uriEscapePath Whether to uri encode the path as part of canonical uri. It's used for S3 only where the\n * pathname is already uri encoded, and the signing process is not expected to uri encode it again. Defaults to true.\n * @returns URI-encoded version of the absolute path component URL (everything between the host and the question mark\n * character (?) that starts the query string parameters). If the absolute path is empty, a forward slash character (/).\n *\n * @internal\n */\nconst getCanonicalUri = (pathname, uriEscapePath = true) => pathname\n ? uriEscapePath\n ? encodeURIComponent(pathname).replace(/%2F/g, '/')\n : pathname\n : '/';\n\nexport { getCanonicalUri };\n//# sourceMappingURL=getCanonicalUri.mjs.map\n","import { EMPTY_HASH, UNSIGNED_PAYLOAD } from '../constants.mjs';\nimport { getHashedDataAsHex } from './dataHashHelpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns the hashed payload.\n *\n * @param body `body` (payload) from the request.\n * @returns String created using the payload in the body of the HTTP request as input to a hash function. This string\n * uses lowercase hexadecimal characters. If the payload is empty, return precalculated result of an empty hash.\n *\n * @internal\n */\nconst getHashedPayload = (body) => {\n // return precalculated empty hash if body is undefined or null\n if (body == null) {\n return EMPTY_HASH;\n }\n if (isSourceData(body)) {\n const hashedData = getHashedDataAsHex(null, body);\n return hashedData;\n }\n // Defined body is not signable. Return unsigned payload which may or may not be accepted by the service.\n return UNSIGNED_PAYLOAD;\n};\nconst isSourceData = (body) => \n// Exclude UNSIGNED_PAYLOAD constant to prevent it from being hashed as a string\nbody !== UNSIGNED_PAYLOAD &&\n (typeof body === 'string' || ArrayBuffer.isView(body) || isArrayBuffer(body));\nconst isArrayBuffer = (arg) => (typeof ArrayBuffer === 'function' && arg instanceof ArrayBuffer) ||\n Object.prototype.toString.call(arg) === '[object ArrayBuffer]';\n\nexport { getHashedPayload };\n//# sourceMappingURL=getHashedPayload.mjs.map\n","import { getCanonicalHeaders } from './getCanonicalHeaders.mjs';\nimport { getCanonicalQueryString } from './getCanonicalQueryString.mjs';\nimport { getCanonicalUri } from './getCanonicalUri.mjs';\nimport { getHashedPayload } from './getHashedPayload.mjs';\nimport { getSignedHeaders } from './getSignedHeaders.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns a canonical request.\n *\n * @param request `HttpRequest` from which to create the canonical request from.\n * @param uriEscapePath Whether to uri encode the path as part of canonical uri. It's used for S3 only where the\n * pathname is already uri encoded, and the signing process is not expected to uri encode it again. Defaults to true.\n * @returns String created by by concatenating the following strings, separated by newline characters:\n * - HTTPMethod\n * - CanonicalUri\n * - CanonicalQueryString\n * - CanonicalHeaders\n * - SignedHeaders\n * - HashedPayload\n *\n * @internal\n */\nconst getCanonicalRequest = ({ body, headers, method, url }, uriEscapePath = true) => [\n method,\n getCanonicalUri(url.pathname, uriEscapePath),\n getCanonicalQueryString(url.searchParams),\n getCanonicalHeaders(headers),\n getSignedHeaders(headers),\n getHashedPayload(body),\n].join('\\n');\n\nexport { getCanonicalRequest };\n//# sourceMappingURL=getCanonicalRequest.mjs.map\n","import { KEY_TYPE_IDENTIFIER, SIGNATURE_IDENTIFIER } from '../constants.mjs';\nimport { getHashedData } from './dataHashHelpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns a signing key to be used for signing requests.\n *\n * @param secretAccessKey AWS secret access key from credentials.\n * @param date Current date in the format 'YYYYMMDD'.\n * @param region AWS region in which the service resides.\n * @param service Service to which the signed request is being sent.\n *\n * @returns `Uint8Array` calculated from its composite parts.\n *\n * @internal\n */\nconst getSigningKey = (secretAccessKey, date, region, service) => {\n const key = `${SIGNATURE_IDENTIFIER}${secretAccessKey}`;\n const dateKey = getHashedData(key, date);\n const regionKey = getHashedData(dateKey, region);\n const serviceKey = getHashedData(regionKey, service);\n const signingKey = getHashedData(serviceKey, KEY_TYPE_IDENTIFIER);\n return signingKey;\n};\n\nexport { getSigningKey };\n//# sourceMappingURL=getSigningKey.mjs.map\n","import { SHA256_ALGORITHM_IDENTIFIER } from '../constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns a string to be signed.\n *\n * @param date Current date in the format 'YYYYMMDDThhmmssZ'.\n * @param credentialScope String representing the credential scope with format 'YYYYMMDD/region/service/aws4_request'.\n * @param hashedRequest Hashed canonical request.\n *\n * @returns A string created by by concatenating the following strings, separated by newline characters:\n * - Algorithm\n * - RequestDateTime\n * - CredentialScope\n * - HashedCanonicalRequest\n *\n * @internal\n */\nconst getStringToSign = (date, credentialScope, hashedRequest) => [SHA256_ALGORITHM_IDENTIFIER, date, credentialScope, hashedRequest].join('\\n');\n\nexport { getStringToSign };\n//# sourceMappingURL=getStringToSign.mjs.map\n","import { getHashedDataAsHex } from './dataHashHelpers.mjs';\nimport { getCanonicalRequest } from './getCanonicalRequest.mjs';\nimport { getSigningKey } from './getSigningKey.mjs';\nimport { getStringToSign } from './getStringToSign.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Calculates and returns an AWS API Signature.\n * https://docs.aws.amazon.com/IAM/latest/UserGuide/create-signed-request.html\n *\n * @param request `HttpRequest` to be signed.\n * @param signRequestOptions `SignRequestOptions` object containing values used to construct the signature.\n * @returns AWS API Signature to sign a request or url with.\n *\n * @internal\n */\nconst getSignature = (request, { credentialScope, longDate, secretAccessKey, shortDate, signingRegion, signingService, uriEscapePath, }) => {\n // step 1: create a canonical request\n const canonicalRequest = getCanonicalRequest(request, uriEscapePath);\n // step 2: create a hash of the canonical request\n const hashedRequest = getHashedDataAsHex(null, canonicalRequest);\n // step 3: create a string to sign\n const stringToSign = getStringToSign(longDate, credentialScope, hashedRequest);\n // step 4: calculate the signature\n const signature = getHashedDataAsHex(getSigningKey(secretAccessKey, shortDate, signingRegion, signingService), stringToSign);\n return signature;\n};\n\nexport { getSignature };\n//# sourceMappingURL=getSignature.mjs.map\n","import { getSignedHeaders } from './utils/getSignedHeaders.mjs';\nimport { getSigningValues } from './utils/getSigningValues.mjs';\nimport { HOST_HEADER, AMZ_DATE_HEADER, TOKEN_HEADER, SHA256_ALGORITHM_IDENTIFIER, AUTH_HEADER } from './constants.mjs';\nimport { getSignature } from './utils/getSignature.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Given a `HttpRequest`, returns a Signature Version 4 signed `HttpRequest`.\n *\n * @param request `HttpRequest` to be signed.\n * @param signRequestOptions `SignRequestOptions` object containing values used to construct the signature.\n * @returns A `HttpRequest` with authentication headers which can grant temporary access to AWS resources.\n */\nconst signRequest = (request, options) => {\n const signingValues = getSigningValues(options);\n const { accessKeyId, credentialScope, longDate, sessionToken } = signingValues;\n // create the request to sign\n const headers = { ...request.headers };\n headers[HOST_HEADER] = request.url.host;\n headers[AMZ_DATE_HEADER] = longDate;\n if (sessionToken) {\n headers[TOKEN_HEADER] = sessionToken;\n }\n const requestToSign = { ...request, headers };\n // calculate and add the signature to the request\n const signature = getSignature(requestToSign, signingValues);\n const credentialEntry = `Credential=${accessKeyId}/${credentialScope}`;\n const signedHeadersEntry = `SignedHeaders=${getSignedHeaders(headers)}`;\n const signatureEntry = `Signature=${signature}`;\n headers[AUTH_HEADER] =\n `${SHA256_ALGORITHM_IDENTIFIER} ${credentialEntry}, ${signedHeadersEntry}, ${signatureEntry}`;\n return requestToSign;\n};\n\nexport { signRequest };\n//# sourceMappingURL=signRequest.mjs.map\n","function _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\n/**\n * Return true if `value` is object-like. A value is object-like if it's not\n * `null` and has a `typeof` result of \"object\".\n */\nexport default function isObjectLike(value) {\n return _typeof(value) == 'object' && value !== null;\n}\n","// In ES2015 (or a polyfilled) environment, this will be Symbol.iterator\n// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')\nexport var SYMBOL_ITERATOR = typeof Symbol === 'function' && Symbol.iterator != null ? Symbol.iterator : '@@iterator'; // In ES2017 (or a polyfilled) environment, this will be Symbol.asyncIterator\n// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')\n\nexport var SYMBOL_ASYNC_ITERATOR = typeof Symbol === 'function' && Symbol.asyncIterator != null ? Symbol.asyncIterator : '@@asyncIterator'; // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')\n\nexport var SYMBOL_TO_STRING_TAG = typeof Symbol === 'function' && Symbol.toStringTag != null ? Symbol.toStringTag : '@@toStringTag';\n","/**\n * Represents a location in a Source.\n */\n\n/**\n * Takes a Source and a UTF-8 character offset, and returns the corresponding\n * line and column as a SourceLocation.\n */\nexport function getLocation(source, position) {\n var lineRegexp = /\\r\\n|[\\n\\r]/g;\n var line = 1;\n var column = position + 1;\n var match;\n\n while ((match = lineRegexp.exec(source.body)) && match.index < position) {\n line += 1;\n column = position + 1 - (match.index + match[0].length);\n }\n\n return {\n line: line,\n column: column\n };\n}\n","import { getLocation } from \"./location.mjs\";\n/**\n * Render a helpful description of the location in the GraphQL Source document.\n */\n\nexport function printLocation(location) {\n return printSourceLocation(location.source, getLocation(location.source, location.start));\n}\n/**\n * Render a helpful description of the location in the GraphQL Source document.\n */\n\nexport function printSourceLocation(source, sourceLocation) {\n var firstLineColumnOffset = source.locationOffset.column - 1;\n var body = whitespace(firstLineColumnOffset) + source.body;\n var lineIndex = sourceLocation.line - 1;\n var lineOffset = source.locationOffset.line - 1;\n var lineNum = sourceLocation.line + lineOffset;\n var columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;\n var columnNum = sourceLocation.column + columnOffset;\n var locationStr = \"\".concat(source.name, \":\").concat(lineNum, \":\").concat(columnNum, \"\\n\");\n var lines = body.split(/\\r\\n|[\\n\\r]/g);\n var locationLine = lines[lineIndex]; // Special case for minified documents\n\n if (locationLine.length > 120) {\n var subLineIndex = Math.floor(columnNum / 80);\n var subLineColumnNum = columnNum % 80;\n var subLines = [];\n\n for (var i = 0; i < locationLine.length; i += 80) {\n subLines.push(locationLine.slice(i, i + 80));\n }\n\n return locationStr + printPrefixedLines([[\"\".concat(lineNum), subLines[0]]].concat(subLines.slice(1, subLineIndex + 1).map(function (subLine) {\n return ['', subLine];\n }), [[' ', whitespace(subLineColumnNum - 1) + '^'], ['', subLines[subLineIndex + 1]]]));\n }\n\n return locationStr + printPrefixedLines([// Lines specified like this: [\"prefix\", \"string\"],\n [\"\".concat(lineNum - 1), lines[lineIndex - 1]], [\"\".concat(lineNum), locationLine], ['', whitespace(columnNum - 1) + '^'], [\"\".concat(lineNum + 1), lines[lineIndex + 1]]]);\n}\n\nfunction printPrefixedLines(lines) {\n var existingLines = lines.filter(function (_ref) {\n var _ = _ref[0],\n line = _ref[1];\n return line !== undefined;\n });\n var padLen = Math.max.apply(Math, existingLines.map(function (_ref2) {\n var prefix = _ref2[0];\n return prefix.length;\n }));\n return existingLines.map(function (_ref3) {\n var prefix = _ref3[0],\n line = _ref3[1];\n return leftPad(padLen, prefix) + (line ? ' | ' + line : ' |');\n }).join('\\n');\n}\n\nfunction whitespace(len) {\n return Array(len + 1).join(' ');\n}\n\nfunction leftPad(len, str) {\n return whitespace(len - str.length) + str;\n}\n","function _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _wrapNativeSuper(Class) { var _cache = typeof Map === \"function\" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== \"function\") { throw new TypeError(\"Super expression must either be null or a function\"); } if (typeof _cache !== \"undefined\") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }\n\nfunction _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _isNativeFunction(fn) { return Function.toString.call(fn).indexOf(\"[native code]\") !== -1; }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nimport isObjectLike from \"../jsutils/isObjectLike.mjs\";\nimport { SYMBOL_TO_STRING_TAG } from \"../polyfills/symbols.mjs\";\nimport { getLocation } from \"../language/location.mjs\";\nimport { printLocation, printSourceLocation } from \"../language/printLocation.mjs\";\n/**\n * A GraphQLError describes an Error found during the parse, validate, or\n * execute phases of performing a GraphQL operation. In addition to a message\n * and stack trace, it also includes information about the locations in a\n * GraphQL document and/or execution result that correspond to the Error.\n */\n\nexport var GraphQLError = /*#__PURE__*/function (_Error) {\n _inherits(GraphQLError, _Error);\n\n var _super = _createSuper(GraphQLError);\n\n /**\n * An array of { line, column } locations within the source GraphQL document\n * which correspond to this error.\n *\n * Errors during validation often contain multiple locations, for example to\n * point out two things with the same name. Errors during execution include a\n * single location, the field which produced the error.\n *\n * Enumerable, and appears in the result of JSON.stringify().\n */\n\n /**\n * An array describing the JSON-path into the execution response which\n * corresponds to this error. Only included for errors during execution.\n *\n * Enumerable, and appears in the result of JSON.stringify().\n */\n\n /**\n * An array of GraphQL AST Nodes corresponding to this error.\n */\n\n /**\n * The source GraphQL document for the first location of this error.\n *\n * Note that if this Error represents more than one node, the source may not\n * represent nodes after the first node.\n */\n\n /**\n * An array of character offsets within the source GraphQL document\n * which correspond to this error.\n */\n\n /**\n * The original error thrown from a field resolver during execution.\n */\n\n /**\n * Extension fields to add to the formatted error.\n */\n function GraphQLError(message, nodes, source, positions, path, originalError, extensions) {\n var _nodeLocations, _nodeLocations2, _nodeLocations3;\n\n var _this;\n\n _classCallCheck(this, GraphQLError);\n\n _this = _super.call(this, message);\n _this.name = 'GraphQLError';\n _this.originalError = originalError !== null && originalError !== void 0 ? originalError : undefined; // Compute list of blame nodes.\n\n _this.nodes = undefinedIfEmpty(Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined);\n var nodeLocations = [];\n\n for (var _i2 = 0, _ref3 = (_this$nodes = _this.nodes) !== null && _this$nodes !== void 0 ? _this$nodes : []; _i2 < _ref3.length; _i2++) {\n var _this$nodes;\n\n var _ref4 = _ref3[_i2];\n var loc = _ref4.loc;\n\n if (loc != null) {\n nodeLocations.push(loc);\n }\n }\n\n nodeLocations = undefinedIfEmpty(nodeLocations); // Compute locations in the source for the given nodes/positions.\n\n _this.source = source !== null && source !== void 0 ? source : (_nodeLocations = nodeLocations) === null || _nodeLocations === void 0 ? void 0 : _nodeLocations[0].source;\n _this.positions = positions !== null && positions !== void 0 ? positions : (_nodeLocations2 = nodeLocations) === null || _nodeLocations2 === void 0 ? void 0 : _nodeLocations2.map(function (loc) {\n return loc.start;\n });\n _this.locations = positions && source ? positions.map(function (pos) {\n return getLocation(source, pos);\n }) : (_nodeLocations3 = nodeLocations) === null || _nodeLocations3 === void 0 ? void 0 : _nodeLocations3.map(function (loc) {\n return getLocation(loc.source, loc.start);\n });\n _this.path = path !== null && path !== void 0 ? path : undefined;\n var originalExtensions = originalError === null || originalError === void 0 ? void 0 : originalError.extensions;\n\n if (extensions == null && isObjectLike(originalExtensions)) {\n _this.extensions = _objectSpread({}, originalExtensions);\n } else {\n _this.extensions = extensions !== null && extensions !== void 0 ? extensions : {};\n } // By being enumerable, JSON.stringify will include bellow properties in the resulting output.\n // This ensures that the simplest possible GraphQL service adheres to the spec.\n\n\n Object.defineProperties(_assertThisInitialized(_this), {\n message: {\n enumerable: true\n },\n locations: {\n enumerable: _this.locations != null\n },\n path: {\n enumerable: _this.path != null\n },\n extensions: {\n enumerable: _this.extensions != null && Object.keys(_this.extensions).length > 0\n },\n name: {\n enumerable: false\n },\n nodes: {\n enumerable: false\n },\n source: {\n enumerable: false\n },\n positions: {\n enumerable: false\n },\n originalError: {\n enumerable: false\n }\n }); // Include (non-enumerable) stack trace.\n\n if (originalError !== null && originalError !== void 0 && originalError.stack) {\n Object.defineProperty(_assertThisInitialized(_this), 'stack', {\n value: originalError.stack,\n writable: true,\n configurable: true\n });\n return _possibleConstructorReturn(_this);\n } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')\n\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(_assertThisInitialized(_this), GraphQLError);\n } else {\n Object.defineProperty(_assertThisInitialized(_this), 'stack', {\n value: Error().stack,\n writable: true,\n configurable: true\n });\n }\n\n return _this;\n }\n\n _createClass(GraphQLError, [{\n key: \"toString\",\n value: function toString() {\n return printError(this);\n } // FIXME: workaround to not break chai comparisons, should be remove in v16\n // $FlowFixMe[unsupported-syntax] Flow doesn't support computed properties yet\n\n }, {\n key: SYMBOL_TO_STRING_TAG,\n get: function get() {\n return 'Object';\n }\n }]);\n\n return GraphQLError;\n}( /*#__PURE__*/_wrapNativeSuper(Error));\n\nfunction undefinedIfEmpty(array) {\n return array === undefined || array.length === 0 ? undefined : array;\n}\n/**\n * Prints a GraphQLError to a string, representing useful location information\n * about the error's position in the source.\n */\n\n\nexport function printError(error) {\n var output = error.message;\n\n if (error.nodes) {\n for (var _i4 = 0, _error$nodes2 = error.nodes; _i4 < _error$nodes2.length; _i4++) {\n var node = _error$nodes2[_i4];\n\n if (node.loc) {\n output += '\\n\\n' + printLocation(node.loc);\n }\n }\n } else if (error.source && error.locations) {\n for (var _i6 = 0, _error$locations2 = error.locations; _i6 < _error$locations2.length; _i6++) {\n var location = _error$locations2[_i6];\n output += '\\n\\n' + printSourceLocation(error.source, location);\n }\n }\n\n return output;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nclass NonRetryableError extends Error {\n constructor() {\n super(...arguments);\n this.nonRetryable = true;\n }\n}\n\nexport { NonRetryableError };\n//# sourceMappingURL=NonRetryableError.mjs.map\n","import { MAX_DELAY_MS } from './constants.mjs';\nimport { jitteredBackoff } from './jitteredBackoff.mjs';\nimport { retry } from './retry.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * @private\n * Internal use of Amplify only\n */\nconst jitteredExponentialRetry = (functionToRetry, args, maxDelayMs = MAX_DELAY_MS, onTerminate) => retry(functionToRetry, args, jitteredBackoff(maxDelayMs), onTerminate);\n\nexport { jitteredExponentialRetry };\n//# sourceMappingURL=jitteredExponentialRetry.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction bytesToString(input) {\n return Array.from(input, byte => String.fromCodePoint(byte)).join('');\n}\n\nexport { bytesToString };\n//# sourceMappingURL=bytesToString.mjs.map\n","import { getBtoa } from '../../globalHelpers/index.mjs';\nimport { bytesToString } from './bytesToString.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst base64Encoder = {\n /**\n * Convert input to base64-encoded string\n * @param input - string to convert to base64\n * @param options - encoding options that can optionally produce a base64url string\n * @returns base64-encoded string\n */\n convert(input, options = {\n urlSafe: false,\n skipPadding: false,\n }) {\n const inputStr = typeof input === 'string' ? input : bytesToString(input);\n let encodedStr = getBtoa()(inputStr);\n // urlSafe char replacement and skipPadding options conform to the base64url spec\n // https://datatracker.ietf.org/doc/html/rfc4648#section-5\n if (options.urlSafe) {\n encodedStr = encodedStr.replace(/\\+/g, '-').replace(/\\//g, '_');\n }\n if (options.skipPadding) {\n encodedStr = encodedStr.replace(/=/g, '');\n }\n return encodedStr;\n },\n};\n\nexport { base64Encoder };\n//# sourceMappingURL=base64Encoder.mjs.map\n","export { AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst MAX_DELAY_MS = 5000;\nconst NON_RETRYABLE_CODES = [400, 401, 403];\nconst NON_RETRYABLE_ERROR_TYPES = [\n 'BadRequestException',\n 'UnauthorizedException',\n];\nconst CONNECTION_STATE_CHANGE = 'ConnectionStateChange';\nvar MESSAGE_TYPES;\n(function (MESSAGE_TYPES) {\n /**\n * Client -> Server message.\n * This message type is the first message after handshake and this will initialize AWS AppSync RealTime communication\n */\n MESSAGE_TYPES[\"GQL_CONNECTION_INIT\"] = \"connection_init\";\n /**\n * Server -> Client message\n * This message type is in case there is an issue with AWS AppSync RealTime when establishing connection\n */\n MESSAGE_TYPES[\"GQL_CONNECTION_ERROR\"] = \"connection_error\";\n /**\n * Server -> Client message.\n * This message type is for the ack response from AWS AppSync RealTime for GQL_CONNECTION_INIT message\n */\n MESSAGE_TYPES[\"GQL_CONNECTION_ACK\"] = \"connection_ack\";\n /**\n * Client -> Server message.\n * This message type is for register subscriptions with AWS AppSync RealTime\n */\n MESSAGE_TYPES[\"GQL_START\"] = \"start\";\n /**\n * Server -> Client message.\n * This message type is for the ack response from AWS AppSync RealTime for GQL_START message\n */\n MESSAGE_TYPES[\"GQL_START_ACK\"] = \"start_ack\";\n /**\n * Server -> Client message.\n * This message type is for subscription message from AWS AppSync RealTime or Events\n */\n MESSAGE_TYPES[\"DATA\"] = \"data\";\n /**\n * Server -> Client message.\n * This message type helps the client to know is still receiving messages from AWS AppSync RealTime\n */\n MESSAGE_TYPES[\"GQL_CONNECTION_KEEP_ALIVE\"] = \"ka\";\n /**\n * Client -> Server message.\n * This message type is for unregister subscriptions with AWS AppSync RealTime\n */\n MESSAGE_TYPES[\"GQL_STOP\"] = \"stop\";\n /**\n * Server -> Client message.\n * This message type is for the ack response from AWS AppSync RealTime for GQL_STOP message\n */\n MESSAGE_TYPES[\"GQL_COMPLETE\"] = \"complete\";\n /**\n * Server -> Client message.\n * This message type is for sending error messages from AWS AppSync RealTime to the client\n */\n MESSAGE_TYPES[\"GQL_ERROR\"] = \"error\";\n /**\n * Client -> Server message.\n * This message type is for registering subscriptions with Events\n */\n MESSAGE_TYPES[\"EVENT_SUBSCRIBE\"] = \"subscribe\";\n /**\n * Client -> Server message.\n * This message type is for publishing a message with Events\n */\n MESSAGE_TYPES[\"EVENT_PUBLISH\"] = \"publish\";\n /**\n * Server -> Client message.\n * Server acknowledges successful subscription\n */\n MESSAGE_TYPES[\"EVENT_SUBSCRIBE_ACK\"] = \"subscribe_success\";\n /**\n * Server -> Client message.\n * Server acknowledges successful publish\n */\n MESSAGE_TYPES[\"EVENT_PUBLISH_ACK\"] = \"publish_success\";\n /**\n * Client -> Server message.\n * This message type is for unregister subscriptions with AWS AppSync RealTime\n */\n MESSAGE_TYPES[\"EVENT_STOP\"] = \"unsubscribe\";\n /**\n * Server -> Client message.\n * This is the ack response from AWS AppSync Events to EVENT_STOP message\n */\n MESSAGE_TYPES[\"EVENT_COMPLETE\"] = \"unsubscribe_success\";\n /**\n * Server -> Client message.\n * This message type is for sending error messages from AWS AppSync Events to the client\n */\n MESSAGE_TYPES[\"EVENT_SUBSCRIBE_ERROR\"] = \"subscribe_error\";\n})(MESSAGE_TYPES || (MESSAGE_TYPES = {}));\nvar SUBSCRIPTION_STATUS;\n(function (SUBSCRIPTION_STATUS) {\n SUBSCRIPTION_STATUS[SUBSCRIPTION_STATUS[\"PENDING\"] = 0] = \"PENDING\";\n SUBSCRIPTION_STATUS[SUBSCRIPTION_STATUS[\"CONNECTED\"] = 1] = \"CONNECTED\";\n SUBSCRIPTION_STATUS[SUBSCRIPTION_STATUS[\"FAILED\"] = 2] = \"FAILED\";\n})(SUBSCRIPTION_STATUS || (SUBSCRIPTION_STATUS = {}));\nvar SOCKET_STATUS;\n(function (SOCKET_STATUS) {\n SOCKET_STATUS[SOCKET_STATUS[\"CLOSED\"] = 0] = \"CLOSED\";\n SOCKET_STATUS[SOCKET_STATUS[\"READY\"] = 1] = \"READY\";\n SOCKET_STATUS[SOCKET_STATUS[\"CONNECTING\"] = 2] = \"CONNECTING\";\n})(SOCKET_STATUS || (SOCKET_STATUS = {}));\nconst AWS_APPSYNC_REALTIME_HEADERS = {\n accept: 'application/json, text/javascript',\n 'content-encoding': 'amz-1.0',\n 'content-type': 'application/json; charset=UTF-8',\n};\n/**\n * Time in milleseconds to wait for GQL_CONNECTION_INIT message\n */\nconst CONNECTION_INIT_TIMEOUT = 15000;\n/**\n * Time in milleseconds to wait for GQL_START_ACK message\n */\nconst START_ACK_TIMEOUT = 15000;\n/**\n * Default Time in milleseconds to wait for GQL_CONNECTION_KEEP_ALIVE message\n */\nconst DEFAULT_KEEP_ALIVE_TIMEOUT = 5 * 60 * 1000;\n/**\n * Default Time in milleseconds between monitoring checks of keep alive status\n */\nconst DEFAULT_KEEP_ALIVE_HEARTBEAT_TIMEOUT = 5 * 1000;\n/**\n * Default Time in milleseconds to alert for missed GQL_CONNECTION_KEEP_ALIVE message\n */\nconst DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT = 65 * 1000;\n/**\n * Default delay time in milleseconds between when reconnect is triggered vs when it is attempted\n */\nconst RECONNECT_DELAY = 5 * 1000;\n/**\n * Default interval time in milleseconds between when reconnect is re-attempted\n */\nconst RECONNECT_INTERVAL = 60 * 1000;\n\nexport { AWS_APPSYNC_REALTIME_HEADERS, CONNECTION_INIT_TIMEOUT, CONNECTION_STATE_CHANGE, DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT, DEFAULT_KEEP_ALIVE_HEARTBEAT_TIMEOUT, DEFAULT_KEEP_ALIVE_TIMEOUT, MAX_DELAY_MS, MESSAGE_TYPES, NON_RETRYABLE_CODES, NON_RETRYABLE_ERROR_TYPES, RECONNECT_DELAY, RECONNECT_INTERVAL, SOCKET_STATUS, START_ACK_TIMEOUT, SUBSCRIPTION_STATUS };\n//# sourceMappingURL=constants.mjs.map\n","var CONTROL_MSG;\n(function (CONTROL_MSG) {\n CONTROL_MSG[\"CONNECTION_CLOSED\"] = \"Connection closed\";\n CONTROL_MSG[\"CONNECTION_FAILED\"] = \"Connection failed\";\n CONTROL_MSG[\"REALTIME_SUBSCRIPTION_INIT_ERROR\"] = \"AppSync Realtime subscription init error\";\n CONTROL_MSG[\"SUBSCRIPTION_ACK\"] = \"Subscription ack\";\n CONTROL_MSG[\"TIMEOUT_DISCONNECT\"] = \"Timeout disconnect\";\n})(CONTROL_MSG || (CONTROL_MSG = {}));\n/** @enum {string} */\nvar ConnectionState;\n(function (ConnectionState) {\n /*\n * The connection is alive and healthy\n */\n ConnectionState[\"Connected\"] = \"Connected\";\n /*\n * The connection is alive, but the connection is offline\n */\n ConnectionState[\"ConnectedPendingNetwork\"] = \"ConnectedPendingNetwork\";\n /*\n * The connection has been disconnected while in use\n */\n ConnectionState[\"ConnectionDisrupted\"] = \"ConnectionDisrupted\";\n /*\n * The connection has been disconnected and the network is offline\n */\n ConnectionState[\"ConnectionDisruptedPendingNetwork\"] = \"ConnectionDisruptedPendingNetwork\";\n /*\n * The connection is in the process of connecting\n */\n ConnectionState[\"Connecting\"] = \"Connecting\";\n /*\n * The connection is not in use and is being disconnected\n */\n ConnectionState[\"ConnectedPendingDisconnect\"] = \"ConnectedPendingDisconnect\";\n /*\n * The connection is not in use and has been disconnected\n */\n ConnectionState[\"Disconnected\"] = \"Disconnected\";\n /*\n * The connection is alive, but a keep alive message has been missed\n */\n ConnectionState[\"ConnectedPendingKeepAlive\"] = \"ConnectedPendingKeepAlive\";\n})(ConnectionState || (ConnectionState = {}));\n\nexport { CONTROL_MSG, ConnectionState };\n//# sourceMappingURL=PubSub.mjs.map\n","import { Reachability } from '@aws-amplify/core/internals/utils';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst ReachabilityMonitor = () => new Reachability().networkMonitor();\n\nexport { ReachabilityMonitor };\n//# sourceMappingURL=index.mjs.map\n","import { Observable, map, filter } from 'rxjs';\nimport { ConnectionState } from '../types/PubSub.mjs';\nimport { ReachabilityMonitor } from './ReachabilityMonitor/index.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst CONNECTION_CHANGE = {\n KEEP_ALIVE_MISSED: { keepAliveState: 'unhealthy' },\n KEEP_ALIVE: { keepAliveState: 'healthy' },\n CONNECTION_ESTABLISHED: { connectionState: 'connected' },\n CONNECTION_FAILED: {\n intendedConnectionState: 'disconnected',\n connectionState: 'disconnected',\n },\n CLOSING_CONNECTION: { intendedConnectionState: 'disconnected' },\n OPENING_CONNECTION: {\n intendedConnectionState: 'connected',\n connectionState: 'connecting',\n },\n CLOSED: { connectionState: 'disconnected' },\n ONLINE: { networkState: 'connected' },\n OFFLINE: { networkState: 'disconnected' },\n};\nclass ConnectionStateMonitor {\n constructor() {\n this._networkMonitoringSubscription = undefined;\n this._linkedConnectionState = {\n networkState: 'connected',\n connectionState: 'disconnected',\n intendedConnectionState: 'disconnected',\n keepAliveState: 'healthy',\n };\n // Attempt to update the state with the current actual network state\n this._initialNetworkStateSubscription = ReachabilityMonitor().subscribe(({ online }) => {\n this.record(online ? CONNECTION_CHANGE.ONLINE : CONNECTION_CHANGE.OFFLINE);\n this._initialNetworkStateSubscription?.unsubscribe();\n });\n this._linkedConnectionStateObservable =\n new Observable(connectionStateObserver => {\n connectionStateObserver.next(this._linkedConnectionState);\n this._linkedConnectionStateObserver = connectionStateObserver;\n });\n }\n /**\n * Turn network state monitoring on if it isn't on already\n */\n enableNetworkMonitoring() {\n // If no initial network state was discovered, stop trying\n this._initialNetworkStateSubscription?.unsubscribe();\n // Maintain the network state based on the reachability monitor\n if (this._networkMonitoringSubscription === undefined) {\n this._networkMonitoringSubscription = ReachabilityMonitor().subscribe(({ online }) => {\n this.record(online ? CONNECTION_CHANGE.ONLINE : CONNECTION_CHANGE.OFFLINE);\n });\n }\n }\n /**\n * Turn network state monitoring off if it isn't off already\n */\n disableNetworkMonitoring() {\n this._networkMonitoringSubscription?.unsubscribe();\n this._networkMonitoringSubscription = undefined;\n }\n /**\n * Get the observable that allows us to monitor the connection state\n *\n * @returns {Observable<ConnectionState>} - The observable that emits ConnectionState updates\n */\n get connectionStateObservable() {\n let previous;\n // The linked state aggregates state changes to any of the network, connection,\n // intendedConnection and keepAliveHealth. Some states will change these independent\n // states without changing the overall connection state.\n // After translating from linked states to ConnectionState, then remove any duplicates\n return this._linkedConnectionStateObservable\n .pipe(map(value => {\n return this.connectionStatesTranslator(value);\n }))\n .pipe(filter(current => {\n const toInclude = current !== previous;\n previous = current;\n return toInclude;\n }));\n }\n /*\n * Updates local connection state and emits the full state to the observer.\n */\n record(statusUpdates) {\n // Maintain the network monitor\n if (statusUpdates.intendedConnectionState === 'connected') {\n this.enableNetworkMonitoring();\n }\n else if (statusUpdates.intendedConnectionState === 'disconnected') {\n this.disableNetworkMonitoring();\n }\n // Maintain the socket state\n const newSocketStatus = {\n ...this._linkedConnectionState,\n ...statusUpdates,\n };\n this._linkedConnectionState = { ...newSocketStatus };\n this._linkedConnectionStateObserver?.next(this._linkedConnectionState);\n }\n /*\n * Translate the ConnectionState structure into a specific ConnectionState string literal union\n */\n connectionStatesTranslator({ connectionState, networkState, intendedConnectionState, keepAliveState, }) {\n if (connectionState === 'connected' && networkState === 'disconnected')\n return ConnectionState.ConnectedPendingNetwork;\n if (connectionState === 'connected' &&\n intendedConnectionState === 'disconnected')\n return ConnectionState.ConnectedPendingDisconnect;\n if (connectionState === 'disconnected' &&\n intendedConnectionState === 'connected' &&\n networkState === 'disconnected')\n return ConnectionState.ConnectionDisruptedPendingNetwork;\n if (connectionState === 'disconnected' &&\n intendedConnectionState === 'connected')\n return ConnectionState.ConnectionDisrupted;\n if (connectionState === 'connected' && keepAliveState === 'unhealthy')\n return ConnectionState.ConnectedPendingKeepAlive;\n // All remaining states directly correspond to the connection state\n if (connectionState === 'connecting')\n return ConnectionState.Connecting;\n if (connectionState === 'disconnected')\n return ConnectionState.Disconnected;\n return ConnectionState.Connected;\n }\n}\n\nexport { CONNECTION_CHANGE, ConnectionStateMonitor };\n//# sourceMappingURL=ConnectionStateMonitor.mjs.map\n","import { RECONNECT_INTERVAL, RECONNECT_DELAY } from '../Providers/constants.mjs';\n\nvar ReconnectEvent;\n(function (ReconnectEvent) {\n ReconnectEvent[\"START_RECONNECT\"] = \"START_RECONNECT\";\n ReconnectEvent[\"HALT_RECONNECT\"] = \"HALT_RECONNECT\";\n})(ReconnectEvent || (ReconnectEvent = {}));\n/**\n * Captures the reconnect event logic used to determine when to reconnect to PubSub providers.\n * Reconnect attempts are delayed by 5 seconds to let the interface settle.\n * Attempting to reconnect only once creates unrecoverable states when the network state isn't\n * supported by the browser, so this keeps retrying every minute until halted.\n */\nclass ReconnectionMonitor {\n constructor() {\n this.reconnectObservers = [];\n }\n /**\n * Add reconnect observer to the list of observers to alert on reconnect\n */\n addObserver(reconnectObserver) {\n this.reconnectObservers.push(reconnectObserver);\n }\n /**\n * Given a reconnect event, start the appropriate behavior\n */\n record(event) {\n if (event === ReconnectEvent.START_RECONNECT) {\n // If the reconnection hasn't been started\n if (this.reconnectSetTimeoutId === undefined &&\n this.reconnectIntervalId === undefined) {\n this.reconnectSetTimeoutId = setTimeout(() => {\n // Reconnect now\n this._triggerReconnect();\n // Retry reconnect every periodically until it works\n this.reconnectIntervalId = setInterval(() => {\n this._triggerReconnect();\n }, RECONNECT_INTERVAL);\n }, RECONNECT_DELAY);\n }\n }\n if (event === ReconnectEvent.HALT_RECONNECT) {\n if (this.reconnectIntervalId) {\n clearInterval(this.reconnectIntervalId);\n this.reconnectIntervalId = undefined;\n }\n if (this.reconnectSetTimeoutId) {\n clearTimeout(this.reconnectSetTimeoutId);\n this.reconnectSetTimeoutId = undefined;\n }\n }\n }\n /**\n * Complete all reconnect observers\n */\n close() {\n this.reconnectObservers.forEach(reconnectObserver => {\n reconnectObserver.complete?.();\n });\n }\n _triggerReconnect() {\n this.reconnectObservers.forEach(reconnectObserver => {\n reconnectObserver.next?.();\n });\n }\n}\n\nexport { ReconnectEvent, ReconnectionMonitor };\n//# sourceMappingURL=ReconnectionMonitor.mjs.map\n","import { AmplifyUrlSearchParams, AmplifyUrl } from '@aws-amplify/core/internals/utils';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst protocol = 'wss://';\nconst standardDomainPattern = /^https:\\/\\/\\w{26}\\.appsync-api\\.\\w{2}(?:(?:-\\w{2,})+)-\\d\\.amazonaws.com(?:\\.cn)?\\/graphql$/i;\nconst eventDomainPattern = /^https:\\/\\/\\w{26}\\.\\w+-api\\.\\w{2}(?:(?:-\\w{2,})+)-\\d\\.amazonaws.com(?:\\.cn)?\\/event$/i;\nconst customDomainPath = '/realtime';\nconst isCustomDomain = (url) => {\n return url.match(standardDomainPattern) === null;\n};\nconst isEventDomain = (url) => url.match(eventDomainPattern) !== null;\nconst getRealtimeEndpointUrl = (appSyncGraphqlEndpoint) => {\n let realtimeEndpoint = appSyncGraphqlEndpoint ?? '';\n if (isEventDomain(realtimeEndpoint)) {\n realtimeEndpoint = realtimeEndpoint\n .concat(customDomainPath)\n .replace('ddpg-api', 'grt-gamma')\n .replace('appsync-api', 'appsync-realtime-api');\n }\n else if (isCustomDomain(realtimeEndpoint)) {\n realtimeEndpoint = realtimeEndpoint.concat(customDomainPath);\n }\n else {\n realtimeEndpoint = realtimeEndpoint\n .replace('appsync-api', 'appsync-realtime-api')\n .replace('gogi-beta', 'grt-beta')\n .replace('ddpg-api', 'grt-gamma');\n }\n realtimeEndpoint = realtimeEndpoint\n .replace('https://', protocol)\n .replace('http://', protocol);\n return new AmplifyUrl(realtimeEndpoint);\n};\n/**\n * Strips out `Authorization` header if present\n */\nconst extractNonAuthHeaders = (headers) => {\n if (!headers) {\n return {};\n }\n if ('Authorization' in headers) {\n const { Authorization: _, ...nonAuthHeaders } = headers;\n return nonAuthHeaders;\n }\n return headers;\n};\n/**\n *\n * @param headers - http headers\n * @returns uri-encoded query parameters derived from custom headers\n */\nconst queryParamsFromCustomHeaders = (headers) => {\n const nonAuthHeaders = extractNonAuthHeaders(headers);\n const params = new AmplifyUrlSearchParams();\n Object.entries(nonAuthHeaders).forEach(([k, v]) => {\n params.append(k, v);\n });\n return params;\n};\n/**\n * Normalizes AppSync realtime endpoint URL\n *\n * @param appSyncGraphqlEndpoint - AppSync endpointUri from config\n * @param urlParams - URLSearchParams\n * @returns fully resolved string realtime endpoint URL\n */\nconst realtimeUrlWithQueryString = (appSyncGraphqlEndpoint, urlParams) => {\n const realtimeEndpointUrl = getRealtimeEndpointUrl(appSyncGraphqlEndpoint);\n // preserves any query params a customer might manually set in the configuration\n const existingParams = new AmplifyUrlSearchParams(realtimeEndpointUrl.search);\n for (const [k, v] of urlParams.entries()) {\n existingParams.append(k, v);\n }\n realtimeEndpointUrl.search = existingParams.toString();\n return realtimeEndpointUrl.toString();\n};\n// TODO: move to separate file?\nconst additionalHeadersFromOptions = async (options) => {\n const { appSyncGraphqlEndpoint, query, libraryConfigHeaders = () => ({}), additionalHeaders = {}, authToken, } = options;\n let additionalCustomHeaders = {};\n const _libraryConfigHeaders = await libraryConfigHeaders();\n if (typeof additionalHeaders === 'function') {\n const requestOptions = {\n url: appSyncGraphqlEndpoint || '',\n queryString: query || '',\n };\n additionalCustomHeaders = await additionalHeaders(requestOptions);\n }\n else {\n additionalCustomHeaders = additionalHeaders;\n }\n // if an authorization header is set, have the explicit, operation-level authToken take precedence\n if (authToken) {\n additionalCustomHeaders = {\n ...additionalCustomHeaders,\n Authorization: authToken,\n };\n }\n return {\n additionalCustomHeaders,\n libraryConfigHeaders: _libraryConfigHeaders,\n };\n};\n\nexport { additionalHeadersFromOptions, getRealtimeEndpointUrl, isCustomDomain, queryParamsFromCustomHeaders, realtimeUrlWithQueryString };\n//# sourceMappingURL=appsyncUrl.mjs.map\n","import { ConsoleLogger, fetchAuthSession } from '@aws-amplify/core';\nimport { signRequest } from '@aws-amplify/core/internals/aws-client-utils';\nimport { AmplifyUrl } from '@aws-amplify/core/internals/utils';\nimport { AWS_APPSYNC_REALTIME_HEADERS } from '../constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst logger = new ConsoleLogger('AWSAppSyncRealTimeProvider Auth');\nconst awsAuthTokenHeader = async ({ host }) => {\n const session = await fetchAuthSession();\n return {\n Authorization: session?.tokens?.accessToken?.toString(),\n host,\n };\n};\nconst awsRealTimeApiKeyHeader = async ({ apiKey, host, }) => {\n const dt = new Date();\n const dtStr = dt.toISOString().replace(/[:-]|\\.\\d{3}/g, '');\n return {\n host,\n 'x-amz-date': dtStr,\n 'x-api-key': apiKey,\n };\n};\nconst awsRealTimeIAMHeader = async ({ payload, canonicalUri, appSyncGraphqlEndpoint, region, }) => {\n const endpointInfo = {\n region,\n service: 'appsync',\n };\n const creds = (await fetchAuthSession()).credentials;\n const request = {\n url: `${appSyncGraphqlEndpoint}${canonicalUri}`,\n data: payload,\n method: 'POST',\n headers: { ...AWS_APPSYNC_REALTIME_HEADERS },\n };\n const signedParams = signRequest({\n headers: request.headers,\n method: request.method,\n url: new AmplifyUrl(request.url),\n body: request.data,\n }, {\n credentials: creds,\n signingRegion: endpointInfo.region,\n signingService: endpointInfo.service,\n });\n return signedParams.headers;\n};\nconst customAuthHeader = async ({ host, additionalCustomHeaders, }) => {\n /**\n * If `additionalHeaders` was provided to the subscription as a function,\n * the headers that are returned by that function will already have been\n * provided before this function is called.\n */\n if (!additionalCustomHeaders?.Authorization) {\n throw new Error('No auth token specified');\n }\n return {\n Authorization: additionalCustomHeaders.Authorization,\n host,\n };\n};\nconst awsRealTimeHeaderBasedAuth = async ({ apiKey, authenticationType, canonicalUri, appSyncGraphqlEndpoint, region, additionalCustomHeaders, payload, }) => {\n const headerHandler = {\n apiKey: awsRealTimeApiKeyHeader,\n iam: awsRealTimeIAMHeader,\n oidc: awsAuthTokenHeader,\n userPool: awsAuthTokenHeader,\n lambda: customAuthHeader,\n none: customAuthHeader,\n };\n if (!authenticationType || !headerHandler[authenticationType]) {\n logger.debug(`Authentication type ${authenticationType} not supported`);\n return undefined;\n }\n else {\n const handler = headerHandler[authenticationType];\n const host = appSyncGraphqlEndpoint\n ? new AmplifyUrl(appSyncGraphqlEndpoint).host\n : undefined;\n const resolvedApiKey = authenticationType === 'apiKey' ? apiKey : undefined;\n logger.debug(`Authenticating with ${JSON.stringify(authenticationType)}`);\n const result = await handler({\n payload,\n canonicalUri,\n appSyncGraphqlEndpoint,\n apiKey: resolvedApiKey,\n region,\n host,\n additionalCustomHeaders,\n });\n return result;\n }\n};\n\nexport { awsRealTimeHeaderBasedAuth };\n//# sourceMappingURL=authHeaders.mjs.map\n","import { Observable } from 'rxjs';\nimport { GraphQLError } from 'graphql';\nimport { ConsoleLogger, Hub } from '@aws-amplify/core';\nimport { NonRetryableError, amplifyUuid, isNonRetryableError, base64Encoder, jitteredExponentialRetry, AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils';\nimport { ConnectionState, CONTROL_MSG } from '../../types/PubSub.mjs';\nimport { SOCKET_STATUS, NON_RETRYABLE_CODES, NON_RETRYABLE_ERROR_TYPES, SUBSCRIPTION_STATUS, START_ACK_TIMEOUT, DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT, MESSAGE_TYPES, MAX_DELAY_MS, CONNECTION_INIT_TIMEOUT, DEFAULT_KEEP_ALIVE_HEARTBEAT_TIMEOUT, CONNECTION_STATE_CHANGE } from '../constants.mjs';\nimport { ConnectionStateMonitor, CONNECTION_CHANGE } from '../../utils/ConnectionStateMonitor.mjs';\nimport { ReconnectionMonitor, ReconnectEvent } from '../../utils/ReconnectionMonitor.mjs';\nimport { additionalHeadersFromOptions, queryParamsFromCustomHeaders, realtimeUrlWithQueryString } from './appsyncUrl.mjs';\nimport { awsRealTimeHeaderBasedAuth } from './authHeaders.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst dispatchApiEvent = (payload) => {\n Hub.dispatch('api', payload, 'PubSub', AMPLIFY_SYMBOL);\n};\nclass AWSWebSocketProvider {\n constructor(args) {\n this.subscriptionObserverMap = new Map();\n this.allowNoSubscriptions = false;\n this.socketStatus = SOCKET_STATUS.CLOSED;\n this.keepAliveTimestamp = Date.now();\n this.promiseArray = [];\n this.connectionStateMonitor = new ConnectionStateMonitor();\n this.reconnectionMonitor = new ReconnectionMonitor();\n /**\n * Open WebSocket connection & perform handshake\n * Ref: https://docs.aws.amazon.com/appsync/latest/devguide/real-time-websocket-client.html#appsynclong-real-time-websocket-client-implementation-guide-for-graphql-subscriptions\n *\n * @param subprotocol -\n */\n this._establishConnection = async (awsRealTimeUrl, subprotocol) => {\n this.logger.debug(`Establishing WebSocket connection to ${awsRealTimeUrl}`);\n try {\n await this._openConnection(awsRealTimeUrl, subprotocol);\n await this._initiateHandshake();\n }\n catch (err) {\n const { errorType, errorCode } = err;\n if (NON_RETRYABLE_CODES.includes(errorCode) ||\n // Event API does not currently return `errorCode`. This may change in the future.\n // For now fall back to also checking known non-retryable error types\n NON_RETRYABLE_ERROR_TYPES.includes(errorType)) {\n throw new NonRetryableError(errorType);\n }\n else if (errorType) {\n throw new Error(errorType);\n }\n else {\n throw err;\n }\n }\n };\n this.logger = new ConsoleLogger(args.providerName);\n this.wsProtocolName = args.wsProtocolName;\n this.wsConnectUri = args.connectUri;\n this.connectionStateMonitorSubscription =\n this._startConnectionStateMonitoring();\n }\n /**\n * Mark the socket closed and release all active listeners\n */\n close() {\n // Mark the socket closed both in status and the connection monitor\n this.socketStatus = SOCKET_STATUS.CLOSED;\n this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_FAILED);\n // Turn off the subscription monitor Hub publishing\n this.connectionStateMonitorSubscription.unsubscribe();\n // Complete all reconnect observers\n this.reconnectionMonitor.close();\n return new Promise((resolve, reject) => {\n if (this.awsRealTimeSocket) {\n this.awsRealTimeSocket.onclose = (_) => {\n this._closeSocket();\n this.subscriptionObserverMap = new Map();\n this.awsRealTimeSocket = undefined;\n resolve();\n };\n this.awsRealTimeSocket.onerror = (err) => {\n reject(err);\n };\n this.awsRealTimeSocket.close();\n }\n else {\n resolve();\n }\n });\n }\n subscribe(options, customUserAgentDetails) {\n return new Observable(observer => {\n if (!options?.appSyncGraphqlEndpoint) {\n observer.error({\n errors: [\n {\n ...new GraphQLError(`Subscribe only available for AWS AppSync endpoint`),\n },\n ],\n });\n observer.complete();\n return;\n }\n let subscriptionStartInProgress = false;\n const subscriptionId = amplifyUuid();\n const startSubscription = () => {\n if (!subscriptionStartInProgress) {\n subscriptionStartInProgress = true;\n this._startSubscriptionWithAWSAppSyncRealTime({\n options,\n observer,\n subscriptionId,\n customUserAgentDetails,\n })\n .catch(err => {\n this.logger.debug(`${CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR}: ${err}`);\n this._closeSocket();\n })\n .finally(() => {\n subscriptionStartInProgress = false;\n });\n }\n };\n // Add an observable to the reconnection list to manage reconnection for this subscription\n const reconnectSubscription = new Observable(reconnectSubscriptionObserver => {\n this.reconnectionMonitor.addObserver(reconnectSubscriptionObserver);\n }).subscribe(() => {\n startSubscription();\n });\n startSubscription();\n return async () => {\n await this._cleanupSubscription(subscriptionId, reconnectSubscription);\n };\n });\n }\n async connect(options) {\n if (this.socketStatus === SOCKET_STATUS.READY) {\n return;\n }\n await this._connectWebSocket(options);\n }\n async publish(options, customUserAgentDetails) {\n if (this.socketStatus !== SOCKET_STATUS.READY) {\n throw new Error('Subscription has not been initialized');\n }\n return this._publishMessage(options, customUserAgentDetails);\n }\n async _connectWebSocket(options) {\n const { apiKey, appSyncGraphqlEndpoint, authenticationType, region } = options;\n const { additionalCustomHeaders } = await additionalHeadersFromOptions(options);\n this.connectionStateMonitor.record(CONNECTION_CHANGE.OPENING_CONNECTION);\n await this._initializeWebSocketConnection({\n apiKey,\n appSyncGraphqlEndpoint,\n authenticationType,\n region,\n additionalCustomHeaders,\n });\n }\n async _publishMessage(options, customUserAgentDetails) {\n const subscriptionId = amplifyUuid();\n const { additionalCustomHeaders, libraryConfigHeaders } = await additionalHeadersFromOptions(options);\n const serializedSubscriptionMessage = await this._prepareSubscriptionPayload({\n options,\n subscriptionId,\n customUserAgentDetails,\n additionalCustomHeaders,\n libraryConfigHeaders,\n publish: true,\n });\n return new Promise((resolve, reject) => {\n if (this.awsRealTimeSocket) {\n const publishListener = (event) => {\n const data = JSON.parse(event.data);\n if (data.id === subscriptionId && data.type === 'publish_success') {\n this.awsRealTimeSocket &&\n this.awsRealTimeSocket.removeEventListener('message', publishListener);\n cleanup();\n resolve();\n }\n if (data.errors && data.errors.length > 0) {\n const errorTypes = data.errors.map((error) => error.errorType);\n cleanup();\n reject(new Error(`Publish errors: ${errorTypes.join(', ')}`));\n }\n };\n const errorListener = (error) => {\n cleanup();\n reject(new Error(`WebSocket error: ${error}`));\n };\n const closeListener = () => {\n cleanup();\n reject(new Error('WebSocket is closed'));\n };\n const cleanup = () => {\n this.awsRealTimeSocket?.removeEventListener('message', publishListener);\n this.awsRealTimeSocket?.removeEventListener('error', errorListener);\n this.awsRealTimeSocket?.removeEventListener('close', closeListener);\n };\n this.awsRealTimeSocket.addEventListener('message', publishListener);\n this.awsRealTimeSocket.addEventListener('error', errorListener);\n this.awsRealTimeSocket.addEventListener('close', closeListener);\n this.awsRealTimeSocket.send(serializedSubscriptionMessage);\n }\n else {\n reject(new Error('WebSocket is not connected'));\n }\n });\n }\n async _cleanupSubscription(subscriptionId, reconnectSubscription) {\n // Cleanup reconnection subscription\n reconnectSubscription?.unsubscribe();\n // Cleanup after unsubscribing or observer.complete was called after _startSubscriptionWithAWSAppSyncRealTime\n try {\n // Waiting that subscription has been connected before trying to unsubscribe\n await this._waitForSubscriptionToBeConnected(subscriptionId);\n const { subscriptionState } = this.subscriptionObserverMap.get(subscriptionId) || {};\n if (!subscriptionState) {\n // subscription already unsubscribed\n return;\n }\n if (subscriptionState === SUBSCRIPTION_STATUS.CONNECTED) {\n this._sendUnsubscriptionMessage(subscriptionId);\n }\n else {\n throw new Error('Subscription never connected');\n }\n }\n catch (err) {\n this.logger.debug(`Error while unsubscribing ${err}`);\n }\n finally {\n this._removeSubscriptionObserver(subscriptionId);\n }\n }\n // Monitor the connection state and pass changes along to Hub\n _startConnectionStateMonitoring() {\n return this.connectionStateMonitor.connectionStateObservable.subscribe(connectionState => {\n dispatchApiEvent({\n event: CONNECTION_STATE_CHANGE,\n data: {\n provider: this,\n connectionState,\n },\n message: `Connection state is ${connectionState}`,\n });\n this.connectionState = connectionState;\n // Trigger START_RECONNECT when the connection is disrupted\n if (connectionState === ConnectionState.ConnectionDisrupted) {\n this.reconnectionMonitor.record(ReconnectEvent.START_RECONNECT);\n }\n // Trigger HALT_RECONNECT to halt reconnection attempts when the state is anything other than\n // ConnectionDisrupted or Connecting\n if ([\n ConnectionState.Connected,\n ConnectionState.ConnectedPendingDisconnect,\n ConnectionState.ConnectedPendingKeepAlive,\n ConnectionState.ConnectedPendingNetwork,\n ConnectionState.ConnectionDisruptedPendingNetwork,\n ConnectionState.Disconnected,\n ].includes(connectionState)) {\n this.reconnectionMonitor.record(ReconnectEvent.HALT_RECONNECT);\n }\n });\n }\n async _startSubscriptionWithAWSAppSyncRealTime({ options, observer, subscriptionId, customUserAgentDetails, }) {\n const { query, variables } = options;\n this.subscriptionObserverMap.set(subscriptionId, {\n observer,\n query: query ?? '',\n variables: variables ?? {},\n subscriptionState: SUBSCRIPTION_STATUS.PENDING,\n startAckTimeoutId: undefined,\n });\n const { additionalCustomHeaders, libraryConfigHeaders } = await additionalHeadersFromOptions(options);\n const serializedSubscriptionMessage = await this._prepareSubscriptionPayload({\n options,\n subscriptionId,\n customUserAgentDetails,\n additionalCustomHeaders,\n libraryConfigHeaders,\n });\n try {\n await this._connectWebSocket(options);\n }\n catch (err) {\n this._logStartSubscriptionError(subscriptionId, observer, err);\n return;\n }\n // Potential race condition can occur when unsubscribe is called during _initializeWebSocketConnection.\n // E.g.unsubscribe gets invoked prior to finishing WebSocket handshake or START_ACK.\n // Both subscriptionFailedCallback and subscriptionReadyCallback are used to synchronized this.\n const { subscriptionFailedCallback, subscriptionReadyCallback } = this.subscriptionObserverMap.get(subscriptionId) ?? {};\n // This must be done before sending the message in order to be listening immediately\n this.subscriptionObserverMap.set(subscriptionId, {\n observer,\n subscriptionState: SUBSCRIPTION_STATUS.PENDING,\n query: query ?? '',\n variables: variables ?? {},\n subscriptionReadyCallback,\n subscriptionFailedCallback,\n startAckTimeoutId: setTimeout(() => {\n this._timeoutStartSubscriptionAck(subscriptionId);\n }, START_ACK_TIMEOUT),\n });\n if (this.awsRealTimeSocket) {\n this.awsRealTimeSocket.send(serializedSubscriptionMessage);\n }\n }\n // Log logic for start subscription failures\n _logStartSubscriptionError(subscriptionId, observer, err) {\n this.logger.debug({ err });\n const message = String(err.message ?? '');\n // Resolving to give the state observer time to propogate the update\n this._closeSocket();\n // Capture the error only when the network didn't cause disruption\n if (this.connectionState !== ConnectionState.ConnectionDisruptedPendingNetwork) {\n // When the error is non-retriable, error out the observable\n if (isNonRetryableError(err)) {\n observer.error({\n errors: [\n {\n ...new GraphQLError(`${CONTROL_MSG.CONNECTION_FAILED}: ${message}`),\n },\n ],\n });\n }\n else {\n this.logger.debug(`${CONTROL_MSG.CONNECTION_FAILED}: ${message}`);\n }\n const { subscriptionFailedCallback } = this.subscriptionObserverMap.get(subscriptionId) || {};\n // Notify concurrent unsubscription\n if (typeof subscriptionFailedCallback === 'function') {\n subscriptionFailedCallback();\n }\n }\n }\n // Waiting that subscription has been connected before trying to unsubscribe\n async _waitForSubscriptionToBeConnected(subscriptionId) {\n const subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);\n if (subscriptionObserver) {\n const { subscriptionState } = subscriptionObserver;\n // This in case unsubscribe is invoked before sending start subscription message\n if (subscriptionState === SUBSCRIPTION_STATUS.PENDING) {\n return new Promise((resolve, reject) => {\n const { observer, subscriptionState: observedSubscriptionState, variables, query, } = subscriptionObserver;\n this.subscriptionObserverMap.set(subscriptionId, {\n observer,\n subscriptionState: observedSubscriptionState,\n variables,\n query,\n subscriptionReadyCallback: resolve,\n subscriptionFailedCallback: reject,\n });\n });\n }\n }\n }\n _sendUnsubscriptionMessage(subscriptionId) {\n try {\n if (this.awsRealTimeSocket &&\n this.awsRealTimeSocket.readyState === WebSocket.OPEN &&\n this.socketStatus === SOCKET_STATUS.READY) {\n // Preparing unsubscribe message to stop receiving messages for that subscription\n const unsubscribeMessage = this._unsubscribeMessage(subscriptionId);\n const stringToAWSRealTime = JSON.stringify(unsubscribeMessage);\n this.awsRealTimeSocket.send(stringToAWSRealTime);\n }\n }\n catch (err) {\n // If GQL_STOP is not sent because of disconnection issue, then there is nothing the client can do\n this.logger.debug({ err });\n }\n }\n _removeSubscriptionObserver(subscriptionId) {\n this.subscriptionObserverMap.delete(subscriptionId);\n // Verifying 1000ms after removing subscription in case there are new subscription unmount/mount\n if (!this.allowNoSubscriptions) {\n setTimeout(this._closeSocketIfRequired.bind(this), 1000);\n }\n }\n _closeSocketIfRequired() {\n if (this.subscriptionObserverMap.size > 0) {\n // Active subscriptions on the WebSocket\n return;\n }\n if (!this.awsRealTimeSocket) {\n this.socketStatus = SOCKET_STATUS.CLOSED;\n return;\n }\n this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSING_CONNECTION);\n if (this.awsRealTimeSocket.bufferedAmount > 0) {\n // Still data on the WebSocket\n setTimeout(this._closeSocketIfRequired.bind(this), 1000);\n }\n else {\n this.logger.debug('closing WebSocket...');\n const tempSocket = this.awsRealTimeSocket;\n // Cleaning callbacks to avoid race condition, socket still exists\n tempSocket.onclose = null;\n tempSocket.onerror = null;\n tempSocket.close(1000);\n this.awsRealTimeSocket = undefined;\n this.socketStatus = SOCKET_STATUS.CLOSED;\n this._closeSocket();\n }\n }\n maintainKeepAlive() {\n this.keepAliveTimestamp = Date.now();\n }\n keepAliveHeartbeat(connectionTimeoutMs) {\n const currentTime = Date.now();\n // Check for missed KA message\n if (currentTime - this.keepAliveTimestamp >\n DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT) {\n this.connectionStateMonitor.record(CONNECTION_CHANGE.KEEP_ALIVE_MISSED);\n }\n else {\n this.connectionStateMonitor.record(CONNECTION_CHANGE.KEEP_ALIVE);\n }\n // Recognize we are disconnected if we haven't seen messages in the keep alive timeout period\n if (currentTime - this.keepAliveTimestamp > connectionTimeoutMs) {\n this._errorDisconnect(CONTROL_MSG.TIMEOUT_DISCONNECT);\n }\n }\n _handleIncomingSubscriptionMessage(message) {\n if (typeof message.data !== 'string') {\n return;\n }\n const [isData, data] = this._handleSubscriptionData(message);\n if (isData) {\n this.maintainKeepAlive();\n return;\n }\n const { type, id, payload } = data;\n const { observer = null, query = '', variables = {}, startAckTimeoutId, subscriptionReadyCallback, subscriptionFailedCallback, } = this.subscriptionObserverMap.get(id) || {};\n if (type === MESSAGE_TYPES.GQL_START_ACK ||\n type === MESSAGE_TYPES.EVENT_SUBSCRIBE_ACK) {\n this.logger.debug(`subscription ready for ${JSON.stringify({ query, variables })}`);\n if (typeof subscriptionReadyCallback === 'function') {\n subscriptionReadyCallback();\n }\n if (startAckTimeoutId)\n clearTimeout(startAckTimeoutId);\n dispatchApiEvent({\n event: CONTROL_MSG.SUBSCRIPTION_ACK,\n data: { query, variables },\n message: 'Connection established for subscription',\n });\n const subscriptionState = SUBSCRIPTION_STATUS.CONNECTED;\n if (observer) {\n this.subscriptionObserverMap.set(id, {\n observer,\n query,\n variables,\n startAckTimeoutId: undefined,\n subscriptionState,\n subscriptionReadyCallback,\n subscriptionFailedCallback,\n });\n }\n this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_ESTABLISHED);\n return;\n }\n if (type === MESSAGE_TYPES.GQL_CONNECTION_KEEP_ALIVE) {\n this.maintainKeepAlive();\n return;\n }\n if (type === MESSAGE_TYPES.GQL_ERROR ||\n type === MESSAGE_TYPES.EVENT_SUBSCRIBE_ERROR) {\n const subscriptionState = SUBSCRIPTION_STATUS.FAILED;\n if (observer) {\n this.subscriptionObserverMap.set(id, {\n observer,\n query,\n variables,\n startAckTimeoutId,\n subscriptionReadyCallback,\n subscriptionFailedCallback,\n subscriptionState,\n });\n let errorMessage = JSON.stringify(payload ?? data);\n let isAuthError = false;\n const AUTH_ERROR_TYPES = [\n 'UnauthorizedException',\n 'Unauthorized',\n 'NotAuthorizedException',\n ];\n if (type === MESSAGE_TYPES.EVENT_SUBSCRIBE_ERROR) {\n const { errors } = JSON.parse(String(message.data));\n if (Array.isArray(errors) && errors.length > 0) {\n const error = errors[0];\n errorMessage = `${error.errorType}: ${error.message}`;\n isAuthError =\n AUTH_ERROR_TYPES.includes(error.errorType) ||\n error.message?.includes('Token expired');\n }\n }\n else if (type === MESSAGE_TYPES.GQL_ERROR &&\n payload &&\n typeof payload === 'object') {\n const { errors } = payload;\n if (Array.isArray(errors) && errors.length > 0) {\n const error = errors[0];\n isAuthError =\n AUTH_ERROR_TYPES.includes(error.errorType) ||\n error.message?.includes('Token expired');\n }\n }\n this.logger.debug(`${CONTROL_MSG.CONNECTION_FAILED}: ${errorMessage}`);\n // On auth errors, close the socket to trigger reconnection with fresh tokens.\n // The onclose handler fires _errorDisconnect → CONNECTION_CLOSED, which the\n // ConnectionStateMonitor picks up as ConnectionDisrupted and the\n // ReconnectionMonitor reconnects with refreshed credentials.\n if (isAuthError && this.awsRealTimeSocket) {\n this.logger.warn('Subscription failed due to auth error, closing WebSocket to trigger reconnection with fresh tokens');\n this.awsRealTimeSocket.close(1000, 'Auth error - reconnecting');\n }\n observer.error({\n errors: [\n {\n ...new GraphQLError(`${CONTROL_MSG.CONNECTION_FAILED}: ${errorMessage}`),\n },\n ],\n });\n if (startAckTimeoutId)\n clearTimeout(startAckTimeoutId);\n if (typeof subscriptionFailedCallback === 'function') {\n subscriptionFailedCallback();\n }\n }\n }\n }\n _errorDisconnect(msg) {\n this.logger.debug(`Disconnect error: ${msg}`);\n if (this.awsRealTimeSocket) {\n this._closeSocket();\n this.awsRealTimeSocket.close();\n }\n this.socketStatus = SOCKET_STATUS.CLOSED;\n }\n _closeSocket() {\n if (this.keepAliveHeartbeatIntervalId) {\n clearInterval(this.keepAliveHeartbeatIntervalId);\n this.keepAliveHeartbeatIntervalId = undefined;\n }\n this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);\n }\n _timeoutStartSubscriptionAck(subscriptionId) {\n const subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);\n if (subscriptionObserver) {\n const { observer, query, variables } = subscriptionObserver;\n if (!observer) {\n return;\n }\n this.subscriptionObserverMap.set(subscriptionId, {\n observer,\n query,\n variables,\n subscriptionState: SUBSCRIPTION_STATUS.FAILED,\n });\n this._closeSocket();\n this.logger.debug('timeoutStartSubscription', JSON.stringify({ query, variables }));\n }\n }\n _initializeWebSocketConnection({ appSyncGraphqlEndpoint, authenticationType, apiKey, region, additionalCustomHeaders, }) {\n if (this.socketStatus === SOCKET_STATUS.READY) {\n return;\n }\n // TODO(Eslint): refactor to now use async function as the promise executor\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n this.promiseArray.push({ res: resolve, rej: reject });\n if (this.socketStatus === SOCKET_STATUS.CLOSED) {\n try {\n this.socketStatus = SOCKET_STATUS.CONNECTING;\n // Empty payload on connect\n const payloadString = '{}';\n const authHeader = await awsRealTimeHeaderBasedAuth({\n authenticationType,\n payload: payloadString,\n canonicalUri: this.wsConnectUri,\n apiKey,\n appSyncGraphqlEndpoint,\n region,\n additionalCustomHeaders,\n });\n const headerString = authHeader ? JSON.stringify(authHeader) : '';\n // base64url-encoded string\n const encodedHeader = base64Encoder.convert(headerString, {\n urlSafe: true,\n skipPadding: true,\n });\n const authTokenSubprotocol = `header-${encodedHeader}`;\n const queryParams = queryParamsFromCustomHeaders(additionalCustomHeaders);\n const awsRealTimeUrl = realtimeUrlWithQueryString(appSyncGraphqlEndpoint, queryParams);\n await this._establishRetryableConnection(awsRealTimeUrl, authTokenSubprotocol);\n this.promiseArray.forEach(({ res }) => {\n this.logger.debug('Notifying connection successful');\n res();\n });\n this.socketStatus = SOCKET_STATUS.READY;\n this.promiseArray = [];\n }\n catch (err) {\n this.logger.debug('Connection exited with', err);\n this.promiseArray.forEach(({ rej }) => {\n rej(err);\n });\n this.promiseArray = [];\n if (this.awsRealTimeSocket &&\n this.awsRealTimeSocket.readyState === WebSocket.OPEN) {\n this.awsRealTimeSocket.close(3001);\n }\n this.awsRealTimeSocket = undefined;\n this.socketStatus = SOCKET_STATUS.CLOSED;\n }\n }\n });\n }\n async _establishRetryableConnection(awsRealTimeUrl, subprotocol) {\n this.logger.debug(`Establishing retryable connection`);\n await jitteredExponentialRetry(this._establishConnection.bind(this), [awsRealTimeUrl, subprotocol], MAX_DELAY_MS);\n }\n async _openConnection(awsRealTimeUrl, subprotocol) {\n return new Promise((resolve, reject) => {\n const newSocket = this._getNewWebSocket(awsRealTimeUrl, [\n this.wsProtocolName,\n subprotocol,\n ]);\n newSocket.onerror = () => {\n this.logger.debug(`WebSocket connection error`);\n };\n newSocket.onclose = () => {\n this._closeSocket();\n reject(new Error('Connection handshake error'));\n };\n newSocket.onopen = () => {\n this.awsRealTimeSocket = newSocket;\n resolve();\n };\n });\n }\n _getNewWebSocket(url, protocol) {\n return new WebSocket(url, protocol);\n }\n async _initiateHandshake() {\n return new Promise((resolve, reject) => {\n if (!this.awsRealTimeSocket) {\n reject(new Error('awsRealTimeSocket undefined'));\n return;\n }\n let ackOk = false;\n this.awsRealTimeSocket.onerror = error => {\n this.logger.debug(`WebSocket error ${JSON.stringify(error)}`);\n };\n this.awsRealTimeSocket.onclose = event => {\n this.logger.debug(`WebSocket closed ${event.reason}`);\n this._closeSocket();\n reject(new Error(JSON.stringify(event)));\n };\n this.awsRealTimeSocket.onmessage = (message) => {\n if (typeof message.data !== 'string') {\n return;\n }\n this.logger.debug(`subscription message from AWS AppSyncRealTime: ${message.data} `);\n const data = JSON.parse(message.data);\n const { type } = data;\n const connectionTimeoutMs = this._extractConnectionTimeout(data);\n if (type === MESSAGE_TYPES.GQL_CONNECTION_ACK) {\n ackOk = true;\n this._registerWebsocketHandlers(connectionTimeoutMs);\n resolve('Connected to AWS AppSyncRealTime');\n return;\n }\n if (type === MESSAGE_TYPES.GQL_CONNECTION_ERROR) {\n const { errorType, errorCode } = this._extractErrorCodeAndType(data);\n // TODO(Eslint): refactor to reject an Error object instead of a plain object\n // eslint-disable-next-line prefer-promise-reject-errors\n reject({ errorType, errorCode });\n }\n };\n const gqlInit = {\n type: MESSAGE_TYPES.GQL_CONNECTION_INIT,\n };\n this.awsRealTimeSocket.send(JSON.stringify(gqlInit));\n const checkAckOk = (targetAckOk) => {\n if (!targetAckOk) {\n this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_FAILED);\n reject(new Error(`Connection timeout: ack from AWSAppSyncRealTime was not received after ${CONNECTION_INIT_TIMEOUT} ms`));\n }\n };\n setTimeout(() => {\n checkAckOk(ackOk);\n }, CONNECTION_INIT_TIMEOUT);\n });\n }\n _registerWebsocketHandlers(connectionTimeoutMs) {\n if (!this.awsRealTimeSocket) {\n return;\n }\n // Set up a keep alive heartbeat for this connection\n this.keepAliveHeartbeatIntervalId = setInterval(() => {\n this.keepAliveHeartbeat(connectionTimeoutMs);\n }, DEFAULT_KEEP_ALIVE_HEARTBEAT_TIMEOUT);\n this.awsRealTimeSocket.onmessage =\n this._handleIncomingSubscriptionMessage.bind(this);\n this.awsRealTimeSocket.onerror = err => {\n this.logger.debug(err);\n this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);\n };\n this.awsRealTimeSocket.onclose = event => {\n this.logger.debug(`WebSocket closed ${event.reason}`);\n this._closeSocket();\n this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);\n };\n }\n}\n\nexport { AWSWebSocketProvider };\n//# sourceMappingURL=index.mjs.map\n","import { Amplify } from '@aws-amplify/core';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst normalizeAuth = (explicitAuthMode, defaultAuthMode) => {\n if (!explicitAuthMode) {\n return defaultAuthMode;\n }\n if (explicitAuthMode === 'identityPool') {\n return 'iam';\n }\n return explicitAuthMode;\n};\nconst configure = () => {\n const config = Amplify.getConfig();\n const eventsConfig = config.API?.Events;\n if (!eventsConfig) {\n throw new Error('Amplify configuration is missing. Have you called Amplify.configure()?');\n }\n const configAuthMode = normalizeAuth(eventsConfig.defaultAuthMode, 'apiKey');\n const options = {\n appSyncGraphqlEndpoint: eventsConfig.endpoint,\n region: eventsConfig.region,\n authenticationType: configAuthMode,\n apiKey: eventsConfig.apiKey,\n };\n return options;\n};\n/**\n * Event API expects an array of JSON strings\n *\n * @param events - JSON-serializable value or an array of values\n * @returns array of JSON strings\n */\nconst serializeEvents = (events) => {\n if (Array.isArray(events)) {\n return events.map((ev, idx) => {\n const eventJson = JSON.stringify(ev);\n if (eventJson === undefined) {\n throw new Error(`Event must be a valid JSON value. Received ${ev} at index ${idx}`);\n }\n return eventJson;\n });\n }\n const eventJson = JSON.stringify(events);\n if (eventJson === undefined) {\n throw new Error(`Event must be a valid JSON value. Received ${events}`);\n }\n return [eventJson];\n};\n\nexport { configure, normalizeAuth, serializeEvents };\n//# sourceMappingURL=utils.mjs.map\n","import { USER_AGENT_HEADER, getAmplifyUserAgent } from '@aws-amplify/core/internals/utils';\nimport { MESSAGE_TYPES, DEFAULT_KEEP_ALIVE_TIMEOUT } from '../constants.mjs';\nimport { AWSWebSocketProvider } from '../AWSWebSocketProvider/index.mjs';\nimport { awsRealTimeHeaderBasedAuth } from '../AWSWebSocketProvider/authHeaders.mjs';\nimport { serializeEvents } from '../../internals/events/utils.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst PROVIDER_NAME = 'AWSAppSyncEventsProvider';\nconst WS_PROTOCOL_NAME = 'aws-appsync-event-ws';\nconst CONNECT_URI = ''; // events does not expect a connect uri\nclass AWSAppSyncEventProvider extends AWSWebSocketProvider {\n constructor() {\n super({\n providerName: PROVIDER_NAME,\n wsProtocolName: WS_PROTOCOL_NAME,\n connectUri: CONNECT_URI,\n });\n this.allowNoSubscriptions = true;\n }\n getProviderName() {\n return PROVIDER_NAME;\n }\n async connect(options) {\n return super.connect(options);\n }\n subscribe(options, customUserAgentDetails) {\n return super.subscribe(options, customUserAgentDetails).pipe();\n }\n async publish(options, customUserAgentDetails) {\n return super.publish(options, customUserAgentDetails);\n }\n closeIfNoActiveSubscription() {\n this._closeSocketIfRequired();\n }\n async _prepareSubscriptionPayload({ options, subscriptionId, customUserAgentDetails, additionalCustomHeaders, libraryConfigHeaders, publish, }) {\n const { appSyncGraphqlEndpoint, authenticationType, query, apiKey, region, variables, } = options;\n const data = {\n channel: query,\n events: variables !== undefined ? serializeEvents(variables) : undefined,\n };\n const serializedData = JSON.stringify(data);\n const headers = {\n ...(await awsRealTimeHeaderBasedAuth({\n apiKey,\n appSyncGraphqlEndpoint,\n authenticationType,\n payload: serializedData,\n canonicalUri: '',\n region,\n additionalCustomHeaders,\n })),\n ...libraryConfigHeaders,\n ...additionalCustomHeaders,\n [USER_AGENT_HEADER]: getAmplifyUserAgent(customUserAgentDetails),\n };\n const subscriptionMessage = {\n id: subscriptionId,\n channel: query,\n events: variables !== undefined ? serializeEvents(variables) : undefined,\n authorization: {\n ...headers,\n },\n payload: {\n events: variables !== undefined ? serializeEvents(variables) : undefined,\n channel: query,\n extensions: {\n authorization: {\n ...headers,\n },\n },\n },\n type: publish\n ? MESSAGE_TYPES.EVENT_PUBLISH\n : MESSAGE_TYPES.EVENT_SUBSCRIBE,\n };\n const serializedSubscriptionMessage = JSON.stringify(subscriptionMessage);\n return serializedSubscriptionMessage;\n }\n _handleSubscriptionData(message) {\n this.logger.debug(`subscription message from AWS AppSync Events: ${message.data}`);\n const { id = '', event: payload, type, } = JSON.parse(String(message.data));\n const { observer = null, query = '', variables = {}, } = this.subscriptionObserverMap.get(id) || {};\n this.logger.debug({ id, observer, query, variables });\n if (type === MESSAGE_TYPES.DATA && payload) {\n const deserializedEvent = JSON.parse(payload);\n if (observer) {\n observer.next({ id, type, event: deserializedEvent });\n }\n else {\n this.logger.debug(`observer not found for id: ${id}`);\n }\n return [true, { id, type, payload: deserializedEvent }];\n }\n return [false, { id, type, payload }];\n }\n _unsubscribeMessage(subscriptionId) {\n return {\n id: subscriptionId,\n type: MESSAGE_TYPES.EVENT_STOP,\n };\n }\n _extractConnectionTimeout(data) {\n const { connectionTimeoutMs = DEFAULT_KEEP_ALIVE_TIMEOUT } = data;\n return connectionTimeoutMs;\n }\n _extractErrorCodeAndType(data) {\n const { errors: [{ errorType = '', errorCode = 0 } = {}] = [] } = data;\n return { errorCode, errorType };\n }\n}\nconst AppSyncEventProvider = new AWSAppSyncEventProvider();\n\nexport { AWSAppSyncEventProvider, AppSyncEventProvider };\n//# sourceMappingURL=index.mjs.map\n","import { Amplify } from '@aws-amplify/core';\nimport { amplifyUuid } from '@aws-amplify/core/internals/utils';\nimport { AppSyncEventProvider } from '../../Providers/AWSAppSyncEventsProvider/index.mjs';\nimport { appsyncRequest } from './appsyncRequest.mjs';\nimport { configure, normalizeAuth, serializeEvents } from './utils.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Keeps a list of open channels in the websocket\nconst openChannels = new Set();\n/**\n * @experimental API may change in future versions\n *\n * Establish a WebSocket connection to an Events channel\n *\n * @example\n * const channel = await events.connect(\"default/channel\")\n *\n * channel.subscribe({\n * next: (data) => { console.log(data) },\n * error: (err) => { console.error(err) },\n * })\n *\n * @example // authMode override\n * const channel = await events.connect(\"default/channel\", { authMode: \"userPool\" })\n *\n * @param channel - channel path; `<namespace>/<channel>`\n * @param options - request overrides: `authMode`, `authToken`\n *\n */\nasync function connect(channel, options) {\n const providerOptions = configure();\n providerOptions.authenticationType = normalizeAuth(options?.authMode, providerOptions.authenticationType);\n providerOptions.apiKey = options?.apiKey || providerOptions.apiKey;\n providerOptions.authToken = options?.authToken || providerOptions.authToken;\n await AppSyncEventProvider.connect(providerOptions);\n const channelId = amplifyUuid();\n openChannels.add(channelId);\n let _subscription;\n const sub = (observer, subOptions) => {\n if (!openChannels.has(channelId)) {\n throw new Error('Channel is closed');\n }\n const subscribeOptions = { ...providerOptions, query: channel };\n subscribeOptions.authenticationType = normalizeAuth(subOptions?.authMode, subscribeOptions.authenticationType);\n subscribeOptions.apiKey = subOptions?.apiKey || subscribeOptions.apiKey;\n subscribeOptions.authToken =\n subOptions?.authToken || subscribeOptions.authToken;\n _subscription = AppSyncEventProvider\n .subscribe(subscribeOptions)\n .subscribe(observer);\n return _subscription;\n };\n const pub = async (event, pubOptions) => {\n if (!openChannels.has(channelId)) {\n throw new Error('Channel is closed');\n }\n const publishOptions = {\n ...providerOptions,\n query: channel,\n variables: event,\n };\n publishOptions.authenticationType = normalizeAuth(pubOptions?.authMode, publishOptions.authenticationType);\n publishOptions.apiKey = pubOptions?.apiKey || publishOptions.apiKey;\n publishOptions.authToken =\n pubOptions?.authToken || publishOptions.authToken;\n return AppSyncEventProvider.publish(publishOptions);\n };\n const close = async () => {\n _subscription && _subscription.unsubscribe();\n openChannels.delete(channelId);\n setTimeout(() => {\n if (openChannels.size === 0) {\n AppSyncEventProvider.closeIfNoActiveSubscription();\n }\n }, 1000);\n };\n return {\n subscribe: sub,\n close,\n publish: pub,\n };\n}\n/**\n * @experimental API may change in future versions\n *\n * Publish events to a channel via HTTP request\n *\n * @example\n * await events.post(\"default/channel\", { some: \"event\" })\n *\n * @example // event batching\n * await events.post(\"default/channel\", [{ some: \"event\" }, { some: \"event2\" }])\n *\n * @example // authMode override\n * await events.post(\"default/channel\", { some: \"event\" }, { authMode: \"userPool\" })\n *\n * @param channel - channel path; `<namespace>/<channel>`\n * @param event - JSON-serializable value or an array of values\n * @param options - request overrides: `authMode`, `authToken`\n *\n * @returns void on success\n * @throws on error\n */\nasync function post(channel, event, options) {\n const providerOptions = configure();\n providerOptions.authenticationType = normalizeAuth(options?.authMode, providerOptions.authenticationType);\n providerOptions.apiKey = options?.apiKey || providerOptions.apiKey;\n providerOptions.authToken = options?.authToken || providerOptions.authToken;\n // trailing slash required in publish\n const normalizedChannelName = channel[0] === '/' ? channel : `/${channel}`;\n const publishOptions = {\n ...providerOptions,\n query: normalizedChannelName,\n variables: serializeEvents(event),\n };\n const abortController = new AbortController();\n const res = await appsyncRequest(Amplify, publishOptions, {}, abortController);\n if (res.failed?.length > 0) {\n return res.failed;\n }\n}\n/**\n * @experimental API may change in future versions\n *\n * Close WebSocket connection, disconnect listeners and reconnect observers\n *\n * @example\n * await events.closeAll()\n *\n * @returns void on success\n * @throws on error\n */\nasync function closeAll() {\n await AppSyncEventProvider.close();\n}\n\nexport { closeAll, connect, post };\n//# sourceMappingURL=index.mjs.map\n","var _a;\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const ratio = val / step;\n const roundedRatio = Math.round(ratio);\n // Use a relative epsilon scaled to the magnitude of the result\n const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);\n if (Math.abs(ratio - roundedRatio) < tolerance)\n return 0;\n return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n // Skip the probe under `jitless`: strict CSPs report the caught `new Function`\n // as a `securitypolicyviolation` even though the throw is swallowed.\n if (globalConfig.jitless) {\n return false;\n }\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n if (o instanceof Map)\n return new Map(o);\n if (o instanceof Set)\n return new Set(o);\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n \"string\",\n \"number\",\n \"bigint\",\n \"boolean\",\n \"symbol\",\n \"undefined\",\n]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n if (a._zod.def.checks?.length) {\n throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n }\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: b._zod.def.checks ?? [],\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined).\n// Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue === false) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;\n rest.path ?? (rest.path = []);\n rest.message = message;\n if (ctx?.reportInput) {\n rest.input = _input;\n }\n return rest;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error, path = []) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _parseAsync(_Err)(schema, value, _ctx);\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emoji = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^[A-Za-z0-9_-]*$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)\n// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// const dateSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\nexport const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const time = timeSource({ precision: args.precision });\n const opts = [\"Z\"];\n if (args.local)\n opts.push(\"\");\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n const timeRegex = `${time}(?:${opts.join(\"|\")})`;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n if (def.value < curr) {\n if (def.inclusive)\n bag.maximum = def.value;\n else\n bag.exclusiveMaximum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n if (def.value > curr) {\n if (def.inclusive)\n bag.minimum = def.value;\n else\n bag.exclusiveMinimum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n var _a;\n (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n });\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n if (isInt)\n bag.pattern = regexes.integer;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.size;\n bag.maximum = def.size;\n bag.size = def.size;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.length;\n bag.maximum = def.length;\n bag.length = def.length;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n if (def.pattern) {\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(def.pattern);\n }\n });\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.mime = def.mime;\n });\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export class Doc {\n constructor(args = []) {\n this.content = [];\n this.indent = 0;\n if (this)\n this.args = args;\n }\n indented(fn) {\n this.indent += 1;\n fn(this);\n this.indent -= 1;\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const args = this?.args;\n const content = this?.content ?? [``];\n const lines = [...content.map((x) => ` ${x}`)];\n // console.log(lines.join(\"\\n\"));\n return new F(...args, lines.join(\"\\n\"));\n }\n}\n","export const version = {\n major: 4,\n minor: 4,\n patch: 3,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync, safeParse, safeParseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const checks = [...(inst._zod.def.checks ?? [])];\n // if inst is itself a checks.$ZodCheck, run it as a check\n if (inst._zod.traits.has(\"$ZodCheck\")) {\n checks.unshift(inst);\n }\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer\n // inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (util.explicitlyAborted(payload))\n continue;\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary\n // initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n // Lazy initialize ~standard to avoid creating objects for every schema\n util.defineLazy(inst, \"~standard\", () => ({\n validate: (value) => {\n try {\n const r = safeParse(inst, value);\n return r.success ? { value: r.data } : { issues: r.error?.issues };\n }\n catch (_) {\n return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n }\n },\n vendor: \"zod\",\n version: 1,\n }));\n});\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n // When normalize is off, require :// for http/https URLs\n // This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source) {\n if (!/^https?:\\/\\//i.test(trimmed)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid URL format\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n }\n // @ts-ignore\n const url = new URL(trimmed);\n if (def.hostname) {\n def.hostname.lastIndex = 0;\n if (!def.hostname.test(url.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n if (def.protocol) {\n def.protocol.lastIndex = 0;\n if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n // Set the output value based on normalize flag\n if (def.normalize) {\n // Use normalized URL\n payload.value = url.href;\n }\n else {\n // Preserve the original input (trimmed)\n payload.value = trimmed;\n }\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.nanoid);\n $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv4`;\n});\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv6`;\n inst._zod.check = (payload) => {\n try {\n // @ts-ignore\n new URL(`http://[${payload.value}]`);\n // return;\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n const parts = payload.value.split(\"/\");\n try {\n if (parts.length !== 2)\n throw new Error();\n const [address, prefix] = parts;\n if (!prefix)\n throw new Error();\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n throw new Error();\n if (prefixNum < 0 || prefixNum > 128)\n throw new Error();\n // @ts-ignore\n new URL(`http://[${address}]`);\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n // atob ignores whitespace, so reject it up front.\n if (/\\s/.test(data))\n return false;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64\";\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64URL(data) {\n if (!regexes.base64url.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64url);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64url\";\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? \"Infinity\"\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = Array(input.length);\n const proms = [];\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {\n const isPresent = key in input;\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (isOptionalIn && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && !isOptionalIn) {\n if (!result.issues.length) {\n final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [key],\n });\n }\n return;\n }\n if (result.value === undefined) {\n if (isPresent) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n for (const k of keys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n keys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const isOptionalIn = _catchall.optin === \"optional\";\n const isOptionalOut = _catchall.optout === \"optional\";\n for (const key in input) {\n // skip __proto__ so it can't replace the result prototype via the\n // assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n if (keySet.has(key))\n continue;\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n // const sh = def.shape;\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n if (!desc?.get) {\n const sh = def.shape;\n Object.defineProperty(def, \"shape\", {\n get: () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", {\n value: newSh,\n });\n return newSh;\n },\n });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazy(inst._zod, \"propValues\", () => {\n const shape = def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n propValues[key] ?? (propValues[key] = new Set());\n for (const v of field.values)\n propValues[key].add(v);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = {};\n const proms = [];\n const shape = value.shape;\n for (const key of value.keys) {\n const el = shape[key];\n const isOptionalIn = el._zod.optin === \"optional\";\n const isOptionalOut = el._zod.optout === \"optional\";\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const generateFastpass = (shape) => {\n const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n const normalized = _normalized.value;\n const parseStr = (key) => {\n const k = util.esc(key);\n return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n };\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.keys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(`const newResult = {};`);\n for (const key of normalized.keys) {\n const id = ids[key];\n const k = util.esc(key);\n const schema = shape[key];\n const isOptionalIn = schema?._zod?.optin === \"optional\";\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(key)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys\n doc.write(`\n if (${id}.issues.length) {\n if (${k} in input) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${k} in input;\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n if (!${id}_present && !${id}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${k}]\n });\n }\n\n if (${id}_present) {\n if (${id}.value === undefined) {\n newResult[${k}] = undefined;\n } else {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n const fn = doc.compile();\n return (payload, ctx) => fn(shape, payload, ctx);\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"values\", () => {\n if (def.options.every((o) => o._zod.values)) {\n return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n if (def.options.every((o) => o._zod.pattern)) {\n const patterns = def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const successes = results.filter((r) => r.issues.length === 0);\n if (successes.length === 1) {\n final.value = successes[0].value;\n return final;\n }\n if (successes.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazy(inst._zod, \"propValues\", () => {\n const propValues = {};\n for (const option of def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const [k, v] of Object.entries(pv)) {\n if (!propValues[k])\n propValues[k] = new Set();\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n return propValues;\n });\n const disc = util.cached(() => {\n const opts = def.options;\n const map = new Map();\n for (const o of opts) {\n const values = o._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n for (const v of values) {\n if (map.has(v)) {\n throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n }\n map.set(v, o);\n }\n }\n return map;\n });\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const opt = disc.value.get(input?.[def.discriminator]);\n if (opt) {\n return opt._zod.run(payload, ctx);\n }\n // Fall back to union matching when the fast discriminator path fails:\n // - explicitly enabled via unionFallback, or\n // - during backward direction (encode), since codec-based discriminators\n // have different values in forward vs backward directions\n if (def.unionFallback || ctx.direction === \"backward\") {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n options: Array.from(disc.value.keys()),\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nfunction mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) report each key as unrecognized\n const unrecKeys = new Map();\n let unrecIssue;\n for (const iss of left.issues) {\n if (iss.code === \"unrecognized_keys\") {\n unrecIssue ?? (unrecIssue = iss);\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).l = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n for (const iss of right.issues) {\n if (iss.code === \"unrecognized_keys\") {\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).r = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n // Report only keys unrecognized by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length && unrecIssue) {\n result.issues.push({ ...unrecIssue, keys: bothKeys });\n }\n if (util.aborted(result))\n return result;\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = [];\n const proms = [];\n const optinStart = getTupleOptStart(items, \"optin\");\n const optoutStart = getTupleOptStart(items, \"optout\");\n if (!def.rest) {\n if (input.length < optinStart) {\n payload.issues.push({\n code: \"too_small\",\n minimum: optinStart,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n if (input.length > items.length) {\n payload.issues.push({\n code: \"too_big\",\n maximum: items.length,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n }\n }\n // Run every item in parallel, collecting results into an indexed\n // array. The post-processing in `handleTupleResults` walks them in\n // order so it can decide whether an absent optional-output error can\n // truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n for (let i = 0; i < items.length; i++) {\n const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((rr) => {\n itemResults[i] = rr;\n }));\n }\n else {\n itemResults[i] = r;\n }\n }\n if (def.rest) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n }\n return handleTupleResults(itemResults, payload, items, input, optoutStart);\n };\n});\nfunction getTupleOptStart(items, key) {\n for (let i = items.length - 1; i >= 0; i--) {\n if (items[i]._zod[key] !== \"optional\")\n return i + 1;\n }\n return 0;\n}\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional\n // rule, but only after `optoutStart`: the first index where the output\n // tuple tail can be absent.\n for (let i = 0; i < items.length; i++) {\n const r = itemResults[i];\n const isPresent = i < input.length;\n if (r.issues.length) {\n if (!isPresent && i >= optoutStart) {\n final.value.length = i;\n break;\n }\n final.issues.push(...util.prefixIssues(i, r.issues));\n }\n final.value[i] = r.value;\n }\n // Drop trailing slots that produced `undefined` for absent input\n // (the array analog of an absent optional key on an object). The\n // `i >= input.length` floor is critical: an explicit `undefined`\n // *inside* the input must be preserved even when the schema is\n // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n // explicit undefined value).\n for (let i = final.value.length - 1; i >= input.length; i--) {\n if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n final.value.length = i;\n }\n else {\n break;\n }\n }\n return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n const values = def.keyType._zod.values;\n if (values) {\n payload.value = {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n continue;\n }\n const outKey = keyResult.value;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n });\n }\n }\n else {\n payload.value = {};\n // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key))\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key)\n // This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = new Map();\n for (const [key, value] of input) {\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = new Set();\n for (const item of input) {\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n inst._zod.pattern = new RegExp(`^(${values\n .filter((k) => util.propertyKeyTypes.has(typeof k))\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n if (def.values.length === 0) {\n throw new Error(\"Cannot create literal schema with no valid values\");\n }\n const values = new Set(def.values);\n inst._zod.values = values;\n inst._zod.pattern = new RegExp(`^(${def.values\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n payload.fallback = true;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n payload.fallback = true;\n return payload;\n };\n});\nfunction handleOptionalResult(result, input) {\n if (input === undefined && (result.issues.length || result.fallback)) {\n return { issues: [], value: undefined };\n }\n return result;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (def.innerType._zod.optin === \"optional\") {\n const input = payload.value;\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise)\n return result.then((r) => handleOptionalResult(r, input));\n return handleOptionalResult(result, input);\n }\n if (payload.value === undefined) {\n return payload;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"pattern\", () => def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => {\n const v = def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n payload.fallback = true;\n }\n return payload;\n });\n }\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n payload.fallback = true;\n }\n return payload;\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n if (left.issues.length) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType?._zod?.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n payload.value = Object.freeze(payload.value);\n return payload;\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n if (!part._zod.pattern) {\n // if (!source)\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n if (!source)\n throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n regexParts.push(source.slice(start, end));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._def = def;\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n return function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n };\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n };\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // Cache the resolved inner type on the shared `def` so all clones of this\n // lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance,\n // preserving identity for cycle detection on recursive schemas.\n util.defineLazy(inst._zod, \"innerType\", () => {\n const d = def;\n if (!d._cachedInner)\n d._cachedInner = def.getter();\n return d._cachedInner;\n });\n util.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType?._zod?.pattern);\n util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType?._zod?.propValues);\n util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType?._zod?.optin ?? undefined);\n util.defineLazy(inst._zod, \"optout\", () => inst._zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","var _a;\nexport const $output = Symbol(\"ZodOutput\");\nexport const $input = Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class({\n type: \"string\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class({\n type: \"string\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class({\n type: \"number\",\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class({\n type: \"number\",\n coerce: true,\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n }, params);\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n ...util.normalizeParams(_params),\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import { globalRegistry } from \"./registries.js\";\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n external: params?.external ?? undefined,\n };\n}\nexport function process(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n process(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n Object.assign(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && \"_prefault\" in result.schema)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema\n // defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes\n // multiple schemas map to the same seen object.\n // e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${id}` };\n }\n if (entry[1] === root) {\n return { ref: \"#\" };\n }\n // self-contained schema\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + defId };\n };\n // stored cached version in `def` property\n // remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema\n // or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/<root>` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n // biome-ignore lint:\n continue;\n }\n }\n }\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n Object.assign(schema, refSchema);\n }\n // restore child's own properties (child wins)\n Object.assign(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema\n // This handles cases like: readonly().meta({id}).describe()\n // where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n Object.assign(result, root.def ?? root.schema);\n // The `id` in `.meta()` is a Zod-specific registration tag used to extract\n // schemas into $defs — it is not user-facing JSON Schema metadata. Strip it\n // from the output body where it would otherwise leak. The id is preserved\n // implicitly via the $defs key (and via $ref paths).\n const rootMetaId = ctx.metadataRegistry.get(schema)?.id;\n if (rootMetaId !== undefined && result.id === rootMetaId)\n delete result.id;\n // build defs object\n const defs = ctx.external?.defs ?? {};\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n if (seen.def.id === seen.defId)\n delete seen.def.id;\n defs[seen.defId] = seen.def;\n }\n }\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed\n // each call to finalize() is functionally independent\n // though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n if (_schema._zod.traits.has(\"$ZodCodec\"))\n return true;\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\nimport { getEnumValues } from \"./util.js\";\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding } = schema._zod\n .bag;\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // JSON Schema format: \"time\" requires a full time with offset or Z\n // z.iso.time() does not include timezone information, so format: \"time\" should never be used\n if (format === \"time\") {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const regexes = [...patterns];\n if (regexes.length === 1)\n json.pattern = regexes[0].source;\n else if (regexes.length > 1) {\n json.allOf = [\n ...regexes.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n if (typeof format === \"string\" && format.includes(\"int\"))\n json.type = \"integer\";\n else\n json.type = \"number\";\n // when both minimum and exclusiveMinimum exist, pick the more restrictive one\n const exMin = typeof exclusiveMinimum === \"number\" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);\n const exMax = typeof exclusiveMaximum === \"number\" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);\n const legacy = ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\";\n if (exMin) {\n if (legacy) {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n else if (typeof minimum === \"number\") {\n json.minimum = minimum;\n }\n if (exMax) {\n if (legacy) {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n else if (typeof maximum === \"number\") {\n json.maximum = maximum;\n }\n if (typeof multipleOf === \"number\")\n json.multipleOf = multipleOf;\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt cannot be represented in JSON Schema\");\n }\n};\nexport const symbolProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Symbols cannot be represented in JSON Schema\");\n }\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Undefined cannot be represented in JSON Schema\");\n }\n};\nexport const voidProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Void cannot be represented in JSON Schema\");\n }\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Date cannot be represented in JSON Schema\");\n }\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, _params) => {\n const def = schema._zod.def;\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Literal `undefined` cannot be represented in JSON Schema\");\n }\n else {\n // do not add to vals\n }\n }\n else if (typeof val === \"bigint\") {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt literals cannot be represented in JSON Schema\");\n }\n else {\n vals.push(Number(val));\n }\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"NaN cannot be represented in JSON Schema\");\n }\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const file = {\n type: \"string\",\n format: \"binary\",\n contentEncoding: \"binary\",\n };\n const { minimum, maximum, mime } = schema._zod.bag;\n if (minimum !== undefined)\n file.minLength = minimum;\n if (maximum !== undefined)\n file.maxLength = maximum;\n if (mime) {\n if (mime.length === 1) {\n file.contentMediaType = mime[0];\n Object.assign(_json, file);\n }\n else {\n Object.assign(_json, file); // shared props at root\n _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs\n }\n }\n else {\n Object.assign(_json, file);\n }\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Custom types cannot be represented in JSON Schema\");\n }\n};\nexport const functionProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Function types cannot be represented in JSON Schema\");\n }\n};\nexport const transformProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Transforms cannot be represented in JSON Schema\");\n }\n};\nexport const mapProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Map cannot be represented in JSON Schema\");\n }\n};\nexport const setProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Set cannot be represented in JSON Schema\");\n }\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = process(def.element, ctx, {\n ...params,\n path: [...params.path, \"items\"],\n });\n};\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n json.properties = {};\n const shape = def.shape;\n for (const key in shape) {\n json.properties[key] = process(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n });\n }\n // required keys\n const allKeys = new Set(Object.keys(shape));\n const requiredKeys = new Set([...allKeys].filter((key) => {\n const v = def.shape[key]._zod;\n if (ctx.io === \"input\") {\n return v.optin === undefined;\n }\n else {\n return v.optout === undefined;\n }\n }));\n if (requiredKeys.size > 0) {\n json.required = Array.from(requiredKeys);\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = process(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches)\n // This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = process(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = process(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? process(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (rest) {\n json.items = rest;\n }\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n json.minItems = prefixItems.length;\n if (!rest) {\n json.maxItems = prefixItems.length;\n }\n }\n else {\n json.items = prefixItems;\n if (rest) {\n json.additionalItems = rest;\n }\n }\n // length\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties\n // This correctly represents \"only validate keys matching the pattern\" semantics\n // and composes well with allOf (intersections)\n const keyType = def.keyType;\n const keyBag = keyType._zod.bag;\n const patterns = keyBag?.patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n json.patternProperties[pattern.source] = valueSchema;\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = process(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n }\n json.additionalProperties = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n if (keyValues) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues;\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.default = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io === \"input\")\n json._prefault = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n throw new Error(\"Dynamic catch values are not supported in JSON Schema\");\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const inIsTransform = def.in._zod.traits.has(\"$ZodTransform\");\n const innerType = ctx.io === \"input\" ? (inIsTransform ? def.out : def.in) : def.out;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n process(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n schemas[key] = finalize(ctx, schema);\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n process(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function datetime(params) {\n return core._isoDateTime(ZodISODateTime, params);\n}\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function date(params) {\n return core._isoDate(ZodISODate, params);\n}\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function time(params) {\n return core._isoTime(ZodISOTime, params);\n}\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function duration(params) {\n return core._isoDuration(ZodISODuration, params);\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n Object.defineProperties(inst, {\n format: {\n value: (mapper) => core.formatError(inst, mapper),\n // enumerable: false,\n },\n flatten: {\n value: (mapper) => core.flattenError(inst, mapper),\n // enumerable: false,\n },\n addIssue: {\n value: (issue) => {\n inst.issues.push(issue);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n addIssues: {\n value: (issues) => {\n inst.issues.push(...issues);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n isEmpty: {\n get() {\n return inst.issues.length === 0;\n },\n // enumerable: false,\n },\n });\n // Object.defineProperty(inst, \"isEmpty\", {\n // get() {\n // return inst.issues.length === 0;\n // },\n // });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport * as checks from \"./checks.js\";\nimport * as iso from \"./iso.js\";\nimport * as parse from \"./parse.js\";\n// Lazy-bind builder methods.\n//\n// Builder methods (`.optional`, `.array`, `.refine`, ...) live as\n// non-enumerable getters on each concrete schema constructor's\n// prototype. On first access from an instance the getter allocates\n// `fn.bind(this)` and caches it as an own property on that instance,\n// so detached usage (`const m = schema.optional; m()`) still works\n// and the per-instance allocation only happens for methods actually\n// touched.\n//\n// One install per (prototype, group), memoized by `_installedGroups`.\nconst _installedGroups = /* @__PURE__ */ new WeakMap();\nfunction _installLazyMethods(inst, group, methods) {\n const proto = Object.getPrototypeOf(inst);\n let installed = _installedGroups.get(proto);\n if (!installed) {\n installed = new Set();\n _installedGroups.set(proto, installed);\n }\n if (installed.has(group))\n return;\n installed.add(group);\n for (const key in methods) {\n const fn = methods[key];\n Object.defineProperty(proto, key, {\n configurable: true,\n enumerable: false,\n get() {\n const bound = fn.bind(this);\n Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n enumerable: true,\n value: bound,\n });\n return bound;\n },\n set(v) {\n Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n enumerable: true,\n value: v,\n });\n },\n });\n }\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n core.$ZodType.init(inst, def);\n Object.assign(inst[\"~standard\"], {\n jsonSchema: {\n input: createStandardJSONSchemaMethod(inst, \"input\"),\n output: createStandardJSONSchemaMethod(inst, \"output\"),\n },\n });\n inst.toJSONSchema = createToJSONSchemaMethod(inst, {});\n inst.def = def;\n inst.type = def.type;\n Object.defineProperty(inst, \"_def\", { value: def });\n // Parse-family is intentionally kept as per-instance closures: these are\n // the hot path AND the most-detached methods (`arr.map(schema.parse)`,\n // `const { parse } = schema`, etc.). Eager closures here mean callers pay\n // ~12 closure allocations per schema but get monomorphic call sites and\n // detached usage that \"just works\".\n inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n inst.spa = inst.safeParseAsync;\n inst.encode = (data, params) => parse.encode(inst, data, params);\n inst.decode = (data, params) => parse.decode(inst, data, params);\n inst.encodeAsync = async (data, params) => parse.encodeAsync(inst, data, params);\n inst.decodeAsync = async (data, params) => parse.decodeAsync(inst, data, params);\n inst.safeEncode = (data, params) => parse.safeEncode(inst, data, params);\n inst.safeDecode = (data, params) => parse.safeDecode(inst, data, params);\n inst.safeEncodeAsync = async (data, params) => parse.safeEncodeAsync(inst, data, params);\n inst.safeDecodeAsync = async (data, params) => parse.safeDecodeAsync(inst, data, params);\n // All builder methods are placed on the internal prototype as lazy-bind\n // getters. On first access per-instance, a bound thunk is allocated and\n // cached as an own property; subsequent accesses skip the getter. This\n // means: no per-instance allocation for unused methods, full\n // detachability preserved (`const m = schema.optional; m()` works), and\n // shared underlying function references across all instances.\n _installLazyMethods(inst, \"ZodType\", {\n check(...chks) {\n const def = this.def;\n return this.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...chks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), { parent: true });\n },\n with(...chks) {\n return this.check(...chks);\n },\n clone(def, params) {\n return core.clone(this, def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n refine(check, params) {\n return this.check(refine(check, params));\n },\n superRefine(refinement, params) {\n return this.check(superRefine(refinement, params));\n },\n overwrite(fn) {\n return this.check(checks.overwrite(fn));\n },\n optional() {\n return optional(this);\n },\n exactOptional() {\n return exactOptional(this);\n },\n nullable() {\n return nullable(this);\n },\n nullish() {\n return optional(nullable(this));\n },\n nonoptional(params) {\n return nonoptional(this, params);\n },\n array() {\n return array(this);\n },\n or(arg) {\n return union([this, arg]);\n },\n and(arg) {\n return intersection(this, arg);\n },\n transform(tx) {\n return pipe(this, transform(tx));\n },\n default(d) {\n return _default(this, d);\n },\n prefault(d) {\n return prefault(this, d);\n },\n catch(params) {\n return _catch(this, params);\n },\n pipe(target) {\n return pipe(this, target);\n },\n readonly() {\n return readonly(this);\n },\n describe(description) {\n const cl = this.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n },\n meta(...args) {\n // overloaded: meta() returns the registered metadata, meta(data)\n // returns a clone with `data` registered. The mapped type picks\n // up the second overload, so we accept variadic any-args and\n // return `any` to satisfy both at runtime.\n if (args.length === 0)\n return core.globalRegistry.get(this);\n const cl = this.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n },\n isOptional() {\n return this.safeParse(undefined).success;\n },\n isNullable() {\n return this.safeParse(null).success;\n },\n apply(fn) {\n return fn(this);\n },\n });\n Object.defineProperty(inst, \"description\", {\n get() {\n return core.globalRegistry.get(inst)?.description;\n },\n configurable: true,\n });\n return inst;\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n const bag = inst._zod.bag;\n inst.format = bag.format ?? null;\n inst.minLength = bag.minimum ?? null;\n inst.maxLength = bag.maximum ?? null;\n _installLazyMethods(inst, \"_ZodString\", {\n regex(...args) {\n return this.check(checks.regex(...args));\n },\n includes(...args) {\n return this.check(checks.includes(...args));\n },\n startsWith(...args) {\n return this.check(checks.startsWith(...args));\n },\n endsWith(...args) {\n return this.check(checks.endsWith(...args));\n },\n min(...args) {\n return this.check(checks.minLength(...args));\n },\n max(...args) {\n return this.check(checks.maxLength(...args));\n },\n length(...args) {\n return this.check(checks.length(...args));\n },\n nonempty(...args) {\n return this.check(checks.minLength(1, ...args));\n },\n lowercase(params) {\n return this.check(checks.lowercase(params));\n },\n uppercase(params) {\n return this.check(checks.uppercase(params));\n },\n trim() {\n return this.check(checks.trim());\n },\n normalize(...args) {\n return this.check(checks.normalize(...args));\n },\n toLowerCase() {\n return this.check(checks.toLowerCase());\n },\n toUpperCase() {\n return this.check(checks.toUpperCase());\n },\n slugify() {\n return this.check(checks.slugify());\n },\n });\n});\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n inst.email = (params) => inst.check(core._email(ZodEmail, params));\n inst.url = (params) => inst.check(core._url(ZodURL, params));\n inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params));\n inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params));\n inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params));\n inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params));\n inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params));\n inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params));\n inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params));\n inst.ulid = (params) => inst.check(core._ulid(ZodULID, params));\n inst.base64 = (params) => inst.check(core._base64(ZodBase64, params));\n inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params));\n inst.xid = (params) => inst.check(core._xid(ZodXID, params));\n inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params));\n inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params));\n inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params));\n inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params));\n inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params));\n inst.e164 = (params) => inst.check(core._e164(ZodE164, params));\n // iso\n inst.datetime = (params) => inst.check(iso.datetime(params));\n inst.date = (params) => inst.check(iso.date(params));\n inst.time = (params) => inst.check(iso.time(params));\n inst.duration = (params) => inst.check(iso.duration(params));\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: core.regexes.httpProtocol,\n hostname: core.regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", core.regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", core.regexes.hex, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n _installLazyMethods(inst, \"ZodNumber\", {\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n int(params) {\n return this.check(int(params));\n },\n safe(params) {\n return this.check(int(params));\n },\n positive(params) {\n return this.check(checks.gt(0, params));\n },\n nonnegative(params) {\n return this.check(checks.gte(0, params));\n },\n negative(params) {\n return this.check(checks.lt(0, params));\n },\n nonpositive(params) {\n return this.check(checks.lte(0, params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n step(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n finite() {\n return this;\n },\n });\n const bag = inst._zod.bag;\n inst.minValue =\n Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;\n inst.maxValue =\n Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;\n inst.isInt = (bag.format ?? \"\").includes(\"int\") || Number.isSafeInteger(bag.multipleOf ?? 0.5);\n inst.isFinite = true;\n inst.format = bag.format ?? null;\n});\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.positive = (params) => inst.check(checks.gt(BigInt(0), params));\n inst.negative = (params) => inst.check(checks.lt(BigInt(0), params));\n inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params));\n inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n const bag = inst._zod.bag;\n inst.minValue = bag.minimum ?? null;\n inst.maxValue = bag.maximum ?? null;\n inst.format = bag.format ?? null;\n});\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\n// int64\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\n// uint64\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n const c = inst._zod.bag;\n inst.minDate = c.minimum ? new Date(c.minimum) : null;\n inst.maxDate = c.maximum ? new Date(c.maximum) : null;\n});\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n _installLazyMethods(inst, \"ZodArray\", {\n min(n, params) {\n return this.check(checks.minLength(n, params));\n },\n nonempty(params) {\n return this.check(checks.minLength(1, params));\n },\n max(n, params) {\n return this.check(checks.maxLength(n, params));\n },\n length(n, params) {\n return this.check(checks.length(n, params));\n },\n unwrap() {\n return this.element;\n },\n });\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.defineLazy(inst, \"shape\", () => {\n return def.shape;\n });\n _installLazyMethods(inst, \"ZodObject\", {\n keyof() {\n return _enum(Object.keys(this._zod.def.shape));\n },\n catchall(catchall) {\n return this.clone({ ...this._zod.def, catchall: catchall });\n },\n passthrough() {\n return this.clone({ ...this._zod.def, catchall: unknown() });\n },\n loose() {\n return this.clone({ ...this._zod.def, catchall: unknown() });\n },\n strict() {\n return this.clone({ ...this._zod.def, catchall: never() });\n },\n strip() {\n return this.clone({ ...this._zod.def, catchall: undefined });\n },\n extend(incoming) {\n return util.extend(this, incoming);\n },\n safeExtend(incoming) {\n return util.safeExtend(this, incoming);\n },\n merge(other) {\n return util.merge(this, other);\n },\n pick(mask) {\n return util.pick(this, mask);\n },\n omit(mask) {\n return util.omit(this, mask);\n },\n partial(...args) {\n return util.partial(ZodOptional, this, args[0]);\n },\n required(...args) {\n return util.required(ZodNonOptional, this, args[0]);\n },\n });\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n inst.rest = (rest) => inst.clone({\n ...inst._zod.def,\n rest: rest,\n });\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n const k = core.clone(keyType);\n k._zod.values = undefined;\n return new ZodRecord({\n type: \"record\",\n keyType: k,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n inst.options = Object.values(def.entries);\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n payload.fallback = true;\n return payload;\n });\n }\n payload.value = output;\n payload.fallback = true;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodPreprocess = /*@__PURE__*/ core.$constructor(\"ZodPreprocess\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodPreprocess.init(inst, def);\n});\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodCustom({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\nexport function preprocess(fn, schema) {\n return new ZodPreprocess({\n type: \"pipe\",\n in: transform(fn),\n out: schema,\n });\n}\n","import { z } from \"zod\";\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.string().nullable(),\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.string().nullable(),\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.string().nullable(),\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, useState } from \"react\";\n\nimport { Amplify } from \"@aws-amplify/core\";\nimport {\n CONNECTION_STATE_CHANGE,\n ConnectionState,\n events,\n EventsChannel,\n} from \"aws-amplify/data\";\nimport { Hub } from \"aws-amplify/utils\";\n\nimport { useErrorContext } from \"@/contexts/error-handling.utils\";\nimport { getErrorMessage } from \"@/contexts/utils\";\nimport { amplifyConfig } from \"@/lib/config\";\nimport { BootResponse, MessageResponse } from \"@/lib/eloquent-ai-api-client\";\nimport { Message } from \"@/type\";\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 [isAmplifyReady, setIsAmplifyReady] = useState(false);\n\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<EventsChannel | 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 refs to avoid stale closures in timers/intervals\n const onMessageRef = useRef(onMessage);\n const onCognitionRef = useRef(onCognition);\n const onCognitionCompleteRef = useRef(onCognitionComplete);\n const onErrorRef = useRef(onError);\n const onChatClosedRef = useRef(onChatClosed);\n const onAgentCapturedUrlRef = useRef(onAgentCapturedUrl);\n const onAgentTopicRef = useRef(onAgentTopic);\n const onAgentSummaryRef = useRef(onAgentSummary);\n const onRatingRequestRef = useRef(onRatingRequest);\n const onBreadcrumbRef = useRef(onBreadcrumb);\n const fetchHistoryRef = useRef(fetchHistory);\n const getChatTokenRef = useRef(getChatToken);\n\n useEffect(() => {\n onMessageRef.current = onMessage;\n }, [onMessage]);\n useEffect(() => {\n onCognitionRef.current = onCognition;\n }, [onCognition]);\n useEffect(() => {\n onCognitionCompleteRef.current = onCognitionComplete;\n }, [onCognitionComplete]);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n useEffect(() => {\n onChatClosedRef.current = onChatClosed;\n }, [onChatClosed]);\n useEffect(() => {\n onAgentCapturedUrlRef.current = onAgentCapturedUrl;\n }, [onAgentCapturedUrl]);\n useEffect(() => {\n onAgentTopicRef.current = onAgentTopic;\n }, [onAgentTopic]);\n useEffect(() => {\n onAgentSummaryRef.current = onAgentSummary;\n }, [onAgentSummary]);\n useEffect(() => {\n onRatingRequestRef.current = onRatingRequest;\n }, [onRatingRequest]);\n useEffect(() => {\n onBreadcrumbRef.current = onBreadcrumb;\n }, [onBreadcrumb]);\n useEffect(() => {\n fetchHistoryRef.current = fetchHistory;\n }, [fetchHistory]);\n useEffect(() => {\n getChatTokenRef.current = getChatToken;\n }, [getChatToken]);\n\n const { publishError } = useErrorContext();\n\n const appSyncUrl = chatSettings?.app_sync_url;\n const appSyncRegion = chatSettings?.app_sync_region;\n const appSyncApiKey = chatSettings?.app_sync_api_key;\n\n useEffect(() => {\n if (appSyncUrl && appSyncRegion && appSyncApiKey) {\n Amplify.configure(\n amplifyConfig(appSyncUrl, appSyncApiKey, appSyncRegion),\n );\n setIsAmplifyReady(true);\n }\n }, [appSyncUrl, appSyncRegion, 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 // Opens an AppSync channel and subscribes to real-time events\n const connectChannel = useCallback(\n async (chatIdToConnect: string): Promise<void> => {\n closeChannel();\n const chatToken = getChatTokenRef.current();\n const connectOptions = chatToken\n ? { authMode: \"lambda\" as const, authToken: chatToken }\n : undefined;\n const channel = await events.connect(\n `/default/chat/${chatIdToConnect}`,\n connectOptions,\n );\n eventChannelRef.current = channel;\n\n channel.subscribe({\n next: (event) => {\n if (event.type !== \"data\") {\n console.warn(\"Unexpected event type:\", event.type);\n return;\n }\n\n const parseResult = chatResponseApiSchema.safeParse(event.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 error: (err) => {\n console.error(\"Error in conversation channel:\", err);\n },\n });\n },\n [closeChannel, publishError],\n );\n\n // Fetches history and delivers any unseen assistant messages via onMessage\n const runBackupPoll = useCallback(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\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 // scheduleReconnectRef breaks the circular dependency\n // (scheduleReconnect's setTimeout callback calls scheduleReconnect itself on failure)\n const scheduleReconnectRef = useRef<() => void>(() => {});\n\n const scheduleReconnect = useCallback(() => {\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 scheduleReconnectRef.current();\n }\n }, delay);\n }, [connectChannel, runBackupPoll]);\n\n useEffect(() => {\n scheduleReconnectRef.current = scheduleReconnect;\n }, [scheduleReconnect]);\n\n const connect = useCallback(\n async (chatIdToConnect: string): Promise<void> => {\n if (!isAmplifyReady || !chatIdToConnect) {\n throw new Error(\"Cannot connect: Amplify not ready or missing chatId\");\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 [isAmplifyReady, 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 || !isAmplifyReady || 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, isAmplifyReady, connect]);\n\n // Hub listener for AppSync connection state changes — triggers reconnect on drop\n useEffect(() => {\n const unsubscribe = Hub.listen(\n \"api\",\n (data: {\n payload: { event: string; data: { connectionState: ConnectionState } };\n }) => {\n if (data.payload.event !== CONNECTION_STATE_CHANGE) return;\n const connectionState = data.payload.data?.connectionState;\n if (\n connectionState === \"Disconnected\" ||\n connectionState === \"ConnectedPendingDisconnect\"\n ) {\n scheduleReconnectRef.current();\n }\n },\n );\n return () => unsubscribe();\n }, []);\n\n useEffect(() => {\n return () => {\n disconnect();\n };\n }, [disconnect]);\n\n return { connect, disconnect, clearProcessedIds };\n}\n","\"use client\";\nimport {\n useCallback,\n useEffect,\n useRef,\n type Dispatch,\n type SetStateAction,\n} from \"react\";\n\nimport { Message, MessageData } from \"@/type\";\n\nimport {\n BootResponse,\n EloquentAiApiClient,\n} from \"@/lib/eloquent-ai-api-client\";\n\nimport { useErrorContext } from \"@/contexts/error-handling.utils\";\nimport { useAgentCognitionContext } from \"@/hooks/use-agent-cognition-context\";\nimport { NetworkError, ServerError } from \"@/lib/http\";\nimport { getCurrentUrlSearchParams } from \"@/lib/url-params\";\nimport { usePersistence } from \"./persistence.hook\";\nimport { useRealtimeSocket } from \"./realtime-socket.hook\";\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 = useRef(apiClient);\n useEffect(() => {\n apiClientRef.current = apiClient;\n }, [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 {\n id: response.message_id,\n content: response.response.content ?? \"\",\n sender: \"assistant\" as const,\n timestamp: new Date().toISOString(),\n },\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],\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 [\n ...filtered,\n {\n id: crypto.randomUUID(),\n content: \"\",\n sender: \"assistant\" as const,\n timestamp: new Date().toISOString(),\n isRatingRequest: true,\n },\n ];\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((chatId: string) => {\n if (!apiClientRef.current) return Promise.resolve([]);\n return apiClientRef.current.getChatHistory(chatId);\n }, []);\n\n const getChatToken = useCallback(() => {\n return apiClientRef.current?.getChatToken() ?? null;\n }, []);\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) => [\n ...prev,\n {\n id: crypto.randomUUID(),\n content: \"This conversation is closed, please start a new chat.\",\n sender: \"assistant\" as const,\n timestamp: new Date().toISOString(),\n },\n ]);\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],\n );\n\n return {\n onCleanMessages,\n onSendMessage,\n onRateChat,\n };\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 { 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.utils\";\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 { useEffect, useState } from \"react\";\nimport { usePersistence } from \"./persistence.hook\";\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\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 const [isReady, setIsReady] = useState(false);\n const [userId, setUserId] = useState<string>(\"\");\n const [deviceId, setDeviceId] = useState<string>(\"\");\n const [externalId, setExternalId] = useState<string | null | undefined>(null);\n\n useEffect(() => {\n const savedData = getSavedChatData();\n\n if (!savedData?.userId) {\n if (initialUserId) {\n // TODO should we have an internal userId and a different externalId?\n setUserId(initialUserId);\n setExternalId(initialUserId);\n } else {\n setUserId(crypto.randomUUID());\n }\n } else if (savedData?.externalId !== initialUserId) {\n // If the externalId is the same as the initialUserId, we can use the saved userId\n setUserId(savedData.userId);\n setExternalId(initialUserId);\n } else {\n setUserId(savedData?.userId);\n setExternalId(savedData.externalId);\n }\n setDeviceId(savedData?.deviceId || crypto.randomUUID());\n setIsReady(true);\n }, [getSavedChatData, initialUserId]);\n\n return {\n isReady,\n userId,\n deviceId,\n externalId,\n };\n}\n","\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\n\nimport { Message } from \"@/type\";\n\nimport { getApiUrl } from \"@/lib/config\";\nimport {\n BootResponse,\n EloquentAiApiClient,\n} from \"@/lib/eloquent-ai-api-client\";\nimport { wrapPromise } from \"@/lib/utils\";\nimport { withRetry } from \"@/lib/retry\";\n\nimport { useFetch } from \"@/hooks/useFetch\";\n\nimport { usePersistence } from \"./persistence.hook\";\nimport { useUserIdentity } from \"./user-identity.hook\";\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\n useEffect(() => {\n if (!isUserIdentityReady) return;\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 [\n {\n id: crypto.randomUUID(),\n content: welcomeMessage,\n sender: \"assistant\" as const,\n timestamp: new Date().toISOString(),\n isWelcomeMessage: true,\n },\n ];\n });\n }\n\n setIsReady(true);\n };\n\n bootSDK();\n // Ignore exhaustive deps for: sdkBootFetch, apiClient, appId, userId\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isUserIdentityReady, messages.length]);\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 \"@uidotdev/usehooks\";\nimport { useCallback, useEffect, useState } from \"react\";\n\nimport { Message, MessageData } from \"@/type\";\n\nimport { ThemeContextType } from \"@/contexts/theme.context\";\n\nimport { ChatInterfaceProps } from \"@/components/chat-interface\";\n\nimport { deleteCookie, getCookie, setCookie } from \"@/lib/utils\";\n\nimport { useInterfaceProps } from \"./interface-props.hook\";\nimport { useMessageEvents } from \"./message-events.hook\";\nimport { useSdkInitialization } from \"./sdk-initialization.hook\";\nimport { useUiInitialization } from \"./ui-initialization.hook\";\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}: Readonly<\n Partial<UseChatProps> & {\n environment: \"test\" | \"live\";\n apiUrl?: string;\n appId: string;\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 (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 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 ]);\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 const hasCleanChatButton =\n chatSettings?.clean_chat_button ?? 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.\n const setChatOpen = useCallback<\n (value: boolean | ((prev: boolean) => boolean)) => void\n >(\n (value) => {\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],\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 // Restore the \"chat closed\" state saved to localStorage, so it survives a page refresh\n useEffect(() => {\n if (initialIsChatClosed) {\n setIsChatClosed(true);\n }\n }, [initialIsChatClosed]);\n\n const handleChatClosed = useCallback(() => {\n setIsChatClosed(true);\n }, []);\n\n // Proactive message state\n const [proactiveMessage, setProactiveMessage] = useState({\n text: \"\",\n isVisible: false,\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 useEffect(() => {\n if (currentChat) {\n if (externalId) {\n apiClient?.identifyUser({\n userId,\n userName,\n userData,\n externalId,\n deviceId,\n conversationId: currentChat.id,\n });\n }\n }\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 setProactiveMessage((prev) => ({\n ...prev,\n isVisible: false,\n }));\n }, []);\n\n // Show initial proactive message if provided\n useEffect(() => {\n if (\n chatSettings?.auto_display_welcome_message &&\n chatSettings?.welcome_message &&\n isReady\n ) {\n setProactiveMessage((prev) => ({\n ...prev,\n text: chatSettings.welcome_message || prev.text,\n isVisible: true,\n // The state initializes before boot resolves — apply the effective\n // (boot ?? prop) delay when the message is actually shown.\n autoHideDelay: proactiveMessageHideDelay,\n }));\n }\n }, [\n isReady,\n chatSettings?.auto_display_welcome_message,\n chatSettings?.welcome_message,\n proactiveMessageHideDelay,\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 \"@/hooks/use-agent-cognition\";\nimport { AgentCognitionContext } from \"./agent-cognition-context-definition\";\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 {\n ErrorContext,\n SdkError,\n createPublishApiError,\n} from \"./error-handling.utils\";\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 { useEffect, useState, type CSSProperties } from \"react\";\n\nimport mainCSS from \"@/index.css?inline\";\nimport wrapperCSS from \"@/wrapper.css?inline\";\n\nimport { Message } from \"@/type\";\n\nimport { LOGO_ANIMATED_URL } from \"@/lib/config\";\nimport { cn } from \"@/lib/utils\";\n\nimport { ChatBubble } from \"@/components/chat-bubble\";\nimport { ChatInterface } from \"@/components/chat-interface\";\nimport { Iframe } from \"@/components/iframe\";\nimport { Portal } from \"@/components/portal\";\nimport { ProactiveMessage } from \"@/components/chat/proactive-message\";\n\nimport { useChat, type UseChatProps } from \"@/components/chat/chat.hook\";\nimport { useKeyboardInset } from \"@/components/chat/keyboard-inset.hook\";\nimport { useScrollLock } from \"@/components/chat/scroll-lock.hook\";\nimport { AgentCognitionProvider } from \"@/contexts/agent-cognition.context\";\nimport { ErrorProvider } from \"@/contexts/error-handling.context\";\nimport { useErrorContext } from \"@/contexts/error-handling.utils\";\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 INTERNAL_ONLY_FEATURE_HIDE_PROACTIVE_MESSAGE?: boolean;\n INTERNAL_ONLY_SHOW_CLEAR_CHAT_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 INTERNAL_ONLY_FEATURE_HIDE_COPY_BUTTON?: boolean;\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_FEATURE_HIDE_PROACTIVE_MESSAGE = false,\n INTERNAL_ONLY_BLOCK_STYLE = false,\n INTERNAL_ONLY_FEATURE_MESSAGE_CLICK = undefined,\n INTERNAL_ONLY_FEATURE_CLEAR_CHAT_CLICK = undefined,\n INTERNAL_ONLY_FEATURE_HIDE_COPY_BUTTON = true,\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 });\n\n const keyboardInset = useKeyboardInset(isMobile && chatOpen);\n useScrollLock(isMobile && chatOpen);\n\n // Preload the header logo animation in parallel with SDK boot so\n // ChatInterface's own loading state (waiting on this asset) has already\n // resolved by the time isReady flips, avoiding a second skeleton flash.\n const [logoPreloaded, setLogoPreloaded] = useState(false);\n useEffect(() => {\n fetch(LOGO_ANIMATED_URL)\n .catch(() => {})\n .finally(() => setLogoPreloaded(true));\n }, []);\n\n if (hideSdk) return null;\n if (!isReady || !logoPreloaded) return null;\n if (!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 <ChatInterface\n {...chatInterfaceProps}\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 hideCopyButton={INTERNAL_ONLY_FEATURE_HIDE_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 </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 {!INTERNAL_ONLY_FEATURE_HIDE_PROACTIVE_MESSAGE &&\n proactiveMessage &&\n !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","Sentry","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","hideTimer","timer","getContrastingTextColor","e","X","useInterfaceProps","chatProps","chatSettings","useMemo","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","value","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","AWS_CLOUDWATCH_CATEGORY","USER_AGENT_HEADER","NO_HUBCALLBACK_PROVIDED_EXCEPTION","LogType","LOG_LEVELS","ConsoleLogger","name","level","n","dt","type","msg","loggerLevelName","loggerLevel","log","prefix","obj","plugin","logEvent","pluggable","AmplifyError","recoverySuggestion","underlyingError","metadata","extendedRequestId","httpStatusCode","requestId","AMPLIFY_SYMBOL","logger","HubClass","channel","listener","holder","callback","payload","source","ampSymbol","capsule","listenerName","cb","Hub","getBtoa","isNonRetryableError","retry","functionToRetry","args","delayFn","onTerminate","resolve","reject","attempt","terminated","wakeUp","lastError","err","retryIn","_resolve","deepFreeze","object","propNames","authTypeMapping","parseAWSExports","aws_appsync_apiKey","aws_appsync_authenticationType","aws_appsync_graphqlEndpoint","aws_appsync_region","aws_bots_config","aws_cognito_identity_pool_id","aws_cognito_sign_up_verification_method","aws_cognito_mfa_configuration","aws_cognito_mfa_types","aws_cognito_password_protection_settings","aws_cognito_verification_mechanisms","aws_cognito_signup_attributes","aws_cognito_social_providers","aws_cognito_username_attributes","aws_mandatory_sign_in","aws_mobile_analytics_app_id","aws_mobile_analytics_app_region","aws_user_files_s3_bucket","aws_user_files_s3_bucket_region","aws_user_files_s3_dangerously_connect_to_http_endpoint_for_testing","aws_user_pools_id","aws_user_pools_web_client_id","geo","oauth","predictions","aws_cloud_logic_custom","Notifications","modelIntrospection","amplifyConfig","InAppMessaging","Push","bot","defaultAuthMode","mfaConfig","passwordFormatConfig","userAttributes","attributes","loginWithEmailEnabled","loginWithPhoneEnabled","hasOAuthConfig","hasSocialProviderConfig","getOAuthConfig","parseSocialProviders","amazon_location_service","acc","api","endpoint","service","voiceId","getRedirectUrl","redirectStr","domain","scope","redirectSignIn","redirectSignOut","responseType","provider","updatedProvider","ADD_OAUTH_LISTENER","byteToHex","i","unsafeStringify","arr","offset","getRandomValues","rnds8","rng","randomUUID","native","v4","buf","rnds","isAmplifyOutputs","version","parseStorage","amplifyOutputsStorageProperties","bucket_name","aws_region","buckets","createBucketInfoMap","parseAuth","amplifyOutputsAuthProperties","user_pool_id","user_pool_client_id","identity_pool_id","password_policy","mfa_configuration","mfa_methods","unauthenticated_identities_enabled","username_attributes","standard_required_attributes","groups","passwordless","authConfig","getMfaStatus","getOAuthProviders","curr","parseAnalytics","amplifyOutputsAnalyticsProperties","amazon_pinpoint","parseGeo","geofence_collections","maps","search_indices","parseData","amplifyOutputsDataProperties","default_authorization_type","api_key","model_introspection","getGraphQLAuthMode","parseCustom","amplifyOutputsCustomProperties","parseNotifications","amplifyOutputsNotificationsProperties","channels","amazon_pinpoint_app_id","amazon_connect","supportedChannels","hasInAppMessaging","hasPushNotification","notificationsConfig","pushNotificationConfig","parseAmplifyOutputs","amplifyOutputs","resourcesConfig","customConfig","authModeNames","authType","providerNames","providers","oAuthProviders","mfaConfiguration","mappedBuckets","bucketName","paths","sanitizedPaths","parseAmplifyConfig","BLOCK_SIZE","DIGEST_LENGTH","KEY","INIT","MAX_HASHABLE_LENGTH","RawSha256","position","byteLength","bitsHashed","bufferView","undecoratedLength","out","_a","buffer","state","state0","state1","state2","state3","state4","state5","state6","state7","u","t1_1","t2_1","t1","t2","fromUtf8","input","fromUtf8Browser","convertToBuffer","isEmptyData","Sha256","secret","toHash","__awaiter","__generator","inner","bufferFromSecret","outer","bufferHash","SHORT_TO_HEX","encodedByte","toHex","bytes","Framework","Category","AiAction","AnalyticsAction","ApiAction","AuthAction","DataStoreAction","GeoAction","InAppMessagingAction","InteractionsAction","PredictionsAction","PubSubAction","PushNotificationAction","StorageAction","globalExists","windowExists","documentExists","processExists","keyPrefixMatch","reactWebDetect","elementKeyPrefixedWithReact","elementIsReactEnabled","element","allElementsWithId","reactSSRDetect","vueWebDetect","vueSSRDetect","svelteWebDetect","svelteSSRDetect","nextWebDetect","nextSSRDetect","nuxtWebDetect","nuxtSSRDetect","angularWebDetect","angularVersionSetInDocument","angularContentSetInWindow","angularSSRDetect","reactNativeDetect","expoDetect","webDetect","detectionMap","detect","detectionEntry","frameworkCache","frameworkChangeObservers","resetTriggered","SSR_RESET_TIMEOUT","WEB_RESET_TIMEOUT","PRIME_FRAMEWORK_DELAY","detectFramework","fcn","resetTimeout","clearCache","framework","delay","customUserAgentState","getCustomUserAgent","category","BASE_USER_AGENT","sanitizeAmplifyVersion","amplifyVersion","getAmplifyUserAgentObject","action","userAgent","customState","getAmplifyUserAgent","customUserAgentDetails","agentKey","agentValue","isFunction","createErrorClass","createImpl","_super","instance","ctorFunc","UnsubscriptionError","errors","arrRemove","item","index","Subscription","initialTeardown","e_1","e_2","_b","_parentage","_parentage_1","__values","_parentage_1_1","parent_1","e_1_1","initialFinalizer","_finalizers","_finalizers_1","_finalizers_1_1","finalizer","execFinalizer","__spreadArray","__read","e_2_1","teardown","parent","empty","isSubscription","timeoutProvider","handler","timeout","_i","handle","reportUnhandledError","noop","errorContext","Subscriber","__extends","destination","_this","EMPTY_OBSERVER","next","complete","SafeSubscriber","ConsumerObserver","partialObserver","handleUnhandledError","observerOrNext","defaultErrorHandler","observable","identity","x","pipeFromArray","fns","prev","fn","Observable","subscribe","operator","subscriber","isSubscriber","sink","promiseCtor","getPromiseCtor","Symbol_observable","operations","isObserver","hasLift","operate","init","liftedSource","createOperatorSubscriber","onNext","onComplete","onError","onFinalize","OperatorSubscriber","shouldUnsubscribe","closed_1","isArrayLike","isPromise","isInteropObservable","isAsyncIterable","createInvalidObservableTypeError","getSymbolIterator","iterator","isIterable","Symbol_iterator","readableStreamLikeToAsyncGenerator","readableStream","__asyncGenerator","reader","done","__await","isReadableStreamLike","innerFrom","fromInteropObservable","fromArrayLike","fromPromise","fromAsyncIterable","fromIterable","fromReadableStreamLike","obs","array","promise","iterable","iterable_1","iterable_1_1","asyncIterable","process","asyncIterable_1","asyncIterable_1_1","__asyncValues","executeSchedule","parentSubscription","scheduler","work","repeat","scheduleSubscription","observeOn","subscribeOn","scheduleObservable","schedulePromise","scheduleArray","scheduleIterable","scheduleAsyncIterable","scheduleReadableStreamLike","scheduled","from","map","project","thisArg","filter","predicate","isWebWorker","selfContext","Reachability","_","globalObj","observer","notifyOnline","notifyOffline","_observer","AuthClass","authResourcesConfig","authOptions","getCustomEndpointWarningMessage","credentialsAndIdentityId","userSub","tokens","target","AmplifyClass","libraryOptions","resolvedResourceConfig","Amplify","fetchAuthSession","amplify","fetchAuthSession$1","MAX_DELAY_MS","jitteredBackoff","maxDelayMs","amplifyUuid","AmplifyUrl","AmplifyUrlSearchParams","getSignedHeaders","AMZ_DATE_QUERY_PARAM","TOKEN_QUERY_PARAM","AUTH_HEADER","HOST_HEADER","AMZ_DATE_HEADER","TOKEN_HEADER","KEY_TYPE_IDENTIFIER","SHA256_ALGORITHM_IDENTIFIER","SIGNATURE_IDENTIFIER","EMPTY_HASH","UNSIGNED_PAYLOAD","getCredentialScope","date","getFormattedDates","longDate","getSigningValues","credentials","signingDate","signingRegion","signingService","uriEscapePath","accessKeyId","secretAccessKey","sessionToken","shortDate","credentialScope","getHashedData","sha256","getHashedDataAsHex","hashedData","getCanonicalHeaders","a","b","entry","getCanonicalQueryString","searchParams","keyA","valA","keyB","valB","val","escapeUri","uri","hexEncode","c","getCanonicalUri","pathname","getHashedPayload","body","isSourceData","isArrayBuffer","arg","getCanonicalRequest","method","getSigningKey","dateKey","regionKey","serviceKey","getStringToSign","hashedRequest","getSignature","request","canonicalRequest","stringToSign","signRequest","signingValues","requestToSign","signature","credentialEntry","signedHeadersEntry","signatureEntry","_typeof","isObjectLike","SYMBOL_TO_STRING_TAG","getLocation","lineRegexp","line","column","match","printLocation","location","printSourceLocation","sourceLocation","firstLineColumnOffset","whitespace","lineIndex","lineOffset","lineNum","columnOffset","columnNum","locationStr","lines","locationLine","subLineIndex","subLineColumnNum","subLines","printPrefixedLines","subLine","existingLines","_ref","padLen","_ref2","_ref3","leftPad","len","str","ownKeys","enumerableOnly","keys","symbols","sym","_objectSpread","_defineProperty","_classCallCheck","Constructor","_defineProperties","descriptor","_createClass","protoProps","staticProps","_inherits","subClass","superClass","_setPrototypeOf","_createSuper","Derived","hasNativeReflectConstruct","_isNativeReflectConstruct","Super","_getPrototypeOf","NewTarget","_possibleConstructorReturn","self","call","_assertThisInitialized","_wrapNativeSuper","Class","_cache","_isNativeFunction","Wrapper","_construct","Parent","o","p","GraphQLError","_Error","nodes","positions","path","originalError","extensions","_nodeLocations","_nodeLocations2","_nodeLocations3","undefinedIfEmpty","nodeLocations","_i2","_this$nodes","_ref4","loc","pos","originalExtensions","printError","output","_i4","_error$nodes2","node","_i6","_error$locations2","NonRetryableError","jitteredExponentialRetry","bytesToString","byte","base64Encoder","inputStr","encodedStr","NON_RETRYABLE_CODES","NON_RETRYABLE_ERROR_TYPES","CONNECTION_STATE_CHANGE","MESSAGE_TYPES","SUBSCRIPTION_STATUS","SOCKET_STATUS","AWS_APPSYNC_REALTIME_HEADERS","CONNECTION_INIT_TIMEOUT","START_ACK_TIMEOUT","DEFAULT_KEEP_ALIVE_TIMEOUT","DEFAULT_KEEP_ALIVE_HEARTBEAT_TIMEOUT","DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT","RECONNECT_DELAY","RECONNECT_INTERVAL","CONTROL_MSG","ConnectionState","ReachabilityMonitor","CONNECTION_CHANGE","ConnectionStateMonitor","online","connectionStateObserver","previous","current","toInclude","statusUpdates","newSocketStatus","connectionState","networkState","intendedConnectionState","keepAliveState","ReconnectEvent","ReconnectionMonitor","reconnectObserver","protocol","standardDomainPattern","eventDomainPattern","customDomainPath","isCustomDomain","isEventDomain","getRealtimeEndpointUrl","appSyncGraphqlEndpoint","realtimeEndpoint","extractNonAuthHeaders","nonAuthHeaders","queryParamsFromCustomHeaders","k","v","realtimeUrlWithQueryString","urlParams","realtimeEndpointUrl","existingParams","additionalHeadersFromOptions","query","libraryConfigHeaders","additionalHeaders","authToken","additionalCustomHeaders","_libraryConfigHeaders","awsAuthTokenHeader","host","awsRealTimeApiKeyHeader","apiKey","dtStr","awsRealTimeIAMHeader","canonicalUri","endpointInfo","creds","customAuthHeader","awsRealTimeHeaderBasedAuth","authenticationType","headerHandler","resolvedApiKey","dispatchApiEvent","AWSWebSocketProvider","awsRealTimeUrl","subprotocol","errorType","errorCode","subscriptionStartInProgress","subscriptionId","startSubscription","reconnectSubscription","reconnectSubscriptionObserver","serializedSubscriptionMessage","publishListener","cleanup","errorTypes","errorListener","closeListener","subscriptionState","variables","subscriptionFailedCallback","subscriptionReadyCallback","subscriptionObserver","observedSubscriptionState","unsubscribeMessage","stringToAWSRealTime","tempSocket","connectionTimeoutMs","currentTime","isData","id","startAckTimeoutId","errorMessage","isAuthError","AUTH_ERROR_TYPES","authHeader","headerString","authTokenSubprotocol","queryParams","res","rej","newSocket","ackOk","gqlInit","checkAckOk","targetAckOk","normalizeAuth","explicitAuthMode","configure","eventsConfig","configAuthMode","serializeEvents","events","ev","idx","eventJson","PROVIDER_NAME","WS_PROTOCOL_NAME","CONNECT_URI","AWSAppSyncEventProvider","publish","serializedData","subscriptionMessage","deserializedEvent","AppSyncEventProvider","openChannels","connect","providerOptions","channelId","_subscription","subOptions","subscribeOptions","pubOptions","publishOptions","$constructor","initializer","inst","def","proto","Definition","$ZodAsyncError","$ZodEncodeError","globalConfig","newConfig","getEnumValues","entries","numericValues","jsonStringifyReplacer","cached","getter","nullish","cleanRegex","start","end","EVALUATING","defineLazy","assignProp","prop","mergeDefs","defs","mergedDescriptors","descriptors","esc","slugify","captureStackTrace","_args","isObject","allowsEval","F","isPlainObject","ctor","prot","shallowClone","propertyKeyTypes","escapeRegex","clone","cl","normalizeParams","_params","optionalKeys","shape","pick","schema","mask","currDef","checks","newShape","omit","extend","existingShape","_shape","safeExtend","merge","partial","oldShape","required","aborted","startIndex","explicitlyAborted","prefixIssues","issues","iss","unwrapMessage","finalizeIssue","ctx","_inst","_continue","_input","rest","getLengthableOrigin","issue","util.jsonStringifyReplacer","$ZodError","$ZodRealError","flattenError","mapper","fieldErrors","formErrors","sub","formatError","processError","fullpath","el","_parse","_Err","_ctx","core.$ZodAsyncError","util.finalizeIssue","core.config","util.captureStackTrace","_parseAsync","_safeParse","errors.$ZodError","safeParse","errors.$ZodRealError","_safeParseAsync","safeParseAsync","_encode","_decode","_encodeAsync","_decodeAsync","_safeEncode","_safeDecode","_safeEncodeAsync","_safeDecodeAsync","cuid","cuid2","ulid","xid","ksuid","nanoid","duration","guid","uuid","email","_emoji","emoji","ipv4","ipv6","cidrv4","cidrv6","base64","base64url","httpProtocol","e164","dateSource","timeSource","hhmm","time","datetime","opts","timeRegex","string","regex","_null","lowercase","uppercase","$ZodCheck","core.$constructor","$ZodCheckMaxLength","util.nullish","origin","util.getLengthableOrigin","$ZodCheckMinLength","$ZodCheckLengthEquals","bag","length","tooBig","$ZodCheckStringFormat","$ZodCheckRegex","$ZodCheckLowerCase","regexes.lowercase","$ZodCheckUpperCase","regexes.uppercase","$ZodCheckIncludes","escapedRegex","util.escapeRegex","pattern","$ZodCheckStartsWith","$ZodCheckEndsWith","$ZodCheckOverwrite","Doc","minIndent","dedented","$ZodType","ch","runChecks","isAborted","util.aborted","asyncResult","util.explicitlyAborted","currLen","handleCanaryResult","canary","checkResult","util.defineLazy","r","$ZodString","regexes.string","$ZodStringFormat","checks.$ZodCheckStringFormat","$ZodGUID","regexes.guid","$ZodUUID","regexes.uuid","$ZodEmail","regexes.email","$ZodURL","trimmed","regexes.httpProtocol","$ZodEmoji","regexes.emoji","$ZodNanoID","regexes.nanoid","$ZodCUID","regexes.cuid","$ZodCUID2","regexes.cuid2","$ZodULID","regexes.ulid","$ZodXID","regexes.xid","$ZodKSUID","regexes.ksuid","$ZodISODateTime","regexes.datetime","$ZodISODate","regexes.date","$ZodISOTime","regexes.time","$ZodISODuration","regexes.duration","$ZodIPv4","regexes.ipv4","$ZodIPv6","regexes.ipv6","$ZodCIDRv4","regexes.cidrv4","$ZodCIDRv6","regexes.cidrv6","parts","address","prefixNum","isValidBase64","$ZodBase64","regexes.base64","isValidBase64URL","regexes.base64url","padded","$ZodBase64URL","$ZodE164","regexes.e164","isValidJWT","algorithm","tokensParts","header","parsedHeader","$ZodJWT","$ZodNull","regexes.null","$ZodUnknown","$ZodNever","handleArrayResult","final","util.prefixIssues","$ZodArray","proms","handlePropertyResult","isOptionalIn","isOptionalOut","isPresent","normalizeDef","okeys","util.optionalKeys","handleCatchall","unrecognized","keySet","_catchall","t","$ZodObject","sh","newSh","_normalized","util.cached","propValues","field","util.isObject","catchall","$ZodObjectJIT","superParse","generateFastpass","doc","normalized","parseStr","util.esc","ids","counter","fastpass","jit","core.globalConfig","fastEnabled","util.allowsEval","handleUnionResults","results","nonaborted","$ZodUnion","option","patterns","util.cleanRegex","first","async","$ZodIntersection","left","right","handleIntersectionResults","mergeValues","util.isPlainObject","bKeys","sharedKeys","newObj","sharedValue","newArray","itemA","itemB","unrecKeys","unrecIssue","bothKeys","f","merged","$ZodEnum","values","util.getEnumValues","valuesSet","util.propertyKeyTypes","$ZodLiteral","$ZodTransform","core.$ZodEncodeError","_out","handleOptionalResult","$ZodOptional","$ZodExactOptional","$ZodNullable","$ZodDefault","handleDefaultResult","$ZodPrefault","$ZodNonOptional","handleNonOptionalResult","$ZodCatch","$ZodPipe","handlePipeResult","$ZodReadonly","handleReadonlyResult","$ZodCustom","checks.$ZodCheck","handleRefineResult","_iss","util.issue","$ZodRegistry","_meta","meta","pm","registry","globalRegistry","_string","util.normalizeParams","_email","_guid","_uuid","_uuidv4","_uuidv6","_uuidv7","_url","_nanoid","_cuid","_cuid2","_ulid","_xid","_ksuid","_ipv4","_ipv6","_cidrv4","_cidrv6","_base64","_base64url","_e164","_jwt","_isoDateTime","_isoDate","_isoTime","_isoDuration","_unknown","_never","_maxLength","maximum","checks.$ZodCheckMaxLength","_minLength","minimum","checks.$ZodCheckMinLength","_length","checks.$ZodCheckLengthEquals","_regex","checks.$ZodCheckRegex","_lowercase","checks.$ZodCheckLowerCase","_uppercase","checks.$ZodCheckUpperCase","_includes","includes","checks.$ZodCheckIncludes","_startsWith","checks.$ZodCheckStartsWith","_endsWith","suffix","checks.$ZodCheckEndsWith","_overwrite","tx","checks.$ZodCheckOverwrite","_normalize","form","_trim","_toLowerCase","_toUpperCase","_slugify","util.slugify","_array","_refine","_superRefine","_check","_issue","initializeContext","seen","overrideSchema","_json","processor","isTransforming","extractDefs","root","idToSchema","existing","makeURI","defsSegment","externalId","uriGenerator","defUriPrefix","defId","extractToDef","ref","ext","finalize","flattenRef","zodSchema","_cached","refSeen","refSchema","parentSeen","rootMetaId","finalized","createStandardJSONSchemaMethod","_schema","createToJSONSchemaMethod","processors","io","formatMap","stringProcessor","json","format","contentEncoding","regexes","nullProcessor","neverProcessor","unknownProcessor","enumProcessor","literalProcessor","vals","customProcessor","transformProcessor","arrayProcessor","objectProcessor","allKeys","requiredKeys","unionProcessor","isExclusive","intersectionProcessor","isSimpleIntersection","allOf","nullableProcessor","nonoptionalProcessor","defaultProcessor","prefaultProcessor","catchProcessor","catchValue","pipeProcessor","inIsTransform","innerType","readonlyProcessor","optionalProcessor","ZodISODateTime","core.$ZodISODateTime","schemas.ZodStringFormat","core._isoDateTime","ZodISODate","core.$ZodISODate","core._isoDate","ZodISOTime","core.$ZodISOTime","core._isoTime","ZodISODuration","core.$ZodISODuration","core._isoDuration","core.formatError","core.flattenError","ZodRealError","parse","core._parse","parseAsync","core._parseAsync","core._safeParse","core._safeParseAsync","encode","core._encode","decode","core._decode","encodeAsync","core._encodeAsync","decodeAsync","core._decodeAsync","safeEncode","core._safeEncode","safeDecode","core._safeDecode","safeEncodeAsync","core._safeEncodeAsync","safeDecodeAsync","core._safeDecodeAsync","_installedGroups","_installLazyMethods","group","methods","installed","bound","ZodType","core.$ZodType","parse.parse","parse.safeParse","parse.parseAsync","parse.safeParseAsync","parse.encode","parse.decode","parse.encodeAsync","parse.decodeAsync","parse.safeEncode","parse.safeDecode","parse.safeEncodeAsync","parse.safeDecodeAsync","chks","util.mergeDefs","core.clone","reg","check","refine","refinement","superRefine","checks.overwrite","optional","exactOptional","nullable","nonoptional","union","intersection","pipe","transform","d","_default","prefault","_catch","readonly","description","core.globalRegistry","_ZodString","core.$ZodString","processors.stringProcessor","checks.regex","checks.includes","checks.startsWith","checks.endsWith","checks.minLength","checks.maxLength","checks.length","checks.lowercase","checks.uppercase","checks.trim","checks.normalize","checks.toLowerCase","checks.toUpperCase","checks.slugify","ZodString","core._email","ZodEmail","core._url","ZodURL","core._jwt","ZodJWT","core._emoji","ZodEmoji","core._guid","ZodGUID","core._uuid","ZodUUID","core._uuidv4","core._uuidv6","core._uuidv7","core._nanoid","ZodNanoID","core._cuid","ZodCUID","core._cuid2","ZodCUID2","core._ulid","ZodULID","core._base64","ZodBase64","core._base64url","ZodBase64URL","core._xid","ZodXID","core._ksuid","ZodKSUID","core._ipv4","ZodIPv4","core._ipv6","ZodIPv6","core._cidrv4","ZodCIDRv4","core._cidrv6","ZodCIDRv6","core._e164","ZodE164","iso.datetime","iso.date","iso.time","iso.duration","core._string","ZodStringFormat","core.$ZodStringFormat","core.$ZodEmail","core.$ZodGUID","core.$ZodUUID","core.$ZodURL","core.$ZodEmoji","core.$ZodNanoID","core.$ZodCUID","core.$ZodCUID2","core.$ZodULID","core.$ZodXID","core.$ZodKSUID","core.$ZodIPv4","core.$ZodIPv6","core.$ZodCIDRv4","core.$ZodCIDRv6","core.$ZodBase64","core.$ZodBase64URL","core.$ZodE164","core.$ZodJWT","ZodNull","core.$ZodNull","processors.nullProcessor","core._null","ZodUnknown","core.$ZodUnknown","processors.unknownProcessor","unknown","core._unknown","ZodNever","core.$ZodNever","processors.neverProcessor","never","core._never","ZodArray","core.$ZodArray","processors.arrayProcessor","core._array","ZodObject","core.$ZodObjectJIT","processors.objectProcessor","_enum","incoming","util.extend","util.safeExtend","other","util.merge","util.pick","util.omit","util.partial","ZodOptional","util.required","ZodNonOptional","ZodUnion","core.$ZodUnion","processors.unionProcessor","ZodIntersection","core.$ZodIntersection","processors.intersectionProcessor","ZodEnum","core.$ZodEnum","processors.enumProcessor","newEntries","ZodLiteral","core.$ZodLiteral","processors.literalProcessor","literal","ZodTransform","core.$ZodTransform","processors.transformProcessor","core.$ZodOptional","processors.optionalProcessor","ZodExactOptional","core.$ZodExactOptional","ZodNullable","core.$ZodNullable","processors.nullableProcessor","ZodDefault","core.$ZodDefault","processors.defaultProcessor","defaultValue","util.shallowClone","ZodPrefault","core.$ZodPrefault","processors.prefaultProcessor","core.$ZodNonOptional","processors.nonoptionalProcessor","ZodCatch","core.$ZodCatch","processors.catchProcessor","ZodPipe","core.$ZodPipe","processors.pipeProcessor","in_","ZodReadonly","core.$ZodReadonly","processors.readonlyProcessor","ZodCustom","core.$ZodCustom","processors.customProcessor","core._refine","core._superRefine","zodConfig","utteranceSchema","z.object","z.literal","z.string","agentCognitionSchema","chatClosedExpiredSchema","agentCapturedUrlSchema","agentTopicSchema","agentSummarySchema","chatRatingSchema","breadcrumbSchema","chatEscalatedSchema","z.null","errorSchema","utteranceApiResponseSchema","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","onChatClosed","onAgentCapturedUrl","onAgentTopic","onAgentSummary","onRatingRequest","onBreadcrumb","fetchHistory","getChatToken","backupPollingInterval","isAmplifyReady","setIsAmplifyReady","processedIdsRef","useRef","eventChannelRef","activeChatIdRef","reconnectAttemptsRef","reconnectTimerRef","backupPollIntervalRef","shouldReconnectRef","isReconnectingRef","onMessageRef","onCognitionRef","onCognitionCompleteRef","onErrorRef","onChatClosedRef","onAgentCapturedUrlRef","onAgentTopicRef","onAgentSummaryRef","onRatingRequestRef","onBreadcrumbRef","fetchHistoryRef","getChatTokenRef","publishError","useErrorContext","appSyncUrl","appSyncRegion","appSyncApiKey","closeChannel","stopBackupPoll","clearReconnectTimer","connectChannel","chatIdToConnect","connectOptions","events.connect","parseResult","notification","utterance","messageId","code","getErrorMessage","cognition","capturedUrl","topic","summary","runBackupPoll","chatIdToPoll","history","startBackupPoll","scheduleReconnectRef","scheduleReconnect","chatIdToReconnect","disconnect","clearProcessedIds","unsubscribe","useMessageEvents","userName","userData","apiClient","setMessages","currentChat","setCurrentChat","isChatClosed","publishApiError","publishNetworkError","showCognition","hideCognition","useAgentCognitionContext","apiClientRef","onReceiveMessage","updatedMessages","handleRealTimeError","handleRatingRequest","handleChatClosed","onCleanMessages","onSendMessage","userMessage","newMessages","connectError","onRateChat","rating","EloquentAiApiClient","regionApiUrl","getRegionApiUrl","DEFAULT_OPTIONS","isRetryableError","getDelayMs","exponentialDelay","cappedDelay","withRetry","operation","cache","inflight","useFetch","fetcher","dedupe","setData","setError","isLoading","setIsLoading","mountedRef","fetch","cachedData","useUserIdentity","initialUserId","isReady","setIsReady","setUserId","setDeviceId","setExternalId","savedData","useSdkInitialization","apiUrlOverride","isUserIdentityReady","apiUrl","getApiUrl","setChatSettings","setIsChatClosed","isChatActive","setIsChatActive","sdkBootFetch","savedMessages","savedIsChatClosed","savedChatToken","orgResponse","orgError","wrapPromise","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","initialChat","initialMessages","initialIsChatClosed","chatInterfaceProps","propInitialOpen","propCloseButton","propCleanChatButton","chatClosedCookieName","chatOpen","setChatOpenState","getCookie","hasAppliedBootInitialOpen","setHasAppliedBootInitialOpen","bootInitialOpen","isInitiallyOpen","hasCloseButton","hasCleanChatButton","proactiveMessageHideDelay","setChatOpen","deleteCookie","setCookie","chatOpenDebounced","useDebounce","proactiveMessage","setProactiveMessage","onStartNewChat","hideProactiveMessage","useKeyboardInset","enabled","inset","setInset","viewport","update","overlap","useScrollLock","locked","scrollY","previousStyle","useAgentCognition","setIsVisible","content","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_FEATURE_HIDE_PROACTIVE_MESSAGE","INTERNAL_ONLY_BLOCK_STYLE","INTERNAL_ONLY_FEATURE_MESSAGE_CLICK","INTERNAL_ONLY_FEATURE_CLEAR_CHAT_CLICK","INTERNAL_ONLY_FEATURE_HIDE_COPY_BUTTON","INTERNAL_ONLY_ENVIRONMENT","INTERNAL_ONLY_API_URL","keyboardInset","logoPreloaded","setLogoPreloaded","LOGO_ANIMATED_URL","renderContent","wrapperCSS","Fragment","mainCSS","ChatInterface","ThemeProvider","Chat","renderChat","Component","ReactDOMClient"],"mappings":";;;;;;;;;;;;AACA,IAAI,OAAO,SAAW,KAAa;AAIjC,QAAMA,IAAkD;AAIxD,SAAO,qBAAe,EAAE,KAAK,CAACC,MAAW;AACvC,IAAAA,EAAO,KAAK;AAAA,MACV,KAAK;AAAA,MACL,aAAAD;AAAA,MACA,gBAAgB;AAAA,MA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A,oBAC1B,WAAWA,EAAiB;AAAA,oBAC5B,WAAWG;AAAA,oBACX,gBAAgB,MAAM;AACpB,sBAAAR,EAAY,EAAI,GAChBQ,EAAA;AAAA,oBACF;AAAA,oBACA,eAAeH,EAAiB;AAAA,kBAAA;AAAA,gBAAA;AAAA,cAClC;AAAA,YAAA,EAEN,CACF;AAAA,UAAA;AAAA,QAAA,IAEA;AAAA,MAAA;AAAA,IAAA;AAAA,EAAA;AAiBV,SAAO,gBAAA/yD,EAAA81D,IAAA,EAAG,UAXJZ,IACKU,GAAA,IAGLpF,KACK,gBAAAxwD,EAACc,IAAA,EAAO,WAAW0vD,IAAkB,gBAAgB,IAGvD,KAGY,CAAE;AACzB;AAEO,SAAS0F,GAAK51D,GAA4B;AAC/C,SACE,gBAAAN,EAACw0D,MACC,UAAA,gBAAAx0D,EAACs0D,IAAA,EACC,4BAACS,IAAA,EAAc,GAAGz0D,EAAA,CAAO,EAAA,CAC3B,EAAA,CACF;AAEJ;AC9SO,SAAS61D,GACdp1D,GACAT,GACiB;AAUjB,UATe,CACb81D,GACAr1D,GACAT,MACG;AACH,UAAM0xC,IAAOqkB,GAAe,WAAWt1D,CAAS;AAChD,WAAAixC,EAAK,OAAO,gBAAAhyC,EAACo2D,GAAA,EAAW,GAAG91D,GAAO,CAAE,GAC7B0xC,EAAK;AAAA,EACd,GACckkB,IAAMn1D,GAAWT,CAAK;AACtC;","x_google_ignoreList":[9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149]}