@apdesign/oms-agent 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +77 -0
- package/dist-lib/entry.css +1 -0
- package/dist-lib/entry.d.ts +62 -0
- package/dist-lib/oms-agent.cjs +144 -0
- package/dist-lib/oms-agent.cjs.map +1 -0
- package/dist-lib/oms-agent.mjs +10902 -0
- package/dist-lib/oms-agent.mjs.map +1 -0
- package/package.json +70 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oms-agent.cjs","sources":["../node_modules/react/cjs/react-jsx-runtime.production.js","../node_modules/react/cjs/react-jsx-runtime.development.js","../node_modules/react/jsx-runtime.js","../node_modules/lucide-react/dist/esm/shared/src/utils/mergeClasses.js","../node_modules/lucide-react/dist/esm/shared/src/utils/toKebabCase.js","../node_modules/lucide-react/dist/esm/shared/src/utils/toCamelCase.js","../node_modules/lucide-react/dist/esm/shared/src/utils/toPascalCase.js","../node_modules/lucide-react/dist/esm/defaultAttributes.js","../node_modules/lucide-react/dist/esm/shared/src/utils/hasA11yProp.js","../node_modules/lucide-react/dist/esm/Icon.js","../node_modules/lucide-react/dist/esm/createLucideIcon.js","../node_modules/lucide-react/dist/esm/icons/bot.js","../node_modules/lucide-react/dist/esm/icons/crosshair.js","../node_modules/lucide-react/dist/esm/icons/file-code-corner.js","../node_modules/lucide-react/dist/esm/icons/send.js","../node_modules/lucide-react/dist/esm/icons/x.js","../node_modules/clsx/dist/clsx.mjs","../node_modules/tailwind-merge/dist/bundle-mjs.mjs","../src/shared/lib/utils.ts","../node_modules/@ai-sdk/provider/dist/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","../node_modules/zod/v3/helpers/util.js","../node_modules/zod/v3/ZodError.js","../node_modules/zod/v3/helpers/errorUtil.js","../node_modules/zod/v3/types.js","../node_modules/eventsource-parser/dist/index.js","../node_modules/eventsource-parser/dist/stream.js","../node_modules/@ai-sdk/provider-utils/dist/index.mjs","../node_modules/ai/dist/index.mjs","../node_modules/throttleit/index.js","../node_modules/@ai-sdk/react/dist/index.mjs","../src/integrations/oms/config.ts","../src/shared/schemas/agent.ts","../src/features/agent/hooks/useOmsAgentChat.ts","../src/features/chat/components/OmsAgentPanel.tsx","../src/features/context/services/contextCollector.ts","../src/mocks/omsKnowledge.ts","../src/integrations/oms/bridge.ts","../src/features/chat/components/OmsAgentWidget.tsx","../src/features/inspector/hooks/useElementInspector.ts"],"sourcesContent":["/**\n * @license React\n * react-jsx-runtime.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\");\nfunction jsxProd(type, config, maybeKey) {\n var key = null;\n void 0 !== maybeKey && (key = \"\" + maybeKey);\n void 0 !== config.key && (key = \"\" + config.key);\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n config = maybeKey.ref;\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n ref: void 0 !== config ? config : null,\n props: maybeKey\n };\n}\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsxProd;\nexports.jsxs = jsxProd;\n","/**\n * @license React\n * react-jsx-runtime.development.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\n\"production\" !== process.env.NODE_ENV &&\n (function () {\n function getComponentNameFromType(type) {\n if (null == type) return null;\n if (\"function\" === typeof type)\n return type.$$typeof === REACT_CLIENT_REFERENCE\n ? null\n : type.displayName || type.name || null;\n if (\"string\" === typeof type) return type;\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return \"Fragment\";\n case REACT_PROFILER_TYPE:\n return \"Profiler\";\n case REACT_STRICT_MODE_TYPE:\n return \"StrictMode\";\n case REACT_SUSPENSE_TYPE:\n return \"Suspense\";\n case REACT_SUSPENSE_LIST_TYPE:\n return \"SuspenseList\";\n case REACT_ACTIVITY_TYPE:\n return \"Activity\";\n }\n if (\"object\" === typeof type)\n switch (\n (\"number\" === typeof type.tag &&\n console.error(\n \"Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.\"\n ),\n type.$$typeof)\n ) {\n case REACT_PORTAL_TYPE:\n return \"Portal\";\n case REACT_CONTEXT_TYPE:\n return type.displayName || \"Context\";\n case REACT_CONSUMER_TYPE:\n return (type._context.displayName || \"Context\") + \".Consumer\";\n case REACT_FORWARD_REF_TYPE:\n var innerType = type.render;\n type = type.displayName;\n type ||\n ((type = innerType.displayName || innerType.name || \"\"),\n (type = \"\" !== type ? \"ForwardRef(\" + type + \")\" : \"ForwardRef\"));\n return type;\n case REACT_MEMO_TYPE:\n return (\n (innerType = type.displayName || null),\n null !== innerType\n ? innerType\n : getComponentNameFromType(type.type) || \"Memo\"\n );\n case REACT_LAZY_TYPE:\n innerType = type._payload;\n type = type._init;\n try {\n return getComponentNameFromType(type(innerType));\n } catch (x) {}\n }\n return null;\n }\n function testStringCoercion(value) {\n return \"\" + value;\n }\n function checkKeyStringCoercion(value) {\n try {\n testStringCoercion(value);\n var JSCompiler_inline_result = !1;\n } catch (e) {\n JSCompiler_inline_result = !0;\n }\n if (JSCompiler_inline_result) {\n JSCompiler_inline_result = console;\n var JSCompiler_temp_const = JSCompiler_inline_result.error;\n var JSCompiler_inline_result$jscomp$0 =\n (\"function\" === typeof Symbol &&\n Symbol.toStringTag &&\n value[Symbol.toStringTag]) ||\n value.constructor.name ||\n \"Object\";\n JSCompiler_temp_const.call(\n JSCompiler_inline_result,\n \"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.\",\n JSCompiler_inline_result$jscomp$0\n );\n return testStringCoercion(value);\n }\n }\n function getTaskName(type) {\n if (type === REACT_FRAGMENT_TYPE) return \"<>\";\n if (\n \"object\" === typeof type &&\n null !== type &&\n type.$$typeof === REACT_LAZY_TYPE\n )\n return \"<...>\";\n try {\n var name = getComponentNameFromType(type);\n return name ? \"<\" + name + \">\" : \"<...>\";\n } catch (x) {\n return \"<...>\";\n }\n }\n function getOwner() {\n var dispatcher = ReactSharedInternals.A;\n return null === dispatcher ? null : dispatcher.getOwner();\n }\n function UnknownOwner() {\n return Error(\"react-stack-top-frame\");\n }\n function hasValidKey(config) {\n if (hasOwnProperty.call(config, \"key\")) {\n var getter = Object.getOwnPropertyDescriptor(config, \"key\").get;\n if (getter && getter.isReactWarning) return !1;\n }\n return void 0 !== config.key;\n }\n function defineKeyPropWarningGetter(props, displayName) {\n function warnAboutAccessingKey() {\n specialPropKeyWarningShown ||\n ((specialPropKeyWarningShown = !0),\n console.error(\n \"%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)\",\n displayName\n ));\n }\n warnAboutAccessingKey.isReactWarning = !0;\n Object.defineProperty(props, \"key\", {\n get: warnAboutAccessingKey,\n configurable: !0\n });\n }\n function elementRefGetterWithDeprecationWarning() {\n var componentName = getComponentNameFromType(this.type);\n didWarnAboutElementRef[componentName] ||\n ((didWarnAboutElementRef[componentName] = !0),\n console.error(\n \"Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.\"\n ));\n componentName = this.props.ref;\n return void 0 !== componentName ? componentName : null;\n }\n function ReactElement(type, key, props, owner, debugStack, debugTask) {\n var refProp = props.ref;\n type = {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n props: props,\n _owner: owner\n };\n null !== (void 0 !== refProp ? refProp : null)\n ? Object.defineProperty(type, \"ref\", {\n enumerable: !1,\n get: elementRefGetterWithDeprecationWarning\n })\n : Object.defineProperty(type, \"ref\", { enumerable: !1, value: null });\n type._store = {};\n Object.defineProperty(type._store, \"validated\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: 0\n });\n Object.defineProperty(type, \"_debugInfo\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: null\n });\n Object.defineProperty(type, \"_debugStack\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: debugStack\n });\n Object.defineProperty(type, \"_debugTask\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: debugTask\n });\n Object.freeze && (Object.freeze(type.props), Object.freeze(type));\n return type;\n }\n function jsxDEVImpl(\n type,\n config,\n maybeKey,\n isStaticChildren,\n debugStack,\n debugTask\n ) {\n var children = config.children;\n if (void 0 !== children)\n if (isStaticChildren)\n if (isArrayImpl(children)) {\n for (\n isStaticChildren = 0;\n isStaticChildren < children.length;\n isStaticChildren++\n )\n validateChildKeys(children[isStaticChildren]);\n Object.freeze && Object.freeze(children);\n } else\n console.error(\n \"React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.\"\n );\n else validateChildKeys(children);\n if (hasOwnProperty.call(config, \"key\")) {\n children = getComponentNameFromType(type);\n var keys = Object.keys(config).filter(function (k) {\n return \"key\" !== k;\n });\n isStaticChildren =\n 0 < keys.length\n ? \"{key: someKey, \" + keys.join(\": ..., \") + \": ...}\"\n : \"{key: someKey}\";\n didWarnAboutKeySpread[children + isStaticChildren] ||\n ((keys =\n 0 < keys.length ? \"{\" + keys.join(\": ..., \") + \": ...}\" : \"{}\"),\n console.error(\n 'A props object containing a \"key\" prop is being spread into JSX:\\n let props = %s;\\n <%s {...props} />\\nReact keys must be passed directly to JSX without using spread:\\n let props = %s;\\n <%s key={someKey} {...props} />',\n isStaticChildren,\n children,\n keys,\n children\n ),\n (didWarnAboutKeySpread[children + isStaticChildren] = !0));\n }\n children = null;\n void 0 !== maybeKey &&\n (checkKeyStringCoercion(maybeKey), (children = \"\" + maybeKey));\n hasValidKey(config) &&\n (checkKeyStringCoercion(config.key), (children = \"\" + config.key));\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n children &&\n defineKeyPropWarningGetter(\n maybeKey,\n \"function\" === typeof type\n ? type.displayName || type.name || \"Unknown\"\n : type\n );\n return ReactElement(\n type,\n children,\n maybeKey,\n getOwner(),\n debugStack,\n debugTask\n );\n }\n function validateChildKeys(node) {\n isValidElement(node)\n ? node._store && (node._store.validated = 1)\n : \"object\" === typeof node &&\n null !== node &&\n node.$$typeof === REACT_LAZY_TYPE &&\n (\"fulfilled\" === node._payload.status\n ? isValidElement(node._payload.value) &&\n node._payload.value._store &&\n (node._payload.value._store.validated = 1)\n : node._store && (node._store.validated = 1));\n }\n function isValidElement(object) {\n return (\n \"object\" === typeof object &&\n null !== object &&\n object.$$typeof === REACT_ELEMENT_TYPE\n );\n }\n var React = require(\"react\"),\n REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_PORTAL_TYPE = Symbol.for(\"react.portal\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\"),\n REACT_STRICT_MODE_TYPE = Symbol.for(\"react.strict_mode\"),\n REACT_PROFILER_TYPE = Symbol.for(\"react.profiler\"),\n REACT_CONSUMER_TYPE = Symbol.for(\"react.consumer\"),\n REACT_CONTEXT_TYPE = Symbol.for(\"react.context\"),\n REACT_FORWARD_REF_TYPE = Symbol.for(\"react.forward_ref\"),\n REACT_SUSPENSE_TYPE = Symbol.for(\"react.suspense\"),\n REACT_SUSPENSE_LIST_TYPE = Symbol.for(\"react.suspense_list\"),\n REACT_MEMO_TYPE = Symbol.for(\"react.memo\"),\n REACT_LAZY_TYPE = Symbol.for(\"react.lazy\"),\n REACT_ACTIVITY_TYPE = Symbol.for(\"react.activity\"),\n REACT_CLIENT_REFERENCE = Symbol.for(\"react.client.reference\"),\n ReactSharedInternals =\n React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,\n hasOwnProperty = Object.prototype.hasOwnProperty,\n isArrayImpl = Array.isArray,\n createTask = console.createTask\n ? console.createTask\n : function () {\n return null;\n };\n React = {\n react_stack_bottom_frame: function (callStackForError) {\n return callStackForError();\n }\n };\n var specialPropKeyWarningShown;\n var didWarnAboutElementRef = {};\n var unknownOwnerDebugStack = React.react_stack_bottom_frame.bind(\n React,\n UnknownOwner\n )();\n var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));\n var didWarnAboutKeySpread = {};\n exports.Fragment = REACT_FRAGMENT_TYPE;\n exports.jsx = function (type, config, maybeKey) {\n var trackActualOwner =\n 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;\n return jsxDEVImpl(\n type,\n config,\n maybeKey,\n !1,\n trackActualOwner\n ? Error(\"react-stack-top-frame\")\n : unknownOwnerDebugStack,\n trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask\n );\n };\n exports.jsxs = function (type, config, maybeKey) {\n var trackActualOwner =\n 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;\n return jsxDEVImpl(\n type,\n config,\n maybeKey,\n !0,\n trackActualOwner\n ? Error(\"react-stack-top-frame\")\n : unknownOwnerDebugStack,\n trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask\n );\n };\n })();\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","/**\n * @license lucide-react v0.577.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nconst mergeClasses = (...classes) => classes.filter((className, index, array) => {\n return Boolean(className) && className.trim() !== \"\" && array.indexOf(className) === index;\n}).join(\" \").trim();\n\nexport { mergeClasses };\n//# sourceMappingURL=mergeClasses.js.map\n","/**\n * @license lucide-react v0.577.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nconst toKebabCase = (string) => string.replace(/([a-z0-9])([A-Z])/g, \"$1-$2\").toLowerCase();\n\nexport { toKebabCase };\n//# sourceMappingURL=toKebabCase.js.map\n","/**\n * @license lucide-react v0.577.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nconst toCamelCase = (string) => string.replace(\n /^([A-Z])|[\\s-_]+(\\w)/g,\n (match, p1, p2) => p2 ? p2.toUpperCase() : p1.toLowerCase()\n);\n\nexport { toCamelCase };\n//# sourceMappingURL=toCamelCase.js.map\n","/**\n * @license lucide-react v0.577.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport { toCamelCase } from './toCamelCase.js';\n\nconst toPascalCase = (string) => {\n const camelCase = toCamelCase(string);\n return camelCase.charAt(0).toUpperCase() + camelCase.slice(1);\n};\n\nexport { toPascalCase };\n//# sourceMappingURL=toPascalCase.js.map\n","/**\n * @license lucide-react v0.577.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nvar defaultAttributes = {\n xmlns: \"http://www.w3.org/2000/svg\",\n width: 24,\n height: 24,\n viewBox: \"0 0 24 24\",\n fill: \"none\",\n stroke: \"currentColor\",\n strokeWidth: 2,\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\"\n};\n\nexport { defaultAttributes as default };\n//# sourceMappingURL=defaultAttributes.js.map\n","/**\n * @license lucide-react v0.577.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nconst hasA11yProp = (props) => {\n for (const prop in props) {\n if (prop.startsWith(\"aria-\") || prop === \"role\" || prop === \"title\") {\n return true;\n }\n }\n return false;\n};\n\nexport { hasA11yProp };\n//# sourceMappingURL=hasA11yProp.js.map\n","/**\n * @license lucide-react v0.577.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport { forwardRef, createElement } from 'react';\nimport defaultAttributes from './defaultAttributes.js';\nimport { hasA11yProp } from './shared/src/utils/hasA11yProp.js';\nimport { mergeClasses } from './shared/src/utils/mergeClasses.js';\n\nconst Icon = forwardRef(\n ({\n color = \"currentColor\",\n size = 24,\n strokeWidth = 2,\n absoluteStrokeWidth,\n className = \"\",\n children,\n iconNode,\n ...rest\n }, ref) => createElement(\n \"svg\",\n {\n ref,\n ...defaultAttributes,\n width: size,\n height: size,\n stroke: color,\n strokeWidth: absoluteStrokeWidth ? Number(strokeWidth) * 24 / Number(size) : strokeWidth,\n className: mergeClasses(\"lucide\", className),\n ...!children && !hasA11yProp(rest) && { \"aria-hidden\": \"true\" },\n ...rest\n },\n [\n ...iconNode.map(([tag, attrs]) => createElement(tag, attrs)),\n ...Array.isArray(children) ? children : [children]\n ]\n )\n);\n\nexport { Icon as default };\n//# sourceMappingURL=Icon.js.map\n","/**\n * @license lucide-react v0.577.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport { forwardRef, createElement } from 'react';\nimport { mergeClasses } from './shared/src/utils/mergeClasses.js';\nimport { toKebabCase } from './shared/src/utils/toKebabCase.js';\nimport { toPascalCase } from './shared/src/utils/toPascalCase.js';\nimport Icon from './Icon.js';\n\nconst createLucideIcon = (iconName, iconNode) => {\n const Component = forwardRef(\n ({ className, ...props }, ref) => createElement(Icon, {\n ref,\n iconNode,\n className: mergeClasses(\n `lucide-${toKebabCase(toPascalCase(iconName))}`,\n `lucide-${iconName}`,\n className\n ),\n ...props\n })\n );\n Component.displayName = toPascalCase(iconName);\n return Component;\n};\n\nexport { createLucideIcon as default };\n//# sourceMappingURL=createLucideIcon.js.map\n","/**\n * @license lucide-react v0.577.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"path\", { d: \"M12 8V4H8\", key: \"hb8ula\" }],\n [\"rect\", { width: \"16\", height: \"12\", x: \"4\", y: \"8\", rx: \"2\", key: \"enze0r\" }],\n [\"path\", { d: \"M2 14h2\", key: \"vft8re\" }],\n [\"path\", { d: \"M20 14h2\", key: \"4cs60a\" }],\n [\"path\", { d: \"M15 13v2\", key: \"1xurst\" }],\n [\"path\", { d: \"M9 13v2\", key: \"rq6x2g\" }]\n];\nconst Bot = createLucideIcon(\"bot\", __iconNode);\n\nexport { __iconNode, Bot as default };\n//# sourceMappingURL=bot.js.map\n","/**\n * @license lucide-react v0.577.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"circle\", { cx: \"12\", cy: \"12\", r: \"10\", key: \"1mglay\" }],\n [\"line\", { x1: \"22\", x2: \"18\", y1: \"12\", y2: \"12\", key: \"l9bcsi\" }],\n [\"line\", { x1: \"6\", x2: \"2\", y1: \"12\", y2: \"12\", key: \"13hhkx\" }],\n [\"line\", { x1: \"12\", x2: \"12\", y1: \"6\", y2: \"2\", key: \"10w3f3\" }],\n [\"line\", { x1: \"12\", x2: \"12\", y1: \"22\", y2: \"18\", key: \"15g9kq\" }]\n];\nconst Crosshair = createLucideIcon(\"crosshair\", __iconNode);\n\nexport { __iconNode, Crosshair as default };\n//# sourceMappingURL=crosshair.js.map\n","/**\n * @license lucide-react v0.577.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\n \"path\",\n {\n d: \"M4 12.15V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2h-3.35\",\n key: \"1wthlu\"\n }\n ],\n [\"path\", { d: \"M14 2v5a1 1 0 0 0 1 1h5\", key: \"wfsgrz\" }],\n [\"path\", { d: \"m5 16-3 3 3 3\", key: \"331omg\" }],\n [\"path\", { d: \"m9 22 3-3-3-3\", key: \"lsp7cz\" }]\n];\nconst FileCodeCorner = createLucideIcon(\"file-code-corner\", __iconNode);\n\nexport { __iconNode, FileCodeCorner as default };\n//# sourceMappingURL=file-code-corner.js.map\n","/**\n * @license lucide-react v0.577.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\n \"path\",\n {\n d: \"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z\",\n key: \"1ffxy3\"\n }\n ],\n [\"path\", { d: \"m21.854 2.147-10.94 10.939\", key: \"12cjpa\" }]\n];\nconst Send = createLucideIcon(\"send\", __iconNode);\n\nexport { __iconNode, Send as default };\n//# sourceMappingURL=send.js.map\n","/**\n * @license lucide-react v0.577.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.js';\n\nconst __iconNode = [\n [\"path\", { d: \"M18 6 6 18\", key: \"1bl5f8\" }],\n [\"path\", { d: \"m6 6 12 12\", key: \"d8bk6v\" }]\n];\nconst X = createLucideIcon(\"x\", __iconNode);\n\nexport { __iconNode, X as default };\n//# sourceMappingURL=x.js.map\n","function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=\" \"),n+=f)}else for(f in e)e[f]&&(n&&(n+=\" \"),n+=f);return n}export function clsx(){for(var e,t,f=0,n=\"\",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=\" \"),n+=t);return n}export default clsx;","/**\n * Concatenates two arrays faster than the array spread operator.\n */\nconst concatArrays = (array1, array2) => {\n // Pre-allocate for better V8 optimization\n const combinedArray = new Array(array1.length + array2.length);\n for (let i = 0; i < array1.length; i++) {\n combinedArray[i] = array1[i];\n }\n for (let i = 0; i < array2.length; i++) {\n combinedArray[array1.length + i] = array2[i];\n }\n return combinedArray;\n};\n\n// Factory function ensures consistent object shapes\nconst createClassValidatorObject = (classGroupId, validator) => ({\n classGroupId,\n validator\n});\n// Factory ensures consistent ClassPartObject shape\nconst createClassPartObject = (nextPart = new Map(), validators = null, classGroupId) => ({\n nextPart,\n validators,\n classGroupId\n});\nconst CLASS_PART_SEPARATOR = '-';\nconst EMPTY_CONFLICTS = [];\n// I use two dots here because one dot is used as prefix for class groups in plugins\nconst ARBITRARY_PROPERTY_PREFIX = 'arbitrary..';\nconst createClassGroupUtils = config => {\n const classMap = createClassMap(config);\n const {\n conflictingClassGroups,\n conflictingClassGroupModifiers\n } = config;\n const getClassGroupId = className => {\n if (className.startsWith('[') && className.endsWith(']')) {\n return getGroupIdForArbitraryProperty(className);\n }\n const classParts = className.split(CLASS_PART_SEPARATOR);\n // Classes like `-inset-1` produce an empty string as first classPart. We assume that classes for negative values are used correctly and skip it.\n const startIndex = classParts[0] === '' && classParts.length > 1 ? 1 : 0;\n return getGroupRecursive(classParts, startIndex, classMap);\n };\n const getConflictingClassGroupIds = (classGroupId, hasPostfixModifier) => {\n if (hasPostfixModifier) {\n const modifierConflicts = conflictingClassGroupModifiers[classGroupId];\n const baseConflicts = conflictingClassGroups[classGroupId];\n if (modifierConflicts) {\n if (baseConflicts) {\n // Merge base conflicts with modifier conflicts\n return concatArrays(baseConflicts, modifierConflicts);\n }\n // Only modifier conflicts\n return modifierConflicts;\n }\n // Fall back to without postfix if no modifier conflicts\n return baseConflicts || EMPTY_CONFLICTS;\n }\n return conflictingClassGroups[classGroupId] || EMPTY_CONFLICTS;\n };\n return {\n getClassGroupId,\n getConflictingClassGroupIds\n };\n};\nconst getGroupRecursive = (classParts, startIndex, classPartObject) => {\n const classPathsLength = classParts.length - startIndex;\n if (classPathsLength === 0) {\n return classPartObject.classGroupId;\n }\n const currentClassPart = classParts[startIndex];\n const nextClassPartObject = classPartObject.nextPart.get(currentClassPart);\n if (nextClassPartObject) {\n const result = getGroupRecursive(classParts, startIndex + 1, nextClassPartObject);\n if (result) return result;\n }\n const validators = classPartObject.validators;\n if (validators === null) {\n return undefined;\n }\n // Build classRest string efficiently by joining from startIndex onwards\n const classRest = startIndex === 0 ? classParts.join(CLASS_PART_SEPARATOR) : classParts.slice(startIndex).join(CLASS_PART_SEPARATOR);\n const validatorsLength = validators.length;\n for (let i = 0; i < validatorsLength; i++) {\n const validatorObj = validators[i];\n if (validatorObj.validator(classRest)) {\n return validatorObj.classGroupId;\n }\n }\n return undefined;\n};\n/**\n * Get the class group ID for an arbitrary property.\n *\n * @param className - The class name to get the group ID for. Is expected to be string starting with `[` and ending with `]`.\n */\nconst getGroupIdForArbitraryProperty = className => className.slice(1, -1).indexOf(':') === -1 ? undefined : (() => {\n const content = className.slice(1, -1);\n const colonIndex = content.indexOf(':');\n const property = content.slice(0, colonIndex);\n return property ? ARBITRARY_PROPERTY_PREFIX + property : undefined;\n})();\n/**\n * Exported for testing only\n */\nconst createClassMap = config => {\n const {\n theme,\n classGroups\n } = config;\n return processClassGroups(classGroups, theme);\n};\n// Split into separate functions to maintain monomorphic call sites\nconst processClassGroups = (classGroups, theme) => {\n const classMap = createClassPartObject();\n for (const classGroupId in classGroups) {\n const group = classGroups[classGroupId];\n processClassesRecursively(group, classMap, classGroupId, theme);\n }\n return classMap;\n};\nconst processClassesRecursively = (classGroup, classPartObject, classGroupId, theme) => {\n const len = classGroup.length;\n for (let i = 0; i < len; i++) {\n const classDefinition = classGroup[i];\n processClassDefinition(classDefinition, classPartObject, classGroupId, theme);\n }\n};\n// Split into separate functions for each type to maintain monomorphic call sites\nconst processClassDefinition = (classDefinition, classPartObject, classGroupId, theme) => {\n if (typeof classDefinition === 'string') {\n processStringDefinition(classDefinition, classPartObject, classGroupId);\n return;\n }\n if (typeof classDefinition === 'function') {\n processFunctionDefinition(classDefinition, classPartObject, classGroupId, theme);\n return;\n }\n processObjectDefinition(classDefinition, classPartObject, classGroupId, theme);\n};\nconst processStringDefinition = (classDefinition, classPartObject, classGroupId) => {\n const classPartObjectToEdit = classDefinition === '' ? classPartObject : getPart(classPartObject, classDefinition);\n classPartObjectToEdit.classGroupId = classGroupId;\n};\nconst processFunctionDefinition = (classDefinition, classPartObject, classGroupId, theme) => {\n if (isThemeGetter(classDefinition)) {\n processClassesRecursively(classDefinition(theme), classPartObject, classGroupId, theme);\n return;\n }\n if (classPartObject.validators === null) {\n classPartObject.validators = [];\n }\n classPartObject.validators.push(createClassValidatorObject(classGroupId, classDefinition));\n};\nconst processObjectDefinition = (classDefinition, classPartObject, classGroupId, theme) => {\n const entries = Object.entries(classDefinition);\n const len = entries.length;\n for (let i = 0; i < len; i++) {\n const [key, value] = entries[i];\n processClassesRecursively(value, getPart(classPartObject, key), classGroupId, theme);\n }\n};\nconst getPart = (classPartObject, path) => {\n let current = classPartObject;\n const parts = path.split(CLASS_PART_SEPARATOR);\n const len = parts.length;\n for (let i = 0; i < len; i++) {\n const part = parts[i];\n let next = current.nextPart.get(part);\n if (!next) {\n next = createClassPartObject();\n current.nextPart.set(part, next);\n }\n current = next;\n }\n return current;\n};\n// Type guard maintains monomorphic check\nconst isThemeGetter = func => 'isThemeGetter' in func && func.isThemeGetter === true;\n\n// LRU cache implementation using plain objects for simplicity\nconst createLruCache = maxCacheSize => {\n if (maxCacheSize < 1) {\n return {\n get: () => undefined,\n set: () => {}\n };\n }\n let cacheSize = 0;\n let cache = Object.create(null);\n let previousCache = Object.create(null);\n const update = (key, value) => {\n cache[key] = value;\n cacheSize++;\n if (cacheSize > maxCacheSize) {\n cacheSize = 0;\n previousCache = cache;\n cache = Object.create(null);\n }\n };\n return {\n get(key) {\n let value = cache[key];\n if (value !== undefined) {\n return value;\n }\n if ((value = previousCache[key]) !== undefined) {\n update(key, value);\n return value;\n }\n },\n set(key, value) {\n if (key in cache) {\n cache[key] = value;\n } else {\n update(key, value);\n }\n }\n };\n};\nconst IMPORTANT_MODIFIER = '!';\nconst MODIFIER_SEPARATOR = ':';\nconst EMPTY_MODIFIERS = [];\n// Pre-allocated result object shape for consistency\nconst createResultObject = (modifiers, hasImportantModifier, baseClassName, maybePostfixModifierPosition, isExternal) => ({\n modifiers,\n hasImportantModifier,\n baseClassName,\n maybePostfixModifierPosition,\n isExternal\n});\nconst createParseClassName = config => {\n const {\n prefix,\n experimentalParseClassName\n } = config;\n /**\n * Parse class name into parts.\n *\n * Inspired by `splitAtTopLevelOnly` used in Tailwind CSS\n * @see https://github.com/tailwindlabs/tailwindcss/blob/v3.2.2/src/util/splitAtTopLevelOnly.js\n */\n let parseClassName = className => {\n // Use simple array with push for better performance\n const modifiers = [];\n let bracketDepth = 0;\n let parenDepth = 0;\n let modifierStart = 0;\n let postfixModifierPosition;\n const len = className.length;\n for (let index = 0; index < len; index++) {\n const currentCharacter = className[index];\n if (bracketDepth === 0 && parenDepth === 0) {\n if (currentCharacter === MODIFIER_SEPARATOR) {\n modifiers.push(className.slice(modifierStart, index));\n modifierStart = index + 1;\n continue;\n }\n if (currentCharacter === '/') {\n postfixModifierPosition = index;\n continue;\n }\n }\n if (currentCharacter === '[') bracketDepth++;else if (currentCharacter === ']') bracketDepth--;else if (currentCharacter === '(') parenDepth++;else if (currentCharacter === ')') parenDepth--;\n }\n const baseClassNameWithImportantModifier = modifiers.length === 0 ? className : className.slice(modifierStart);\n // Inline important modifier check\n let baseClassName = baseClassNameWithImportantModifier;\n let hasImportantModifier = false;\n if (baseClassNameWithImportantModifier.endsWith(IMPORTANT_MODIFIER)) {\n baseClassName = baseClassNameWithImportantModifier.slice(0, -1);\n hasImportantModifier = true;\n } else if (\n /**\n * In Tailwind CSS v3 the important modifier was at the start of the base class name. This is still supported for legacy reasons.\n * @see https://github.com/dcastil/tailwind-merge/issues/513#issuecomment-2614029864\n */\n baseClassNameWithImportantModifier.startsWith(IMPORTANT_MODIFIER)) {\n baseClassName = baseClassNameWithImportantModifier.slice(1);\n hasImportantModifier = true;\n }\n const maybePostfixModifierPosition = postfixModifierPosition && postfixModifierPosition > modifierStart ? postfixModifierPosition - modifierStart : undefined;\n return createResultObject(modifiers, hasImportantModifier, baseClassName, maybePostfixModifierPosition);\n };\n if (prefix) {\n const fullPrefix = prefix + MODIFIER_SEPARATOR;\n const parseClassNameOriginal = parseClassName;\n parseClassName = className => className.startsWith(fullPrefix) ? parseClassNameOriginal(className.slice(fullPrefix.length)) : createResultObject(EMPTY_MODIFIERS, false, className, undefined, true);\n }\n if (experimentalParseClassName) {\n const parseClassNameOriginal = parseClassName;\n parseClassName = className => experimentalParseClassName({\n className,\n parseClassName: parseClassNameOriginal\n });\n }\n return parseClassName;\n};\n\n/**\n * Sorts modifiers according to following schema:\n * - Predefined modifiers are sorted alphabetically\n * - When an arbitrary variant appears, it must be preserved which modifiers are before and after it\n */\nconst createSortModifiers = config => {\n // Pre-compute weights for all known modifiers for O(1) comparison\n const modifierWeights = new Map();\n // Assign weights to sensitive modifiers (highest priority, but preserve order)\n config.orderSensitiveModifiers.forEach((mod, index) => {\n modifierWeights.set(mod, 1000000 + index); // High weights for sensitive mods\n });\n return modifiers => {\n const result = [];\n let currentSegment = [];\n // Process modifiers in one pass\n for (let i = 0; i < modifiers.length; i++) {\n const modifier = modifiers[i];\n // Check if modifier is sensitive (starts with '[' or in orderSensitiveModifiers)\n const isArbitrary = modifier[0] === '[';\n const isOrderSensitive = modifierWeights.has(modifier);\n if (isArbitrary || isOrderSensitive) {\n // Sort and flush current segment alphabetically\n if (currentSegment.length > 0) {\n currentSegment.sort();\n result.push(...currentSegment);\n currentSegment = [];\n }\n result.push(modifier);\n } else {\n // Regular modifier - add to current segment for batch sorting\n currentSegment.push(modifier);\n }\n }\n // Sort and add any remaining segment items\n if (currentSegment.length > 0) {\n currentSegment.sort();\n result.push(...currentSegment);\n }\n return result;\n };\n};\nconst createConfigUtils = config => ({\n cache: createLruCache(config.cacheSize),\n parseClassName: createParseClassName(config),\n sortModifiers: createSortModifiers(config),\n ...createClassGroupUtils(config)\n});\nconst SPLIT_CLASSES_REGEX = /\\s+/;\nconst mergeClassList = (classList, configUtils) => {\n const {\n parseClassName,\n getClassGroupId,\n getConflictingClassGroupIds,\n sortModifiers\n } = configUtils;\n /**\n * Set of classGroupIds in following format:\n * `{importantModifier}{variantModifiers}{classGroupId}`\n * @example 'float'\n * @example 'hover:focus:bg-color'\n * @example 'md:!pr'\n */\n const classGroupsInConflict = [];\n const classNames = classList.trim().split(SPLIT_CLASSES_REGEX);\n let result = '';\n for (let index = classNames.length - 1; index >= 0; index -= 1) {\n const originalClassName = classNames[index];\n const {\n isExternal,\n modifiers,\n hasImportantModifier,\n baseClassName,\n maybePostfixModifierPosition\n } = parseClassName(originalClassName);\n if (isExternal) {\n result = originalClassName + (result.length > 0 ? ' ' + result : result);\n continue;\n }\n let hasPostfixModifier = !!maybePostfixModifierPosition;\n let classGroupId = getClassGroupId(hasPostfixModifier ? baseClassName.substring(0, maybePostfixModifierPosition) : baseClassName);\n if (!classGroupId) {\n if (!hasPostfixModifier) {\n // Not a Tailwind class\n result = originalClassName + (result.length > 0 ? ' ' + result : result);\n continue;\n }\n classGroupId = getClassGroupId(baseClassName);\n if (!classGroupId) {\n // Not a Tailwind class\n result = originalClassName + (result.length > 0 ? ' ' + result : result);\n continue;\n }\n hasPostfixModifier = false;\n }\n // Fast path: skip sorting for empty or single modifier\n const variantModifier = modifiers.length === 0 ? '' : modifiers.length === 1 ? modifiers[0] : sortModifiers(modifiers).join(':');\n const modifierId = hasImportantModifier ? variantModifier + IMPORTANT_MODIFIER : variantModifier;\n const classId = modifierId + classGroupId;\n if (classGroupsInConflict.indexOf(classId) > -1) {\n // Tailwind class omitted due to conflict\n continue;\n }\n classGroupsInConflict.push(classId);\n const conflictGroups = getConflictingClassGroupIds(classGroupId, hasPostfixModifier);\n for (let i = 0; i < conflictGroups.length; ++i) {\n const group = conflictGroups[i];\n classGroupsInConflict.push(modifierId + group);\n }\n // Tailwind class not in conflict\n result = originalClassName + (result.length > 0 ? ' ' + result : result);\n }\n return result;\n};\n\n/**\n * The code in this file is copied from https://github.com/lukeed/clsx and modified to suit the needs of tailwind-merge better.\n *\n * Specifically:\n * - Runtime code from https://github.com/lukeed/clsx/blob/v1.2.1/src/index.js\n * - TypeScript types from https://github.com/lukeed/clsx/blob/v1.2.1/clsx.d.ts\n *\n * Original code has MIT license: Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com)\n */\nconst twJoin = (...classLists) => {\n let index = 0;\n let argument;\n let resolvedValue;\n let string = '';\n while (index < classLists.length) {\n if (argument = classLists[index++]) {\n if (resolvedValue = toValue(argument)) {\n string && (string += ' ');\n string += resolvedValue;\n }\n }\n }\n return string;\n};\nconst toValue = mix => {\n // Fast path for strings\n if (typeof mix === 'string') {\n return mix;\n }\n let resolvedValue;\n let string = '';\n for (let k = 0; k < mix.length; k++) {\n if (mix[k]) {\n if (resolvedValue = toValue(mix[k])) {\n string && (string += ' ');\n string += resolvedValue;\n }\n }\n }\n return string;\n};\nconst createTailwindMerge = (createConfigFirst, ...createConfigRest) => {\n let configUtils;\n let cacheGet;\n let cacheSet;\n let functionToCall;\n const initTailwindMerge = classList => {\n const config = createConfigRest.reduce((previousConfig, createConfigCurrent) => createConfigCurrent(previousConfig), createConfigFirst());\n configUtils = createConfigUtils(config);\n cacheGet = configUtils.cache.get;\n cacheSet = configUtils.cache.set;\n functionToCall = tailwindMerge;\n return tailwindMerge(classList);\n };\n const tailwindMerge = classList => {\n const cachedResult = cacheGet(classList);\n if (cachedResult) {\n return cachedResult;\n }\n const result = mergeClassList(classList, configUtils);\n cacheSet(classList, result);\n return result;\n };\n functionToCall = initTailwindMerge;\n return (...args) => functionToCall(twJoin(...args));\n};\nconst fallbackThemeArr = [];\nconst fromTheme = key => {\n const themeGetter = theme => theme[key] || fallbackThemeArr;\n themeGetter.isThemeGetter = true;\n return themeGetter;\n};\nconst arbitraryValueRegex = /^\\[(?:(\\w[\\w-]*):)?(.+)\\]$/i;\nconst arbitraryVariableRegex = /^\\((?:(\\w[\\w-]*):)?(.+)\\)$/i;\nconst fractionRegex = /^\\d+(?:\\.\\d+)?\\/\\d+(?:\\.\\d+)?$/;\nconst tshirtUnitRegex = /^(\\d+(\\.\\d+)?)?(xs|sm|md|lg|xl)$/;\nconst lengthUnitRegex = /\\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\\b(calc|min|max|clamp)\\(.+\\)|^0$/;\nconst colorFunctionRegex = /^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\\(.+\\)$/;\n// Shadow always begins with x and y offset separated by underscore optionally prepended by inset\nconst shadowRegex = /^(inset_)?-?((\\d+)?\\.?(\\d+)[a-z]+|0)_-?((\\d+)?\\.?(\\d+)[a-z]+|0)/;\nconst imageRegex = /^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\\(.+\\)$/;\nconst isFraction = value => fractionRegex.test(value);\nconst isNumber = value => !!value && !Number.isNaN(Number(value));\nconst isInteger = value => !!value && Number.isInteger(Number(value));\nconst isPercent = value => value.endsWith('%') && isNumber(value.slice(0, -1));\nconst isTshirtSize = value => tshirtUnitRegex.test(value);\nconst isAny = () => true;\nconst isLengthOnly = value =>\n// `colorFunctionRegex` check is necessary because color functions can have percentages in them which which would be incorrectly classified as lengths.\n// For example, `hsl(0 0% 0%)` would be classified as a length without this check.\n// I could also use lookbehind assertion in `lengthUnitRegex` but that isn't supported widely enough.\nlengthUnitRegex.test(value) && !colorFunctionRegex.test(value);\nconst isNever = () => false;\nconst isShadow = value => shadowRegex.test(value);\nconst isImage = value => imageRegex.test(value);\nconst isAnyNonArbitrary = value => !isArbitraryValue(value) && !isArbitraryVariable(value);\nconst isArbitrarySize = value => getIsArbitraryValue(value, isLabelSize, isNever);\nconst isArbitraryValue = value => arbitraryValueRegex.test(value);\nconst isArbitraryLength = value => getIsArbitraryValue(value, isLabelLength, isLengthOnly);\nconst isArbitraryNumber = value => getIsArbitraryValue(value, isLabelNumber, isNumber);\nconst isArbitraryWeight = value => getIsArbitraryValue(value, isLabelWeight, isAny);\nconst isArbitraryFamilyName = value => getIsArbitraryValue(value, isLabelFamilyName, isNever);\nconst isArbitraryPosition = value => getIsArbitraryValue(value, isLabelPosition, isNever);\nconst isArbitraryImage = value => getIsArbitraryValue(value, isLabelImage, isImage);\nconst isArbitraryShadow = value => getIsArbitraryValue(value, isLabelShadow, isShadow);\nconst isArbitraryVariable = value => arbitraryVariableRegex.test(value);\nconst isArbitraryVariableLength = value => getIsArbitraryVariable(value, isLabelLength);\nconst isArbitraryVariableFamilyName = value => getIsArbitraryVariable(value, isLabelFamilyName);\nconst isArbitraryVariablePosition = value => getIsArbitraryVariable(value, isLabelPosition);\nconst isArbitraryVariableSize = value => getIsArbitraryVariable(value, isLabelSize);\nconst isArbitraryVariableImage = value => getIsArbitraryVariable(value, isLabelImage);\nconst isArbitraryVariableShadow = value => getIsArbitraryVariable(value, isLabelShadow, true);\nconst isArbitraryVariableWeight = value => getIsArbitraryVariable(value, isLabelWeight, true);\n// Helpers\nconst getIsArbitraryValue = (value, testLabel, testValue) => {\n const result = arbitraryValueRegex.exec(value);\n if (result) {\n if (result[1]) {\n return testLabel(result[1]);\n }\n return testValue(result[2]);\n }\n return false;\n};\nconst getIsArbitraryVariable = (value, testLabel, shouldMatchNoLabel = false) => {\n const result = arbitraryVariableRegex.exec(value);\n if (result) {\n if (result[1]) {\n return testLabel(result[1]);\n }\n return shouldMatchNoLabel;\n }\n return false;\n};\n// Labels\nconst isLabelPosition = label => label === 'position' || label === 'percentage';\nconst isLabelImage = label => label === 'image' || label === 'url';\nconst isLabelSize = label => label === 'length' || label === 'size' || label === 'bg-size';\nconst isLabelLength = label => label === 'length';\nconst isLabelNumber = label => label === 'number';\nconst isLabelFamilyName = label => label === 'family-name';\nconst isLabelWeight = label => label === 'number' || label === 'weight';\nconst isLabelShadow = label => label === 'shadow';\nconst validators = /*#__PURE__*/Object.defineProperty({\n __proto__: null,\n isAny,\n isAnyNonArbitrary,\n isArbitraryFamilyName,\n isArbitraryImage,\n isArbitraryLength,\n isArbitraryNumber,\n isArbitraryPosition,\n isArbitraryShadow,\n isArbitrarySize,\n isArbitraryValue,\n isArbitraryVariable,\n isArbitraryVariableFamilyName,\n isArbitraryVariableImage,\n isArbitraryVariableLength,\n isArbitraryVariablePosition,\n isArbitraryVariableShadow,\n isArbitraryVariableSize,\n isArbitraryVariableWeight,\n isArbitraryWeight,\n isFraction,\n isInteger,\n isNumber,\n isPercent,\n isTshirtSize\n}, Symbol.toStringTag, {\n value: 'Module'\n});\nconst getDefaultConfig = () => {\n /**\n * Theme getters for theme variable namespaces\n * @see https://tailwindcss.com/docs/theme#theme-variable-namespaces\n */\n /***/\n const themeColor = fromTheme('color');\n const themeFont = fromTheme('font');\n const themeText = fromTheme('text');\n const themeFontWeight = fromTheme('font-weight');\n const themeTracking = fromTheme('tracking');\n const themeLeading = fromTheme('leading');\n const themeBreakpoint = fromTheme('breakpoint');\n const themeContainer = fromTheme('container');\n const themeSpacing = fromTheme('spacing');\n const themeRadius = fromTheme('radius');\n const themeShadow = fromTheme('shadow');\n const themeInsetShadow = fromTheme('inset-shadow');\n const themeTextShadow = fromTheme('text-shadow');\n const themeDropShadow = fromTheme('drop-shadow');\n const themeBlur = fromTheme('blur');\n const themePerspective = fromTheme('perspective');\n const themeAspect = fromTheme('aspect');\n const themeEase = fromTheme('ease');\n const themeAnimate = fromTheme('animate');\n /**\n * Helpers to avoid repeating the same scales\n *\n * We use functions that create a new array every time they're called instead of static arrays.\n * This ensures that users who modify any scale by mutating the array (e.g. with `array.push(element)`) don't accidentally mutate arrays in other parts of the config.\n */\n /***/\n const scaleBreak = () => ['auto', 'avoid', 'all', 'avoid-page', 'page', 'left', 'right', 'column'];\n const scalePosition = () => ['center', 'top', 'bottom', 'left', 'right', 'top-left',\n // Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378\n 'left-top', 'top-right',\n // Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378\n 'right-top', 'bottom-right',\n // Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378\n 'right-bottom', 'bottom-left',\n // Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378\n 'left-bottom'];\n const scalePositionWithArbitrary = () => [...scalePosition(), isArbitraryVariable, isArbitraryValue];\n const scaleOverflow = () => ['auto', 'hidden', 'clip', 'visible', 'scroll'];\n const scaleOverscroll = () => ['auto', 'contain', 'none'];\n const scaleUnambiguousSpacing = () => [isArbitraryVariable, isArbitraryValue, themeSpacing];\n const scaleInset = () => [isFraction, 'full', 'auto', ...scaleUnambiguousSpacing()];\n const scaleGridTemplateColsRows = () => [isInteger, 'none', 'subgrid', isArbitraryVariable, isArbitraryValue];\n const scaleGridColRowStartAndEnd = () => ['auto', {\n span: ['full', isInteger, isArbitraryVariable, isArbitraryValue]\n }, isInteger, isArbitraryVariable, isArbitraryValue];\n const scaleGridColRowStartOrEnd = () => [isInteger, 'auto', isArbitraryVariable, isArbitraryValue];\n const scaleGridAutoColsRows = () => ['auto', 'min', 'max', 'fr', isArbitraryVariable, isArbitraryValue];\n const scaleAlignPrimaryAxis = () => ['start', 'end', 'center', 'between', 'around', 'evenly', 'stretch', 'baseline', 'center-safe', 'end-safe'];\n const scaleAlignSecondaryAxis = () => ['start', 'end', 'center', 'stretch', 'center-safe', 'end-safe'];\n const scaleMargin = () => ['auto', ...scaleUnambiguousSpacing()];\n const scaleSizing = () => [isFraction, 'auto', 'full', 'dvw', 'dvh', 'lvw', 'lvh', 'svw', 'svh', 'min', 'max', 'fit', ...scaleUnambiguousSpacing()];\n const scaleSizingInline = () => [isFraction, 'screen', 'full', 'dvw', 'lvw', 'svw', 'min', 'max', 'fit', ...scaleUnambiguousSpacing()];\n const scaleSizingBlock = () => [isFraction, 'screen', 'full', 'lh', 'dvh', 'lvh', 'svh', 'min', 'max', 'fit', ...scaleUnambiguousSpacing()];\n const scaleColor = () => [themeColor, isArbitraryVariable, isArbitraryValue];\n const scaleBgPosition = () => [...scalePosition(), isArbitraryVariablePosition, isArbitraryPosition, {\n position: [isArbitraryVariable, isArbitraryValue]\n }];\n const scaleBgRepeat = () => ['no-repeat', {\n repeat: ['', 'x', 'y', 'space', 'round']\n }];\n const scaleBgSize = () => ['auto', 'cover', 'contain', isArbitraryVariableSize, isArbitrarySize, {\n size: [isArbitraryVariable, isArbitraryValue]\n }];\n const scaleGradientStopPosition = () => [isPercent, isArbitraryVariableLength, isArbitraryLength];\n const scaleRadius = () => [\n // Deprecated since Tailwind CSS v4.0.0\n '', 'none', 'full', themeRadius, isArbitraryVariable, isArbitraryValue];\n const scaleBorderWidth = () => ['', isNumber, isArbitraryVariableLength, isArbitraryLength];\n const scaleLineStyle = () => ['solid', 'dashed', 'dotted', 'double'];\n const scaleBlendMode = () => ['normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity'];\n const scaleMaskImagePosition = () => [isNumber, isPercent, isArbitraryVariablePosition, isArbitraryPosition];\n const scaleBlur = () => [\n // Deprecated since Tailwind CSS v4.0.0\n '', 'none', themeBlur, isArbitraryVariable, isArbitraryValue];\n const scaleRotate = () => ['none', isNumber, isArbitraryVariable, isArbitraryValue];\n const scaleScale = () => ['none', isNumber, isArbitraryVariable, isArbitraryValue];\n const scaleSkew = () => [isNumber, isArbitraryVariable, isArbitraryValue];\n const scaleTranslate = () => [isFraction, 'full', ...scaleUnambiguousSpacing()];\n return {\n cacheSize: 500,\n theme: {\n animate: ['spin', 'ping', 'pulse', 'bounce'],\n aspect: ['video'],\n blur: [isTshirtSize],\n breakpoint: [isTshirtSize],\n color: [isAny],\n container: [isTshirtSize],\n 'drop-shadow': [isTshirtSize],\n ease: ['in', 'out', 'in-out'],\n font: [isAnyNonArbitrary],\n 'font-weight': ['thin', 'extralight', 'light', 'normal', 'medium', 'semibold', 'bold', 'extrabold', 'black'],\n 'inset-shadow': [isTshirtSize],\n leading: ['none', 'tight', 'snug', 'normal', 'relaxed', 'loose'],\n perspective: ['dramatic', 'near', 'normal', 'midrange', 'distant', 'none'],\n radius: [isTshirtSize],\n shadow: [isTshirtSize],\n spacing: ['px', isNumber],\n text: [isTshirtSize],\n 'text-shadow': [isTshirtSize],\n tracking: ['tighter', 'tight', 'normal', 'wide', 'wider', 'widest']\n },\n classGroups: {\n // --------------\n // --- Layout ---\n // --------------\n /**\n * Aspect Ratio\n * @see https://tailwindcss.com/docs/aspect-ratio\n */\n aspect: [{\n aspect: ['auto', 'square', isFraction, isArbitraryValue, isArbitraryVariable, themeAspect]\n }],\n /**\n * Container\n * @see https://tailwindcss.com/docs/container\n * @deprecated since Tailwind CSS v4.0.0\n */\n container: ['container'],\n /**\n * Columns\n * @see https://tailwindcss.com/docs/columns\n */\n columns: [{\n columns: [isNumber, isArbitraryValue, isArbitraryVariable, themeContainer]\n }],\n /**\n * Break After\n * @see https://tailwindcss.com/docs/break-after\n */\n 'break-after': [{\n 'break-after': scaleBreak()\n }],\n /**\n * Break Before\n * @see https://tailwindcss.com/docs/break-before\n */\n 'break-before': [{\n 'break-before': scaleBreak()\n }],\n /**\n * Break Inside\n * @see https://tailwindcss.com/docs/break-inside\n */\n 'break-inside': [{\n 'break-inside': ['auto', 'avoid', 'avoid-page', 'avoid-column']\n }],\n /**\n * Box Decoration Break\n * @see https://tailwindcss.com/docs/box-decoration-break\n */\n 'box-decoration': [{\n 'box-decoration': ['slice', 'clone']\n }],\n /**\n * Box Sizing\n * @see https://tailwindcss.com/docs/box-sizing\n */\n box: [{\n box: ['border', 'content']\n }],\n /**\n * Display\n * @see https://tailwindcss.com/docs/display\n */\n display: ['block', 'inline-block', 'inline', 'flex', 'inline-flex', 'table', 'inline-table', 'table-caption', 'table-cell', 'table-column', 'table-column-group', 'table-footer-group', 'table-header-group', 'table-row-group', 'table-row', 'flow-root', 'grid', 'inline-grid', 'contents', 'list-item', 'hidden'],\n /**\n * Screen Reader Only\n * @see https://tailwindcss.com/docs/display#screen-reader-only\n */\n sr: ['sr-only', 'not-sr-only'],\n /**\n * Floats\n * @see https://tailwindcss.com/docs/float\n */\n float: [{\n float: ['right', 'left', 'none', 'start', 'end']\n }],\n /**\n * Clear\n * @see https://tailwindcss.com/docs/clear\n */\n clear: [{\n clear: ['left', 'right', 'both', 'none', 'start', 'end']\n }],\n /**\n * Isolation\n * @see https://tailwindcss.com/docs/isolation\n */\n isolation: ['isolate', 'isolation-auto'],\n /**\n * Object Fit\n * @see https://tailwindcss.com/docs/object-fit\n */\n 'object-fit': [{\n object: ['contain', 'cover', 'fill', 'none', 'scale-down']\n }],\n /**\n * Object Position\n * @see https://tailwindcss.com/docs/object-position\n */\n 'object-position': [{\n object: scalePositionWithArbitrary()\n }],\n /**\n * Overflow\n * @see https://tailwindcss.com/docs/overflow\n */\n overflow: [{\n overflow: scaleOverflow()\n }],\n /**\n * Overflow X\n * @see https://tailwindcss.com/docs/overflow\n */\n 'overflow-x': [{\n 'overflow-x': scaleOverflow()\n }],\n /**\n * Overflow Y\n * @see https://tailwindcss.com/docs/overflow\n */\n 'overflow-y': [{\n 'overflow-y': scaleOverflow()\n }],\n /**\n * Overscroll Behavior\n * @see https://tailwindcss.com/docs/overscroll-behavior\n */\n overscroll: [{\n overscroll: scaleOverscroll()\n }],\n /**\n * Overscroll Behavior X\n * @see https://tailwindcss.com/docs/overscroll-behavior\n */\n 'overscroll-x': [{\n 'overscroll-x': scaleOverscroll()\n }],\n /**\n * Overscroll Behavior Y\n * @see https://tailwindcss.com/docs/overscroll-behavior\n */\n 'overscroll-y': [{\n 'overscroll-y': scaleOverscroll()\n }],\n /**\n * Position\n * @see https://tailwindcss.com/docs/position\n */\n position: ['static', 'fixed', 'absolute', 'relative', 'sticky'],\n /**\n * Inset\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n inset: [{\n inset: scaleInset()\n }],\n /**\n * Inset Inline\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n 'inset-x': [{\n 'inset-x': scaleInset()\n }],\n /**\n * Inset Block\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n 'inset-y': [{\n 'inset-y': scaleInset()\n }],\n /**\n * Inset Inline Start\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n * @todo class group will be renamed to `inset-s` in next major release\n */\n start: [{\n 'inset-s': scaleInset(),\n /**\n * @deprecated since Tailwind CSS v4.2.0 in favor of `inset-s-*` utilities.\n * @see https://github.com/tailwindlabs/tailwindcss/pull/19613\n */\n start: scaleInset()\n }],\n /**\n * Inset Inline End\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n * @todo class group will be renamed to `inset-e` in next major release\n */\n end: [{\n 'inset-e': scaleInset(),\n /**\n * @deprecated since Tailwind CSS v4.2.0 in favor of `inset-e-*` utilities.\n * @see https://github.com/tailwindlabs/tailwindcss/pull/19613\n */\n end: scaleInset()\n }],\n /**\n * Inset Block Start\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n 'inset-bs': [{\n 'inset-bs': scaleInset()\n }],\n /**\n * Inset Block End\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n 'inset-be': [{\n 'inset-be': scaleInset()\n }],\n /**\n * Top\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n top: [{\n top: scaleInset()\n }],\n /**\n * Right\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n right: [{\n right: scaleInset()\n }],\n /**\n * Bottom\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n bottom: [{\n bottom: scaleInset()\n }],\n /**\n * Left\n * @see https://tailwindcss.com/docs/top-right-bottom-left\n */\n left: [{\n left: scaleInset()\n }],\n /**\n * Visibility\n * @see https://tailwindcss.com/docs/visibility\n */\n visibility: ['visible', 'invisible', 'collapse'],\n /**\n * Z-Index\n * @see https://tailwindcss.com/docs/z-index\n */\n z: [{\n z: [isInteger, 'auto', isArbitraryVariable, isArbitraryValue]\n }],\n // ------------------------\n // --- Flexbox and Grid ---\n // ------------------------\n /**\n * Flex Basis\n * @see https://tailwindcss.com/docs/flex-basis\n */\n basis: [{\n basis: [isFraction, 'full', 'auto', themeContainer, ...scaleUnambiguousSpacing()]\n }],\n /**\n * Flex Direction\n * @see https://tailwindcss.com/docs/flex-direction\n */\n 'flex-direction': [{\n flex: ['row', 'row-reverse', 'col', 'col-reverse']\n }],\n /**\n * Flex Wrap\n * @see https://tailwindcss.com/docs/flex-wrap\n */\n 'flex-wrap': [{\n flex: ['nowrap', 'wrap', 'wrap-reverse']\n }],\n /**\n * Flex\n * @see https://tailwindcss.com/docs/flex\n */\n flex: [{\n flex: [isNumber, isFraction, 'auto', 'initial', 'none', isArbitraryValue]\n }],\n /**\n * Flex Grow\n * @see https://tailwindcss.com/docs/flex-grow\n */\n grow: [{\n grow: ['', isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Flex Shrink\n * @see https://tailwindcss.com/docs/flex-shrink\n */\n shrink: [{\n shrink: ['', isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Order\n * @see https://tailwindcss.com/docs/order\n */\n order: [{\n order: [isInteger, 'first', 'last', 'none', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Grid Template Columns\n * @see https://tailwindcss.com/docs/grid-template-columns\n */\n 'grid-cols': [{\n 'grid-cols': scaleGridTemplateColsRows()\n }],\n /**\n * Grid Column Start / End\n * @see https://tailwindcss.com/docs/grid-column\n */\n 'col-start-end': [{\n col: scaleGridColRowStartAndEnd()\n }],\n /**\n * Grid Column Start\n * @see https://tailwindcss.com/docs/grid-column\n */\n 'col-start': [{\n 'col-start': scaleGridColRowStartOrEnd()\n }],\n /**\n * Grid Column End\n * @see https://tailwindcss.com/docs/grid-column\n */\n 'col-end': [{\n 'col-end': scaleGridColRowStartOrEnd()\n }],\n /**\n * Grid Template Rows\n * @see https://tailwindcss.com/docs/grid-template-rows\n */\n 'grid-rows': [{\n 'grid-rows': scaleGridTemplateColsRows()\n }],\n /**\n * Grid Row Start / End\n * @see https://tailwindcss.com/docs/grid-row\n */\n 'row-start-end': [{\n row: scaleGridColRowStartAndEnd()\n }],\n /**\n * Grid Row Start\n * @see https://tailwindcss.com/docs/grid-row\n */\n 'row-start': [{\n 'row-start': scaleGridColRowStartOrEnd()\n }],\n /**\n * Grid Row End\n * @see https://tailwindcss.com/docs/grid-row\n */\n 'row-end': [{\n 'row-end': scaleGridColRowStartOrEnd()\n }],\n /**\n * Grid Auto Flow\n * @see https://tailwindcss.com/docs/grid-auto-flow\n */\n 'grid-flow': [{\n 'grid-flow': ['row', 'col', 'dense', 'row-dense', 'col-dense']\n }],\n /**\n * Grid Auto Columns\n * @see https://tailwindcss.com/docs/grid-auto-columns\n */\n 'auto-cols': [{\n 'auto-cols': scaleGridAutoColsRows()\n }],\n /**\n * Grid Auto Rows\n * @see https://tailwindcss.com/docs/grid-auto-rows\n */\n 'auto-rows': [{\n 'auto-rows': scaleGridAutoColsRows()\n }],\n /**\n * Gap\n * @see https://tailwindcss.com/docs/gap\n */\n gap: [{\n gap: scaleUnambiguousSpacing()\n }],\n /**\n * Gap X\n * @see https://tailwindcss.com/docs/gap\n */\n 'gap-x': [{\n 'gap-x': scaleUnambiguousSpacing()\n }],\n /**\n * Gap Y\n * @see https://tailwindcss.com/docs/gap\n */\n 'gap-y': [{\n 'gap-y': scaleUnambiguousSpacing()\n }],\n /**\n * Justify Content\n * @see https://tailwindcss.com/docs/justify-content\n */\n 'justify-content': [{\n justify: [...scaleAlignPrimaryAxis(), 'normal']\n }],\n /**\n * Justify Items\n * @see https://tailwindcss.com/docs/justify-items\n */\n 'justify-items': [{\n 'justify-items': [...scaleAlignSecondaryAxis(), 'normal']\n }],\n /**\n * Justify Self\n * @see https://tailwindcss.com/docs/justify-self\n */\n 'justify-self': [{\n 'justify-self': ['auto', ...scaleAlignSecondaryAxis()]\n }],\n /**\n * Align Content\n * @see https://tailwindcss.com/docs/align-content\n */\n 'align-content': [{\n content: ['normal', ...scaleAlignPrimaryAxis()]\n }],\n /**\n * Align Items\n * @see https://tailwindcss.com/docs/align-items\n */\n 'align-items': [{\n items: [...scaleAlignSecondaryAxis(), {\n baseline: ['', 'last']\n }]\n }],\n /**\n * Align Self\n * @see https://tailwindcss.com/docs/align-self\n */\n 'align-self': [{\n self: ['auto', ...scaleAlignSecondaryAxis(), {\n baseline: ['', 'last']\n }]\n }],\n /**\n * Place Content\n * @see https://tailwindcss.com/docs/place-content\n */\n 'place-content': [{\n 'place-content': scaleAlignPrimaryAxis()\n }],\n /**\n * Place Items\n * @see https://tailwindcss.com/docs/place-items\n */\n 'place-items': [{\n 'place-items': [...scaleAlignSecondaryAxis(), 'baseline']\n }],\n /**\n * Place Self\n * @see https://tailwindcss.com/docs/place-self\n */\n 'place-self': [{\n 'place-self': ['auto', ...scaleAlignSecondaryAxis()]\n }],\n // Spacing\n /**\n * Padding\n * @see https://tailwindcss.com/docs/padding\n */\n p: [{\n p: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Inline\n * @see https://tailwindcss.com/docs/padding\n */\n px: [{\n px: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Block\n * @see https://tailwindcss.com/docs/padding\n */\n py: [{\n py: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Inline Start\n * @see https://tailwindcss.com/docs/padding\n */\n ps: [{\n ps: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Inline End\n * @see https://tailwindcss.com/docs/padding\n */\n pe: [{\n pe: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Block Start\n * @see https://tailwindcss.com/docs/padding\n */\n pbs: [{\n pbs: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Block End\n * @see https://tailwindcss.com/docs/padding\n */\n pbe: [{\n pbe: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Top\n * @see https://tailwindcss.com/docs/padding\n */\n pt: [{\n pt: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Right\n * @see https://tailwindcss.com/docs/padding\n */\n pr: [{\n pr: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Bottom\n * @see https://tailwindcss.com/docs/padding\n */\n pb: [{\n pb: scaleUnambiguousSpacing()\n }],\n /**\n * Padding Left\n * @see https://tailwindcss.com/docs/padding\n */\n pl: [{\n pl: scaleUnambiguousSpacing()\n }],\n /**\n * Margin\n * @see https://tailwindcss.com/docs/margin\n */\n m: [{\n m: scaleMargin()\n }],\n /**\n * Margin Inline\n * @see https://tailwindcss.com/docs/margin\n */\n mx: [{\n mx: scaleMargin()\n }],\n /**\n * Margin Block\n * @see https://tailwindcss.com/docs/margin\n */\n my: [{\n my: scaleMargin()\n }],\n /**\n * Margin Inline Start\n * @see https://tailwindcss.com/docs/margin\n */\n ms: [{\n ms: scaleMargin()\n }],\n /**\n * Margin Inline End\n * @see https://tailwindcss.com/docs/margin\n */\n me: [{\n me: scaleMargin()\n }],\n /**\n * Margin Block Start\n * @see https://tailwindcss.com/docs/margin\n */\n mbs: [{\n mbs: scaleMargin()\n }],\n /**\n * Margin Block End\n * @see https://tailwindcss.com/docs/margin\n */\n mbe: [{\n mbe: scaleMargin()\n }],\n /**\n * Margin Top\n * @see https://tailwindcss.com/docs/margin\n */\n mt: [{\n mt: scaleMargin()\n }],\n /**\n * Margin Right\n * @see https://tailwindcss.com/docs/margin\n */\n mr: [{\n mr: scaleMargin()\n }],\n /**\n * Margin Bottom\n * @see https://tailwindcss.com/docs/margin\n */\n mb: [{\n mb: scaleMargin()\n }],\n /**\n * Margin Left\n * @see https://tailwindcss.com/docs/margin\n */\n ml: [{\n ml: scaleMargin()\n }],\n /**\n * Space Between X\n * @see https://tailwindcss.com/docs/margin#adding-space-between-children\n */\n 'space-x': [{\n 'space-x': scaleUnambiguousSpacing()\n }],\n /**\n * Space Between X Reverse\n * @see https://tailwindcss.com/docs/margin#adding-space-between-children\n */\n 'space-x-reverse': ['space-x-reverse'],\n /**\n * Space Between Y\n * @see https://tailwindcss.com/docs/margin#adding-space-between-children\n */\n 'space-y': [{\n 'space-y': scaleUnambiguousSpacing()\n }],\n /**\n * Space Between Y Reverse\n * @see https://tailwindcss.com/docs/margin#adding-space-between-children\n */\n 'space-y-reverse': ['space-y-reverse'],\n // --------------\n // --- Sizing ---\n // --------------\n /**\n * Size\n * @see https://tailwindcss.com/docs/width#setting-both-width-and-height\n */\n size: [{\n size: scaleSizing()\n }],\n /**\n * Inline Size\n * @see https://tailwindcss.com/docs/width\n */\n 'inline-size': [{\n inline: ['auto', ...scaleSizingInline()]\n }],\n /**\n * Min-Inline Size\n * @see https://tailwindcss.com/docs/min-width\n */\n 'min-inline-size': [{\n 'min-inline': ['auto', ...scaleSizingInline()]\n }],\n /**\n * Max-Inline Size\n * @see https://tailwindcss.com/docs/max-width\n */\n 'max-inline-size': [{\n 'max-inline': ['none', ...scaleSizingInline()]\n }],\n /**\n * Block Size\n * @see https://tailwindcss.com/docs/height\n */\n 'block-size': [{\n block: ['auto', ...scaleSizingBlock()]\n }],\n /**\n * Min-Block Size\n * @see https://tailwindcss.com/docs/min-height\n */\n 'min-block-size': [{\n 'min-block': ['auto', ...scaleSizingBlock()]\n }],\n /**\n * Max-Block Size\n * @see https://tailwindcss.com/docs/max-height\n */\n 'max-block-size': [{\n 'max-block': ['none', ...scaleSizingBlock()]\n }],\n /**\n * Width\n * @see https://tailwindcss.com/docs/width\n */\n w: [{\n w: [themeContainer, 'screen', ...scaleSizing()]\n }],\n /**\n * Min-Width\n * @see https://tailwindcss.com/docs/min-width\n */\n 'min-w': [{\n 'min-w': [themeContainer, 'screen', /** Deprecated. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 */\n 'none', ...scaleSizing()]\n }],\n /**\n * Max-Width\n * @see https://tailwindcss.com/docs/max-width\n */\n 'max-w': [{\n 'max-w': [themeContainer, 'screen', 'none', /** Deprecated since Tailwind CSS v4.0.0. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 */\n 'prose', /** Deprecated since Tailwind CSS v4.0.0. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 */\n {\n screen: [themeBreakpoint]\n }, ...scaleSizing()]\n }],\n /**\n * Height\n * @see https://tailwindcss.com/docs/height\n */\n h: [{\n h: ['screen', 'lh', ...scaleSizing()]\n }],\n /**\n * Min-Height\n * @see https://tailwindcss.com/docs/min-height\n */\n 'min-h': [{\n 'min-h': ['screen', 'lh', 'none', ...scaleSizing()]\n }],\n /**\n * Max-Height\n * @see https://tailwindcss.com/docs/max-height\n */\n 'max-h': [{\n 'max-h': ['screen', 'lh', ...scaleSizing()]\n }],\n // ------------------\n // --- Typography ---\n // ------------------\n /**\n * Font Size\n * @see https://tailwindcss.com/docs/font-size\n */\n 'font-size': [{\n text: ['base', themeText, isArbitraryVariableLength, isArbitraryLength]\n }],\n /**\n * Font Smoothing\n * @see https://tailwindcss.com/docs/font-smoothing\n */\n 'font-smoothing': ['antialiased', 'subpixel-antialiased'],\n /**\n * Font Style\n * @see https://tailwindcss.com/docs/font-style\n */\n 'font-style': ['italic', 'not-italic'],\n /**\n * Font Weight\n * @see https://tailwindcss.com/docs/font-weight\n */\n 'font-weight': [{\n font: [themeFontWeight, isArbitraryVariableWeight, isArbitraryWeight]\n }],\n /**\n * Font Stretch\n * @see https://tailwindcss.com/docs/font-stretch\n */\n 'font-stretch': [{\n 'font-stretch': ['ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded', isPercent, isArbitraryValue]\n }],\n /**\n * Font Family\n * @see https://tailwindcss.com/docs/font-family\n */\n 'font-family': [{\n font: [isArbitraryVariableFamilyName, isArbitraryFamilyName, themeFont]\n }],\n /**\n * Font Feature Settings\n * @see https://tailwindcss.com/docs/font-feature-settings\n */\n 'font-features': [{\n 'font-features': [isArbitraryValue]\n }],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-normal': ['normal-nums'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-ordinal': ['ordinal'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-slashed-zero': ['slashed-zero'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-figure': ['lining-nums', 'oldstyle-nums'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-spacing': ['proportional-nums', 'tabular-nums'],\n /**\n * Font Variant Numeric\n * @see https://tailwindcss.com/docs/font-variant-numeric\n */\n 'fvn-fraction': ['diagonal-fractions', 'stacked-fractions'],\n /**\n * Letter Spacing\n * @see https://tailwindcss.com/docs/letter-spacing\n */\n tracking: [{\n tracking: [themeTracking, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Line Clamp\n * @see https://tailwindcss.com/docs/line-clamp\n */\n 'line-clamp': [{\n 'line-clamp': [isNumber, 'none', isArbitraryVariable, isArbitraryNumber]\n }],\n /**\n * Line Height\n * @see https://tailwindcss.com/docs/line-height\n */\n leading: [{\n leading: [/** Deprecated since Tailwind CSS v4.0.0. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 */\n themeLeading, ...scaleUnambiguousSpacing()]\n }],\n /**\n * List Style Image\n * @see https://tailwindcss.com/docs/list-style-image\n */\n 'list-image': [{\n 'list-image': ['none', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * List Style Position\n * @see https://tailwindcss.com/docs/list-style-position\n */\n 'list-style-position': [{\n list: ['inside', 'outside']\n }],\n /**\n * List Style Type\n * @see https://tailwindcss.com/docs/list-style-type\n */\n 'list-style-type': [{\n list: ['disc', 'decimal', 'none', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Text Alignment\n * @see https://tailwindcss.com/docs/text-align\n */\n 'text-alignment': [{\n text: ['left', 'center', 'right', 'justify', 'start', 'end']\n }],\n /**\n * Placeholder Color\n * @deprecated since Tailwind CSS v3.0.0\n * @see https://v3.tailwindcss.com/docs/placeholder-color\n */\n 'placeholder-color': [{\n placeholder: scaleColor()\n }],\n /**\n * Text Color\n * @see https://tailwindcss.com/docs/text-color\n */\n 'text-color': [{\n text: scaleColor()\n }],\n /**\n * Text Decoration\n * @see https://tailwindcss.com/docs/text-decoration\n */\n 'text-decoration': ['underline', 'overline', 'line-through', 'no-underline'],\n /**\n * Text Decoration Style\n * @see https://tailwindcss.com/docs/text-decoration-style\n */\n 'text-decoration-style': [{\n decoration: [...scaleLineStyle(), 'wavy']\n }],\n /**\n * Text Decoration Thickness\n * @see https://tailwindcss.com/docs/text-decoration-thickness\n */\n 'text-decoration-thickness': [{\n decoration: [isNumber, 'from-font', 'auto', isArbitraryVariable, isArbitraryLength]\n }],\n /**\n * Text Decoration Color\n * @see https://tailwindcss.com/docs/text-decoration-color\n */\n 'text-decoration-color': [{\n decoration: scaleColor()\n }],\n /**\n * Text Underline Offset\n * @see https://tailwindcss.com/docs/text-underline-offset\n */\n 'underline-offset': [{\n 'underline-offset': [isNumber, 'auto', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Text Transform\n * @see https://tailwindcss.com/docs/text-transform\n */\n 'text-transform': ['uppercase', 'lowercase', 'capitalize', 'normal-case'],\n /**\n * Text Overflow\n * @see https://tailwindcss.com/docs/text-overflow\n */\n 'text-overflow': ['truncate', 'text-ellipsis', 'text-clip'],\n /**\n * Text Wrap\n * @see https://tailwindcss.com/docs/text-wrap\n */\n 'text-wrap': [{\n text: ['wrap', 'nowrap', 'balance', 'pretty']\n }],\n /**\n * Text Indent\n * @see https://tailwindcss.com/docs/text-indent\n */\n indent: [{\n indent: scaleUnambiguousSpacing()\n }],\n /**\n * Vertical Alignment\n * @see https://tailwindcss.com/docs/vertical-align\n */\n 'vertical-align': [{\n align: ['baseline', 'top', 'middle', 'bottom', 'text-top', 'text-bottom', 'sub', 'super', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Whitespace\n * @see https://tailwindcss.com/docs/whitespace\n */\n whitespace: [{\n whitespace: ['normal', 'nowrap', 'pre', 'pre-line', 'pre-wrap', 'break-spaces']\n }],\n /**\n * Word Break\n * @see https://tailwindcss.com/docs/word-break\n */\n break: [{\n break: ['normal', 'words', 'all', 'keep']\n }],\n /**\n * Overflow Wrap\n * @see https://tailwindcss.com/docs/overflow-wrap\n */\n wrap: [{\n wrap: ['break-word', 'anywhere', 'normal']\n }],\n /**\n * Hyphens\n * @see https://tailwindcss.com/docs/hyphens\n */\n hyphens: [{\n hyphens: ['none', 'manual', 'auto']\n }],\n /**\n * Content\n * @see https://tailwindcss.com/docs/content\n */\n content: [{\n content: ['none', isArbitraryVariable, isArbitraryValue]\n }],\n // -------------------\n // --- Backgrounds ---\n // -------------------\n /**\n * Background Attachment\n * @see https://tailwindcss.com/docs/background-attachment\n */\n 'bg-attachment': [{\n bg: ['fixed', 'local', 'scroll']\n }],\n /**\n * Background Clip\n * @see https://tailwindcss.com/docs/background-clip\n */\n 'bg-clip': [{\n 'bg-clip': ['border', 'padding', 'content', 'text']\n }],\n /**\n * Background Origin\n * @see https://tailwindcss.com/docs/background-origin\n */\n 'bg-origin': [{\n 'bg-origin': ['border', 'padding', 'content']\n }],\n /**\n * Background Position\n * @see https://tailwindcss.com/docs/background-position\n */\n 'bg-position': [{\n bg: scaleBgPosition()\n }],\n /**\n * Background Repeat\n * @see https://tailwindcss.com/docs/background-repeat\n */\n 'bg-repeat': [{\n bg: scaleBgRepeat()\n }],\n /**\n * Background Size\n * @see https://tailwindcss.com/docs/background-size\n */\n 'bg-size': [{\n bg: scaleBgSize()\n }],\n /**\n * Background Image\n * @see https://tailwindcss.com/docs/background-image\n */\n 'bg-image': [{\n bg: ['none', {\n linear: [{\n to: ['t', 'tr', 'r', 'br', 'b', 'bl', 'l', 'tl']\n }, isInteger, isArbitraryVariable, isArbitraryValue],\n radial: ['', isArbitraryVariable, isArbitraryValue],\n conic: [isInteger, isArbitraryVariable, isArbitraryValue]\n }, isArbitraryVariableImage, isArbitraryImage]\n }],\n /**\n * Background Color\n * @see https://tailwindcss.com/docs/background-color\n */\n 'bg-color': [{\n bg: scaleColor()\n }],\n /**\n * Gradient Color Stops From Position\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-from-pos': [{\n from: scaleGradientStopPosition()\n }],\n /**\n * Gradient Color Stops Via Position\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-via-pos': [{\n via: scaleGradientStopPosition()\n }],\n /**\n * Gradient Color Stops To Position\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-to-pos': [{\n to: scaleGradientStopPosition()\n }],\n /**\n * Gradient Color Stops From\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-from': [{\n from: scaleColor()\n }],\n /**\n * Gradient Color Stops Via\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-via': [{\n via: scaleColor()\n }],\n /**\n * Gradient Color Stops To\n * @see https://tailwindcss.com/docs/gradient-color-stops\n */\n 'gradient-to': [{\n to: scaleColor()\n }],\n // ---------------\n // --- Borders ---\n // ---------------\n /**\n * Border Radius\n * @see https://tailwindcss.com/docs/border-radius\n */\n rounded: [{\n rounded: scaleRadius()\n }],\n /**\n * Border Radius Start\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-s': [{\n 'rounded-s': scaleRadius()\n }],\n /**\n * Border Radius End\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-e': [{\n 'rounded-e': scaleRadius()\n }],\n /**\n * Border Radius Top\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-t': [{\n 'rounded-t': scaleRadius()\n }],\n /**\n * Border Radius Right\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-r': [{\n 'rounded-r': scaleRadius()\n }],\n /**\n * Border Radius Bottom\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-b': [{\n 'rounded-b': scaleRadius()\n }],\n /**\n * Border Radius Left\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-l': [{\n 'rounded-l': scaleRadius()\n }],\n /**\n * Border Radius Start Start\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-ss': [{\n 'rounded-ss': scaleRadius()\n }],\n /**\n * Border Radius Start End\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-se': [{\n 'rounded-se': scaleRadius()\n }],\n /**\n * Border Radius End End\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-ee': [{\n 'rounded-ee': scaleRadius()\n }],\n /**\n * Border Radius End Start\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-es': [{\n 'rounded-es': scaleRadius()\n }],\n /**\n * Border Radius Top Left\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-tl': [{\n 'rounded-tl': scaleRadius()\n }],\n /**\n * Border Radius Top Right\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-tr': [{\n 'rounded-tr': scaleRadius()\n }],\n /**\n * Border Radius Bottom Right\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-br': [{\n 'rounded-br': scaleRadius()\n }],\n /**\n * Border Radius Bottom Left\n * @see https://tailwindcss.com/docs/border-radius\n */\n 'rounded-bl': [{\n 'rounded-bl': scaleRadius()\n }],\n /**\n * Border Width\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w': [{\n border: scaleBorderWidth()\n }],\n /**\n * Border Width Inline\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-x': [{\n 'border-x': scaleBorderWidth()\n }],\n /**\n * Border Width Block\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-y': [{\n 'border-y': scaleBorderWidth()\n }],\n /**\n * Border Width Inline Start\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-s': [{\n 'border-s': scaleBorderWidth()\n }],\n /**\n * Border Width Inline End\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-e': [{\n 'border-e': scaleBorderWidth()\n }],\n /**\n * Border Width Block Start\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-bs': [{\n 'border-bs': scaleBorderWidth()\n }],\n /**\n * Border Width Block End\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-be': [{\n 'border-be': scaleBorderWidth()\n }],\n /**\n * Border Width Top\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-t': [{\n 'border-t': scaleBorderWidth()\n }],\n /**\n * Border Width Right\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-r': [{\n 'border-r': scaleBorderWidth()\n }],\n /**\n * Border Width Bottom\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-b': [{\n 'border-b': scaleBorderWidth()\n }],\n /**\n * Border Width Left\n * @see https://tailwindcss.com/docs/border-width\n */\n 'border-w-l': [{\n 'border-l': scaleBorderWidth()\n }],\n /**\n * Divide Width X\n * @see https://tailwindcss.com/docs/border-width#between-children\n */\n 'divide-x': [{\n 'divide-x': scaleBorderWidth()\n }],\n /**\n * Divide Width X Reverse\n * @see https://tailwindcss.com/docs/border-width#between-children\n */\n 'divide-x-reverse': ['divide-x-reverse'],\n /**\n * Divide Width Y\n * @see https://tailwindcss.com/docs/border-width#between-children\n */\n 'divide-y': [{\n 'divide-y': scaleBorderWidth()\n }],\n /**\n * Divide Width Y Reverse\n * @see https://tailwindcss.com/docs/border-width#between-children\n */\n 'divide-y-reverse': ['divide-y-reverse'],\n /**\n * Border Style\n * @see https://tailwindcss.com/docs/border-style\n */\n 'border-style': [{\n border: [...scaleLineStyle(), 'hidden', 'none']\n }],\n /**\n * Divide Style\n * @see https://tailwindcss.com/docs/border-style#setting-the-divider-style\n */\n 'divide-style': [{\n divide: [...scaleLineStyle(), 'hidden', 'none']\n }],\n /**\n * Border Color\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color': [{\n border: scaleColor()\n }],\n /**\n * Border Color Inline\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-x': [{\n 'border-x': scaleColor()\n }],\n /**\n * Border Color Block\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-y': [{\n 'border-y': scaleColor()\n }],\n /**\n * Border Color Inline Start\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-s': [{\n 'border-s': scaleColor()\n }],\n /**\n * Border Color Inline End\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-e': [{\n 'border-e': scaleColor()\n }],\n /**\n * Border Color Block Start\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-bs': [{\n 'border-bs': scaleColor()\n }],\n /**\n * Border Color Block End\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-be': [{\n 'border-be': scaleColor()\n }],\n /**\n * Border Color Top\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-t': [{\n 'border-t': scaleColor()\n }],\n /**\n * Border Color Right\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-r': [{\n 'border-r': scaleColor()\n }],\n /**\n * Border Color Bottom\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-b': [{\n 'border-b': scaleColor()\n }],\n /**\n * Border Color Left\n * @see https://tailwindcss.com/docs/border-color\n */\n 'border-color-l': [{\n 'border-l': scaleColor()\n }],\n /**\n * Divide Color\n * @see https://tailwindcss.com/docs/divide-color\n */\n 'divide-color': [{\n divide: scaleColor()\n }],\n /**\n * Outline Style\n * @see https://tailwindcss.com/docs/outline-style\n */\n 'outline-style': [{\n outline: [...scaleLineStyle(), 'none', 'hidden']\n }],\n /**\n * Outline Offset\n * @see https://tailwindcss.com/docs/outline-offset\n */\n 'outline-offset': [{\n 'outline-offset': [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Outline Width\n * @see https://tailwindcss.com/docs/outline-width\n */\n 'outline-w': [{\n outline: ['', isNumber, isArbitraryVariableLength, isArbitraryLength]\n }],\n /**\n * Outline Color\n * @see https://tailwindcss.com/docs/outline-color\n */\n 'outline-color': [{\n outline: scaleColor()\n }],\n // ---------------\n // --- Effects ---\n // ---------------\n /**\n * Box Shadow\n * @see https://tailwindcss.com/docs/box-shadow\n */\n shadow: [{\n shadow: [\n // Deprecated since Tailwind CSS v4.0.0\n '', 'none', themeShadow, isArbitraryVariableShadow, isArbitraryShadow]\n }],\n /**\n * Box Shadow Color\n * @see https://tailwindcss.com/docs/box-shadow#setting-the-shadow-color\n */\n 'shadow-color': [{\n shadow: scaleColor()\n }],\n /**\n * Inset Box Shadow\n * @see https://tailwindcss.com/docs/box-shadow#adding-an-inset-shadow\n */\n 'inset-shadow': [{\n 'inset-shadow': ['none', themeInsetShadow, isArbitraryVariableShadow, isArbitraryShadow]\n }],\n /**\n * Inset Box Shadow Color\n * @see https://tailwindcss.com/docs/box-shadow#setting-the-inset-shadow-color\n */\n 'inset-shadow-color': [{\n 'inset-shadow': scaleColor()\n }],\n /**\n * Ring Width\n * @see https://tailwindcss.com/docs/box-shadow#adding-a-ring\n */\n 'ring-w': [{\n ring: scaleBorderWidth()\n }],\n /**\n * Ring Width Inset\n * @see https://v3.tailwindcss.com/docs/ring-width#inset-rings\n * @deprecated since Tailwind CSS v4.0.0\n * @see https://github.com/tailwindlabs/tailwindcss/blob/v4.0.0/packages/tailwindcss/src/utilities.ts#L4158\n */\n 'ring-w-inset': ['ring-inset'],\n /**\n * Ring Color\n * @see https://tailwindcss.com/docs/box-shadow#setting-the-ring-color\n */\n 'ring-color': [{\n ring: scaleColor()\n }],\n /**\n * Ring Offset Width\n * @see https://v3.tailwindcss.com/docs/ring-offset-width\n * @deprecated since Tailwind CSS v4.0.0\n * @see https://github.com/tailwindlabs/tailwindcss/blob/v4.0.0/packages/tailwindcss/src/utilities.ts#L4158\n */\n 'ring-offset-w': [{\n 'ring-offset': [isNumber, isArbitraryLength]\n }],\n /**\n * Ring Offset Color\n * @see https://v3.tailwindcss.com/docs/ring-offset-color\n * @deprecated since Tailwind CSS v4.0.0\n * @see https://github.com/tailwindlabs/tailwindcss/blob/v4.0.0/packages/tailwindcss/src/utilities.ts#L4158\n */\n 'ring-offset-color': [{\n 'ring-offset': scaleColor()\n }],\n /**\n * Inset Ring Width\n * @see https://tailwindcss.com/docs/box-shadow#adding-an-inset-ring\n */\n 'inset-ring-w': [{\n 'inset-ring': scaleBorderWidth()\n }],\n /**\n * Inset Ring Color\n * @see https://tailwindcss.com/docs/box-shadow#setting-the-inset-ring-color\n */\n 'inset-ring-color': [{\n 'inset-ring': scaleColor()\n }],\n /**\n * Text Shadow\n * @see https://tailwindcss.com/docs/text-shadow\n */\n 'text-shadow': [{\n 'text-shadow': ['none', themeTextShadow, isArbitraryVariableShadow, isArbitraryShadow]\n }],\n /**\n * Text Shadow Color\n * @see https://tailwindcss.com/docs/text-shadow#setting-the-shadow-color\n */\n 'text-shadow-color': [{\n 'text-shadow': scaleColor()\n }],\n /**\n * Opacity\n * @see https://tailwindcss.com/docs/opacity\n */\n opacity: [{\n opacity: [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Mix Blend Mode\n * @see https://tailwindcss.com/docs/mix-blend-mode\n */\n 'mix-blend': [{\n 'mix-blend': [...scaleBlendMode(), 'plus-darker', 'plus-lighter']\n }],\n /**\n * Background Blend Mode\n * @see https://tailwindcss.com/docs/background-blend-mode\n */\n 'bg-blend': [{\n 'bg-blend': scaleBlendMode()\n }],\n /**\n * Mask Clip\n * @see https://tailwindcss.com/docs/mask-clip\n */\n 'mask-clip': [{\n 'mask-clip': ['border', 'padding', 'content', 'fill', 'stroke', 'view']\n }, 'mask-no-clip'],\n /**\n * Mask Composite\n * @see https://tailwindcss.com/docs/mask-composite\n */\n 'mask-composite': [{\n mask: ['add', 'subtract', 'intersect', 'exclude']\n }],\n /**\n * Mask Image\n * @see https://tailwindcss.com/docs/mask-image\n */\n 'mask-image-linear-pos': [{\n 'mask-linear': [isNumber]\n }],\n 'mask-image-linear-from-pos': [{\n 'mask-linear-from': scaleMaskImagePosition()\n }],\n 'mask-image-linear-to-pos': [{\n 'mask-linear-to': scaleMaskImagePosition()\n }],\n 'mask-image-linear-from-color': [{\n 'mask-linear-from': scaleColor()\n }],\n 'mask-image-linear-to-color': [{\n 'mask-linear-to': scaleColor()\n }],\n 'mask-image-t-from-pos': [{\n 'mask-t-from': scaleMaskImagePosition()\n }],\n 'mask-image-t-to-pos': [{\n 'mask-t-to': scaleMaskImagePosition()\n }],\n 'mask-image-t-from-color': [{\n 'mask-t-from': scaleColor()\n }],\n 'mask-image-t-to-color': [{\n 'mask-t-to': scaleColor()\n }],\n 'mask-image-r-from-pos': [{\n 'mask-r-from': scaleMaskImagePosition()\n }],\n 'mask-image-r-to-pos': [{\n 'mask-r-to': scaleMaskImagePosition()\n }],\n 'mask-image-r-from-color': [{\n 'mask-r-from': scaleColor()\n }],\n 'mask-image-r-to-color': [{\n 'mask-r-to': scaleColor()\n }],\n 'mask-image-b-from-pos': [{\n 'mask-b-from': scaleMaskImagePosition()\n }],\n 'mask-image-b-to-pos': [{\n 'mask-b-to': scaleMaskImagePosition()\n }],\n 'mask-image-b-from-color': [{\n 'mask-b-from': scaleColor()\n }],\n 'mask-image-b-to-color': [{\n 'mask-b-to': scaleColor()\n }],\n 'mask-image-l-from-pos': [{\n 'mask-l-from': scaleMaskImagePosition()\n }],\n 'mask-image-l-to-pos': [{\n 'mask-l-to': scaleMaskImagePosition()\n }],\n 'mask-image-l-from-color': [{\n 'mask-l-from': scaleColor()\n }],\n 'mask-image-l-to-color': [{\n 'mask-l-to': scaleColor()\n }],\n 'mask-image-x-from-pos': [{\n 'mask-x-from': scaleMaskImagePosition()\n }],\n 'mask-image-x-to-pos': [{\n 'mask-x-to': scaleMaskImagePosition()\n }],\n 'mask-image-x-from-color': [{\n 'mask-x-from': scaleColor()\n }],\n 'mask-image-x-to-color': [{\n 'mask-x-to': scaleColor()\n }],\n 'mask-image-y-from-pos': [{\n 'mask-y-from': scaleMaskImagePosition()\n }],\n 'mask-image-y-to-pos': [{\n 'mask-y-to': scaleMaskImagePosition()\n }],\n 'mask-image-y-from-color': [{\n 'mask-y-from': scaleColor()\n }],\n 'mask-image-y-to-color': [{\n 'mask-y-to': scaleColor()\n }],\n 'mask-image-radial': [{\n 'mask-radial': [isArbitraryVariable, isArbitraryValue]\n }],\n 'mask-image-radial-from-pos': [{\n 'mask-radial-from': scaleMaskImagePosition()\n }],\n 'mask-image-radial-to-pos': [{\n 'mask-radial-to': scaleMaskImagePosition()\n }],\n 'mask-image-radial-from-color': [{\n 'mask-radial-from': scaleColor()\n }],\n 'mask-image-radial-to-color': [{\n 'mask-radial-to': scaleColor()\n }],\n 'mask-image-radial-shape': [{\n 'mask-radial': ['circle', 'ellipse']\n }],\n 'mask-image-radial-size': [{\n 'mask-radial': [{\n closest: ['side', 'corner'],\n farthest: ['side', 'corner']\n }]\n }],\n 'mask-image-radial-pos': [{\n 'mask-radial-at': scalePosition()\n }],\n 'mask-image-conic-pos': [{\n 'mask-conic': [isNumber]\n }],\n 'mask-image-conic-from-pos': [{\n 'mask-conic-from': scaleMaskImagePosition()\n }],\n 'mask-image-conic-to-pos': [{\n 'mask-conic-to': scaleMaskImagePosition()\n }],\n 'mask-image-conic-from-color': [{\n 'mask-conic-from': scaleColor()\n }],\n 'mask-image-conic-to-color': [{\n 'mask-conic-to': scaleColor()\n }],\n /**\n * Mask Mode\n * @see https://tailwindcss.com/docs/mask-mode\n */\n 'mask-mode': [{\n mask: ['alpha', 'luminance', 'match']\n }],\n /**\n * Mask Origin\n * @see https://tailwindcss.com/docs/mask-origin\n */\n 'mask-origin': [{\n 'mask-origin': ['border', 'padding', 'content', 'fill', 'stroke', 'view']\n }],\n /**\n * Mask Position\n * @see https://tailwindcss.com/docs/mask-position\n */\n 'mask-position': [{\n mask: scaleBgPosition()\n }],\n /**\n * Mask Repeat\n * @see https://tailwindcss.com/docs/mask-repeat\n */\n 'mask-repeat': [{\n mask: scaleBgRepeat()\n }],\n /**\n * Mask Size\n * @see https://tailwindcss.com/docs/mask-size\n */\n 'mask-size': [{\n mask: scaleBgSize()\n }],\n /**\n * Mask Type\n * @see https://tailwindcss.com/docs/mask-type\n */\n 'mask-type': [{\n 'mask-type': ['alpha', 'luminance']\n }],\n /**\n * Mask Image\n * @see https://tailwindcss.com/docs/mask-image\n */\n 'mask-image': [{\n mask: ['none', isArbitraryVariable, isArbitraryValue]\n }],\n // ---------------\n // --- Filters ---\n // ---------------\n /**\n * Filter\n * @see https://tailwindcss.com/docs/filter\n */\n filter: [{\n filter: [\n // Deprecated since Tailwind CSS v3.0.0\n '', 'none', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Blur\n * @see https://tailwindcss.com/docs/blur\n */\n blur: [{\n blur: scaleBlur()\n }],\n /**\n * Brightness\n * @see https://tailwindcss.com/docs/brightness\n */\n brightness: [{\n brightness: [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Contrast\n * @see https://tailwindcss.com/docs/contrast\n */\n contrast: [{\n contrast: [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Drop Shadow\n * @see https://tailwindcss.com/docs/drop-shadow\n */\n 'drop-shadow': [{\n 'drop-shadow': [\n // Deprecated since Tailwind CSS v4.0.0\n '', 'none', themeDropShadow, isArbitraryVariableShadow, isArbitraryShadow]\n }],\n /**\n * Drop Shadow Color\n * @see https://tailwindcss.com/docs/filter-drop-shadow#setting-the-shadow-color\n */\n 'drop-shadow-color': [{\n 'drop-shadow': scaleColor()\n }],\n /**\n * Grayscale\n * @see https://tailwindcss.com/docs/grayscale\n */\n grayscale: [{\n grayscale: ['', isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Hue Rotate\n * @see https://tailwindcss.com/docs/hue-rotate\n */\n 'hue-rotate': [{\n 'hue-rotate': [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Invert\n * @see https://tailwindcss.com/docs/invert\n */\n invert: [{\n invert: ['', isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Saturate\n * @see https://tailwindcss.com/docs/saturate\n */\n saturate: [{\n saturate: [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Sepia\n * @see https://tailwindcss.com/docs/sepia\n */\n sepia: [{\n sepia: ['', isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Backdrop Filter\n * @see https://tailwindcss.com/docs/backdrop-filter\n */\n 'backdrop-filter': [{\n 'backdrop-filter': [\n // Deprecated since Tailwind CSS v3.0.0\n '', 'none', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Backdrop Blur\n * @see https://tailwindcss.com/docs/backdrop-blur\n */\n 'backdrop-blur': [{\n 'backdrop-blur': scaleBlur()\n }],\n /**\n * Backdrop Brightness\n * @see https://tailwindcss.com/docs/backdrop-brightness\n */\n 'backdrop-brightness': [{\n 'backdrop-brightness': [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Backdrop Contrast\n * @see https://tailwindcss.com/docs/backdrop-contrast\n */\n 'backdrop-contrast': [{\n 'backdrop-contrast': [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Backdrop Grayscale\n * @see https://tailwindcss.com/docs/backdrop-grayscale\n */\n 'backdrop-grayscale': [{\n 'backdrop-grayscale': ['', isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Backdrop Hue Rotate\n * @see https://tailwindcss.com/docs/backdrop-hue-rotate\n */\n 'backdrop-hue-rotate': [{\n 'backdrop-hue-rotate': [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Backdrop Invert\n * @see https://tailwindcss.com/docs/backdrop-invert\n */\n 'backdrop-invert': [{\n 'backdrop-invert': ['', isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Backdrop Opacity\n * @see https://tailwindcss.com/docs/backdrop-opacity\n */\n 'backdrop-opacity': [{\n 'backdrop-opacity': [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Backdrop Saturate\n * @see https://tailwindcss.com/docs/backdrop-saturate\n */\n 'backdrop-saturate': [{\n 'backdrop-saturate': [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Backdrop Sepia\n * @see https://tailwindcss.com/docs/backdrop-sepia\n */\n 'backdrop-sepia': [{\n 'backdrop-sepia': ['', isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n // --------------\n // --- Tables ---\n // --------------\n /**\n * Border Collapse\n * @see https://tailwindcss.com/docs/border-collapse\n */\n 'border-collapse': [{\n border: ['collapse', 'separate']\n }],\n /**\n * Border Spacing\n * @see https://tailwindcss.com/docs/border-spacing\n */\n 'border-spacing': [{\n 'border-spacing': scaleUnambiguousSpacing()\n }],\n /**\n * Border Spacing X\n * @see https://tailwindcss.com/docs/border-spacing\n */\n 'border-spacing-x': [{\n 'border-spacing-x': scaleUnambiguousSpacing()\n }],\n /**\n * Border Spacing Y\n * @see https://tailwindcss.com/docs/border-spacing\n */\n 'border-spacing-y': [{\n 'border-spacing-y': scaleUnambiguousSpacing()\n }],\n /**\n * Table Layout\n * @see https://tailwindcss.com/docs/table-layout\n */\n 'table-layout': [{\n table: ['auto', 'fixed']\n }],\n /**\n * Caption Side\n * @see https://tailwindcss.com/docs/caption-side\n */\n caption: [{\n caption: ['top', 'bottom']\n }],\n // ---------------------------------\n // --- Transitions and Animation ---\n // ---------------------------------\n /**\n * Transition Property\n * @see https://tailwindcss.com/docs/transition-property\n */\n transition: [{\n transition: ['', 'all', 'colors', 'opacity', 'shadow', 'transform', 'none', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Transition Behavior\n * @see https://tailwindcss.com/docs/transition-behavior\n */\n 'transition-behavior': [{\n transition: ['normal', 'discrete']\n }],\n /**\n * Transition Duration\n * @see https://tailwindcss.com/docs/transition-duration\n */\n duration: [{\n duration: [isNumber, 'initial', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Transition Timing Function\n * @see https://tailwindcss.com/docs/transition-timing-function\n */\n ease: [{\n ease: ['linear', 'initial', themeEase, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Transition Delay\n * @see https://tailwindcss.com/docs/transition-delay\n */\n delay: [{\n delay: [isNumber, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Animation\n * @see https://tailwindcss.com/docs/animation\n */\n animate: [{\n animate: ['none', themeAnimate, isArbitraryVariable, isArbitraryValue]\n }],\n // ------------------\n // --- Transforms ---\n // ------------------\n /**\n * Backface Visibility\n * @see https://tailwindcss.com/docs/backface-visibility\n */\n backface: [{\n backface: ['hidden', 'visible']\n }],\n /**\n * Perspective\n * @see https://tailwindcss.com/docs/perspective\n */\n perspective: [{\n perspective: [themePerspective, isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Perspective Origin\n * @see https://tailwindcss.com/docs/perspective-origin\n */\n 'perspective-origin': [{\n 'perspective-origin': scalePositionWithArbitrary()\n }],\n /**\n * Rotate\n * @see https://tailwindcss.com/docs/rotate\n */\n rotate: [{\n rotate: scaleRotate()\n }],\n /**\n * Rotate X\n * @see https://tailwindcss.com/docs/rotate\n */\n 'rotate-x': [{\n 'rotate-x': scaleRotate()\n }],\n /**\n * Rotate Y\n * @see https://tailwindcss.com/docs/rotate\n */\n 'rotate-y': [{\n 'rotate-y': scaleRotate()\n }],\n /**\n * Rotate Z\n * @see https://tailwindcss.com/docs/rotate\n */\n 'rotate-z': [{\n 'rotate-z': scaleRotate()\n }],\n /**\n * Scale\n * @see https://tailwindcss.com/docs/scale\n */\n scale: [{\n scale: scaleScale()\n }],\n /**\n * Scale X\n * @see https://tailwindcss.com/docs/scale\n */\n 'scale-x': [{\n 'scale-x': scaleScale()\n }],\n /**\n * Scale Y\n * @see https://tailwindcss.com/docs/scale\n */\n 'scale-y': [{\n 'scale-y': scaleScale()\n }],\n /**\n * Scale Z\n * @see https://tailwindcss.com/docs/scale\n */\n 'scale-z': [{\n 'scale-z': scaleScale()\n }],\n /**\n * Scale 3D\n * @see https://tailwindcss.com/docs/scale\n */\n 'scale-3d': ['scale-3d'],\n /**\n * Skew\n * @see https://tailwindcss.com/docs/skew\n */\n skew: [{\n skew: scaleSkew()\n }],\n /**\n * Skew X\n * @see https://tailwindcss.com/docs/skew\n */\n 'skew-x': [{\n 'skew-x': scaleSkew()\n }],\n /**\n * Skew Y\n * @see https://tailwindcss.com/docs/skew\n */\n 'skew-y': [{\n 'skew-y': scaleSkew()\n }],\n /**\n * Transform\n * @see https://tailwindcss.com/docs/transform\n */\n transform: [{\n transform: [isArbitraryVariable, isArbitraryValue, '', 'none', 'gpu', 'cpu']\n }],\n /**\n * Transform Origin\n * @see https://tailwindcss.com/docs/transform-origin\n */\n 'transform-origin': [{\n origin: scalePositionWithArbitrary()\n }],\n /**\n * Transform Style\n * @see https://tailwindcss.com/docs/transform-style\n */\n 'transform-style': [{\n transform: ['3d', 'flat']\n }],\n /**\n * Translate\n * @see https://tailwindcss.com/docs/translate\n */\n translate: [{\n translate: scaleTranslate()\n }],\n /**\n * Translate X\n * @see https://tailwindcss.com/docs/translate\n */\n 'translate-x': [{\n 'translate-x': scaleTranslate()\n }],\n /**\n * Translate Y\n * @see https://tailwindcss.com/docs/translate\n */\n 'translate-y': [{\n 'translate-y': scaleTranslate()\n }],\n /**\n * Translate Z\n * @see https://tailwindcss.com/docs/translate\n */\n 'translate-z': [{\n 'translate-z': scaleTranslate()\n }],\n /**\n * Translate None\n * @see https://tailwindcss.com/docs/translate\n */\n 'translate-none': ['translate-none'],\n // ---------------------\n // --- Interactivity ---\n // ---------------------\n /**\n * Accent Color\n * @see https://tailwindcss.com/docs/accent-color\n */\n accent: [{\n accent: scaleColor()\n }],\n /**\n * Appearance\n * @see https://tailwindcss.com/docs/appearance\n */\n appearance: [{\n appearance: ['none', 'auto']\n }],\n /**\n * Caret Color\n * @see https://tailwindcss.com/docs/just-in-time-mode#caret-color-utilities\n */\n 'caret-color': [{\n caret: scaleColor()\n }],\n /**\n * Color Scheme\n * @see https://tailwindcss.com/docs/color-scheme\n */\n 'color-scheme': [{\n scheme: ['normal', 'dark', 'light', 'light-dark', 'only-dark', 'only-light']\n }],\n /**\n * Cursor\n * @see https://tailwindcss.com/docs/cursor\n */\n cursor: [{\n cursor: ['auto', 'default', 'pointer', 'wait', 'text', 'move', 'help', 'not-allowed', 'none', 'context-menu', 'progress', 'cell', 'crosshair', 'vertical-text', 'alias', 'copy', 'no-drop', 'grab', 'grabbing', 'all-scroll', 'col-resize', 'row-resize', 'n-resize', 'e-resize', 's-resize', 'w-resize', 'ne-resize', 'nw-resize', 'se-resize', 'sw-resize', 'ew-resize', 'ns-resize', 'nesw-resize', 'nwse-resize', 'zoom-in', 'zoom-out', isArbitraryVariable, isArbitraryValue]\n }],\n /**\n * Field Sizing\n * @see https://tailwindcss.com/docs/field-sizing\n */\n 'field-sizing': [{\n 'field-sizing': ['fixed', 'content']\n }],\n /**\n * Pointer Events\n * @see https://tailwindcss.com/docs/pointer-events\n */\n 'pointer-events': [{\n 'pointer-events': ['auto', 'none']\n }],\n /**\n * Resize\n * @see https://tailwindcss.com/docs/resize\n */\n resize: [{\n resize: ['none', '', 'y', 'x']\n }],\n /**\n * Scroll Behavior\n * @see https://tailwindcss.com/docs/scroll-behavior\n */\n 'scroll-behavior': [{\n scroll: ['auto', 'smooth']\n }],\n /**\n * Scroll Margin\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-m': [{\n 'scroll-m': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Inline\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mx': [{\n 'scroll-mx': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Block\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-my': [{\n 'scroll-my': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Inline Start\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-ms': [{\n 'scroll-ms': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Inline End\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-me': [{\n 'scroll-me': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Block Start\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mbs': [{\n 'scroll-mbs': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Block End\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mbe': [{\n 'scroll-mbe': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Top\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mt': [{\n 'scroll-mt': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Right\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mr': [{\n 'scroll-mr': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Bottom\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-mb': [{\n 'scroll-mb': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Margin Left\n * @see https://tailwindcss.com/docs/scroll-margin\n */\n 'scroll-ml': [{\n 'scroll-ml': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-p': [{\n 'scroll-p': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Inline\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-px': [{\n 'scroll-px': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Block\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-py': [{\n 'scroll-py': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Inline Start\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-ps': [{\n 'scroll-ps': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Inline End\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pe': [{\n 'scroll-pe': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Block Start\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pbs': [{\n 'scroll-pbs': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Block End\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pbe': [{\n 'scroll-pbe': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Top\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pt': [{\n 'scroll-pt': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Right\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pr': [{\n 'scroll-pr': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Bottom\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pb': [{\n 'scroll-pb': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Padding Left\n * @see https://tailwindcss.com/docs/scroll-padding\n */\n 'scroll-pl': [{\n 'scroll-pl': scaleUnambiguousSpacing()\n }],\n /**\n * Scroll Snap Align\n * @see https://tailwindcss.com/docs/scroll-snap-align\n */\n 'snap-align': [{\n snap: ['start', 'end', 'center', 'align-none']\n }],\n /**\n * Scroll Snap Stop\n * @see https://tailwindcss.com/docs/scroll-snap-stop\n */\n 'snap-stop': [{\n snap: ['normal', 'always']\n }],\n /**\n * Scroll Snap Type\n * @see https://tailwindcss.com/docs/scroll-snap-type\n */\n 'snap-type': [{\n snap: ['none', 'x', 'y', 'both']\n }],\n /**\n * Scroll Snap Type Strictness\n * @see https://tailwindcss.com/docs/scroll-snap-type\n */\n 'snap-strictness': [{\n snap: ['mandatory', 'proximity']\n }],\n /**\n * Touch Action\n * @see https://tailwindcss.com/docs/touch-action\n */\n touch: [{\n touch: ['auto', 'none', 'manipulation']\n }],\n /**\n * Touch Action X\n * @see https://tailwindcss.com/docs/touch-action\n */\n 'touch-x': [{\n 'touch-pan': ['x', 'left', 'right']\n }],\n /**\n * Touch Action Y\n * @see https://tailwindcss.com/docs/touch-action\n */\n 'touch-y': [{\n 'touch-pan': ['y', 'up', 'down']\n }],\n /**\n * Touch Action Pinch Zoom\n * @see https://tailwindcss.com/docs/touch-action\n */\n 'touch-pz': ['touch-pinch-zoom'],\n /**\n * User Select\n * @see https://tailwindcss.com/docs/user-select\n */\n select: [{\n select: ['none', 'text', 'all', 'auto']\n }],\n /**\n * Will Change\n * @see https://tailwindcss.com/docs/will-change\n */\n 'will-change': [{\n 'will-change': ['auto', 'scroll', 'contents', 'transform', isArbitraryVariable, isArbitraryValue]\n }],\n // -----------\n // --- SVG ---\n // -----------\n /**\n * Fill\n * @see https://tailwindcss.com/docs/fill\n */\n fill: [{\n fill: ['none', ...scaleColor()]\n }],\n /**\n * Stroke Width\n * @see https://tailwindcss.com/docs/stroke-width\n */\n 'stroke-w': [{\n stroke: [isNumber, isArbitraryVariableLength, isArbitraryLength, isArbitraryNumber]\n }],\n /**\n * Stroke\n * @see https://tailwindcss.com/docs/stroke\n */\n stroke: [{\n stroke: ['none', ...scaleColor()]\n }],\n // ---------------------\n // --- Accessibility ---\n // ---------------------\n /**\n * Forced Color Adjust\n * @see https://tailwindcss.com/docs/forced-color-adjust\n */\n 'forced-color-adjust': [{\n 'forced-color-adjust': ['auto', 'none']\n }]\n },\n conflictingClassGroups: {\n overflow: ['overflow-x', 'overflow-y'],\n overscroll: ['overscroll-x', 'overscroll-y'],\n inset: ['inset-x', 'inset-y', 'inset-bs', 'inset-be', 'start', 'end', 'top', 'right', 'bottom', 'left'],\n 'inset-x': ['right', 'left'],\n 'inset-y': ['top', 'bottom'],\n flex: ['basis', 'grow', 'shrink'],\n gap: ['gap-x', 'gap-y'],\n p: ['px', 'py', 'ps', 'pe', 'pbs', 'pbe', 'pt', 'pr', 'pb', 'pl'],\n px: ['pr', 'pl'],\n py: ['pt', 'pb'],\n m: ['mx', 'my', 'ms', 'me', 'mbs', 'mbe', 'mt', 'mr', 'mb', 'ml'],\n mx: ['mr', 'ml'],\n my: ['mt', 'mb'],\n size: ['w', 'h'],\n 'font-size': ['leading'],\n 'fvn-normal': ['fvn-ordinal', 'fvn-slashed-zero', 'fvn-figure', 'fvn-spacing', 'fvn-fraction'],\n 'fvn-ordinal': ['fvn-normal'],\n 'fvn-slashed-zero': ['fvn-normal'],\n 'fvn-figure': ['fvn-normal'],\n 'fvn-spacing': ['fvn-normal'],\n 'fvn-fraction': ['fvn-normal'],\n 'line-clamp': ['display', 'overflow'],\n rounded: ['rounded-s', 'rounded-e', 'rounded-t', 'rounded-r', 'rounded-b', 'rounded-l', 'rounded-ss', 'rounded-se', 'rounded-ee', 'rounded-es', 'rounded-tl', 'rounded-tr', 'rounded-br', 'rounded-bl'],\n 'rounded-s': ['rounded-ss', 'rounded-es'],\n 'rounded-e': ['rounded-se', 'rounded-ee'],\n 'rounded-t': ['rounded-tl', 'rounded-tr'],\n 'rounded-r': ['rounded-tr', 'rounded-br'],\n 'rounded-b': ['rounded-br', 'rounded-bl'],\n 'rounded-l': ['rounded-tl', 'rounded-bl'],\n 'border-spacing': ['border-spacing-x', 'border-spacing-y'],\n 'border-w': ['border-w-x', 'border-w-y', 'border-w-s', 'border-w-e', 'border-w-bs', 'border-w-be', 'border-w-t', 'border-w-r', 'border-w-b', 'border-w-l'],\n 'border-w-x': ['border-w-r', 'border-w-l'],\n 'border-w-y': ['border-w-t', 'border-w-b'],\n 'border-color': ['border-color-x', 'border-color-y', 'border-color-s', 'border-color-e', 'border-color-bs', 'border-color-be', 'border-color-t', 'border-color-r', 'border-color-b', 'border-color-l'],\n 'border-color-x': ['border-color-r', 'border-color-l'],\n 'border-color-y': ['border-color-t', 'border-color-b'],\n translate: ['translate-x', 'translate-y', 'translate-none'],\n 'translate-none': ['translate', 'translate-x', 'translate-y', 'translate-z'],\n 'scroll-m': ['scroll-mx', 'scroll-my', 'scroll-ms', 'scroll-me', 'scroll-mbs', 'scroll-mbe', 'scroll-mt', 'scroll-mr', 'scroll-mb', 'scroll-ml'],\n 'scroll-mx': ['scroll-mr', 'scroll-ml'],\n 'scroll-my': ['scroll-mt', 'scroll-mb'],\n 'scroll-p': ['scroll-px', 'scroll-py', 'scroll-ps', 'scroll-pe', 'scroll-pbs', 'scroll-pbe', 'scroll-pt', 'scroll-pr', 'scroll-pb', 'scroll-pl'],\n 'scroll-px': ['scroll-pr', 'scroll-pl'],\n 'scroll-py': ['scroll-pt', 'scroll-pb'],\n touch: ['touch-x', 'touch-y', 'touch-pz'],\n 'touch-x': ['touch'],\n 'touch-y': ['touch'],\n 'touch-pz': ['touch']\n },\n conflictingClassGroupModifiers: {\n 'font-size': ['leading']\n },\n orderSensitiveModifiers: ['*', '**', 'after', 'backdrop', 'before', 'details-content', 'file', 'first-letter', 'first-line', 'marker', 'placeholder', 'selection']\n };\n};\n\n/**\n * @param baseConfig Config where other config will be merged into. This object will be mutated.\n * @param configExtension Partial config to merge into the `baseConfig`.\n */\nconst mergeConfigs = (baseConfig, {\n cacheSize,\n prefix,\n experimentalParseClassName,\n extend = {},\n override = {}\n}) => {\n overrideProperty(baseConfig, 'cacheSize', cacheSize);\n overrideProperty(baseConfig, 'prefix', prefix);\n overrideProperty(baseConfig, 'experimentalParseClassName', experimentalParseClassName);\n overrideConfigProperties(baseConfig.theme, override.theme);\n overrideConfigProperties(baseConfig.classGroups, override.classGroups);\n overrideConfigProperties(baseConfig.conflictingClassGroups, override.conflictingClassGroups);\n overrideConfigProperties(baseConfig.conflictingClassGroupModifiers, override.conflictingClassGroupModifiers);\n overrideProperty(baseConfig, 'orderSensitiveModifiers', override.orderSensitiveModifiers);\n mergeConfigProperties(baseConfig.theme, extend.theme);\n mergeConfigProperties(baseConfig.classGroups, extend.classGroups);\n mergeConfigProperties(baseConfig.conflictingClassGroups, extend.conflictingClassGroups);\n mergeConfigProperties(baseConfig.conflictingClassGroupModifiers, extend.conflictingClassGroupModifiers);\n mergeArrayProperties(baseConfig, extend, 'orderSensitiveModifiers');\n return baseConfig;\n};\nconst overrideProperty = (baseObject, overrideKey, overrideValue) => {\n if (overrideValue !== undefined) {\n baseObject[overrideKey] = overrideValue;\n }\n};\nconst overrideConfigProperties = (baseObject, overrideObject) => {\n if (overrideObject) {\n for (const key in overrideObject) {\n overrideProperty(baseObject, key, overrideObject[key]);\n }\n }\n};\nconst mergeConfigProperties = (baseObject, mergeObject) => {\n if (mergeObject) {\n for (const key in mergeObject) {\n mergeArrayProperties(baseObject, mergeObject, key);\n }\n }\n};\nconst mergeArrayProperties = (baseObject, mergeObject, key) => {\n const mergeValue = mergeObject[key];\n if (mergeValue !== undefined) {\n baseObject[key] = baseObject[key] ? baseObject[key].concat(mergeValue) : mergeValue;\n }\n};\nconst extendTailwindMerge = (configExtension, ...createConfig) => typeof configExtension === 'function' ? createTailwindMerge(getDefaultConfig, configExtension, ...createConfig) : createTailwindMerge(() => mergeConfigs(getDefaultConfig(), configExtension), ...createConfig);\nconst twMerge = /*#__PURE__*/createTailwindMerge(getDefaultConfig);\nexport { createTailwindMerge, extendTailwindMerge, fromTheme, getDefaultConfig, mergeConfigs, twJoin, twMerge, validators };\n//# sourceMappingURL=bundle-mjs.mjs.map\n","import { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n\nexport function sleep(ms: number) {\n return new Promise((resolve) => window.setTimeout(resolve, ms));\n}\n\nexport function uniqueBy<T>(items: T[], getKey: (item: T) => string) {\n const seen = new Set<string>();\n\n return items.filter((item) => {\n const key = getKey(item);\n\n if (seen.has(key)) {\n return false;\n }\n\n seen.add(key);\n return true;\n });\n}\n","// src/errors/ai-sdk-error.ts\nvar marker = \"vercel.ai.error\";\nvar symbol = Symbol.for(marker);\nvar _a, _b;\nvar AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {\n /**\n * Creates an AI SDK Error.\n *\n * @param {Object} params - The parameters for creating the error.\n * @param {string} params.name - The name of the error.\n * @param {string} params.message - The error message.\n * @param {unknown} [params.cause] - The underlying cause of the error.\n */\n constructor({\n name: name14,\n message,\n cause\n }) {\n super(message);\n this[_a] = true;\n this.name = name14;\n this.cause = cause;\n }\n /**\n * Checks if the given error is an AI SDK Error.\n * @param {unknown} error - The error to check.\n * @returns {boolean} True if the error is an AI SDK Error, false otherwise.\n */\n static isInstance(error) {\n return _AISDKError.hasMarker(error, marker);\n }\n static hasMarker(error, marker15) {\n const markerSymbol = Symbol.for(marker15);\n return error != null && typeof error === \"object\" && markerSymbol in error && typeof error[markerSymbol] === \"boolean\" && error[markerSymbol] === true;\n }\n};\n\n// src/errors/api-call-error.ts\nvar name = \"AI_APICallError\";\nvar marker2 = `vercel.ai.error.${name}`;\nvar symbol2 = Symbol.for(marker2);\nvar _a2, _b2;\nvar APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) {\n constructor({\n message,\n url,\n requestBodyValues,\n statusCode,\n responseHeaders,\n responseBody,\n cause,\n isRetryable = statusCode != null && (statusCode === 408 || // request timeout\n statusCode === 409 || // conflict\n statusCode === 429 || // too many requests\n statusCode >= 500),\n // server error\n data\n }) {\n super({ name, message, cause });\n this[_a2] = true;\n this.url = url;\n this.requestBodyValues = requestBodyValues;\n this.statusCode = statusCode;\n this.responseHeaders = responseHeaders;\n this.responseBody = responseBody;\n this.isRetryable = isRetryable;\n this.data = data;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker2);\n }\n};\n\n// src/errors/empty-response-body-error.ts\nvar name2 = \"AI_EmptyResponseBodyError\";\nvar marker3 = `vercel.ai.error.${name2}`;\nvar symbol3 = Symbol.for(marker3);\nvar _a3, _b3;\nvar EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) {\n // used in isInstance\n constructor({ message = \"Empty response body\" } = {}) {\n super({ name: name2, message });\n this[_a3] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker3);\n }\n};\n\n// src/errors/get-error-message.ts\nfunction getErrorMessage(error) {\n if (error == null) {\n return \"unknown error\";\n }\n if (typeof error === \"string\") {\n return error;\n }\n if (error instanceof Error) {\n return error.message;\n }\n return JSON.stringify(error);\n}\n\n// src/errors/invalid-argument-error.ts\nvar name3 = \"AI_InvalidArgumentError\";\nvar marker4 = `vercel.ai.error.${name3}`;\nvar symbol4 = Symbol.for(marker4);\nvar _a4, _b4;\nvar InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) {\n constructor({\n message,\n cause,\n argument\n }) {\n super({ name: name3, message, cause });\n this[_a4] = true;\n this.argument = argument;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker4);\n }\n};\n\n// src/errors/invalid-prompt-error.ts\nvar name4 = \"AI_InvalidPromptError\";\nvar marker5 = `vercel.ai.error.${name4}`;\nvar symbol5 = Symbol.for(marker5);\nvar _a5, _b5;\nvar InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) {\n constructor({\n prompt,\n message,\n cause\n }) {\n super({ name: name4, message: `Invalid prompt: ${message}`, cause });\n this[_a5] = true;\n this.prompt = prompt;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker5);\n }\n};\n\n// src/errors/invalid-response-data-error.ts\nvar name5 = \"AI_InvalidResponseDataError\";\nvar marker6 = `vercel.ai.error.${name5}`;\nvar symbol6 = Symbol.for(marker6);\nvar _a6, _b6;\nvar InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) {\n constructor({\n data,\n message = `Invalid response data: ${JSON.stringify(data)}.`\n }) {\n super({ name: name5, message });\n this[_a6] = true;\n this.data = data;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker6);\n }\n};\n\n// src/errors/json-parse-error.ts\nvar name6 = \"AI_JSONParseError\";\nvar marker7 = `vercel.ai.error.${name6}`;\nvar symbol7 = Symbol.for(marker7);\nvar _a7, _b7;\nvar JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) {\n constructor({ text, cause }) {\n super({\n name: name6,\n message: `JSON parsing failed: Text: ${text}.\nError message: ${getErrorMessage(cause)}`,\n cause\n });\n this[_a7] = true;\n this.text = text;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker7);\n }\n};\n\n// src/errors/load-api-key-error.ts\nvar name7 = \"AI_LoadAPIKeyError\";\nvar marker8 = `vercel.ai.error.${name7}`;\nvar symbol8 = Symbol.for(marker8);\nvar _a8, _b8;\nvar LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) {\n // used in isInstance\n constructor({ message }) {\n super({ name: name7, message });\n this[_a8] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker8);\n }\n};\n\n// src/errors/load-setting-error.ts\nvar name8 = \"AI_LoadSettingError\";\nvar marker9 = `vercel.ai.error.${name8}`;\nvar symbol9 = Symbol.for(marker9);\nvar _a9, _b9;\nvar LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) {\n // used in isInstance\n constructor({ message }) {\n super({ name: name8, message });\n this[_a9] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker9);\n }\n};\n\n// src/errors/no-content-generated-error.ts\nvar name9 = \"AI_NoContentGeneratedError\";\nvar marker10 = `vercel.ai.error.${name9}`;\nvar symbol10 = Symbol.for(marker10);\nvar _a10, _b10;\nvar NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) {\n // used in isInstance\n constructor({\n message = \"No content generated.\"\n } = {}) {\n super({ name: name9, message });\n this[_a10] = true;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker10);\n }\n};\n\n// src/errors/no-such-model-error.ts\nvar name10 = \"AI_NoSuchModelError\";\nvar marker11 = `vercel.ai.error.${name10}`;\nvar symbol11 = Symbol.for(marker11);\nvar _a11, _b11;\nvar NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {\n constructor({\n errorName = name10,\n modelId,\n modelType,\n message = `No such ${modelType}: ${modelId}`\n }) {\n super({ name: errorName, message });\n this[_a11] = true;\n this.modelId = modelId;\n this.modelType = modelType;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker11);\n }\n};\n\n// src/errors/too-many-embedding-values-for-call-error.ts\nvar name11 = \"AI_TooManyEmbeddingValuesForCallError\";\nvar marker12 = `vercel.ai.error.${name11}`;\nvar symbol12 = Symbol.for(marker12);\nvar _a12, _b12;\nvar TooManyEmbeddingValuesForCallError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) {\n constructor(options) {\n super({\n name: name11,\n message: `Too many values for a single embedding call. The ${options.provider} model \"${options.modelId}\" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`\n });\n this[_a12] = true;\n this.provider = options.provider;\n this.modelId = options.modelId;\n this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;\n this.values = options.values;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker12);\n }\n};\n\n// src/errors/type-validation-error.ts\nvar name12 = \"AI_TypeValidationError\";\nvar marker13 = `vercel.ai.error.${name12}`;\nvar symbol13 = Symbol.for(marker13);\nvar _a13, _b13;\nvar TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {\n constructor({\n value,\n cause,\n context\n }) {\n let contextPrefix = \"Type validation failed\";\n if (context == null ? void 0 : context.field) {\n contextPrefix += ` for ${context.field}`;\n }\n if ((context == null ? void 0 : context.entityName) || (context == null ? void 0 : context.entityId)) {\n contextPrefix += \" (\";\n const parts = [];\n if (context.entityName) {\n parts.push(context.entityName);\n }\n if (context.entityId) {\n parts.push(`id: \"${context.entityId}\"`);\n }\n contextPrefix += parts.join(\", \");\n contextPrefix += \")\";\n }\n super({\n name: name12,\n message: `${contextPrefix}: Value: ${JSON.stringify(value)}.\nError message: ${getErrorMessage(cause)}`,\n cause\n });\n this[_a13] = true;\n this.value = value;\n this.context = context;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker13);\n }\n /**\n * Wraps an error into a TypeValidationError.\n * If the cause is already a TypeValidationError with the same value and context, it returns the cause.\n * Otherwise, it creates a new TypeValidationError.\n *\n * @param {Object} params - The parameters for wrapping the error.\n * @param {unknown} params.value - The value that failed validation.\n * @param {unknown} params.cause - The original error or cause of the validation failure.\n * @param {TypeValidationContext} params.context - Optional context about what is being validated.\n * @returns {TypeValidationError} A TypeValidationError instance.\n */\n static wrap({\n value,\n cause,\n context\n }) {\n var _a15, _b15, _c;\n if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a15 = cause.context) == null ? void 0 : _a15.field) === (context == null ? void 0 : context.field) && ((_b15 = cause.context) == null ? void 0 : _b15.entityName) === (context == null ? void 0 : context.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context == null ? void 0 : context.entityId)) {\n return cause;\n }\n return new _TypeValidationError({ value, cause, context });\n }\n};\n\n// src/errors/unsupported-functionality-error.ts\nvar name13 = \"AI_UnsupportedFunctionalityError\";\nvar marker14 = `vercel.ai.error.${name13}`;\nvar symbol14 = Symbol.for(marker14);\nvar _a14, _b14;\nvar UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {\n constructor({\n functionality,\n message = `'${functionality}' functionality not supported.`\n }) {\n super({ name: name13, message });\n this[_a14] = true;\n this.functionality = functionality;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker14);\n }\n};\n\n// src/json-value/is-json.ts\nfunction isJSONValue(value) {\n if (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return true;\n }\n if (Array.isArray(value)) {\n return value.every(isJSONValue);\n }\n if (typeof value === \"object\") {\n return Object.entries(value).every(\n ([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val))\n );\n }\n return false;\n}\nfunction isJSONArray(value) {\n return Array.isArray(value) && value.every(isJSONValue);\n}\nfunction isJSONObject(value) {\n return value != null && typeof value === \"object\" && Object.entries(value).every(\n ([key, val]) => typeof key === \"string\" && (val === void 0 || isJSONValue(val))\n );\n}\nexport {\n AISDKError,\n APICallError,\n EmptyResponseBodyError,\n InvalidArgumentError,\n InvalidPromptError,\n InvalidResponseDataError,\n JSONParseError,\n LoadAPIKeyError,\n LoadSettingError,\n NoContentGeneratedError,\n NoSuchModelError,\n TooManyEmbeddingValuesForCallError,\n TypeValidationError,\n UnsupportedFunctionalityError,\n getErrorMessage,\n isJSONArray,\n isJSONObject,\n isJSONValue\n};\n//# sourceMappingURL=index.mjs.map","/** A special constant with type `never` */\nexport const NEVER = 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}\nexport const globalConfig = {};\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\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 valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepString = step.toString();\n let stepDecCount = (stepString.split(\".\")[1] || \"\").length;\n if (stepDecCount === 0 && /\\d?e-\\d?/.test(stepString)) {\n const match = stepString.match(/\\d?e-(\\d?)/);\n if (match?.[1]) {\n stepDecCount = Number.parseInt(match[1]);\n }\n }\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nconst EVALUATING = 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 = cached(() => {\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 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 = new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = new Set([\"string\", \"number\", \"bigint\", \"boolean\", \"symbol\", \"undefined\"]);\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 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: [], // delete existing 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}\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 full = { ...iss, path: iss.path ?? [] };\n // for backwards compatibility\n if (!iss.message) {\n const message = 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 full.message = message;\n }\n // delete (full as any).def;\n delete full.inst;\n delete full.continue;\n if (!ctx?.reportInput) {\n delete full.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\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) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues });\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues });\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.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 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 }, issue.path));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, 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 ? Object.assign(_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 ? Object.assign(_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 ? Object.assign(_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 ? Object.assign(_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 ? Object.assign(_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 ? Object.assign(_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 ? Object.assign(_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\";\nexport const cuid = /^[cC][^\\s-]{8,}$/;\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,}$/;\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: 3,\n patch: 6,\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 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 // @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});\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 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.optin = \"optional\";\n inst._zod.optout = \"optional\";\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, isOptionalOut) {\n if (result.issues.length) {\n // For optional-out schemas, ignore errors on absent keys\n if (isOptionalOut && !(key in input)) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (result.value === undefined) {\n if (key in input) {\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 // iterate over input keys\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const isOptionalOut = _catchall.optout === \"optional\";\n for (const key in input) {\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, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, 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 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, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, 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 isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(key)};`);\n if (isOptionalOut) {\n // For optional-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 {\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 single = def.options.length === 1;\n const first = def.options[0]._zod.run;\n inst._zod.parse = (payload, ctx) => {\n if (single) {\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 single = def.options.length === 1;\n const first = def.options[0]._zod.run;\n inst._zod.parse = (payload, ctx) => {\n if (single) {\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 if (def.unionFallback) {\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 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 reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== \"optional\");\n const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex;\n if (!def.rest) {\n const tooBig = input.length > items.length;\n const tooSmall = input.length < optStart - 1;\n if (tooBig || tooSmall) {\n payload.issues.push({\n ...(tooBig\n ? { code: \"too_big\", maximum: items.length, inclusive: true }\n : { code: \"too_small\", minimum: items.length }),\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n }\n let i = -1;\n for (const item of items) {\n i++;\n if (i >= input.length)\n if (i >= optStart)\n continue;\n const result = item._zod.run({\n value: input[i],\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n if (def.rest) {\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({\n value: el,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleTupleResult(result, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\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}\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 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[key] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[key] = 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 for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\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.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(result, input) {\n if (result.issues.length && input === undefined) {\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 result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise)\n return result.then((r) => handleOptionalResult(r, payload.value));\n return handleOptionalResult(result, payload.value);\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 util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\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 }\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 }\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 }, 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 $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 // let _innerType!: any;\n // util.defineLazy(def, \"getter\", () => {\n // if (!_innerType) {\n // _innerType = def.getter();\n // }\n // return () => _innerType;\n // });\n util.defineLazy(inst._zod, \"innerType\", () => def.getter());\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// @__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) {\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 });\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\" && result.schema._prefault)\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 // 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 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 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 if (typeof exclusiveMinimum === \"number\") {\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n if (typeof minimum === \"number\") {\n json.minimum = minimum;\n if (typeof exclusiveMinimum === \"number\" && ctx.target !== \"draft-04\") {\n if (exclusiveMinimum >= minimum)\n delete json.minimum;\n else\n delete json.exclusiveMinimum;\n }\n }\n if (typeof exclusiveMaximum === \"number\") {\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n if (typeof maximum === \"number\") {\n json.maximum = maximum;\n if (typeof exclusiveMaximum === \"number\" && ctx.target !== \"draft-04\") {\n if (exclusiveMaximum <= maximum)\n delete json.maximum;\n else\n delete json.exclusiveMaximum;\n }\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, { ...params, path: [...params.path, \"items\"] });\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 innerType = ctx.io === \"input\" ? (def.in._zod.def.type === \"transform\" ? 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 = core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = 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\";\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 // base methods\n inst.check = (...checks) => {\n return inst.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...checks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), {\n parent: true,\n });\n };\n inst.with = inst.check;\n inst.clone = (def, params) => core.clone(inst, def, params);\n inst.brand = () => inst;\n inst.register = ((reg, meta) => {\n reg.add(inst, meta);\n return inst;\n });\n // parsing\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 // encoding/decoding\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 // refinements\n inst.refine = (check, params) => inst.check(refine(check, params));\n inst.superRefine = (refinement) => inst.check(superRefine(refinement));\n inst.overwrite = (fn) => inst.check(checks.overwrite(fn));\n // wrappers\n inst.optional = () => optional(inst);\n inst.exactOptional = () => exactOptional(inst);\n inst.nullable = () => nullable(inst);\n inst.nullish = () => optional(nullable(inst));\n inst.nonoptional = (params) => nonoptional(inst, params);\n inst.array = () => array(inst);\n inst.or = (arg) => union([inst, arg]);\n inst.and = (arg) => intersection(inst, arg);\n inst.transform = (tx) => pipe(inst, transform(tx));\n inst.default = (def) => _default(inst, def);\n inst.prefault = (def) => prefault(inst, def);\n // inst.coalesce = (def, params) => coalesce(inst, def, params);\n inst.catch = (params) => _catch(inst, params);\n inst.pipe = (target) => pipe(inst, target);\n inst.readonly = () => readonly(inst);\n // meta\n inst.describe = (description) => {\n const cl = inst.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n };\n Object.defineProperty(inst, \"description\", {\n get() {\n return core.globalRegistry.get(inst)?.description;\n },\n configurable: true,\n });\n inst.meta = (...args) => {\n if (args.length === 0) {\n return core.globalRegistry.get(inst);\n }\n const cl = inst.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n };\n // helpers\n inst.isOptional = () => inst.safeParse(undefined).success;\n inst.isNullable = () => inst.safeParse(null).success;\n inst.apply = (fn) => fn(inst);\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 // validations\n inst.regex = (...args) => inst.check(checks.regex(...args));\n inst.includes = (...args) => inst.check(checks.includes(...args));\n inst.startsWith = (...args) => inst.check(checks.startsWith(...args));\n inst.endsWith = (...args) => inst.check(checks.endsWith(...args));\n inst.min = (...args) => inst.check(checks.minLength(...args));\n inst.max = (...args) => inst.check(checks.maxLength(...args));\n inst.length = (...args) => inst.check(checks.length(...args));\n inst.nonempty = (...args) => inst.check(checks.minLength(1, ...args));\n inst.lowercase = (params) => inst.check(checks.lowercase(params));\n inst.uppercase = (params) => inst.check(checks.uppercase(params));\n // transforms\n inst.trim = () => inst.check(checks.trim());\n inst.normalize = (...args) => inst.check(checks.normalize(...args));\n inst.toLowerCase = () => inst.check(checks.toLowerCase());\n inst.toUpperCase = () => inst.check(checks.toUpperCase());\n inst.slugify = () => inst.check(checks.slugify());\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: /^https?$/,\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}\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});\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 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.int = (params) => inst.check(int(params));\n inst.safe = (params) => inst.check(int(params));\n inst.positive = (params) => inst.check(checks.gt(0, params));\n inst.nonnegative = (params) => inst.check(checks.gte(0, params));\n inst.negative = (params) => inst.check(checks.lt(0, params));\n inst.nonpositive = (params) => inst.check(checks.lte(0, params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n inst.step = (value, params) => inst.check(checks.multipleOf(value, params));\n // inst.finite = (params) => inst.check(core.finite(params));\n inst.finite = () => inst;\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 inst.min = (minLength, params) => inst.check(checks.minLength(minLength, params));\n inst.nonempty = (params) => inst.check(checks.minLength(1, params));\n inst.max = (maxLength, params) => inst.check(checks.maxLength(maxLength, params));\n inst.length = (len, params) => inst.check(checks.length(len, params));\n inst.unwrap = () => inst.element;\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 inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));\n inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall });\n inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });\n inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });\n inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });\n inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined });\n inst.extend = (incoming) => {\n return util.extend(inst, incoming);\n };\n inst.safeExtend = (incoming) => {\n return util.safeExtend(inst, incoming);\n };\n inst.merge = (other) => util.merge(inst, other);\n inst.pick = (mask) => util.pick(inst, mask);\n inst.omit = (mask) => util.omit(inst, mask);\n inst.partial = (...args) => util.partial(ZodOptional, inst, args[0]);\n inst.required = (...args) => util.required(ZodNonOptional, inst, args[0]);\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 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 return payload;\n });\n }\n payload.value = output;\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 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) {\n return core._superRefine(fn);\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\n// /** @deprecated Use `z.pipe()` and `z.transform()` instead. */\nexport function preprocess(fn, schema) {\n return pipe(transform(fn), schema);\n}\n","export var util;\n(function (util) {\n util.assertEqual = (_) => { };\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && Number.isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array.map((val) => (typeof val === \"string\" ? `'${val}'` : val)).join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nexport var objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nexport const ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n","import { util } from \"./helpers/util.js\";\nexport const ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nexport const quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nexport class ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\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 processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = Object.create(null);\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n const firstEl = sub.path[0];\n fieldErrors[firstEl] = fieldErrors[firstEl] || [];\n fieldErrors[firstEl].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n","export var errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n // biome-ignore lint:\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message?.message;\n})(errorUtil || (errorUtil = {}));\n","import { ZodError, ZodIssueCode, } from \"./ZodError.js\";\nimport { defaultErrorMap, getErrorMap } from \"./errors.js\";\nimport { errorUtil } from \"./helpers/errorUtil.js\";\nimport { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from \"./helpers/parseUtil.js\";\nimport { util, ZodParsedType, getParsedType } from \"./helpers/util.js\";\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (Array.isArray(this._key)) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message ?? ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: message ?? required_error ?? ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: message ?? invalid_type_error ?? ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nexport class ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n const ctx = {\n common: {\n issues: [],\n async: params?.async ?? false,\n contextualErrorMap: params?.errorMap,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if (err?.message?.toLowerCase()?.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params?.errorMap,\n async: true,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\" ? refinementData(val, ctx) : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?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// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[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// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?: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])$/;\nconst ipv4CidrRegex = /^(?:(?: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])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\nconst ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;\nconst ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(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\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\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 dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n let secondsRegexSource = `[0-5]\\\\d`;\n if (args.precision) {\n secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n }\n const secondsQuantifier = args.precision ? \"+\" : \"?\"; // require seconds if precision is nonzero\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(\".\");\n if (!header)\n return false;\n // Convert base64url to base64\n const base64 = header\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n // @ts-ignore\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== \"object\" || decoded === null)\n return false;\n if (\"typ\" in decoded && decoded?.typ !== \"JWT\")\n return false;\n if (!decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nexport class ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n // @ts-ignore\n new URL(input.data);\n }\n catch {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"jwt\") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"jwt\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cidr\") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cidr\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64url\") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return this._addCheck({\n kind: \"base64url\",\n ...errorUtil.errToObj(message),\n });\n }\n jwt(options) {\n return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n offset: options?.offset ?? false,\n local: options?.local ?? false,\n ...errorUtil.errToObj(options?.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n ...errorUtil.errToObj(options?.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options?.position,\n ...errorUtil.errToObj(options?.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get isBase64url() {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nexport class ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" || (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null;\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" || ch.kind === \"int\" || ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n }\n catch {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (Number.isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: params?.coerce || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nexport class ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nexport class ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nexport class ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nexport class ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nexport class ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nexport class ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nexport class ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nexport class ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<T, Augmentation>,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n this._cached = { shape, keys };\n return this._cached;\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") {\n }\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: errorUtil.errToObj(message).message ?? defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n for (const key of util.objectKeys(mask)) {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nexport class ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util.objectKeys(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 { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\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 { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nexport class ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\n// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];\nexport class ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nexport class ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nexport class ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nexport class ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nexport class ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nexport class ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nexport class ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nexport class ZodEnum extends ZodType {\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(this._def.values);\n }\n if (!this._cache.has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\nZodEnum.create = createZodEnum;\nexport class ZodNativeEnum extends ZodType {\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(util.getValidEnumValues(this._def.values));\n }\n if (!this._cache.has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nexport class ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nexport class ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return INVALID;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n if (!isValid(base))\n return INVALID;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n status: status.value,\n value: result,\n }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nexport { ZodEffects as ZodTransformer };\nexport class ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nexport class ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nexport class ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\" ? params.default : () => params.default,\n ...processCreateParams(params),\n });\n};\nexport class ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nexport class ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nexport const BRAND = Symbol(\"zod_brand\");\nexport class ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nexport class ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nexport class ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\n////////////////////////////////////////\n////////////////////////////////////////\n////////// //////////\n////////// z.custom //////////\n////////// //////////\n////////////////////////////////////////\n////////////////////////////////////////\nfunction cleanParams(params, data) {\n const p = typeof params === \"function\" ? params(data) : typeof params === \"string\" ? { message: params } : params;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n return p2;\n}\nexport function custom(check, _params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n const r = check(data);\n if (r instanceof Promise) {\n return r.then((r) => {\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n });\n }\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n return;\n });\n return ZodAny.create();\n}\nexport { ZodType as Schema, ZodType as ZodSchema };\nexport const late = {\n object: ZodObject.lazycreate,\n};\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n// requires TS 4.4+\nclass Class {\n constructor(..._) { }\n}\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nexport const coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nexport { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };\nexport const NEVER = INVALID;\n","class ParseError extends Error {\n constructor(message, options) {\n super(message), this.name = \"ParseError\", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;\n }\n}\nfunction noop(_arg) {\n}\nfunction createParser(callbacks) {\n if (typeof callbacks == \"function\")\n throw new TypeError(\n \"`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?\"\n );\n const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;\n let incompleteLine = \"\", isFirstChunk = !0, id, data = \"\", eventType = \"\";\n function feed(newChunk) {\n const chunk = isFirstChunk ? newChunk.replace(/^\\xEF\\xBB\\xBF/, \"\") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);\n for (const line of complete)\n parseLine(line);\n incompleteLine = incomplete, isFirstChunk = !1;\n }\n function parseLine(line) {\n if (line === \"\") {\n dispatchEvent();\n return;\n }\n if (line.startsWith(\":\")) {\n onComment && onComment(line.slice(line.startsWith(\": \") ? 2 : 1));\n return;\n }\n const fieldSeparatorIndex = line.indexOf(\":\");\n if (fieldSeparatorIndex !== -1) {\n const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === \" \" ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);\n processField(field, value, line);\n return;\n }\n processField(line, \"\", line);\n }\n function processField(field, value, line) {\n switch (field) {\n case \"event\":\n eventType = value;\n break;\n case \"data\":\n data = `${data}${value}\n`;\n break;\n case \"id\":\n id = value.includes(\"\\0\") ? void 0 : value;\n break;\n case \"retry\":\n /^\\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(\n new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n type: \"invalid-retry\",\n value,\n line\n })\n );\n break;\n default:\n onError(\n new ParseError(\n `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}\\u2026` : field}\"`,\n { type: \"unknown-field\", field, value, line }\n )\n );\n break;\n }\n }\n function dispatchEvent() {\n data.length > 0 && onEvent({\n id,\n event: eventType || void 0,\n // If the data buffer's last character is a U+000A LINE FEED (LF) character,\n // then remove the last character from the data buffer.\n data: data.endsWith(`\n`) ? data.slice(0, -1) : data\n }), id = void 0, data = \"\", eventType = \"\";\n }\n function reset(options = {}) {\n incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = !0, id = void 0, data = \"\", eventType = \"\", incompleteLine = \"\";\n }\n return { feed, reset };\n}\nfunction splitLines(chunk) {\n const lines = [];\n let incompleteLine = \"\", searchIndex = 0;\n for (; searchIndex < chunk.length; ) {\n const crIndex = chunk.indexOf(\"\\r\", searchIndex), lfIndex = chunk.indexOf(`\n`, searchIndex);\n let lineEnd = -1;\n if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {\n incompleteLine = chunk.slice(searchIndex);\n break;\n } else {\n const line = chunk.slice(searchIndex, lineEnd);\n lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === \"\\r\" && chunk[searchIndex] === `\n` && searchIndex++;\n }\n }\n return [lines, incompleteLine];\n}\nexport {\n ParseError,\n createParser\n};\n//# sourceMappingURL=index.js.map\n","import { createParser } from \"./index.js\";\nimport { ParseError } from \"./index.js\";\nclass EventSourceParserStream extends TransformStream {\n constructor({ onError, onRetry, onComment } = {}) {\n let parser;\n super({\n start(controller) {\n parser = createParser({\n onEvent: (event) => {\n controller.enqueue(event);\n },\n onError(error) {\n onError === \"terminate\" ? controller.error(error) : typeof onError == \"function\" && onError(error);\n },\n onRetry,\n onComment\n });\n },\n transform(chunk) {\n parser.feed(chunk);\n }\n });\n }\n}\nexport {\n EventSourceParserStream,\n ParseError\n};\n//# sourceMappingURL=stream.js.map\n","// src/combine-headers.ts\nfunction combineHeaders(...headers) {\n return headers.reduce(\n (combinedHeaders, currentHeaders) => ({\n ...combinedHeaders,\n ...currentHeaders != null ? currentHeaders : {}\n }),\n {}\n );\n}\n\n// src/convert-async-iterator-to-readable-stream.ts\nfunction convertAsyncIteratorToReadableStream(iterator) {\n let cancelled = false;\n return new ReadableStream({\n /**\n * Called when the consumer wants to pull more data from the stream.\n *\n * @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.\n * @returns {Promise<void>}\n */\n async pull(controller) {\n if (cancelled) return;\n try {\n const { value, done } = await iterator.next();\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n controller.error(error);\n }\n },\n /**\n * Called when the consumer cancels the stream.\n */\n async cancel(reason) {\n cancelled = true;\n if (iterator.return) {\n try {\n await iterator.return(reason);\n } catch (e) {\n }\n }\n }\n });\n}\n\n// src/create-tool-name-mapping.ts\nfunction createToolNameMapping({\n tools = [],\n providerToolNames,\n resolveProviderToolName\n}) {\n var _a2;\n const customToolNameToProviderToolName = {};\n const providerToolNameToCustomToolName = {};\n for (const tool2 of tools) {\n if (tool2.type === \"provider\") {\n const providerToolName = (_a2 = resolveProviderToolName == null ? void 0 : resolveProviderToolName(tool2)) != null ? _a2 : tool2.id in providerToolNames ? providerToolNames[tool2.id] : void 0;\n if (providerToolName == null) {\n continue;\n }\n customToolNameToProviderToolName[tool2.name] = providerToolName;\n providerToolNameToCustomToolName[providerToolName] = tool2.name;\n }\n }\n return {\n toProviderToolName: (customToolName) => {\n var _a3;\n return (_a3 = customToolNameToProviderToolName[customToolName]) != null ? _a3 : customToolName;\n },\n toCustomToolName: (providerToolName) => {\n var _a3;\n return (_a3 = providerToolNameToCustomToolName[providerToolName]) != null ? _a3 : providerToolName;\n }\n };\n}\n\n// src/delay.ts\nasync function delay(delayInMs, options) {\n if (delayInMs == null) {\n return Promise.resolve();\n }\n const signal = options == null ? void 0 : options.abortSignal;\n return new Promise((resolve2, reject) => {\n if (signal == null ? void 0 : signal.aborted) {\n reject(createAbortError());\n return;\n }\n const timeoutId = setTimeout(() => {\n cleanup();\n resolve2();\n }, delayInMs);\n const cleanup = () => {\n clearTimeout(timeoutId);\n signal == null ? void 0 : signal.removeEventListener(\"abort\", onAbort);\n };\n const onAbort = () => {\n cleanup();\n reject(createAbortError());\n };\n signal == null ? void 0 : signal.addEventListener(\"abort\", onAbort);\n });\n}\nfunction createAbortError() {\n return new DOMException(\"Delay was aborted\", \"AbortError\");\n}\n\n// src/delayed-promise.ts\nvar DelayedPromise = class {\n constructor() {\n this.status = { type: \"pending\" };\n this._resolve = void 0;\n this._reject = void 0;\n }\n get promise() {\n if (this._promise) {\n return this._promise;\n }\n this._promise = new Promise((resolve2, reject) => {\n if (this.status.type === \"resolved\") {\n resolve2(this.status.value);\n } else if (this.status.type === \"rejected\") {\n reject(this.status.error);\n }\n this._resolve = resolve2;\n this._reject = reject;\n });\n return this._promise;\n }\n resolve(value) {\n var _a2;\n this.status = { type: \"resolved\", value };\n if (this._promise) {\n (_a2 = this._resolve) == null ? void 0 : _a2.call(this, value);\n }\n }\n reject(error) {\n var _a2;\n this.status = { type: \"rejected\", error };\n if (this._promise) {\n (_a2 = this._reject) == null ? void 0 : _a2.call(this, error);\n }\n }\n isResolved() {\n return this.status.type === \"resolved\";\n }\n isRejected() {\n return this.status.type === \"rejected\";\n }\n isPending() {\n return this.status.type === \"pending\";\n }\n};\n\n// src/extract-response-headers.ts\nfunction extractResponseHeaders(response) {\n return Object.fromEntries([...response.headers]);\n}\n\n// src/uint8-utils.ts\nvar { btoa, atob } = globalThis;\nfunction convertBase64ToUint8Array(base64String) {\n const base64Url = base64String.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const latin1string = atob(base64Url);\n return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));\n}\nfunction convertUint8ArrayToBase64(array) {\n let latin1string = \"\";\n for (let i = 0; i < array.length; i++) {\n latin1string += String.fromCodePoint(array[i]);\n }\n return btoa(latin1string);\n}\nfunction convertToBase64(value) {\n return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;\n}\n\n// src/convert-image-model-file-to-data-uri.ts\nfunction convertImageModelFileToDataUri(file) {\n if (file.type === \"url\") return file.url;\n return `data:${file.mediaType};base64,${typeof file.data === \"string\" ? file.data : convertUint8ArrayToBase64(file.data)}`;\n}\n\n// src/convert-to-form-data.ts\nfunction convertToFormData(input, options = {}) {\n const { useArrayBrackets = true } = options;\n const formData = new FormData();\n for (const [key, value] of Object.entries(input)) {\n if (value == null) {\n continue;\n }\n if (Array.isArray(value)) {\n if (value.length === 1) {\n formData.append(key, value[0]);\n continue;\n }\n const arrayKey = useArrayBrackets ? `${key}[]` : key;\n for (const item of value) {\n formData.append(arrayKey, item);\n }\n continue;\n }\n formData.append(key, value);\n }\n return formData;\n}\n\n// src/download-error.ts\nimport { AISDKError } from \"@ai-sdk/provider\";\nvar name = \"AI_DownloadError\";\nvar marker = `vercel.ai.error.${name}`;\nvar symbol = Symbol.for(marker);\nvar _a, _b;\nvar DownloadError = class extends (_b = AISDKError, _a = symbol, _b) {\n constructor({\n url,\n statusCode,\n statusText,\n cause,\n message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`\n }) {\n super({ name, message, cause });\n this[_a] = true;\n this.url = url;\n this.statusCode = statusCode;\n this.statusText = statusText;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker);\n }\n};\n\n// src/read-response-with-size-limit.ts\nvar DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;\nasync function readResponseWithSizeLimit({\n response,\n url,\n maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE\n}) {\n const contentLength = response.headers.get(\"content-length\");\n if (contentLength != null) {\n const length = parseInt(contentLength, 10);\n if (!isNaN(length) && length > maxBytes) {\n throw new DownloadError({\n url,\n message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).`\n });\n }\n }\n const body = response.body;\n if (body == null) {\n return new Uint8Array(0);\n }\n const reader = body.getReader();\n const chunks = [];\n let totalBytes = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n totalBytes += value.length;\n if (totalBytes > maxBytes) {\n throw new DownloadError({\n url,\n message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.`\n });\n }\n chunks.push(value);\n }\n } finally {\n try {\n await reader.cancel();\n } finally {\n reader.releaseLock();\n }\n }\n const result = new Uint8Array(totalBytes);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n return result;\n}\n\n// src/validate-download-url.ts\nfunction validateDownloadUrl(url) {\n let parsed;\n try {\n parsed = new URL(url);\n } catch (e) {\n throw new DownloadError({\n url,\n message: `Invalid URL: ${url}`\n });\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw new DownloadError({\n url,\n message: `URL scheme must be http or https, got ${parsed.protocol}`\n });\n }\n const hostname = parsed.hostname;\n if (!hostname) {\n throw new DownloadError({\n url,\n message: `URL must have a hostname`\n });\n }\n if (hostname === \"localhost\" || hostname.endsWith(\".local\") || hostname.endsWith(\".localhost\")) {\n throw new DownloadError({\n url,\n message: `URL with hostname ${hostname} is not allowed`\n });\n }\n if (hostname.startsWith(\"[\") && hostname.endsWith(\"]\")) {\n const ipv6 = hostname.slice(1, -1);\n if (isPrivateIPv6(ipv6)) {\n throw new DownloadError({\n url,\n message: `URL with IPv6 address ${hostname} is not allowed`\n });\n }\n return;\n }\n if (isIPv4(hostname)) {\n if (isPrivateIPv4(hostname)) {\n throw new DownloadError({\n url,\n message: `URL with IP address ${hostname} is not allowed`\n });\n }\n return;\n }\n}\nfunction isIPv4(hostname) {\n const parts = hostname.split(\".\");\n if (parts.length !== 4) return false;\n return parts.every((part) => {\n const num = Number(part);\n return Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part;\n });\n}\nfunction isPrivateIPv4(ip) {\n const parts = ip.split(\".\").map(Number);\n const [a, b] = parts;\n if (a === 0) return true;\n if (a === 10) return true;\n if (a === 127) return true;\n if (a === 169 && b === 254) return true;\n if (a === 172 && b >= 16 && b <= 31) return true;\n if (a === 192 && b === 168) return true;\n return false;\n}\nfunction isPrivateIPv6(ip) {\n const normalized = ip.toLowerCase();\n if (normalized === \"::1\") return true;\n if (normalized === \"::\") return true;\n if (normalized.startsWith(\"::ffff:\")) {\n const mappedPart = normalized.slice(7);\n if (isIPv4(mappedPart)) {\n return isPrivateIPv4(mappedPart);\n }\n const hexParts = mappedPart.split(\":\");\n if (hexParts.length === 2) {\n const high = parseInt(hexParts[0], 16);\n const low = parseInt(hexParts[1], 16);\n if (!isNaN(high) && !isNaN(low)) {\n const a = high >> 8 & 255;\n const b = high & 255;\n const c = low >> 8 & 255;\n const d = low & 255;\n return isPrivateIPv4(`${a}.${b}.${c}.${d}`);\n }\n }\n }\n if (normalized.startsWith(\"fc\") || normalized.startsWith(\"fd\")) return true;\n if (normalized.startsWith(\"fe80\")) return true;\n return false;\n}\n\n// src/download-blob.ts\nasync function downloadBlob(url, options) {\n var _a2, _b2;\n validateDownloadUrl(url);\n try {\n const response = await fetch(url, {\n signal: options == null ? void 0 : options.abortSignal\n });\n if (!response.ok) {\n throw new DownloadError({\n url,\n statusCode: response.status,\n statusText: response.statusText\n });\n }\n const data = await readResponseWithSizeLimit({\n response,\n url,\n maxBytes: (_a2 = options == null ? void 0 : options.maxBytes) != null ? _a2 : DEFAULT_MAX_DOWNLOAD_SIZE\n });\n const contentType = (_b2 = response.headers.get(\"content-type\")) != null ? _b2 : void 0;\n return new Blob([data], contentType ? { type: contentType } : void 0);\n } catch (error) {\n if (DownloadError.isInstance(error)) {\n throw error;\n }\n throw new DownloadError({ url, cause: error });\n }\n}\n\n// src/generate-id.ts\nimport { InvalidArgumentError } from \"@ai-sdk/provider\";\nvar createIdGenerator = ({\n prefix,\n size = 16,\n alphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\",\n separator = \"-\"\n} = {}) => {\n const generator = () => {\n const alphabetLength = alphabet.length;\n const chars = new Array(size);\n for (let i = 0; i < size; i++) {\n chars[i] = alphabet[Math.random() * alphabetLength | 0];\n }\n return chars.join(\"\");\n };\n if (prefix == null) {\n return generator;\n }\n if (alphabet.includes(separator)) {\n throw new InvalidArgumentError({\n argument: \"separator\",\n message: `The separator \"${separator}\" must not be part of the alphabet \"${alphabet}\".`\n });\n }\n return () => `${prefix}${separator}${generator()}`;\n};\nvar generateId = createIdGenerator();\n\n// src/get-error-message.ts\nfunction getErrorMessage(error) {\n if (error == null) {\n return \"unknown error\";\n }\n if (typeof error === \"string\") {\n return error;\n }\n if (error instanceof Error) {\n return error.message;\n }\n return JSON.stringify(error);\n}\n\n// src/get-from-api.ts\nimport { APICallError as APICallError2 } from \"@ai-sdk/provider\";\n\n// src/handle-fetch-error.ts\nimport { APICallError } from \"@ai-sdk/provider\";\n\n// src/is-abort-error.ts\nfunction isAbortError(error) {\n return (error instanceof Error || error instanceof DOMException) && (error.name === \"AbortError\" || error.name === \"ResponseAborted\" || // Next.js\n error.name === \"TimeoutError\");\n}\n\n// src/handle-fetch-error.ts\nvar FETCH_FAILED_ERROR_MESSAGES = [\"fetch failed\", \"failed to fetch\"];\nvar BUN_ERROR_CODES = [\n \"ConnectionRefused\",\n \"ConnectionClosed\",\n \"FailedToOpenSocket\",\n \"ECONNRESET\",\n \"ECONNREFUSED\",\n \"ETIMEDOUT\",\n \"EPIPE\"\n];\nfunction isBunNetworkError(error) {\n if (!(error instanceof Error)) {\n return false;\n }\n const code = error.code;\n if (typeof code === \"string\" && BUN_ERROR_CODES.includes(code)) {\n return true;\n }\n return false;\n}\nfunction handleFetchError({\n error,\n url,\n requestBodyValues\n}) {\n if (isAbortError(error)) {\n return error;\n }\n if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {\n const cause = error.cause;\n if (cause != null) {\n return new APICallError({\n message: `Cannot connect to API: ${cause.message}`,\n cause,\n url,\n requestBodyValues,\n isRetryable: true\n // retry when network error\n });\n }\n }\n if (isBunNetworkError(error)) {\n return new APICallError({\n message: `Cannot connect to API: ${error.message}`,\n cause: error,\n url,\n requestBodyValues,\n isRetryable: true\n });\n }\n return error;\n}\n\n// src/get-runtime-environment-user-agent.ts\nfunction getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {\n var _a2, _b2, _c;\n if (globalThisAny.window) {\n return `runtime/browser`;\n }\n if ((_a2 = globalThisAny.navigator) == null ? void 0 : _a2.userAgent) {\n return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;\n }\n if ((_c = (_b2 = globalThisAny.process) == null ? void 0 : _b2.versions) == null ? void 0 : _c.node) {\n return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;\n }\n if (globalThisAny.EdgeRuntime) {\n return `runtime/vercel-edge`;\n }\n return \"runtime/unknown\";\n}\n\n// src/normalize-headers.ts\nfunction normalizeHeaders(headers) {\n if (headers == null) {\n return {};\n }\n const normalized = {};\n if (headers instanceof Headers) {\n headers.forEach((value, key) => {\n normalized[key.toLowerCase()] = value;\n });\n } else {\n if (!Array.isArray(headers)) {\n headers = Object.entries(headers);\n }\n for (const [key, value] of headers) {\n if (value != null) {\n normalized[key.toLowerCase()] = value;\n }\n }\n }\n return normalized;\n}\n\n// src/with-user-agent-suffix.ts\nfunction withUserAgentSuffix(headers, ...userAgentSuffixParts) {\n const normalizedHeaders = new Headers(normalizeHeaders(headers));\n const currentUserAgentHeader = normalizedHeaders.get(\"user-agent\") || \"\";\n normalizedHeaders.set(\n \"user-agent\",\n [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(\" \")\n );\n return Object.fromEntries(normalizedHeaders.entries());\n}\n\n// src/version.ts\nvar VERSION = true ? \"4.0.19\" : \"0.0.0-test\";\n\n// src/get-from-api.ts\nvar getOriginalFetch = () => globalThis.fetch;\nvar getFromApi = async ({\n url,\n headers = {},\n successfulResponseHandler,\n failedResponseHandler,\n abortSignal,\n fetch: fetch2 = getOriginalFetch()\n}) => {\n try {\n const response = await fetch2(url, {\n method: \"GET\",\n headers: withUserAgentSuffix(\n headers,\n `ai-sdk/provider-utils/${VERSION}`,\n getRuntimeEnvironmentUserAgent()\n ),\n signal: abortSignal\n });\n const responseHeaders = extractResponseHeaders(response);\n if (!response.ok) {\n let errorInformation;\n try {\n errorInformation = await failedResponseHandler({\n response,\n url,\n requestBodyValues: {}\n });\n } catch (error) {\n if (isAbortError(error) || APICallError2.isInstance(error)) {\n throw error;\n }\n throw new APICallError2({\n message: \"Failed to process error response\",\n cause: error,\n statusCode: response.status,\n url,\n responseHeaders,\n requestBodyValues: {}\n });\n }\n throw errorInformation.value;\n }\n try {\n return await successfulResponseHandler({\n response,\n url,\n requestBodyValues: {}\n });\n } catch (error) {\n if (error instanceof Error) {\n if (isAbortError(error) || APICallError2.isInstance(error)) {\n throw error;\n }\n }\n throw new APICallError2({\n message: \"Failed to process successful response\",\n cause: error,\n statusCode: response.status,\n url,\n responseHeaders,\n requestBodyValues: {}\n });\n }\n } catch (error) {\n throw handleFetchError({ error, url, requestBodyValues: {} });\n }\n};\n\n// src/inject-json-instruction.ts\nvar DEFAULT_SCHEMA_PREFIX = \"JSON schema:\";\nvar DEFAULT_SCHEMA_SUFFIX = \"You MUST answer with a JSON object that matches the JSON schema above.\";\nvar DEFAULT_GENERIC_SUFFIX = \"You MUST answer with JSON.\";\nfunction injectJsonInstruction({\n prompt,\n schema,\n schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : void 0,\n schemaSuffix = schema != null ? DEFAULT_SCHEMA_SUFFIX : DEFAULT_GENERIC_SUFFIX\n}) {\n return [\n prompt != null && prompt.length > 0 ? prompt : void 0,\n prompt != null && prompt.length > 0 ? \"\" : void 0,\n // add a newline if prompt is not null\n schemaPrefix,\n schema != null ? JSON.stringify(schema) : void 0,\n schemaSuffix\n ].filter((line) => line != null).join(\"\\n\");\n}\nfunction injectJsonInstructionIntoMessages({\n messages,\n schema,\n schemaPrefix,\n schemaSuffix\n}) {\n var _a2, _b2;\n const systemMessage = ((_a2 = messages[0]) == null ? void 0 : _a2.role) === \"system\" ? { ...messages[0] } : { role: \"system\", content: \"\" };\n systemMessage.content = injectJsonInstruction({\n prompt: systemMessage.content,\n schema,\n schemaPrefix,\n schemaSuffix\n });\n return [\n systemMessage,\n ...((_b2 = messages[0]) == null ? void 0 : _b2.role) === \"system\" ? messages.slice(1) : messages\n ];\n}\n\n// src/is-non-nullable.ts\nfunction isNonNullable(value) {\n return value != null;\n}\n\n// src/is-url-supported.ts\nfunction isUrlSupported({\n mediaType,\n url,\n supportedUrls\n}) {\n url = url.toLowerCase();\n mediaType = mediaType.toLowerCase();\n return Object.entries(supportedUrls).map(([key, value]) => {\n const mediaType2 = key.toLowerCase();\n return mediaType2 === \"*\" || mediaType2 === \"*/*\" ? { mediaTypePrefix: \"\", regexes: value } : { mediaTypePrefix: mediaType2.replace(/\\*/, \"\"), regexes: value };\n }).filter(({ mediaTypePrefix }) => mediaType.startsWith(mediaTypePrefix)).flatMap(({ regexes }) => regexes).some((pattern) => pattern.test(url));\n}\n\n// src/load-api-key.ts\nimport { LoadAPIKeyError } from \"@ai-sdk/provider\";\nfunction loadApiKey({\n apiKey,\n environmentVariableName,\n apiKeyParameterName = \"apiKey\",\n description\n}) {\n if (typeof apiKey === \"string\") {\n return apiKey;\n }\n if (apiKey != null) {\n throw new LoadAPIKeyError({\n message: `${description} API key must be a string.`\n });\n }\n if (typeof process === \"undefined\") {\n throw new LoadAPIKeyError({\n message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`\n });\n }\n apiKey = process.env[environmentVariableName];\n if (apiKey == null) {\n throw new LoadAPIKeyError({\n message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`\n });\n }\n if (typeof apiKey !== \"string\") {\n throw new LoadAPIKeyError({\n message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`\n });\n }\n return apiKey;\n}\n\n// src/load-optional-setting.ts\nfunction loadOptionalSetting({\n settingValue,\n environmentVariableName\n}) {\n if (typeof settingValue === \"string\") {\n return settingValue;\n }\n if (settingValue != null || typeof process === \"undefined\") {\n return void 0;\n }\n settingValue = process.env[environmentVariableName];\n if (settingValue == null || typeof settingValue !== \"string\") {\n return void 0;\n }\n return settingValue;\n}\n\n// src/load-setting.ts\nimport { LoadSettingError } from \"@ai-sdk/provider\";\nfunction loadSetting({\n settingValue,\n environmentVariableName,\n settingName,\n description\n}) {\n if (typeof settingValue === \"string\") {\n return settingValue;\n }\n if (settingValue != null) {\n throw new LoadSettingError({\n message: `${description} setting must be a string.`\n });\n }\n if (typeof process === \"undefined\") {\n throw new LoadSettingError({\n message: `${description} setting is missing. Pass it using the '${settingName}' parameter. Environment variables is not supported in this environment.`\n });\n }\n settingValue = process.env[environmentVariableName];\n if (settingValue == null) {\n throw new LoadSettingError({\n message: `${description} setting is missing. Pass it using the '${settingName}' parameter or the ${environmentVariableName} environment variable.`\n });\n }\n if (typeof settingValue !== \"string\") {\n throw new LoadSettingError({\n message: `${description} setting must be a string. The value of the ${environmentVariableName} environment variable is not a string.`\n });\n }\n return settingValue;\n}\n\n// src/media-type-to-extension.ts\nfunction mediaTypeToExtension(mediaType) {\n var _a2;\n const [_type, subtype = \"\"] = mediaType.toLowerCase().split(\"/\");\n return (_a2 = {\n mpeg: \"mp3\",\n \"x-wav\": \"wav\",\n opus: \"ogg\",\n mp4: \"m4a\",\n \"x-m4a\": \"m4a\"\n }[subtype]) != null ? _a2 : subtype;\n}\n\n// src/parse-json.ts\nimport {\n JSONParseError,\n TypeValidationError as TypeValidationError3\n} from \"@ai-sdk/provider\";\n\n// src/secure-json-parse.ts\nvar suspectProtoRx = /\"(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])(?:p|\\\\u0070)(?:r|\\\\u0072)(?:o|\\\\u006[Ff])(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])\"\\s*:/;\nvar suspectConstructorRx = /\"(?:c|\\\\u0063)(?:o|\\\\u006[Ff])(?:n|\\\\u006[Ee])(?:s|\\\\u0073)(?:t|\\\\u0074)(?:r|\\\\u0072)(?:u|\\\\u0075)(?:c|\\\\u0063)(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:r|\\\\u0072)\"\\s*:/;\nfunction _parse(text) {\n const obj = JSON.parse(text);\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {\n return obj;\n }\n return filter(obj);\n}\nfunction filter(obj) {\n let next = [obj];\n while (next.length) {\n const nodes = next;\n next = [];\n for (const node of nodes) {\n if (Object.prototype.hasOwnProperty.call(node, \"__proto__\")) {\n throw new SyntaxError(\"Object contains forbidden prototype property\");\n }\n if (Object.prototype.hasOwnProperty.call(node, \"constructor\") && node.constructor !== null && typeof node.constructor === \"object\" && Object.prototype.hasOwnProperty.call(node.constructor, \"prototype\")) {\n throw new SyntaxError(\"Object contains forbidden prototype property\");\n }\n for (const key in node) {\n const value = node[key];\n if (value && typeof value === \"object\") {\n next.push(value);\n }\n }\n }\n }\n return obj;\n}\nfunction secureJsonParse(text) {\n const { stackTraceLimit } = Error;\n try {\n Error.stackTraceLimit = 0;\n } catch (e) {\n return _parse(text);\n }\n try {\n return _parse(text);\n } finally {\n Error.stackTraceLimit = stackTraceLimit;\n }\n}\n\n// src/validate-types.ts\nimport { TypeValidationError as TypeValidationError2 } from \"@ai-sdk/provider\";\n\n// src/schema.ts\nimport { TypeValidationError } from \"@ai-sdk/provider\";\nimport * as z4 from \"zod/v4\";\n\n// src/add-additional-properties-to-json-schema.ts\nfunction addAdditionalPropertiesToJsonSchema(jsonSchema2) {\n if (jsonSchema2.type === \"object\" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes(\"object\")) {\n jsonSchema2.additionalProperties = false;\n const { properties } = jsonSchema2;\n if (properties != null) {\n for (const key of Object.keys(properties)) {\n properties[key] = visit(properties[key]);\n }\n }\n }\n if (jsonSchema2.items != null) {\n jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items);\n }\n if (jsonSchema2.anyOf != null) {\n jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit);\n }\n if (jsonSchema2.allOf != null) {\n jsonSchema2.allOf = jsonSchema2.allOf.map(visit);\n }\n if (jsonSchema2.oneOf != null) {\n jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit);\n }\n const { definitions } = jsonSchema2;\n if (definitions != null) {\n for (const key of Object.keys(definitions)) {\n definitions[key] = visit(definitions[key]);\n }\n }\n return jsonSchema2;\n}\nfunction visit(def) {\n if (typeof def === \"boolean\") return def;\n return addAdditionalPropertiesToJsonSchema(def);\n}\n\n// src/to-json-schema/zod3-to-json-schema/options.ts\nvar ignoreOverride = Symbol(\n \"Let zodToJsonSchema decide on which parser to use\"\n);\nvar defaultOptions = {\n name: void 0,\n $refStrategy: \"root\",\n basePath: [\"#\"],\n effectStrategy: \"input\",\n pipeStrategy: \"all\",\n dateStrategy: \"format:date-time\",\n mapStrategy: \"entries\",\n removeAdditionalStrategy: \"passthrough\",\n allowedAdditionalProperties: true,\n rejectedAdditionalProperties: false,\n definitionPath: \"definitions\",\n strictUnions: false,\n definitions: {},\n errorMessages: false,\n patternStrategy: \"escape\",\n applyRegexFlags: false,\n emailStrategy: \"format:email\",\n base64Strategy: \"contentEncoding:base64\",\n nameStrategy: \"ref\"\n};\nvar getDefaultOptions = (options) => typeof options === \"string\" ? {\n ...defaultOptions,\n name: options\n} : {\n ...defaultOptions,\n ...options\n};\n\n// src/to-json-schema/zod3-to-json-schema/select-parser.ts\nimport { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from \"zod/v3\";\n\n// src/to-json-schema/zod3-to-json-schema/parsers/any.ts\nfunction parseAnyDef() {\n return {};\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/array.ts\nimport { ZodFirstPartyTypeKind } from \"zod/v3\";\nfunction parseArrayDef(def, refs) {\n var _a2, _b2, _c;\n const res = {\n type: \"array\"\n };\n if (((_a2 = def.type) == null ? void 0 : _a2._def) && ((_c = (_b2 = def.type) == null ? void 0 : _b2._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {\n res.items = parseDef(def.type._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\"]\n });\n }\n if (def.minLength) {\n res.minItems = def.minLength.value;\n }\n if (def.maxLength) {\n res.maxItems = def.maxLength.value;\n }\n if (def.exactLength) {\n res.minItems = def.exactLength.value;\n res.maxItems = def.exactLength.value;\n }\n return res;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/bigint.ts\nfunction parseBigintDef(def) {\n const res = {\n type: \"integer\",\n format: \"int64\"\n };\n if (!def.checks) return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n if (check.inclusive) {\n res.minimum = check.value;\n } else {\n res.exclusiveMinimum = check.value;\n }\n break;\n case \"max\":\n if (check.inclusive) {\n res.maximum = check.value;\n } else {\n res.exclusiveMaximum = check.value;\n }\n break;\n case \"multipleOf\":\n res.multipleOf = check.value;\n break;\n }\n }\n return res;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/boolean.ts\nfunction parseBooleanDef() {\n return { type: \"boolean\" };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/branded.ts\nfunction parseBrandedDef(_def, refs) {\n return parseDef(_def.type._def, refs);\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/catch.ts\nvar parseCatchDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/date.ts\nfunction parseDateDef(def, refs, overrideDateStrategy) {\n const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;\n if (Array.isArray(strategy)) {\n return {\n anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))\n };\n }\n switch (strategy) {\n case \"string\":\n case \"format:date-time\":\n return {\n type: \"string\",\n format: \"date-time\"\n };\n case \"format:date\":\n return {\n type: \"string\",\n format: \"date\"\n };\n case \"integer\":\n return integerDateParser(def);\n }\n}\nvar integerDateParser = (def) => {\n const res = {\n type: \"integer\",\n format: \"unix-time\"\n };\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n res.minimum = check.value;\n break;\n case \"max\":\n res.maximum = check.value;\n break;\n }\n }\n return res;\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/default.ts\nfunction parseDefaultDef(_def, refs) {\n return {\n ...parseDef(_def.innerType._def, refs),\n default: _def.defaultValue()\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/effects.ts\nfunction parseEffectsDef(_def, refs) {\n return refs.effectStrategy === \"input\" ? parseDef(_def.schema._def, refs) : parseAnyDef();\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/enum.ts\nfunction parseEnumDef(def) {\n return {\n type: \"string\",\n enum: Array.from(def.values)\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/intersection.ts\nvar isJsonSchema7AllOfType = (type) => {\n if (\"type\" in type && type.type === \"string\") return false;\n return \"allOf\" in type;\n};\nfunction parseIntersectionDef(def, refs) {\n const allOf = [\n parseDef(def.left._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"0\"]\n }),\n parseDef(def.right._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"1\"]\n })\n ].filter((x) => !!x);\n const mergedAllOf = [];\n allOf.forEach((schema) => {\n if (isJsonSchema7AllOfType(schema)) {\n mergedAllOf.push(...schema.allOf);\n } else {\n let nestedSchema = schema;\n if (\"additionalProperties\" in schema && schema.additionalProperties === false) {\n const { additionalProperties, ...rest } = schema;\n nestedSchema = rest;\n }\n mergedAllOf.push(nestedSchema);\n }\n });\n return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/literal.ts\nfunction parseLiteralDef(def) {\n const parsedType = typeof def.value;\n if (parsedType !== \"bigint\" && parsedType !== \"number\" && parsedType !== \"boolean\" && parsedType !== \"string\") {\n return {\n type: Array.isArray(def.value) ? \"array\" : \"object\"\n };\n }\n return {\n type: parsedType === \"bigint\" ? \"integer\" : parsedType,\n const: def.value\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/record.ts\nimport {\n ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2\n} from \"zod/v3\";\n\n// src/to-json-schema/zod3-to-json-schema/parsers/string.ts\nvar emojiRegex = void 0;\nvar zodPatterns = {\n /**\n * `c` was changed to `[cC]` to replicate /i flag\n */\n cuid: /^[cC][^\\s-]{8,}$/,\n cuid2: /^[0-9a-z]+$/,\n ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n /**\n * `a-z` was added to replicate /i flag\n */\n email: /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n /**\n * Constructed a valid Unicode RegExp\n *\n * Lazily instantiate since this type of regex isn't supported\n * in all envs (e.g. React Native).\n *\n * See:\n * https://github.com/colinhacks/zod/issues/2433\n * Fix in Zod:\n * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n */\n emoji: () => {\n if (emojiRegex === void 0) {\n emojiRegex = RegExp(\n \"^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$\",\n \"u\"\n );\n }\n return emojiRegex;\n },\n /**\n * Unused\n */\n uuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n /**\n * Unused\n */\n 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])$/,\n ipv4Cidr: /^(?:(?: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])\\/(3[0-2]|[12]?[0-9])$/,\n /**\n * Unused\n */\n ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,\n base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,\n nanoid: /^[a-zA-Z0-9_-]{21}$/,\n jwt: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/\n};\nfunction parseStringDef(def, refs) {\n const res = {\n type: \"string\"\n };\n if (def.checks) {\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n res.minLength = typeof res.minLength === \"number\" ? Math.max(res.minLength, check.value) : check.value;\n break;\n case \"max\":\n res.maxLength = typeof res.maxLength === \"number\" ? Math.min(res.maxLength, check.value) : check.value;\n break;\n case \"email\":\n switch (refs.emailStrategy) {\n case \"format:email\":\n addFormat(res, \"email\", check.message, refs);\n break;\n case \"format:idn-email\":\n addFormat(res, \"idn-email\", check.message, refs);\n break;\n case \"pattern:zod\":\n addPattern(res, zodPatterns.email, check.message, refs);\n break;\n }\n break;\n case \"url\":\n addFormat(res, \"uri\", check.message, refs);\n break;\n case \"uuid\":\n addFormat(res, \"uuid\", check.message, refs);\n break;\n case \"regex\":\n addPattern(res, check.regex, check.message, refs);\n break;\n case \"cuid\":\n addPattern(res, zodPatterns.cuid, check.message, refs);\n break;\n case \"cuid2\":\n addPattern(res, zodPatterns.cuid2, check.message, refs);\n break;\n case \"startsWith\":\n addPattern(\n res,\n RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),\n check.message,\n refs\n );\n break;\n case \"endsWith\":\n addPattern(\n res,\n RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),\n check.message,\n refs\n );\n break;\n case \"datetime\":\n addFormat(res, \"date-time\", check.message, refs);\n break;\n case \"date\":\n addFormat(res, \"date\", check.message, refs);\n break;\n case \"time\":\n addFormat(res, \"time\", check.message, refs);\n break;\n case \"duration\":\n addFormat(res, \"duration\", check.message, refs);\n break;\n case \"length\":\n res.minLength = typeof res.minLength === \"number\" ? Math.max(res.minLength, check.value) : check.value;\n res.maxLength = typeof res.maxLength === \"number\" ? Math.min(res.maxLength, check.value) : check.value;\n break;\n case \"includes\": {\n addPattern(\n res,\n RegExp(escapeLiteralCheckValue(check.value, refs)),\n check.message,\n refs\n );\n break;\n }\n case \"ip\": {\n if (check.version !== \"v6\") {\n addFormat(res, \"ipv4\", check.message, refs);\n }\n if (check.version !== \"v4\") {\n addFormat(res, \"ipv6\", check.message, refs);\n }\n break;\n }\n case \"base64url\":\n addPattern(res, zodPatterns.base64url, check.message, refs);\n break;\n case \"jwt\":\n addPattern(res, zodPatterns.jwt, check.message, refs);\n break;\n case \"cidr\": {\n if (check.version !== \"v6\") {\n addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);\n }\n if (check.version !== \"v4\") {\n addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);\n }\n break;\n }\n case \"emoji\":\n addPattern(res, zodPatterns.emoji(), check.message, refs);\n break;\n case \"ulid\": {\n addPattern(res, zodPatterns.ulid, check.message, refs);\n break;\n }\n case \"base64\": {\n switch (refs.base64Strategy) {\n case \"format:binary\": {\n addFormat(res, \"binary\", check.message, refs);\n break;\n }\n case \"contentEncoding:base64\": {\n res.contentEncoding = \"base64\";\n break;\n }\n case \"pattern:zod\": {\n addPattern(res, zodPatterns.base64, check.message, refs);\n break;\n }\n }\n break;\n }\n case \"nanoid\": {\n addPattern(res, zodPatterns.nanoid, check.message, refs);\n }\n case \"toLowerCase\":\n case \"toUpperCase\":\n case \"trim\":\n break;\n default:\n /* @__PURE__ */ ((_) => {\n })(check);\n }\n }\n }\n return res;\n}\nfunction escapeLiteralCheckValue(literal, refs) {\n return refs.patternStrategy === \"escape\" ? escapeNonAlphaNumeric(literal) : literal;\n}\nvar ALPHA_NUMERIC = new Set(\n \"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789\"\n);\nfunction escapeNonAlphaNumeric(source) {\n let result = \"\";\n for (let i = 0; i < source.length; i++) {\n if (!ALPHA_NUMERIC.has(source[i])) {\n result += \"\\\\\";\n }\n result += source[i];\n }\n return result;\n}\nfunction addFormat(schema, value, message, refs) {\n var _a2;\n if (schema.format || ((_a2 = schema.anyOf) == null ? void 0 : _a2.some((x) => x.format))) {\n if (!schema.anyOf) {\n schema.anyOf = [];\n }\n if (schema.format) {\n schema.anyOf.push({\n format: schema.format\n });\n delete schema.format;\n }\n schema.anyOf.push({\n format: value,\n ...message && refs.errorMessages && { errorMessage: { format: message } }\n });\n } else {\n schema.format = value;\n }\n}\nfunction addPattern(schema, regex, message, refs) {\n var _a2;\n if (schema.pattern || ((_a2 = schema.allOf) == null ? void 0 : _a2.some((x) => x.pattern))) {\n if (!schema.allOf) {\n schema.allOf = [];\n }\n if (schema.pattern) {\n schema.allOf.push({\n pattern: schema.pattern\n });\n delete schema.pattern;\n }\n schema.allOf.push({\n pattern: stringifyRegExpWithFlags(regex, refs),\n ...message && refs.errorMessages && { errorMessage: { pattern: message } }\n });\n } else {\n schema.pattern = stringifyRegExpWithFlags(regex, refs);\n }\n}\nfunction stringifyRegExpWithFlags(regex, refs) {\n var _a2;\n if (!refs.applyRegexFlags || !regex.flags) {\n return regex.source;\n }\n const flags = {\n i: regex.flags.includes(\"i\"),\n // Case-insensitive\n m: regex.flags.includes(\"m\"),\n // `^` and `$` matches adjacent to newline characters\n s: regex.flags.includes(\"s\")\n // `.` matches newlines\n };\n const source = flags.i ? regex.source.toLowerCase() : regex.source;\n let pattern = \"\";\n let isEscaped = false;\n let inCharGroup = false;\n let inCharRange = false;\n for (let i = 0; i < source.length; i++) {\n if (isEscaped) {\n pattern += source[i];\n isEscaped = false;\n continue;\n }\n if (flags.i) {\n if (inCharGroup) {\n if (source[i].match(/[a-z]/)) {\n if (inCharRange) {\n pattern += source[i];\n pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n inCharRange = false;\n } else if (source[i + 1] === \"-\" && ((_a2 = source[i + 2]) == null ? void 0 : _a2.match(/[a-z]/))) {\n pattern += source[i];\n inCharRange = true;\n } else {\n pattern += `${source[i]}${source[i].toUpperCase()}`;\n }\n continue;\n }\n } else if (source[i].match(/[a-z]/)) {\n pattern += `[${source[i]}${source[i].toUpperCase()}]`;\n continue;\n }\n }\n if (flags.m) {\n if (source[i] === \"^\") {\n pattern += `(^|(?<=[\\r\n]))`;\n continue;\n } else if (source[i] === \"$\") {\n pattern += `($|(?=[\\r\n]))`;\n continue;\n }\n }\n if (flags.s && source[i] === \".\") {\n pattern += inCharGroup ? `${source[i]}\\r\n` : `[${source[i]}\\r\n]`;\n continue;\n }\n pattern += source[i];\n if (source[i] === \"\\\\\") {\n isEscaped = true;\n } else if (inCharGroup && source[i] === \"]\") {\n inCharGroup = false;\n } else if (!inCharGroup && source[i] === \"[\") {\n inCharGroup = true;\n }\n }\n try {\n new RegExp(pattern);\n } catch (e) {\n console.warn(\n `Could not convert regex pattern at ${refs.currentPath.join(\n \"/\"\n )} to a flag-independent form! Falling back to the flag-ignorant source`\n );\n return regex.source;\n }\n return pattern;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/record.ts\nfunction parseRecordDef(def, refs) {\n var _a2, _b2, _c, _d, _e, _f;\n const schema = {\n type: \"object\",\n additionalProperties: (_a2 = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalProperties\"]\n })) != null ? _a2 : refs.allowedAdditionalProperties\n };\n if (((_b2 = def.keyType) == null ? void 0 : _b2._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {\n const { type, ...keyType } = parseStringDef(def.keyType._def, refs);\n return {\n ...schema,\n propertyNames: keyType\n };\n } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {\n return {\n ...schema,\n propertyNames: {\n enum: def.keyType._def.values\n }\n };\n } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {\n const { type, ...keyType } = parseBrandedDef(\n def.keyType._def,\n refs\n );\n return {\n ...schema,\n propertyNames: keyType\n };\n }\n return schema;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/map.ts\nfunction parseMapDef(def, refs) {\n if (refs.mapStrategy === \"record\") {\n return parseRecordDef(def, refs);\n }\n const keys = parseDef(def.keyType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", \"items\", \"0\"]\n }) || parseAnyDef();\n const values = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", \"items\", \"1\"]\n }) || parseAnyDef();\n return {\n type: \"array\",\n maxItems: 125,\n items: {\n type: \"array\",\n items: [keys, values],\n minItems: 2,\n maxItems: 2\n }\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/native-enum.ts\nfunction parseNativeEnumDef(def) {\n const object = def.values;\n const actualKeys = Object.keys(def.values).filter((key) => {\n return typeof object[object[key]] !== \"number\";\n });\n const actualValues = actualKeys.map((key) => object[key]);\n const parsedTypes = Array.from(\n new Set(actualValues.map((values) => typeof values))\n );\n return {\n type: parsedTypes.length === 1 ? parsedTypes[0] === \"string\" ? \"string\" : \"number\" : [\"string\", \"number\"],\n enum: actualValues\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/never.ts\nfunction parseNeverDef() {\n return { not: parseAnyDef() };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/null.ts\nfunction parseNullDef() {\n return {\n type: \"null\"\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/union.ts\nvar primitiveMappings = {\n ZodString: \"string\",\n ZodNumber: \"number\",\n ZodBigInt: \"integer\",\n ZodBoolean: \"boolean\",\n ZodNull: \"null\"\n};\nfunction parseUnionDef(def, refs) {\n const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n if (options.every(\n (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)\n )) {\n const types = options.reduce((types2, x) => {\n const type = primitiveMappings[x._def.typeName];\n return type && !types2.includes(type) ? [...types2, type] : types2;\n }, []);\n return {\n type: types.length > 1 ? types : types[0]\n };\n } else if (options.every((x) => x._def.typeName === \"ZodLiteral\" && !x.description)) {\n const types = options.reduce(\n (acc, x) => {\n const type = typeof x._def.value;\n switch (type) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n return [...acc, type];\n case \"bigint\":\n return [...acc, \"integer\"];\n case \"object\":\n if (x._def.value === null) return [...acc, \"null\"];\n case \"symbol\":\n case \"undefined\":\n case \"function\":\n default:\n return acc;\n }\n },\n []\n );\n if (types.length === options.length) {\n const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n return {\n type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n enum: options.reduce(\n (acc, x) => {\n return acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n },\n []\n )\n };\n }\n } else if (options.every((x) => x._def.typeName === \"ZodEnum\")) {\n return {\n type: \"string\",\n enum: options.reduce(\n (acc, x) => [\n ...acc,\n ...x._def.values.filter((x2) => !acc.includes(x2))\n ],\n []\n )\n };\n }\n return asAnyOf(def, refs);\n}\nvar asAnyOf = (def, refs) => {\n const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(\n (x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", `${i}`]\n })\n ).filter(\n (x) => !!x && (!refs.strictUnions || typeof x === \"object\" && Object.keys(x).length > 0)\n );\n return anyOf.length ? { anyOf } : void 0;\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/nullable.ts\nfunction parseNullableDef(def, refs) {\n if ([\"ZodString\", \"ZodNumber\", \"ZodBigInt\", \"ZodBoolean\", \"ZodNull\"].includes(\n def.innerType._def.typeName\n ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {\n return {\n type: [\n primitiveMappings[def.innerType._def.typeName],\n \"null\"\n ]\n };\n }\n const base = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", \"0\"]\n });\n return base && { anyOf: [base, { type: \"null\" }] };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/number.ts\nfunction parseNumberDef(def) {\n const res = {\n type: \"number\"\n };\n if (!def.checks) return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case \"int\":\n res.type = \"integer\";\n break;\n case \"min\":\n if (check.inclusive) {\n res.minimum = check.value;\n } else {\n res.exclusiveMinimum = check.value;\n }\n break;\n case \"max\":\n if (check.inclusive) {\n res.maximum = check.value;\n } else {\n res.exclusiveMaximum = check.value;\n }\n break;\n case \"multipleOf\":\n res.multipleOf = check.value;\n break;\n }\n }\n return res;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/object.ts\nfunction parseObjectDef(def, refs) {\n const result = {\n type: \"object\",\n properties: {}\n };\n const required = [];\n const shape = def.shape();\n for (const propName in shape) {\n let propDef = shape[propName];\n if (propDef === void 0 || propDef._def === void 0) {\n continue;\n }\n const propOptional = safeIsOptional(propDef);\n const parsedDef = parseDef(propDef._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"properties\", propName],\n propertyPath: [...refs.currentPath, \"properties\", propName]\n });\n if (parsedDef === void 0) {\n continue;\n }\n result.properties[propName] = parsedDef;\n if (!propOptional) {\n required.push(propName);\n }\n }\n if (required.length) {\n result.required = required;\n }\n const additionalProperties = decideAdditionalProperties(def, refs);\n if (additionalProperties !== void 0) {\n result.additionalProperties = additionalProperties;\n }\n return result;\n}\nfunction decideAdditionalProperties(def, refs) {\n if (def.catchall._def.typeName !== \"ZodNever\") {\n return parseDef(def.catchall._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalProperties\"]\n });\n }\n switch (def.unknownKeys) {\n case \"passthrough\":\n return refs.allowedAdditionalProperties;\n case \"strict\":\n return refs.rejectedAdditionalProperties;\n case \"strip\":\n return refs.removeAdditionalStrategy === \"strict\" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;\n }\n}\nfunction safeIsOptional(schema) {\n try {\n return schema.isOptional();\n } catch (e) {\n return true;\n }\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/optional.ts\nvar parseOptionalDef = (def, refs) => {\n var _a2;\n if (refs.currentPath.toString() === ((_a2 = refs.propertyPath) == null ? void 0 : _a2.toString())) {\n return parseDef(def.innerType._def, refs);\n }\n const innerSchema = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", \"1\"]\n });\n return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/pipeline.ts\nvar parsePipelineDef = (def, refs) => {\n if (refs.pipeStrategy === \"input\") {\n return parseDef(def.in._def, refs);\n } else if (refs.pipeStrategy === \"output\") {\n return parseDef(def.out._def, refs);\n }\n const a = parseDef(def.in._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"0\"]\n });\n const b = parseDef(def.out._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", a ? \"1\" : \"0\"]\n });\n return {\n allOf: [a, b].filter((x) => x !== void 0)\n };\n};\n\n// src/to-json-schema/zod3-to-json-schema/parsers/promise.ts\nfunction parsePromiseDef(def, refs) {\n return parseDef(def.type._def, refs);\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/set.ts\nfunction parseSetDef(def, refs) {\n const items = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\"]\n });\n const schema = {\n type: \"array\",\n uniqueItems: true,\n items\n };\n if (def.minSize) {\n schema.minItems = def.minSize.value;\n }\n if (def.maxSize) {\n schema.maxItems = def.maxSize.value;\n }\n return schema;\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/tuple.ts\nfunction parseTupleDef(def, refs) {\n if (def.rest) {\n return {\n type: \"array\",\n minItems: def.items.length,\n items: def.items.map(\n (x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", `${i}`]\n })\n ).reduce(\n (acc, x) => x === void 0 ? acc : [...acc, x],\n []\n ),\n additionalItems: parseDef(def.rest._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalItems\"]\n })\n };\n } else {\n return {\n type: \"array\",\n minItems: def.items.length,\n maxItems: def.items.length,\n items: def.items.map(\n (x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", `${i}`]\n })\n ).reduce(\n (acc, x) => x === void 0 ? acc : [...acc, x],\n []\n )\n };\n }\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/undefined.ts\nfunction parseUndefinedDef() {\n return {\n not: parseAnyDef()\n };\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/unknown.ts\nfunction parseUnknownDef() {\n return parseAnyDef();\n}\n\n// src/to-json-schema/zod3-to-json-schema/parsers/readonly.ts\nvar parseReadonlyDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n\n// src/to-json-schema/zod3-to-json-schema/select-parser.ts\nvar selectParser = (def, typeName, refs) => {\n switch (typeName) {\n case ZodFirstPartyTypeKind3.ZodString:\n return parseStringDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodNumber:\n return parseNumberDef(def);\n case ZodFirstPartyTypeKind3.ZodObject:\n return parseObjectDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodBigInt:\n return parseBigintDef(def);\n case ZodFirstPartyTypeKind3.ZodBoolean:\n return parseBooleanDef();\n case ZodFirstPartyTypeKind3.ZodDate:\n return parseDateDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodUndefined:\n return parseUndefinedDef();\n case ZodFirstPartyTypeKind3.ZodNull:\n return parseNullDef();\n case ZodFirstPartyTypeKind3.ZodArray:\n return parseArrayDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodUnion:\n case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:\n return parseUnionDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodIntersection:\n return parseIntersectionDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodTuple:\n return parseTupleDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodRecord:\n return parseRecordDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodLiteral:\n return parseLiteralDef(def);\n case ZodFirstPartyTypeKind3.ZodEnum:\n return parseEnumDef(def);\n case ZodFirstPartyTypeKind3.ZodNativeEnum:\n return parseNativeEnumDef(def);\n case ZodFirstPartyTypeKind3.ZodNullable:\n return parseNullableDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodOptional:\n return parseOptionalDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodMap:\n return parseMapDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodSet:\n return parseSetDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodLazy:\n return () => def.getter()._def;\n case ZodFirstPartyTypeKind3.ZodPromise:\n return parsePromiseDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodNaN:\n case ZodFirstPartyTypeKind3.ZodNever:\n return parseNeverDef();\n case ZodFirstPartyTypeKind3.ZodEffects:\n return parseEffectsDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodAny:\n return parseAnyDef();\n case ZodFirstPartyTypeKind3.ZodUnknown:\n return parseUnknownDef();\n case ZodFirstPartyTypeKind3.ZodDefault:\n return parseDefaultDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodBranded:\n return parseBrandedDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodReadonly:\n return parseReadonlyDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodCatch:\n return parseCatchDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodPipeline:\n return parsePipelineDef(def, refs);\n case ZodFirstPartyTypeKind3.ZodFunction:\n case ZodFirstPartyTypeKind3.ZodVoid:\n case ZodFirstPartyTypeKind3.ZodSymbol:\n return void 0;\n default:\n return /* @__PURE__ */ ((_) => void 0)(typeName);\n }\n};\n\n// src/to-json-schema/zod3-to-json-schema/get-relative-path.ts\nvar getRelativePath = (pathA, pathB) => {\n let i = 0;\n for (; i < pathA.length && i < pathB.length; i++) {\n if (pathA[i] !== pathB[i]) break;\n }\n return [(pathA.length - i).toString(), ...pathB.slice(i)].join(\"/\");\n};\n\n// src/to-json-schema/zod3-to-json-schema/parse-def.ts\nfunction parseDef(def, refs, forceResolution = false) {\n var _a2;\n const seenItem = refs.seen.get(def);\n if (refs.override) {\n const overrideResult = (_a2 = refs.override) == null ? void 0 : _a2.call(\n refs,\n def,\n refs,\n seenItem,\n forceResolution\n );\n if (overrideResult !== ignoreOverride) {\n return overrideResult;\n }\n }\n if (seenItem && !forceResolution) {\n const seenSchema = get$ref(seenItem, refs);\n if (seenSchema !== void 0) {\n return seenSchema;\n }\n }\n const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };\n refs.seen.set(def, newItem);\n const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);\n const jsonSchema2 = typeof jsonSchemaOrGetter === \"function\" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;\n if (jsonSchema2) {\n addMeta(def, refs, jsonSchema2);\n }\n if (refs.postProcess) {\n const postProcessResult = refs.postProcess(jsonSchema2, def, refs);\n newItem.jsonSchema = jsonSchema2;\n return postProcessResult;\n }\n newItem.jsonSchema = jsonSchema2;\n return jsonSchema2;\n}\nvar get$ref = (item, refs) => {\n switch (refs.$refStrategy) {\n case \"root\":\n return { $ref: item.path.join(\"/\") };\n case \"relative\":\n return { $ref: getRelativePath(refs.currentPath, item.path) };\n case \"none\":\n case \"seen\": {\n if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {\n console.warn(\n `Recursive reference detected at ${refs.currentPath.join(\n \"/\"\n )}! Defaulting to any`\n );\n return parseAnyDef();\n }\n return refs.$refStrategy === \"seen\" ? parseAnyDef() : void 0;\n }\n }\n};\nvar addMeta = (def, refs, jsonSchema2) => {\n if (def.description) {\n jsonSchema2.description = def.description;\n }\n return jsonSchema2;\n};\n\n// src/to-json-schema/zod3-to-json-schema/refs.ts\nvar getRefs = (options) => {\n const _options = getDefaultOptions(options);\n const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;\n return {\n ..._options,\n currentPath,\n propertyPath: void 0,\n seen: new Map(\n Object.entries(_options.definitions).map(([name2, def]) => [\n def._def,\n {\n def: def._def,\n path: [..._options.basePath, _options.definitionPath, name2],\n // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.\n jsonSchema: void 0\n }\n ])\n )\n };\n};\n\n// src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.ts\nvar zod3ToJsonSchema = (schema, options) => {\n var _a2;\n const refs = getRefs(options);\n let definitions = typeof options === \"object\" && options.definitions ? Object.entries(options.definitions).reduce(\n (acc, [name3, schema2]) => {\n var _a3;\n return {\n ...acc,\n [name3]: (_a3 = parseDef(\n schema2._def,\n {\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name3]\n },\n true\n )) != null ? _a3 : parseAnyDef()\n };\n },\n {}\n ) : void 0;\n const name2 = typeof options === \"string\" ? options : (options == null ? void 0 : options.nameStrategy) === \"title\" ? void 0 : options == null ? void 0 : options.name;\n const main = (_a2 = parseDef(\n schema._def,\n name2 === void 0 ? refs : {\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name2]\n },\n false\n )) != null ? _a2 : parseAnyDef();\n const title = typeof options === \"object\" && options.name !== void 0 && options.nameStrategy === \"title\" ? options.name : void 0;\n if (title !== void 0) {\n main.title = title;\n }\n const combined = name2 === void 0 ? definitions ? {\n ...main,\n [refs.definitionPath]: definitions\n } : main : {\n $ref: [\n ...refs.$refStrategy === \"relative\" ? [] : refs.basePath,\n refs.definitionPath,\n name2\n ].join(\"/\"),\n [refs.definitionPath]: {\n ...definitions,\n [name2]: main\n }\n };\n combined.$schema = \"http://json-schema.org/draft-07/schema#\";\n return combined;\n};\n\n// src/schema.ts\nvar schemaSymbol = Symbol.for(\"vercel.ai.schema\");\nfunction lazySchema(createSchema) {\n let schema;\n return () => {\n if (schema == null) {\n schema = createSchema();\n }\n return schema;\n };\n}\nfunction jsonSchema(jsonSchema2, {\n validate\n} = {}) {\n return {\n [schemaSymbol]: true,\n _type: void 0,\n // should never be used directly\n get jsonSchema() {\n if (typeof jsonSchema2 === \"function\") {\n jsonSchema2 = jsonSchema2();\n }\n return jsonSchema2;\n },\n validate\n };\n}\nfunction isSchema(value) {\n return typeof value === \"object\" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && \"jsonSchema\" in value && \"validate\" in value;\n}\nfunction asSchema(schema) {\n return schema == null ? jsonSchema({ properties: {}, additionalProperties: false }) : isSchema(schema) ? schema : \"~standard\" in schema ? schema[\"~standard\"].vendor === \"zod\" ? zodSchema(schema) : standardSchema(schema) : schema();\n}\nfunction standardSchema(standardSchema2) {\n return jsonSchema(\n () => addAdditionalPropertiesToJsonSchema(\n standardSchema2[\"~standard\"].jsonSchema.input({\n target: \"draft-07\"\n })\n ),\n {\n validate: async (value) => {\n const result = await standardSchema2[\"~standard\"].validate(value);\n return \"value\" in result ? { success: true, value: result.value } : {\n success: false,\n error: new TypeValidationError({\n value,\n cause: result.issues\n })\n };\n }\n }\n );\n}\nfunction zod3Schema(zodSchema2, options) {\n var _a2;\n const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;\n return jsonSchema(\n // defer json schema creation to avoid unnecessary computation when only validation is needed\n () => zod3ToJsonSchema(zodSchema2, {\n $refStrategy: useReferences ? \"root\" : \"none\"\n }),\n {\n validate: async (value) => {\n const result = await zodSchema2.safeParseAsync(value);\n return result.success ? { success: true, value: result.data } : { success: false, error: result.error };\n }\n }\n );\n}\nfunction zod4Schema(zodSchema2, options) {\n var _a2;\n const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;\n return jsonSchema(\n // defer json schema creation to avoid unnecessary computation when only validation is needed\n () => addAdditionalPropertiesToJsonSchema(\n z4.toJSONSchema(zodSchema2, {\n target: \"draft-7\",\n io: \"input\",\n reused: useReferences ? \"ref\" : \"inline\"\n })\n ),\n {\n validate: async (value) => {\n const result = await z4.safeParseAsync(zodSchema2, value);\n return result.success ? { success: true, value: result.data } : { success: false, error: result.error };\n }\n }\n );\n}\nfunction isZod4Schema(zodSchema2) {\n return \"_zod\" in zodSchema2;\n}\nfunction zodSchema(zodSchema2, options) {\n if (isZod4Schema(zodSchema2)) {\n return zod4Schema(zodSchema2, options);\n } else {\n return zod3Schema(zodSchema2, options);\n }\n}\n\n// src/validate-types.ts\nasync function validateTypes({\n value,\n schema,\n context\n}) {\n const result = await safeValidateTypes({ value, schema, context });\n if (!result.success) {\n throw TypeValidationError2.wrap({ value, cause: result.error, context });\n }\n return result.value;\n}\nasync function safeValidateTypes({\n value,\n schema,\n context\n}) {\n const actualSchema = asSchema(schema);\n try {\n if (actualSchema.validate == null) {\n return { success: true, value, rawValue: value };\n }\n const result = await actualSchema.validate(value);\n if (result.success) {\n return { success: true, value: result.value, rawValue: value };\n }\n return {\n success: false,\n error: TypeValidationError2.wrap({ value, cause: result.error, context }),\n rawValue: value\n };\n } catch (error) {\n return {\n success: false,\n error: TypeValidationError2.wrap({ value, cause: error, context }),\n rawValue: value\n };\n }\n}\n\n// src/parse-json.ts\nasync function parseJSON({\n text,\n schema\n}) {\n try {\n const value = secureJsonParse(text);\n if (schema == null) {\n return value;\n }\n return validateTypes({ value, schema });\n } catch (error) {\n if (JSONParseError.isInstance(error) || TypeValidationError3.isInstance(error)) {\n throw error;\n }\n throw new JSONParseError({ text, cause: error });\n }\n}\nasync function safeParseJSON({\n text,\n schema\n}) {\n try {\n const value = secureJsonParse(text);\n if (schema == null) {\n return { success: true, value, rawValue: value };\n }\n return await safeValidateTypes({ value, schema });\n } catch (error) {\n return {\n success: false,\n error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),\n rawValue: void 0\n };\n }\n}\nfunction isParsableJson(input) {\n try {\n secureJsonParse(input);\n return true;\n } catch (e) {\n return false;\n }\n}\n\n// src/parse-json-event-stream.ts\nimport {\n EventSourceParserStream\n} from \"eventsource-parser/stream\";\nfunction parseJsonEventStream({\n stream,\n schema\n}) {\n return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(\n new TransformStream({\n async transform({ data }, controller) {\n if (data === \"[DONE]\") {\n return;\n }\n controller.enqueue(await safeParseJSON({ text: data, schema }));\n }\n })\n );\n}\n\n// src/parse-provider-options.ts\nimport { InvalidArgumentError as InvalidArgumentError2 } from \"@ai-sdk/provider\";\nasync function parseProviderOptions({\n provider,\n providerOptions,\n schema\n}) {\n if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {\n return void 0;\n }\n const parsedProviderOptions = await safeValidateTypes({\n value: providerOptions[provider],\n schema\n });\n if (!parsedProviderOptions.success) {\n throw new InvalidArgumentError2({\n argument: \"providerOptions\",\n message: `invalid ${provider} provider options`,\n cause: parsedProviderOptions.error\n });\n }\n return parsedProviderOptions.value;\n}\n\n// src/post-to-api.ts\nimport { APICallError as APICallError3 } from \"@ai-sdk/provider\";\nvar getOriginalFetch2 = () => globalThis.fetch;\nvar postJsonToApi = async ({\n url,\n headers,\n body,\n failedResponseHandler,\n successfulResponseHandler,\n abortSignal,\n fetch: fetch2\n}) => postToApi({\n url,\n headers: {\n \"Content-Type\": \"application/json\",\n ...headers\n },\n body: {\n content: JSON.stringify(body),\n values: body\n },\n failedResponseHandler,\n successfulResponseHandler,\n abortSignal,\n fetch: fetch2\n});\nvar postFormDataToApi = async ({\n url,\n headers,\n formData,\n failedResponseHandler,\n successfulResponseHandler,\n abortSignal,\n fetch: fetch2\n}) => postToApi({\n url,\n headers,\n body: {\n content: formData,\n values: Object.fromEntries(formData.entries())\n },\n failedResponseHandler,\n successfulResponseHandler,\n abortSignal,\n fetch: fetch2\n});\nvar postToApi = async ({\n url,\n headers = {},\n body,\n successfulResponseHandler,\n failedResponseHandler,\n abortSignal,\n fetch: fetch2 = getOriginalFetch2()\n}) => {\n try {\n const response = await fetch2(url, {\n method: \"POST\",\n headers: withUserAgentSuffix(\n headers,\n `ai-sdk/provider-utils/${VERSION}`,\n getRuntimeEnvironmentUserAgent()\n ),\n body: body.content,\n signal: abortSignal\n });\n const responseHeaders = extractResponseHeaders(response);\n if (!response.ok) {\n let errorInformation;\n try {\n errorInformation = await failedResponseHandler({\n response,\n url,\n requestBodyValues: body.values\n });\n } catch (error) {\n if (isAbortError(error) || APICallError3.isInstance(error)) {\n throw error;\n }\n throw new APICallError3({\n message: \"Failed to process error response\",\n cause: error,\n statusCode: response.status,\n url,\n responseHeaders,\n requestBodyValues: body.values\n });\n }\n throw errorInformation.value;\n }\n try {\n return await successfulResponseHandler({\n response,\n url,\n requestBodyValues: body.values\n });\n } catch (error) {\n if (error instanceof Error) {\n if (isAbortError(error) || APICallError3.isInstance(error)) {\n throw error;\n }\n }\n throw new APICallError3({\n message: \"Failed to process successful response\",\n cause: error,\n statusCode: response.status,\n url,\n responseHeaders,\n requestBodyValues: body.values\n });\n }\n } catch (error) {\n throw handleFetchError({ error, url, requestBodyValues: body.values });\n }\n};\n\n// src/types/tool.ts\nfunction tool(tool2) {\n return tool2;\n}\nfunction dynamicTool(tool2) {\n return { ...tool2, type: \"dynamic\" };\n}\n\n// src/provider-tool-factory.ts\nfunction createProviderToolFactory({\n id,\n inputSchema\n}) {\n return ({\n execute,\n outputSchema,\n needsApproval,\n toModelOutput,\n onInputStart,\n onInputDelta,\n onInputAvailable,\n ...args\n }) => tool({\n type: \"provider\",\n id,\n args,\n inputSchema,\n outputSchema,\n execute,\n needsApproval,\n toModelOutput,\n onInputStart,\n onInputDelta,\n onInputAvailable\n });\n}\nfunction createProviderToolFactoryWithOutputSchema({\n id,\n inputSchema,\n outputSchema,\n supportsDeferredResults\n}) {\n return ({\n execute,\n needsApproval,\n toModelOutput,\n onInputStart,\n onInputDelta,\n onInputAvailable,\n ...args\n }) => tool({\n type: \"provider\",\n id,\n args,\n inputSchema,\n outputSchema,\n execute,\n needsApproval,\n toModelOutput,\n onInputStart,\n onInputDelta,\n onInputAvailable,\n supportsDeferredResults\n });\n}\n\n// src/remove-undefined-entries.ts\nfunction removeUndefinedEntries(record) {\n return Object.fromEntries(\n Object.entries(record).filter(([_key, value]) => value != null)\n );\n}\n\n// src/resolve.ts\nasync function resolve(value) {\n if (typeof value === \"function\") {\n value = value();\n }\n return Promise.resolve(value);\n}\n\n// src/response-handler.ts\nimport { APICallError as APICallError4, EmptyResponseBodyError } from \"@ai-sdk/provider\";\nvar createJsonErrorResponseHandler = ({\n errorSchema,\n errorToMessage,\n isRetryable\n}) => async ({ response, url, requestBodyValues }) => {\n const responseBody = await response.text();\n const responseHeaders = extractResponseHeaders(response);\n if (responseBody.trim() === \"\") {\n return {\n responseHeaders,\n value: new APICallError4({\n message: response.statusText,\n url,\n requestBodyValues,\n statusCode: response.status,\n responseHeaders,\n responseBody,\n isRetryable: isRetryable == null ? void 0 : isRetryable(response)\n })\n };\n }\n try {\n const parsedError = await parseJSON({\n text: responseBody,\n schema: errorSchema\n });\n return {\n responseHeaders,\n value: new APICallError4({\n message: errorToMessage(parsedError),\n url,\n requestBodyValues,\n statusCode: response.status,\n responseHeaders,\n responseBody,\n data: parsedError,\n isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)\n })\n };\n } catch (parseError) {\n return {\n responseHeaders,\n value: new APICallError4({\n message: response.statusText,\n url,\n requestBodyValues,\n statusCode: response.status,\n responseHeaders,\n responseBody,\n isRetryable: isRetryable == null ? void 0 : isRetryable(response)\n })\n };\n }\n};\nvar createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {\n const responseHeaders = extractResponseHeaders(response);\n if (response.body == null) {\n throw new EmptyResponseBodyError({});\n }\n return {\n responseHeaders,\n value: parseJsonEventStream({\n stream: response.body,\n schema: chunkSchema\n })\n };\n};\nvar createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {\n const responseBody = await response.text();\n const parsedResult = await safeParseJSON({\n text: responseBody,\n schema: responseSchema\n });\n const responseHeaders = extractResponseHeaders(response);\n if (!parsedResult.success) {\n throw new APICallError4({\n message: \"Invalid JSON response\",\n cause: parsedResult.error,\n statusCode: response.status,\n responseHeaders,\n responseBody,\n url,\n requestBodyValues\n });\n }\n return {\n responseHeaders,\n value: parsedResult.value,\n rawValue: parsedResult.rawValue\n };\n};\nvar createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {\n const responseHeaders = extractResponseHeaders(response);\n if (!response.body) {\n throw new APICallError4({\n message: \"Response body is empty\",\n url,\n requestBodyValues,\n statusCode: response.status,\n responseHeaders,\n responseBody: void 0\n });\n }\n try {\n const buffer = await response.arrayBuffer();\n return {\n responseHeaders,\n value: new Uint8Array(buffer)\n };\n } catch (error) {\n throw new APICallError4({\n message: \"Failed to read response as array buffer\",\n url,\n requestBodyValues,\n statusCode: response.status,\n responseHeaders,\n responseBody: void 0,\n cause: error\n });\n }\n};\nvar createStatusCodeErrorResponseHandler = () => async ({ response, url, requestBodyValues }) => {\n const responseHeaders = extractResponseHeaders(response);\n const responseBody = await response.text();\n return {\n responseHeaders,\n value: new APICallError4({\n message: response.statusText,\n url,\n requestBodyValues,\n statusCode: response.status,\n responseHeaders,\n responseBody\n })\n };\n};\n\n// src/strip-file-extension.ts\nfunction stripFileExtension(filename) {\n const firstDotIndex = filename.indexOf(\".\");\n return firstDotIndex === -1 ? filename : filename.slice(0, firstDotIndex);\n}\n\n// src/without-trailing-slash.ts\nfunction withoutTrailingSlash(url) {\n return url == null ? void 0 : url.replace(/\\/$/, \"\");\n}\n\n// src/is-async-iterable.ts\nfunction isAsyncIterable(obj) {\n return obj != null && typeof obj[Symbol.asyncIterator] === \"function\";\n}\n\n// src/types/execute-tool.ts\nasync function* executeTool({\n execute,\n input,\n options\n}) {\n const result = execute(input, options);\n if (isAsyncIterable(result)) {\n let lastOutput;\n for await (const output of result) {\n lastOutput = output;\n yield { type: \"preliminary\", output };\n }\n yield { type: \"final\", output: lastOutput };\n } else {\n yield { type: \"final\", output: await result };\n }\n}\n\n// src/index.ts\nimport {\n EventSourceParserStream as EventSourceParserStream2\n} from \"eventsource-parser/stream\";\nexport {\n DEFAULT_MAX_DOWNLOAD_SIZE,\n DelayedPromise,\n DownloadError,\n EventSourceParserStream2 as EventSourceParserStream,\n VERSION,\n asSchema,\n combineHeaders,\n convertAsyncIteratorToReadableStream,\n convertBase64ToUint8Array,\n convertImageModelFileToDataUri,\n convertToBase64,\n convertToFormData,\n convertUint8ArrayToBase64,\n createBinaryResponseHandler,\n createEventSourceResponseHandler,\n createIdGenerator,\n createJsonErrorResponseHandler,\n createJsonResponseHandler,\n createProviderToolFactory,\n createProviderToolFactoryWithOutputSchema,\n createStatusCodeErrorResponseHandler,\n createToolNameMapping,\n delay,\n downloadBlob,\n dynamicTool,\n executeTool,\n extractResponseHeaders,\n generateId,\n getErrorMessage,\n getFromApi,\n getRuntimeEnvironmentUserAgent,\n injectJsonInstructionIntoMessages,\n isAbortError,\n isNonNullable,\n isParsableJson,\n isUrlSupported,\n jsonSchema,\n lazySchema,\n loadApiKey,\n loadOptionalSetting,\n loadSetting,\n mediaTypeToExtension,\n normalizeHeaders,\n parseJSON,\n parseJsonEventStream,\n parseProviderOptions,\n postFormDataToApi,\n postJsonToApi,\n postToApi,\n readResponseWithSizeLimit,\n removeUndefinedEntries,\n resolve,\n safeParseJSON,\n safeValidateTypes,\n stripFileExtension,\n tool,\n validateDownloadUrl,\n validateTypes,\n withUserAgentSuffix,\n withoutTrailingSlash,\n zodSchema\n};\n//# sourceMappingURL=index.mjs.map","var __defProp = Object.defineProperty;\nvar __export = (target, all) => {\n for (var name21 in all)\n __defProp(target, name21, { get: all[name21], enumerable: true });\n};\n\n// src/index.ts\nimport { createGateway, gateway as gateway2 } from \"@ai-sdk/gateway\";\nimport {\n asSchema as asSchema5,\n createIdGenerator as createIdGenerator5,\n dynamicTool,\n generateId,\n jsonSchema,\n parseJsonEventStream as parseJsonEventStream3,\n tool,\n zodSchema as zodSchema3\n} from \"@ai-sdk/provider-utils\";\n\n// src/generate-text/generate-text.ts\nimport {\n createIdGenerator,\n getErrorMessage as getErrorMessage5,\n withUserAgentSuffix as withUserAgentSuffix2\n} from \"@ai-sdk/provider-utils\";\n\n// src/error/index.ts\nimport {\n AISDKError as AISDKError21,\n APICallError,\n EmptyResponseBodyError,\n InvalidPromptError,\n InvalidResponseDataError,\n JSONParseError,\n LoadAPIKeyError,\n LoadSettingError,\n NoContentGeneratedError,\n NoSuchModelError,\n TooManyEmbeddingValuesForCallError,\n TypeValidationError,\n UnsupportedFunctionalityError\n} from \"@ai-sdk/provider\";\n\n// src/error/invalid-argument-error.ts\nimport { AISDKError } from \"@ai-sdk/provider\";\nvar name = \"AI_InvalidArgumentError\";\nvar marker = `vercel.ai.error.${name}`;\nvar symbol = Symbol.for(marker);\nvar _a;\nvar InvalidArgumentError = class extends AISDKError {\n constructor({\n parameter,\n value,\n message\n }) {\n super({\n name,\n message: `Invalid argument for parameter ${parameter}: ${message}`\n });\n this[_a] = true;\n this.parameter = parameter;\n this.value = value;\n }\n static isInstance(error) {\n return AISDKError.hasMarker(error, marker);\n }\n};\n_a = symbol;\n\n// src/error/invalid-stream-part-error.ts\nimport { AISDKError as AISDKError2 } from \"@ai-sdk/provider\";\nvar name2 = \"AI_InvalidStreamPartError\";\nvar marker2 = `vercel.ai.error.${name2}`;\nvar symbol2 = Symbol.for(marker2);\nvar _a2;\nvar InvalidStreamPartError = class extends AISDKError2 {\n constructor({\n chunk,\n message\n }) {\n super({ name: name2, message });\n this[_a2] = true;\n this.chunk = chunk;\n }\n static isInstance(error) {\n return AISDKError2.hasMarker(error, marker2);\n }\n};\n_a2 = symbol2;\n\n// src/error/invalid-tool-approval-error.ts\nimport { AISDKError as AISDKError3 } from \"@ai-sdk/provider\";\nvar name3 = \"AI_InvalidToolApprovalError\";\nvar marker3 = `vercel.ai.error.${name3}`;\nvar symbol3 = Symbol.for(marker3);\nvar _a3;\nvar InvalidToolApprovalError = class extends AISDKError3 {\n constructor({ approvalId }) {\n super({\n name: name3,\n message: `Tool approval response references unknown approvalId: \"${approvalId}\". No matching tool-approval-request found in message history.`\n });\n this[_a3] = true;\n this.approvalId = approvalId;\n }\n static isInstance(error) {\n return AISDKError3.hasMarker(error, marker3);\n }\n};\n_a3 = symbol3;\n\n// src/error/invalid-tool-input-error.ts\nimport { AISDKError as AISDKError4, getErrorMessage } from \"@ai-sdk/provider\";\nvar name4 = \"AI_InvalidToolInputError\";\nvar marker4 = `vercel.ai.error.${name4}`;\nvar symbol4 = Symbol.for(marker4);\nvar _a4;\nvar InvalidToolInputError = class extends AISDKError4 {\n constructor({\n toolInput,\n toolName,\n cause,\n message = `Invalid input for tool ${toolName}: ${getErrorMessage(cause)}`\n }) {\n super({ name: name4, message, cause });\n this[_a4] = true;\n this.toolInput = toolInput;\n this.toolName = toolName;\n }\n static isInstance(error) {\n return AISDKError4.hasMarker(error, marker4);\n }\n};\n_a4 = symbol4;\n\n// src/error/tool-call-not-found-for-approval-error.ts\nimport { AISDKError as AISDKError5 } from \"@ai-sdk/provider\";\nvar name5 = \"AI_ToolCallNotFoundForApprovalError\";\nvar marker5 = `vercel.ai.error.${name5}`;\nvar symbol5 = Symbol.for(marker5);\nvar _a5;\nvar ToolCallNotFoundForApprovalError = class extends AISDKError5 {\n constructor({\n toolCallId,\n approvalId\n }) {\n super({\n name: name5,\n message: `Tool call \"${toolCallId}\" not found for approval request \"${approvalId}\".`\n });\n this[_a5] = true;\n this.toolCallId = toolCallId;\n this.approvalId = approvalId;\n }\n static isInstance(error) {\n return AISDKError5.hasMarker(error, marker5);\n }\n};\n_a5 = symbol5;\n\n// src/error/missing-tool-result-error.ts\nimport { AISDKError as AISDKError6 } from \"@ai-sdk/provider\";\nvar name6 = \"AI_MissingToolResultsError\";\nvar marker6 = `vercel.ai.error.${name6}`;\nvar symbol6 = Symbol.for(marker6);\nvar _a6;\nvar MissingToolResultsError = class extends AISDKError6 {\n constructor({ toolCallIds }) {\n super({\n name: name6,\n message: `Tool result${toolCallIds.length > 1 ? \"s are\" : \" is\"} missing for tool call${toolCallIds.length > 1 ? \"s\" : \"\"} ${toolCallIds.join(\n \", \"\n )}.`\n });\n this[_a6] = true;\n this.toolCallIds = toolCallIds;\n }\n static isInstance(error) {\n return AISDKError6.hasMarker(error, marker6);\n }\n};\n_a6 = symbol6;\n\n// src/error/no-image-generated-error.ts\nimport { AISDKError as AISDKError7 } from \"@ai-sdk/provider\";\nvar name7 = \"AI_NoImageGeneratedError\";\nvar marker7 = `vercel.ai.error.${name7}`;\nvar symbol7 = Symbol.for(marker7);\nvar _a7;\nvar NoImageGeneratedError = class extends AISDKError7 {\n constructor({\n message = \"No image generated.\",\n cause,\n responses\n }) {\n super({ name: name7, message, cause });\n this[_a7] = true;\n this.responses = responses;\n }\n static isInstance(error) {\n return AISDKError7.hasMarker(error, marker7);\n }\n};\n_a7 = symbol7;\n\n// src/error/no-object-generated-error.ts\nimport { AISDKError as AISDKError8 } from \"@ai-sdk/provider\";\nvar name8 = \"AI_NoObjectGeneratedError\";\nvar marker8 = `vercel.ai.error.${name8}`;\nvar symbol8 = Symbol.for(marker8);\nvar _a8;\nvar NoObjectGeneratedError = class extends AISDKError8 {\n constructor({\n message = \"No object generated.\",\n cause,\n text: text2,\n response,\n usage,\n finishReason\n }) {\n super({ name: name8, message, cause });\n this[_a8] = true;\n this.text = text2;\n this.response = response;\n this.usage = usage;\n this.finishReason = finishReason;\n }\n static isInstance(error) {\n return AISDKError8.hasMarker(error, marker8);\n }\n};\n_a8 = symbol8;\n\n// src/error/no-output-generated-error.ts\nimport { AISDKError as AISDKError9 } from \"@ai-sdk/provider\";\nvar name9 = \"AI_NoOutputGeneratedError\";\nvar marker9 = `vercel.ai.error.${name9}`;\nvar symbol9 = Symbol.for(marker9);\nvar _a9;\nvar NoOutputGeneratedError = class extends AISDKError9 {\n // used in isInstance\n constructor({\n message = \"No output generated.\",\n cause\n } = {}) {\n super({ name: name9, message, cause });\n this[_a9] = true;\n }\n static isInstance(error) {\n return AISDKError9.hasMarker(error, marker9);\n }\n};\n_a9 = symbol9;\n\n// src/error/no-speech-generated-error.ts\nimport { AISDKError as AISDKError10 } from \"@ai-sdk/provider\";\nvar name10 = \"AI_NoSpeechGeneratedError\";\nvar marker10 = `vercel.ai.error.${name10}`;\nvar symbol10 = Symbol.for(marker10);\nvar _a10;\nvar NoSpeechGeneratedError = class extends AISDKError10 {\n constructor(options) {\n super({\n name: name10,\n message: \"No speech audio generated.\"\n });\n this[_a10] = true;\n this.responses = options.responses;\n }\n static isInstance(error) {\n return AISDKError10.hasMarker(error, marker10);\n }\n};\n_a10 = symbol10;\n\n// src/error/no-transcript-generated-error.ts\nimport { AISDKError as AISDKError11 } from \"@ai-sdk/provider\";\nvar name11 = \"AI_NoTranscriptGeneratedError\";\nvar marker11 = `vercel.ai.error.${name11}`;\nvar symbol11 = Symbol.for(marker11);\nvar _a11;\nvar NoTranscriptGeneratedError = class extends AISDKError11 {\n constructor(options) {\n super({\n name: name11,\n message: \"No transcript generated.\"\n });\n this[_a11] = true;\n this.responses = options.responses;\n }\n static isInstance(error) {\n return AISDKError11.hasMarker(error, marker11);\n }\n};\n_a11 = symbol11;\n\n// src/error/no-video-generated-error.ts\nimport { AISDKError as AISDKError12 } from \"@ai-sdk/provider\";\nvar name12 = \"AI_NoVideoGeneratedError\";\nvar marker12 = `vercel.ai.error.${name12}`;\nvar symbol12 = Symbol.for(marker12);\nvar _a12;\nvar NoVideoGeneratedError = class extends AISDKError12 {\n constructor({\n message = \"No video generated.\",\n cause,\n responses\n }) {\n super({ name: name12, message, cause });\n this[_a12] = true;\n this.responses = responses;\n }\n static isInstance(error) {\n return AISDKError12.hasMarker(error, marker12);\n }\n /**\n * @deprecated use `isInstance` instead\n */\n static isNoVideoGeneratedError(error) {\n return error instanceof Error && error.name === name12 && typeof error.responses !== \"undefined\" ? true : false;\n }\n /**\n * @deprecated Do not use this method. It will be removed in the next major version.\n */\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n stack: this.stack,\n cause: this.cause,\n responses: this.responses\n };\n }\n};\n_a12 = symbol12;\n\n// src/error/no-such-tool-error.ts\nimport { AISDKError as AISDKError13 } from \"@ai-sdk/provider\";\nvar name13 = \"AI_NoSuchToolError\";\nvar marker13 = `vercel.ai.error.${name13}`;\nvar symbol13 = Symbol.for(marker13);\nvar _a13;\nvar NoSuchToolError = class extends AISDKError13 {\n constructor({\n toolName,\n availableTools = void 0,\n message = `Model tried to call unavailable tool '${toolName}'. ${availableTools === void 0 ? \"No tools are available.\" : `Available tools: ${availableTools.join(\", \")}.`}`\n }) {\n super({ name: name13, message });\n this[_a13] = true;\n this.toolName = toolName;\n this.availableTools = availableTools;\n }\n static isInstance(error) {\n return AISDKError13.hasMarker(error, marker13);\n }\n};\n_a13 = symbol13;\n\n// src/error/tool-call-repair-error.ts\nimport { AISDKError as AISDKError14, getErrorMessage as getErrorMessage2 } from \"@ai-sdk/provider\";\nvar name14 = \"AI_ToolCallRepairError\";\nvar marker14 = `vercel.ai.error.${name14}`;\nvar symbol14 = Symbol.for(marker14);\nvar _a14;\nvar ToolCallRepairError = class extends AISDKError14 {\n constructor({\n cause,\n originalError,\n message = `Error repairing tool call: ${getErrorMessage2(cause)}`\n }) {\n super({ name: name14, message, cause });\n this[_a14] = true;\n this.originalError = originalError;\n }\n static isInstance(error) {\n return AISDKError14.hasMarker(error, marker14);\n }\n};\n_a14 = symbol14;\n\n// src/error/unsupported-model-version-error.ts\nimport { AISDKError as AISDKError15 } from \"@ai-sdk/provider\";\nvar UnsupportedModelVersionError = class extends AISDKError15 {\n constructor(options) {\n super({\n name: \"AI_UnsupportedModelVersionError\",\n message: `Unsupported model version ${options.version} for provider \"${options.provider}\" and model \"${options.modelId}\". AI SDK 5 only supports models that implement specification version \"v2\".`\n });\n this.version = options.version;\n this.provider = options.provider;\n this.modelId = options.modelId;\n }\n};\n\n// src/error/ui-message-stream-error.ts\nimport { AISDKError as AISDKError16 } from \"@ai-sdk/provider\";\nvar name15 = \"AI_UIMessageStreamError\";\nvar marker15 = `vercel.ai.error.${name15}`;\nvar symbol15 = Symbol.for(marker15);\nvar _a15;\nvar UIMessageStreamError = class extends AISDKError16 {\n constructor({\n chunkType,\n chunkId,\n message\n }) {\n super({ name: name15, message });\n this[_a15] = true;\n this.chunkType = chunkType;\n this.chunkId = chunkId;\n }\n static isInstance(error) {\n return AISDKError16.hasMarker(error, marker15);\n }\n};\n_a15 = symbol15;\n\n// src/prompt/invalid-data-content-error.ts\nimport { AISDKError as AISDKError17 } from \"@ai-sdk/provider\";\nvar name16 = \"AI_InvalidDataContentError\";\nvar marker16 = `vercel.ai.error.${name16}`;\nvar symbol16 = Symbol.for(marker16);\nvar _a16;\nvar InvalidDataContentError = class extends AISDKError17 {\n constructor({\n content,\n cause,\n message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`\n }) {\n super({ name: name16, message, cause });\n this[_a16] = true;\n this.content = content;\n }\n static isInstance(error) {\n return AISDKError17.hasMarker(error, marker16);\n }\n};\n_a16 = symbol16;\n\n// src/prompt/invalid-message-role-error.ts\nimport { AISDKError as AISDKError18 } from \"@ai-sdk/provider\";\nvar name17 = \"AI_InvalidMessageRoleError\";\nvar marker17 = `vercel.ai.error.${name17}`;\nvar symbol17 = Symbol.for(marker17);\nvar _a17;\nvar InvalidMessageRoleError = class extends AISDKError18 {\n constructor({\n role,\n message = `Invalid message role: '${role}'. Must be one of: \"system\", \"user\", \"assistant\", \"tool\".`\n }) {\n super({ name: name17, message });\n this[_a17] = true;\n this.role = role;\n }\n static isInstance(error) {\n return AISDKError18.hasMarker(error, marker17);\n }\n};\n_a17 = symbol17;\n\n// src/prompt/message-conversion-error.ts\nimport { AISDKError as AISDKError19 } from \"@ai-sdk/provider\";\nvar name18 = \"AI_MessageConversionError\";\nvar marker18 = `vercel.ai.error.${name18}`;\nvar symbol18 = Symbol.for(marker18);\nvar _a18;\nvar MessageConversionError = class extends AISDKError19 {\n constructor({\n originalMessage,\n message\n }) {\n super({ name: name18, message });\n this[_a18] = true;\n this.originalMessage = originalMessage;\n }\n static isInstance(error) {\n return AISDKError19.hasMarker(error, marker18);\n }\n};\n_a18 = symbol18;\n\n// src/error/index.ts\nimport { DownloadError } from \"@ai-sdk/provider-utils\";\n\n// src/util/retry-error.ts\nimport { AISDKError as AISDKError20 } from \"@ai-sdk/provider\";\nvar name19 = \"AI_RetryError\";\nvar marker19 = `vercel.ai.error.${name19}`;\nvar symbol19 = Symbol.for(marker19);\nvar _a19;\nvar RetryError = class extends AISDKError20 {\n constructor({\n message,\n reason,\n errors\n }) {\n super({ name: name19, message });\n this[_a19] = true;\n this.reason = reason;\n this.errors = errors;\n this.lastError = errors[errors.length - 1];\n }\n static isInstance(error) {\n return AISDKError20.hasMarker(error, marker19);\n }\n};\n_a19 = symbol19;\n\n// src/util/as-array.ts\nfunction asArray(value) {\n return value === void 0 ? [] : Array.isArray(value) ? value : [value];\n}\n\n// src/util/notify.ts\nasync function notify(options) {\n for (const callback of asArray(options.callbacks)) {\n if (callback == null)\n continue;\n try {\n await callback(options.event);\n } catch (_ignored) {\n }\n }\n}\n\n// src/logger/log-warnings.ts\nfunction formatWarning({\n warning,\n provider,\n model\n}) {\n const prefix = `AI SDK Warning (${provider} / ${model}):`;\n switch (warning.type) {\n case \"unsupported\": {\n let message = `${prefix} The feature \"${warning.feature}\" is not supported.`;\n if (warning.details) {\n message += ` ${warning.details}`;\n }\n return message;\n }\n case \"compatibility\": {\n let message = `${prefix} The feature \"${warning.feature}\" is used in a compatibility mode.`;\n if (warning.details) {\n message += ` ${warning.details}`;\n }\n return message;\n }\n case \"other\": {\n return `${prefix} ${warning.message}`;\n }\n default: {\n return `${prefix} ${JSON.stringify(warning, null, 2)}`;\n }\n }\n}\nvar FIRST_WARNING_INFO_MESSAGE = \"AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.\";\nvar hasLoggedBefore = false;\nvar logWarnings = (options) => {\n if (options.warnings.length === 0) {\n return;\n }\n const logger = globalThis.AI_SDK_LOG_WARNINGS;\n if (logger === false) {\n return;\n }\n if (typeof logger === \"function\") {\n logger(options);\n return;\n }\n if (!hasLoggedBefore) {\n hasLoggedBefore = true;\n console.info(FIRST_WARNING_INFO_MESSAGE);\n }\n for (const warning of options.warnings) {\n console.warn(\n formatWarning({\n warning,\n provider: options.provider,\n model: options.model\n })\n );\n }\n};\n\n// src/model/resolve-model.ts\nimport { gateway } from \"@ai-sdk/gateway\";\n\n// src/util/log-v2-compatibility-warning.ts\nfunction logV2CompatibilityWarning({\n provider,\n modelId\n}) {\n logWarnings({\n warnings: [\n {\n type: \"compatibility\",\n feature: \"specificationVersion\",\n details: `Using v2 specification compatibility mode. Some features may not be available.`\n }\n ],\n provider,\n model: modelId\n });\n}\n\n// src/model/as-embedding-model-v3.ts\nfunction asEmbeddingModelV3(model) {\n if (model.specificationVersion === \"v3\") {\n return model;\n }\n logV2CompatibilityWarning({\n provider: model.provider,\n modelId: model.modelId\n });\n return new Proxy(model, {\n get(target, prop) {\n if (prop === \"specificationVersion\")\n return \"v3\";\n return target[prop];\n }\n });\n}\n\n// src/model/as-image-model-v3.ts\nfunction asImageModelV3(model) {\n if (model.specificationVersion === \"v3\") {\n return model;\n }\n logV2CompatibilityWarning({\n provider: model.provider,\n modelId: model.modelId\n });\n return new Proxy(model, {\n get(target, prop) {\n if (prop === \"specificationVersion\")\n return \"v3\";\n return target[prop];\n }\n });\n}\n\n// src/model/as-language-model-v3.ts\nfunction asLanguageModelV3(model) {\n if (model.specificationVersion === \"v3\") {\n return model;\n }\n logV2CompatibilityWarning({\n provider: model.provider,\n modelId: model.modelId\n });\n return new Proxy(model, {\n get(target, prop) {\n switch (prop) {\n case \"specificationVersion\":\n return \"v3\";\n case \"doGenerate\":\n return async (...args) => {\n const result = await target.doGenerate(...args);\n return {\n ...result,\n finishReason: convertV2FinishReasonToV3(result.finishReason),\n usage: convertV2UsageToV3(result.usage)\n };\n };\n case \"doStream\":\n return async (...args) => {\n const result = await target.doStream(...args);\n return {\n ...result,\n stream: convertV2StreamToV3(result.stream)\n };\n };\n default:\n return target[prop];\n }\n }\n });\n}\nfunction convertV2StreamToV3(stream) {\n return stream.pipeThrough(\n new TransformStream({\n transform(chunk, controller) {\n switch (chunk.type) {\n case \"finish\":\n controller.enqueue({\n ...chunk,\n finishReason: convertV2FinishReasonToV3(chunk.finishReason),\n usage: convertV2UsageToV3(chunk.usage)\n });\n break;\n default:\n controller.enqueue(chunk);\n break;\n }\n }\n })\n );\n}\nfunction convertV2FinishReasonToV3(finishReason) {\n return {\n unified: finishReason === \"unknown\" ? \"other\" : finishReason,\n raw: void 0\n };\n}\nfunction convertV2UsageToV3(usage) {\n return {\n inputTokens: {\n total: usage.inputTokens,\n noCache: void 0,\n cacheRead: usage.cachedInputTokens,\n cacheWrite: void 0\n },\n outputTokens: {\n total: usage.outputTokens,\n text: void 0,\n reasoning: usage.reasoningTokens\n }\n };\n}\n\n// src/model/as-speech-model-v3.ts\nfunction asSpeechModelV3(model) {\n if (model.specificationVersion === \"v3\") {\n return model;\n }\n logV2CompatibilityWarning({\n provider: model.provider,\n modelId: model.modelId\n });\n return new Proxy(model, {\n get(target, prop) {\n if (prop === \"specificationVersion\")\n return \"v3\";\n return target[prop];\n }\n });\n}\n\n// src/model/as-transcription-model-v3.ts\nfunction asTranscriptionModelV3(model) {\n if (model.specificationVersion === \"v3\") {\n return model;\n }\n logV2CompatibilityWarning({\n provider: model.provider,\n modelId: model.modelId\n });\n return new Proxy(model, {\n get(target, prop) {\n if (prop === \"specificationVersion\")\n return \"v3\";\n return target[prop];\n }\n });\n}\n\n// src/model/resolve-model.ts\nfunction resolveLanguageModel(model) {\n if (typeof model !== \"string\") {\n if (model.specificationVersion !== \"v3\" && model.specificationVersion !== \"v2\") {\n const unsupportedModel = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId\n });\n }\n return asLanguageModelV3(model);\n }\n return getGlobalProvider().languageModel(model);\n}\nfunction resolveEmbeddingModel(model) {\n if (typeof model !== \"string\") {\n if (model.specificationVersion !== \"v3\" && model.specificationVersion !== \"v2\") {\n const unsupportedModel = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId\n });\n }\n return asEmbeddingModelV3(model);\n }\n return getGlobalProvider().embeddingModel(model);\n}\nfunction resolveTranscriptionModel(model) {\n var _a21, _b;\n if (typeof model !== \"string\") {\n if (model.specificationVersion !== \"v3\" && model.specificationVersion !== \"v2\") {\n const unsupportedModel = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId\n });\n }\n return asTranscriptionModelV3(model);\n }\n return (_b = (_a21 = getGlobalProvider()).transcriptionModel) == null ? void 0 : _b.call(_a21, model);\n}\nfunction resolveSpeechModel(model) {\n var _a21, _b;\n if (typeof model !== \"string\") {\n if (model.specificationVersion !== \"v3\" && model.specificationVersion !== \"v2\") {\n const unsupportedModel = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId\n });\n }\n return asSpeechModelV3(model);\n }\n return (_b = (_a21 = getGlobalProvider()).speechModel) == null ? void 0 : _b.call(_a21, model);\n}\nfunction resolveImageModel(model) {\n if (typeof model !== \"string\") {\n if (model.specificationVersion !== \"v3\" && model.specificationVersion !== \"v2\") {\n const unsupportedModel = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId\n });\n }\n return asImageModelV3(model);\n }\n return getGlobalProvider().imageModel(model);\n}\nfunction resolveVideoModel(model) {\n if (typeof model === \"string\") {\n const provider = getGlobalProvider();\n const videoModel = provider.videoModel;\n if (!videoModel) {\n throw new Error(\n 'The default provider does not support video models. Please use a Experimental_VideoModelV3 object from a provider (e.g., vertex.video(\"model-id\")).'\n );\n }\n return videoModel(model);\n }\n if (model.specificationVersion !== \"v3\") {\n const unsupportedModel = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId\n });\n }\n return model;\n}\nfunction getGlobalProvider() {\n var _a21;\n return (_a21 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a21 : gateway;\n}\n\n// src/prompt/call-settings.ts\nfunction getTotalTimeoutMs(timeout) {\n if (timeout == null) {\n return void 0;\n }\n if (typeof timeout === \"number\") {\n return timeout;\n }\n return timeout.totalMs;\n}\nfunction getStepTimeoutMs(timeout) {\n if (timeout == null || typeof timeout === \"number\") {\n return void 0;\n }\n return timeout.stepMs;\n}\nfunction getChunkTimeoutMs(timeout) {\n if (timeout == null || typeof timeout === \"number\") {\n return void 0;\n }\n return timeout.chunkMs;\n}\n\n// src/prompt/convert-to-language-model-prompt.ts\nimport {\n isUrlSupported\n} from \"@ai-sdk/provider-utils\";\n\n// src/util/detect-media-type.ts\nimport { convertBase64ToUint8Array } from \"@ai-sdk/provider-utils\";\nvar imageMediaTypeSignatures = [\n {\n mediaType: \"image/gif\",\n bytesPrefix: [71, 73, 70]\n // GIF\n },\n {\n mediaType: \"image/png\",\n bytesPrefix: [137, 80, 78, 71]\n // PNG\n },\n {\n mediaType: \"image/jpeg\",\n bytesPrefix: [255, 216]\n // JPEG\n },\n {\n mediaType: \"image/webp\",\n bytesPrefix: [\n 82,\n 73,\n 70,\n 70,\n // \"RIFF\"\n null,\n null,\n null,\n null,\n // file size (variable)\n 87,\n 69,\n 66,\n 80\n // \"WEBP\"\n ]\n },\n {\n mediaType: \"image/bmp\",\n bytesPrefix: [66, 77]\n },\n {\n mediaType: \"image/tiff\",\n bytesPrefix: [73, 73, 42, 0]\n },\n {\n mediaType: \"image/tiff\",\n bytesPrefix: [77, 77, 0, 42]\n },\n {\n mediaType: \"image/avif\",\n bytesPrefix: [\n 0,\n 0,\n 0,\n 32,\n 102,\n 116,\n 121,\n 112,\n 97,\n 118,\n 105,\n 102\n ]\n },\n {\n mediaType: \"image/heic\",\n bytesPrefix: [\n 0,\n 0,\n 0,\n 32,\n 102,\n 116,\n 121,\n 112,\n 104,\n 101,\n 105,\n 99\n ]\n }\n];\nvar audioMediaTypeSignatures = [\n {\n mediaType: \"audio/mpeg\",\n bytesPrefix: [255, 251]\n },\n {\n mediaType: \"audio/mpeg\",\n bytesPrefix: [255, 250]\n },\n {\n mediaType: \"audio/mpeg\",\n bytesPrefix: [255, 243]\n },\n {\n mediaType: \"audio/mpeg\",\n bytesPrefix: [255, 242]\n },\n {\n mediaType: \"audio/mpeg\",\n bytesPrefix: [255, 227]\n },\n {\n mediaType: \"audio/mpeg\",\n bytesPrefix: [255, 226]\n },\n {\n mediaType: \"audio/wav\",\n bytesPrefix: [\n 82,\n // R\n 73,\n // I\n 70,\n // F\n 70,\n // F\n null,\n null,\n null,\n null,\n 87,\n // W\n 65,\n // A\n 86,\n // V\n 69\n // E\n ]\n },\n {\n mediaType: \"audio/ogg\",\n bytesPrefix: [79, 103, 103, 83]\n },\n {\n mediaType: \"audio/flac\",\n bytesPrefix: [102, 76, 97, 67]\n },\n {\n mediaType: \"audio/aac\",\n bytesPrefix: [64, 21, 0, 0]\n },\n {\n mediaType: \"audio/mp4\",\n bytesPrefix: [102, 116, 121, 112]\n },\n {\n mediaType: \"audio/webm\",\n bytesPrefix: [26, 69, 223, 163]\n }\n];\nvar videoMediaTypeSignatures = [\n {\n mediaType: \"video/mp4\",\n bytesPrefix: [\n 0,\n 0,\n 0,\n null,\n 102,\n 116,\n 121,\n 112\n // ftyp\n ]\n },\n {\n mediaType: \"video/webm\",\n bytesPrefix: [26, 69, 223, 163]\n // EBML\n },\n {\n mediaType: \"video/quicktime\",\n bytesPrefix: [\n 0,\n 0,\n 0,\n 20,\n 102,\n 116,\n 121,\n 112,\n 113,\n 116\n // ftypqt\n ]\n },\n {\n mediaType: \"video/x-msvideo\",\n bytesPrefix: [82, 73, 70, 70]\n // RIFF (AVI)\n }\n];\nvar stripID3 = (data) => {\n const bytes = typeof data === \"string\" ? convertBase64ToUint8Array(data) : data;\n const id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;\n return bytes.slice(id3Size + 10);\n};\nfunction stripID3TagsIfPresent(data) {\n const hasId3 = typeof data === \"string\" && data.startsWith(\"SUQz\") || typeof data !== \"string\" && data.length > 10 && data[0] === 73 && // 'I'\n data[1] === 68 && // 'D'\n data[2] === 51;\n return hasId3 ? stripID3(data) : data;\n}\nfunction detectMediaType({\n data,\n signatures\n}) {\n const processedData = stripID3TagsIfPresent(data);\n const bytes = typeof processedData === \"string\" ? convertBase64ToUint8Array(\n processedData.substring(0, Math.min(processedData.length, 24))\n ) : processedData;\n for (const signature of signatures) {\n if (bytes.length >= signature.bytesPrefix.length && signature.bytesPrefix.every(\n (byte, index) => byte === null || bytes[index] === byte\n )) {\n return signature.mediaType;\n }\n }\n return void 0;\n}\n\n// src/util/download/download.ts\nimport {\n DownloadError as DownloadError2,\n readResponseWithSizeLimit,\n DEFAULT_MAX_DOWNLOAD_SIZE,\n validateDownloadUrl\n} from \"@ai-sdk/provider-utils\";\nimport {\n withUserAgentSuffix,\n getRuntimeEnvironmentUserAgent\n} from \"@ai-sdk/provider-utils\";\n\n// src/version.ts\nvar VERSION = true ? \"6.0.116\" : \"0.0.0-test\";\n\n// src/util/download/download.ts\nvar download = async ({\n url,\n maxBytes,\n abortSignal\n}) => {\n var _a21;\n const urlText = url.toString();\n validateDownloadUrl(urlText);\n try {\n const response = await fetch(urlText, {\n headers: withUserAgentSuffix(\n {},\n `ai-sdk/${VERSION}`,\n getRuntimeEnvironmentUserAgent()\n ),\n signal: abortSignal\n });\n if (!response.ok) {\n throw new DownloadError2({\n url: urlText,\n statusCode: response.status,\n statusText: response.statusText\n });\n }\n const data = await readResponseWithSizeLimit({\n response,\n url: urlText,\n maxBytes: maxBytes != null ? maxBytes : DEFAULT_MAX_DOWNLOAD_SIZE\n });\n return {\n data,\n mediaType: (_a21 = response.headers.get(\"content-type\")) != null ? _a21 : void 0\n };\n } catch (error) {\n if (DownloadError2.isInstance(error)) {\n throw error;\n }\n throw new DownloadError2({ url: urlText, cause: error });\n }\n};\n\n// src/util/download/download-function.ts\nvar createDefaultDownloadFunction = (download2 = download) => (requestedDownloads) => Promise.all(\n requestedDownloads.map(\n async (requestedDownload) => requestedDownload.isUrlSupportedByModel ? null : download2(requestedDownload)\n )\n);\n\n// src/prompt/data-content.ts\nimport { AISDKError as AISDKError22 } from \"@ai-sdk/provider\";\nimport {\n convertBase64ToUint8Array as convertBase64ToUint8Array2,\n convertUint8ArrayToBase64\n} from \"@ai-sdk/provider-utils\";\nimport { z } from \"zod/v4\";\n\n// src/prompt/split-data-url.ts\nfunction splitDataUrl(dataUrl) {\n try {\n const [header, base64Content] = dataUrl.split(\",\");\n return {\n mediaType: header.split(\";\")[0].split(\":\")[1],\n base64Content\n };\n } catch (error) {\n return {\n mediaType: void 0,\n base64Content: void 0\n };\n }\n}\n\n// src/prompt/data-content.ts\nvar dataContentSchema = z.union([\n z.string(),\n z.instanceof(Uint8Array),\n z.instanceof(ArrayBuffer),\n z.custom(\n // Buffer might not be available in some environments such as CloudFlare:\n (value) => {\n var _a21, _b;\n return (_b = (_a21 = globalThis.Buffer) == null ? void 0 : _a21.isBuffer(value)) != null ? _b : false;\n },\n { message: \"Must be a Buffer\" }\n )\n]);\nfunction convertToLanguageModelV3DataContent(content) {\n if (content instanceof Uint8Array) {\n return { data: content, mediaType: void 0 };\n }\n if (content instanceof ArrayBuffer) {\n return { data: new Uint8Array(content), mediaType: void 0 };\n }\n if (typeof content === \"string\") {\n try {\n content = new URL(content);\n } catch (error) {\n }\n }\n if (content instanceof URL && content.protocol === \"data:\") {\n const { mediaType: dataUrlMediaType, base64Content } = splitDataUrl(\n content.toString()\n );\n if (dataUrlMediaType == null || base64Content == null) {\n throw new AISDKError22({\n name: \"InvalidDataContentError\",\n message: `Invalid data URL format in content ${content.toString()}`\n });\n }\n return { data: base64Content, mediaType: dataUrlMediaType };\n }\n return { data: content, mediaType: void 0 };\n}\nfunction convertDataContentToBase64String(content) {\n if (typeof content === \"string\") {\n return content;\n }\n if (content instanceof ArrayBuffer) {\n return convertUint8ArrayToBase64(new Uint8Array(content));\n }\n return convertUint8ArrayToBase64(content);\n}\nfunction convertDataContentToUint8Array(content) {\n if (content instanceof Uint8Array) {\n return content;\n }\n if (typeof content === \"string\") {\n try {\n return convertBase64ToUint8Array2(content);\n } catch (error) {\n throw new InvalidDataContentError({\n message: \"Invalid data content. Content string is not a base64-encoded media.\",\n content,\n cause: error\n });\n }\n }\n if (content instanceof ArrayBuffer) {\n return new Uint8Array(content);\n }\n throw new InvalidDataContentError({ content });\n}\n\n// src/prompt/convert-to-language-model-prompt.ts\nasync function convertToLanguageModelPrompt({\n prompt,\n supportedUrls,\n download: download2 = createDefaultDownloadFunction()\n}) {\n const downloadedAssets = await downloadAssets(\n prompt.messages,\n download2,\n supportedUrls\n );\n const approvalIdToToolCallId = /* @__PURE__ */ new Map();\n for (const message of prompt.messages) {\n if (message.role === \"assistant\" && Array.isArray(message.content)) {\n for (const part of message.content) {\n if (part.type === \"tool-approval-request\" && \"approvalId\" in part && \"toolCallId\" in part) {\n approvalIdToToolCallId.set(\n part.approvalId,\n part.toolCallId\n );\n }\n }\n }\n }\n const approvedToolCallIds = /* @__PURE__ */ new Set();\n for (const message of prompt.messages) {\n if (message.role === \"tool\") {\n for (const part of message.content) {\n if (part.type === \"tool-approval-response\") {\n const toolCallId = approvalIdToToolCallId.get(part.approvalId);\n if (toolCallId) {\n approvedToolCallIds.add(toolCallId);\n }\n }\n }\n }\n }\n const messages = [\n ...prompt.system != null ? typeof prompt.system === \"string\" ? [{ role: \"system\", content: prompt.system }] : asArray(prompt.system).map((message) => ({\n role: \"system\",\n content: message.content,\n providerOptions: message.providerOptions\n })) : [],\n ...prompt.messages.map(\n (message) => convertToLanguageModelMessage({ message, downloadedAssets })\n )\n ];\n const combinedMessages = [];\n for (const message of messages) {\n if (message.role !== \"tool\") {\n combinedMessages.push(message);\n continue;\n }\n const lastCombinedMessage = combinedMessages.at(-1);\n if ((lastCombinedMessage == null ? void 0 : lastCombinedMessage.role) === \"tool\") {\n lastCombinedMessage.content.push(...message.content);\n } else {\n combinedMessages.push(message);\n }\n }\n const toolCallIds = /* @__PURE__ */ new Set();\n for (const message of combinedMessages) {\n switch (message.role) {\n case \"assistant\": {\n for (const content of message.content) {\n if (content.type === \"tool-call\" && !content.providerExecuted) {\n toolCallIds.add(content.toolCallId);\n }\n }\n break;\n }\n case \"tool\": {\n for (const content of message.content) {\n if (content.type === \"tool-result\") {\n toolCallIds.delete(content.toolCallId);\n }\n }\n break;\n }\n case \"user\":\n case \"system\":\n for (const id of approvedToolCallIds) {\n toolCallIds.delete(id);\n }\n if (toolCallIds.size > 0) {\n throw new MissingToolResultsError({\n toolCallIds: Array.from(toolCallIds)\n });\n }\n break;\n }\n }\n for (const id of approvedToolCallIds) {\n toolCallIds.delete(id);\n }\n if (toolCallIds.size > 0) {\n throw new MissingToolResultsError({ toolCallIds: Array.from(toolCallIds) });\n }\n return combinedMessages.filter(\n // Filter out empty tool messages (e.g. if they only contained\n // tool-approval-response parts that were removed).\n // This prevents sending invalid empty messages to the provider.\n // Note: provider-executed tool-approval-response parts are preserved.\n (message) => message.role !== \"tool\" || message.content.length > 0\n );\n}\nfunction convertToLanguageModelMessage({\n message,\n downloadedAssets\n}) {\n const role = message.role;\n switch (role) {\n case \"system\": {\n return {\n role: \"system\",\n content: message.content,\n providerOptions: message.providerOptions\n };\n }\n case \"user\": {\n if (typeof message.content === \"string\") {\n return {\n role: \"user\",\n content: [{ type: \"text\", text: message.content }],\n providerOptions: message.providerOptions\n };\n }\n return {\n role: \"user\",\n content: message.content.map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== \"text\" || part.text !== \"\"),\n providerOptions: message.providerOptions\n };\n }\n case \"assistant\": {\n if (typeof message.content === \"string\") {\n return {\n role: \"assistant\",\n content: [{ type: \"text\", text: message.content }],\n providerOptions: message.providerOptions\n };\n }\n return {\n role: \"assistant\",\n content: message.content.filter(\n // remove empty text parts (no text, and no provider options):\n (part) => part.type !== \"text\" || part.text !== \"\" || part.providerOptions != null\n ).filter(\n (part) => part.type !== \"tool-approval-request\"\n ).map((part) => {\n const providerOptions = part.providerOptions;\n switch (part.type) {\n case \"file\": {\n const { data, mediaType } = convertToLanguageModelV3DataContent(\n part.data\n );\n return {\n type: \"file\",\n data,\n filename: part.filename,\n mediaType: mediaType != null ? mediaType : part.mediaType,\n providerOptions\n };\n }\n case \"reasoning\": {\n return {\n type: \"reasoning\",\n text: part.text,\n providerOptions\n };\n }\n case \"text\": {\n return {\n type: \"text\",\n text: part.text,\n providerOptions\n };\n }\n case \"tool-call\": {\n return {\n type: \"tool-call\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n providerExecuted: part.providerExecuted,\n providerOptions\n };\n }\n case \"tool-result\": {\n return {\n type: \"tool-result\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output: mapToolResultOutput(part.output),\n providerOptions\n };\n }\n }\n }),\n providerOptions: message.providerOptions\n };\n }\n case \"tool\": {\n return {\n role: \"tool\",\n content: message.content.filter(\n // Only include tool-approval-response for provider-executed tools\n (part) => part.type !== \"tool-approval-response\" || part.providerExecuted\n ).map((part) => {\n switch (part.type) {\n case \"tool-result\": {\n return {\n type: \"tool-result\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output: mapToolResultOutput(part.output),\n providerOptions: part.providerOptions\n };\n }\n case \"tool-approval-response\": {\n return {\n type: \"tool-approval-response\",\n approvalId: part.approvalId,\n approved: part.approved,\n reason: part.reason\n };\n }\n }\n }),\n providerOptions: message.providerOptions\n };\n }\n default: {\n const _exhaustiveCheck = role;\n throw new InvalidMessageRoleError({ role: _exhaustiveCheck });\n }\n }\n}\nasync function downloadAssets(messages, download2, supportedUrls) {\n const plannedDownloads = messages.filter((message) => message.role === \"user\").map((message) => message.content).filter(\n (content) => Array.isArray(content)\n ).flat().filter(\n (part) => part.type === \"image\" || part.type === \"file\"\n ).map((part) => {\n var _a21;\n const mediaType = (_a21 = part.mediaType) != null ? _a21 : part.type === \"image\" ? \"image/*\" : void 0;\n let data = part.type === \"image\" ? part.image : part.data;\n if (typeof data === \"string\") {\n try {\n data = new URL(data);\n } catch (ignored) {\n }\n }\n return { mediaType, data };\n }).filter(\n (part) => part.data instanceof URL\n ).map((part) => ({\n url: part.data,\n isUrlSupportedByModel: part.mediaType != null && isUrlSupported({\n url: part.data.toString(),\n mediaType: part.mediaType,\n supportedUrls\n })\n }));\n const downloadedFiles = await download2(plannedDownloads);\n return Object.fromEntries(\n downloadedFiles.map(\n (file, index) => file == null ? null : [\n plannedDownloads[index].url.toString(),\n { data: file.data, mediaType: file.mediaType }\n ]\n ).filter((file) => file != null)\n );\n}\nfunction convertPartToLanguageModelPart(part, downloadedAssets) {\n var _a21;\n if (part.type === \"text\") {\n return {\n type: \"text\",\n text: part.text,\n providerOptions: part.providerOptions\n };\n }\n let originalData;\n const type = part.type;\n switch (type) {\n case \"image\":\n originalData = part.image;\n break;\n case \"file\":\n originalData = part.data;\n break;\n default:\n throw new Error(`Unsupported part type: ${type}`);\n }\n const { data: convertedData, mediaType: convertedMediaType } = convertToLanguageModelV3DataContent(originalData);\n let mediaType = convertedMediaType != null ? convertedMediaType : part.mediaType;\n let data = convertedData;\n if (data instanceof URL) {\n const downloadedFile = downloadedAssets[data.toString()];\n if (downloadedFile) {\n data = downloadedFile.data;\n mediaType != null ? mediaType : mediaType = downloadedFile.mediaType;\n }\n }\n switch (type) {\n case \"image\": {\n if (data instanceof Uint8Array || typeof data === \"string\") {\n mediaType = (_a21 = detectMediaType({ data, signatures: imageMediaTypeSignatures })) != null ? _a21 : mediaType;\n }\n return {\n type: \"file\",\n mediaType: mediaType != null ? mediaType : \"image/*\",\n // any image\n filename: void 0,\n data,\n providerOptions: part.providerOptions\n };\n }\n case \"file\": {\n if (mediaType == null) {\n throw new Error(`Media type is missing for file part`);\n }\n return {\n type: \"file\",\n mediaType,\n filename: part.filename,\n data,\n providerOptions: part.providerOptions\n };\n }\n }\n}\nfunction mapToolResultOutput(output) {\n if (output.type !== \"content\") {\n return output;\n }\n return {\n type: \"content\",\n value: output.value.map((item) => {\n if (item.type !== \"media\") {\n return item;\n }\n if (item.mediaType.startsWith(\"image/\")) {\n return {\n type: \"image-data\",\n data: item.data,\n mediaType: item.mediaType\n };\n }\n return {\n type: \"file-data\",\n data: item.data,\n mediaType: item.mediaType\n };\n })\n };\n}\n\n// src/prompt/create-tool-model-output.ts\nimport { getErrorMessage as getErrorMessage3 } from \"@ai-sdk/provider\";\nasync function createToolModelOutput({\n toolCallId,\n input,\n output,\n tool: tool2,\n errorMode\n}) {\n if (errorMode === \"text\") {\n return { type: \"error-text\", value: getErrorMessage3(output) };\n } else if (errorMode === \"json\") {\n return { type: \"error-json\", value: toJSONValue(output) };\n }\n if (tool2 == null ? void 0 : tool2.toModelOutput) {\n return await tool2.toModelOutput({ toolCallId, input, output });\n }\n return typeof output === \"string\" ? { type: \"text\", value: output } : { type: \"json\", value: toJSONValue(output) };\n}\nfunction toJSONValue(value) {\n return value === void 0 ? null : value;\n}\n\n// src/prompt/prepare-call-settings.ts\nfunction prepareCallSettings({\n maxOutputTokens,\n temperature,\n topP,\n topK,\n presencePenalty,\n frequencyPenalty,\n seed,\n stopSequences\n}) {\n if (maxOutputTokens != null) {\n if (!Number.isInteger(maxOutputTokens)) {\n throw new InvalidArgumentError({\n parameter: \"maxOutputTokens\",\n value: maxOutputTokens,\n message: \"maxOutputTokens must be an integer\"\n });\n }\n if (maxOutputTokens < 1) {\n throw new InvalidArgumentError({\n parameter: \"maxOutputTokens\",\n value: maxOutputTokens,\n message: \"maxOutputTokens must be >= 1\"\n });\n }\n }\n if (temperature != null) {\n if (typeof temperature !== \"number\") {\n throw new InvalidArgumentError({\n parameter: \"temperature\",\n value: temperature,\n message: \"temperature must be a number\"\n });\n }\n }\n if (topP != null) {\n if (typeof topP !== \"number\") {\n throw new InvalidArgumentError({\n parameter: \"topP\",\n value: topP,\n message: \"topP must be a number\"\n });\n }\n }\n if (topK != null) {\n if (typeof topK !== \"number\") {\n throw new InvalidArgumentError({\n parameter: \"topK\",\n value: topK,\n message: \"topK must be a number\"\n });\n }\n }\n if (presencePenalty != null) {\n if (typeof presencePenalty !== \"number\") {\n throw new InvalidArgumentError({\n parameter: \"presencePenalty\",\n value: presencePenalty,\n message: \"presencePenalty must be a number\"\n });\n }\n }\n if (frequencyPenalty != null) {\n if (typeof frequencyPenalty !== \"number\") {\n throw new InvalidArgumentError({\n parameter: \"frequencyPenalty\",\n value: frequencyPenalty,\n message: \"frequencyPenalty must be a number\"\n });\n }\n }\n if (seed != null) {\n if (!Number.isInteger(seed)) {\n throw new InvalidArgumentError({\n parameter: \"seed\",\n value: seed,\n message: \"seed must be an integer\"\n });\n }\n }\n return {\n maxOutputTokens,\n temperature,\n topP,\n topK,\n presencePenalty,\n frequencyPenalty,\n stopSequences,\n seed\n };\n}\n\n// src/prompt/prepare-tools-and-tool-choice.ts\nimport { asSchema } from \"@ai-sdk/provider-utils\";\n\n// src/util/is-non-empty-object.ts\nfunction isNonEmptyObject(object2) {\n return object2 != null && Object.keys(object2).length > 0;\n}\n\n// src/prompt/prepare-tools-and-tool-choice.ts\nasync function prepareToolsAndToolChoice({\n tools,\n toolChoice,\n activeTools\n}) {\n if (!isNonEmptyObject(tools)) {\n return {\n tools: void 0,\n toolChoice: void 0\n };\n }\n const filteredTools = activeTools != null ? Object.entries(tools).filter(\n ([name21]) => activeTools.includes(name21)\n ) : Object.entries(tools);\n const languageModelTools = [];\n for (const [name21, tool2] of filteredTools) {\n const toolType = tool2.type;\n switch (toolType) {\n case void 0:\n case \"dynamic\":\n case \"function\":\n languageModelTools.push({\n type: \"function\",\n name: name21,\n description: tool2.description,\n inputSchema: await asSchema(tool2.inputSchema).jsonSchema,\n ...tool2.inputExamples != null ? { inputExamples: tool2.inputExamples } : {},\n providerOptions: tool2.providerOptions,\n ...tool2.strict != null ? { strict: tool2.strict } : {}\n });\n break;\n case \"provider\":\n languageModelTools.push({\n type: \"provider\",\n name: name21,\n id: tool2.id,\n args: tool2.args\n });\n break;\n default: {\n const exhaustiveCheck = toolType;\n throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);\n }\n }\n }\n return {\n tools: languageModelTools,\n toolChoice: toolChoice == null ? { type: \"auto\" } : typeof toolChoice === \"string\" ? { type: toolChoice } : { type: \"tool\", toolName: toolChoice.toolName }\n };\n}\n\n// src/prompt/standardize-prompt.ts\nimport { InvalidPromptError as InvalidPromptError2 } from \"@ai-sdk/provider\";\nimport {\n safeValidateTypes\n} from \"@ai-sdk/provider-utils\";\nimport { z as z6 } from \"zod/v4\";\n\n// src/prompt/message.ts\nimport { z as z5 } from \"zod/v4\";\n\n// src/types/provider-metadata.ts\nimport { z as z3 } from \"zod/v4\";\n\n// src/types/json-value.ts\nimport { z as z2 } from \"zod/v4\";\nvar jsonValueSchema = z2.lazy(\n () => z2.union([\n z2.null(),\n z2.string(),\n z2.number(),\n z2.boolean(),\n z2.record(z2.string(), jsonValueSchema.optional()),\n z2.array(jsonValueSchema)\n ])\n);\n\n// src/types/provider-metadata.ts\nvar providerMetadataSchema = z3.record(\n z3.string(),\n z3.record(z3.string(), jsonValueSchema.optional())\n);\n\n// src/prompt/content-part.ts\nimport { z as z4 } from \"zod/v4\";\nvar textPartSchema = z4.object({\n type: z4.literal(\"text\"),\n text: z4.string(),\n providerOptions: providerMetadataSchema.optional()\n});\nvar imagePartSchema = z4.object({\n type: z4.literal(\"image\"),\n image: z4.union([dataContentSchema, z4.instanceof(URL)]),\n mediaType: z4.string().optional(),\n providerOptions: providerMetadataSchema.optional()\n});\nvar filePartSchema = z4.object({\n type: z4.literal(\"file\"),\n data: z4.union([dataContentSchema, z4.instanceof(URL)]),\n filename: z4.string().optional(),\n mediaType: z4.string(),\n providerOptions: providerMetadataSchema.optional()\n});\nvar reasoningPartSchema = z4.object({\n type: z4.literal(\"reasoning\"),\n text: z4.string(),\n providerOptions: providerMetadataSchema.optional()\n});\nvar toolCallPartSchema = z4.object({\n type: z4.literal(\"tool-call\"),\n toolCallId: z4.string(),\n toolName: z4.string(),\n input: z4.unknown(),\n providerOptions: providerMetadataSchema.optional(),\n providerExecuted: z4.boolean().optional()\n});\nvar outputSchema = z4.discriminatedUnion(\n \"type\",\n [\n z4.object({\n type: z4.literal(\"text\"),\n value: z4.string(),\n providerOptions: providerMetadataSchema.optional()\n }),\n z4.object({\n type: z4.literal(\"json\"),\n value: jsonValueSchema,\n providerOptions: providerMetadataSchema.optional()\n }),\n z4.object({\n type: z4.literal(\"execution-denied\"),\n reason: z4.string().optional(),\n providerOptions: providerMetadataSchema.optional()\n }),\n z4.object({\n type: z4.literal(\"error-text\"),\n value: z4.string(),\n providerOptions: providerMetadataSchema.optional()\n }),\n z4.object({\n type: z4.literal(\"error-json\"),\n value: jsonValueSchema,\n providerOptions: providerMetadataSchema.optional()\n }),\n z4.object({\n type: z4.literal(\"content\"),\n value: z4.array(\n z4.union([\n z4.object({\n type: z4.literal(\"text\"),\n text: z4.string(),\n providerOptions: providerMetadataSchema.optional()\n }),\n z4.object({\n type: z4.literal(\"media\"),\n data: z4.string(),\n mediaType: z4.string()\n }),\n z4.object({\n type: z4.literal(\"file-data\"),\n data: z4.string(),\n mediaType: z4.string(),\n filename: z4.string().optional(),\n providerOptions: providerMetadataSchema.optional()\n }),\n z4.object({\n type: z4.literal(\"file-url\"),\n url: z4.string(),\n providerOptions: providerMetadataSchema.optional()\n }),\n z4.object({\n type: z4.literal(\"file-id\"),\n fileId: z4.union([z4.string(), z4.record(z4.string(), z4.string())]),\n providerOptions: providerMetadataSchema.optional()\n }),\n z4.object({\n type: z4.literal(\"image-data\"),\n data: z4.string(),\n mediaType: z4.string(),\n providerOptions: providerMetadataSchema.optional()\n }),\n z4.object({\n type: z4.literal(\"image-url\"),\n url: z4.string(),\n providerOptions: providerMetadataSchema.optional()\n }),\n z4.object({\n type: z4.literal(\"image-file-id\"),\n fileId: z4.union([z4.string(), z4.record(z4.string(), z4.string())]),\n providerOptions: providerMetadataSchema.optional()\n }),\n z4.object({\n type: z4.literal(\"custom\"),\n providerOptions: providerMetadataSchema.optional()\n })\n ])\n )\n })\n ]\n);\nvar toolResultPartSchema = z4.object({\n type: z4.literal(\"tool-result\"),\n toolCallId: z4.string(),\n toolName: z4.string(),\n output: outputSchema,\n providerOptions: providerMetadataSchema.optional()\n});\nvar toolApprovalRequestSchema = z4.object({\n type: z4.literal(\"tool-approval-request\"),\n approvalId: z4.string(),\n toolCallId: z4.string()\n});\nvar toolApprovalResponseSchema = z4.object({\n type: z4.literal(\"tool-approval-response\"),\n approvalId: z4.string(),\n approved: z4.boolean(),\n reason: z4.string().optional()\n});\n\n// src/prompt/message.ts\nvar systemModelMessageSchema = z5.object(\n {\n role: z5.literal(\"system\"),\n content: z5.string(),\n providerOptions: providerMetadataSchema.optional()\n }\n);\nvar userModelMessageSchema = z5.object({\n role: z5.literal(\"user\"),\n content: z5.union([\n z5.string(),\n z5.array(z5.union([textPartSchema, imagePartSchema, filePartSchema]))\n ]),\n providerOptions: providerMetadataSchema.optional()\n});\nvar assistantModelMessageSchema = z5.object({\n role: z5.literal(\"assistant\"),\n content: z5.union([\n z5.string(),\n z5.array(\n z5.union([\n textPartSchema,\n filePartSchema,\n reasoningPartSchema,\n toolCallPartSchema,\n toolResultPartSchema,\n toolApprovalRequestSchema\n ])\n )\n ]),\n providerOptions: providerMetadataSchema.optional()\n});\nvar toolModelMessageSchema = z5.object({\n role: z5.literal(\"tool\"),\n content: z5.array(z5.union([toolResultPartSchema, toolApprovalResponseSchema])),\n providerOptions: providerMetadataSchema.optional()\n});\nvar modelMessageSchema = z5.union([\n systemModelMessageSchema,\n userModelMessageSchema,\n assistantModelMessageSchema,\n toolModelMessageSchema\n]);\n\n// src/prompt/standardize-prompt.ts\nasync function standardizePrompt(prompt) {\n if (prompt.prompt == null && prompt.messages == null) {\n throw new InvalidPromptError2({\n prompt,\n message: \"prompt or messages must be defined\"\n });\n }\n if (prompt.prompt != null && prompt.messages != null) {\n throw new InvalidPromptError2({\n prompt,\n message: \"prompt and messages cannot be defined at the same time\"\n });\n }\n if (prompt.system != null && typeof prompt.system !== \"string\" && !asArray(prompt.system).every(\n (message) => typeof message === \"object\" && message !== null && \"role\" in message && message.role === \"system\"\n )) {\n throw new InvalidPromptError2({\n prompt,\n message: \"system must be a string, SystemModelMessage, or array of SystemModelMessage\"\n });\n }\n let messages;\n if (prompt.prompt != null && typeof prompt.prompt === \"string\") {\n messages = [{ role: \"user\", content: prompt.prompt }];\n } else if (prompt.prompt != null && Array.isArray(prompt.prompt)) {\n messages = prompt.prompt;\n } else if (prompt.messages != null) {\n messages = prompt.messages;\n } else {\n throw new InvalidPromptError2({\n prompt,\n message: \"prompt or messages must be defined\"\n });\n }\n if (messages.length === 0) {\n throw new InvalidPromptError2({\n prompt,\n message: \"messages must not be empty\"\n });\n }\n const validationResult = await safeValidateTypes({\n value: messages,\n schema: z6.array(modelMessageSchema)\n });\n if (!validationResult.success) {\n throw new InvalidPromptError2({\n prompt,\n message: \"The messages do not match the ModelMessage[] schema.\",\n cause: validationResult.error\n });\n }\n return {\n messages,\n system: prompt.system\n };\n}\n\n// src/prompt/wrap-gateway-error.ts\nimport { GatewayAuthenticationError } from \"@ai-sdk/gateway\";\nimport { AISDKError as AISDKError23 } from \"@ai-sdk/provider\";\nfunction wrapGatewayError(error) {\n if (!GatewayAuthenticationError.isInstance(error))\n return error;\n const isProductionEnv = (process == null ? void 0 : process.env.NODE_ENV) === \"production\";\n const moreInfoURL = \"https://ai-sdk.dev/unauthenticated-ai-gateway\";\n if (isProductionEnv) {\n return new AISDKError23({\n name: \"GatewayError\",\n message: `Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${moreInfoURL}`\n });\n }\n return Object.assign(\n new Error(`\\x1B[1m\\x1B[31mUnauthenticated request to AI Gateway.\\x1B[0m\n\nTo authenticate, set the \\x1B[33mAI_GATEWAY_API_KEY\\x1B[0m environment variable with your API key.\n\nAlternatively, you can use a provider module instead of the AI Gateway.\n\nLearn more: \\x1B[34m${moreInfoURL}\\x1B[0m\n\n`),\n { name: \"GatewayAuthenticationError\" }\n );\n}\n\n// src/telemetry/assemble-operation-name.ts\nfunction assembleOperationName({\n operationId,\n telemetry\n}) {\n return {\n // standardized operation and resource name:\n \"operation.name\": `${operationId}${(telemetry == null ? void 0 : telemetry.functionId) != null ? ` ${telemetry.functionId}` : \"\"}`,\n \"resource.name\": telemetry == null ? void 0 : telemetry.functionId,\n // detailed, AI SDK specific data:\n \"ai.operationId\": operationId,\n \"ai.telemetry.functionId\": telemetry == null ? void 0 : telemetry.functionId\n };\n}\n\n// src/telemetry/get-base-telemetry-attributes.ts\nfunction getBaseTelemetryAttributes({\n model,\n settings,\n telemetry,\n headers\n}) {\n var _a21;\n return {\n \"ai.model.provider\": model.provider,\n \"ai.model.id\": model.modelId,\n // settings:\n ...Object.entries(settings).reduce((attributes, [key, value]) => {\n if (key === \"timeout\") {\n const totalTimeoutMs = getTotalTimeoutMs(\n value\n );\n if (totalTimeoutMs != null) {\n attributes[`ai.settings.${key}`] = totalTimeoutMs;\n }\n } else {\n attributes[`ai.settings.${key}`] = value;\n }\n return attributes;\n }, {}),\n // add metadata as attributes:\n ...Object.entries((_a21 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a21 : {}).reduce(\n (attributes, [key, value]) => {\n attributes[`ai.telemetry.metadata.${key}`] = value;\n return attributes;\n },\n {}\n ),\n // request headers\n ...Object.entries(headers != null ? headers : {}).reduce((attributes, [key, value]) => {\n if (value !== void 0) {\n attributes[`ai.request.headers.${key}`] = value;\n }\n return attributes;\n }, {})\n };\n}\n\n// src/telemetry/get-tracer.ts\nimport { trace } from \"@opentelemetry/api\";\n\n// src/telemetry/noop-tracer.ts\nvar noopTracer = {\n startSpan() {\n return noopSpan;\n },\n startActiveSpan(name21, arg1, arg2, arg3) {\n if (typeof arg1 === \"function\") {\n return arg1(noopSpan);\n }\n if (typeof arg2 === \"function\") {\n return arg2(noopSpan);\n }\n if (typeof arg3 === \"function\") {\n return arg3(noopSpan);\n }\n }\n};\nvar noopSpan = {\n spanContext() {\n return noopSpanContext;\n },\n setAttribute() {\n return this;\n },\n setAttributes() {\n return this;\n },\n addEvent() {\n return this;\n },\n addLink() {\n return this;\n },\n addLinks() {\n return this;\n },\n setStatus() {\n return this;\n },\n updateName() {\n return this;\n },\n end() {\n return this;\n },\n isRecording() {\n return false;\n },\n recordException() {\n return this;\n }\n};\nvar noopSpanContext = {\n traceId: \"\",\n spanId: \"\",\n traceFlags: 0\n};\n\n// src/telemetry/get-tracer.ts\nfunction getTracer({\n isEnabled = false,\n tracer\n} = {}) {\n if (!isEnabled) {\n return noopTracer;\n }\n if (tracer) {\n return tracer;\n }\n return trace.getTracer(\"ai\");\n}\n\n// src/telemetry/record-span.ts\nimport {\n SpanStatusCode,\n context\n} from \"@opentelemetry/api\";\nasync function recordSpan({\n name: name21,\n tracer,\n attributes,\n fn,\n endWhenDone = true\n}) {\n return tracer.startActiveSpan(\n name21,\n { attributes: await attributes },\n async (span) => {\n const ctx = context.active();\n try {\n const result = await context.with(ctx, () => fn(span));\n if (endWhenDone) {\n span.end();\n }\n return result;\n } catch (error) {\n try {\n recordErrorOnSpan(span, error);\n } finally {\n span.end();\n }\n throw error;\n }\n }\n );\n}\nfunction recordErrorOnSpan(span, error) {\n if (error instanceof Error) {\n span.recordException({\n name: error.name,\n message: error.message,\n stack: error.stack\n });\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error.message\n });\n } else {\n span.setStatus({ code: SpanStatusCode.ERROR });\n }\n}\n\n// src/telemetry/select-telemetry-attributes.ts\nasync function selectTelemetryAttributes({\n telemetry,\n attributes\n}) {\n if ((telemetry == null ? void 0 : telemetry.isEnabled) !== true) {\n return {};\n }\n const resultAttributes = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (value == null) {\n continue;\n }\n if (typeof value === \"object\" && \"input\" in value && typeof value.input === \"function\") {\n if ((telemetry == null ? void 0 : telemetry.recordInputs) === false) {\n continue;\n }\n const result = await value.input();\n if (result != null) {\n resultAttributes[key] = result;\n }\n continue;\n }\n if (typeof value === \"object\" && \"output\" in value && typeof value.output === \"function\") {\n if ((telemetry == null ? void 0 : telemetry.recordOutputs) === false) {\n continue;\n }\n const result = await value.output();\n if (result != null) {\n resultAttributes[key] = result;\n }\n continue;\n }\n resultAttributes[key] = value;\n }\n return resultAttributes;\n}\n\n// src/telemetry/stringify-for-telemetry.ts\nfunction stringifyForTelemetry(prompt) {\n return JSON.stringify(\n prompt.map((message) => ({\n ...message,\n content: typeof message.content === \"string\" ? message.content : message.content.map(\n (part) => part.type === \"file\" ? {\n ...part,\n data: part.data instanceof Uint8Array ? convertDataContentToBase64String(part.data) : part.data\n } : part\n )\n }))\n );\n}\n\n// src/telemetry/telemetry-integration-registry.ts\nfunction registerTelemetryIntegration(integration) {\n if (!globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) {\n globalThis.AI_SDK_TELEMETRY_INTEGRATIONS = [];\n }\n globalThis.AI_SDK_TELEMETRY_INTEGRATIONS.push(integration);\n}\nfunction getGlobalTelemetryIntegrations() {\n var _a21;\n return (_a21 = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) != null ? _a21 : [];\n}\n\n// src/telemetry/get-global-telemetry-integration.ts\nfunction bindTelemetryIntegration(integration) {\n var _a21, _b, _c, _d, _e, _f;\n return {\n onStart: (_a21 = integration.onStart) == null ? void 0 : _a21.bind(integration),\n onStepStart: (_b = integration.onStepStart) == null ? void 0 : _b.bind(integration),\n onToolCallStart: (_c = integration.onToolCallStart) == null ? void 0 : _c.bind(integration),\n onToolCallFinish: (_d = integration.onToolCallFinish) == null ? void 0 : _d.bind(integration),\n onStepFinish: (_e = integration.onStepFinish) == null ? void 0 : _e.bind(integration),\n onFinish: (_f = integration.onFinish) == null ? void 0 : _f.bind(integration)\n };\n}\nfunction getGlobalTelemetryIntegration() {\n const globalIntegrations = getGlobalTelemetryIntegrations();\n return (integrations) => {\n const localIntegrations = asArray(integrations);\n const allIntegrations = [...globalIntegrations, ...localIntegrations];\n function createTelemetryComposite(getListenerFromIntegration) {\n const listeners = allIntegrations.map(getListenerFromIntegration).filter(Boolean);\n return async (event) => {\n for (const listener of listeners) {\n try {\n await listener(event);\n } catch (_ignored) {\n }\n }\n };\n }\n return {\n onStart: createTelemetryComposite((integration) => integration.onStart),\n onStepStart: createTelemetryComposite(\n (integration) => integration.onStepStart\n ),\n onToolCallStart: createTelemetryComposite(\n (integration) => integration.onToolCallStart\n ),\n onToolCallFinish: createTelemetryComposite(\n (integration) => integration.onToolCallFinish\n ),\n onStepFinish: createTelemetryComposite(\n (integration) => integration.onStepFinish\n ),\n onFinish: createTelemetryComposite((integration) => integration.onFinish)\n };\n };\n}\n\n// src/types/usage.ts\nfunction asLanguageModelUsage(usage) {\n return {\n inputTokens: usage.inputTokens.total,\n inputTokenDetails: {\n noCacheTokens: usage.inputTokens.noCache,\n cacheReadTokens: usage.inputTokens.cacheRead,\n cacheWriteTokens: usage.inputTokens.cacheWrite\n },\n outputTokens: usage.outputTokens.total,\n outputTokenDetails: {\n textTokens: usage.outputTokens.text,\n reasoningTokens: usage.outputTokens.reasoning\n },\n totalTokens: addTokenCounts(\n usage.inputTokens.total,\n usage.outputTokens.total\n ),\n raw: usage.raw,\n reasoningTokens: usage.outputTokens.reasoning,\n cachedInputTokens: usage.inputTokens.cacheRead\n };\n}\nfunction createNullLanguageModelUsage() {\n return {\n inputTokens: void 0,\n inputTokenDetails: {\n noCacheTokens: void 0,\n cacheReadTokens: void 0,\n cacheWriteTokens: void 0\n },\n outputTokens: void 0,\n outputTokenDetails: {\n textTokens: void 0,\n reasoningTokens: void 0\n },\n totalTokens: void 0,\n raw: void 0\n };\n}\nfunction addLanguageModelUsage(usage1, usage2) {\n var _a21, _b, _c, _d, _e, _f, _g, _h, _i, _j;\n return {\n inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),\n inputTokenDetails: {\n noCacheTokens: addTokenCounts(\n (_a21 = usage1.inputTokenDetails) == null ? void 0 : _a21.noCacheTokens,\n (_b = usage2.inputTokenDetails) == null ? void 0 : _b.noCacheTokens\n ),\n cacheReadTokens: addTokenCounts(\n (_c = usage1.inputTokenDetails) == null ? void 0 : _c.cacheReadTokens,\n (_d = usage2.inputTokenDetails) == null ? void 0 : _d.cacheReadTokens\n ),\n cacheWriteTokens: addTokenCounts(\n (_e = usage1.inputTokenDetails) == null ? void 0 : _e.cacheWriteTokens,\n (_f = usage2.inputTokenDetails) == null ? void 0 : _f.cacheWriteTokens\n )\n },\n outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),\n outputTokenDetails: {\n textTokens: addTokenCounts(\n (_g = usage1.outputTokenDetails) == null ? void 0 : _g.textTokens,\n (_h = usage2.outputTokenDetails) == null ? void 0 : _h.textTokens\n ),\n reasoningTokens: addTokenCounts(\n (_i = usage1.outputTokenDetails) == null ? void 0 : _i.reasoningTokens,\n (_j = usage2.outputTokenDetails) == null ? void 0 : _j.reasoningTokens\n )\n },\n totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens),\n reasoningTokens: addTokenCounts(\n usage1.reasoningTokens,\n usage2.reasoningTokens\n ),\n cachedInputTokens: addTokenCounts(\n usage1.cachedInputTokens,\n usage2.cachedInputTokens\n )\n };\n}\nfunction addTokenCounts(tokenCount1, tokenCount2) {\n return tokenCount1 == null && tokenCount2 == null ? void 0 : (tokenCount1 != null ? tokenCount1 : 0) + (tokenCount2 != null ? tokenCount2 : 0);\n}\nfunction addImageModelUsage(usage1, usage2) {\n return {\n inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),\n outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),\n totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens)\n };\n}\n\n// src/util/merge-objects.ts\nfunction mergeObjects(base, overrides) {\n if (base === void 0 && overrides === void 0) {\n return void 0;\n }\n if (base === void 0) {\n return overrides;\n }\n if (overrides === void 0) {\n return base;\n }\n const result = { ...base };\n for (const key in overrides) {\n if (Object.prototype.hasOwnProperty.call(overrides, key)) {\n const overridesValue = overrides[key];\n if (overridesValue === void 0)\n continue;\n const baseValue = key in base ? base[key] : void 0;\n const isSourceObject = overridesValue !== null && typeof overridesValue === \"object\" && !Array.isArray(overridesValue) && !(overridesValue instanceof Date) && !(overridesValue instanceof RegExp);\n const isTargetObject = baseValue !== null && baseValue !== void 0 && typeof baseValue === \"object\" && !Array.isArray(baseValue) && !(baseValue instanceof Date) && !(baseValue instanceof RegExp);\n if (isSourceObject && isTargetObject) {\n result[key] = mergeObjects(\n baseValue,\n overridesValue\n );\n } else {\n result[key] = overridesValue;\n }\n }\n }\n return result;\n}\n\n// src/util/retry-with-exponential-backoff.ts\nimport { APICallError as APICallError2 } from \"@ai-sdk/provider\";\nimport { delay, getErrorMessage as getErrorMessage4, isAbortError } from \"@ai-sdk/provider-utils\";\nfunction getRetryDelayInMs({\n error,\n exponentialBackoffDelay\n}) {\n const headers = error.responseHeaders;\n if (!headers)\n return exponentialBackoffDelay;\n let ms;\n const retryAfterMs = headers[\"retry-after-ms\"];\n if (retryAfterMs) {\n const timeoutMs = parseFloat(retryAfterMs);\n if (!Number.isNaN(timeoutMs)) {\n ms = timeoutMs;\n }\n }\n const retryAfter = headers[\"retry-after\"];\n if (retryAfter && ms === void 0) {\n const timeoutSeconds = parseFloat(retryAfter);\n if (!Number.isNaN(timeoutSeconds)) {\n ms = timeoutSeconds * 1e3;\n } else {\n ms = Date.parse(retryAfter) - Date.now();\n }\n }\n if (ms != null && !Number.isNaN(ms) && 0 <= ms && (ms < 60 * 1e3 || ms < exponentialBackoffDelay)) {\n return ms;\n }\n return exponentialBackoffDelay;\n}\nvar retryWithExponentialBackoffRespectingRetryHeaders = ({\n maxRetries = 2,\n initialDelayInMs = 2e3,\n backoffFactor = 2,\n abortSignal\n} = {}) => async (f) => _retryWithExponentialBackoff(f, {\n maxRetries,\n delayInMs: initialDelayInMs,\n backoffFactor,\n abortSignal\n});\nasync function _retryWithExponentialBackoff(f, {\n maxRetries,\n delayInMs,\n backoffFactor,\n abortSignal\n}, errors = []) {\n try {\n return await f();\n } catch (error) {\n if (isAbortError(error)) {\n throw error;\n }\n if (maxRetries === 0) {\n throw error;\n }\n const errorMessage = getErrorMessage4(error);\n const newErrors = [...errors, error];\n const tryNumber = newErrors.length;\n if (tryNumber > maxRetries) {\n throw new RetryError({\n message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,\n reason: \"maxRetriesExceeded\",\n errors: newErrors\n });\n }\n if (error instanceof Error && APICallError2.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {\n await delay(\n getRetryDelayInMs({\n error,\n exponentialBackoffDelay: delayInMs\n }),\n { abortSignal }\n );\n return _retryWithExponentialBackoff(\n f,\n {\n maxRetries,\n delayInMs: backoffFactor * delayInMs,\n backoffFactor,\n abortSignal\n },\n newErrors\n );\n }\n if (tryNumber === 1) {\n throw error;\n }\n throw new RetryError({\n message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,\n reason: \"errorNotRetryable\",\n errors: newErrors\n });\n }\n}\n\n// src/util/prepare-retries.ts\nfunction prepareRetries({\n maxRetries,\n abortSignal\n}) {\n if (maxRetries != null) {\n if (!Number.isInteger(maxRetries)) {\n throw new InvalidArgumentError({\n parameter: \"maxRetries\",\n value: maxRetries,\n message: \"maxRetries must be an integer\"\n });\n }\n if (maxRetries < 0) {\n throw new InvalidArgumentError({\n parameter: \"maxRetries\",\n value: maxRetries,\n message: \"maxRetries must be >= 0\"\n });\n }\n }\n const maxRetriesResult = maxRetries != null ? maxRetries : 2;\n return {\n maxRetries: maxRetriesResult,\n retry: retryWithExponentialBackoffRespectingRetryHeaders({\n maxRetries: maxRetriesResult,\n abortSignal\n })\n };\n}\n\n// src/generate-text/collect-tool-approvals.ts\nfunction collectToolApprovals({\n messages\n}) {\n const lastMessage = messages.at(-1);\n if ((lastMessage == null ? void 0 : lastMessage.role) != \"tool\") {\n return {\n approvedToolApprovals: [],\n deniedToolApprovals: []\n };\n }\n const toolCallsByToolCallId = {};\n for (const message of messages) {\n if (message.role === \"assistant\" && typeof message.content !== \"string\") {\n const content = message.content;\n for (const part of content) {\n if (part.type === \"tool-call\") {\n toolCallsByToolCallId[part.toolCallId] = part;\n }\n }\n }\n }\n const toolApprovalRequestsByApprovalId = {};\n for (const message of messages) {\n if (message.role === \"assistant\" && typeof message.content !== \"string\") {\n const content = message.content;\n for (const part of content) {\n if (part.type === \"tool-approval-request\") {\n toolApprovalRequestsByApprovalId[part.approvalId] = part;\n }\n }\n }\n }\n const toolResults = {};\n for (const part of lastMessage.content) {\n if (part.type === \"tool-result\") {\n toolResults[part.toolCallId] = part;\n }\n }\n const approvedToolApprovals = [];\n const deniedToolApprovals = [];\n const approvalResponses = lastMessage.content.filter(\n (part) => part.type === \"tool-approval-response\"\n );\n for (const approvalResponse of approvalResponses) {\n const approvalRequest = toolApprovalRequestsByApprovalId[approvalResponse.approvalId];\n if (approvalRequest == null) {\n throw new InvalidToolApprovalError({\n approvalId: approvalResponse.approvalId\n });\n }\n if (toolResults[approvalRequest.toolCallId] != null) {\n continue;\n }\n const toolCall = toolCallsByToolCallId[approvalRequest.toolCallId];\n if (toolCall == null) {\n throw new ToolCallNotFoundForApprovalError({\n toolCallId: approvalRequest.toolCallId,\n approvalId: approvalRequest.approvalId\n });\n }\n const approval = {\n approvalRequest,\n approvalResponse,\n toolCall\n };\n if (approvalResponse.approved) {\n approvedToolApprovals.push(approval);\n } else {\n deniedToolApprovals.push(approval);\n }\n }\n return { approvedToolApprovals, deniedToolApprovals };\n}\n\n// src/generate-text/execute-tool-call.ts\nimport { executeTool } from \"@ai-sdk/provider-utils\";\n\n// src/util/now.ts\nfunction now() {\n var _a21, _b;\n return (_b = (_a21 = globalThis == null ? void 0 : globalThis.performance) == null ? void 0 : _a21.now()) != null ? _b : Date.now();\n}\n\n// src/generate-text/execute-tool-call.ts\nasync function executeToolCall({\n toolCall,\n tools,\n tracer,\n telemetry,\n messages,\n abortSignal,\n experimental_context,\n stepNumber,\n model,\n onPreliminaryToolResult,\n onToolCallStart,\n onToolCallFinish\n}) {\n const { toolName, toolCallId, input } = toolCall;\n const tool2 = tools == null ? void 0 : tools[toolName];\n if ((tool2 == null ? void 0 : tool2.execute) == null) {\n return void 0;\n }\n const baseCallbackEvent = {\n stepNumber,\n model,\n toolCall,\n messages,\n abortSignal,\n functionId: telemetry == null ? void 0 : telemetry.functionId,\n metadata: telemetry == null ? void 0 : telemetry.metadata,\n experimental_context\n };\n return recordSpan({\n name: \"ai.toolCall\",\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: \"ai.toolCall\",\n telemetry\n }),\n \"ai.toolCall.name\": toolName,\n \"ai.toolCall.id\": toolCallId,\n \"ai.toolCall.args\": {\n output: () => JSON.stringify(input)\n }\n }\n }),\n tracer,\n fn: async (span) => {\n let output;\n await notify({ event: baseCallbackEvent, callbacks: onToolCallStart });\n const startTime = now();\n try {\n const stream = executeTool({\n execute: tool2.execute.bind(tool2),\n input,\n options: {\n toolCallId,\n messages,\n abortSignal,\n experimental_context\n }\n });\n for await (const part of stream) {\n if (part.type === \"preliminary\") {\n onPreliminaryToolResult == null ? void 0 : onPreliminaryToolResult({\n ...toolCall,\n type: \"tool-result\",\n output: part.output,\n preliminary: true\n });\n } else {\n output = part.output;\n }\n }\n } catch (error) {\n const durationMs2 = now() - startTime;\n await notify({\n event: {\n ...baseCallbackEvent,\n success: false,\n error,\n durationMs: durationMs2\n },\n callbacks: onToolCallFinish\n });\n recordErrorOnSpan(span, error);\n return {\n type: \"tool-error\",\n toolCallId,\n toolName,\n input,\n error,\n dynamic: tool2.type === \"dynamic\",\n ...toolCall.providerMetadata != null ? { providerMetadata: toolCall.providerMetadata } : {}\n };\n }\n const durationMs = now() - startTime;\n await notify({\n event: {\n ...baseCallbackEvent,\n success: true,\n output,\n durationMs\n },\n callbacks: onToolCallFinish\n });\n try {\n span.setAttributes(\n await selectTelemetryAttributes({\n telemetry,\n attributes: {\n \"ai.toolCall.result\": {\n output: () => JSON.stringify(output)\n }\n }\n })\n );\n } catch (ignored) {\n }\n return {\n type: \"tool-result\",\n toolCallId,\n toolName,\n input,\n output,\n dynamic: tool2.type === \"dynamic\",\n ...toolCall.providerMetadata != null ? { providerMetadata: toolCall.providerMetadata } : {}\n };\n }\n });\n}\n\n// src/generate-text/extract-reasoning-content.ts\nfunction extractReasoningContent(content) {\n const parts = content.filter(\n (content2) => content2.type === \"reasoning\"\n );\n return parts.length === 0 ? void 0 : parts.map((content2) => content2.text).join(\"\\n\");\n}\n\n// src/generate-text/extract-text-content.ts\nfunction extractTextContent(content) {\n const parts = content.filter(\n (content2) => content2.type === \"text\"\n );\n if (parts.length === 0) {\n return void 0;\n }\n return parts.map((content2) => content2.text).join(\"\");\n}\n\n// src/generate-text/generated-file.ts\nimport {\n convertBase64ToUint8Array as convertBase64ToUint8Array3,\n convertUint8ArrayToBase64 as convertUint8ArrayToBase642\n} from \"@ai-sdk/provider-utils\";\nvar DefaultGeneratedFile = class {\n constructor({\n data,\n mediaType\n }) {\n const isUint8Array = data instanceof Uint8Array;\n this.base64Data = isUint8Array ? void 0 : data;\n this.uint8ArrayData = isUint8Array ? data : void 0;\n this.mediaType = mediaType;\n }\n // lazy conversion with caching to avoid unnecessary conversion overhead:\n get base64() {\n if (this.base64Data == null) {\n this.base64Data = convertUint8ArrayToBase642(this.uint8ArrayData);\n }\n return this.base64Data;\n }\n // lazy conversion with caching to avoid unnecessary conversion overhead:\n get uint8Array() {\n if (this.uint8ArrayData == null) {\n this.uint8ArrayData = convertBase64ToUint8Array3(this.base64Data);\n }\n return this.uint8ArrayData;\n }\n};\nvar DefaultGeneratedFileWithType = class extends DefaultGeneratedFile {\n constructor(options) {\n super(options);\n this.type = \"file\";\n }\n};\n\n// src/generate-text/is-approval-needed.ts\nasync function isApprovalNeeded({\n tool: tool2,\n toolCall,\n messages,\n experimental_context\n}) {\n if (tool2.needsApproval == null) {\n return false;\n }\n if (typeof tool2.needsApproval === \"boolean\") {\n return tool2.needsApproval;\n }\n return await tool2.needsApproval(toolCall.input, {\n toolCallId: toolCall.toolCallId,\n messages,\n experimental_context\n });\n}\n\n// src/generate-text/output.ts\nvar output_exports = {};\n__export(output_exports, {\n array: () => array,\n choice: () => choice,\n json: () => json,\n object: () => object,\n text: () => text\n});\nimport {\n TypeValidationError as TypeValidationError2\n} from \"@ai-sdk/provider\";\nimport {\n asSchema as asSchema2,\n resolve,\n safeParseJSON as safeParseJSON2,\n safeValidateTypes as safeValidateTypes2\n} from \"@ai-sdk/provider-utils\";\n\n// src/util/parse-partial-json.ts\nimport { safeParseJSON } from \"@ai-sdk/provider-utils\";\n\n// src/util/fix-json.ts\nfunction fixJson(input) {\n const stack = [\"ROOT\"];\n let lastValidIndex = -1;\n let literalStart = null;\n function processValueStart(char, i, swapState) {\n {\n switch (char) {\n case '\"': {\n lastValidIndex = i;\n stack.pop();\n stack.push(swapState);\n stack.push(\"INSIDE_STRING\");\n break;\n }\n case \"f\":\n case \"t\":\n case \"n\": {\n lastValidIndex = i;\n literalStart = i;\n stack.pop();\n stack.push(swapState);\n stack.push(\"INSIDE_LITERAL\");\n break;\n }\n case \"-\": {\n stack.pop();\n stack.push(swapState);\n stack.push(\"INSIDE_NUMBER\");\n break;\n }\n case \"0\":\n case \"1\":\n case \"2\":\n case \"3\":\n case \"4\":\n case \"5\":\n case \"6\":\n case \"7\":\n case \"8\":\n case \"9\": {\n lastValidIndex = i;\n stack.pop();\n stack.push(swapState);\n stack.push(\"INSIDE_NUMBER\");\n break;\n }\n case \"{\": {\n lastValidIndex = i;\n stack.pop();\n stack.push(swapState);\n stack.push(\"INSIDE_OBJECT_START\");\n break;\n }\n case \"[\": {\n lastValidIndex = i;\n stack.pop();\n stack.push(swapState);\n stack.push(\"INSIDE_ARRAY_START\");\n break;\n }\n }\n }\n }\n function processAfterObjectValue(char, i) {\n switch (char) {\n case \",\": {\n stack.pop();\n stack.push(\"INSIDE_OBJECT_AFTER_COMMA\");\n break;\n }\n case \"}\": {\n lastValidIndex = i;\n stack.pop();\n break;\n }\n }\n }\n function processAfterArrayValue(char, i) {\n switch (char) {\n case \",\": {\n stack.pop();\n stack.push(\"INSIDE_ARRAY_AFTER_COMMA\");\n break;\n }\n case \"]\": {\n lastValidIndex = i;\n stack.pop();\n break;\n }\n }\n }\n for (let i = 0; i < input.length; i++) {\n const char = input[i];\n const currentState = stack[stack.length - 1];\n switch (currentState) {\n case \"ROOT\":\n processValueStart(char, i, \"FINISH\");\n break;\n case \"INSIDE_OBJECT_START\": {\n switch (char) {\n case '\"': {\n stack.pop();\n stack.push(\"INSIDE_OBJECT_KEY\");\n break;\n }\n case \"}\": {\n lastValidIndex = i;\n stack.pop();\n break;\n }\n }\n break;\n }\n case \"INSIDE_OBJECT_AFTER_COMMA\": {\n switch (char) {\n case '\"': {\n stack.pop();\n stack.push(\"INSIDE_OBJECT_KEY\");\n break;\n }\n }\n break;\n }\n case \"INSIDE_OBJECT_KEY\": {\n switch (char) {\n case '\"': {\n stack.pop();\n stack.push(\"INSIDE_OBJECT_AFTER_KEY\");\n break;\n }\n }\n break;\n }\n case \"INSIDE_OBJECT_AFTER_KEY\": {\n switch (char) {\n case \":\": {\n stack.pop();\n stack.push(\"INSIDE_OBJECT_BEFORE_VALUE\");\n break;\n }\n }\n break;\n }\n case \"INSIDE_OBJECT_BEFORE_VALUE\": {\n processValueStart(char, i, \"INSIDE_OBJECT_AFTER_VALUE\");\n break;\n }\n case \"INSIDE_OBJECT_AFTER_VALUE\": {\n processAfterObjectValue(char, i);\n break;\n }\n case \"INSIDE_STRING\": {\n switch (char) {\n case '\"': {\n stack.pop();\n lastValidIndex = i;\n break;\n }\n case \"\\\\\": {\n stack.push(\"INSIDE_STRING_ESCAPE\");\n break;\n }\n default: {\n lastValidIndex = i;\n }\n }\n break;\n }\n case \"INSIDE_ARRAY_START\": {\n switch (char) {\n case \"]\": {\n lastValidIndex = i;\n stack.pop();\n break;\n }\n default: {\n lastValidIndex = i;\n processValueStart(char, i, \"INSIDE_ARRAY_AFTER_VALUE\");\n break;\n }\n }\n break;\n }\n case \"INSIDE_ARRAY_AFTER_VALUE\": {\n switch (char) {\n case \",\": {\n stack.pop();\n stack.push(\"INSIDE_ARRAY_AFTER_COMMA\");\n break;\n }\n case \"]\": {\n lastValidIndex = i;\n stack.pop();\n break;\n }\n default: {\n lastValidIndex = i;\n break;\n }\n }\n break;\n }\n case \"INSIDE_ARRAY_AFTER_COMMA\": {\n processValueStart(char, i, \"INSIDE_ARRAY_AFTER_VALUE\");\n break;\n }\n case \"INSIDE_STRING_ESCAPE\": {\n stack.pop();\n lastValidIndex = i;\n break;\n }\n case \"INSIDE_NUMBER\": {\n switch (char) {\n case \"0\":\n case \"1\":\n case \"2\":\n case \"3\":\n case \"4\":\n case \"5\":\n case \"6\":\n case \"7\":\n case \"8\":\n case \"9\": {\n lastValidIndex = i;\n break;\n }\n case \"e\":\n case \"E\":\n case \"-\":\n case \".\": {\n break;\n }\n case \",\": {\n stack.pop();\n if (stack[stack.length - 1] === \"INSIDE_ARRAY_AFTER_VALUE\") {\n processAfterArrayValue(char, i);\n }\n if (stack[stack.length - 1] === \"INSIDE_OBJECT_AFTER_VALUE\") {\n processAfterObjectValue(char, i);\n }\n break;\n }\n case \"}\": {\n stack.pop();\n if (stack[stack.length - 1] === \"INSIDE_OBJECT_AFTER_VALUE\") {\n processAfterObjectValue(char, i);\n }\n break;\n }\n case \"]\": {\n stack.pop();\n if (stack[stack.length - 1] === \"INSIDE_ARRAY_AFTER_VALUE\") {\n processAfterArrayValue(char, i);\n }\n break;\n }\n default: {\n stack.pop();\n break;\n }\n }\n break;\n }\n case \"INSIDE_LITERAL\": {\n const partialLiteral = input.substring(literalStart, i + 1);\n if (!\"false\".startsWith(partialLiteral) && !\"true\".startsWith(partialLiteral) && !\"null\".startsWith(partialLiteral)) {\n stack.pop();\n if (stack[stack.length - 1] === \"INSIDE_OBJECT_AFTER_VALUE\") {\n processAfterObjectValue(char, i);\n } else if (stack[stack.length - 1] === \"INSIDE_ARRAY_AFTER_VALUE\") {\n processAfterArrayValue(char, i);\n }\n } else {\n lastValidIndex = i;\n }\n break;\n }\n }\n }\n let result = input.slice(0, lastValidIndex + 1);\n for (let i = stack.length - 1; i >= 0; i--) {\n const state = stack[i];\n switch (state) {\n case \"INSIDE_STRING\": {\n result += '\"';\n break;\n }\n case \"INSIDE_OBJECT_KEY\":\n case \"INSIDE_OBJECT_AFTER_KEY\":\n case \"INSIDE_OBJECT_AFTER_COMMA\":\n case \"INSIDE_OBJECT_START\":\n case \"INSIDE_OBJECT_BEFORE_VALUE\":\n case \"INSIDE_OBJECT_AFTER_VALUE\": {\n result += \"}\";\n break;\n }\n case \"INSIDE_ARRAY_START\":\n case \"INSIDE_ARRAY_AFTER_COMMA\":\n case \"INSIDE_ARRAY_AFTER_VALUE\": {\n result += \"]\";\n break;\n }\n case \"INSIDE_LITERAL\": {\n const partialLiteral = input.substring(literalStart, input.length);\n if (\"true\".startsWith(partialLiteral)) {\n result += \"true\".slice(partialLiteral.length);\n } else if (\"false\".startsWith(partialLiteral)) {\n result += \"false\".slice(partialLiteral.length);\n } else if (\"null\".startsWith(partialLiteral)) {\n result += \"null\".slice(partialLiteral.length);\n }\n }\n }\n }\n return result;\n}\n\n// src/util/parse-partial-json.ts\nasync function parsePartialJson(jsonText) {\n if (jsonText === void 0) {\n return { value: void 0, state: \"undefined-input\" };\n }\n let result = await safeParseJSON({ text: jsonText });\n if (result.success) {\n return { value: result.value, state: \"successful-parse\" };\n }\n result = await safeParseJSON({ text: fixJson(jsonText) });\n if (result.success) {\n return { value: result.value, state: \"repaired-parse\" };\n }\n return { value: void 0, state: \"failed-parse\" };\n}\n\n// src/generate-text/output.ts\nvar text = () => ({\n name: \"text\",\n responseFormat: Promise.resolve({ type: \"text\" }),\n async parseCompleteOutput({ text: text2 }) {\n return text2;\n },\n async parsePartialOutput({ text: text2 }) {\n return { partial: text2 };\n },\n createElementStreamTransform() {\n return void 0;\n }\n});\nvar object = ({\n schema: inputSchema,\n name: name21,\n description\n}) => {\n const schema = asSchema2(inputSchema);\n return {\n name: \"object\",\n responseFormat: resolve(schema.jsonSchema).then((jsonSchema2) => ({\n type: \"json\",\n schema: jsonSchema2,\n ...name21 != null && { name: name21 },\n ...description != null && { description }\n })),\n async parseCompleteOutput({ text: text2 }, context2) {\n const parseResult = await safeParseJSON2({ text: text2 });\n if (!parseResult.success) {\n throw new NoObjectGeneratedError({\n message: \"No object generated: could not parse the response.\",\n cause: parseResult.error,\n text: text2,\n response: context2.response,\n usage: context2.usage,\n finishReason: context2.finishReason\n });\n }\n const validationResult = await safeValidateTypes2({\n value: parseResult.value,\n schema\n });\n if (!validationResult.success) {\n throw new NoObjectGeneratedError({\n message: \"No object generated: response did not match schema.\",\n cause: validationResult.error,\n text: text2,\n response: context2.response,\n usage: context2.usage,\n finishReason: context2.finishReason\n });\n }\n return validationResult.value;\n },\n async parsePartialOutput({ text: text2 }) {\n const result = await parsePartialJson(text2);\n switch (result.state) {\n case \"failed-parse\":\n case \"undefined-input\": {\n return void 0;\n }\n case \"repaired-parse\":\n case \"successful-parse\": {\n return {\n // Note: currently no validation of partial results:\n partial: result.value\n };\n }\n }\n },\n createElementStreamTransform() {\n return void 0;\n }\n };\n};\nvar array = ({\n element: inputElementSchema,\n name: name21,\n description\n}) => {\n const elementSchema = asSchema2(inputElementSchema);\n return {\n name: \"array\",\n // JSON schema that describes an array of elements:\n responseFormat: resolve(elementSchema.jsonSchema).then((jsonSchema2) => {\n const { $schema, ...itemSchema } = jsonSchema2;\n return {\n type: \"json\",\n schema: {\n $schema: \"http://json-schema.org/draft-07/schema#\",\n type: \"object\",\n properties: {\n elements: { type: \"array\", items: itemSchema }\n },\n required: [\"elements\"],\n additionalProperties: false\n },\n ...name21 != null && { name: name21 },\n ...description != null && { description }\n };\n }),\n async parseCompleteOutput({ text: text2 }, context2) {\n const parseResult = await safeParseJSON2({ text: text2 });\n if (!parseResult.success) {\n throw new NoObjectGeneratedError({\n message: \"No object generated: could not parse the response.\",\n cause: parseResult.error,\n text: text2,\n response: context2.response,\n usage: context2.usage,\n finishReason: context2.finishReason\n });\n }\n const outerValue = parseResult.value;\n if (outerValue == null || typeof outerValue !== \"object\" || !(\"elements\" in outerValue) || !Array.isArray(outerValue.elements)) {\n throw new NoObjectGeneratedError({\n message: \"No object generated: response did not match schema.\",\n cause: new TypeValidationError2({\n value: outerValue,\n cause: \"response must be an object with an elements array\"\n }),\n text: text2,\n response: context2.response,\n usage: context2.usage,\n finishReason: context2.finishReason\n });\n }\n for (const element of outerValue.elements) {\n const validationResult = await safeValidateTypes2({\n value: element,\n schema: elementSchema\n });\n if (!validationResult.success) {\n throw new NoObjectGeneratedError({\n message: \"No object generated: response did not match schema.\",\n cause: validationResult.error,\n text: text2,\n response: context2.response,\n usage: context2.usage,\n finishReason: context2.finishReason\n });\n }\n }\n return outerValue.elements;\n },\n async parsePartialOutput({ text: text2 }) {\n const result = await parsePartialJson(text2);\n switch (result.state) {\n case \"failed-parse\":\n case \"undefined-input\": {\n return void 0;\n }\n case \"repaired-parse\":\n case \"successful-parse\": {\n const outerValue = result.value;\n if (outerValue == null || typeof outerValue !== \"object\" || !(\"elements\" in outerValue) || !Array.isArray(outerValue.elements)) {\n return void 0;\n }\n const rawElements = result.state === \"repaired-parse\" && outerValue.elements.length > 0 ? outerValue.elements.slice(0, -1) : outerValue.elements;\n const parsedElements = [];\n for (const rawElement of rawElements) {\n const validationResult = await safeValidateTypes2({\n value: rawElement,\n schema: elementSchema\n });\n if (validationResult.success) {\n parsedElements.push(validationResult.value);\n }\n }\n return { partial: parsedElements };\n }\n }\n },\n createElementStreamTransform() {\n let publishedElements = 0;\n return new TransformStream({\n transform({ partialOutput }, controller) {\n if (partialOutput != null) {\n for (; publishedElements < partialOutput.length; publishedElements++) {\n controller.enqueue(partialOutput[publishedElements]);\n }\n }\n }\n });\n }\n };\n};\nvar choice = ({\n options: choiceOptions,\n name: name21,\n description\n}) => {\n return {\n name: \"choice\",\n // JSON schema that describes an enumeration:\n responseFormat: Promise.resolve({\n type: \"json\",\n schema: {\n $schema: \"http://json-schema.org/draft-07/schema#\",\n type: \"object\",\n properties: {\n result: { type: \"string\", enum: choiceOptions }\n },\n required: [\"result\"],\n additionalProperties: false\n },\n ...name21 != null && { name: name21 },\n ...description != null && { description }\n }),\n async parseCompleteOutput({ text: text2 }, context2) {\n const parseResult = await safeParseJSON2({ text: text2 });\n if (!parseResult.success) {\n throw new NoObjectGeneratedError({\n message: \"No object generated: could not parse the response.\",\n cause: parseResult.error,\n text: text2,\n response: context2.response,\n usage: context2.usage,\n finishReason: context2.finishReason\n });\n }\n const outerValue = parseResult.value;\n if (outerValue == null || typeof outerValue !== \"object\" || !(\"result\" in outerValue) || typeof outerValue.result !== \"string\" || !choiceOptions.includes(outerValue.result)) {\n throw new NoObjectGeneratedError({\n message: \"No object generated: response did not match schema.\",\n cause: new TypeValidationError2({\n value: outerValue,\n cause: \"response must be an object that contains a choice value.\"\n }),\n text: text2,\n response: context2.response,\n usage: context2.usage,\n finishReason: context2.finishReason\n });\n }\n return outerValue.result;\n },\n async parsePartialOutput({ text: text2 }) {\n const result = await parsePartialJson(text2);\n switch (result.state) {\n case \"failed-parse\":\n case \"undefined-input\": {\n return void 0;\n }\n case \"repaired-parse\":\n case \"successful-parse\": {\n const outerValue = result.value;\n if (outerValue == null || typeof outerValue !== \"object\" || !(\"result\" in outerValue) || typeof outerValue.result !== \"string\") {\n return void 0;\n }\n const potentialMatches = choiceOptions.filter(\n (choiceOption) => choiceOption.startsWith(outerValue.result)\n );\n if (result.state === \"successful-parse\") {\n return potentialMatches.includes(outerValue.result) ? { partial: outerValue.result } : void 0;\n } else {\n return potentialMatches.length === 1 ? { partial: potentialMatches[0] } : void 0;\n }\n }\n }\n },\n createElementStreamTransform() {\n return void 0;\n }\n };\n};\nvar json = ({\n name: name21,\n description\n} = {}) => {\n return {\n name: \"json\",\n responseFormat: Promise.resolve({\n type: \"json\",\n ...name21 != null && { name: name21 },\n ...description != null && { description }\n }),\n async parseCompleteOutput({ text: text2 }, context2) {\n const parseResult = await safeParseJSON2({ text: text2 });\n if (!parseResult.success) {\n throw new NoObjectGeneratedError({\n message: \"No object generated: could not parse the response.\",\n cause: parseResult.error,\n text: text2,\n response: context2.response,\n usage: context2.usage,\n finishReason: context2.finishReason\n });\n }\n return parseResult.value;\n },\n async parsePartialOutput({ text: text2 }) {\n const result = await parsePartialJson(text2);\n switch (result.state) {\n case \"failed-parse\":\n case \"undefined-input\": {\n return void 0;\n }\n case \"repaired-parse\":\n case \"successful-parse\": {\n return result.value === void 0 ? void 0 : { partial: result.value };\n }\n }\n },\n createElementStreamTransform() {\n return void 0;\n }\n };\n};\n\n// src/generate-text/parse-tool-call.ts\nimport {\n asSchema as asSchema3,\n safeParseJSON as safeParseJSON3,\n safeValidateTypes as safeValidateTypes3\n} from \"@ai-sdk/provider-utils\";\nasync function parseToolCall({\n toolCall,\n tools,\n repairToolCall,\n system,\n messages\n}) {\n var _a21;\n try {\n if (tools == null) {\n if (toolCall.providerExecuted && toolCall.dynamic) {\n return await parseProviderExecutedDynamicToolCall(toolCall);\n }\n throw new NoSuchToolError({ toolName: toolCall.toolName });\n }\n try {\n return await doParseToolCall({ toolCall, tools });\n } catch (error) {\n if (repairToolCall == null || !(NoSuchToolError.isInstance(error) || InvalidToolInputError.isInstance(error))) {\n throw error;\n }\n let repairedToolCall = null;\n try {\n repairedToolCall = await repairToolCall({\n toolCall,\n tools,\n inputSchema: async ({ toolName }) => {\n const { inputSchema } = tools[toolName];\n return await asSchema3(inputSchema).jsonSchema;\n },\n system,\n messages,\n error\n });\n } catch (repairError) {\n throw new ToolCallRepairError({\n cause: repairError,\n originalError: error\n });\n }\n if (repairedToolCall == null) {\n throw error;\n }\n return await doParseToolCall({ toolCall: repairedToolCall, tools });\n }\n } catch (error) {\n const parsedInput = await safeParseJSON3({ text: toolCall.input });\n const input = parsedInput.success ? parsedInput.value : toolCall.input;\n return {\n type: \"tool-call\",\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input,\n dynamic: true,\n invalid: true,\n error,\n title: (_a21 = tools == null ? void 0 : tools[toolCall.toolName]) == null ? void 0 : _a21.title,\n providerExecuted: toolCall.providerExecuted,\n providerMetadata: toolCall.providerMetadata\n };\n }\n}\nasync function parseProviderExecutedDynamicToolCall(toolCall) {\n const parseResult = toolCall.input.trim() === \"\" ? { success: true, value: {} } : await safeParseJSON3({ text: toolCall.input });\n if (parseResult.success === false) {\n throw new InvalidToolInputError({\n toolName: toolCall.toolName,\n toolInput: toolCall.input,\n cause: parseResult.error\n });\n }\n return {\n type: \"tool-call\",\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: parseResult.value,\n providerExecuted: true,\n dynamic: true,\n providerMetadata: toolCall.providerMetadata\n };\n}\nasync function doParseToolCall({\n toolCall,\n tools\n}) {\n const toolName = toolCall.toolName;\n const tool2 = tools[toolName];\n if (tool2 == null) {\n if (toolCall.providerExecuted && toolCall.dynamic) {\n return await parseProviderExecutedDynamicToolCall(toolCall);\n }\n throw new NoSuchToolError({\n toolName: toolCall.toolName,\n availableTools: Object.keys(tools)\n });\n }\n const schema = asSchema3(tool2.inputSchema);\n const parseResult = toolCall.input.trim() === \"\" ? await safeValidateTypes3({ value: {}, schema }) : await safeParseJSON3({ text: toolCall.input, schema });\n if (parseResult.success === false) {\n throw new InvalidToolInputError({\n toolName,\n toolInput: toolCall.input,\n cause: parseResult.error\n });\n }\n return tool2.type === \"dynamic\" ? {\n type: \"tool-call\",\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: parseResult.value,\n providerExecuted: toolCall.providerExecuted,\n providerMetadata: toolCall.providerMetadata,\n dynamic: true,\n title: tool2.title\n } : {\n type: \"tool-call\",\n toolCallId: toolCall.toolCallId,\n toolName,\n input: parseResult.value,\n providerExecuted: toolCall.providerExecuted,\n providerMetadata: toolCall.providerMetadata,\n title: tool2.title\n };\n}\n\n// src/generate-text/step-result.ts\nvar DefaultStepResult = class {\n constructor({\n stepNumber,\n model,\n functionId,\n metadata,\n experimental_context,\n content,\n finishReason,\n rawFinishReason,\n usage,\n warnings,\n request,\n response,\n providerMetadata\n }) {\n this.stepNumber = stepNumber;\n this.model = model;\n this.functionId = functionId;\n this.metadata = metadata;\n this.experimental_context = experimental_context;\n this.content = content;\n this.finishReason = finishReason;\n this.rawFinishReason = rawFinishReason;\n this.usage = usage;\n this.warnings = warnings;\n this.request = request;\n this.response = response;\n this.providerMetadata = providerMetadata;\n }\n get text() {\n return this.content.filter((part) => part.type === \"text\").map((part) => part.text).join(\"\");\n }\n get reasoning() {\n return this.content.filter((part) => part.type === \"reasoning\");\n }\n get reasoningText() {\n return this.reasoning.length === 0 ? void 0 : this.reasoning.map((part) => part.text).join(\"\");\n }\n get files() {\n return this.content.filter((part) => part.type === \"file\").map((part) => part.file);\n }\n get sources() {\n return this.content.filter((part) => part.type === \"source\");\n }\n get toolCalls() {\n return this.content.filter((part) => part.type === \"tool-call\");\n }\n get staticToolCalls() {\n return this.toolCalls.filter(\n (toolCall) => toolCall.dynamic !== true\n );\n }\n get dynamicToolCalls() {\n return this.toolCalls.filter(\n (toolCall) => toolCall.dynamic === true\n );\n }\n get toolResults() {\n return this.content.filter((part) => part.type === \"tool-result\");\n }\n get staticToolResults() {\n return this.toolResults.filter(\n (toolResult) => toolResult.dynamic !== true\n );\n }\n get dynamicToolResults() {\n return this.toolResults.filter(\n (toolResult) => toolResult.dynamic === true\n );\n }\n};\n\n// src/generate-text/stop-condition.ts\nfunction stepCountIs(stepCount) {\n return ({ steps }) => steps.length === stepCount;\n}\nfunction hasToolCall(toolName) {\n return ({ steps }) => {\n var _a21, _b, _c;\n return (_c = (_b = (_a21 = steps[steps.length - 1]) == null ? void 0 : _a21.toolCalls) == null ? void 0 : _b.some(\n (toolCall) => toolCall.toolName === toolName\n )) != null ? _c : false;\n };\n}\nasync function isStopConditionMet({\n stopConditions,\n steps\n}) {\n return (await Promise.all(stopConditions.map((condition) => condition({ steps })))).some((result) => result);\n}\n\n// src/generate-text/to-response-messages.ts\nasync function toResponseMessages({\n content: inputContent,\n tools\n}) {\n const responseMessages = [];\n const content = [];\n for (const part of inputContent) {\n if (part.type === \"source\") {\n continue;\n }\n if ((part.type === \"tool-result\" || part.type === \"tool-error\") && !part.providerExecuted) {\n continue;\n }\n if (part.type === \"text\" && part.text.length === 0) {\n continue;\n }\n switch (part.type) {\n case \"text\":\n content.push({\n type: \"text\",\n text: part.text,\n providerOptions: part.providerMetadata\n });\n break;\n case \"reasoning\":\n content.push({\n type: \"reasoning\",\n text: part.text,\n providerOptions: part.providerMetadata\n });\n break;\n case \"file\":\n content.push({\n type: \"file\",\n data: part.file.base64,\n mediaType: part.file.mediaType,\n providerOptions: part.providerMetadata\n });\n break;\n case \"tool-call\":\n content.push({\n type: \"tool-call\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n providerExecuted: part.providerExecuted,\n providerOptions: part.providerMetadata\n });\n break;\n case \"tool-result\": {\n const output = await createToolModelOutput({\n toolCallId: part.toolCallId,\n input: part.input,\n tool: tools == null ? void 0 : tools[part.toolName],\n output: part.output,\n errorMode: \"none\"\n });\n content.push({\n type: \"tool-result\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output,\n providerOptions: part.providerMetadata\n });\n break;\n }\n case \"tool-error\": {\n const output = await createToolModelOutput({\n toolCallId: part.toolCallId,\n input: part.input,\n tool: tools == null ? void 0 : tools[part.toolName],\n output: part.error,\n errorMode: \"json\"\n });\n content.push({\n type: \"tool-result\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output,\n providerOptions: part.providerMetadata\n });\n break;\n }\n case \"tool-approval-request\":\n content.push({\n type: \"tool-approval-request\",\n approvalId: part.approvalId,\n toolCallId: part.toolCall.toolCallId\n });\n break;\n }\n }\n if (content.length > 0) {\n responseMessages.push({\n role: \"assistant\",\n content\n });\n }\n const toolResultContent = [];\n for (const part of inputContent) {\n if (!(part.type === \"tool-result\" || part.type === \"tool-error\") || part.providerExecuted) {\n continue;\n }\n const output = await createToolModelOutput({\n toolCallId: part.toolCallId,\n input: part.input,\n tool: tools == null ? void 0 : tools[part.toolName],\n output: part.type === \"tool-result\" ? part.output : part.error,\n errorMode: part.type === \"tool-error\" ? \"text\" : \"none\"\n });\n toolResultContent.push({\n type: \"tool-result\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output,\n ...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n });\n }\n if (toolResultContent.length > 0) {\n responseMessages.push({\n role: \"tool\",\n content: toolResultContent\n });\n }\n return responseMessages;\n}\n\n// src/util/merge-abort-signals.ts\nfunction mergeAbortSignals(...signals) {\n const validSignals = signals.filter(\n (signal) => signal != null\n );\n if (validSignals.length === 0) {\n return void 0;\n }\n if (validSignals.length === 1) {\n return validSignals[0];\n }\n const controller = new AbortController();\n for (const signal of validSignals) {\n if (signal.aborted) {\n controller.abort(signal.reason);\n return controller.signal;\n }\n signal.addEventListener(\n \"abort\",\n () => {\n controller.abort(signal.reason);\n },\n { once: true }\n );\n }\n return controller.signal;\n}\n\n// src/generate-text/generate-text.ts\nvar originalGenerateId = createIdGenerator({\n prefix: \"aitxt\",\n size: 24\n});\nasync function generateText({\n model: modelArg,\n tools,\n toolChoice,\n system,\n prompt,\n messages,\n maxRetries: maxRetriesArg,\n abortSignal,\n timeout,\n headers,\n stopWhen = stepCountIs(1),\n experimental_output,\n output = experimental_output,\n experimental_telemetry: telemetry,\n providerOptions,\n experimental_activeTools,\n activeTools = experimental_activeTools,\n experimental_prepareStep,\n prepareStep = experimental_prepareStep,\n experimental_repairToolCall: repairToolCall,\n experimental_download: download2,\n experimental_context,\n experimental_include: include,\n _internal: { generateId: generateId2 = originalGenerateId } = {},\n experimental_onStart: onStart,\n experimental_onStepStart: onStepStart,\n experimental_onToolCallStart: onToolCallStart,\n experimental_onToolCallFinish: onToolCallFinish,\n onStepFinish,\n onFinish,\n ...settings\n}) {\n const model = resolveLanguageModel(modelArg);\n const createGlobalTelemetry = getGlobalTelemetryIntegration();\n const stopConditions = asArray(stopWhen);\n const totalTimeoutMs = getTotalTimeoutMs(timeout);\n const stepTimeoutMs = getStepTimeoutMs(timeout);\n const stepAbortController = stepTimeoutMs != null ? new AbortController() : void 0;\n const mergedAbortSignal = mergeAbortSignals(\n abortSignal,\n totalTimeoutMs != null ? AbortSignal.timeout(totalTimeoutMs) : void 0,\n stepAbortController == null ? void 0 : stepAbortController.signal\n );\n const { maxRetries, retry } = prepareRetries({\n maxRetries: maxRetriesArg,\n abortSignal: mergedAbortSignal\n });\n const callSettings = prepareCallSettings(settings);\n const headersWithUserAgent = withUserAgentSuffix2(\n headers != null ? headers : {},\n `ai/${VERSION}`\n );\n const baseTelemetryAttributes = getBaseTelemetryAttributes({\n model,\n telemetry,\n headers: headersWithUserAgent,\n settings: { ...callSettings, maxRetries }\n });\n const modelInfo = { provider: model.provider, modelId: model.modelId };\n const initialPrompt = await standardizePrompt({\n system,\n prompt,\n messages\n });\n const globalTelemetry = createGlobalTelemetry(telemetry == null ? void 0 : telemetry.integrations);\n await notify({\n event: {\n model: modelInfo,\n system,\n prompt,\n messages,\n tools,\n toolChoice,\n activeTools,\n maxOutputTokens: callSettings.maxOutputTokens,\n temperature: callSettings.temperature,\n topP: callSettings.topP,\n topK: callSettings.topK,\n presencePenalty: callSettings.presencePenalty,\n frequencyPenalty: callSettings.frequencyPenalty,\n stopSequences: callSettings.stopSequences,\n seed: callSettings.seed,\n maxRetries,\n timeout,\n headers,\n providerOptions,\n stopWhen,\n output,\n abortSignal,\n include,\n functionId: telemetry == null ? void 0 : telemetry.functionId,\n metadata: telemetry == null ? void 0 : telemetry.metadata,\n experimental_context\n },\n callbacks: [\n onStart,\n globalTelemetry.onStart\n ]\n });\n const tracer = getTracer(telemetry);\n try {\n return await recordSpan({\n name: \"ai.generateText\",\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: \"ai.generateText\",\n telemetry\n }),\n ...baseTelemetryAttributes,\n // model:\n \"ai.model.provider\": model.provider,\n \"ai.model.id\": model.modelId,\n // specific settings that only make sense on the outer level:\n \"ai.prompt\": {\n input: () => JSON.stringify({ system, prompt, messages })\n }\n }\n }),\n tracer,\n fn: async (span) => {\n var _a21, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;\n const initialMessages = initialPrompt.messages;\n const responseMessages = [];\n const { approvedToolApprovals, deniedToolApprovals } = collectToolApprovals({ messages: initialMessages });\n const localApprovedToolApprovals = approvedToolApprovals.filter(\n (toolApproval) => !toolApproval.toolCall.providerExecuted\n );\n if (deniedToolApprovals.length > 0 || localApprovedToolApprovals.length > 0) {\n const toolOutputs = await executeTools({\n toolCalls: localApprovedToolApprovals.map(\n (toolApproval) => toolApproval.toolCall\n ),\n tools,\n tracer,\n telemetry,\n messages: initialMessages,\n abortSignal: mergedAbortSignal,\n experimental_context,\n stepNumber: 0,\n model: modelInfo,\n onToolCallStart: [\n onToolCallStart,\n globalTelemetry.onToolCallStart\n ],\n onToolCallFinish: [\n onToolCallFinish,\n globalTelemetry.onToolCallFinish\n ]\n });\n const toolContent = [];\n for (const output2 of toolOutputs) {\n const modelOutput = await createToolModelOutput({\n toolCallId: output2.toolCallId,\n input: output2.input,\n tool: tools == null ? void 0 : tools[output2.toolName],\n output: output2.type === \"tool-result\" ? output2.output : output2.error,\n errorMode: output2.type === \"tool-error\" ? \"text\" : \"none\"\n });\n toolContent.push({\n type: \"tool-result\",\n toolCallId: output2.toolCallId,\n toolName: output2.toolName,\n output: modelOutput\n });\n }\n for (const toolApproval of deniedToolApprovals) {\n toolContent.push({\n type: \"tool-result\",\n toolCallId: toolApproval.toolCall.toolCallId,\n toolName: toolApproval.toolCall.toolName,\n output: {\n type: \"execution-denied\",\n reason: toolApproval.approvalResponse.reason,\n // For provider-executed tools, include approvalId so provider can correlate\n ...toolApproval.toolCall.providerExecuted && {\n providerOptions: {\n openai: {\n approvalId: toolApproval.approvalResponse.approvalId\n }\n }\n }\n }\n });\n }\n responseMessages.push({\n role: \"tool\",\n content: toolContent\n });\n }\n const providerExecutedToolApprovals = [\n ...approvedToolApprovals,\n ...deniedToolApprovals\n ].filter((toolApproval) => toolApproval.toolCall.providerExecuted);\n if (providerExecutedToolApprovals.length > 0) {\n responseMessages.push({\n role: \"tool\",\n content: providerExecutedToolApprovals.map(\n (toolApproval) => ({\n type: \"tool-approval-response\",\n approvalId: toolApproval.approvalResponse.approvalId,\n approved: toolApproval.approvalResponse.approved,\n reason: toolApproval.approvalResponse.reason,\n providerExecuted: true\n })\n )\n });\n }\n const callSettings2 = prepareCallSettings(settings);\n let currentModelResponse;\n let clientToolCalls = [];\n let clientToolOutputs = [];\n const steps = [];\n const pendingDeferredToolCalls = /* @__PURE__ */ new Map();\n do {\n const stepTimeoutId = stepTimeoutMs != null ? setTimeout(() => stepAbortController.abort(), stepTimeoutMs) : void 0;\n try {\n const stepInputMessages = [...initialMessages, ...responseMessages];\n const prepareStepResult = await (prepareStep == null ? void 0 : prepareStep({\n model,\n steps,\n stepNumber: steps.length,\n messages: stepInputMessages,\n experimental_context\n }));\n const stepModel = resolveLanguageModel(\n (_a21 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a21 : model\n );\n const stepModelInfo = {\n provider: stepModel.provider,\n modelId: stepModel.modelId\n };\n const promptMessages = await convertToLanguageModelPrompt({\n prompt: {\n system: (_b = prepareStepResult == null ? void 0 : prepareStepResult.system) != null ? _b : initialPrompt.system,\n messages: (_c = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _c : stepInputMessages\n },\n supportedUrls: await stepModel.supportedUrls,\n download: download2\n });\n experimental_context = (_d = prepareStepResult == null ? void 0 : prepareStepResult.experimental_context) != null ? _d : experimental_context;\n const stepActiveTools = (_e = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _e : activeTools;\n const { toolChoice: stepToolChoice, tools: stepTools } = await prepareToolsAndToolChoice({\n tools,\n toolChoice: (_f = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _f : toolChoice,\n activeTools: stepActiveTools\n });\n const stepMessages = (_g = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _g : stepInputMessages;\n const stepSystem = (_h = prepareStepResult == null ? void 0 : prepareStepResult.system) != null ? _h : initialPrompt.system;\n const stepProviderOptions = mergeObjects(\n providerOptions,\n prepareStepResult == null ? void 0 : prepareStepResult.providerOptions\n );\n await notify({\n event: {\n stepNumber: steps.length,\n model: stepModelInfo,\n system: stepSystem,\n messages: stepMessages,\n tools,\n toolChoice: stepToolChoice,\n activeTools: stepActiveTools,\n steps: [...steps],\n providerOptions: stepProviderOptions,\n timeout,\n headers,\n stopWhen,\n output,\n abortSignal,\n include,\n functionId: telemetry == null ? void 0 : telemetry.functionId,\n metadata: telemetry == null ? void 0 : telemetry.metadata,\n experimental_context\n },\n callbacks: [\n onStepStart,\n globalTelemetry.onStepStart\n ]\n });\n currentModelResponse = await retry(\n () => {\n var _a22;\n return recordSpan({\n name: \"ai.generateText.doGenerate\",\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: \"ai.generateText.doGenerate\",\n telemetry\n }),\n ...baseTelemetryAttributes,\n // model:\n \"ai.model.provider\": stepModel.provider,\n \"ai.model.id\": stepModel.modelId,\n // prompt:\n \"ai.prompt.messages\": {\n input: () => stringifyForTelemetry(promptMessages)\n },\n \"ai.prompt.tools\": {\n // convert the language model level tools:\n input: () => stepTools == null ? void 0 : stepTools.map((tool2) => JSON.stringify(tool2))\n },\n \"ai.prompt.toolChoice\": {\n input: () => stepToolChoice != null ? JSON.stringify(stepToolChoice) : void 0\n },\n // standardized gen-ai llm span attributes:\n \"gen_ai.system\": stepModel.provider,\n \"gen_ai.request.model\": stepModel.modelId,\n \"gen_ai.request.frequency_penalty\": settings.frequencyPenalty,\n \"gen_ai.request.max_tokens\": settings.maxOutputTokens,\n \"gen_ai.request.presence_penalty\": settings.presencePenalty,\n \"gen_ai.request.stop_sequences\": settings.stopSequences,\n \"gen_ai.request.temperature\": (_a22 = settings.temperature) != null ? _a22 : void 0,\n \"gen_ai.request.top_k\": settings.topK,\n \"gen_ai.request.top_p\": settings.topP\n }\n }),\n tracer,\n fn: async (span2) => {\n var _a23, _b2, _c2, _d2, _e2, _f2, _g2, _h2;\n const result = await stepModel.doGenerate({\n ...callSettings2,\n tools: stepTools,\n toolChoice: stepToolChoice,\n responseFormat: await (output == null ? void 0 : output.responseFormat),\n prompt: promptMessages,\n providerOptions: stepProviderOptions,\n abortSignal: mergedAbortSignal,\n headers: headersWithUserAgent\n });\n const responseData = {\n id: (_b2 = (_a23 = result.response) == null ? void 0 : _a23.id) != null ? _b2 : generateId2(),\n timestamp: (_d2 = (_c2 = result.response) == null ? void 0 : _c2.timestamp) != null ? _d2 : /* @__PURE__ */ new Date(),\n modelId: (_f2 = (_e2 = result.response) == null ? void 0 : _e2.modelId) != null ? _f2 : stepModel.modelId,\n headers: (_g2 = result.response) == null ? void 0 : _g2.headers,\n body: (_h2 = result.response) == null ? void 0 : _h2.body\n };\n span2.setAttributes(\n await selectTelemetryAttributes({\n telemetry,\n attributes: {\n \"ai.response.finishReason\": result.finishReason.unified,\n \"ai.response.text\": {\n output: () => extractTextContent(result.content)\n },\n \"ai.response.reasoning\": {\n output: () => extractReasoningContent(result.content)\n },\n \"ai.response.toolCalls\": {\n output: () => {\n const toolCalls = asToolCalls(result.content);\n return toolCalls == null ? void 0 : JSON.stringify(toolCalls);\n }\n },\n \"ai.response.id\": responseData.id,\n \"ai.response.model\": responseData.modelId,\n \"ai.response.timestamp\": responseData.timestamp.toISOString(),\n \"ai.response.providerMetadata\": JSON.stringify(\n result.providerMetadata\n ),\n // TODO rename telemetry attributes to inputTokens and outputTokens\n \"ai.usage.promptTokens\": result.usage.inputTokens.total,\n \"ai.usage.completionTokens\": result.usage.outputTokens.total,\n // standardized gen-ai llm span attributes:\n \"gen_ai.response.finish_reasons\": [\n result.finishReason.unified\n ],\n \"gen_ai.response.id\": responseData.id,\n \"gen_ai.response.model\": responseData.modelId,\n \"gen_ai.usage.input_tokens\": result.usage.inputTokens.total,\n \"gen_ai.usage.output_tokens\": result.usage.outputTokens.total\n }\n })\n );\n return { ...result, response: responseData };\n }\n });\n }\n );\n const stepToolCalls = await Promise.all(\n currentModelResponse.content.filter(\n (part) => part.type === \"tool-call\"\n ).map(\n (toolCall) => parseToolCall({\n toolCall,\n tools,\n repairToolCall,\n system,\n messages: stepInputMessages\n })\n )\n );\n const toolApprovalRequests = {};\n for (const toolCall of stepToolCalls) {\n if (toolCall.invalid) {\n continue;\n }\n const tool2 = tools == null ? void 0 : tools[toolCall.toolName];\n if (tool2 == null) {\n continue;\n }\n if ((tool2 == null ? void 0 : tool2.onInputAvailable) != null) {\n await tool2.onInputAvailable({\n input: toolCall.input,\n toolCallId: toolCall.toolCallId,\n messages: stepInputMessages,\n abortSignal: mergedAbortSignal,\n experimental_context\n });\n }\n if (await isApprovalNeeded({\n tool: tool2,\n toolCall,\n messages: stepInputMessages,\n experimental_context\n })) {\n toolApprovalRequests[toolCall.toolCallId] = {\n type: \"tool-approval-request\",\n approvalId: generateId2(),\n toolCall\n };\n }\n }\n const invalidToolCalls = stepToolCalls.filter(\n (toolCall) => toolCall.invalid && toolCall.dynamic\n );\n clientToolOutputs = [];\n for (const toolCall of invalidToolCalls) {\n clientToolOutputs.push({\n type: \"tool-error\",\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: toolCall.input,\n error: getErrorMessage5(toolCall.error),\n dynamic: true\n });\n }\n clientToolCalls = stepToolCalls.filter(\n (toolCall) => !toolCall.providerExecuted\n );\n if (tools != null) {\n clientToolOutputs.push(\n ...await executeTools({\n toolCalls: clientToolCalls.filter(\n (toolCall) => !toolCall.invalid && toolApprovalRequests[toolCall.toolCallId] == null\n ),\n tools,\n tracer,\n telemetry,\n messages: stepInputMessages,\n abortSignal: mergedAbortSignal,\n experimental_context,\n stepNumber: steps.length,\n model: stepModelInfo,\n onToolCallStart: [\n onToolCallStart,\n globalTelemetry.onToolCallStart\n ],\n onToolCallFinish: [\n onToolCallFinish,\n globalTelemetry.onToolCallFinish\n ]\n })\n );\n }\n for (const toolCall of stepToolCalls) {\n if (!toolCall.providerExecuted)\n continue;\n const tool2 = tools == null ? void 0 : tools[toolCall.toolName];\n if ((tool2 == null ? void 0 : tool2.type) === \"provider\" && tool2.supportsDeferredResults) {\n const hasResultInResponse = currentModelResponse.content.some(\n (part) => part.type === \"tool-result\" && part.toolCallId === toolCall.toolCallId\n );\n if (!hasResultInResponse) {\n pendingDeferredToolCalls.set(toolCall.toolCallId, {\n toolName: toolCall.toolName\n });\n }\n }\n }\n for (const part of currentModelResponse.content) {\n if (part.type === \"tool-result\") {\n pendingDeferredToolCalls.delete(part.toolCallId);\n }\n }\n const stepContent = asContent({\n content: currentModelResponse.content,\n toolCalls: stepToolCalls,\n toolOutputs: clientToolOutputs,\n toolApprovalRequests: Object.values(toolApprovalRequests),\n tools\n });\n responseMessages.push(\n ...await toResponseMessages({\n content: stepContent,\n tools\n })\n );\n const stepRequest = ((_i = include == null ? void 0 : include.requestBody) != null ? _i : true) ? (_j = currentModelResponse.request) != null ? _j : {} : { ...currentModelResponse.request, body: void 0 };\n const stepResponse = {\n ...currentModelResponse.response,\n // deep clone msgs to avoid mutating past messages in multi-step:\n messages: structuredClone(responseMessages),\n // Conditionally include response body:\n body: ((_k = include == null ? void 0 : include.responseBody) != null ? _k : true) ? (_l = currentModelResponse.response) == null ? void 0 : _l.body : void 0\n };\n const stepNumber = steps.length;\n const currentStepResult = new DefaultStepResult({\n stepNumber,\n model: stepModelInfo,\n functionId: telemetry == null ? void 0 : telemetry.functionId,\n metadata: telemetry == null ? void 0 : telemetry.metadata,\n experimental_context,\n content: stepContent,\n finishReason: currentModelResponse.finishReason.unified,\n rawFinishReason: currentModelResponse.finishReason.raw,\n usage: asLanguageModelUsage(currentModelResponse.usage),\n warnings: currentModelResponse.warnings,\n providerMetadata: currentModelResponse.providerMetadata,\n request: stepRequest,\n response: stepResponse\n });\n logWarnings({\n warnings: (_m = currentModelResponse.warnings) != null ? _m : [],\n provider: stepModelInfo.provider,\n model: stepModelInfo.modelId\n });\n steps.push(currentStepResult);\n await notify({\n event: currentStepResult,\n callbacks: [onStepFinish, globalTelemetry.onStepFinish]\n });\n } finally {\n if (stepTimeoutId != null) {\n clearTimeout(stepTimeoutId);\n }\n }\n } while (\n // Continue if:\n // 1. There are client tool calls that have all been executed, OR\n // 2. There are pending deferred results from provider-executed tools\n (clientToolCalls.length > 0 && clientToolOutputs.length === clientToolCalls.length || pendingDeferredToolCalls.size > 0) && // continue until a stop condition is met:\n !await isStopConditionMet({ stopConditions, steps })\n );\n span.setAttributes(\n await selectTelemetryAttributes({\n telemetry,\n attributes: {\n \"ai.response.finishReason\": currentModelResponse.finishReason.unified,\n \"ai.response.text\": {\n output: () => extractTextContent(currentModelResponse.content)\n },\n \"ai.response.reasoning\": {\n output: () => extractReasoningContent(currentModelResponse.content)\n },\n \"ai.response.toolCalls\": {\n output: () => {\n const toolCalls = asToolCalls(currentModelResponse.content);\n return toolCalls == null ? void 0 : JSON.stringify(toolCalls);\n }\n },\n \"ai.response.providerMetadata\": JSON.stringify(\n currentModelResponse.providerMetadata\n ),\n // TODO rename telemetry attributes to inputTokens and outputTokens\n \"ai.usage.promptTokens\": currentModelResponse.usage.inputTokens.total,\n \"ai.usage.completionTokens\": currentModelResponse.usage.outputTokens.total\n }\n })\n );\n const lastStep = steps[steps.length - 1];\n const totalUsage = steps.reduce(\n (totalUsage2, step) => {\n return addLanguageModelUsage(totalUsage2, step.usage);\n },\n {\n inputTokens: void 0,\n outputTokens: void 0,\n totalTokens: void 0,\n reasoningTokens: void 0,\n cachedInputTokens: void 0\n }\n );\n await notify({\n event: {\n stepNumber: lastStep.stepNumber,\n model: lastStep.model,\n functionId: lastStep.functionId,\n metadata: lastStep.metadata,\n experimental_context: lastStep.experimental_context,\n finishReason: lastStep.finishReason,\n rawFinishReason: lastStep.rawFinishReason,\n usage: lastStep.usage,\n content: lastStep.content,\n text: lastStep.text,\n reasoningText: lastStep.reasoningText,\n reasoning: lastStep.reasoning,\n files: lastStep.files,\n sources: lastStep.sources,\n toolCalls: lastStep.toolCalls,\n staticToolCalls: lastStep.staticToolCalls,\n dynamicToolCalls: lastStep.dynamicToolCalls,\n toolResults: lastStep.toolResults,\n staticToolResults: lastStep.staticToolResults,\n dynamicToolResults: lastStep.dynamicToolResults,\n request: lastStep.request,\n response: lastStep.response,\n warnings: lastStep.warnings,\n providerMetadata: lastStep.providerMetadata,\n steps,\n totalUsage\n },\n callbacks: [\n onFinish,\n globalTelemetry.onFinish\n ]\n });\n let resolvedOutput;\n if (lastStep.finishReason === \"stop\") {\n const outputSpecification = output != null ? output : text();\n resolvedOutput = await outputSpecification.parseCompleteOutput(\n { text: lastStep.text },\n {\n response: lastStep.response,\n usage: lastStep.usage,\n finishReason: lastStep.finishReason\n }\n );\n }\n return new DefaultGenerateTextResult({\n steps,\n totalUsage,\n output: resolvedOutput\n });\n }\n });\n } catch (error) {\n throw wrapGatewayError(error);\n }\n}\nasync function executeTools({\n toolCalls,\n tools,\n tracer,\n telemetry,\n messages,\n abortSignal,\n experimental_context,\n stepNumber,\n model,\n onToolCallStart,\n onToolCallFinish\n}) {\n const toolOutputs = await Promise.all(\n toolCalls.map(\n async (toolCall) => executeToolCall({\n toolCall,\n tools,\n tracer,\n telemetry,\n messages,\n abortSignal,\n experimental_context,\n stepNumber,\n model,\n onToolCallStart,\n onToolCallFinish\n })\n )\n );\n return toolOutputs.filter(\n (output) => output != null\n );\n}\nvar DefaultGenerateTextResult = class {\n constructor(options) {\n this.steps = options.steps;\n this._output = options.output;\n this.totalUsage = options.totalUsage;\n }\n get finalStep() {\n return this.steps[this.steps.length - 1];\n }\n get content() {\n return this.finalStep.content;\n }\n get text() {\n return this.finalStep.text;\n }\n get files() {\n return this.finalStep.files;\n }\n get reasoningText() {\n return this.finalStep.reasoningText;\n }\n get reasoning() {\n return this.finalStep.reasoning;\n }\n get toolCalls() {\n return this.finalStep.toolCalls;\n }\n get staticToolCalls() {\n return this.finalStep.staticToolCalls;\n }\n get dynamicToolCalls() {\n return this.finalStep.dynamicToolCalls;\n }\n get toolResults() {\n return this.finalStep.toolResults;\n }\n get staticToolResults() {\n return this.finalStep.staticToolResults;\n }\n get dynamicToolResults() {\n return this.finalStep.dynamicToolResults;\n }\n get sources() {\n return this.finalStep.sources;\n }\n get finishReason() {\n return this.finalStep.finishReason;\n }\n get rawFinishReason() {\n return this.finalStep.rawFinishReason;\n }\n get warnings() {\n return this.finalStep.warnings;\n }\n get providerMetadata() {\n return this.finalStep.providerMetadata;\n }\n get response() {\n return this.finalStep.response;\n }\n get request() {\n return this.finalStep.request;\n }\n get usage() {\n return this.finalStep.usage;\n }\n get experimental_output() {\n return this.output;\n }\n get output() {\n if (this._output == null) {\n throw new NoOutputGeneratedError();\n }\n return this._output;\n }\n};\nfunction asToolCalls(content) {\n const parts = content.filter(\n (part) => part.type === \"tool-call\"\n );\n if (parts.length === 0) {\n return void 0;\n }\n return parts.map((toolCall) => ({\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: toolCall.input\n }));\n}\nfunction asContent({\n content,\n toolCalls,\n toolOutputs,\n toolApprovalRequests,\n tools\n}) {\n const contentParts = [];\n for (const part of content) {\n switch (part.type) {\n case \"text\":\n case \"reasoning\":\n case \"source\":\n contentParts.push(part);\n break;\n case \"file\": {\n contentParts.push({\n type: \"file\",\n file: new DefaultGeneratedFile(part),\n ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n });\n break;\n }\n case \"tool-call\": {\n contentParts.push(\n toolCalls.find((toolCall) => toolCall.toolCallId === part.toolCallId)\n );\n break;\n }\n case \"tool-result\": {\n const toolCall = toolCalls.find(\n (toolCall2) => toolCall2.toolCallId === part.toolCallId\n );\n if (toolCall == null) {\n const tool2 = tools == null ? void 0 : tools[part.toolName];\n const supportsDeferredResults = (tool2 == null ? void 0 : tool2.type) === \"provider\" && tool2.supportsDeferredResults;\n if (!supportsDeferredResults) {\n throw new Error(`Tool call ${part.toolCallId} not found.`);\n }\n if (part.isError) {\n contentParts.push({\n type: \"tool-error\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: void 0,\n error: part.result,\n providerExecuted: true,\n dynamic: part.dynamic\n });\n } else {\n contentParts.push({\n type: \"tool-result\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: void 0,\n output: part.result,\n providerExecuted: true,\n dynamic: part.dynamic\n });\n }\n break;\n }\n if (part.isError) {\n contentParts.push({\n type: \"tool-error\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: toolCall.input,\n error: part.result,\n providerExecuted: true,\n dynamic: toolCall.dynamic\n });\n } else {\n contentParts.push({\n type: \"tool-result\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: toolCall.input,\n output: part.result,\n providerExecuted: true,\n dynamic: toolCall.dynamic\n });\n }\n break;\n }\n case \"tool-approval-request\": {\n const toolCall = toolCalls.find(\n (toolCall2) => toolCall2.toolCallId === part.toolCallId\n );\n if (toolCall == null) {\n throw new ToolCallNotFoundForApprovalError({\n toolCallId: part.toolCallId,\n approvalId: part.approvalId\n });\n }\n contentParts.push({\n type: \"tool-approval-request\",\n approvalId: part.approvalId,\n toolCall\n });\n break;\n }\n }\n }\n return [...contentParts, ...toolOutputs, ...toolApprovalRequests];\n}\n\n// src/generate-text/stream-text.ts\nimport {\n getErrorMessage as getErrorMessage7,\n UnsupportedFunctionalityError as UnsupportedFunctionalityError2\n} from \"@ai-sdk/provider\";\nimport {\n createIdGenerator as createIdGenerator2,\n DelayedPromise,\n isAbortError as isAbortError2\n} from \"@ai-sdk/provider-utils\";\n\n// src/util/prepare-headers.ts\nfunction prepareHeaders(headers, defaultHeaders) {\n const responseHeaders = new Headers(headers != null ? headers : {});\n for (const [key, value] of Object.entries(defaultHeaders)) {\n if (!responseHeaders.has(key)) {\n responseHeaders.set(key, value);\n }\n }\n return responseHeaders;\n}\n\n// src/text-stream/create-text-stream-response.ts\nfunction createTextStreamResponse({\n status,\n statusText,\n headers,\n textStream\n}) {\n return new Response(textStream.pipeThrough(new TextEncoderStream()), {\n status: status != null ? status : 200,\n statusText,\n headers: prepareHeaders(headers, {\n \"content-type\": \"text/plain; charset=utf-8\"\n })\n });\n}\n\n// src/util/write-to-server-response.ts\nfunction writeToServerResponse({\n response,\n status,\n statusText,\n headers,\n stream\n}) {\n const statusCode = status != null ? status : 200;\n if (statusText !== void 0) {\n response.writeHead(statusCode, statusText, headers);\n } else {\n response.writeHead(statusCode, headers);\n }\n const reader = stream.getReader();\n const read = async () => {\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done)\n break;\n const canContinue = response.write(value);\n if (!canContinue) {\n await new Promise((resolve3) => {\n response.once(\"drain\", resolve3);\n });\n }\n }\n } catch (error) {\n throw error;\n } finally {\n response.end();\n }\n };\n read();\n}\n\n// src/text-stream/pipe-text-stream-to-response.ts\nfunction pipeTextStreamToResponse({\n response,\n status,\n statusText,\n headers,\n textStream\n}) {\n writeToServerResponse({\n response,\n status,\n statusText,\n headers: Object.fromEntries(\n prepareHeaders(headers, {\n \"content-type\": \"text/plain; charset=utf-8\"\n }).entries()\n ),\n stream: textStream.pipeThrough(new TextEncoderStream())\n });\n}\n\n// src/ui-message-stream/json-to-sse-transform-stream.ts\nvar JsonToSseTransformStream = class extends TransformStream {\n constructor() {\n super({\n transform(part, controller) {\n controller.enqueue(`data: ${JSON.stringify(part)}\n\n`);\n },\n flush(controller) {\n controller.enqueue(\"data: [DONE]\\n\\n\");\n }\n });\n }\n};\n\n// src/ui-message-stream/ui-message-stream-headers.ts\nvar UI_MESSAGE_STREAM_HEADERS = {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-cache\",\n connection: \"keep-alive\",\n \"x-vercel-ai-ui-message-stream\": \"v1\",\n \"x-accel-buffering\": \"no\"\n // disable nginx buffering\n};\n\n// src/ui-message-stream/create-ui-message-stream-response.ts\nfunction createUIMessageStreamResponse({\n status,\n statusText,\n headers,\n stream,\n consumeSseStream\n}) {\n let sseStream = stream.pipeThrough(new JsonToSseTransformStream());\n if (consumeSseStream) {\n const [stream1, stream2] = sseStream.tee();\n sseStream = stream1;\n consumeSseStream({ stream: stream2 });\n }\n return new Response(sseStream.pipeThrough(new TextEncoderStream()), {\n status,\n statusText,\n headers: prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS)\n });\n}\n\n// src/ui-message-stream/get-response-ui-message-id.ts\nfunction getResponseUIMessageId({\n originalMessages,\n responseMessageId\n}) {\n if (originalMessages == null) {\n return void 0;\n }\n const lastMessage = originalMessages[originalMessages.length - 1];\n return (lastMessage == null ? void 0 : lastMessage.role) === \"assistant\" ? lastMessage.id : typeof responseMessageId === \"function\" ? responseMessageId() : responseMessageId;\n}\n\n// src/ui/process-ui-message-stream.ts\nimport { validateTypes } from \"@ai-sdk/provider-utils\";\n\n// src/ui-message-stream/ui-message-chunks.ts\nimport { z as z7 } from \"zod/v4\";\nimport { lazySchema, zodSchema } from \"@ai-sdk/provider-utils\";\nvar uiMessageChunkSchema = lazySchema(\n () => zodSchema(\n z7.union([\n z7.strictObject({\n type: z7.literal(\"text-start\"),\n id: z7.string(),\n providerMetadata: providerMetadataSchema.optional()\n }),\n z7.strictObject({\n type: z7.literal(\"text-delta\"),\n id: z7.string(),\n delta: z7.string(),\n providerMetadata: providerMetadataSchema.optional()\n }),\n z7.strictObject({\n type: z7.literal(\"text-end\"),\n id: z7.string(),\n providerMetadata: providerMetadataSchema.optional()\n }),\n z7.strictObject({\n type: z7.literal(\"error\"),\n errorText: z7.string()\n }),\n z7.strictObject({\n type: z7.literal(\"tool-input-start\"),\n toolCallId: z7.string(),\n toolName: z7.string(),\n providerExecuted: z7.boolean().optional(),\n providerMetadata: providerMetadataSchema.optional(),\n dynamic: z7.boolean().optional(),\n title: z7.string().optional()\n }),\n z7.strictObject({\n type: z7.literal(\"tool-input-delta\"),\n toolCallId: z7.string(),\n inputTextDelta: z7.string()\n }),\n z7.strictObject({\n type: z7.literal(\"tool-input-available\"),\n toolCallId: z7.string(),\n toolName: z7.string(),\n input: z7.unknown(),\n providerExecuted: z7.boolean().optional(),\n providerMetadata: providerMetadataSchema.optional(),\n dynamic: z7.boolean().optional(),\n title: z7.string().optional()\n }),\n z7.strictObject({\n type: z7.literal(\"tool-input-error\"),\n toolCallId: z7.string(),\n toolName: z7.string(),\n input: z7.unknown(),\n providerExecuted: z7.boolean().optional(),\n providerMetadata: providerMetadataSchema.optional(),\n dynamic: z7.boolean().optional(),\n errorText: z7.string(),\n title: z7.string().optional()\n }),\n z7.strictObject({\n type: z7.literal(\"tool-approval-request\"),\n approvalId: z7.string(),\n toolCallId: z7.string()\n }),\n z7.strictObject({\n type: z7.literal(\"tool-output-available\"),\n toolCallId: z7.string(),\n output: z7.unknown(),\n providerExecuted: z7.boolean().optional(),\n dynamic: z7.boolean().optional(),\n preliminary: z7.boolean().optional()\n }),\n z7.strictObject({\n type: z7.literal(\"tool-output-error\"),\n toolCallId: z7.string(),\n errorText: z7.string(),\n providerExecuted: z7.boolean().optional(),\n dynamic: z7.boolean().optional()\n }),\n z7.strictObject({\n type: z7.literal(\"tool-output-denied\"),\n toolCallId: z7.string()\n }),\n z7.strictObject({\n type: z7.literal(\"reasoning-start\"),\n id: z7.string(),\n providerMetadata: providerMetadataSchema.optional()\n }),\n z7.strictObject({\n type: z7.literal(\"reasoning-delta\"),\n id: z7.string(),\n delta: z7.string(),\n providerMetadata: providerMetadataSchema.optional()\n }),\n z7.strictObject({\n type: z7.literal(\"reasoning-end\"),\n id: z7.string(),\n providerMetadata: providerMetadataSchema.optional()\n }),\n z7.strictObject({\n type: z7.literal(\"source-url\"),\n sourceId: z7.string(),\n url: z7.string(),\n title: z7.string().optional(),\n providerMetadata: providerMetadataSchema.optional()\n }),\n z7.strictObject({\n type: z7.literal(\"source-document\"),\n sourceId: z7.string(),\n mediaType: z7.string(),\n title: z7.string(),\n filename: z7.string().optional(),\n providerMetadata: providerMetadataSchema.optional()\n }),\n z7.strictObject({\n type: z7.literal(\"file\"),\n url: z7.string(),\n mediaType: z7.string(),\n providerMetadata: providerMetadataSchema.optional()\n }),\n z7.strictObject({\n type: z7.custom(\n (value) => typeof value === \"string\" && value.startsWith(\"data-\"),\n { message: 'Type must start with \"data-\"' }\n ),\n id: z7.string().optional(),\n data: z7.unknown(),\n transient: z7.boolean().optional()\n }),\n z7.strictObject({\n type: z7.literal(\"start-step\")\n }),\n z7.strictObject({\n type: z7.literal(\"finish-step\")\n }),\n z7.strictObject({\n type: z7.literal(\"start\"),\n messageId: z7.string().optional(),\n messageMetadata: z7.unknown().optional()\n }),\n z7.strictObject({\n type: z7.literal(\"finish\"),\n finishReason: z7.enum([\n \"stop\",\n \"length\",\n \"content-filter\",\n \"tool-calls\",\n \"error\",\n \"other\"\n ]).optional(),\n messageMetadata: z7.unknown().optional()\n }),\n z7.strictObject({\n type: z7.literal(\"abort\"),\n reason: z7.string().optional()\n }),\n z7.strictObject({\n type: z7.literal(\"message-metadata\"),\n messageMetadata: z7.unknown()\n })\n ])\n )\n);\nfunction isDataUIMessageChunk(chunk) {\n return chunk.type.startsWith(\"data-\");\n}\n\n// src/ui/ui-messages.ts\nfunction isDataUIPart(part) {\n return part.type.startsWith(\"data-\");\n}\nfunction isTextUIPart(part) {\n return part.type === \"text\";\n}\nfunction isFileUIPart(part) {\n return part.type === \"file\";\n}\nfunction isReasoningUIPart(part) {\n return part.type === \"reasoning\";\n}\nfunction isStaticToolUIPart(part) {\n return part.type.startsWith(\"tool-\");\n}\nfunction isDynamicToolUIPart(part) {\n return part.type === \"dynamic-tool\";\n}\nfunction isToolUIPart(part) {\n return isStaticToolUIPart(part) || isDynamicToolUIPart(part);\n}\nvar isToolOrDynamicToolUIPart = isToolUIPart;\nfunction getStaticToolName(part) {\n return part.type.split(\"-\").slice(1).join(\"-\");\n}\nfunction getToolName(part) {\n return isDynamicToolUIPart(part) ? part.toolName : getStaticToolName(part);\n}\nvar getToolOrDynamicToolName = getToolName;\n\n// src/ui/process-ui-message-stream.ts\nfunction createStreamingUIMessageState({\n lastMessage,\n messageId\n}) {\n return {\n message: (lastMessage == null ? void 0 : lastMessage.role) === \"assistant\" ? lastMessage : {\n id: messageId,\n metadata: void 0,\n role: \"assistant\",\n parts: []\n },\n activeTextParts: {},\n activeReasoningParts: {},\n partialToolCalls: {}\n };\n}\nfunction processUIMessageStream({\n stream,\n messageMetadataSchema,\n dataPartSchemas,\n runUpdateMessageJob,\n onError,\n onToolCall,\n onData\n}) {\n return stream.pipeThrough(\n new TransformStream({\n async transform(chunk, controller) {\n await runUpdateMessageJob(async ({ state, write }) => {\n var _a21, _b, _c, _d;\n function getToolInvocation(toolCallId) {\n const toolInvocations = state.message.parts.filter(isToolUIPart);\n const toolInvocation = toolInvocations.find(\n (invocation) => invocation.toolCallId === toolCallId\n );\n if (toolInvocation == null) {\n throw new UIMessageStreamError({\n chunkType: \"tool-invocation\",\n chunkId: toolCallId,\n message: `No tool invocation found for tool call ID \"${toolCallId}\".`\n });\n }\n return toolInvocation;\n }\n function updateToolPart(options) {\n var _a22;\n const part = state.message.parts.find(\n (part2) => isStaticToolUIPart(part2) && part2.toolCallId === options.toolCallId\n );\n const anyOptions = options;\n const anyPart = part;\n if (part != null) {\n part.state = options.state;\n anyPart.input = anyOptions.input;\n anyPart.output = anyOptions.output;\n anyPart.errorText = anyOptions.errorText;\n anyPart.rawInput = anyOptions.rawInput;\n anyPart.preliminary = anyOptions.preliminary;\n if (options.title !== void 0) {\n anyPart.title = options.title;\n }\n anyPart.providerExecuted = (_a22 = anyOptions.providerExecuted) != null ? _a22 : part.providerExecuted;\n if (anyOptions.providerMetadata != null) {\n part.callProviderMetadata = anyOptions.providerMetadata;\n }\n } else {\n state.message.parts.push({\n type: `tool-${options.toolName}`,\n toolCallId: options.toolCallId,\n state: options.state,\n title: options.title,\n input: anyOptions.input,\n output: anyOptions.output,\n rawInput: anyOptions.rawInput,\n errorText: anyOptions.errorText,\n providerExecuted: anyOptions.providerExecuted,\n preliminary: anyOptions.preliminary,\n ...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}\n });\n }\n }\n function updateDynamicToolPart(options) {\n var _a22, _b2;\n const part = state.message.parts.find(\n (part2) => part2.type === \"dynamic-tool\" && part2.toolCallId === options.toolCallId\n );\n const anyOptions = options;\n const anyPart = part;\n if (part != null) {\n part.state = options.state;\n anyPart.toolName = options.toolName;\n anyPart.input = anyOptions.input;\n anyPart.output = anyOptions.output;\n anyPart.errorText = anyOptions.errorText;\n anyPart.rawInput = (_a22 = anyOptions.rawInput) != null ? _a22 : anyPart.rawInput;\n anyPart.preliminary = anyOptions.preliminary;\n if (options.title !== void 0) {\n anyPart.title = options.title;\n }\n anyPart.providerExecuted = (_b2 = anyOptions.providerExecuted) != null ? _b2 : part.providerExecuted;\n if (anyOptions.providerMetadata != null) {\n part.callProviderMetadata = anyOptions.providerMetadata;\n }\n } else {\n state.message.parts.push({\n type: \"dynamic-tool\",\n toolName: options.toolName,\n toolCallId: options.toolCallId,\n state: options.state,\n input: anyOptions.input,\n output: anyOptions.output,\n errorText: anyOptions.errorText,\n preliminary: anyOptions.preliminary,\n providerExecuted: anyOptions.providerExecuted,\n title: options.title,\n ...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}\n });\n }\n }\n async function updateMessageMetadata(metadata) {\n if (metadata != null) {\n const mergedMetadata = state.message.metadata != null ? mergeObjects(state.message.metadata, metadata) : metadata;\n if (messageMetadataSchema != null) {\n await validateTypes({\n value: mergedMetadata,\n schema: messageMetadataSchema,\n context: {\n field: \"message.metadata\",\n entityId: state.message.id\n }\n });\n }\n state.message.metadata = mergedMetadata;\n }\n }\n switch (chunk.type) {\n case \"text-start\": {\n const textPart = {\n type: \"text\",\n text: \"\",\n providerMetadata: chunk.providerMetadata,\n state: \"streaming\"\n };\n state.activeTextParts[chunk.id] = textPart;\n state.message.parts.push(textPart);\n write();\n break;\n }\n case \"text-delta\": {\n const textPart = state.activeTextParts[chunk.id];\n if (textPart == null) {\n throw new UIMessageStreamError({\n chunkType: \"text-delta\",\n chunkId: chunk.id,\n message: `Received text-delta for missing text part with ID \"${chunk.id}\". Ensure a \"text-start\" chunk is sent before any \"text-delta\" chunks.`\n });\n }\n textPart.text += chunk.delta;\n textPart.providerMetadata = (_a21 = chunk.providerMetadata) != null ? _a21 : textPart.providerMetadata;\n write();\n break;\n }\n case \"text-end\": {\n const textPart = state.activeTextParts[chunk.id];\n if (textPart == null) {\n throw new UIMessageStreamError({\n chunkType: \"text-end\",\n chunkId: chunk.id,\n message: `Received text-end for missing text part with ID \"${chunk.id}\". Ensure a \"text-start\" chunk is sent before any \"text-end\" chunks.`\n });\n }\n textPart.state = \"done\";\n textPart.providerMetadata = (_b = chunk.providerMetadata) != null ? _b : textPart.providerMetadata;\n delete state.activeTextParts[chunk.id];\n write();\n break;\n }\n case \"reasoning-start\": {\n const reasoningPart = {\n type: \"reasoning\",\n text: \"\",\n providerMetadata: chunk.providerMetadata,\n state: \"streaming\"\n };\n state.activeReasoningParts[chunk.id] = reasoningPart;\n state.message.parts.push(reasoningPart);\n write();\n break;\n }\n case \"reasoning-delta\": {\n const reasoningPart = state.activeReasoningParts[chunk.id];\n if (reasoningPart == null) {\n throw new UIMessageStreamError({\n chunkType: \"reasoning-delta\",\n chunkId: chunk.id,\n message: `Received reasoning-delta for missing reasoning part with ID \"${chunk.id}\". Ensure a \"reasoning-start\" chunk is sent before any \"reasoning-delta\" chunks.`\n });\n }\n reasoningPart.text += chunk.delta;\n reasoningPart.providerMetadata = (_c = chunk.providerMetadata) != null ? _c : reasoningPart.providerMetadata;\n write();\n break;\n }\n case \"reasoning-end\": {\n const reasoningPart = state.activeReasoningParts[chunk.id];\n if (reasoningPart == null) {\n throw new UIMessageStreamError({\n chunkType: \"reasoning-end\",\n chunkId: chunk.id,\n message: `Received reasoning-end for missing reasoning part with ID \"${chunk.id}\". Ensure a \"reasoning-start\" chunk is sent before any \"reasoning-end\" chunks.`\n });\n }\n reasoningPart.providerMetadata = (_d = chunk.providerMetadata) != null ? _d : reasoningPart.providerMetadata;\n reasoningPart.state = \"done\";\n delete state.activeReasoningParts[chunk.id];\n write();\n break;\n }\n case \"file\": {\n state.message.parts.push({\n type: \"file\",\n mediaType: chunk.mediaType,\n url: chunk.url,\n ...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}\n });\n write();\n break;\n }\n case \"source-url\": {\n state.message.parts.push({\n type: \"source-url\",\n sourceId: chunk.sourceId,\n url: chunk.url,\n title: chunk.title,\n providerMetadata: chunk.providerMetadata\n });\n write();\n break;\n }\n case \"source-document\": {\n state.message.parts.push({\n type: \"source-document\",\n sourceId: chunk.sourceId,\n mediaType: chunk.mediaType,\n title: chunk.title,\n filename: chunk.filename,\n providerMetadata: chunk.providerMetadata\n });\n write();\n break;\n }\n case \"tool-input-start\": {\n const toolInvocations = state.message.parts.filter(isStaticToolUIPart);\n state.partialToolCalls[chunk.toolCallId] = {\n text: \"\",\n toolName: chunk.toolName,\n index: toolInvocations.length,\n dynamic: chunk.dynamic,\n title: chunk.title\n };\n if (chunk.dynamic) {\n updateDynamicToolPart({\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n state: \"input-streaming\",\n input: void 0,\n providerExecuted: chunk.providerExecuted,\n title: chunk.title,\n providerMetadata: chunk.providerMetadata\n });\n } else {\n updateToolPart({\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n state: \"input-streaming\",\n input: void 0,\n providerExecuted: chunk.providerExecuted,\n title: chunk.title,\n providerMetadata: chunk.providerMetadata\n });\n }\n write();\n break;\n }\n case \"tool-input-delta\": {\n const partialToolCall = state.partialToolCalls[chunk.toolCallId];\n if (partialToolCall == null) {\n throw new UIMessageStreamError({\n chunkType: \"tool-input-delta\",\n chunkId: chunk.toolCallId,\n message: `Received tool-input-delta for missing tool call with ID \"${chunk.toolCallId}\". Ensure a \"tool-input-start\" chunk is sent before any \"tool-input-delta\" chunks.`\n });\n }\n partialToolCall.text += chunk.inputTextDelta;\n const { value: partialArgs } = await parsePartialJson(\n partialToolCall.text\n );\n if (partialToolCall.dynamic) {\n updateDynamicToolPart({\n toolCallId: chunk.toolCallId,\n toolName: partialToolCall.toolName,\n state: \"input-streaming\",\n input: partialArgs,\n title: partialToolCall.title\n });\n } else {\n updateToolPart({\n toolCallId: chunk.toolCallId,\n toolName: partialToolCall.toolName,\n state: \"input-streaming\",\n input: partialArgs,\n title: partialToolCall.title\n });\n }\n write();\n break;\n }\n case \"tool-input-available\": {\n if (chunk.dynamic) {\n updateDynamicToolPart({\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n state: \"input-available\",\n input: chunk.input,\n providerExecuted: chunk.providerExecuted,\n providerMetadata: chunk.providerMetadata,\n title: chunk.title\n });\n } else {\n updateToolPart({\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n state: \"input-available\",\n input: chunk.input,\n providerExecuted: chunk.providerExecuted,\n providerMetadata: chunk.providerMetadata,\n title: chunk.title\n });\n }\n write();\n if (onToolCall && !chunk.providerExecuted) {\n await onToolCall({\n toolCall: chunk\n });\n }\n break;\n }\n case \"tool-input-error\": {\n const existingPart = state.message.parts.filter(isToolUIPart).find((p) => p.toolCallId === chunk.toolCallId);\n const isDynamic = existingPart != null ? existingPart.type === \"dynamic-tool\" : !!chunk.dynamic;\n if (isDynamic) {\n updateDynamicToolPart({\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n state: \"output-error\",\n input: chunk.input,\n errorText: chunk.errorText,\n providerExecuted: chunk.providerExecuted,\n providerMetadata: chunk.providerMetadata\n });\n } else {\n updateToolPart({\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n state: \"output-error\",\n input: void 0,\n rawInput: chunk.input,\n errorText: chunk.errorText,\n providerExecuted: chunk.providerExecuted,\n providerMetadata: chunk.providerMetadata\n });\n }\n write();\n break;\n }\n case \"tool-approval-request\": {\n const toolInvocation = getToolInvocation(chunk.toolCallId);\n toolInvocation.state = \"approval-requested\";\n toolInvocation.approval = { id: chunk.approvalId };\n write();\n break;\n }\n case \"tool-output-denied\": {\n const toolInvocation = getToolInvocation(chunk.toolCallId);\n toolInvocation.state = \"output-denied\";\n write();\n break;\n }\n case \"tool-output-available\": {\n const toolInvocation = getToolInvocation(chunk.toolCallId);\n if (toolInvocation.type === \"dynamic-tool\") {\n updateDynamicToolPart({\n toolCallId: chunk.toolCallId,\n toolName: toolInvocation.toolName,\n state: \"output-available\",\n input: toolInvocation.input,\n output: chunk.output,\n preliminary: chunk.preliminary,\n providerExecuted: chunk.providerExecuted,\n title: toolInvocation.title\n });\n } else {\n updateToolPart({\n toolCallId: chunk.toolCallId,\n toolName: getStaticToolName(toolInvocation),\n state: \"output-available\",\n input: toolInvocation.input,\n output: chunk.output,\n providerExecuted: chunk.providerExecuted,\n preliminary: chunk.preliminary,\n title: toolInvocation.title\n });\n }\n write();\n break;\n }\n case \"tool-output-error\": {\n const toolInvocation = getToolInvocation(chunk.toolCallId);\n if (toolInvocation.type === \"dynamic-tool\") {\n updateDynamicToolPart({\n toolCallId: chunk.toolCallId,\n toolName: toolInvocation.toolName,\n state: \"output-error\",\n input: toolInvocation.input,\n errorText: chunk.errorText,\n providerExecuted: chunk.providerExecuted,\n title: toolInvocation.title\n });\n } else {\n updateToolPart({\n toolCallId: chunk.toolCallId,\n toolName: getStaticToolName(toolInvocation),\n state: \"output-error\",\n input: toolInvocation.input,\n rawInput: toolInvocation.rawInput,\n errorText: chunk.errorText,\n providerExecuted: chunk.providerExecuted,\n title: toolInvocation.title\n });\n }\n write();\n break;\n }\n case \"start-step\": {\n state.message.parts.push({ type: \"step-start\" });\n break;\n }\n case \"finish-step\": {\n state.activeTextParts = {};\n state.activeReasoningParts = {};\n break;\n }\n case \"start\": {\n if (chunk.messageId != null) {\n state.message.id = chunk.messageId;\n }\n await updateMessageMetadata(chunk.messageMetadata);\n if (chunk.messageId != null || chunk.messageMetadata != null) {\n write();\n }\n break;\n }\n case \"finish\": {\n if (chunk.finishReason != null) {\n state.finishReason = chunk.finishReason;\n }\n await updateMessageMetadata(chunk.messageMetadata);\n if (chunk.messageMetadata != null) {\n write();\n }\n break;\n }\n case \"message-metadata\": {\n await updateMessageMetadata(chunk.messageMetadata);\n if (chunk.messageMetadata != null) {\n write();\n }\n break;\n }\n case \"error\": {\n onError == null ? void 0 : onError(new Error(chunk.errorText));\n break;\n }\n default: {\n if (isDataUIMessageChunk(chunk)) {\n if ((dataPartSchemas == null ? void 0 : dataPartSchemas[chunk.type]) != null) {\n const partIdx = state.message.parts.findIndex(\n (p) => \"id\" in p && \"data\" in p && p.id === chunk.id && p.type === chunk.type\n );\n const actualPartIdx = partIdx >= 0 ? partIdx : state.message.parts.length;\n await validateTypes({\n value: chunk.data,\n schema: dataPartSchemas[chunk.type],\n context: {\n field: `message.parts[${actualPartIdx}].data`,\n entityName: chunk.type,\n entityId: chunk.id\n }\n });\n }\n const dataChunk = chunk;\n if (dataChunk.transient) {\n onData == null ? void 0 : onData(dataChunk);\n break;\n }\n const existingUIPart = dataChunk.id != null ? state.message.parts.find(\n (chunkArg) => dataChunk.type === chunkArg.type && dataChunk.id === chunkArg.id\n ) : void 0;\n if (existingUIPart != null) {\n existingUIPart.data = dataChunk.data;\n } else {\n state.message.parts.push(dataChunk);\n }\n onData == null ? void 0 : onData(dataChunk);\n write();\n }\n }\n }\n controller.enqueue(chunk);\n });\n }\n })\n );\n}\n\n// src/ui-message-stream/handle-ui-message-stream-finish.ts\nfunction handleUIMessageStreamFinish({\n messageId,\n originalMessages = [],\n onStepFinish,\n onFinish,\n onError,\n stream\n}) {\n let lastMessage = originalMessages == null ? void 0 : originalMessages[originalMessages.length - 1];\n if ((lastMessage == null ? void 0 : lastMessage.role) !== \"assistant\") {\n lastMessage = void 0;\n } else {\n messageId = lastMessage.id;\n }\n let isAborted = false;\n const idInjectedStream = stream.pipeThrough(\n new TransformStream({\n transform(chunk, controller) {\n if (chunk.type === \"start\") {\n const startChunk = chunk;\n if (startChunk.messageId == null && messageId != null) {\n startChunk.messageId = messageId;\n }\n }\n if (chunk.type === \"abort\") {\n isAborted = true;\n }\n controller.enqueue(chunk);\n }\n })\n );\n if (onFinish == null && onStepFinish == null) {\n return idInjectedStream;\n }\n const state = createStreamingUIMessageState({\n lastMessage: lastMessage ? structuredClone(lastMessage) : void 0,\n messageId: messageId != null ? messageId : \"\"\n // will be overridden by the stream\n });\n const runUpdateMessageJob = async (job) => {\n await job({ state, write: () => {\n } });\n };\n let finishCalled = false;\n const callOnFinish = async () => {\n if (finishCalled || !onFinish) {\n return;\n }\n finishCalled = true;\n const isContinuation = state.message.id === (lastMessage == null ? void 0 : lastMessage.id);\n await onFinish({\n isAborted,\n isContinuation,\n responseMessage: state.message,\n messages: [\n ...isContinuation ? originalMessages.slice(0, -1) : originalMessages,\n state.message\n ],\n finishReason: state.finishReason\n });\n };\n const callOnStepFinish = async () => {\n if (!onStepFinish) {\n return;\n }\n const isContinuation = state.message.id === (lastMessage == null ? void 0 : lastMessage.id);\n try {\n await onStepFinish({\n isContinuation,\n responseMessage: structuredClone(state.message),\n messages: [\n ...isContinuation ? originalMessages.slice(0, -1) : originalMessages,\n structuredClone(state.message)\n ]\n });\n } catch (error) {\n onError(error);\n }\n };\n return processUIMessageStream({\n stream: idInjectedStream,\n runUpdateMessageJob,\n onError\n }).pipeThrough(\n new TransformStream({\n async transform(chunk, controller) {\n if (chunk.type === \"finish-step\") {\n await callOnStepFinish();\n }\n controller.enqueue(chunk);\n },\n // @ts-expect-error cancel is still new and missing from types https://developer.mozilla.org/en-US/docs/Web/API/TransformStream#browser_compatibility\n async cancel() {\n await callOnFinish();\n },\n async flush() {\n await callOnFinish();\n }\n })\n );\n}\n\n// src/ui-message-stream/pipe-ui-message-stream-to-response.ts\nfunction pipeUIMessageStreamToResponse({\n response,\n status,\n statusText,\n headers,\n stream,\n consumeSseStream\n}) {\n let sseStream = stream.pipeThrough(new JsonToSseTransformStream());\n if (consumeSseStream) {\n const [stream1, stream2] = sseStream.tee();\n sseStream = stream1;\n consumeSseStream({ stream: stream2 });\n }\n writeToServerResponse({\n response,\n status,\n statusText,\n headers: Object.fromEntries(\n prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS).entries()\n ),\n stream: sseStream.pipeThrough(new TextEncoderStream())\n });\n}\n\n// src/util/async-iterable-stream.ts\nfunction createAsyncIterableStream(source) {\n const stream = source.pipeThrough(new TransformStream());\n stream[Symbol.asyncIterator] = function() {\n const reader = this.getReader();\n let finished = false;\n async function cleanup(cancelStream) {\n var _a21;\n if (finished)\n return;\n finished = true;\n try {\n if (cancelStream) {\n await ((_a21 = reader.cancel) == null ? void 0 : _a21.call(reader));\n }\n } finally {\n try {\n reader.releaseLock();\n } catch (e) {\n }\n }\n }\n return {\n /**\n * Reads the next chunk from the stream.\n * @returns A promise resolving to the next IteratorResult.\n */\n async next() {\n if (finished) {\n return { done: true, value: void 0 };\n }\n const { done, value } = await reader.read();\n if (done) {\n await cleanup(true);\n return { done: true, value: void 0 };\n }\n return { done: false, value };\n },\n /**\n * May be called on early exit (e.g., break from for-await) or after completion.\n * Ensures the stream is cancelled and resources are released.\n * @returns A promise resolving to a completed IteratorResult.\n */\n async return() {\n await cleanup(true);\n return { done: true, value: void 0 };\n },\n /**\n * Called on early exit with error.\n * Ensures the stream is cancelled and resources are released, then rethrows the error.\n * @param err The error to throw.\n * @returns A promise that rejects with the provided error.\n */\n async throw(err) {\n await cleanup(true);\n throw err;\n }\n };\n };\n return stream;\n}\n\n// src/util/consume-stream.ts\nasync function consumeStream({\n stream,\n onError\n}) {\n const reader = stream.getReader();\n try {\n while (true) {\n const { done } = await reader.read();\n if (done)\n break;\n }\n } catch (error) {\n onError == null ? void 0 : onError(error);\n } finally {\n reader.releaseLock();\n }\n}\n\n// src/util/create-resolvable-promise.ts\nfunction createResolvablePromise() {\n let resolve3;\n let reject;\n const promise = new Promise((res, rej) => {\n resolve3 = res;\n reject = rej;\n });\n return {\n promise,\n resolve: resolve3,\n reject\n };\n}\n\n// src/util/create-stitchable-stream.ts\nfunction createStitchableStream() {\n let innerStreamReaders = [];\n let controller = null;\n let isClosed = false;\n let waitForNewStream = createResolvablePromise();\n const terminate = () => {\n isClosed = true;\n waitForNewStream.resolve();\n innerStreamReaders.forEach((reader) => reader.cancel());\n innerStreamReaders = [];\n controller == null ? void 0 : controller.close();\n };\n const processPull = async () => {\n if (isClosed && innerStreamReaders.length === 0) {\n controller == null ? void 0 : controller.close();\n return;\n }\n if (innerStreamReaders.length === 0) {\n waitForNewStream = createResolvablePromise();\n await waitForNewStream.promise;\n return processPull();\n }\n try {\n const { value, done } = await innerStreamReaders[0].read();\n if (done) {\n innerStreamReaders.shift();\n if (innerStreamReaders.length === 0 && isClosed) {\n controller == null ? void 0 : controller.close();\n } else {\n await processPull();\n }\n } else {\n controller == null ? void 0 : controller.enqueue(value);\n }\n } catch (error) {\n controller == null ? void 0 : controller.error(error);\n innerStreamReaders.shift();\n terminate();\n }\n };\n return {\n stream: new ReadableStream({\n start(controllerParam) {\n controller = controllerParam;\n },\n pull: processPull,\n async cancel() {\n for (const reader of innerStreamReaders) {\n await reader.cancel();\n }\n innerStreamReaders = [];\n isClosed = true;\n }\n }),\n addStream: (innerStream) => {\n if (isClosed) {\n throw new Error(\"Cannot add inner stream: outer stream is closed\");\n }\n innerStreamReaders.push(innerStream.getReader());\n waitForNewStream.resolve();\n },\n /**\n * Gracefully close the outer stream. This will let the inner streams\n * finish processing and then close the outer stream.\n */\n close: () => {\n isClosed = true;\n waitForNewStream.resolve();\n if (innerStreamReaders.length === 0) {\n controller == null ? void 0 : controller.close();\n }\n },\n /**\n * Immediately close the outer stream. This will cancel all inner streams\n * and close the outer stream.\n */\n terminate\n };\n}\n\n// src/generate-text/run-tools-transformation.ts\nimport {\n getErrorMessage as getErrorMessage6\n} from \"@ai-sdk/provider-utils\";\nfunction runToolsTransformation({\n tools,\n generatorStream,\n tracer,\n telemetry,\n system,\n messages,\n abortSignal,\n repairToolCall,\n experimental_context,\n generateId: generateId2,\n stepNumber,\n model,\n onToolCallStart,\n onToolCallFinish\n}) {\n let toolResultsStreamController = null;\n const toolResultsStream = new ReadableStream({\n start(controller) {\n toolResultsStreamController = controller;\n }\n });\n const outstandingToolResults = /* @__PURE__ */ new Set();\n const toolInputs = /* @__PURE__ */ new Map();\n const toolCallsByToolCallId = /* @__PURE__ */ new Map();\n let canClose = false;\n let finishChunk = void 0;\n function attemptClose() {\n if (canClose && outstandingToolResults.size === 0) {\n if (finishChunk != null) {\n toolResultsStreamController.enqueue(finishChunk);\n }\n toolResultsStreamController.close();\n }\n }\n const forwardStream = new TransformStream({\n async transform(chunk, controller) {\n const chunkType = chunk.type;\n switch (chunkType) {\n case \"stream-start\":\n case \"text-start\":\n case \"text-delta\":\n case \"text-end\":\n case \"reasoning-start\":\n case \"reasoning-delta\":\n case \"reasoning-end\":\n case \"tool-input-start\":\n case \"tool-input-delta\":\n case \"tool-input-end\":\n case \"source\":\n case \"response-metadata\":\n case \"error\":\n case \"raw\": {\n controller.enqueue(chunk);\n break;\n }\n case \"file\": {\n controller.enqueue({\n type: \"file\",\n file: new DefaultGeneratedFileWithType({\n data: chunk.data,\n mediaType: chunk.mediaType\n }),\n ...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}\n });\n break;\n }\n case \"finish\": {\n finishChunk = {\n type: \"finish\",\n finishReason: chunk.finishReason.unified,\n rawFinishReason: chunk.finishReason.raw,\n usage: asLanguageModelUsage(chunk.usage),\n providerMetadata: chunk.providerMetadata\n };\n break;\n }\n case \"tool-approval-request\": {\n const toolCall = toolCallsByToolCallId.get(chunk.toolCallId);\n if (toolCall == null) {\n toolResultsStreamController.enqueue({\n type: \"error\",\n error: new ToolCallNotFoundForApprovalError({\n toolCallId: chunk.toolCallId,\n approvalId: chunk.approvalId\n })\n });\n break;\n }\n controller.enqueue({\n type: \"tool-approval-request\",\n approvalId: chunk.approvalId,\n toolCall\n });\n break;\n }\n case \"tool-call\": {\n try {\n const toolCall = await parseToolCall({\n toolCall: chunk,\n tools,\n repairToolCall,\n system,\n messages\n });\n toolCallsByToolCallId.set(toolCall.toolCallId, toolCall);\n controller.enqueue(toolCall);\n if (toolCall.invalid) {\n toolResultsStreamController.enqueue({\n type: \"tool-error\",\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: toolCall.input,\n error: getErrorMessage6(toolCall.error),\n dynamic: true,\n title: toolCall.title\n });\n break;\n }\n const tool2 = tools == null ? void 0 : tools[toolCall.toolName];\n if (tool2 == null) {\n break;\n }\n if (tool2.onInputAvailable != null) {\n await tool2.onInputAvailable({\n input: toolCall.input,\n toolCallId: toolCall.toolCallId,\n messages,\n abortSignal,\n experimental_context\n });\n }\n if (await isApprovalNeeded({\n tool: tool2,\n toolCall,\n messages,\n experimental_context\n })) {\n toolResultsStreamController.enqueue({\n type: \"tool-approval-request\",\n approvalId: generateId2(),\n toolCall\n });\n break;\n }\n toolInputs.set(toolCall.toolCallId, toolCall.input);\n if (tool2.execute != null && toolCall.providerExecuted !== true) {\n const toolExecutionId = generateId2();\n outstandingToolResults.add(toolExecutionId);\n executeToolCall({\n toolCall,\n tools,\n tracer,\n telemetry,\n messages,\n abortSignal,\n experimental_context,\n stepNumber,\n model,\n onToolCallStart,\n onToolCallFinish,\n onPreliminaryToolResult: (result) => {\n toolResultsStreamController.enqueue(result);\n }\n }).then((result) => {\n toolResultsStreamController.enqueue(result);\n }).catch((error) => {\n toolResultsStreamController.enqueue({\n type: \"error\",\n error\n });\n }).finally(() => {\n outstandingToolResults.delete(toolExecutionId);\n attemptClose();\n });\n }\n } catch (error) {\n toolResultsStreamController.enqueue({ type: \"error\", error });\n }\n break;\n }\n case \"tool-result\": {\n const toolName = chunk.toolName;\n if (chunk.isError) {\n toolResultsStreamController.enqueue({\n type: \"tool-error\",\n toolCallId: chunk.toolCallId,\n toolName,\n input: toolInputs.get(chunk.toolCallId),\n providerExecuted: true,\n error: chunk.result,\n dynamic: chunk.dynamic\n });\n } else {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: chunk.toolCallId,\n toolName,\n input: toolInputs.get(chunk.toolCallId),\n output: chunk.result,\n providerExecuted: true,\n dynamic: chunk.dynamic\n });\n }\n break;\n }\n default: {\n const _exhaustiveCheck = chunkType;\n throw new Error(`Unhandled chunk type: ${_exhaustiveCheck}`);\n }\n }\n },\n flush() {\n canClose = true;\n attemptClose();\n }\n });\n return new ReadableStream({\n async start(controller) {\n return Promise.all([\n generatorStream.pipeThrough(forwardStream).pipeTo(\n new WritableStream({\n write(chunk) {\n controller.enqueue(chunk);\n },\n close() {\n }\n })\n ),\n toolResultsStream.pipeTo(\n new WritableStream({\n write(chunk) {\n controller.enqueue(chunk);\n },\n close() {\n controller.close();\n }\n })\n )\n ]);\n }\n });\n}\n\n// src/generate-text/stream-text.ts\nvar originalGenerateId2 = createIdGenerator2({\n prefix: \"aitxt\",\n size: 24\n});\nfunction streamText({\n model,\n tools,\n toolChoice,\n system,\n prompt,\n messages,\n maxRetries,\n abortSignal,\n timeout,\n headers,\n stopWhen = stepCountIs(1),\n experimental_output,\n output = experimental_output,\n experimental_telemetry: telemetry,\n prepareStep,\n providerOptions,\n experimental_activeTools,\n activeTools = experimental_activeTools,\n experimental_repairToolCall: repairToolCall,\n experimental_transform: transform,\n experimental_download: download2,\n includeRawChunks = false,\n onChunk,\n onError = ({ error }) => {\n console.error(error);\n },\n onFinish,\n onAbort,\n onStepFinish,\n experimental_onStart: onStart,\n experimental_onStepStart: onStepStart,\n experimental_onToolCallStart: onToolCallStart,\n experimental_onToolCallFinish: onToolCallFinish,\n experimental_context,\n experimental_include: include,\n _internal: { now: now2 = now, generateId: generateId2 = originalGenerateId2 } = {},\n ...settings\n}) {\n const totalTimeoutMs = getTotalTimeoutMs(timeout);\n const stepTimeoutMs = getStepTimeoutMs(timeout);\n const chunkTimeoutMs = getChunkTimeoutMs(timeout);\n const stepAbortController = stepTimeoutMs != null ? new AbortController() : void 0;\n const chunkAbortController = chunkTimeoutMs != null ? new AbortController() : void 0;\n return new DefaultStreamTextResult({\n model: resolveLanguageModel(model),\n telemetry,\n headers,\n settings,\n maxRetries,\n abortSignal: mergeAbortSignals(\n abortSignal,\n totalTimeoutMs != null ? AbortSignal.timeout(totalTimeoutMs) : void 0,\n stepAbortController == null ? void 0 : stepAbortController.signal,\n chunkAbortController == null ? void 0 : chunkAbortController.signal\n ),\n stepTimeoutMs,\n stepAbortController,\n chunkTimeoutMs,\n chunkAbortController,\n system,\n prompt,\n messages,\n tools,\n toolChoice,\n transforms: asArray(transform),\n activeTools,\n repairToolCall,\n stopConditions: asArray(stopWhen),\n output,\n providerOptions,\n prepareStep,\n includeRawChunks,\n timeout,\n stopWhen,\n originalAbortSignal: abortSignal,\n onChunk,\n onError,\n onFinish,\n onAbort,\n onStepFinish,\n onStart,\n onStepStart,\n onToolCallStart,\n onToolCallFinish,\n now: now2,\n generateId: generateId2,\n experimental_context,\n download: download2,\n include\n });\n}\nfunction createOutputTransformStream(output) {\n let firstTextChunkId = void 0;\n let text2 = \"\";\n let textChunk = \"\";\n let textProviderMetadata = void 0;\n let lastPublishedJson = \"\";\n function publishTextChunk({\n controller,\n partialOutput = void 0\n }) {\n controller.enqueue({\n part: {\n type: \"text-delta\",\n id: firstTextChunkId,\n text: textChunk,\n providerMetadata: textProviderMetadata\n },\n partialOutput\n });\n textChunk = \"\";\n }\n return new TransformStream({\n async transform(chunk, controller) {\n var _a21;\n if (chunk.type === \"finish-step\" && textChunk.length > 0) {\n publishTextChunk({ controller });\n }\n if (chunk.type !== \"text-delta\" && chunk.type !== \"text-start\" && chunk.type !== \"text-end\") {\n controller.enqueue({ part: chunk, partialOutput: void 0 });\n return;\n }\n if (firstTextChunkId == null) {\n firstTextChunkId = chunk.id;\n } else if (chunk.id !== firstTextChunkId) {\n controller.enqueue({ part: chunk, partialOutput: void 0 });\n return;\n }\n if (chunk.type === \"text-start\") {\n controller.enqueue({ part: chunk, partialOutput: void 0 });\n return;\n }\n if (chunk.type === \"text-end\") {\n if (textChunk.length > 0) {\n publishTextChunk({ controller });\n }\n controller.enqueue({ part: chunk, partialOutput: void 0 });\n return;\n }\n text2 += chunk.text;\n textChunk += chunk.text;\n textProviderMetadata = (_a21 = chunk.providerMetadata) != null ? _a21 : textProviderMetadata;\n const result = await output.parsePartialOutput({ text: text2 });\n if (result !== void 0) {\n const currentJson = JSON.stringify(result.partial);\n if (currentJson !== lastPublishedJson) {\n publishTextChunk({ controller, partialOutput: result.partial });\n lastPublishedJson = currentJson;\n }\n }\n }\n });\n}\nvar DefaultStreamTextResult = class {\n constructor({\n model,\n telemetry,\n headers,\n settings,\n maxRetries: maxRetriesArg,\n abortSignal,\n stepTimeoutMs,\n stepAbortController,\n chunkTimeoutMs,\n chunkAbortController,\n system,\n prompt,\n messages,\n tools,\n toolChoice,\n transforms,\n activeTools,\n repairToolCall,\n stopConditions,\n output,\n providerOptions,\n prepareStep,\n includeRawChunks,\n now: now2,\n generateId: generateId2,\n timeout,\n stopWhen,\n originalAbortSignal,\n onChunk,\n onError,\n onFinish,\n onAbort,\n onStepFinish,\n onStart,\n onStepStart,\n onToolCallStart,\n onToolCallFinish,\n experimental_context,\n download: download2,\n include\n }) {\n this._totalUsage = new DelayedPromise();\n this._finishReason = new DelayedPromise();\n this._rawFinishReason = new DelayedPromise();\n this._steps = new DelayedPromise();\n this.outputSpecification = output;\n this.includeRawChunks = includeRawChunks;\n this.tools = tools;\n const createGlobalTelemetry = getGlobalTelemetryIntegration();\n const globalTelemetry = createGlobalTelemetry(telemetry == null ? void 0 : telemetry.integrations);\n let stepFinish;\n let recordedContent = [];\n const recordedResponseMessages = [];\n let recordedFinishReason = void 0;\n let recordedRawFinishReason = void 0;\n let recordedTotalUsage = void 0;\n let recordedRequest = {};\n let recordedWarnings = [];\n const recordedSteps = [];\n const pendingDeferredToolCalls = /* @__PURE__ */ new Map();\n let rootSpan;\n let activeTextContent = {};\n let activeReasoningContent = {};\n const eventProcessor = new TransformStream({\n async transform(chunk, controller) {\n var _a21, _b, _c, _d;\n controller.enqueue(chunk);\n const { part } = chunk;\n if (part.type === \"text-delta\" || part.type === \"reasoning-delta\" || part.type === \"source\" || part.type === \"tool-call\" || part.type === \"tool-result\" || part.type === \"tool-input-start\" || part.type === \"tool-input-delta\" || part.type === \"raw\") {\n await (onChunk == null ? void 0 : onChunk({ chunk: part }));\n }\n if (part.type === \"error\") {\n await onError({ error: wrapGatewayError(part.error) });\n }\n if (part.type === \"text-start\") {\n activeTextContent[part.id] = {\n type: \"text\",\n text: \"\",\n providerMetadata: part.providerMetadata\n };\n recordedContent.push(activeTextContent[part.id]);\n }\n if (part.type === \"text-delta\") {\n const activeText = activeTextContent[part.id];\n if (activeText == null) {\n controller.enqueue({\n part: {\n type: \"error\",\n error: `text part ${part.id} not found`\n },\n partialOutput: void 0\n });\n return;\n }\n activeText.text += part.text;\n activeText.providerMetadata = (_a21 = part.providerMetadata) != null ? _a21 : activeText.providerMetadata;\n }\n if (part.type === \"text-end\") {\n const activeText = activeTextContent[part.id];\n if (activeText == null) {\n controller.enqueue({\n part: {\n type: \"error\",\n error: `text part ${part.id} not found`\n },\n partialOutput: void 0\n });\n return;\n }\n activeText.providerMetadata = (_b = part.providerMetadata) != null ? _b : activeText.providerMetadata;\n delete activeTextContent[part.id];\n }\n if (part.type === \"reasoning-start\") {\n activeReasoningContent[part.id] = {\n type: \"reasoning\",\n text: \"\",\n providerMetadata: part.providerMetadata\n };\n recordedContent.push(activeReasoningContent[part.id]);\n }\n if (part.type === \"reasoning-delta\") {\n const activeReasoning = activeReasoningContent[part.id];\n if (activeReasoning == null) {\n controller.enqueue({\n part: {\n type: \"error\",\n error: `reasoning part ${part.id} not found`\n },\n partialOutput: void 0\n });\n return;\n }\n activeReasoning.text += part.text;\n activeReasoning.providerMetadata = (_c = part.providerMetadata) != null ? _c : activeReasoning.providerMetadata;\n }\n if (part.type === \"reasoning-end\") {\n const activeReasoning = activeReasoningContent[part.id];\n if (activeReasoning == null) {\n controller.enqueue({\n part: {\n type: \"error\",\n error: `reasoning part ${part.id} not found`\n },\n partialOutput: void 0\n });\n return;\n }\n activeReasoning.providerMetadata = (_d = part.providerMetadata) != null ? _d : activeReasoning.providerMetadata;\n delete activeReasoningContent[part.id];\n }\n if (part.type === \"file\") {\n recordedContent.push({\n type: \"file\",\n file: part.file,\n ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n });\n }\n if (part.type === \"source\") {\n recordedContent.push(part);\n }\n if (part.type === \"tool-call\") {\n recordedContent.push(part);\n }\n if (part.type === \"tool-result\" && !part.preliminary) {\n recordedContent.push(part);\n }\n if (part.type === \"tool-approval-request\") {\n recordedContent.push(part);\n }\n if (part.type === \"tool-error\") {\n recordedContent.push(part);\n }\n if (part.type === \"start-step\") {\n recordedContent = [];\n activeReasoningContent = {};\n activeTextContent = {};\n recordedRequest = part.request;\n recordedWarnings = part.warnings;\n }\n if (part.type === \"finish-step\") {\n const stepMessages = await toResponseMessages({\n content: recordedContent,\n tools\n });\n const currentStepResult = new DefaultStepResult({\n stepNumber: recordedSteps.length,\n model: modelInfo,\n ...callbackTelemetryProps,\n experimental_context,\n content: recordedContent,\n finishReason: part.finishReason,\n rawFinishReason: part.rawFinishReason,\n usage: part.usage,\n warnings: recordedWarnings,\n request: recordedRequest,\n response: {\n ...part.response,\n messages: [...recordedResponseMessages, ...stepMessages]\n },\n providerMetadata: part.providerMetadata\n });\n await notify({\n event: currentStepResult,\n callbacks: [onStepFinish, globalTelemetry.onStepFinish]\n });\n logWarnings({\n warnings: recordedWarnings,\n provider: modelInfo.provider,\n model: modelInfo.modelId\n });\n recordedSteps.push(currentStepResult);\n recordedResponseMessages.push(...stepMessages);\n stepFinish.resolve();\n }\n if (part.type === \"finish\") {\n recordedTotalUsage = part.totalUsage;\n recordedFinishReason = part.finishReason;\n recordedRawFinishReason = part.rawFinishReason;\n }\n },\n async flush(controller) {\n try {\n if (recordedSteps.length === 0) {\n const error = (abortSignal == null ? void 0 : abortSignal.aborted) ? abortSignal.reason : new NoOutputGeneratedError({\n message: \"No output generated. Check the stream for errors.\"\n });\n self._finishReason.reject(error);\n self._rawFinishReason.reject(error);\n self._totalUsage.reject(error);\n self._steps.reject(error);\n return;\n }\n const finishReason = recordedFinishReason != null ? recordedFinishReason : \"other\";\n const totalUsage = recordedTotalUsage != null ? recordedTotalUsage : createNullLanguageModelUsage();\n self._finishReason.resolve(finishReason);\n self._rawFinishReason.resolve(recordedRawFinishReason);\n self._totalUsage.resolve(totalUsage);\n self._steps.resolve(recordedSteps);\n const finalStep = recordedSteps[recordedSteps.length - 1];\n await notify({\n event: {\n stepNumber: finalStep.stepNumber,\n model: finalStep.model,\n functionId: finalStep.functionId,\n metadata: finalStep.metadata,\n experimental_context: finalStep.experimental_context,\n finishReason: finalStep.finishReason,\n rawFinishReason: finalStep.rawFinishReason,\n totalUsage,\n usage: finalStep.usage,\n content: finalStep.content,\n text: finalStep.text,\n reasoningText: finalStep.reasoningText,\n reasoning: finalStep.reasoning,\n files: finalStep.files,\n sources: finalStep.sources,\n toolCalls: finalStep.toolCalls,\n staticToolCalls: finalStep.staticToolCalls,\n dynamicToolCalls: finalStep.dynamicToolCalls,\n toolResults: finalStep.toolResults,\n staticToolResults: finalStep.staticToolResults,\n dynamicToolResults: finalStep.dynamicToolResults,\n request: finalStep.request,\n response: finalStep.response,\n warnings: finalStep.warnings,\n providerMetadata: finalStep.providerMetadata,\n steps: recordedSteps\n },\n callbacks: [\n onFinish,\n globalTelemetry.onFinish\n ]\n });\n rootSpan.setAttributes(\n await selectTelemetryAttributes({\n telemetry,\n attributes: {\n \"ai.response.finishReason\": finishReason,\n \"ai.response.text\": { output: () => finalStep.text },\n \"ai.response.reasoning\": {\n output: () => finalStep.reasoningText\n },\n \"ai.response.toolCalls\": {\n output: () => {\n var _a21;\n return ((_a21 = finalStep.toolCalls) == null ? void 0 : _a21.length) ? JSON.stringify(finalStep.toolCalls) : void 0;\n }\n },\n \"ai.response.providerMetadata\": JSON.stringify(\n finalStep.providerMetadata\n ),\n \"ai.usage.inputTokens\": totalUsage.inputTokens,\n \"ai.usage.outputTokens\": totalUsage.outputTokens,\n \"ai.usage.totalTokens\": totalUsage.totalTokens,\n \"ai.usage.reasoningTokens\": totalUsage.reasoningTokens,\n \"ai.usage.cachedInputTokens\": totalUsage.cachedInputTokens\n }\n })\n );\n } catch (error) {\n controller.error(error);\n } finally {\n rootSpan.end();\n }\n }\n });\n const stitchableStream = createStitchableStream();\n this.addStream = stitchableStream.addStream;\n this.closeStream = stitchableStream.close;\n const reader = stitchableStream.stream.getReader();\n let stream = new ReadableStream({\n async start(controller) {\n controller.enqueue({ type: \"start\" });\n },\n async pull(controller) {\n function abort() {\n onAbort == null ? void 0 : onAbort({ steps: recordedSteps });\n controller.enqueue({\n type: \"abort\",\n // The `reason` is usually of type DOMException, but it can also be of any type,\n // so we use getErrorMessage for serialization because it is already designed to accept values of the unknown type.\n // See: https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/reason\n ...(abortSignal == null ? void 0 : abortSignal.reason) !== void 0 ? { reason: getErrorMessage7(abortSignal.reason) } : {}\n });\n controller.close();\n }\n try {\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n return;\n }\n if (abortSignal == null ? void 0 : abortSignal.aborted) {\n abort();\n return;\n }\n controller.enqueue(value);\n } catch (error) {\n if (isAbortError2(error) && (abortSignal == null ? void 0 : abortSignal.aborted)) {\n abort();\n } else {\n controller.error(error);\n }\n }\n },\n cancel(reason) {\n return stitchableStream.stream.cancel(reason);\n }\n });\n for (const transform of transforms) {\n stream = stream.pipeThrough(\n transform({\n tools,\n stopStream() {\n stitchableStream.terminate();\n }\n })\n );\n }\n this.baseStream = stream.pipeThrough(createOutputTransformStream(output != null ? output : text())).pipeThrough(eventProcessor);\n const { maxRetries, retry } = prepareRetries({\n maxRetries: maxRetriesArg,\n abortSignal\n });\n const tracer = getTracer(telemetry);\n const callSettings = prepareCallSettings(settings);\n const baseTelemetryAttributes = getBaseTelemetryAttributes({\n model,\n telemetry,\n headers,\n settings: { ...callSettings, maxRetries }\n });\n const self = this;\n const modelInfo = { provider: model.provider, modelId: model.modelId };\n const callbackTelemetryProps = {\n functionId: telemetry == null ? void 0 : telemetry.functionId,\n metadata: telemetry == null ? void 0 : telemetry.metadata\n };\n recordSpan({\n name: \"ai.streamText\",\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({ operationId: \"ai.streamText\", telemetry }),\n ...baseTelemetryAttributes,\n // specific settings that only make sense on the outer level:\n \"ai.prompt\": {\n input: () => JSON.stringify({ system, prompt, messages })\n }\n }\n }),\n tracer,\n endWhenDone: false,\n fn: async (rootSpanArg) => {\n rootSpan = rootSpanArg;\n const initialPrompt = await standardizePrompt({\n system,\n prompt,\n messages\n });\n await notify({\n event: {\n model: modelInfo,\n system,\n prompt,\n messages,\n tools,\n toolChoice,\n activeTools,\n maxOutputTokens: callSettings.maxOutputTokens,\n temperature: callSettings.temperature,\n topP: callSettings.topP,\n topK: callSettings.topK,\n presencePenalty: callSettings.presencePenalty,\n frequencyPenalty: callSettings.frequencyPenalty,\n stopSequences: callSettings.stopSequences,\n seed: callSettings.seed,\n maxRetries,\n timeout,\n headers,\n providerOptions,\n stopWhen,\n output,\n abortSignal: originalAbortSignal,\n include,\n ...callbackTelemetryProps,\n experimental_context\n },\n callbacks: [\n onStart,\n globalTelemetry.onStart\n ]\n });\n const initialMessages = initialPrompt.messages;\n const initialResponseMessages = [];\n const { approvedToolApprovals, deniedToolApprovals } = collectToolApprovals({ messages: initialMessages });\n if (deniedToolApprovals.length > 0 || approvedToolApprovals.length > 0) {\n const providerExecutedToolApprovals = [\n ...approvedToolApprovals,\n ...deniedToolApprovals\n ].filter((toolApproval) => toolApproval.toolCall.providerExecuted);\n const localApprovedToolApprovals = approvedToolApprovals.filter(\n (toolApproval) => !toolApproval.toolCall.providerExecuted\n );\n const localDeniedToolApprovals = deniedToolApprovals.filter(\n (toolApproval) => !toolApproval.toolCall.providerExecuted\n );\n const deniedProviderExecutedToolApprovals = deniedToolApprovals.filter(\n (toolApproval) => toolApproval.toolCall.providerExecuted\n );\n let toolExecutionStepStreamController;\n const toolExecutionStepStream = new ReadableStream({\n start(controller) {\n toolExecutionStepStreamController = controller;\n }\n });\n self.addStream(toolExecutionStepStream);\n try {\n for (const toolApproval of [\n ...localDeniedToolApprovals,\n ...deniedProviderExecutedToolApprovals\n ]) {\n toolExecutionStepStreamController == null ? void 0 : toolExecutionStepStreamController.enqueue({\n type: \"tool-output-denied\",\n toolCallId: toolApproval.toolCall.toolCallId,\n toolName: toolApproval.toolCall.toolName\n });\n }\n const toolOutputs = [];\n await Promise.all(\n localApprovedToolApprovals.map(async (toolApproval) => {\n const result = await executeToolCall({\n toolCall: toolApproval.toolCall,\n tools,\n tracer,\n telemetry,\n messages: initialMessages,\n abortSignal,\n experimental_context,\n stepNumber: recordedSteps.length,\n model: modelInfo,\n onToolCallStart: [\n onToolCallStart,\n globalTelemetry.onToolCallStart\n ],\n onToolCallFinish: [\n onToolCallFinish,\n globalTelemetry.onToolCallFinish\n ],\n onPreliminaryToolResult: (result2) => {\n toolExecutionStepStreamController == null ? void 0 : toolExecutionStepStreamController.enqueue(result2);\n }\n });\n if (result != null) {\n toolExecutionStepStreamController == null ? void 0 : toolExecutionStepStreamController.enqueue(result);\n toolOutputs.push(result);\n }\n })\n );\n if (providerExecutedToolApprovals.length > 0) {\n initialResponseMessages.push({\n role: \"tool\",\n content: providerExecutedToolApprovals.map(\n (toolApproval) => ({\n type: \"tool-approval-response\",\n approvalId: toolApproval.approvalResponse.approvalId,\n approved: toolApproval.approvalResponse.approved,\n reason: toolApproval.approvalResponse.reason,\n providerExecuted: true\n })\n )\n });\n }\n if (toolOutputs.length > 0 || localDeniedToolApprovals.length > 0) {\n const localToolContent = [];\n for (const output2 of toolOutputs) {\n localToolContent.push({\n type: \"tool-result\",\n toolCallId: output2.toolCallId,\n toolName: output2.toolName,\n output: await createToolModelOutput({\n toolCallId: output2.toolCallId,\n input: output2.input,\n tool: tools == null ? void 0 : tools[output2.toolName],\n output: output2.type === \"tool-result\" ? output2.output : output2.error,\n errorMode: output2.type === \"tool-error\" ? \"text\" : \"none\"\n })\n });\n }\n for (const toolApproval of localDeniedToolApprovals) {\n localToolContent.push({\n type: \"tool-result\",\n toolCallId: toolApproval.toolCall.toolCallId,\n toolName: toolApproval.toolCall.toolName,\n output: {\n type: \"execution-denied\",\n reason: toolApproval.approvalResponse.reason\n }\n });\n }\n initialResponseMessages.push({\n role: \"tool\",\n content: localToolContent\n });\n }\n } finally {\n toolExecutionStepStreamController == null ? void 0 : toolExecutionStepStreamController.close();\n }\n }\n recordedResponseMessages.push(...initialResponseMessages);\n async function streamStep({\n currentStep,\n responseMessages,\n usage\n }) {\n var _a21, _b, _c, _d, _e, _f, _g, _h, _i;\n const includeRawChunks2 = self.includeRawChunks;\n const stepTimeoutId = stepTimeoutMs != null ? setTimeout(() => stepAbortController.abort(), stepTimeoutMs) : void 0;\n let chunkTimeoutId = void 0;\n function resetChunkTimeout() {\n if (chunkTimeoutMs != null) {\n if (chunkTimeoutId != null) {\n clearTimeout(chunkTimeoutId);\n }\n chunkTimeoutId = setTimeout(\n () => chunkAbortController.abort(),\n chunkTimeoutMs\n );\n }\n }\n function clearChunkTimeout() {\n if (chunkTimeoutId != null) {\n clearTimeout(chunkTimeoutId);\n chunkTimeoutId = void 0;\n }\n }\n function clearStepTimeout() {\n if (stepTimeoutId != null) {\n clearTimeout(stepTimeoutId);\n }\n }\n try {\n stepFinish = new DelayedPromise();\n const stepInputMessages = [...initialMessages, ...responseMessages];\n const prepareStepResult = await (prepareStep == null ? void 0 : prepareStep({\n model,\n steps: recordedSteps,\n stepNumber: recordedSteps.length,\n messages: stepInputMessages,\n experimental_context\n }));\n const stepModel = resolveLanguageModel(\n (_a21 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a21 : model\n );\n const stepModelInfo = {\n provider: stepModel.provider,\n modelId: stepModel.modelId\n };\n const promptMessages = await convertToLanguageModelPrompt({\n prompt: {\n system: (_b = prepareStepResult == null ? void 0 : prepareStepResult.system) != null ? _b : initialPrompt.system,\n messages: (_c = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _c : stepInputMessages\n },\n supportedUrls: await stepModel.supportedUrls,\n download: download2\n });\n const stepActiveTools = (_d = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _d : activeTools;\n const { toolChoice: stepToolChoice, tools: stepTools } = await prepareToolsAndToolChoice({\n tools,\n toolChoice: (_e = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _e : toolChoice,\n activeTools: stepActiveTools\n });\n experimental_context = (_f = prepareStepResult == null ? void 0 : prepareStepResult.experimental_context) != null ? _f : experimental_context;\n const stepMessages = (_g = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _g : stepInputMessages;\n const stepSystem = (_h = prepareStepResult == null ? void 0 : prepareStepResult.system) != null ? _h : initialPrompt.system;\n const stepProviderOptions = mergeObjects(\n providerOptions,\n prepareStepResult == null ? void 0 : prepareStepResult.providerOptions\n );\n await notify({\n event: {\n stepNumber: recordedSteps.length,\n model: stepModelInfo,\n system: stepSystem,\n messages: stepMessages,\n tools,\n toolChoice: stepToolChoice,\n activeTools: stepActiveTools,\n steps: [...recordedSteps],\n providerOptions: stepProviderOptions,\n timeout,\n headers,\n stopWhen,\n output,\n abortSignal: originalAbortSignal,\n include,\n ...callbackTelemetryProps,\n experimental_context\n },\n callbacks: [\n onStepStart,\n globalTelemetry.onStepStart\n ]\n });\n const {\n result: { stream: stream2, response, request },\n doStreamSpan,\n startTimestampMs\n } = await retry(\n () => recordSpan({\n name: \"ai.streamText.doStream\",\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: \"ai.streamText.doStream\",\n telemetry\n }),\n ...baseTelemetryAttributes,\n // model:\n \"ai.model.provider\": stepModel.provider,\n \"ai.model.id\": stepModel.modelId,\n // prompt:\n \"ai.prompt.messages\": {\n input: () => stringifyForTelemetry(promptMessages)\n },\n \"ai.prompt.tools\": {\n // convert the language model level tools:\n input: () => stepTools == null ? void 0 : stepTools.map((tool2) => JSON.stringify(tool2))\n },\n \"ai.prompt.toolChoice\": {\n input: () => stepToolChoice != null ? JSON.stringify(stepToolChoice) : void 0\n },\n // standardized gen-ai llm span attributes:\n \"gen_ai.system\": stepModel.provider,\n \"gen_ai.request.model\": stepModel.modelId,\n \"gen_ai.request.frequency_penalty\": callSettings.frequencyPenalty,\n \"gen_ai.request.max_tokens\": callSettings.maxOutputTokens,\n \"gen_ai.request.presence_penalty\": callSettings.presencePenalty,\n \"gen_ai.request.stop_sequences\": callSettings.stopSequences,\n \"gen_ai.request.temperature\": callSettings.temperature,\n \"gen_ai.request.top_k\": callSettings.topK,\n \"gen_ai.request.top_p\": callSettings.topP\n }\n }),\n tracer,\n endWhenDone: false,\n fn: async (doStreamSpan2) => ({\n startTimestampMs: now2(),\n // get before the call\n doStreamSpan: doStreamSpan2,\n result: await stepModel.doStream({\n ...callSettings,\n tools: stepTools,\n toolChoice: stepToolChoice,\n responseFormat: await (output == null ? void 0 : output.responseFormat),\n prompt: promptMessages,\n providerOptions: stepProviderOptions,\n abortSignal,\n headers,\n includeRawChunks: includeRawChunks2\n })\n })\n })\n );\n const streamWithToolResults = runToolsTransformation({\n tools,\n generatorStream: stream2,\n tracer,\n telemetry,\n system,\n messages: stepInputMessages,\n repairToolCall,\n abortSignal,\n experimental_context,\n generateId: generateId2,\n stepNumber: recordedSteps.length,\n model: stepModelInfo,\n onToolCallStart: [\n onToolCallStart,\n globalTelemetry.onToolCallStart\n ],\n onToolCallFinish: [\n onToolCallFinish,\n globalTelemetry.onToolCallFinish\n ]\n });\n const stepRequest = ((_i = include == null ? void 0 : include.requestBody) != null ? _i : true) ? request != null ? request : {} : { ...request, body: void 0 };\n const stepToolCalls = [];\n const stepToolOutputs = [];\n let warnings;\n const activeToolCallToolNames = {};\n let stepFinishReason = \"other\";\n let stepRawFinishReason = void 0;\n let stepUsage = createNullLanguageModelUsage();\n let stepProviderMetadata;\n let stepFirstChunk = true;\n let stepResponse = {\n id: generateId2(),\n timestamp: /* @__PURE__ */ new Date(),\n modelId: modelInfo.modelId\n };\n let activeText = \"\";\n self.addStream(\n streamWithToolResults.pipeThrough(\n new TransformStream({\n async transform(chunk, controller) {\n var _a22, _b2, _c2, _d2, _e2;\n resetChunkTimeout();\n if (chunk.type === \"stream-start\") {\n warnings = chunk.warnings;\n return;\n }\n if (stepFirstChunk) {\n const msToFirstChunk = now2() - startTimestampMs;\n stepFirstChunk = false;\n doStreamSpan.addEvent(\"ai.stream.firstChunk\", {\n \"ai.response.msToFirstChunk\": msToFirstChunk\n });\n doStreamSpan.setAttributes({\n \"ai.response.msToFirstChunk\": msToFirstChunk\n });\n controller.enqueue({\n type: \"start-step\",\n request: stepRequest,\n warnings: warnings != null ? warnings : []\n });\n }\n const chunkType = chunk.type;\n switch (chunkType) {\n case \"tool-approval-request\":\n case \"text-start\":\n case \"text-end\": {\n controller.enqueue(chunk);\n break;\n }\n case \"text-delta\": {\n if (chunk.delta.length > 0) {\n controller.enqueue({\n type: \"text-delta\",\n id: chunk.id,\n text: chunk.delta,\n providerMetadata: chunk.providerMetadata\n });\n activeText += chunk.delta;\n }\n break;\n }\n case \"reasoning-start\":\n case \"reasoning-end\": {\n controller.enqueue(chunk);\n break;\n }\n case \"reasoning-delta\": {\n controller.enqueue({\n type: \"reasoning-delta\",\n id: chunk.id,\n text: chunk.delta,\n providerMetadata: chunk.providerMetadata\n });\n break;\n }\n case \"tool-call\": {\n controller.enqueue(chunk);\n stepToolCalls.push(chunk);\n break;\n }\n case \"tool-result\": {\n controller.enqueue(chunk);\n if (!chunk.preliminary) {\n stepToolOutputs.push(chunk);\n }\n break;\n }\n case \"tool-error\": {\n controller.enqueue(chunk);\n stepToolOutputs.push(chunk);\n break;\n }\n case \"response-metadata\": {\n stepResponse = {\n id: (_a22 = chunk.id) != null ? _a22 : stepResponse.id,\n timestamp: (_b2 = chunk.timestamp) != null ? _b2 : stepResponse.timestamp,\n modelId: (_c2 = chunk.modelId) != null ? _c2 : stepResponse.modelId\n };\n break;\n }\n case \"finish\": {\n stepUsage = chunk.usage;\n stepFinishReason = chunk.finishReason;\n stepRawFinishReason = chunk.rawFinishReason;\n stepProviderMetadata = chunk.providerMetadata;\n const msToFinish = now2() - startTimestampMs;\n doStreamSpan.addEvent(\"ai.stream.finish\");\n doStreamSpan.setAttributes({\n \"ai.response.msToFinish\": msToFinish,\n \"ai.response.avgOutputTokensPerSecond\": 1e3 * ((_d2 = stepUsage.outputTokens) != null ? _d2 : 0) / msToFinish\n });\n break;\n }\n case \"file\": {\n controller.enqueue(chunk);\n break;\n }\n case \"source\": {\n controller.enqueue(chunk);\n break;\n }\n case \"tool-input-start\": {\n activeToolCallToolNames[chunk.id] = chunk.toolName;\n const tool2 = tools == null ? void 0 : tools[chunk.toolName];\n if ((tool2 == null ? void 0 : tool2.onInputStart) != null) {\n await tool2.onInputStart({\n toolCallId: chunk.id,\n messages: stepInputMessages,\n abortSignal,\n experimental_context\n });\n }\n controller.enqueue({\n ...chunk,\n dynamic: (_e2 = chunk.dynamic) != null ? _e2 : (tool2 == null ? void 0 : tool2.type) === \"dynamic\",\n title: tool2 == null ? void 0 : tool2.title\n });\n break;\n }\n case \"tool-input-end\": {\n delete activeToolCallToolNames[chunk.id];\n controller.enqueue(chunk);\n break;\n }\n case \"tool-input-delta\": {\n const toolName = activeToolCallToolNames[chunk.id];\n const tool2 = tools == null ? void 0 : tools[toolName];\n if ((tool2 == null ? void 0 : tool2.onInputDelta) != null) {\n await tool2.onInputDelta({\n inputTextDelta: chunk.delta,\n toolCallId: chunk.id,\n messages: stepInputMessages,\n abortSignal,\n experimental_context\n });\n }\n controller.enqueue(chunk);\n break;\n }\n case \"error\": {\n controller.enqueue(chunk);\n stepFinishReason = \"error\";\n break;\n }\n case \"raw\": {\n if (includeRawChunks2) {\n controller.enqueue(chunk);\n }\n break;\n }\n default: {\n const exhaustiveCheck = chunkType;\n throw new Error(\n `Unknown chunk type: ${exhaustiveCheck}`\n );\n }\n }\n },\n // invoke onFinish callback and resolve toolResults promise when the stream is about to close:\n async flush(controller) {\n const stepToolCallsJson = stepToolCalls.length > 0 ? JSON.stringify(stepToolCalls) : void 0;\n try {\n doStreamSpan.setAttributes(\n await selectTelemetryAttributes({\n telemetry,\n attributes: {\n \"ai.response.finishReason\": stepFinishReason,\n \"ai.response.text\": {\n output: () => activeText\n },\n \"ai.response.reasoning\": {\n output: () => {\n const reasoningParts = recordedContent.filter(\n (c) => c.type === \"reasoning\"\n );\n return reasoningParts.length > 0 ? reasoningParts.map((r) => r.text).join(\"\\n\") : void 0;\n }\n },\n \"ai.response.toolCalls\": {\n output: () => stepToolCallsJson\n },\n \"ai.response.id\": stepResponse.id,\n \"ai.response.model\": stepResponse.modelId,\n \"ai.response.timestamp\": stepResponse.timestamp.toISOString(),\n \"ai.response.providerMetadata\": JSON.stringify(stepProviderMetadata),\n \"ai.usage.inputTokens\": stepUsage.inputTokens,\n \"ai.usage.outputTokens\": stepUsage.outputTokens,\n \"ai.usage.totalTokens\": stepUsage.totalTokens,\n \"ai.usage.reasoningTokens\": stepUsage.reasoningTokens,\n \"ai.usage.cachedInputTokens\": stepUsage.cachedInputTokens,\n // standardized gen-ai llm span attributes:\n \"gen_ai.response.finish_reasons\": [\n stepFinishReason\n ],\n \"gen_ai.response.id\": stepResponse.id,\n \"gen_ai.response.model\": stepResponse.modelId,\n \"gen_ai.usage.input_tokens\": stepUsage.inputTokens,\n \"gen_ai.usage.output_tokens\": stepUsage.outputTokens\n }\n })\n );\n } catch (error) {\n } finally {\n doStreamSpan.end();\n }\n controller.enqueue({\n type: \"finish-step\",\n finishReason: stepFinishReason,\n rawFinishReason: stepRawFinishReason,\n usage: stepUsage,\n providerMetadata: stepProviderMetadata,\n response: {\n ...stepResponse,\n headers: response == null ? void 0 : response.headers\n }\n });\n const combinedUsage = addLanguageModelUsage(\n usage,\n stepUsage\n );\n await stepFinish.promise;\n const clientToolCalls = stepToolCalls.filter(\n (toolCall) => toolCall.providerExecuted !== true\n );\n const clientToolOutputs = stepToolOutputs.filter(\n (toolOutput) => toolOutput.providerExecuted !== true\n );\n for (const toolCall of stepToolCalls) {\n if (toolCall.providerExecuted !== true)\n continue;\n const tool2 = tools == null ? void 0 : tools[toolCall.toolName];\n if ((tool2 == null ? void 0 : tool2.type) === \"provider\" && tool2.supportsDeferredResults) {\n const hasResultInStep = stepToolOutputs.some(\n (output2) => (output2.type === \"tool-result\" || output2.type === \"tool-error\") && output2.toolCallId === toolCall.toolCallId\n );\n if (!hasResultInStep) {\n pendingDeferredToolCalls.set(toolCall.toolCallId, {\n toolName: toolCall.toolName\n });\n }\n }\n }\n for (const output2 of stepToolOutputs) {\n if (output2.type === \"tool-result\" || output2.type === \"tool-error\") {\n pendingDeferredToolCalls.delete(output2.toolCallId);\n }\n }\n clearStepTimeout();\n clearChunkTimeout();\n if (\n // Continue if:\n // 1. There are client tool calls that have all been executed, OR\n // 2. There are pending deferred results from provider-executed tools\n (clientToolCalls.length > 0 && clientToolOutputs.length === clientToolCalls.length || pendingDeferredToolCalls.size > 0) && // continue until a stop condition is met:\n !await isStopConditionMet({\n stopConditions,\n steps: recordedSteps\n })\n ) {\n responseMessages.push(\n ...await toResponseMessages({\n content: (\n // use transformed content to create the messages for the next step:\n recordedSteps[recordedSteps.length - 1].content\n ),\n tools\n })\n );\n try {\n await streamStep({\n currentStep: currentStep + 1,\n responseMessages,\n usage: combinedUsage\n });\n } catch (error) {\n controller.enqueue({\n type: \"error\",\n error\n });\n self.closeStream();\n }\n } else {\n controller.enqueue({\n type: \"finish\",\n finishReason: stepFinishReason,\n rawFinishReason: stepRawFinishReason,\n totalUsage: combinedUsage\n });\n self.closeStream();\n }\n }\n })\n )\n );\n } finally {\n clearStepTimeout();\n clearChunkTimeout();\n }\n }\n await streamStep({\n currentStep: 0,\n responseMessages: initialResponseMessages,\n usage: createNullLanguageModelUsage()\n });\n }\n }).catch((error) => {\n self.addStream(\n new ReadableStream({\n start(controller) {\n controller.enqueue({ type: \"error\", error });\n controller.close();\n }\n })\n );\n self.closeStream();\n });\n }\n get steps() {\n this.consumeStream();\n return this._steps.promise;\n }\n get finalStep() {\n return this.steps.then((steps) => steps[steps.length - 1]);\n }\n get content() {\n return this.finalStep.then((step) => step.content);\n }\n get warnings() {\n return this.finalStep.then((step) => step.warnings);\n }\n get providerMetadata() {\n return this.finalStep.then((step) => step.providerMetadata);\n }\n get text() {\n return this.finalStep.then((step) => step.text);\n }\n get reasoningText() {\n return this.finalStep.then((step) => step.reasoningText);\n }\n get reasoning() {\n return this.finalStep.then((step) => step.reasoning);\n }\n get sources() {\n return this.finalStep.then((step) => step.sources);\n }\n get files() {\n return this.finalStep.then((step) => step.files);\n }\n get toolCalls() {\n return this.finalStep.then((step) => step.toolCalls);\n }\n get staticToolCalls() {\n return this.finalStep.then((step) => step.staticToolCalls);\n }\n get dynamicToolCalls() {\n return this.finalStep.then((step) => step.dynamicToolCalls);\n }\n get toolResults() {\n return this.finalStep.then((step) => step.toolResults);\n }\n get staticToolResults() {\n return this.finalStep.then((step) => step.staticToolResults);\n }\n get dynamicToolResults() {\n return this.finalStep.then((step) => step.dynamicToolResults);\n }\n get usage() {\n return this.finalStep.then((step) => step.usage);\n }\n get request() {\n return this.finalStep.then((step) => step.request);\n }\n get response() {\n return this.finalStep.then((step) => step.response);\n }\n get totalUsage() {\n this.consumeStream();\n return this._totalUsage.promise;\n }\n get finishReason() {\n this.consumeStream();\n return this._finishReason.promise;\n }\n get rawFinishReason() {\n this.consumeStream();\n return this._rawFinishReason.promise;\n }\n /**\n * Split out a new stream from the original stream.\n * The original stream is replaced to allow for further splitting,\n * since we do not know how many times the stream will be split.\n *\n * Note: this leads to buffering the stream content on the server.\n * However, the LLM results are expected to be small enough to not cause issues.\n */\n teeStream() {\n const [stream1, stream2] = this.baseStream.tee();\n this.baseStream = stream2;\n return stream1;\n }\n get textStream() {\n return createAsyncIterableStream(\n this.teeStream().pipeThrough(\n new TransformStream({\n transform({ part }, controller) {\n if (part.type === \"text-delta\") {\n controller.enqueue(part.text);\n }\n }\n })\n )\n );\n }\n get fullStream() {\n return createAsyncIterableStream(\n this.teeStream().pipeThrough(\n new TransformStream({\n transform({ part }, controller) {\n controller.enqueue(part);\n }\n })\n )\n );\n }\n async consumeStream(options) {\n var _a21;\n try {\n await consumeStream({\n stream: this.fullStream,\n onError: options == null ? void 0 : options.onError\n });\n } catch (error) {\n (_a21 = options == null ? void 0 : options.onError) == null ? void 0 : _a21.call(options, error);\n }\n }\n get experimental_partialOutputStream() {\n return this.partialOutputStream;\n }\n get partialOutputStream() {\n return createAsyncIterableStream(\n this.teeStream().pipeThrough(\n new TransformStream({\n transform({ partialOutput }, controller) {\n if (partialOutput != null) {\n controller.enqueue(partialOutput);\n }\n }\n })\n )\n );\n }\n get elementStream() {\n var _a21, _b, _c;\n const transform = (_a21 = this.outputSpecification) == null ? void 0 : _a21.createElementStreamTransform();\n if (transform == null) {\n throw new UnsupportedFunctionalityError2({\n functionality: `element streams in ${(_c = (_b = this.outputSpecification) == null ? void 0 : _b.name) != null ? _c : \"text\"} mode`\n });\n }\n return createAsyncIterableStream(this.teeStream().pipeThrough(transform));\n }\n get output() {\n return this.finalStep.then((step) => {\n var _a21;\n const output = (_a21 = this.outputSpecification) != null ? _a21 : text();\n return output.parseCompleteOutput(\n { text: step.text },\n {\n response: step.response,\n usage: step.usage,\n finishReason: step.finishReason\n }\n );\n });\n }\n toUIMessageStream({\n originalMessages,\n generateMessageId,\n onFinish,\n messageMetadata,\n sendReasoning = true,\n sendSources = false,\n sendStart = true,\n sendFinish = true,\n onError = getErrorMessage7\n } = {}) {\n const responseMessageId = generateMessageId != null ? getResponseUIMessageId({\n originalMessages,\n responseMessageId: generateMessageId\n }) : void 0;\n const isDynamic = (part) => {\n var _a21;\n const tool2 = (_a21 = this.tools) == null ? void 0 : _a21[part.toolName];\n if (tool2 == null) {\n return part.dynamic;\n }\n return (tool2 == null ? void 0 : tool2.type) === \"dynamic\" ? true : void 0;\n };\n const baseStream = this.fullStream.pipeThrough(\n new TransformStream({\n transform: async (part, controller) => {\n const messageMetadataValue = messageMetadata == null ? void 0 : messageMetadata({ part });\n const partType = part.type;\n switch (partType) {\n case \"text-start\": {\n controller.enqueue({\n type: \"text-start\",\n id: part.id,\n ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n });\n break;\n }\n case \"text-delta\": {\n controller.enqueue({\n type: \"text-delta\",\n id: part.id,\n delta: part.text,\n ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n });\n break;\n }\n case \"text-end\": {\n controller.enqueue({\n type: \"text-end\",\n id: part.id,\n ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n });\n break;\n }\n case \"reasoning-start\": {\n controller.enqueue({\n type: \"reasoning-start\",\n id: part.id,\n ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n });\n break;\n }\n case \"reasoning-delta\": {\n if (sendReasoning) {\n controller.enqueue({\n type: \"reasoning-delta\",\n id: part.id,\n delta: part.text,\n ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n });\n }\n break;\n }\n case \"reasoning-end\": {\n controller.enqueue({\n type: \"reasoning-end\",\n id: part.id,\n ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n });\n break;\n }\n case \"file\": {\n controller.enqueue({\n type: \"file\",\n mediaType: part.file.mediaType,\n url: `data:${part.file.mediaType};base64,${part.file.base64}`,\n ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n });\n break;\n }\n case \"source\": {\n if (sendSources && part.sourceType === \"url\") {\n controller.enqueue({\n type: \"source-url\",\n sourceId: part.id,\n url: part.url,\n title: part.title,\n ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n });\n }\n if (sendSources && part.sourceType === \"document\") {\n controller.enqueue({\n type: \"source-document\",\n sourceId: part.id,\n mediaType: part.mediaType,\n title: part.title,\n filename: part.filename,\n ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n });\n }\n break;\n }\n case \"tool-input-start\": {\n const dynamic = isDynamic(part);\n controller.enqueue({\n type: \"tool-input-start\",\n toolCallId: part.id,\n toolName: part.toolName,\n ...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n ...dynamic != null ? { dynamic } : {},\n ...part.title != null ? { title: part.title } : {}\n });\n break;\n }\n case \"tool-input-delta\": {\n controller.enqueue({\n type: \"tool-input-delta\",\n toolCallId: part.id,\n inputTextDelta: part.delta\n });\n break;\n }\n case \"tool-call\": {\n const dynamic = isDynamic(part);\n if (part.invalid) {\n controller.enqueue({\n type: \"tool-input-error\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n ...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n ...dynamic != null ? { dynamic } : {},\n errorText: onError(part.error),\n ...part.title != null ? { title: part.title } : {}\n });\n } else {\n controller.enqueue({\n type: \"tool-input-available\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n ...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n ...dynamic != null ? { dynamic } : {},\n ...part.title != null ? { title: part.title } : {}\n });\n }\n break;\n }\n case \"tool-approval-request\": {\n controller.enqueue({\n type: \"tool-approval-request\",\n approvalId: part.approvalId,\n toolCallId: part.toolCall.toolCallId\n });\n break;\n }\n case \"tool-result\": {\n const dynamic = isDynamic(part);\n controller.enqueue({\n type: \"tool-output-available\",\n toolCallId: part.toolCallId,\n output: part.output,\n ...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n ...part.preliminary != null ? { preliminary: part.preliminary } : {},\n ...dynamic != null ? { dynamic } : {}\n });\n break;\n }\n case \"tool-error\": {\n const dynamic = isDynamic(part);\n controller.enqueue({\n type: \"tool-output-error\",\n toolCallId: part.toolCallId,\n errorText: onError(part.error),\n ...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n ...dynamic != null ? { dynamic } : {}\n });\n break;\n }\n case \"tool-output-denied\": {\n controller.enqueue({\n type: \"tool-output-denied\",\n toolCallId: part.toolCallId\n });\n break;\n }\n case \"error\": {\n controller.enqueue({\n type: \"error\",\n errorText: onError(part.error)\n });\n break;\n }\n case \"start-step\": {\n controller.enqueue({ type: \"start-step\" });\n break;\n }\n case \"finish-step\": {\n controller.enqueue({ type: \"finish-step\" });\n break;\n }\n case \"start\": {\n if (sendStart) {\n controller.enqueue({\n type: \"start\",\n ...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {},\n ...responseMessageId != null ? { messageId: responseMessageId } : {}\n });\n }\n break;\n }\n case \"finish\": {\n if (sendFinish) {\n controller.enqueue({\n type: \"finish\",\n finishReason: part.finishReason,\n ...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {}\n });\n }\n break;\n }\n case \"abort\": {\n controller.enqueue(part);\n break;\n }\n case \"tool-input-end\": {\n break;\n }\n case \"raw\": {\n break;\n }\n default: {\n const exhaustiveCheck = partType;\n throw new Error(`Unknown chunk type: ${exhaustiveCheck}`);\n }\n }\n if (messageMetadataValue != null && partType !== \"start\" && partType !== \"finish\") {\n controller.enqueue({\n type: \"message-metadata\",\n messageMetadata: messageMetadataValue\n });\n }\n }\n })\n );\n return createAsyncIterableStream(\n handleUIMessageStreamFinish({\n stream: baseStream,\n messageId: responseMessageId != null ? responseMessageId : generateMessageId == null ? void 0 : generateMessageId(),\n originalMessages,\n onFinish,\n onError\n })\n );\n }\n pipeUIMessageStreamToResponse(response, {\n originalMessages,\n generateMessageId,\n onFinish,\n messageMetadata,\n sendReasoning,\n sendSources,\n sendFinish,\n sendStart,\n onError,\n ...init\n } = {}) {\n pipeUIMessageStreamToResponse({\n response,\n stream: this.toUIMessageStream({\n originalMessages,\n generateMessageId,\n onFinish,\n messageMetadata,\n sendReasoning,\n sendSources,\n sendFinish,\n sendStart,\n onError\n }),\n ...init\n });\n }\n pipeTextStreamToResponse(response, init) {\n pipeTextStreamToResponse({\n response,\n textStream: this.textStream,\n ...init\n });\n }\n toUIMessageStreamResponse({\n originalMessages,\n generateMessageId,\n onFinish,\n messageMetadata,\n sendReasoning,\n sendSources,\n sendFinish,\n sendStart,\n onError,\n ...init\n } = {}) {\n return createUIMessageStreamResponse({\n stream: this.toUIMessageStream({\n originalMessages,\n generateMessageId,\n onFinish,\n messageMetadata,\n sendReasoning,\n sendSources,\n sendFinish,\n sendStart,\n onError\n }),\n ...init\n });\n }\n toTextStreamResponse(init) {\n return createTextStreamResponse({\n textStream: this.textStream,\n ...init\n });\n }\n};\n\n// src/agent/tool-loop-agent.ts\nvar ToolLoopAgent = class {\n constructor(settings) {\n this.version = \"agent-v1\";\n this.settings = settings;\n }\n /**\n * The id of the agent.\n */\n get id() {\n return this.settings.id;\n }\n /**\n * The tools that the agent can use.\n */\n get tools() {\n return this.settings.tools;\n }\n async prepareCall(options) {\n var _a21, _b, _c, _d;\n const {\n experimental_onStart: _settingsOnStart,\n experimental_onStepStart: _settingsOnStepStart,\n experimental_onToolCallStart: _settingsOnToolCallStart,\n experimental_onToolCallFinish: _settingsOnToolCallFinish,\n onStepFinish: _settingsOnStepFinish,\n onFinish: _settingsOnFinish,\n ...settingsWithoutCallbacks\n } = this.settings;\n const baseCallArgs = {\n ...settingsWithoutCallbacks,\n stopWhen: (_a21 = this.settings.stopWhen) != null ? _a21 : stepCountIs(20),\n ...options\n };\n const preparedCallArgs = (_d = await ((_c = (_b = this.settings).prepareCall) == null ? void 0 : _c.call(\n _b,\n baseCallArgs\n ))) != null ? _d : baseCallArgs;\n const { instructions, messages, prompt, ...callArgs } = preparedCallArgs;\n return {\n ...callArgs,\n // restore prompt types\n ...{ system: instructions, messages, prompt }\n };\n }\n mergeCallbacks(settingsCallback, methodCallback) {\n if (methodCallback && settingsCallback) {\n return async (event) => {\n await settingsCallback(event);\n await methodCallback(event);\n };\n }\n return methodCallback != null ? methodCallback : settingsCallback;\n }\n /**\n * Generates an output from the agent (non-streaming).\n */\n async generate({\n abortSignal,\n timeout,\n experimental_onStart,\n experimental_onStepStart,\n experimental_onToolCallStart,\n experimental_onToolCallFinish,\n onStepFinish,\n onFinish,\n ...options\n }) {\n return generateText({\n ...await this.prepareCall(options),\n abortSignal,\n timeout,\n experimental_onStart: this.mergeCallbacks(\n this.settings.experimental_onStart,\n experimental_onStart\n ),\n experimental_onStepStart: this.mergeCallbacks(\n this.settings.experimental_onStepStart,\n experimental_onStepStart\n ),\n experimental_onToolCallStart: this.mergeCallbacks(\n this.settings.experimental_onToolCallStart,\n experimental_onToolCallStart\n ),\n experimental_onToolCallFinish: this.mergeCallbacks(\n this.settings.experimental_onToolCallFinish,\n experimental_onToolCallFinish\n ),\n onStepFinish: this.mergeCallbacks(\n this.settings.onStepFinish,\n onStepFinish\n ),\n onFinish: this.mergeCallbacks(this.settings.onFinish, onFinish)\n });\n }\n /**\n * Streams an output from the agent (streaming).\n */\n async stream({\n abortSignal,\n timeout,\n experimental_transform,\n experimental_onStart,\n experimental_onStepStart,\n experimental_onToolCallStart,\n experimental_onToolCallFinish,\n onStepFinish,\n onFinish,\n ...options\n }) {\n return streamText({\n ...await this.prepareCall(options),\n abortSignal,\n timeout,\n experimental_transform,\n experimental_onStart: this.mergeCallbacks(\n this.settings.experimental_onStart,\n experimental_onStart\n ),\n experimental_onStepStart: this.mergeCallbacks(\n this.settings.experimental_onStepStart,\n experimental_onStepStart\n ),\n experimental_onToolCallStart: this.mergeCallbacks(\n this.settings.experimental_onToolCallStart,\n experimental_onToolCallStart\n ),\n experimental_onToolCallFinish: this.mergeCallbacks(\n this.settings.experimental_onToolCallFinish,\n experimental_onToolCallFinish\n ),\n onStepFinish: this.mergeCallbacks(\n this.settings.onStepFinish,\n onStepFinish\n ),\n onFinish: this.mergeCallbacks(this.settings.onFinish, onFinish)\n });\n }\n};\n\n// src/ui-message-stream/create-ui-message-stream.ts\nimport {\n generateId as generateIdFunc,\n getErrorMessage as getErrorMessage8\n} from \"@ai-sdk/provider-utils\";\nfunction createUIMessageStream({\n execute,\n onError = getErrorMessage8,\n originalMessages,\n onStepFinish,\n onFinish,\n generateId: generateId2 = generateIdFunc\n}) {\n let controller;\n const ongoingStreamPromises = [];\n const stream = new ReadableStream({\n start(controllerArg) {\n controller = controllerArg;\n }\n });\n function safeEnqueue(data) {\n try {\n controller.enqueue(data);\n } catch (error) {\n }\n }\n try {\n const result = execute({\n writer: {\n write(part) {\n safeEnqueue(part);\n },\n merge(streamArg) {\n ongoingStreamPromises.push(\n (async () => {\n const reader = streamArg.getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done)\n break;\n safeEnqueue(value);\n }\n })().catch((error) => {\n safeEnqueue({\n type: \"error\",\n errorText: onError(error)\n });\n })\n );\n },\n onError\n }\n });\n if (result) {\n ongoingStreamPromises.push(\n result.catch((error) => {\n safeEnqueue({\n type: \"error\",\n errorText: onError(error)\n });\n })\n );\n }\n } catch (error) {\n safeEnqueue({\n type: \"error\",\n errorText: onError(error)\n });\n }\n const waitForStreams = new Promise(async (resolve3) => {\n while (ongoingStreamPromises.length > 0) {\n await ongoingStreamPromises.shift();\n }\n resolve3();\n });\n waitForStreams.finally(() => {\n try {\n controller.close();\n } catch (error) {\n }\n });\n return handleUIMessageStreamFinish({\n stream,\n messageId: generateId2(),\n originalMessages,\n onStepFinish,\n onFinish,\n onError\n });\n}\n\n// src/ui-message-stream/read-ui-message-stream.ts\nfunction readUIMessageStream({\n message,\n stream,\n onError,\n terminateOnError = false\n}) {\n var _a21;\n let controller;\n let hasErrored = false;\n const outputStream = new ReadableStream({\n start(controllerParam) {\n controller = controllerParam;\n }\n });\n const state = createStreamingUIMessageState({\n messageId: (_a21 = message == null ? void 0 : message.id) != null ? _a21 : \"\",\n lastMessage: message\n });\n const handleError = (error) => {\n onError == null ? void 0 : onError(error);\n if (!hasErrored && terminateOnError) {\n hasErrored = true;\n controller == null ? void 0 : controller.error(error);\n }\n };\n consumeStream({\n stream: processUIMessageStream({\n stream,\n runUpdateMessageJob(job) {\n return job({\n state,\n write: () => {\n controller == null ? void 0 : controller.enqueue(structuredClone(state.message));\n }\n });\n },\n onError: handleError\n }),\n onError: handleError\n }).finally(() => {\n if (!hasErrored) {\n controller == null ? void 0 : controller.close();\n }\n });\n return createAsyncIterableStream(outputStream);\n}\n\n// src/ui/convert-to-model-messages.ts\nimport {\n isNonNullable\n} from \"@ai-sdk/provider-utils\";\nasync function convertToModelMessages(messages, options) {\n const modelMessages = [];\n if (options == null ? void 0 : options.ignoreIncompleteToolCalls) {\n messages = messages.map((message) => ({\n ...message,\n parts: message.parts.filter(\n (part) => !isToolUIPart(part) || part.state !== \"input-streaming\" && part.state !== \"input-available\"\n )\n }));\n }\n for (const message of messages) {\n switch (message.role) {\n case \"system\": {\n const textParts = message.parts.filter(\n (part) => part.type === \"text\"\n );\n const providerMetadata = textParts.reduce((acc, part) => {\n if (part.providerMetadata != null) {\n return { ...acc, ...part.providerMetadata };\n }\n return acc;\n }, {});\n modelMessages.push({\n role: \"system\",\n content: textParts.map((part) => part.text).join(\"\"),\n ...Object.keys(providerMetadata).length > 0 ? { providerOptions: providerMetadata } : {}\n });\n break;\n }\n case \"user\": {\n modelMessages.push({\n role: \"user\",\n content: message.parts.map((part) => {\n var _a21;\n if (isTextUIPart(part)) {\n return {\n type: \"text\",\n text: part.text,\n ...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n };\n }\n if (isFileUIPart(part)) {\n return {\n type: \"file\",\n mediaType: part.mediaType,\n filename: part.filename,\n data: part.url,\n ...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n };\n }\n if (isDataUIPart(part)) {\n return (_a21 = options == null ? void 0 : options.convertDataPart) == null ? void 0 : _a21.call(\n options,\n part\n );\n }\n }).filter(isNonNullable)\n });\n break;\n }\n case \"assistant\": {\n if (message.parts != null) {\n let block = [];\n async function processBlock() {\n var _a21, _b, _c, _d, _e, _f;\n if (block.length === 0) {\n return;\n }\n const content = [];\n for (const part of block) {\n if (isTextUIPart(part)) {\n content.push({\n type: \"text\",\n text: part.text,\n ...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n });\n } else if (isFileUIPart(part)) {\n content.push({\n type: \"file\",\n mediaType: part.mediaType,\n filename: part.filename,\n data: part.url,\n ...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n });\n } else if (isReasoningUIPart(part)) {\n content.push({\n type: \"reasoning\",\n text: part.text,\n providerOptions: part.providerMetadata\n });\n } else if (isToolUIPart(part)) {\n const toolName = getToolName(part);\n if (part.state !== \"input-streaming\") {\n content.push({\n type: \"tool-call\",\n toolCallId: part.toolCallId,\n toolName,\n input: part.state === \"output-error\" ? (_a21 = part.input) != null ? _a21 : \"rawInput\" in part ? part.rawInput : void 0 : part.input,\n providerExecuted: part.providerExecuted,\n ...part.callProviderMetadata != null ? { providerOptions: part.callProviderMetadata } : {}\n });\n if (part.approval != null) {\n content.push({\n type: \"tool-approval-request\",\n approvalId: part.approval.id,\n toolCallId: part.toolCallId\n });\n }\n if (part.providerExecuted === true && part.state !== \"approval-responded\" && (part.state === \"output-available\" || part.state === \"output-error\")) {\n content.push({\n type: \"tool-result\",\n toolCallId: part.toolCallId,\n toolName,\n output: await createToolModelOutput({\n toolCallId: part.toolCallId,\n input: part.input,\n output: part.state === \"output-error\" ? part.errorText : part.output,\n tool: (_b = options == null ? void 0 : options.tools) == null ? void 0 : _b[toolName],\n errorMode: part.state === \"output-error\" ? \"json\" : \"none\"\n }),\n ...part.callProviderMetadata != null ? { providerOptions: part.callProviderMetadata } : {}\n });\n }\n }\n } else if (isDataUIPart(part)) {\n const dataPart = (_c = options == null ? void 0 : options.convertDataPart) == null ? void 0 : _c.call(\n options,\n part\n );\n if (dataPart != null) {\n content.push(dataPart);\n }\n } else {\n const _exhaustiveCheck = part;\n throw new Error(`Unsupported part: ${_exhaustiveCheck}`);\n }\n }\n modelMessages.push({\n role: \"assistant\",\n content\n });\n const toolParts = block.filter(\n (part) => {\n var _a22;\n return isToolUIPart(part) && (part.providerExecuted !== true || ((_a22 = part.approval) == null ? void 0 : _a22.approved) != null);\n }\n );\n if (toolParts.length > 0) {\n {\n const content2 = [];\n for (const toolPart of toolParts) {\n if (((_d = toolPart.approval) == null ? void 0 : _d.approved) != null) {\n content2.push({\n type: \"tool-approval-response\",\n approvalId: toolPart.approval.id,\n approved: toolPart.approval.approved,\n reason: toolPart.approval.reason,\n providerExecuted: toolPart.providerExecuted\n });\n }\n if (toolPart.providerExecuted === true) {\n continue;\n }\n switch (toolPart.state) {\n case \"output-denied\": {\n content2.push({\n type: \"tool-result\",\n toolCallId: toolPart.toolCallId,\n toolName: getToolName(toolPart),\n output: {\n type: \"error-text\",\n value: (_e = toolPart.approval.reason) != null ? _e : \"Tool execution denied.\"\n },\n ...toolPart.callProviderMetadata != null ? { providerOptions: toolPart.callProviderMetadata } : {}\n });\n break;\n }\n case \"output-error\":\n case \"output-available\": {\n const toolName = getToolName(toolPart);\n content2.push({\n type: \"tool-result\",\n toolCallId: toolPart.toolCallId,\n toolName,\n output: await createToolModelOutput({\n toolCallId: toolPart.toolCallId,\n input: toolPart.input,\n output: toolPart.state === \"output-error\" ? toolPart.errorText : toolPart.output,\n tool: (_f = options == null ? void 0 : options.tools) == null ? void 0 : _f[toolName],\n errorMode: toolPart.state === \"output-error\" ? \"text\" : \"none\"\n }),\n ...toolPart.callProviderMetadata != null ? { providerOptions: toolPart.callProviderMetadata } : {}\n });\n break;\n }\n }\n }\n if (content2.length > 0) {\n modelMessages.push({\n role: \"tool\",\n content: content2\n });\n }\n }\n }\n block = [];\n }\n for (const part of message.parts) {\n if (isTextUIPart(part) || isReasoningUIPart(part) || isFileUIPart(part) || isToolUIPart(part) || isDataUIPart(part)) {\n block.push(part);\n } else if (part.type === \"step-start\") {\n await processBlock();\n }\n }\n await processBlock();\n break;\n }\n break;\n }\n default: {\n const _exhaustiveCheck = message.role;\n throw new MessageConversionError({\n originalMessage: message,\n message: `Unsupported role: ${_exhaustiveCheck}`\n });\n }\n }\n }\n return modelMessages;\n}\n\n// src/ui/validate-ui-messages.ts\nimport { TypeValidationError as TypeValidationError3 } from \"@ai-sdk/provider\";\nimport {\n lazySchema as lazySchema2,\n validateTypes as validateTypes2,\n zodSchema as zodSchema2\n} from \"@ai-sdk/provider-utils\";\nimport { z as z8 } from \"zod/v4\";\nvar uiMessagesSchema = lazySchema2(\n () => zodSchema2(\n z8.array(\n z8.object({\n id: z8.string(),\n role: z8.enum([\"system\", \"user\", \"assistant\"]),\n metadata: z8.unknown().optional(),\n parts: z8.array(\n z8.union([\n z8.object({\n type: z8.literal(\"text\"),\n text: z8.string(),\n state: z8.enum([\"streaming\", \"done\"]).optional(),\n providerMetadata: providerMetadataSchema.optional()\n }),\n z8.object({\n type: z8.literal(\"reasoning\"),\n text: z8.string(),\n state: z8.enum([\"streaming\", \"done\"]).optional(),\n providerMetadata: providerMetadataSchema.optional()\n }),\n z8.object({\n type: z8.literal(\"source-url\"),\n sourceId: z8.string(),\n url: z8.string(),\n title: z8.string().optional(),\n providerMetadata: providerMetadataSchema.optional()\n }),\n z8.object({\n type: z8.literal(\"source-document\"),\n sourceId: z8.string(),\n mediaType: z8.string(),\n title: z8.string(),\n filename: z8.string().optional(),\n providerMetadata: providerMetadataSchema.optional()\n }),\n z8.object({\n type: z8.literal(\"file\"),\n mediaType: z8.string(),\n filename: z8.string().optional(),\n url: z8.string(),\n providerMetadata: providerMetadataSchema.optional()\n }),\n z8.object({\n type: z8.literal(\"step-start\")\n }),\n z8.object({\n type: z8.string().startsWith(\"data-\"),\n id: z8.string().optional(),\n data: z8.unknown()\n }),\n z8.object({\n type: z8.literal(\"dynamic-tool\"),\n toolName: z8.string(),\n toolCallId: z8.string(),\n state: z8.literal(\"input-streaming\"),\n input: z8.unknown().optional(),\n providerExecuted: z8.boolean().optional(),\n callProviderMetadata: providerMetadataSchema.optional(),\n output: z8.never().optional(),\n errorText: z8.never().optional(),\n approval: z8.never().optional()\n }),\n z8.object({\n type: z8.literal(\"dynamic-tool\"),\n toolName: z8.string(),\n toolCallId: z8.string(),\n state: z8.literal(\"input-available\"),\n input: z8.unknown(),\n providerExecuted: z8.boolean().optional(),\n output: z8.never().optional(),\n errorText: z8.never().optional(),\n callProviderMetadata: providerMetadataSchema.optional(),\n approval: z8.never().optional()\n }),\n z8.object({\n type: z8.literal(\"dynamic-tool\"),\n toolName: z8.string(),\n toolCallId: z8.string(),\n state: z8.literal(\"approval-requested\"),\n input: z8.unknown(),\n providerExecuted: z8.boolean().optional(),\n output: z8.never().optional(),\n errorText: z8.never().optional(),\n callProviderMetadata: providerMetadataSchema.optional(),\n approval: z8.object({\n id: z8.string(),\n approved: z8.never().optional(),\n reason: z8.never().optional()\n })\n }),\n z8.object({\n type: z8.literal(\"dynamic-tool\"),\n toolName: z8.string(),\n toolCallId: z8.string(),\n state: z8.literal(\"approval-responded\"),\n input: z8.unknown(),\n providerExecuted: z8.boolean().optional(),\n output: z8.never().optional(),\n errorText: z8.never().optional(),\n callProviderMetadata: providerMetadataSchema.optional(),\n approval: z8.object({\n id: z8.string(),\n approved: z8.boolean(),\n reason: z8.string().optional()\n })\n }),\n z8.object({\n type: z8.literal(\"dynamic-tool\"),\n toolName: z8.string(),\n toolCallId: z8.string(),\n state: z8.literal(\"output-available\"),\n input: z8.unknown(),\n providerExecuted: z8.boolean().optional(),\n output: z8.unknown(),\n errorText: z8.never().optional(),\n callProviderMetadata: providerMetadataSchema.optional(),\n preliminary: z8.boolean().optional(),\n approval: z8.object({\n id: z8.string(),\n approved: z8.literal(true),\n reason: z8.string().optional()\n }).optional()\n }),\n z8.object({\n type: z8.literal(\"dynamic-tool\"),\n toolName: z8.string(),\n toolCallId: z8.string(),\n state: z8.literal(\"output-error\"),\n input: z8.unknown(),\n rawInput: z8.unknown().optional(),\n providerExecuted: z8.boolean().optional(),\n output: z8.never().optional(),\n errorText: z8.string(),\n callProviderMetadata: providerMetadataSchema.optional(),\n approval: z8.object({\n id: z8.string(),\n approved: z8.literal(true),\n reason: z8.string().optional()\n }).optional()\n }),\n z8.object({\n type: z8.literal(\"dynamic-tool\"),\n toolName: z8.string(),\n toolCallId: z8.string(),\n state: z8.literal(\"output-denied\"),\n input: z8.unknown(),\n providerExecuted: z8.boolean().optional(),\n output: z8.never().optional(),\n errorText: z8.never().optional(),\n callProviderMetadata: providerMetadataSchema.optional(),\n approval: z8.object({\n id: z8.string(),\n approved: z8.literal(false),\n reason: z8.string().optional()\n })\n }),\n z8.object({\n type: z8.string().startsWith(\"tool-\"),\n toolCallId: z8.string(),\n state: z8.literal(\"input-streaming\"),\n providerExecuted: z8.boolean().optional(),\n callProviderMetadata: providerMetadataSchema.optional(),\n input: z8.unknown().optional(),\n output: z8.never().optional(),\n errorText: z8.never().optional(),\n approval: z8.never().optional()\n }),\n z8.object({\n type: z8.string().startsWith(\"tool-\"),\n toolCallId: z8.string(),\n state: z8.literal(\"input-available\"),\n providerExecuted: z8.boolean().optional(),\n input: z8.unknown(),\n output: z8.never().optional(),\n errorText: z8.never().optional(),\n callProviderMetadata: providerMetadataSchema.optional(),\n approval: z8.never().optional()\n }),\n z8.object({\n type: z8.string().startsWith(\"tool-\"),\n toolCallId: z8.string(),\n state: z8.literal(\"approval-requested\"),\n input: z8.unknown(),\n providerExecuted: z8.boolean().optional(),\n output: z8.never().optional(),\n errorText: z8.never().optional(),\n callProviderMetadata: providerMetadataSchema.optional(),\n approval: z8.object({\n id: z8.string(),\n approved: z8.never().optional(),\n reason: z8.never().optional()\n })\n }),\n z8.object({\n type: z8.string().startsWith(\"tool-\"),\n toolCallId: z8.string(),\n state: z8.literal(\"approval-responded\"),\n input: z8.unknown(),\n providerExecuted: z8.boolean().optional(),\n output: z8.never().optional(),\n errorText: z8.never().optional(),\n callProviderMetadata: providerMetadataSchema.optional(),\n approval: z8.object({\n id: z8.string(),\n approved: z8.boolean(),\n reason: z8.string().optional()\n })\n }),\n z8.object({\n type: z8.string().startsWith(\"tool-\"),\n toolCallId: z8.string(),\n state: z8.literal(\"output-available\"),\n providerExecuted: z8.boolean().optional(),\n input: z8.unknown(),\n output: z8.unknown(),\n errorText: z8.never().optional(),\n callProviderMetadata: providerMetadataSchema.optional(),\n preliminary: z8.boolean().optional(),\n approval: z8.object({\n id: z8.string(),\n approved: z8.literal(true),\n reason: z8.string().optional()\n }).optional()\n }),\n z8.object({\n type: z8.string().startsWith(\"tool-\"),\n toolCallId: z8.string(),\n state: z8.literal(\"output-error\"),\n providerExecuted: z8.boolean().optional(),\n input: z8.unknown(),\n rawInput: z8.unknown().optional(),\n output: z8.never().optional(),\n errorText: z8.string(),\n callProviderMetadata: providerMetadataSchema.optional(),\n approval: z8.object({\n id: z8.string(),\n approved: z8.literal(true),\n reason: z8.string().optional()\n }).optional()\n }),\n z8.object({\n type: z8.string().startsWith(\"tool-\"),\n toolCallId: z8.string(),\n state: z8.literal(\"output-denied\"),\n providerExecuted: z8.boolean().optional(),\n input: z8.unknown(),\n output: z8.never().optional(),\n errorText: z8.never().optional(),\n callProviderMetadata: providerMetadataSchema.optional(),\n approval: z8.object({\n id: z8.string(),\n approved: z8.literal(false),\n reason: z8.string().optional()\n })\n })\n ])\n ).nonempty(\"Message must contain at least one part\")\n })\n ).nonempty(\"Messages array must not be empty\")\n )\n);\nasync function safeValidateUIMessages({\n messages,\n metadataSchema,\n dataSchemas,\n tools\n}) {\n try {\n if (messages == null) {\n return {\n success: false,\n error: new InvalidArgumentError({\n parameter: \"messages\",\n value: messages,\n message: \"messages parameter must be provided\"\n })\n };\n }\n const validatedMessages = await validateTypes2({\n value: messages,\n schema: uiMessagesSchema\n });\n if (metadataSchema) {\n for (const [msgIdx, message] of validatedMessages.entries()) {\n await validateTypes2({\n value: message.metadata,\n schema: metadataSchema,\n context: {\n field: `messages[${msgIdx}].metadata`,\n entityId: message.id\n }\n });\n }\n }\n if (dataSchemas || tools) {\n for (const [msgIdx, message] of validatedMessages.entries()) {\n for (const [partIdx, part] of message.parts.entries()) {\n if (dataSchemas && part.type.startsWith(\"data-\")) {\n const dataPart = part;\n const dataName = dataPart.type.slice(5);\n const dataSchema = dataSchemas[dataName];\n if (!dataSchema) {\n return {\n success: false,\n error: new TypeValidationError3({\n value: dataPart.data,\n cause: `No data schema found for data part ${dataName}`,\n context: {\n field: `messages[${msgIdx}].parts[${partIdx}].data`,\n entityName: dataName,\n entityId: dataPart.id\n }\n })\n };\n }\n await validateTypes2({\n value: dataPart.data,\n schema: dataSchema,\n context: {\n field: `messages[${msgIdx}].parts[${partIdx}].data`,\n entityName: dataName,\n entityId: dataPart.id\n }\n });\n }\n if (tools && part.type.startsWith(\"tool-\")) {\n const toolPart = part;\n const toolName = toolPart.type.slice(5);\n const tool2 = tools[toolName];\n if (!tool2) {\n return {\n success: false,\n error: new TypeValidationError3({\n value: toolPart.input,\n cause: `No tool schema found for tool part ${toolName}`,\n context: {\n field: `messages[${msgIdx}].parts[${partIdx}].input`,\n entityName: toolName,\n entityId: toolPart.toolCallId\n }\n })\n };\n }\n if (toolPart.state === \"input-available\" || toolPart.state === \"output-available\" || toolPart.state === \"output-error\" && toolPart.input !== void 0) {\n await validateTypes2({\n value: toolPart.input,\n schema: tool2.inputSchema,\n context: {\n field: `messages[${msgIdx}].parts[${partIdx}].input`,\n entityName: toolName,\n entityId: toolPart.toolCallId\n }\n });\n }\n if (toolPart.state === \"output-available\" && tool2.outputSchema) {\n await validateTypes2({\n value: toolPart.output,\n schema: tool2.outputSchema,\n context: {\n field: `messages[${msgIdx}].parts[${partIdx}].output`,\n entityName: toolName,\n entityId: toolPart.toolCallId\n }\n });\n }\n }\n }\n }\n }\n return {\n success: true,\n data: validatedMessages\n };\n } catch (error) {\n const err = error;\n return {\n success: false,\n error: err\n };\n }\n}\nasync function validateUIMessages({\n messages,\n metadataSchema,\n dataSchemas,\n tools\n}) {\n const response = await safeValidateUIMessages({\n messages,\n metadataSchema,\n dataSchemas,\n tools\n });\n if (!response.success)\n throw response.error;\n return response.data;\n}\n\n// src/agent/create-agent-ui-stream.ts\nasync function createAgentUIStream({\n agent,\n uiMessages,\n options,\n abortSignal,\n timeout,\n experimental_transform,\n onStepFinish,\n ...uiMessageStreamOptions\n}) {\n var _a21;\n const validatedMessages = await validateUIMessages({\n messages: uiMessages,\n tools: agent.tools\n });\n const modelMessages = await convertToModelMessages(validatedMessages, {\n tools: agent.tools\n });\n const result = await agent.stream({\n prompt: modelMessages,\n options,\n abortSignal,\n timeout,\n experimental_transform,\n onStepFinish\n });\n return result.toUIMessageStream({\n ...uiMessageStreamOptions,\n // TODO reading `originalMessages` is here for bc, always use `validatedMessages` in v7\n originalMessages: (_a21 = uiMessageStreamOptions.originalMessages) != null ? _a21 : validatedMessages\n });\n}\n\n// src/agent/create-agent-ui-stream-response.ts\nasync function createAgentUIStreamResponse({\n headers,\n status,\n statusText,\n consumeSseStream,\n ...options\n}) {\n return createUIMessageStreamResponse({\n headers,\n status,\n statusText,\n consumeSseStream,\n stream: await createAgentUIStream(options)\n });\n}\n\n// src/agent/pipe-agent-ui-stream-to-response.ts\nasync function pipeAgentUIStreamToResponse({\n response,\n headers,\n status,\n statusText,\n consumeSseStream,\n ...options\n}) {\n pipeUIMessageStreamToResponse({\n response,\n headers,\n status,\n statusText,\n consumeSseStream,\n stream: await createAgentUIStream(options)\n });\n}\n\n// src/embed/embed.ts\nimport { withUserAgentSuffix as withUserAgentSuffix3 } from \"@ai-sdk/provider-utils\";\nasync function embed({\n model: modelArg,\n value,\n providerOptions,\n maxRetries: maxRetriesArg,\n abortSignal,\n headers,\n experimental_telemetry: telemetry\n}) {\n const model = resolveEmbeddingModel(modelArg);\n const { maxRetries, retry } = prepareRetries({\n maxRetries: maxRetriesArg,\n abortSignal\n });\n const headersWithUserAgent = withUserAgentSuffix3(\n headers != null ? headers : {},\n `ai/${VERSION}`\n );\n const baseTelemetryAttributes = getBaseTelemetryAttributes({\n model,\n telemetry,\n headers: headersWithUserAgent,\n settings: { maxRetries }\n });\n const tracer = getTracer(telemetry);\n return recordSpan({\n name: \"ai.embed\",\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({ operationId: \"ai.embed\", telemetry }),\n ...baseTelemetryAttributes,\n \"ai.value\": { input: () => JSON.stringify(value) }\n }\n }),\n tracer,\n fn: async (span) => {\n const { embedding, usage, warnings, response, providerMetadata } = await retry(\n () => (\n // nested spans to align with the embedMany telemetry data:\n recordSpan({\n name: \"ai.embed.doEmbed\",\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: \"ai.embed.doEmbed\",\n telemetry\n }),\n ...baseTelemetryAttributes,\n // specific settings that only make sense on the outer level:\n \"ai.values\": { input: () => [JSON.stringify(value)] }\n }\n }),\n tracer,\n fn: async (doEmbedSpan) => {\n var _a21;\n const modelResponse = await model.doEmbed({\n values: [value],\n abortSignal,\n headers: headersWithUserAgent,\n providerOptions\n });\n const embedding2 = modelResponse.embeddings[0];\n const usage2 = (_a21 = modelResponse.usage) != null ? _a21 : { tokens: NaN };\n doEmbedSpan.setAttributes(\n await selectTelemetryAttributes({\n telemetry,\n attributes: {\n \"ai.embeddings\": {\n output: () => modelResponse.embeddings.map(\n (embedding3) => JSON.stringify(embedding3)\n )\n },\n \"ai.usage.tokens\": usage2.tokens\n }\n })\n );\n return {\n embedding: embedding2,\n usage: usage2,\n warnings: modelResponse.warnings,\n providerMetadata: modelResponse.providerMetadata,\n response: modelResponse.response\n };\n }\n })\n )\n );\n span.setAttributes(\n await selectTelemetryAttributes({\n telemetry,\n attributes: {\n \"ai.embedding\": { output: () => JSON.stringify(embedding) },\n \"ai.usage.tokens\": usage.tokens\n }\n })\n );\n logWarnings({ warnings, provider: model.provider, model: model.modelId });\n return new DefaultEmbedResult({\n value,\n embedding,\n usage,\n warnings,\n providerMetadata,\n response\n });\n }\n });\n}\nvar DefaultEmbedResult = class {\n constructor(options) {\n this.value = options.value;\n this.embedding = options.embedding;\n this.usage = options.usage;\n this.warnings = options.warnings;\n this.providerMetadata = options.providerMetadata;\n this.response = options.response;\n }\n};\n\n// src/embed/embed-many.ts\nimport { withUserAgentSuffix as withUserAgentSuffix4 } from \"@ai-sdk/provider-utils\";\n\n// src/util/split-array.ts\nfunction splitArray(array2, chunkSize) {\n if (chunkSize <= 0) {\n throw new Error(\"chunkSize must be greater than 0\");\n }\n const result = [];\n for (let i = 0; i < array2.length; i += chunkSize) {\n result.push(array2.slice(i, i + chunkSize));\n }\n return result;\n}\n\n// src/embed/embed-many.ts\nasync function embedMany({\n model: modelArg,\n values,\n maxParallelCalls = Infinity,\n maxRetries: maxRetriesArg,\n abortSignal,\n headers,\n providerOptions,\n experimental_telemetry: telemetry\n}) {\n const model = resolveEmbeddingModel(modelArg);\n const { maxRetries, retry } = prepareRetries({\n maxRetries: maxRetriesArg,\n abortSignal\n });\n const headersWithUserAgent = withUserAgentSuffix4(\n headers != null ? headers : {},\n `ai/${VERSION}`\n );\n const baseTelemetryAttributes = getBaseTelemetryAttributes({\n model,\n telemetry,\n headers: headersWithUserAgent,\n settings: { maxRetries }\n });\n const tracer = getTracer(telemetry);\n return recordSpan({\n name: \"ai.embedMany\",\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({ operationId: \"ai.embedMany\", telemetry }),\n ...baseTelemetryAttributes,\n // specific settings that only make sense on the outer level:\n \"ai.values\": {\n input: () => values.map((value) => JSON.stringify(value))\n }\n }\n }),\n tracer,\n fn: async (span) => {\n var _a21;\n const [maxEmbeddingsPerCall, supportsParallelCalls] = await Promise.all([\n model.maxEmbeddingsPerCall,\n model.supportsParallelCalls\n ]);\n if (maxEmbeddingsPerCall == null || maxEmbeddingsPerCall === Infinity) {\n const { embeddings: embeddings2, usage, warnings: warnings2, response, providerMetadata: providerMetadata2 } = await retry(() => {\n return recordSpan({\n name: \"ai.embedMany.doEmbed\",\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: \"ai.embedMany.doEmbed\",\n telemetry\n }),\n ...baseTelemetryAttributes,\n // specific settings that only make sense on the outer level:\n \"ai.values\": {\n input: () => values.map((value) => JSON.stringify(value))\n }\n }\n }),\n tracer,\n fn: async (doEmbedSpan) => {\n var _a22;\n const modelResponse = await model.doEmbed({\n values,\n abortSignal,\n headers: headersWithUserAgent,\n providerOptions\n });\n const embeddings3 = modelResponse.embeddings;\n const usage2 = (_a22 = modelResponse.usage) != null ? _a22 : { tokens: NaN };\n doEmbedSpan.setAttributes(\n await selectTelemetryAttributes({\n telemetry,\n attributes: {\n \"ai.embeddings\": {\n output: () => embeddings3.map(\n (embedding) => JSON.stringify(embedding)\n )\n },\n \"ai.usage.tokens\": usage2.tokens\n }\n })\n );\n return {\n embeddings: embeddings3,\n usage: usage2,\n warnings: modelResponse.warnings,\n providerMetadata: modelResponse.providerMetadata,\n response: modelResponse.response\n };\n }\n });\n });\n span.setAttributes(\n await selectTelemetryAttributes({\n telemetry,\n attributes: {\n \"ai.embeddings\": {\n output: () => embeddings2.map((embedding) => JSON.stringify(embedding))\n },\n \"ai.usage.tokens\": usage.tokens\n }\n })\n );\n logWarnings({\n warnings: warnings2,\n provider: model.provider,\n model: model.modelId\n });\n return new DefaultEmbedManyResult({\n values,\n embeddings: embeddings2,\n usage,\n warnings: warnings2,\n providerMetadata: providerMetadata2,\n responses: [response]\n });\n }\n const valueChunks = splitArray(values, maxEmbeddingsPerCall);\n const embeddings = [];\n const warnings = [];\n const responses = [];\n let tokens = 0;\n let providerMetadata;\n const parallelChunks = splitArray(\n valueChunks,\n supportsParallelCalls ? maxParallelCalls : 1\n );\n for (const parallelChunk of parallelChunks) {\n const results = await Promise.all(\n parallelChunk.map((chunk) => {\n return retry(() => {\n return recordSpan({\n name: \"ai.embedMany.doEmbed\",\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: \"ai.embedMany.doEmbed\",\n telemetry\n }),\n ...baseTelemetryAttributes,\n // specific settings that only make sense on the outer level:\n \"ai.values\": {\n input: () => chunk.map((value) => JSON.stringify(value))\n }\n }\n }),\n tracer,\n fn: async (doEmbedSpan) => {\n var _a22;\n const modelResponse = await model.doEmbed({\n values: chunk,\n abortSignal,\n headers: headersWithUserAgent,\n providerOptions\n });\n const embeddings2 = modelResponse.embeddings;\n const usage = (_a22 = modelResponse.usage) != null ? _a22 : { tokens: NaN };\n doEmbedSpan.setAttributes(\n await selectTelemetryAttributes({\n telemetry,\n attributes: {\n \"ai.embeddings\": {\n output: () => embeddings2.map(\n (embedding) => JSON.stringify(embedding)\n )\n },\n \"ai.usage.tokens\": usage.tokens\n }\n })\n );\n return {\n embeddings: embeddings2,\n usage,\n warnings: modelResponse.warnings,\n providerMetadata: modelResponse.providerMetadata,\n response: modelResponse.response\n };\n }\n });\n });\n })\n );\n for (const result of results) {\n embeddings.push(...result.embeddings);\n warnings.push(...result.warnings);\n responses.push(result.response);\n tokens += result.usage.tokens;\n if (result.providerMetadata) {\n if (!providerMetadata) {\n providerMetadata = { ...result.providerMetadata };\n } else {\n for (const [providerName, metadata] of Object.entries(\n result.providerMetadata\n )) {\n providerMetadata[providerName] = {\n ...(_a21 = providerMetadata[providerName]) != null ? _a21 : {},\n ...metadata\n };\n }\n }\n }\n }\n }\n span.setAttributes(\n await selectTelemetryAttributes({\n telemetry,\n attributes: {\n \"ai.embeddings\": {\n output: () => embeddings.map((embedding) => JSON.stringify(embedding))\n },\n \"ai.usage.tokens\": tokens\n }\n })\n );\n logWarnings({\n warnings,\n provider: model.provider,\n model: model.modelId\n });\n return new DefaultEmbedManyResult({\n values,\n embeddings,\n usage: { tokens },\n warnings,\n providerMetadata,\n responses\n });\n }\n });\n}\nvar DefaultEmbedManyResult = class {\n constructor(options) {\n this.values = options.values;\n this.embeddings = options.embeddings;\n this.usage = options.usage;\n this.warnings = options.warnings;\n this.providerMetadata = options.providerMetadata;\n this.responses = options.responses;\n }\n};\n\n// src/generate-image/generate-image.ts\nimport {\n convertBase64ToUint8Array as convertBase64ToUint8Array4,\n withUserAgentSuffix as withUserAgentSuffix5\n} from \"@ai-sdk/provider-utils\";\nasync function generateImage({\n model: modelArg,\n prompt: promptArg,\n n = 1,\n maxImagesPerCall,\n size,\n aspectRatio,\n seed,\n providerOptions,\n maxRetries: maxRetriesArg,\n abortSignal,\n headers\n}) {\n var _a21, _b;\n const model = resolveImageModel(modelArg);\n const headersWithUserAgent = withUserAgentSuffix5(\n headers != null ? headers : {},\n `ai/${VERSION}`\n );\n const { retry } = prepareRetries({\n maxRetries: maxRetriesArg,\n abortSignal\n });\n const maxImagesPerCallWithDefault = (_a21 = maxImagesPerCall != null ? maxImagesPerCall : await invokeModelMaxImagesPerCall(model)) != null ? _a21 : 1;\n const callCount = Math.ceil(n / maxImagesPerCallWithDefault);\n const callImageCounts = Array.from({ length: callCount }, (_, i) => {\n if (i < callCount - 1) {\n return maxImagesPerCallWithDefault;\n }\n const remainder = n % maxImagesPerCallWithDefault;\n return remainder === 0 ? maxImagesPerCallWithDefault : remainder;\n });\n const results = await Promise.all(\n callImageCounts.map(\n async (callImageCount) => retry(() => {\n const { prompt, files, mask } = normalizePrompt(promptArg);\n return model.doGenerate({\n prompt,\n files,\n mask,\n n: callImageCount,\n abortSignal,\n headers: headersWithUserAgent,\n size,\n aspectRatio,\n seed,\n providerOptions: providerOptions != null ? providerOptions : {}\n });\n })\n )\n );\n const images = [];\n const warnings = [];\n const responses = [];\n const providerMetadata = {};\n let totalUsage = {\n inputTokens: void 0,\n outputTokens: void 0,\n totalTokens: void 0\n };\n for (const result of results) {\n images.push(\n ...result.images.map(\n (image) => {\n var _a22;\n return new DefaultGeneratedFile({\n data: image,\n mediaType: (_a22 = detectMediaType({\n data: image,\n signatures: imageMediaTypeSignatures\n })) != null ? _a22 : \"image/png\"\n });\n }\n )\n );\n warnings.push(...result.warnings);\n if (result.usage != null) {\n totalUsage = addImageModelUsage(totalUsage, result.usage);\n }\n if (result.providerMetadata) {\n for (const [providerName, metadata] of Object.entries(result.providerMetadata)) {\n if (providerName === \"gateway\") {\n const currentEntry = providerMetadata[providerName];\n if (currentEntry != null && typeof currentEntry === \"object\") {\n providerMetadata[providerName] = {\n ...currentEntry,\n ...metadata\n };\n } else {\n providerMetadata[providerName] = metadata;\n }\n const imagesValue = providerMetadata[providerName].images;\n if (Array.isArray(imagesValue) && imagesValue.length === 0) {\n delete providerMetadata[providerName].images;\n }\n } else {\n (_b = providerMetadata[providerName]) != null ? _b : providerMetadata[providerName] = { images: [] };\n providerMetadata[providerName].images.push(\n ...result.providerMetadata[providerName].images\n );\n }\n }\n }\n responses.push(result.response);\n }\n logWarnings({ warnings, provider: model.provider, model: model.modelId });\n if (!images.length) {\n throw new NoImageGeneratedError({ responses });\n }\n return new DefaultGenerateImageResult({\n images,\n warnings,\n responses,\n providerMetadata,\n usage: totalUsage\n });\n}\nvar DefaultGenerateImageResult = class {\n constructor(options) {\n this.images = options.images;\n this.warnings = options.warnings;\n this.responses = options.responses;\n this.providerMetadata = options.providerMetadata;\n this.usage = options.usage;\n }\n get image() {\n return this.images[0];\n }\n};\nasync function invokeModelMaxImagesPerCall(model) {\n const isFunction = model.maxImagesPerCall instanceof Function;\n if (!isFunction) {\n return model.maxImagesPerCall;\n }\n return model.maxImagesPerCall({\n modelId: model.modelId\n });\n}\nfunction normalizePrompt(prompt) {\n if (typeof prompt === \"string\") {\n return { prompt, files: void 0, mask: void 0 };\n }\n return {\n prompt: prompt.text,\n files: prompt.images.map(toImageModelV3File),\n mask: prompt.mask ? toImageModelV3File(prompt.mask) : void 0\n };\n}\nfunction toImageModelV3File(dataContent) {\n if (typeof dataContent === \"string\" && dataContent.startsWith(\"http\")) {\n return {\n type: \"url\",\n url: dataContent\n };\n }\n if (typeof dataContent === \"string\" && dataContent.startsWith(\"data:\")) {\n const { mediaType: dataUrlMediaType, base64Content } = splitDataUrl(dataContent);\n if (base64Content != null) {\n const uint8Data2 = convertBase64ToUint8Array4(base64Content);\n return {\n type: \"file\",\n data: uint8Data2,\n mediaType: dataUrlMediaType || detectMediaType({\n data: uint8Data2,\n signatures: imageMediaTypeSignatures\n }) || \"image/png\"\n };\n }\n }\n const uint8Data = convertDataContentToUint8Array(dataContent);\n return {\n type: \"file\",\n data: uint8Data,\n mediaType: detectMediaType({\n data: uint8Data,\n signatures: imageMediaTypeSignatures\n }) || \"image/png\"\n };\n}\n\n// src/generate-image/index.ts\nvar experimental_generateImage = generateImage;\n\n// src/generate-object/generate-object.ts\nimport {\n createIdGenerator as createIdGenerator3,\n withUserAgentSuffix as withUserAgentSuffix6\n} from \"@ai-sdk/provider-utils\";\n\n// src/generate-object/output-strategy.ts\nimport {\n isJSONArray,\n isJSONObject,\n TypeValidationError as TypeValidationError4,\n UnsupportedFunctionalityError as UnsupportedFunctionalityError3\n} from \"@ai-sdk/provider\";\nimport {\n asSchema as asSchema4,\n safeValidateTypes as safeValidateTypes4\n} from \"@ai-sdk/provider-utils\";\nvar noSchemaOutputStrategy = {\n type: \"no-schema\",\n jsonSchema: async () => void 0,\n async validatePartialResult({ value, textDelta }) {\n return { success: true, value: { partial: value, textDelta } };\n },\n async validateFinalResult(value, context2) {\n return value === void 0 ? {\n success: false,\n error: new NoObjectGeneratedError({\n message: \"No object generated: response did not match schema.\",\n text: context2.text,\n response: context2.response,\n usage: context2.usage,\n finishReason: context2.finishReason\n })\n } : { success: true, value };\n },\n createElementStream() {\n throw new UnsupportedFunctionalityError3({\n functionality: \"element streams in no-schema mode\"\n });\n }\n};\nvar objectOutputStrategy = (schema) => ({\n type: \"object\",\n jsonSchema: async () => await schema.jsonSchema,\n async validatePartialResult({ value, textDelta }) {\n return {\n success: true,\n value: {\n // Note: currently no validation of partial results:\n partial: value,\n textDelta\n }\n };\n },\n async validateFinalResult(value) {\n return safeValidateTypes4({ value, schema });\n },\n createElementStream() {\n throw new UnsupportedFunctionalityError3({\n functionality: \"element streams in object mode\"\n });\n }\n});\nvar arrayOutputStrategy = (schema) => {\n return {\n type: \"array\",\n // wrap in object that contains array of elements, since most LLMs will not\n // be able to generate an array directly:\n // possible future optimization: use arrays directly when model supports grammar-guided generation\n jsonSchema: async () => {\n const { $schema, ...itemSchema } = await schema.jsonSchema;\n return {\n $schema: \"http://json-schema.org/draft-07/schema#\",\n type: \"object\",\n properties: {\n elements: { type: \"array\", items: itemSchema }\n },\n required: [\"elements\"],\n additionalProperties: false\n };\n },\n async validatePartialResult({\n value,\n latestObject,\n isFirstDelta,\n isFinalDelta\n }) {\n var _a21;\n if (!isJSONObject(value) || !isJSONArray(value.elements)) {\n return {\n success: false,\n error: new TypeValidationError4({\n value,\n cause: \"value must be an object that contains an array of elements\"\n })\n };\n }\n const inputArray = value.elements;\n const resultArray = [];\n for (let i = 0; i < inputArray.length; i++) {\n const element = inputArray[i];\n const result = await safeValidateTypes4({ value: element, schema });\n if (i === inputArray.length - 1 && !isFinalDelta) {\n continue;\n }\n if (!result.success) {\n return result;\n }\n resultArray.push(result.value);\n }\n const publishedElementCount = (_a21 = latestObject == null ? void 0 : latestObject.length) != null ? _a21 : 0;\n let textDelta = \"\";\n if (isFirstDelta) {\n textDelta += \"[\";\n }\n if (publishedElementCount > 0) {\n textDelta += \",\";\n }\n textDelta += resultArray.slice(publishedElementCount).map((element) => JSON.stringify(element)).join(\",\");\n if (isFinalDelta) {\n textDelta += \"]\";\n }\n return {\n success: true,\n value: {\n partial: resultArray,\n textDelta\n }\n };\n },\n async validateFinalResult(value) {\n if (!isJSONObject(value) || !isJSONArray(value.elements)) {\n return {\n success: false,\n error: new TypeValidationError4({\n value,\n cause: \"value must be an object that contains an array of elements\"\n })\n };\n }\n const inputArray = value.elements;\n for (const element of inputArray) {\n const result = await safeValidateTypes4({ value: element, schema });\n if (!result.success) {\n return result;\n }\n }\n return { success: true, value: inputArray };\n },\n createElementStream(originalStream) {\n let publishedElements = 0;\n return createAsyncIterableStream(\n originalStream.pipeThrough(\n new TransformStream({\n transform(chunk, controller) {\n switch (chunk.type) {\n case \"object\": {\n const array2 = chunk.object;\n for (; publishedElements < array2.length; publishedElements++) {\n controller.enqueue(array2[publishedElements]);\n }\n break;\n }\n case \"text-delta\":\n case \"finish\":\n case \"error\":\n break;\n default: {\n const _exhaustiveCheck = chunk;\n throw new Error(\n `Unsupported chunk type: ${_exhaustiveCheck}`\n );\n }\n }\n }\n })\n )\n );\n }\n };\n};\nvar enumOutputStrategy = (enumValues) => {\n return {\n type: \"enum\",\n // wrap in object that contains result, since most LLMs will not\n // be able to generate an enum value directly:\n // possible future optimization: use enums directly when model supports top-level enums\n jsonSchema: async () => ({\n $schema: \"http://json-schema.org/draft-07/schema#\",\n type: \"object\",\n properties: {\n result: { type: \"string\", enum: enumValues }\n },\n required: [\"result\"],\n additionalProperties: false\n }),\n async validateFinalResult(value) {\n if (!isJSONObject(value) || typeof value.result !== \"string\") {\n return {\n success: false,\n error: new TypeValidationError4({\n value,\n cause: 'value must be an object that contains a string in the \"result\" property.'\n })\n };\n }\n const result = value.result;\n return enumValues.includes(result) ? { success: true, value: result } : {\n success: false,\n error: new TypeValidationError4({\n value,\n cause: \"value must be a string in the enum\"\n })\n };\n },\n async validatePartialResult({ value, textDelta }) {\n if (!isJSONObject(value) || typeof value.result !== \"string\") {\n return {\n success: false,\n error: new TypeValidationError4({\n value,\n cause: 'value must be an object that contains a string in the \"result\" property.'\n })\n };\n }\n const result = value.result;\n const possibleEnumValues = enumValues.filter(\n (enumValue) => enumValue.startsWith(result)\n );\n if (value.result.length === 0 || possibleEnumValues.length === 0) {\n return {\n success: false,\n error: new TypeValidationError4({\n value,\n cause: \"value must be a string in the enum\"\n })\n };\n }\n return {\n success: true,\n value: {\n partial: possibleEnumValues.length > 1 ? result : possibleEnumValues[0],\n textDelta\n }\n };\n },\n createElementStream() {\n throw new UnsupportedFunctionalityError3({\n functionality: \"element streams in enum mode\"\n });\n }\n };\n};\nfunction getOutputStrategy({\n output,\n schema,\n enumValues\n}) {\n switch (output) {\n case \"object\":\n return objectOutputStrategy(asSchema4(schema));\n case \"array\":\n return arrayOutputStrategy(asSchema4(schema));\n case \"enum\":\n return enumOutputStrategy(enumValues);\n case \"no-schema\":\n return noSchemaOutputStrategy;\n default: {\n const _exhaustiveCheck = output;\n throw new Error(`Unsupported output: ${_exhaustiveCheck}`);\n }\n }\n}\n\n// src/generate-object/parse-and-validate-object-result.ts\nimport { JSONParseError as JSONParseError2, TypeValidationError as TypeValidationError5 } from \"@ai-sdk/provider\";\nimport { safeParseJSON as safeParseJSON4 } from \"@ai-sdk/provider-utils\";\nasync function parseAndValidateObjectResult(result, outputStrategy, context2) {\n const parseResult = await safeParseJSON4({ text: result });\n if (!parseResult.success) {\n throw new NoObjectGeneratedError({\n message: \"No object generated: could not parse the response.\",\n cause: parseResult.error,\n text: result,\n response: context2.response,\n usage: context2.usage,\n finishReason: context2.finishReason\n });\n }\n const validationResult = await outputStrategy.validateFinalResult(\n parseResult.value,\n {\n text: result,\n response: context2.response,\n usage: context2.usage\n }\n );\n if (!validationResult.success) {\n throw new NoObjectGeneratedError({\n message: \"No object generated: response did not match schema.\",\n cause: validationResult.error,\n text: result,\n response: context2.response,\n usage: context2.usage,\n finishReason: context2.finishReason\n });\n }\n return validationResult.value;\n}\nasync function parseAndValidateObjectResultWithRepair(result, outputStrategy, repairText, context2) {\n try {\n return await parseAndValidateObjectResult(result, outputStrategy, context2);\n } catch (error) {\n if (repairText != null && NoObjectGeneratedError.isInstance(error) && (JSONParseError2.isInstance(error.cause) || TypeValidationError5.isInstance(error.cause))) {\n const repairedText = await repairText({\n text: result,\n error: error.cause\n });\n if (repairedText === null) {\n throw error;\n }\n return await parseAndValidateObjectResult(\n repairedText,\n outputStrategy,\n context2\n );\n }\n throw error;\n }\n}\n\n// src/generate-object/validate-object-generation-input.ts\nfunction validateObjectGenerationInput({\n output,\n schema,\n schemaName,\n schemaDescription,\n enumValues\n}) {\n if (output != null && output !== \"object\" && output !== \"array\" && output !== \"enum\" && output !== \"no-schema\") {\n throw new InvalidArgumentError({\n parameter: \"output\",\n value: output,\n message: \"Invalid output type.\"\n });\n }\n if (output === \"no-schema\") {\n if (schema != null) {\n throw new InvalidArgumentError({\n parameter: \"schema\",\n value: schema,\n message: \"Schema is not supported for no-schema output.\"\n });\n }\n if (schemaDescription != null) {\n throw new InvalidArgumentError({\n parameter: \"schemaDescription\",\n value: schemaDescription,\n message: \"Schema description is not supported for no-schema output.\"\n });\n }\n if (schemaName != null) {\n throw new InvalidArgumentError({\n parameter: \"schemaName\",\n value: schemaName,\n message: \"Schema name is not supported for no-schema output.\"\n });\n }\n if (enumValues != null) {\n throw new InvalidArgumentError({\n parameter: \"enumValues\",\n value: enumValues,\n message: \"Enum values are not supported for no-schema output.\"\n });\n }\n }\n if (output === \"object\") {\n if (schema == null) {\n throw new InvalidArgumentError({\n parameter: \"schema\",\n value: schema,\n message: \"Schema is required for object output.\"\n });\n }\n if (enumValues != null) {\n throw new InvalidArgumentError({\n parameter: \"enumValues\",\n value: enumValues,\n message: \"Enum values are not supported for object output.\"\n });\n }\n }\n if (output === \"array\") {\n if (schema == null) {\n throw new InvalidArgumentError({\n parameter: \"schema\",\n value: schema,\n message: \"Element schema is required for array output.\"\n });\n }\n if (enumValues != null) {\n throw new InvalidArgumentError({\n parameter: \"enumValues\",\n value: enumValues,\n message: \"Enum values are not supported for array output.\"\n });\n }\n }\n if (output === \"enum\") {\n if (schema != null) {\n throw new InvalidArgumentError({\n parameter: \"schema\",\n value: schema,\n message: \"Schema is not supported for enum output.\"\n });\n }\n if (schemaDescription != null) {\n throw new InvalidArgumentError({\n parameter: \"schemaDescription\",\n value: schemaDescription,\n message: \"Schema description is not supported for enum output.\"\n });\n }\n if (schemaName != null) {\n throw new InvalidArgumentError({\n parameter: \"schemaName\",\n value: schemaName,\n message: \"Schema name is not supported for enum output.\"\n });\n }\n if (enumValues == null) {\n throw new InvalidArgumentError({\n parameter: \"enumValues\",\n value: enumValues,\n message: \"Enum values are required for enum output.\"\n });\n }\n for (const value of enumValues) {\n if (typeof value !== \"string\") {\n throw new InvalidArgumentError({\n parameter: \"enumValues\",\n value,\n message: \"Enum values must be strings.\"\n });\n }\n }\n }\n}\n\n// src/generate-object/generate-object.ts\nvar originalGenerateId3 = createIdGenerator3({ prefix: \"aiobj\", size: 24 });\nasync function generateObject(options) {\n const {\n model: modelArg,\n output = \"object\",\n system,\n prompt,\n messages,\n maxRetries: maxRetriesArg,\n abortSignal,\n headers,\n experimental_repairText: repairText,\n experimental_telemetry: telemetry,\n experimental_download: download2,\n providerOptions,\n _internal: {\n generateId: generateId2 = originalGenerateId3,\n currentDate = () => /* @__PURE__ */ new Date()\n } = {},\n ...settings\n } = options;\n const model = resolveLanguageModel(modelArg);\n const enumValues = \"enum\" in options ? options.enum : void 0;\n const {\n schema: inputSchema,\n schemaDescription,\n schemaName\n } = \"schema\" in options ? options : {};\n validateObjectGenerationInput({\n output,\n schema: inputSchema,\n schemaName,\n schemaDescription,\n enumValues\n });\n const { maxRetries, retry } = prepareRetries({\n maxRetries: maxRetriesArg,\n abortSignal\n });\n const outputStrategy = getOutputStrategy({\n output,\n schema: inputSchema,\n enumValues\n });\n const callSettings = prepareCallSettings(settings);\n const headersWithUserAgent = withUserAgentSuffix6(\n headers != null ? headers : {},\n `ai/${VERSION}`\n );\n const baseTelemetryAttributes = getBaseTelemetryAttributes({\n model,\n telemetry,\n headers: headersWithUserAgent,\n settings: { ...callSettings, maxRetries }\n });\n const tracer = getTracer(telemetry);\n const jsonSchema2 = await outputStrategy.jsonSchema();\n try {\n return await recordSpan({\n name: \"ai.generateObject\",\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: \"ai.generateObject\",\n telemetry\n }),\n ...baseTelemetryAttributes,\n // specific settings that only make sense on the outer level:\n \"ai.prompt\": {\n input: () => JSON.stringify({ system, prompt, messages })\n },\n \"ai.schema\": jsonSchema2 != null ? { input: () => JSON.stringify(jsonSchema2) } : void 0,\n \"ai.schema.name\": schemaName,\n \"ai.schema.description\": schemaDescription,\n \"ai.settings.output\": outputStrategy.type\n }\n }),\n tracer,\n fn: async (span) => {\n var _a21;\n let result;\n let finishReason;\n let usage;\n let warnings;\n let response;\n let request;\n let resultProviderMetadata;\n let reasoning;\n const standardizedPrompt = await standardizePrompt({\n system,\n prompt,\n messages\n });\n const promptMessages = await convertToLanguageModelPrompt({\n prompt: standardizedPrompt,\n supportedUrls: await model.supportedUrls,\n download: download2\n });\n const generateResult = await retry(\n () => recordSpan({\n name: \"ai.generateObject.doGenerate\",\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: \"ai.generateObject.doGenerate\",\n telemetry\n }),\n ...baseTelemetryAttributes,\n \"ai.prompt.messages\": {\n input: () => stringifyForTelemetry(promptMessages)\n },\n // standardized gen-ai llm span attributes:\n \"gen_ai.system\": model.provider,\n \"gen_ai.request.model\": model.modelId,\n \"gen_ai.request.frequency_penalty\": callSettings.frequencyPenalty,\n \"gen_ai.request.max_tokens\": callSettings.maxOutputTokens,\n \"gen_ai.request.presence_penalty\": callSettings.presencePenalty,\n \"gen_ai.request.temperature\": callSettings.temperature,\n \"gen_ai.request.top_k\": callSettings.topK,\n \"gen_ai.request.top_p\": callSettings.topP\n }\n }),\n tracer,\n fn: async (span2) => {\n var _a22, _b, _c, _d, _e, _f, _g, _h;\n const result2 = await model.doGenerate({\n responseFormat: {\n type: \"json\",\n schema: jsonSchema2,\n name: schemaName,\n description: schemaDescription\n },\n ...prepareCallSettings(settings),\n prompt: promptMessages,\n providerOptions,\n abortSignal,\n headers: headersWithUserAgent\n });\n const responseData = {\n id: (_b = (_a22 = result2.response) == null ? void 0 : _a22.id) != null ? _b : generateId2(),\n timestamp: (_d = (_c = result2.response) == null ? void 0 : _c.timestamp) != null ? _d : currentDate(),\n modelId: (_f = (_e = result2.response) == null ? void 0 : _e.modelId) != null ? _f : model.modelId,\n headers: (_g = result2.response) == null ? void 0 : _g.headers,\n body: (_h = result2.response) == null ? void 0 : _h.body\n };\n const text2 = extractTextContent(result2.content);\n const reasoning2 = extractReasoningContent(result2.content);\n if (text2 === void 0) {\n throw new NoObjectGeneratedError({\n message: \"No object generated: the model did not return a response.\",\n response: responseData,\n usage: asLanguageModelUsage(result2.usage),\n finishReason: result2.finishReason.unified\n });\n }\n span2.setAttributes(\n await selectTelemetryAttributes({\n telemetry,\n attributes: {\n \"ai.response.finishReason\": result2.finishReason.unified,\n \"ai.response.object\": { output: () => text2 },\n \"ai.response.id\": responseData.id,\n \"ai.response.model\": responseData.modelId,\n \"ai.response.timestamp\": responseData.timestamp.toISOString(),\n \"ai.response.providerMetadata\": JSON.stringify(\n result2.providerMetadata\n ),\n // TODO rename telemetry attributes to inputTokens and outputTokens\n \"ai.usage.promptTokens\": result2.usage.inputTokens.total,\n \"ai.usage.completionTokens\": result2.usage.outputTokens.total,\n // standardized gen-ai llm span attributes:\n \"gen_ai.response.finish_reasons\": [\n result2.finishReason.unified\n ],\n \"gen_ai.response.id\": responseData.id,\n \"gen_ai.response.model\": responseData.modelId,\n \"gen_ai.usage.input_tokens\": result2.usage.inputTokens.total,\n \"gen_ai.usage.output_tokens\": result2.usage.outputTokens.total\n }\n })\n );\n return {\n ...result2,\n objectText: text2,\n reasoning: reasoning2,\n responseData\n };\n }\n })\n );\n result = generateResult.objectText;\n finishReason = generateResult.finishReason.unified;\n usage = asLanguageModelUsage(generateResult.usage);\n warnings = generateResult.warnings;\n resultProviderMetadata = generateResult.providerMetadata;\n request = (_a21 = generateResult.request) != null ? _a21 : {};\n response = generateResult.responseData;\n reasoning = generateResult.reasoning;\n logWarnings({\n warnings,\n provider: model.provider,\n model: model.modelId\n });\n const object2 = await parseAndValidateObjectResultWithRepair(\n result,\n outputStrategy,\n repairText,\n {\n response,\n usage,\n finishReason\n }\n );\n span.setAttributes(\n await selectTelemetryAttributes({\n telemetry,\n attributes: {\n \"ai.response.finishReason\": finishReason,\n \"ai.response.object\": {\n output: () => JSON.stringify(object2)\n },\n \"ai.response.providerMetadata\": JSON.stringify(\n resultProviderMetadata\n ),\n // TODO rename telemetry attributes to inputTokens and outputTokens\n \"ai.usage.promptTokens\": usage.inputTokens,\n \"ai.usage.completionTokens\": usage.outputTokens\n }\n })\n );\n return new DefaultGenerateObjectResult({\n object: object2,\n reasoning,\n finishReason,\n usage,\n warnings,\n request,\n response,\n providerMetadata: resultProviderMetadata\n });\n }\n });\n } catch (error) {\n throw wrapGatewayError(error);\n }\n}\nvar DefaultGenerateObjectResult = class {\n constructor(options) {\n this.object = options.object;\n this.finishReason = options.finishReason;\n this.usage = options.usage;\n this.warnings = options.warnings;\n this.providerMetadata = options.providerMetadata;\n this.response = options.response;\n this.request = options.request;\n this.reasoning = options.reasoning;\n }\n toJsonResponse(init) {\n var _a21;\n return new Response(JSON.stringify(this.object), {\n status: (_a21 = init == null ? void 0 : init.status) != null ? _a21 : 200,\n headers: prepareHeaders(init == null ? void 0 : init.headers, {\n \"content-type\": \"application/json; charset=utf-8\"\n })\n });\n }\n};\n\n// src/generate-object/stream-object.ts\nimport {\n createIdGenerator as createIdGenerator4,\n DelayedPromise as DelayedPromise2\n} from \"@ai-sdk/provider-utils\";\n\n// src/util/cosine-similarity.ts\nfunction cosineSimilarity(vector1, vector2) {\n if (vector1.length !== vector2.length) {\n throw new InvalidArgumentError({\n parameter: \"vector1,vector2\",\n value: { vector1Length: vector1.length, vector2Length: vector2.length },\n message: `Vectors must have the same length`\n });\n }\n const n = vector1.length;\n if (n === 0) {\n return 0;\n }\n let magnitudeSquared1 = 0;\n let magnitudeSquared2 = 0;\n let dotProduct = 0;\n for (let i = 0; i < n; i++) {\n const value1 = vector1[i];\n const value2 = vector2[i];\n magnitudeSquared1 += value1 * value1;\n magnitudeSquared2 += value2 * value2;\n dotProduct += value1 * value2;\n }\n return magnitudeSquared1 === 0 || magnitudeSquared2 === 0 ? 0 : dotProduct / (Math.sqrt(magnitudeSquared1) * Math.sqrt(magnitudeSquared2));\n}\n\n// src/util/download/create-download.ts\nfunction createDownload(options) {\n return ({ url, abortSignal }) => download({ url, maxBytes: options == null ? void 0 : options.maxBytes, abortSignal });\n}\n\n// src/util/data-url.ts\nfunction getTextFromDataUrl(dataUrl) {\n const [header, base64Content] = dataUrl.split(\",\");\n const mediaType = header.split(\";\")[0].split(\":\")[1];\n if (mediaType == null || base64Content == null) {\n throw new Error(\"Invalid data URL format\");\n }\n try {\n return window.atob(base64Content);\n } catch (error) {\n throw new Error(`Error decoding data URL`);\n }\n}\n\n// src/util/is-deep-equal-data.ts\nfunction isDeepEqualData(obj1, obj2) {\n if (obj1 === obj2)\n return true;\n if (obj1 == null || obj2 == null)\n return false;\n if (typeof obj1 !== \"object\" && typeof obj2 !== \"object\")\n return obj1 === obj2;\n if (obj1.constructor !== obj2.constructor)\n return false;\n if (obj1 instanceof Date && obj2 instanceof Date) {\n return obj1.getTime() === obj2.getTime();\n }\n if (Array.isArray(obj1)) {\n if (obj1.length !== obj2.length)\n return false;\n for (let i = 0; i < obj1.length; i++) {\n if (!isDeepEqualData(obj1[i], obj2[i]))\n return false;\n }\n return true;\n }\n const keys1 = Object.keys(obj1);\n const keys2 = Object.keys(obj2);\n if (keys1.length !== keys2.length)\n return false;\n for (const key of keys1) {\n if (!keys2.includes(key))\n return false;\n if (!isDeepEqualData(obj1[key], obj2[key]))\n return false;\n }\n return true;\n}\n\n// src/util/serial-job-executor.ts\nvar SerialJobExecutor = class {\n constructor() {\n this.queue = [];\n this.isProcessing = false;\n }\n async processQueue() {\n if (this.isProcessing) {\n return;\n }\n this.isProcessing = true;\n while (this.queue.length > 0) {\n await this.queue[0]();\n this.queue.shift();\n }\n this.isProcessing = false;\n }\n async run(job) {\n return new Promise((resolve3, reject) => {\n this.queue.push(async () => {\n try {\n await job();\n resolve3();\n } catch (error) {\n reject(error);\n }\n });\n void this.processQueue();\n });\n }\n};\n\n// src/util/simulate-readable-stream.ts\nimport { delay as delayFunction } from \"@ai-sdk/provider-utils\";\nfunction simulateReadableStream({\n chunks,\n initialDelayInMs = 0,\n chunkDelayInMs = 0,\n _internal\n}) {\n var _a21;\n const delay2 = (_a21 = _internal == null ? void 0 : _internal.delay) != null ? _a21 : delayFunction;\n let index = 0;\n return new ReadableStream({\n async pull(controller) {\n if (index < chunks.length) {\n await delay2(index === 0 ? initialDelayInMs : chunkDelayInMs);\n controller.enqueue(chunks[index++]);\n } else {\n controller.close();\n }\n }\n });\n}\n\n// src/generate-object/stream-object.ts\nvar originalGenerateId4 = createIdGenerator4({ prefix: \"aiobj\", size: 24 });\nfunction streamObject(options) {\n const {\n model,\n output = \"object\",\n system,\n prompt,\n messages,\n maxRetries,\n abortSignal,\n headers,\n experimental_repairText: repairText,\n experimental_telemetry: telemetry,\n experimental_download: download2,\n providerOptions,\n onError = ({ error }) => {\n console.error(error);\n },\n onFinish,\n _internal: {\n generateId: generateId2 = originalGenerateId4,\n currentDate = () => /* @__PURE__ */ new Date(),\n now: now2 = now\n } = {},\n ...settings\n } = options;\n const enumValues = \"enum\" in options && options.enum ? options.enum : void 0;\n const {\n schema: inputSchema,\n schemaDescription,\n schemaName\n } = \"schema\" in options ? options : {};\n validateObjectGenerationInput({\n output,\n schema: inputSchema,\n schemaName,\n schemaDescription,\n enumValues\n });\n const outputStrategy = getOutputStrategy({\n output,\n schema: inputSchema,\n enumValues\n });\n return new DefaultStreamObjectResult({\n model,\n telemetry,\n headers,\n settings,\n maxRetries,\n abortSignal,\n outputStrategy,\n system,\n prompt,\n messages,\n schemaName,\n schemaDescription,\n providerOptions,\n repairText,\n onError,\n onFinish,\n download: download2,\n generateId: generateId2,\n currentDate,\n now: now2\n });\n}\nvar DefaultStreamObjectResult = class {\n constructor({\n model: modelArg,\n headers,\n telemetry,\n settings,\n maxRetries: maxRetriesArg,\n abortSignal,\n outputStrategy,\n system,\n prompt,\n messages,\n schemaName,\n schemaDescription,\n providerOptions,\n repairText,\n onError,\n onFinish,\n download: download2,\n generateId: generateId2,\n currentDate,\n now: now2\n }) {\n this._object = new DelayedPromise2();\n this._usage = new DelayedPromise2();\n this._providerMetadata = new DelayedPromise2();\n this._warnings = new DelayedPromise2();\n this._request = new DelayedPromise2();\n this._response = new DelayedPromise2();\n this._finishReason = new DelayedPromise2();\n const model = resolveLanguageModel(modelArg);\n const { maxRetries, retry } = prepareRetries({\n maxRetries: maxRetriesArg,\n abortSignal\n });\n const callSettings = prepareCallSettings(settings);\n const baseTelemetryAttributes = getBaseTelemetryAttributes({\n model,\n telemetry,\n headers,\n settings: { ...callSettings, maxRetries }\n });\n const tracer = getTracer(telemetry);\n const self = this;\n const stitchableStream = createStitchableStream();\n const eventProcessor = new TransformStream({\n transform(chunk, controller) {\n controller.enqueue(chunk);\n if (chunk.type === \"error\") {\n onError({ error: wrapGatewayError(chunk.error) });\n }\n }\n });\n this.baseStream = stitchableStream.stream.pipeThrough(eventProcessor);\n recordSpan({\n name: \"ai.streamObject\",\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: \"ai.streamObject\",\n telemetry\n }),\n ...baseTelemetryAttributes,\n // specific settings that only make sense on the outer level:\n \"ai.prompt\": {\n input: () => JSON.stringify({ system, prompt, messages })\n },\n \"ai.schema\": {\n input: async () => JSON.stringify(await outputStrategy.jsonSchema())\n },\n \"ai.schema.name\": schemaName,\n \"ai.schema.description\": schemaDescription,\n \"ai.settings.output\": outputStrategy.type\n }\n }),\n tracer,\n endWhenDone: false,\n fn: async (rootSpan) => {\n const standardizedPrompt = await standardizePrompt({\n system,\n prompt,\n messages\n });\n const callOptions = {\n responseFormat: {\n type: \"json\",\n schema: await outputStrategy.jsonSchema(),\n name: schemaName,\n description: schemaDescription\n },\n ...prepareCallSettings(settings),\n prompt: await convertToLanguageModelPrompt({\n prompt: standardizedPrompt,\n supportedUrls: await model.supportedUrls,\n download: download2\n }),\n providerOptions,\n abortSignal,\n headers,\n includeRawChunks: false\n };\n const transformer = {\n transform: (chunk, controller) => {\n switch (chunk.type) {\n case \"text-delta\":\n controller.enqueue(chunk.delta);\n break;\n case \"response-metadata\":\n case \"finish\":\n case \"error\":\n case \"stream-start\":\n controller.enqueue(chunk);\n break;\n }\n }\n };\n const {\n result: { stream, response, request },\n doStreamSpan,\n startTimestampMs\n } = await retry(\n () => recordSpan({\n name: \"ai.streamObject.doStream\",\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: \"ai.streamObject.doStream\",\n telemetry\n }),\n ...baseTelemetryAttributes,\n \"ai.prompt.messages\": {\n input: () => stringifyForTelemetry(callOptions.prompt)\n },\n // standardized gen-ai llm span attributes:\n \"gen_ai.system\": model.provider,\n \"gen_ai.request.model\": model.modelId,\n \"gen_ai.request.frequency_penalty\": callSettings.frequencyPenalty,\n \"gen_ai.request.max_tokens\": callSettings.maxOutputTokens,\n \"gen_ai.request.presence_penalty\": callSettings.presencePenalty,\n \"gen_ai.request.temperature\": callSettings.temperature,\n \"gen_ai.request.top_k\": callSettings.topK,\n \"gen_ai.request.top_p\": callSettings.topP\n }\n }),\n tracer,\n endWhenDone: false,\n fn: async (doStreamSpan2) => ({\n startTimestampMs: now2(),\n doStreamSpan: doStreamSpan2,\n result: await model.doStream(callOptions)\n })\n })\n );\n self._request.resolve(request != null ? request : {});\n let warnings;\n let usage = createNullLanguageModelUsage();\n let finishReason;\n let providerMetadata;\n let object2;\n let error;\n let accumulatedText = \"\";\n let textDelta = \"\";\n let fullResponse = {\n id: generateId2(),\n timestamp: currentDate(),\n modelId: model.modelId\n };\n let latestObjectJson = void 0;\n let latestObject = void 0;\n let isFirstChunk = true;\n let isFirstDelta = true;\n const transformedStream = stream.pipeThrough(new TransformStream(transformer)).pipeThrough(\n new TransformStream({\n async transform(chunk, controller) {\n var _a21, _b, _c;\n if (typeof chunk === \"object\" && chunk.type === \"stream-start\") {\n warnings = chunk.warnings;\n return;\n }\n if (isFirstChunk) {\n const msToFirstChunk = now2() - startTimestampMs;\n isFirstChunk = false;\n doStreamSpan.addEvent(\"ai.stream.firstChunk\", {\n \"ai.stream.msToFirstChunk\": msToFirstChunk\n });\n doStreamSpan.setAttributes({\n \"ai.stream.msToFirstChunk\": msToFirstChunk\n });\n }\n if (typeof chunk === \"string\") {\n accumulatedText += chunk;\n textDelta += chunk;\n const { value: currentObjectJson, state: parseState } = await parsePartialJson(accumulatedText);\n if (currentObjectJson !== void 0 && !isDeepEqualData(latestObjectJson, currentObjectJson)) {\n const validationResult = await outputStrategy.validatePartialResult({\n value: currentObjectJson,\n textDelta,\n latestObject,\n isFirstDelta,\n isFinalDelta: parseState === \"successful-parse\"\n });\n if (validationResult.success && !isDeepEqualData(\n latestObject,\n validationResult.value.partial\n )) {\n latestObjectJson = currentObjectJson;\n latestObject = validationResult.value.partial;\n controller.enqueue({\n type: \"object\",\n object: latestObject\n });\n controller.enqueue({\n type: \"text-delta\",\n textDelta: validationResult.value.textDelta\n });\n textDelta = \"\";\n isFirstDelta = false;\n }\n }\n return;\n }\n switch (chunk.type) {\n case \"response-metadata\": {\n fullResponse = {\n id: (_a21 = chunk.id) != null ? _a21 : fullResponse.id,\n timestamp: (_b = chunk.timestamp) != null ? _b : fullResponse.timestamp,\n modelId: (_c = chunk.modelId) != null ? _c : fullResponse.modelId\n };\n break;\n }\n case \"finish\": {\n if (textDelta !== \"\") {\n controller.enqueue({ type: \"text-delta\", textDelta });\n }\n finishReason = chunk.finishReason.unified;\n usage = asLanguageModelUsage(chunk.usage);\n providerMetadata = chunk.providerMetadata;\n controller.enqueue({\n ...chunk,\n finishReason: chunk.finishReason.unified,\n usage,\n response: fullResponse\n });\n logWarnings({\n warnings: warnings != null ? warnings : [],\n provider: model.provider,\n model: model.modelId\n });\n self._usage.resolve(usage);\n self._providerMetadata.resolve(providerMetadata);\n self._warnings.resolve(warnings);\n self._response.resolve({\n ...fullResponse,\n headers: response == null ? void 0 : response.headers\n });\n self._finishReason.resolve(finishReason != null ? finishReason : \"other\");\n try {\n object2 = await parseAndValidateObjectResultWithRepair(\n accumulatedText,\n outputStrategy,\n repairText,\n {\n response: fullResponse,\n usage,\n finishReason\n }\n );\n self._object.resolve(object2);\n } catch (e) {\n error = e;\n self._object.reject(e);\n }\n break;\n }\n default: {\n controller.enqueue(chunk);\n break;\n }\n }\n },\n // invoke onFinish callback and resolve toolResults promise when the stream is about to close:\n async flush(controller) {\n try {\n const finalUsage = usage != null ? usage : {\n promptTokens: NaN,\n completionTokens: NaN,\n totalTokens: NaN\n };\n doStreamSpan.setAttributes(\n await selectTelemetryAttributes({\n telemetry,\n attributes: {\n \"ai.response.finishReason\": finishReason,\n \"ai.response.object\": {\n output: () => JSON.stringify(object2)\n },\n \"ai.response.id\": fullResponse.id,\n \"ai.response.model\": fullResponse.modelId,\n \"ai.response.timestamp\": fullResponse.timestamp.toISOString(),\n \"ai.response.providerMetadata\": JSON.stringify(providerMetadata),\n \"ai.usage.inputTokens\": finalUsage.inputTokens,\n \"ai.usage.outputTokens\": finalUsage.outputTokens,\n \"ai.usage.totalTokens\": finalUsage.totalTokens,\n \"ai.usage.reasoningTokens\": finalUsage.reasoningTokens,\n \"ai.usage.cachedInputTokens\": finalUsage.cachedInputTokens,\n // standardized gen-ai llm span attributes:\n \"gen_ai.response.finish_reasons\": [finishReason],\n \"gen_ai.response.id\": fullResponse.id,\n \"gen_ai.response.model\": fullResponse.modelId,\n \"gen_ai.usage.input_tokens\": finalUsage.inputTokens,\n \"gen_ai.usage.output_tokens\": finalUsage.outputTokens\n }\n })\n );\n doStreamSpan.end();\n rootSpan.setAttributes(\n await selectTelemetryAttributes({\n telemetry,\n attributes: {\n \"ai.usage.inputTokens\": finalUsage.inputTokens,\n \"ai.usage.outputTokens\": finalUsage.outputTokens,\n \"ai.usage.totalTokens\": finalUsage.totalTokens,\n \"ai.usage.reasoningTokens\": finalUsage.reasoningTokens,\n \"ai.usage.cachedInputTokens\": finalUsage.cachedInputTokens,\n \"ai.response.object\": {\n output: () => JSON.stringify(object2)\n },\n \"ai.response.providerMetadata\": JSON.stringify(providerMetadata)\n }\n })\n );\n await (onFinish == null ? void 0 : onFinish({\n usage: finalUsage,\n object: object2,\n error,\n response: {\n ...fullResponse,\n headers: response == null ? void 0 : response.headers\n },\n warnings,\n providerMetadata\n }));\n } catch (error2) {\n controller.enqueue({ type: \"error\", error: error2 });\n } finally {\n rootSpan.end();\n }\n }\n })\n );\n stitchableStream.addStream(transformedStream);\n }\n }).catch((error) => {\n stitchableStream.addStream(\n new ReadableStream({\n start(controller) {\n controller.enqueue({ type: \"error\", error });\n controller.close();\n }\n })\n );\n }).finally(() => {\n stitchableStream.close();\n });\n this.outputStrategy = outputStrategy;\n }\n get object() {\n return this._object.promise;\n }\n get usage() {\n return this._usage.promise;\n }\n get providerMetadata() {\n return this._providerMetadata.promise;\n }\n get warnings() {\n return this._warnings.promise;\n }\n get request() {\n return this._request.promise;\n }\n get response() {\n return this._response.promise;\n }\n get finishReason() {\n return this._finishReason.promise;\n }\n get partialObjectStream() {\n return createAsyncIterableStream(\n this.baseStream.pipeThrough(\n new TransformStream({\n transform(chunk, controller) {\n switch (chunk.type) {\n case \"object\":\n controller.enqueue(chunk.object);\n break;\n case \"text-delta\":\n case \"finish\":\n case \"error\":\n break;\n default: {\n const _exhaustiveCheck = chunk;\n throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);\n }\n }\n }\n })\n )\n );\n }\n get elementStream() {\n return this.outputStrategy.createElementStream(this.baseStream);\n }\n get textStream() {\n return createAsyncIterableStream(\n this.baseStream.pipeThrough(\n new TransformStream({\n transform(chunk, controller) {\n switch (chunk.type) {\n case \"text-delta\":\n controller.enqueue(chunk.textDelta);\n break;\n case \"object\":\n case \"finish\":\n case \"error\":\n break;\n default: {\n const _exhaustiveCheck = chunk;\n throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);\n }\n }\n }\n })\n )\n );\n }\n get fullStream() {\n return createAsyncIterableStream(this.baseStream);\n }\n pipeTextStreamToResponse(response, init) {\n pipeTextStreamToResponse({\n response,\n textStream: this.textStream,\n ...init\n });\n }\n toTextStreamResponse(init) {\n return createTextStreamResponse({\n textStream: this.textStream,\n ...init\n });\n }\n};\n\n// src/generate-speech/generate-speech.ts\nimport { withUserAgentSuffix as withUserAgentSuffix7 } from \"@ai-sdk/provider-utils\";\n\n// src/generate-speech/generated-audio-file.ts\nvar DefaultGeneratedAudioFile = class extends DefaultGeneratedFile {\n constructor({\n data,\n mediaType\n }) {\n super({ data, mediaType });\n let format = \"mp3\";\n if (mediaType) {\n const mediaTypeParts = mediaType.split(\"/\");\n if (mediaTypeParts.length === 2) {\n if (mediaType !== \"audio/mpeg\") {\n format = mediaTypeParts[1];\n }\n }\n }\n if (!format) {\n throw new Error(\n \"Audio format must be provided or determinable from media type\"\n );\n }\n this.format = format;\n }\n};\n\n// src/generate-speech/generate-speech.ts\nasync function generateSpeech({\n model,\n text: text2,\n voice,\n outputFormat,\n instructions,\n speed,\n language,\n providerOptions = {},\n maxRetries: maxRetriesArg,\n abortSignal,\n headers\n}) {\n var _a21;\n const resolvedModel = resolveSpeechModel(model);\n if (!resolvedModel) {\n throw new Error(\"Model could not be resolved\");\n }\n const headersWithUserAgent = withUserAgentSuffix7(\n headers != null ? headers : {},\n `ai/${VERSION}`\n );\n const { retry } = prepareRetries({\n maxRetries: maxRetriesArg,\n abortSignal\n });\n const result = await retry(\n () => resolvedModel.doGenerate({\n text: text2,\n voice,\n outputFormat,\n instructions,\n speed,\n language,\n abortSignal,\n headers: headersWithUserAgent,\n providerOptions\n })\n );\n if (!result.audio || result.audio.length === 0) {\n throw new NoSpeechGeneratedError({ responses: [result.response] });\n }\n logWarnings({\n warnings: result.warnings,\n provider: resolvedModel.provider,\n model: resolvedModel.modelId\n });\n return new DefaultSpeechResult({\n audio: new DefaultGeneratedAudioFile({\n data: result.audio,\n mediaType: (_a21 = detectMediaType({\n data: result.audio,\n signatures: audioMediaTypeSignatures\n })) != null ? _a21 : \"audio/mp3\"\n }),\n warnings: result.warnings,\n responses: [result.response],\n providerMetadata: result.providerMetadata\n });\n}\nvar DefaultSpeechResult = class {\n constructor(options) {\n var _a21;\n this.audio = options.audio;\n this.warnings = options.warnings;\n this.responses = options.responses;\n this.providerMetadata = (_a21 = options.providerMetadata) != null ? _a21 : {};\n }\n};\n\n// src/generate-text/prune-messages.ts\nfunction pruneMessages({\n messages,\n reasoning = \"none\",\n toolCalls = [],\n emptyMessages = \"remove\"\n}) {\n if (reasoning === \"all\" || reasoning === \"before-last-message\") {\n messages = messages.map((message, messageIndex) => {\n if (message.role !== \"assistant\" || typeof message.content === \"string\" || reasoning === \"before-last-message\" && messageIndex === messages.length - 1) {\n return message;\n }\n return {\n ...message,\n content: message.content.filter((part) => part.type !== \"reasoning\")\n };\n });\n }\n if (toolCalls === \"none\") {\n toolCalls = [];\n } else if (toolCalls === \"all\") {\n toolCalls = [{ type: \"all\" }];\n } else if (toolCalls === \"before-last-message\") {\n toolCalls = [{ type: \"before-last-message\" }];\n } else if (typeof toolCalls === \"string\") {\n toolCalls = [{ type: toolCalls }];\n }\n for (const toolCall of toolCalls) {\n const keepLastMessagesCount = toolCall.type === \"all\" ? void 0 : toolCall.type === \"before-last-message\" ? 1 : Number(\n toolCall.type.slice(\"before-last-\".length).slice(0, -\"-messages\".length)\n );\n const keptToolCallIds = /* @__PURE__ */ new Set();\n const keptApprovalIds = /* @__PURE__ */ new Set();\n if (keepLastMessagesCount != null) {\n for (const message of messages.slice(-keepLastMessagesCount)) {\n if ((message.role === \"assistant\" || message.role === \"tool\") && typeof message.content !== \"string\") {\n for (const part of message.content) {\n if (part.type === \"tool-call\" || part.type === \"tool-result\") {\n keptToolCallIds.add(part.toolCallId);\n } else if (part.type === \"tool-approval-request\" || part.type === \"tool-approval-response\") {\n keptApprovalIds.add(part.approvalId);\n }\n }\n }\n }\n }\n messages = messages.map((message, messageIndex) => {\n if (message.role !== \"assistant\" && message.role !== \"tool\" || typeof message.content === \"string\" || keepLastMessagesCount && messageIndex >= messages.length - keepLastMessagesCount) {\n return message;\n }\n const toolCallIdToToolName = {};\n const approvalIdToToolName = {};\n return {\n ...message,\n content: message.content.filter((part) => {\n if (part.type !== \"tool-call\" && part.type !== \"tool-result\" && part.type !== \"tool-approval-request\" && part.type !== \"tool-approval-response\") {\n return true;\n }\n if (part.type === \"tool-call\") {\n toolCallIdToToolName[part.toolCallId] = part.toolName;\n } else if (part.type === \"tool-approval-request\") {\n approvalIdToToolName[part.approvalId] = toolCallIdToToolName[part.toolCallId];\n }\n if ((part.type === \"tool-call\" || part.type === \"tool-result\") && keptToolCallIds.has(part.toolCallId) || (part.type === \"tool-approval-request\" || part.type === \"tool-approval-response\") && keptApprovalIds.has(part.approvalId)) {\n return true;\n }\n return toolCall.tools != null && !toolCall.tools.includes(\n part.type === \"tool-call\" || part.type === \"tool-result\" ? part.toolName : approvalIdToToolName[part.approvalId]\n );\n })\n };\n });\n }\n if (emptyMessages === \"remove\") {\n messages = messages.filter((message) => message.content.length > 0);\n }\n return messages;\n}\n\n// src/generate-text/smooth-stream.ts\nimport { delay as originalDelay } from \"@ai-sdk/provider-utils\";\nimport { InvalidArgumentError as InvalidArgumentError2 } from \"@ai-sdk/provider\";\nvar CHUNKING_REGEXPS = {\n word: /\\S+\\s+/m,\n line: /\\n+/m\n};\nfunction smoothStream({\n delayInMs = 10,\n chunking = \"word\",\n _internal: { delay: delay2 = originalDelay } = {}\n} = {}) {\n let detectChunk;\n if (chunking != null && typeof chunking === \"object\" && \"segment\" in chunking && typeof chunking.segment === \"function\") {\n const segmenter = chunking;\n detectChunk = (buffer) => {\n if (buffer.length === 0)\n return null;\n const iterator = segmenter.segment(buffer)[Symbol.iterator]();\n const first = iterator.next().value;\n return (first == null ? void 0 : first.segment) || null;\n };\n } else if (typeof chunking === \"function\") {\n detectChunk = (buffer) => {\n const match = chunking(buffer);\n if (match == null) {\n return null;\n }\n if (!match.length) {\n throw new Error(`Chunking function must return a non-empty string.`);\n }\n if (!buffer.startsWith(match)) {\n throw new Error(\n `Chunking function must return a match that is a prefix of the buffer. Received: \"${match}\" expected to start with \"${buffer}\"`\n );\n }\n return match;\n };\n } else {\n const chunkingRegex = typeof chunking === \"string\" ? CHUNKING_REGEXPS[chunking] : chunking instanceof RegExp ? chunking : void 0;\n if (chunkingRegex == null) {\n throw new InvalidArgumentError2({\n argument: \"chunking\",\n message: `Chunking must be \"word\", \"line\", a RegExp, an Intl.Segmenter, or a ChunkDetector function. Received: ${chunking}`\n });\n }\n detectChunk = (buffer) => {\n const match = chunkingRegex.exec(buffer);\n if (!match) {\n return null;\n }\n return buffer.slice(0, match.index) + (match == null ? void 0 : match[0]);\n };\n }\n return () => {\n let buffer = \"\";\n let id = \"\";\n let type = void 0;\n let providerMetadata = void 0;\n function flushBuffer(controller) {\n if (buffer.length > 0 && type !== void 0) {\n controller.enqueue({\n type,\n text: buffer,\n id,\n ...providerMetadata != null ? { providerMetadata } : {}\n });\n buffer = \"\";\n providerMetadata = void 0;\n }\n }\n return new TransformStream({\n async transform(chunk, controller) {\n if (chunk.type !== \"text-delta\" && chunk.type !== \"reasoning-delta\") {\n flushBuffer(controller);\n controller.enqueue(chunk);\n return;\n }\n if ((chunk.type !== type || chunk.id !== id) && buffer.length > 0) {\n flushBuffer(controller);\n }\n buffer += chunk.text;\n id = chunk.id;\n type = chunk.type;\n if (chunk.providerMetadata != null) {\n providerMetadata = chunk.providerMetadata;\n }\n let match;\n while ((match = detectChunk(buffer)) != null) {\n controller.enqueue({ type, text: match, id });\n buffer = buffer.slice(match.length);\n await delay2(delayInMs);\n }\n }\n });\n };\n}\n\n// src/generate-video/generate-video.ts\nimport {\n convertBase64ToUint8Array as convertBase64ToUint8Array5,\n withUserAgentSuffix as withUserAgentSuffix8\n} from \"@ai-sdk/provider-utils\";\nvar defaultDownload = createDownload();\nasync function experimental_generateVideo({\n model: modelArg,\n prompt: promptArg,\n n = 1,\n maxVideosPerCall,\n aspectRatio,\n resolution,\n duration,\n fps,\n seed,\n providerOptions,\n maxRetries: maxRetriesArg,\n abortSignal,\n headers,\n download: downloadFn = defaultDownload\n}) {\n var _a21;\n const model = resolveVideoModel(modelArg);\n const headersWithUserAgent = withUserAgentSuffix8(\n headers != null ? headers : {},\n `ai/${VERSION}`\n );\n const { retry } = prepareRetries({\n maxRetries: maxRetriesArg,\n abortSignal\n });\n const { prompt, image } = normalizePrompt2(promptArg);\n const maxVideosPerCallWithDefault = (_a21 = maxVideosPerCall != null ? maxVideosPerCall : await invokeModelMaxVideosPerCall(model)) != null ? _a21 : 1;\n const callCount = Math.ceil(n / maxVideosPerCallWithDefault);\n const callVideoCounts = Array.from({ length: callCount }, (_, index) => {\n const remaining = n - index * maxVideosPerCallWithDefault;\n return Math.min(remaining, maxVideosPerCallWithDefault);\n });\n const results = await Promise.all(\n callVideoCounts.map(\n async (callVideoCount) => retry(\n () => model.doGenerate({\n prompt,\n n: callVideoCount,\n aspectRatio,\n resolution,\n duration,\n fps,\n seed,\n image,\n providerOptions: providerOptions != null ? providerOptions : {},\n headers: headersWithUserAgent,\n abortSignal\n })\n )\n )\n );\n const videos = [];\n const warnings = [];\n const responses = [];\n const providerMetadata = {};\n for (const result of results) {\n for (const videoData of result.videos) {\n switch (videoData.type) {\n case \"url\": {\n const { data, mediaType: downloadedMediaType } = await downloadFn({\n url: new URL(videoData.url),\n abortSignal\n });\n const isUsableMediaType = (type) => !!type && type !== \"application/octet-stream\";\n const mediaType = isUsableMediaType(videoData.mediaType) && videoData.mediaType || isUsableMediaType(downloadedMediaType) && downloadedMediaType || detectMediaType({\n data,\n signatures: videoMediaTypeSignatures\n }) || \"video/mp4\";\n videos.push(\n new DefaultGeneratedFile({\n data,\n mediaType\n })\n );\n break;\n }\n case \"base64\": {\n videos.push(\n new DefaultGeneratedFile({\n data: videoData.data,\n mediaType: videoData.mediaType || \"video/mp4\"\n })\n );\n break;\n }\n case \"binary\": {\n const mediaType = videoData.mediaType || detectMediaType({\n data: videoData.data,\n signatures: videoMediaTypeSignatures\n }) || \"video/mp4\";\n videos.push(\n new DefaultGeneratedFile({\n data: videoData.data,\n mediaType\n })\n );\n break;\n }\n }\n }\n warnings.push(...result.warnings);\n responses.push({\n timestamp: result.response.timestamp,\n modelId: result.response.modelId,\n headers: result.response.headers,\n providerMetadata: result.providerMetadata\n });\n if (result.providerMetadata != null) {\n for (const [providerName, metadata] of Object.entries(\n result.providerMetadata\n )) {\n const existingMetadata = providerMetadata[providerName];\n if (existingMetadata != null && typeof existingMetadata === \"object\") {\n providerMetadata[providerName] = {\n ...existingMetadata,\n ...metadata\n };\n if (\"videos\" in existingMetadata && Array.isArray(existingMetadata.videos) && \"videos\" in metadata && Array.isArray(metadata.videos)) {\n providerMetadata[providerName].videos = [\n ...existingMetadata.videos,\n ...metadata.videos\n ];\n }\n } else {\n providerMetadata[providerName] = metadata;\n }\n }\n }\n }\n if (videos.length === 0) {\n throw new NoVideoGeneratedError({ responses });\n }\n if (warnings.length > 0) {\n logWarnings({\n warnings,\n provider: model.provider,\n model: model.modelId\n });\n }\n return {\n video: videos[0],\n videos,\n warnings,\n responses,\n providerMetadata\n };\n}\nfunction normalizePrompt2(promptArg) {\n var _a21, _b;\n if (typeof promptArg === \"string\") {\n return {\n prompt: promptArg,\n image: void 0\n };\n }\n let image;\n if (promptArg.image != null) {\n const dataContent = promptArg.image;\n if (typeof dataContent === \"string\") {\n if (dataContent.startsWith(\"http://\") || dataContent.startsWith(\"https://\")) {\n image = {\n type: \"url\",\n url: dataContent\n };\n } else if (dataContent.startsWith(\"data:\")) {\n const { mediaType, base64Content } = splitDataUrl(dataContent);\n image = {\n type: \"file\",\n mediaType: mediaType != null ? mediaType : \"image/png\",\n data: convertBase64ToUint8Array5(base64Content != null ? base64Content : \"\")\n };\n } else {\n const bytes = convertBase64ToUint8Array5(dataContent);\n const mediaType = (_a21 = detectMediaType({\n data: bytes,\n signatures: imageMediaTypeSignatures\n })) != null ? _a21 : \"image/png\";\n image = {\n type: \"file\",\n mediaType,\n data: bytes\n };\n }\n } else if (dataContent instanceof Uint8Array) {\n const mediaType = (_b = detectMediaType({\n data: dataContent,\n signatures: imageMediaTypeSignatures\n })) != null ? _b : \"image/png\";\n image = {\n type: \"file\",\n mediaType,\n data: dataContent\n };\n }\n }\n return {\n prompt: promptArg.text,\n image\n };\n}\nasync function invokeModelMaxVideosPerCall(model) {\n if (typeof model.maxVideosPerCall === \"function\") {\n return await model.maxVideosPerCall({ modelId: model.modelId });\n }\n return model.maxVideosPerCall;\n}\n\n// src/middleware/default-embedding-settings-middleware.ts\nfunction defaultEmbeddingSettingsMiddleware({\n settings\n}) {\n return {\n specificationVersion: \"v3\",\n transformParams: async ({ params }) => {\n return mergeObjects(settings, params);\n }\n };\n}\n\n// src/middleware/default-settings-middleware.ts\nfunction defaultSettingsMiddleware({\n settings\n}) {\n return {\n specificationVersion: \"v3\",\n transformParams: async ({ params }) => {\n return mergeObjects(settings, params);\n }\n };\n}\n\n// src/middleware/extract-json-middleware.ts\nfunction defaultTransform(text2) {\n return text2.replace(/^```(?:json)?\\s*\\n?/, \"\").replace(/\\n?```\\s*$/, \"\").trim();\n}\nfunction extractJsonMiddleware(options) {\n var _a21;\n const transform = (_a21 = options == null ? void 0 : options.transform) != null ? _a21 : defaultTransform;\n const hasCustomTransform = (options == null ? void 0 : options.transform) !== void 0;\n return {\n specificationVersion: \"v3\",\n wrapGenerate: async ({ doGenerate }) => {\n const { content, ...rest } = await doGenerate();\n const transformedContent = [];\n for (const part of content) {\n if (part.type !== \"text\") {\n transformedContent.push(part);\n continue;\n }\n transformedContent.push({\n ...part,\n text: transform(part.text)\n });\n }\n return { content: transformedContent, ...rest };\n },\n wrapStream: async ({ doStream }) => {\n const { stream, ...rest } = await doStream();\n const textBlocks = {};\n const SUFFIX_BUFFER_SIZE = 12;\n return {\n stream: stream.pipeThrough(\n new TransformStream({\n transform: (chunk, controller) => {\n if (chunk.type === \"text-start\") {\n textBlocks[chunk.id] = {\n startEvent: chunk,\n // Custom transforms need to buffer all content\n phase: hasCustomTransform ? \"buffering\" : \"prefix\",\n buffer: \"\",\n prefixStripped: false\n };\n return;\n }\n if (chunk.type === \"text-delta\") {\n const block = textBlocks[chunk.id];\n if (!block) {\n controller.enqueue(chunk);\n return;\n }\n block.buffer += chunk.delta;\n if (block.phase === \"buffering\") {\n return;\n }\n if (block.phase === \"prefix\") {\n if (block.buffer.length > 0 && !block.buffer.startsWith(\"`\")) {\n block.phase = \"streaming\";\n controller.enqueue(block.startEvent);\n } else if (block.buffer.startsWith(\"```\")) {\n if (block.buffer.includes(\"\\n\")) {\n const prefixMatch = block.buffer.match(/^```(?:json)?\\s*\\n/);\n if (prefixMatch) {\n block.buffer = block.buffer.slice(\n prefixMatch[0].length\n );\n block.prefixStripped = true;\n block.phase = \"streaming\";\n controller.enqueue(block.startEvent);\n } else {\n block.phase = \"streaming\";\n controller.enqueue(block.startEvent);\n }\n }\n } else if (block.buffer.length >= 3 && !block.buffer.startsWith(\"```\")) {\n block.phase = \"streaming\";\n controller.enqueue(block.startEvent);\n }\n }\n if (block.phase === \"streaming\" && block.buffer.length > SUFFIX_BUFFER_SIZE) {\n const toStream = block.buffer.slice(0, -SUFFIX_BUFFER_SIZE);\n block.buffer = block.buffer.slice(-SUFFIX_BUFFER_SIZE);\n controller.enqueue({\n type: \"text-delta\",\n id: chunk.id,\n delta: toStream\n });\n }\n return;\n }\n if (chunk.type === \"text-end\") {\n const block = textBlocks[chunk.id];\n if (block) {\n if (block.phase === \"prefix\" || block.phase === \"buffering\") {\n controller.enqueue(block.startEvent);\n }\n let remaining = block.buffer;\n if (block.phase === \"buffering\") {\n remaining = transform(remaining);\n } else if (block.prefixStripped) {\n remaining = remaining.replace(/\\n?```\\s*$/, \"\").trimEnd();\n } else {\n remaining = transform(remaining);\n }\n if (remaining.length > 0) {\n controller.enqueue({\n type: \"text-delta\",\n id: chunk.id,\n delta: remaining\n });\n }\n controller.enqueue(chunk);\n delete textBlocks[chunk.id];\n return;\n }\n }\n controller.enqueue(chunk);\n }\n })\n ),\n ...rest\n };\n }\n };\n}\n\n// src/util/get-potential-start-index.ts\nfunction getPotentialStartIndex(text2, searchedText) {\n if (searchedText.length === 0) {\n return null;\n }\n const directIndex = text2.indexOf(searchedText);\n if (directIndex !== -1) {\n return directIndex;\n }\n for (let i = text2.length - 1; i >= 0; i--) {\n const suffix = text2.substring(i);\n if (searchedText.startsWith(suffix)) {\n return i;\n }\n }\n return null;\n}\n\n// src/middleware/extract-reasoning-middleware.ts\nfunction extractReasoningMiddleware({\n tagName,\n separator = \"\\n\",\n startWithReasoning = false\n}) {\n const openingTag = `<${tagName}>`;\n const closingTag = `</${tagName}>`;\n return {\n specificationVersion: \"v3\",\n wrapGenerate: async ({ doGenerate }) => {\n const { content, ...rest } = await doGenerate();\n const transformedContent = [];\n for (const part of content) {\n if (part.type !== \"text\") {\n transformedContent.push(part);\n continue;\n }\n const text2 = startWithReasoning ? openingTag + part.text : part.text;\n const regexp = new RegExp(`${openingTag}(.*?)${closingTag}`, \"gs\");\n const matches = Array.from(text2.matchAll(regexp));\n if (!matches.length) {\n transformedContent.push(part);\n continue;\n }\n const reasoningText = matches.map((match) => match[1]).join(separator);\n let textWithoutReasoning = text2;\n for (let i = matches.length - 1; i >= 0; i--) {\n const match = matches[i];\n const beforeMatch = textWithoutReasoning.slice(0, match.index);\n const afterMatch = textWithoutReasoning.slice(\n match.index + match[0].length\n );\n textWithoutReasoning = beforeMatch + (beforeMatch.length > 0 && afterMatch.length > 0 ? separator : \"\") + afterMatch;\n }\n transformedContent.push({\n type: \"reasoning\",\n text: reasoningText\n });\n transformedContent.push({\n type: \"text\",\n text: textWithoutReasoning\n });\n }\n return { content: transformedContent, ...rest };\n },\n wrapStream: async ({ doStream }) => {\n const { stream, ...rest } = await doStream();\n const reasoningExtractions = {};\n let delayedTextStart;\n return {\n stream: stream.pipeThrough(\n new TransformStream({\n transform: (chunk, controller) => {\n if (chunk.type === \"text-start\") {\n delayedTextStart = chunk;\n return;\n }\n if (chunk.type === \"text-end\" && delayedTextStart) {\n controller.enqueue(delayedTextStart);\n delayedTextStart = void 0;\n }\n if (chunk.type !== \"text-delta\") {\n controller.enqueue(chunk);\n return;\n }\n if (reasoningExtractions[chunk.id] == null) {\n reasoningExtractions[chunk.id] = {\n isFirstReasoning: true,\n isFirstText: true,\n afterSwitch: false,\n isReasoning: startWithReasoning,\n buffer: \"\",\n idCounter: 0,\n textId: chunk.id\n };\n }\n const activeExtraction = reasoningExtractions[chunk.id];\n activeExtraction.buffer += chunk.delta;\n function publish(text2) {\n if (text2.length > 0) {\n const prefix = activeExtraction.afterSwitch && (activeExtraction.isReasoning ? !activeExtraction.isFirstReasoning : !activeExtraction.isFirstText) ? separator : \"\";\n if (activeExtraction.isReasoning && (activeExtraction.afterSwitch || activeExtraction.isFirstReasoning)) {\n controller.enqueue({\n type: \"reasoning-start\",\n id: `reasoning-${activeExtraction.idCounter}`\n });\n }\n if (activeExtraction.isReasoning) {\n controller.enqueue({\n type: \"reasoning-delta\",\n delta: prefix + text2,\n id: `reasoning-${activeExtraction.idCounter}`\n });\n } else {\n if (delayedTextStart) {\n controller.enqueue(delayedTextStart);\n delayedTextStart = void 0;\n }\n controller.enqueue({\n type: \"text-delta\",\n delta: prefix + text2,\n id: activeExtraction.textId\n });\n }\n activeExtraction.afterSwitch = false;\n if (activeExtraction.isReasoning) {\n activeExtraction.isFirstReasoning = false;\n } else {\n activeExtraction.isFirstText = false;\n }\n }\n }\n do {\n const nextTag = activeExtraction.isReasoning ? closingTag : openingTag;\n const startIndex = getPotentialStartIndex(\n activeExtraction.buffer,\n nextTag\n );\n if (startIndex == null) {\n publish(activeExtraction.buffer);\n activeExtraction.buffer = \"\";\n break;\n }\n publish(activeExtraction.buffer.slice(0, startIndex));\n const foundFullMatch = startIndex + nextTag.length <= activeExtraction.buffer.length;\n if (foundFullMatch) {\n activeExtraction.buffer = activeExtraction.buffer.slice(\n startIndex + nextTag.length\n );\n if (activeExtraction.isReasoning) {\n if (activeExtraction.isFirstReasoning) {\n controller.enqueue({\n type: \"reasoning-start\",\n id: `reasoning-${activeExtraction.idCounter}`\n });\n }\n controller.enqueue({\n type: \"reasoning-end\",\n id: `reasoning-${activeExtraction.idCounter++}`\n });\n }\n activeExtraction.isReasoning = !activeExtraction.isReasoning;\n activeExtraction.afterSwitch = true;\n } else {\n activeExtraction.buffer = activeExtraction.buffer.slice(startIndex);\n break;\n }\n } while (true);\n }\n })\n ),\n ...rest\n };\n }\n };\n}\n\n// src/middleware/simulate-streaming-middleware.ts\nfunction simulateStreamingMiddleware() {\n return {\n specificationVersion: \"v3\",\n wrapStream: async ({ doGenerate }) => {\n const result = await doGenerate();\n let id = 0;\n const simulatedStream = new ReadableStream({\n start(controller) {\n controller.enqueue({\n type: \"stream-start\",\n warnings: result.warnings\n });\n controller.enqueue({ type: \"response-metadata\", ...result.response });\n for (const part of result.content) {\n switch (part.type) {\n case \"text\": {\n if (part.text.length > 0) {\n controller.enqueue({ type: \"text-start\", id: String(id) });\n controller.enqueue({\n type: \"text-delta\",\n id: String(id),\n delta: part.text\n });\n controller.enqueue({ type: \"text-end\", id: String(id) });\n id++;\n }\n break;\n }\n case \"reasoning\": {\n controller.enqueue({\n type: \"reasoning-start\",\n id: String(id),\n providerMetadata: part.providerMetadata\n });\n controller.enqueue({\n type: \"reasoning-delta\",\n id: String(id),\n delta: part.text\n });\n controller.enqueue({ type: \"reasoning-end\", id: String(id) });\n id++;\n break;\n }\n default: {\n controller.enqueue(part);\n break;\n }\n }\n }\n controller.enqueue({\n type: \"finish\",\n finishReason: result.finishReason,\n usage: result.usage,\n providerMetadata: result.providerMetadata\n });\n controller.close();\n }\n });\n return {\n stream: simulatedStream,\n request: result.request,\n response: result.response\n };\n }\n };\n}\n\n// src/middleware/add-tool-input-examples-middleware.ts\nfunction defaultFormatExample(example) {\n return JSON.stringify(example.input);\n}\nfunction addToolInputExamplesMiddleware({\n prefix = \"Input Examples:\",\n format = defaultFormatExample,\n remove = true\n} = {}) {\n return {\n specificationVersion: \"v3\",\n transformParams: async ({ params }) => {\n var _a21;\n if (!((_a21 = params.tools) == null ? void 0 : _a21.length)) {\n return params;\n }\n const transformedTools = params.tools.map((tool2) => {\n var _a22;\n if (tool2.type !== \"function\" || !((_a22 = tool2.inputExamples) == null ? void 0 : _a22.length)) {\n return tool2;\n }\n const formattedExamples = tool2.inputExamples.map((example, index) => format(example, index)).join(\"\\n\");\n const examplesSection = `${prefix}\n${formattedExamples}`;\n const toolDescription = tool2.description ? `${tool2.description}\n\n${examplesSection}` : examplesSection;\n return {\n ...tool2,\n description: toolDescription,\n inputExamples: remove ? void 0 : tool2.inputExamples\n };\n });\n return {\n ...params,\n tools: transformedTools\n };\n }\n };\n}\n\n// src/middleware/wrap-language-model.ts\nvar wrapLanguageModel = ({\n model,\n middleware: middlewareArg,\n modelId,\n providerId\n}) => {\n return [...asArray(middlewareArg)].reverse().reduce((wrappedModel, middleware) => {\n return doWrap({ model: wrappedModel, middleware, modelId, providerId });\n }, model);\n};\nvar doWrap = ({\n model,\n middleware: {\n transformParams,\n wrapGenerate,\n wrapStream,\n overrideProvider,\n overrideModelId,\n overrideSupportedUrls\n },\n modelId,\n providerId\n}) => {\n var _a21, _b, _c;\n async function doTransform({\n params,\n type\n }) {\n return transformParams ? await transformParams({ params, type, model }) : params;\n }\n return {\n specificationVersion: \"v3\",\n provider: (_a21 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a21 : model.provider,\n modelId: (_b = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b : model.modelId,\n supportedUrls: (_c = overrideSupportedUrls == null ? void 0 : overrideSupportedUrls({ model })) != null ? _c : model.supportedUrls,\n async doGenerate(params) {\n const transformedParams = await doTransform({ params, type: \"generate\" });\n const doGenerate = async () => model.doGenerate(transformedParams);\n const doStream = async () => model.doStream(transformedParams);\n return wrapGenerate ? wrapGenerate({\n doGenerate,\n doStream,\n params: transformedParams,\n model\n }) : doGenerate();\n },\n async doStream(params) {\n const transformedParams = await doTransform({ params, type: \"stream\" });\n const doGenerate = async () => model.doGenerate(transformedParams);\n const doStream = async () => model.doStream(transformedParams);\n return wrapStream ? wrapStream({ doGenerate, doStream, params: transformedParams, model }) : doStream();\n }\n };\n};\n\n// src/middleware/wrap-embedding-model.ts\nvar wrapEmbeddingModel = ({\n model,\n middleware: middlewareArg,\n modelId,\n providerId\n}) => {\n return [...asArray(middlewareArg)].reverse().reduce((wrappedModel, middleware) => {\n return doWrap2({ model: wrappedModel, middleware, modelId, providerId });\n }, model);\n};\nvar doWrap2 = ({\n model,\n middleware: {\n transformParams,\n wrapEmbed,\n overrideProvider,\n overrideModelId,\n overrideMaxEmbeddingsPerCall,\n overrideSupportsParallelCalls\n },\n modelId,\n providerId\n}) => {\n var _a21, _b, _c, _d;\n async function doTransform({\n params\n }) {\n return transformParams ? await transformParams({ params, model }) : params;\n }\n return {\n specificationVersion: \"v3\",\n provider: (_a21 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a21 : model.provider,\n modelId: (_b = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b : model.modelId,\n maxEmbeddingsPerCall: (_c = overrideMaxEmbeddingsPerCall == null ? void 0 : overrideMaxEmbeddingsPerCall({ model })) != null ? _c : model.maxEmbeddingsPerCall,\n supportsParallelCalls: (_d = overrideSupportsParallelCalls == null ? void 0 : overrideSupportsParallelCalls({ model })) != null ? _d : model.supportsParallelCalls,\n async doEmbed(params) {\n const transformedParams = await doTransform({ params });\n const doEmbed = async () => model.doEmbed(transformedParams);\n return wrapEmbed ? wrapEmbed({\n doEmbed,\n params: transformedParams,\n model\n }) : doEmbed();\n }\n };\n};\n\n// src/middleware/wrap-image-model.ts\nvar wrapImageModel = ({\n model,\n middleware: middlewareArg,\n modelId,\n providerId\n}) => {\n return [...asArray(middlewareArg)].reverse().reduce((wrappedModel, middleware) => {\n return doWrap3({ model: wrappedModel, middleware, modelId, providerId });\n }, model);\n};\nvar doWrap3 = ({\n model,\n middleware: {\n transformParams,\n wrapGenerate,\n overrideProvider,\n overrideModelId,\n overrideMaxImagesPerCall\n },\n modelId,\n providerId\n}) => {\n var _a21, _b, _c;\n async function doTransform({ params }) {\n return transformParams ? await transformParams({ params, model }) : params;\n }\n const maxImagesPerCallRaw = (_a21 = overrideMaxImagesPerCall == null ? void 0 : overrideMaxImagesPerCall({ model })) != null ? _a21 : model.maxImagesPerCall;\n const maxImagesPerCall = maxImagesPerCallRaw instanceof Function ? maxImagesPerCallRaw.bind(model) : maxImagesPerCallRaw;\n return {\n specificationVersion: \"v3\",\n provider: (_b = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _b : model.provider,\n modelId: (_c = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _c : model.modelId,\n maxImagesPerCall,\n async doGenerate(params) {\n const transformedParams = await doTransform({ params });\n const doGenerate = async () => model.doGenerate(transformedParams);\n return wrapGenerate ? wrapGenerate({\n doGenerate,\n params: transformedParams,\n model\n }) : doGenerate();\n }\n };\n};\n\n// src/model/as-provider-v3.ts\nfunction asProviderV3(provider) {\n if (\"specificationVersion\" in provider && provider.specificationVersion === \"v3\") {\n return provider;\n }\n const v2Provider = provider;\n return {\n specificationVersion: \"v3\",\n languageModel: (modelId) => asLanguageModelV3(v2Provider.languageModel(modelId)),\n embeddingModel: (modelId) => asEmbeddingModelV3(v2Provider.textEmbeddingModel(modelId)),\n imageModel: (modelId) => asImageModelV3(v2Provider.imageModel(modelId)),\n transcriptionModel: v2Provider.transcriptionModel ? (modelId) => asTranscriptionModelV3(v2Provider.transcriptionModel(modelId)) : void 0,\n speechModel: v2Provider.speechModel ? (modelId) => asSpeechModelV3(v2Provider.speechModel(modelId)) : void 0,\n rerankingModel: void 0\n // v2 providers don't have reranking models\n };\n}\n\n// src/middleware/wrap-provider.ts\nfunction wrapProvider({\n provider,\n languageModelMiddleware,\n imageModelMiddleware\n}) {\n const providerV3 = asProviderV3(provider);\n return {\n specificationVersion: \"v3\",\n languageModel: (modelId) => wrapLanguageModel({\n model: providerV3.languageModel(modelId),\n middleware: languageModelMiddleware\n }),\n embeddingModel: providerV3.embeddingModel,\n imageModel: (modelId) => {\n let model = providerV3.imageModel(modelId);\n if (imageModelMiddleware != null) {\n model = wrapImageModel({ model, middleware: imageModelMiddleware });\n }\n return model;\n },\n transcriptionModel: providerV3.transcriptionModel,\n speechModel: providerV3.speechModel,\n rerankingModel: providerV3.rerankingModel\n };\n}\n\n// src/registry/custom-provider.ts\nimport {\n NoSuchModelError as NoSuchModelError2\n} from \"@ai-sdk/provider\";\nfunction customProvider({\n languageModels,\n embeddingModels,\n imageModels,\n transcriptionModels,\n speechModels,\n rerankingModels,\n videoModels,\n fallbackProvider: fallbackProviderArg\n}) {\n const fallbackProvider = fallbackProviderArg ? asProviderV3(fallbackProviderArg) : void 0;\n return {\n specificationVersion: \"v3\",\n languageModel(modelId) {\n if (languageModels != null && modelId in languageModels) {\n return languageModels[modelId];\n }\n if (fallbackProvider) {\n return fallbackProvider.languageModel(modelId);\n }\n throw new NoSuchModelError2({ modelId, modelType: \"languageModel\" });\n },\n embeddingModel(modelId) {\n if (embeddingModels != null && modelId in embeddingModels) {\n return embeddingModels[modelId];\n }\n if (fallbackProvider) {\n return fallbackProvider.embeddingModel(modelId);\n }\n throw new NoSuchModelError2({ modelId, modelType: \"embeddingModel\" });\n },\n imageModel(modelId) {\n if (imageModels != null && modelId in imageModels) {\n return imageModels[modelId];\n }\n if (fallbackProvider == null ? void 0 : fallbackProvider.imageModel) {\n return fallbackProvider.imageModel(modelId);\n }\n throw new NoSuchModelError2({ modelId, modelType: \"imageModel\" });\n },\n transcriptionModel(modelId) {\n if (transcriptionModels != null && modelId in transcriptionModels) {\n return transcriptionModels[modelId];\n }\n if (fallbackProvider == null ? void 0 : fallbackProvider.transcriptionModel) {\n return fallbackProvider.transcriptionModel(modelId);\n }\n throw new NoSuchModelError2({ modelId, modelType: \"transcriptionModel\" });\n },\n speechModel(modelId) {\n if (speechModels != null && modelId in speechModels) {\n return speechModels[modelId];\n }\n if (fallbackProvider == null ? void 0 : fallbackProvider.speechModel) {\n return fallbackProvider.speechModel(modelId);\n }\n throw new NoSuchModelError2({ modelId, modelType: \"speechModel\" });\n },\n rerankingModel(modelId) {\n if (rerankingModels != null && modelId in rerankingModels) {\n return rerankingModels[modelId];\n }\n if (fallbackProvider == null ? void 0 : fallbackProvider.rerankingModel) {\n return fallbackProvider.rerankingModel(modelId);\n }\n throw new NoSuchModelError2({ modelId, modelType: \"rerankingModel\" });\n },\n videoModel(modelId) {\n if (videoModels != null && modelId in videoModels) {\n return videoModels[modelId];\n }\n const videoModel = fallbackProvider == null ? void 0 : fallbackProvider.videoModel;\n if (videoModel) {\n return videoModel(modelId);\n }\n throw new NoSuchModelError2({ modelId, modelType: \"videoModel\" });\n }\n };\n}\nvar experimental_customProvider = customProvider;\n\n// src/registry/no-such-provider-error.ts\nimport { AISDKError as AISDKError24, NoSuchModelError as NoSuchModelError3 } from \"@ai-sdk/provider\";\nvar name20 = \"AI_NoSuchProviderError\";\nvar marker20 = `vercel.ai.error.${name20}`;\nvar symbol20 = Symbol.for(marker20);\nvar _a20;\nvar NoSuchProviderError = class extends NoSuchModelError3 {\n constructor({\n modelId,\n modelType,\n providerId,\n availableProviders,\n message = `No such provider: ${providerId} (available providers: ${availableProviders.join()})`\n }) {\n super({ errorName: name20, modelId, modelType, message });\n this[_a20] = true;\n this.providerId = providerId;\n this.availableProviders = availableProviders;\n }\n static isInstance(error) {\n return AISDKError24.hasMarker(error, marker20);\n }\n};\n_a20 = symbol20;\n\n// src/registry/provider-registry.ts\nimport {\n NoSuchModelError as NoSuchModelError4\n} from \"@ai-sdk/provider\";\nfunction createProviderRegistry(providers, {\n separator = \":\",\n languageModelMiddleware,\n imageModelMiddleware\n} = {}) {\n const registry = new DefaultProviderRegistry({\n separator,\n languageModelMiddleware,\n imageModelMiddleware\n });\n for (const [id, provider] of Object.entries(providers)) {\n registry.registerProvider({ id, provider });\n }\n return registry;\n}\nvar experimental_createProviderRegistry = createProviderRegistry;\nvar DefaultProviderRegistry = class {\n constructor({\n separator,\n languageModelMiddleware,\n imageModelMiddleware\n }) {\n this.providers = {};\n this.separator = separator;\n this.languageModelMiddleware = languageModelMiddleware;\n this.imageModelMiddleware = imageModelMiddleware;\n }\n registerProvider({\n id,\n provider\n }) {\n this.providers[id] = provider;\n }\n getProvider(id, modelType) {\n const provider = this.providers[id];\n if (provider == null) {\n throw new NoSuchProviderError({\n modelId: id,\n modelType,\n providerId: id,\n availableProviders: Object.keys(this.providers)\n });\n }\n return provider;\n }\n splitId(id, modelType) {\n const index = id.indexOf(this.separator);\n if (index === -1) {\n throw new NoSuchModelError4({\n modelId: id,\n modelType,\n message: `Invalid ${modelType} id for registry: ${id} (must be in the format \"providerId${this.separator}modelId\")`\n });\n }\n return [id.slice(0, index), id.slice(index + this.separator.length)];\n }\n languageModel(id) {\n var _a21, _b;\n const [providerId, modelId] = this.splitId(id, \"languageModel\");\n let model = (_b = (_a21 = this.getProvider(providerId, \"languageModel\")).languageModel) == null ? void 0 : _b.call(\n _a21,\n modelId\n );\n if (model == null) {\n throw new NoSuchModelError4({ modelId: id, modelType: \"languageModel\" });\n }\n if (this.languageModelMiddleware != null) {\n model = wrapLanguageModel({\n model,\n middleware: this.languageModelMiddleware\n });\n }\n return model;\n }\n embeddingModel(id) {\n var _a21;\n const [providerId, modelId] = this.splitId(id, \"embeddingModel\");\n const provider = this.getProvider(providerId, \"embeddingModel\");\n const model = (_a21 = provider.embeddingModel) == null ? void 0 : _a21.call(provider, modelId);\n if (model == null) {\n throw new NoSuchModelError4({\n modelId: id,\n modelType: \"embeddingModel\"\n });\n }\n return model;\n }\n imageModel(id) {\n var _a21;\n const [providerId, modelId] = this.splitId(id, \"imageModel\");\n const provider = this.getProvider(providerId, \"imageModel\");\n let model = (_a21 = provider.imageModel) == null ? void 0 : _a21.call(provider, modelId);\n if (model == null) {\n throw new NoSuchModelError4({ modelId: id, modelType: \"imageModel\" });\n }\n if (this.imageModelMiddleware != null) {\n model = wrapImageModel({\n model,\n middleware: this.imageModelMiddleware\n });\n }\n return model;\n }\n transcriptionModel(id) {\n var _a21;\n const [providerId, modelId] = this.splitId(id, \"transcriptionModel\");\n const provider = this.getProvider(providerId, \"transcriptionModel\");\n const model = (_a21 = provider.transcriptionModel) == null ? void 0 : _a21.call(provider, modelId);\n if (model == null) {\n throw new NoSuchModelError4({\n modelId: id,\n modelType: \"transcriptionModel\"\n });\n }\n return model;\n }\n speechModel(id) {\n var _a21;\n const [providerId, modelId] = this.splitId(id, \"speechModel\");\n const provider = this.getProvider(providerId, \"speechModel\");\n const model = (_a21 = provider.speechModel) == null ? void 0 : _a21.call(provider, modelId);\n if (model == null) {\n throw new NoSuchModelError4({ modelId: id, modelType: \"speechModel\" });\n }\n return model;\n }\n rerankingModel(id) {\n var _a21;\n const [providerId, modelId] = this.splitId(id, \"rerankingModel\");\n const provider = this.getProvider(providerId, \"rerankingModel\");\n const model = (_a21 = provider.rerankingModel) == null ? void 0 : _a21.call(provider, modelId);\n if (model == null) {\n throw new NoSuchModelError4({ modelId: id, modelType: \"rerankingModel\" });\n }\n return model;\n }\n};\n\n// src/rerank/rerank.ts\nasync function rerank({\n model,\n documents,\n query,\n topN,\n maxRetries: maxRetriesArg,\n abortSignal,\n headers,\n providerOptions,\n experimental_telemetry: telemetry\n}) {\n if (documents.length === 0) {\n return new DefaultRerankResult({\n originalDocuments: [],\n ranking: [],\n providerMetadata: void 0,\n response: {\n timestamp: /* @__PURE__ */ new Date(),\n modelId: model.modelId\n }\n });\n }\n const { maxRetries, retry } = prepareRetries({\n maxRetries: maxRetriesArg,\n abortSignal\n });\n const documentsToSend = typeof documents[0] === \"string\" ? { type: \"text\", values: documents } : { type: \"object\", values: documents };\n const baseTelemetryAttributes = getBaseTelemetryAttributes({\n model,\n telemetry,\n headers,\n settings: { maxRetries }\n });\n const tracer = getTracer(telemetry);\n return recordSpan({\n name: \"ai.rerank\",\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({ operationId: \"ai.rerank\", telemetry }),\n ...baseTelemetryAttributes,\n \"ai.documents\": {\n input: () => documents.map((document) => JSON.stringify(document))\n }\n }\n }),\n tracer,\n fn: async () => {\n var _a21, _b;\n const { ranking, response, providerMetadata, warnings } = await retry(\n () => recordSpan({\n name: \"ai.rerank.doRerank\",\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: \"ai.rerank.doRerank\",\n telemetry\n }),\n ...baseTelemetryAttributes,\n // specific settings that only make sense on the outer level:\n \"ai.documents\": {\n input: () => documents.map((document) => JSON.stringify(document))\n }\n }\n }),\n tracer,\n fn: async (doRerankSpan) => {\n const modelResponse = await model.doRerank({\n documents: documentsToSend,\n query,\n topN,\n providerOptions,\n abortSignal,\n headers\n });\n const ranking2 = modelResponse.ranking;\n doRerankSpan.setAttributes(\n await selectTelemetryAttributes({\n telemetry,\n attributes: {\n \"ai.ranking.type\": documentsToSend.type,\n \"ai.ranking\": {\n output: () => ranking2.map((ranking3) => JSON.stringify(ranking3))\n }\n }\n })\n );\n return {\n ranking: ranking2,\n providerMetadata: modelResponse.providerMetadata,\n response: modelResponse.response,\n warnings: modelResponse.warnings\n };\n }\n })\n );\n logWarnings({\n warnings: warnings != null ? warnings : [],\n provider: model.provider,\n model: model.modelId\n });\n return new DefaultRerankResult({\n originalDocuments: documents,\n ranking: ranking.map((ranking2) => ({\n originalIndex: ranking2.index,\n score: ranking2.relevanceScore,\n document: documents[ranking2.index]\n })),\n providerMetadata,\n response: {\n id: response == null ? void 0 : response.id,\n timestamp: (_a21 = response == null ? void 0 : response.timestamp) != null ? _a21 : /* @__PURE__ */ new Date(),\n modelId: (_b = response == null ? void 0 : response.modelId) != null ? _b : model.modelId,\n headers: response == null ? void 0 : response.headers,\n body: response == null ? void 0 : response.body\n }\n });\n }\n });\n}\nvar DefaultRerankResult = class {\n constructor(options) {\n this.originalDocuments = options.originalDocuments;\n this.ranking = options.ranking;\n this.response = options.response;\n this.providerMetadata = options.providerMetadata;\n }\n get rerankedDocuments() {\n return this.ranking.map((ranking) => ranking.document);\n }\n};\n\n// src/transcribe/transcribe.ts\nimport { withUserAgentSuffix as withUserAgentSuffix9 } from \"@ai-sdk/provider-utils\";\nvar defaultDownload2 = createDownload();\nasync function transcribe({\n model,\n audio,\n providerOptions = {},\n maxRetries: maxRetriesArg,\n abortSignal,\n headers,\n download: downloadFn = defaultDownload2\n}) {\n const resolvedModel = resolveTranscriptionModel(model);\n if (!resolvedModel) {\n throw new Error(\"Model could not be resolved\");\n }\n const { retry } = prepareRetries({\n maxRetries: maxRetriesArg,\n abortSignal\n });\n const headersWithUserAgent = withUserAgentSuffix9(\n headers != null ? headers : {},\n `ai/${VERSION}`\n );\n const audioData = audio instanceof URL ? (await downloadFn({ url: audio, abortSignal })).data : convertDataContentToUint8Array(audio);\n const result = await retry(\n () => {\n var _a21;\n return resolvedModel.doGenerate({\n audio: audioData,\n abortSignal,\n headers: headersWithUserAgent,\n providerOptions,\n mediaType: (_a21 = detectMediaType({\n data: audioData,\n signatures: audioMediaTypeSignatures\n })) != null ? _a21 : \"audio/wav\"\n });\n }\n );\n logWarnings({\n warnings: result.warnings,\n provider: resolvedModel.provider,\n model: resolvedModel.modelId\n });\n if (!result.text) {\n throw new NoTranscriptGeneratedError({ responses: [result.response] });\n }\n return new DefaultTranscriptionResult({\n text: result.text,\n segments: result.segments,\n language: result.language,\n durationInSeconds: result.durationInSeconds,\n warnings: result.warnings,\n responses: [result.response],\n providerMetadata: result.providerMetadata\n });\n}\nvar DefaultTranscriptionResult = class {\n constructor(options) {\n var _a21;\n this.text = options.text;\n this.segments = options.segments;\n this.language = options.language;\n this.durationInSeconds = options.durationInSeconds;\n this.warnings = options.warnings;\n this.responses = options.responses;\n this.providerMetadata = (_a21 = options.providerMetadata) != null ? _a21 : {};\n }\n};\n\n// src/ui/call-completion-api.ts\nimport {\n parseJsonEventStream,\n withUserAgentSuffix as withUserAgentSuffix10,\n getRuntimeEnvironmentUserAgent as getRuntimeEnvironmentUserAgent2\n} from \"@ai-sdk/provider-utils\";\n\n// src/ui/process-text-stream.ts\nasync function processTextStream({\n stream,\n onTextPart\n}) {\n const reader = stream.pipeThrough(new TextDecoderStream()).getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n await onTextPart(value);\n }\n}\n\n// src/ui/call-completion-api.ts\nvar getOriginalFetch = () => fetch;\nasync function callCompletionApi({\n api,\n prompt,\n credentials,\n headers,\n body,\n streamProtocol = \"data\",\n setCompletion,\n setLoading,\n setError,\n setAbortController,\n onFinish,\n onError,\n fetch: fetch2 = getOriginalFetch()\n}) {\n var _a21;\n try {\n setLoading(true);\n setError(void 0);\n const abortController = new AbortController();\n setAbortController(abortController);\n setCompletion(\"\");\n const response = await fetch2(api, {\n method: \"POST\",\n body: JSON.stringify({\n prompt,\n ...body\n }),\n credentials,\n headers: withUserAgentSuffix10(\n {\n \"Content-Type\": \"application/json\",\n ...headers\n },\n `ai-sdk/${VERSION}`,\n getRuntimeEnvironmentUserAgent2()\n ),\n signal: abortController.signal\n }).catch((err) => {\n throw err;\n });\n if (!response.ok) {\n throw new Error(\n (_a21 = await response.text()) != null ? _a21 : \"Failed to fetch the chat response.\"\n );\n }\n if (!response.body) {\n throw new Error(\"The response body is empty.\");\n }\n let result = \"\";\n switch (streamProtocol) {\n case \"text\": {\n await processTextStream({\n stream: response.body,\n onTextPart: (chunk) => {\n result += chunk;\n setCompletion(result);\n }\n });\n break;\n }\n case \"data\": {\n await consumeStream({\n stream: parseJsonEventStream({\n stream: response.body,\n schema: uiMessageChunkSchema\n }).pipeThrough(\n new TransformStream({\n async transform(part) {\n if (!part.success) {\n throw part.error;\n }\n const streamPart = part.value;\n if (streamPart.type === \"text-delta\") {\n result += streamPart.delta;\n setCompletion(result);\n } else if (streamPart.type === \"error\") {\n throw new Error(streamPart.errorText);\n }\n }\n })\n ),\n onError: (error) => {\n throw error;\n }\n });\n break;\n }\n default: {\n const exhaustiveCheck = streamProtocol;\n throw new Error(`Unknown stream protocol: ${exhaustiveCheck}`);\n }\n }\n if (onFinish) {\n onFinish(prompt, result);\n }\n setAbortController(null);\n return result;\n } catch (err) {\n if (err.name === \"AbortError\") {\n setAbortController(null);\n return null;\n }\n if (err instanceof Error) {\n if (onError) {\n onError(err);\n }\n }\n setError(err);\n } finally {\n setLoading(false);\n }\n}\n\n// src/ui/chat.ts\nimport {\n generateId as generateIdFunc2\n} from \"@ai-sdk/provider-utils\";\n\n// src/ui/convert-file-list-to-file-ui-parts.ts\nasync function convertFileListToFileUIParts(files) {\n if (files == null) {\n return [];\n }\n if (!globalThis.FileList || !(files instanceof globalThis.FileList)) {\n throw new Error(\"FileList is not supported in the current environment\");\n }\n return Promise.all(\n Array.from(files).map(async (file) => {\n const { name: name21, type } = file;\n const dataUrl = await new Promise((resolve3, reject) => {\n const reader = new FileReader();\n reader.onload = (readerEvent) => {\n var _a21;\n resolve3((_a21 = readerEvent.target) == null ? void 0 : _a21.result);\n };\n reader.onerror = (error) => reject(error);\n reader.readAsDataURL(file);\n });\n return {\n type: \"file\",\n mediaType: type,\n filename: name21,\n url: dataUrl\n };\n })\n );\n}\n\n// src/ui/default-chat-transport.ts\nimport { parseJsonEventStream as parseJsonEventStream2 } from \"@ai-sdk/provider-utils\";\n\n// src/ui/http-chat-transport.ts\nimport {\n normalizeHeaders,\n resolve as resolve2,\n withUserAgentSuffix as withUserAgentSuffix11,\n getRuntimeEnvironmentUserAgent as getRuntimeEnvironmentUserAgent3\n} from \"@ai-sdk/provider-utils\";\nvar HttpChatTransport = class {\n constructor({\n api = \"/api/chat\",\n credentials,\n headers,\n body,\n fetch: fetch2,\n prepareSendMessagesRequest,\n prepareReconnectToStreamRequest\n }) {\n this.api = api;\n this.credentials = credentials;\n this.headers = headers;\n this.body = body;\n this.fetch = fetch2;\n this.prepareSendMessagesRequest = prepareSendMessagesRequest;\n this.prepareReconnectToStreamRequest = prepareReconnectToStreamRequest;\n }\n async sendMessages({\n abortSignal,\n ...options\n }) {\n var _a21, _b, _c, _d, _e;\n const resolvedBody = await resolve2(this.body);\n const resolvedHeaders = await resolve2(this.headers);\n const resolvedCredentials = await resolve2(this.credentials);\n const baseHeaders = {\n ...normalizeHeaders(resolvedHeaders),\n ...normalizeHeaders(options.headers)\n };\n const preparedRequest = await ((_a21 = this.prepareSendMessagesRequest) == null ? void 0 : _a21.call(this, {\n api: this.api,\n id: options.chatId,\n messages: options.messages,\n body: { ...resolvedBody, ...options.body },\n headers: baseHeaders,\n credentials: resolvedCredentials,\n requestMetadata: options.metadata,\n trigger: options.trigger,\n messageId: options.messageId\n }));\n const api = (_b = preparedRequest == null ? void 0 : preparedRequest.api) != null ? _b : this.api;\n const headers = (preparedRequest == null ? void 0 : preparedRequest.headers) !== void 0 ? normalizeHeaders(preparedRequest.headers) : baseHeaders;\n const body = (preparedRequest == null ? void 0 : preparedRequest.body) !== void 0 ? preparedRequest.body : {\n ...resolvedBody,\n ...options.body,\n id: options.chatId,\n messages: options.messages,\n trigger: options.trigger,\n messageId: options.messageId\n };\n const credentials = (_c = preparedRequest == null ? void 0 : preparedRequest.credentials) != null ? _c : resolvedCredentials;\n const fetch2 = (_d = this.fetch) != null ? _d : globalThis.fetch;\n const response = await fetch2(api, {\n method: \"POST\",\n headers: withUserAgentSuffix11(\n {\n \"Content-Type\": \"application/json\",\n ...headers\n },\n `ai-sdk/${VERSION}`,\n getRuntimeEnvironmentUserAgent3()\n ),\n body: JSON.stringify(body),\n credentials,\n signal: abortSignal\n });\n if (!response.ok) {\n throw new Error(\n (_e = await response.text()) != null ? _e : \"Failed to fetch the chat response.\"\n );\n }\n if (!response.body) {\n throw new Error(\"The response body is empty.\");\n }\n return this.processResponseStream(response.body);\n }\n async reconnectToStream(options) {\n var _a21, _b, _c, _d, _e;\n const resolvedBody = await resolve2(this.body);\n const resolvedHeaders = await resolve2(this.headers);\n const resolvedCredentials = await resolve2(this.credentials);\n const baseHeaders = {\n ...normalizeHeaders(resolvedHeaders),\n ...normalizeHeaders(options.headers)\n };\n const preparedRequest = await ((_a21 = this.prepareReconnectToStreamRequest) == null ? void 0 : _a21.call(this, {\n api: this.api,\n id: options.chatId,\n body: { ...resolvedBody, ...options.body },\n headers: baseHeaders,\n credentials: resolvedCredentials,\n requestMetadata: options.metadata\n }));\n const api = (_b = preparedRequest == null ? void 0 : preparedRequest.api) != null ? _b : `${this.api}/${options.chatId}/stream`;\n const headers = (preparedRequest == null ? void 0 : preparedRequest.headers) !== void 0 ? normalizeHeaders(preparedRequest.headers) : baseHeaders;\n const credentials = (_c = preparedRequest == null ? void 0 : preparedRequest.credentials) != null ? _c : resolvedCredentials;\n const fetch2 = (_d = this.fetch) != null ? _d : globalThis.fetch;\n const response = await fetch2(api, {\n method: \"GET\",\n headers: withUserAgentSuffix11(\n headers,\n `ai-sdk/${VERSION}`,\n getRuntimeEnvironmentUserAgent3()\n ),\n credentials\n });\n if (response.status === 204) {\n return null;\n }\n if (!response.ok) {\n throw new Error(\n (_e = await response.text()) != null ? _e : \"Failed to fetch the chat response.\"\n );\n }\n if (!response.body) {\n throw new Error(\"The response body is empty.\");\n }\n return this.processResponseStream(response.body);\n }\n};\n\n// src/ui/default-chat-transport.ts\nvar DefaultChatTransport = class extends HttpChatTransport {\n constructor(options = {}) {\n super(options);\n }\n processResponseStream(stream) {\n return parseJsonEventStream2({\n stream,\n schema: uiMessageChunkSchema\n }).pipeThrough(\n new TransformStream({\n async transform(chunk, controller) {\n if (!chunk.success) {\n throw chunk.error;\n }\n controller.enqueue(chunk.value);\n }\n })\n );\n }\n};\n\n// src/ui/chat.ts\nvar AbstractChat = class {\n constructor({\n generateId: generateId2 = generateIdFunc2,\n id = generateId2(),\n transport = new DefaultChatTransport(),\n messageMetadataSchema,\n dataPartSchemas,\n state,\n onError,\n onToolCall,\n onFinish,\n onData,\n sendAutomaticallyWhen\n }) {\n this.activeResponse = void 0;\n this.jobExecutor = new SerialJobExecutor();\n /**\n * Appends or replaces a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n *\n * If a messageId is provided, the message will be replaced.\n */\n this.sendMessage = async (message, options) => {\n var _a21, _b, _c, _d;\n if (message == null) {\n await this.makeRequest({\n trigger: \"submit-message\",\n messageId: (_a21 = this.lastMessage) == null ? void 0 : _a21.id,\n ...options\n });\n return;\n }\n let uiMessage;\n if (\"text\" in message || \"files\" in message) {\n const fileParts = Array.isArray(message.files) ? message.files : await convertFileListToFileUIParts(message.files);\n uiMessage = {\n parts: [\n ...fileParts,\n ...\"text\" in message && message.text != null ? [{ type: \"text\", text: message.text }] : []\n ]\n };\n } else {\n uiMessage = message;\n }\n if (message.messageId != null) {\n const messageIndex = this.state.messages.findIndex(\n (m) => m.id === message.messageId\n );\n if (messageIndex === -1) {\n throw new Error(`message with id ${message.messageId} not found`);\n }\n if (this.state.messages[messageIndex].role !== \"user\") {\n throw new Error(\n `message with id ${message.messageId} is not a user message`\n );\n }\n this.state.messages = this.state.messages.slice(0, messageIndex + 1);\n this.state.replaceMessage(messageIndex, {\n ...uiMessage,\n id: message.messageId,\n role: (_b = uiMessage.role) != null ? _b : \"user\",\n metadata: message.metadata\n });\n } else {\n this.state.pushMessage({\n ...uiMessage,\n id: (_c = uiMessage.id) != null ? _c : this.generateId(),\n role: (_d = uiMessage.role) != null ? _d : \"user\",\n metadata: message.metadata\n });\n }\n await this.makeRequest({\n trigger: \"submit-message\",\n messageId: message.messageId,\n ...options\n });\n };\n /**\n * Regenerate the assistant message with the provided message id.\n * If no message id is provided, the last assistant message will be regenerated.\n */\n this.regenerate = async ({\n messageId,\n ...options\n } = {}) => {\n const messageIndex = messageId == null ? this.state.messages.length - 1 : this.state.messages.findIndex((message) => message.id === messageId);\n if (messageIndex === -1) {\n throw new Error(`message ${messageId} not found`);\n }\n this.state.messages = this.state.messages.slice(\n 0,\n // if the message is a user message, we need to include it in the request:\n this.messages[messageIndex].role === \"assistant\" ? messageIndex : messageIndex + 1\n );\n await this.makeRequest({\n trigger: \"regenerate-message\",\n messageId,\n ...options\n });\n };\n /**\n * Attempt to resume an ongoing streaming response.\n */\n this.resumeStream = async (options = {}) => {\n await this.makeRequest({ trigger: \"resume-stream\", ...options });\n };\n /**\n * Clear the error state and set the status to ready if the chat is in an error state.\n */\n this.clearError = () => {\n if (this.status === \"error\") {\n this.state.error = void 0;\n this.setStatus({ status: \"ready\" });\n }\n };\n this.addToolApprovalResponse = async ({\n id,\n approved,\n reason\n }) => this.jobExecutor.run(async () => {\n const messages = this.state.messages;\n const lastMessage = messages[messages.length - 1];\n const updatePart = (part) => isToolUIPart(part) && part.state === \"approval-requested\" && part.approval.id === id ? {\n ...part,\n state: \"approval-responded\",\n approval: { id, approved, reason }\n } : part;\n this.state.replaceMessage(messages.length - 1, {\n ...lastMessage,\n parts: lastMessage.parts.map(updatePart)\n });\n if (this.activeResponse) {\n this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(updatePart);\n }\n if (this.status !== \"streaming\" && this.status !== \"submitted\" && this.sendAutomaticallyWhen) {\n this.shouldSendAutomatically().then((shouldSend) => {\n var _a21;\n if (shouldSend) {\n this.makeRequest({\n trigger: \"submit-message\",\n messageId: (_a21 = this.lastMessage) == null ? void 0 : _a21.id\n });\n }\n });\n }\n });\n this.addToolOutput = async ({\n state = \"output-available\",\n tool: tool2,\n toolCallId,\n output,\n errorText\n }) => this.jobExecutor.run(async () => {\n const messages = this.state.messages;\n const lastMessage = messages[messages.length - 1];\n const updatePart = (part) => isToolUIPart(part) && part.toolCallId === toolCallId ? { ...part, state, output, errorText } : part;\n this.state.replaceMessage(messages.length - 1, {\n ...lastMessage,\n parts: lastMessage.parts.map(updatePart)\n });\n if (this.activeResponse) {\n this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(updatePart);\n }\n if (this.status !== \"streaming\" && this.status !== \"submitted\" && this.sendAutomaticallyWhen) {\n this.shouldSendAutomatically().then((shouldSend) => {\n var _a21;\n if (shouldSend) {\n this.makeRequest({\n trigger: \"submit-message\",\n messageId: (_a21 = this.lastMessage) == null ? void 0 : _a21.id\n });\n }\n });\n }\n });\n /** @deprecated Use addToolOutput */\n this.addToolResult = this.addToolOutput;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n this.stop = async () => {\n var _a21;\n if (this.status !== \"streaming\" && this.status !== \"submitted\")\n return;\n if ((_a21 = this.activeResponse) == null ? void 0 : _a21.abortController) {\n this.activeResponse.abortController.abort();\n }\n };\n this.id = id;\n this.transport = transport;\n this.generateId = generateId2;\n this.messageMetadataSchema = messageMetadataSchema;\n this.dataPartSchemas = dataPartSchemas;\n this.state = state;\n this.onError = onError;\n this.onToolCall = onToolCall;\n this.onFinish = onFinish;\n this.onData = onData;\n this.sendAutomaticallyWhen = sendAutomaticallyWhen;\n }\n /**\n * Hook status:\n *\n * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n * - `ready`: The full response has been received and processed; a new user message can be submitted.\n * - `error`: An error occurred during the API request, preventing successful completion.\n */\n get status() {\n return this.state.status;\n }\n setStatus({\n status,\n error\n }) {\n if (this.status === status)\n return;\n this.state.status = status;\n this.state.error = error;\n }\n get error() {\n return this.state.error;\n }\n get messages() {\n return this.state.messages;\n }\n get lastMessage() {\n return this.state.messages[this.state.messages.length - 1];\n }\n set messages(messages) {\n this.state.messages = messages;\n }\n async shouldSendAutomatically() {\n if (!this.sendAutomaticallyWhen)\n return false;\n const result = this.sendAutomaticallyWhen({\n messages: this.state.messages\n });\n if (result && typeof result === \"object\" && \"then\" in result) {\n return await result;\n }\n return result;\n }\n async makeRequest({\n trigger,\n metadata,\n headers,\n body,\n messageId\n }) {\n var _a21, _b, _c;\n let resumeStream;\n if (trigger === \"resume-stream\") {\n try {\n const reconnect = await this.transport.reconnectToStream({\n chatId: this.id,\n metadata,\n headers,\n body\n });\n if (reconnect == null) {\n return;\n }\n resumeStream = reconnect;\n } catch (err) {\n if (this.onError && err instanceof Error) {\n this.onError(err);\n }\n this.setStatus({ status: \"error\", error: err });\n return;\n }\n }\n this.setStatus({ status: \"submitted\", error: void 0 });\n const lastMessage = this.lastMessage;\n let isAbort = false;\n let isDisconnect = false;\n let isError = false;\n try {\n const activeResponse = {\n state: createStreamingUIMessageState({\n lastMessage: this.state.snapshot(lastMessage),\n messageId: this.generateId()\n }),\n abortController: new AbortController()\n };\n activeResponse.abortController.signal.addEventListener(\"abort\", () => {\n isAbort = true;\n });\n this.activeResponse = activeResponse;\n let stream;\n if (trigger === \"resume-stream\") {\n stream = resumeStream;\n } else {\n stream = await this.transport.sendMessages({\n chatId: this.id,\n messages: this.state.messages,\n abortSignal: activeResponse.abortController.signal,\n metadata,\n headers,\n body,\n trigger,\n messageId\n });\n }\n const runUpdateMessageJob = (job) => (\n // serialize the job execution to avoid race conditions:\n this.jobExecutor.run(\n () => job({\n state: activeResponse.state,\n write: () => {\n var _a22;\n this.setStatus({ status: \"streaming\" });\n const replaceLastMessage = activeResponse.state.message.id === ((_a22 = this.lastMessage) == null ? void 0 : _a22.id);\n if (replaceLastMessage) {\n this.state.replaceMessage(\n this.state.messages.length - 1,\n activeResponse.state.message\n );\n } else {\n this.state.pushMessage(activeResponse.state.message);\n }\n }\n })\n )\n );\n await consumeStream({\n stream: processUIMessageStream({\n stream,\n onToolCall: this.onToolCall,\n onData: this.onData,\n messageMetadataSchema: this.messageMetadataSchema,\n dataPartSchemas: this.dataPartSchemas,\n runUpdateMessageJob,\n onError: (error) => {\n throw error;\n }\n }),\n onError: (error) => {\n throw error;\n }\n });\n this.setStatus({ status: \"ready\" });\n } catch (err) {\n if (isAbort || err.name === \"AbortError\") {\n isAbort = true;\n this.setStatus({ status: \"ready\" });\n return null;\n }\n isError = true;\n if (err instanceof TypeError && (err.message.toLowerCase().includes(\"fetch\") || err.message.toLowerCase().includes(\"network\"))) {\n isDisconnect = true;\n }\n if (this.onError && err instanceof Error) {\n this.onError(err);\n }\n this.setStatus({ status: \"error\", error: err });\n } finally {\n try {\n (_b = this.onFinish) == null ? void 0 : _b.call(this, {\n message: this.activeResponse.state.message,\n messages: this.state.messages,\n isAbort,\n isDisconnect,\n isError,\n finishReason: (_a21 = this.activeResponse) == null ? void 0 : _a21.state.finishReason\n });\n } catch (err) {\n console.error(err);\n }\n this.activeResponse = void 0;\n }\n if (!isError && await this.shouldSendAutomatically()) {\n await this.makeRequest({\n trigger: \"submit-message\",\n messageId: (_c = this.lastMessage) == null ? void 0 : _c.id,\n metadata,\n headers,\n body\n });\n }\n }\n};\n\n// src/ui/direct-chat-transport.ts\nvar DirectChatTransport = class {\n constructor({\n agent,\n options,\n ...uiMessageStreamOptions\n }) {\n this.agent = agent;\n this.agentOptions = options;\n this.uiMessageStreamOptions = uiMessageStreamOptions;\n }\n async sendMessages({\n messages,\n abortSignal\n }) {\n const validatedMessages = await validateUIMessages({\n messages,\n tools: this.agent.tools\n });\n const modelMessages = await convertToModelMessages(validatedMessages, {\n tools: this.agent.tools\n });\n const result = await this.agent.stream({\n prompt: modelMessages,\n abortSignal,\n ...this.agentOptions !== void 0 ? { options: this.agentOptions } : {}\n });\n return result.toUIMessageStream(this.uiMessageStreamOptions);\n }\n /**\n * Direct transport does not support reconnection since there is no\n * persistent server-side stream to reconnect to.\n *\n * @returns Always returns `null`\n */\n async reconnectToStream(_options) {\n return null;\n }\n};\n\n// src/ui/last-assistant-message-is-complete-with-approval-responses.ts\nfunction lastAssistantMessageIsCompleteWithApprovalResponses({\n messages\n}) {\n const message = messages[messages.length - 1];\n if (!message) {\n return false;\n }\n if (message.role !== \"assistant\") {\n return false;\n }\n const lastStepStartIndex = message.parts.reduce((lastIndex, part, index) => {\n return part.type === \"step-start\" ? index : lastIndex;\n }, -1);\n const lastStepToolInvocations = message.parts.slice(lastStepStartIndex + 1).filter(isToolUIPart).filter((part) => !part.providerExecuted);\n return (\n // has at least one tool approval response\n lastStepToolInvocations.filter((part) => part.state === \"approval-responded\").length > 0 && // all tool approvals must have a response\n lastStepToolInvocations.every(\n (part) => part.state === \"output-available\" || part.state === \"output-error\" || part.state === \"approval-responded\"\n )\n );\n}\n\n// src/ui/last-assistant-message-is-complete-with-tool-calls.ts\nfunction lastAssistantMessageIsCompleteWithToolCalls({\n messages\n}) {\n const message = messages[messages.length - 1];\n if (!message) {\n return false;\n }\n if (message.role !== \"assistant\") {\n return false;\n }\n const lastStepStartIndex = message.parts.reduce((lastIndex, part, index) => {\n return part.type === \"step-start\" ? index : lastIndex;\n }, -1);\n const lastStepToolInvocations = message.parts.slice(lastStepStartIndex + 1).filter(isToolUIPart).filter((part) => !part.providerExecuted);\n return lastStepToolInvocations.length > 0 && lastStepToolInvocations.every(\n (part) => part.state === \"output-available\" || part.state === \"output-error\"\n );\n}\n\n// src/ui/transform-text-to-ui-message-stream.ts\nfunction transformTextToUiMessageStream({\n stream\n}) {\n return stream.pipeThrough(\n new TransformStream({\n start(controller) {\n controller.enqueue({ type: \"start\" });\n controller.enqueue({ type: \"start-step\" });\n controller.enqueue({ type: \"text-start\", id: \"text-1\" });\n },\n async transform(part, controller) {\n controller.enqueue({ type: \"text-delta\", id: \"text-1\", delta: part });\n },\n async flush(controller) {\n controller.enqueue({ type: \"text-end\", id: \"text-1\" });\n controller.enqueue({ type: \"finish-step\" });\n controller.enqueue({ type: \"finish\" });\n }\n })\n );\n}\n\n// src/ui/text-stream-chat-transport.ts\nvar TextStreamChatTransport = class extends HttpChatTransport {\n constructor(options = {}) {\n super(options);\n }\n processResponseStream(stream) {\n return transformTextToUiMessageStream({\n stream: stream.pipeThrough(new TextDecoderStream())\n });\n }\n};\nexport {\n AISDKError21 as AISDKError,\n APICallError,\n AbstractChat,\n DefaultChatTransport,\n DefaultGeneratedFile,\n DirectChatTransport,\n DownloadError,\n EmptyResponseBodyError,\n ToolLoopAgent as Experimental_Agent,\n HttpChatTransport,\n InvalidArgumentError,\n InvalidDataContentError,\n InvalidMessageRoleError,\n InvalidPromptError,\n InvalidResponseDataError,\n InvalidStreamPartError,\n InvalidToolApprovalError,\n InvalidToolInputError,\n JSONParseError,\n JsonToSseTransformStream,\n LoadAPIKeyError,\n LoadSettingError,\n MessageConversionError,\n MissingToolResultsError,\n NoContentGeneratedError,\n NoImageGeneratedError,\n NoObjectGeneratedError,\n NoOutputGeneratedError,\n NoSpeechGeneratedError,\n NoSuchModelError,\n NoSuchProviderError,\n NoSuchToolError,\n NoTranscriptGeneratedError,\n NoVideoGeneratedError,\n output_exports as Output,\n RetryError,\n SerialJobExecutor,\n TextStreamChatTransport,\n TooManyEmbeddingValuesForCallError,\n ToolCallNotFoundForApprovalError,\n ToolCallRepairError,\n ToolLoopAgent,\n TypeValidationError,\n UIMessageStreamError,\n UI_MESSAGE_STREAM_HEADERS,\n UnsupportedFunctionalityError,\n UnsupportedModelVersionError,\n addToolInputExamplesMiddleware,\n asSchema5 as asSchema,\n assistantModelMessageSchema,\n bindTelemetryIntegration,\n callCompletionApi,\n consumeStream,\n convertFileListToFileUIParts,\n convertToModelMessages,\n cosineSimilarity,\n createAgentUIStream,\n createAgentUIStreamResponse,\n createDownload,\n createGateway,\n createIdGenerator5 as createIdGenerator,\n createProviderRegistry,\n createTextStreamResponse,\n createUIMessageStream,\n createUIMessageStreamResponse,\n customProvider,\n defaultEmbeddingSettingsMiddleware,\n defaultSettingsMiddleware,\n dynamicTool,\n embed,\n embedMany,\n experimental_createProviderRegistry,\n experimental_customProvider,\n experimental_generateImage,\n generateSpeech as experimental_generateSpeech,\n experimental_generateVideo,\n transcribe as experimental_transcribe,\n extractJsonMiddleware,\n extractReasoningMiddleware,\n gateway2 as gateway,\n generateId,\n generateImage,\n generateObject,\n generateText,\n getStaticToolName,\n getTextFromDataUrl,\n getToolName,\n getToolOrDynamicToolName,\n hasToolCall,\n isDataUIPart,\n isDeepEqualData,\n isFileUIPart,\n isReasoningUIPart,\n isStaticToolUIPart,\n isTextUIPart,\n isToolOrDynamicToolUIPart,\n isToolUIPart,\n jsonSchema,\n lastAssistantMessageIsCompleteWithApprovalResponses,\n lastAssistantMessageIsCompleteWithToolCalls,\n modelMessageSchema,\n parseJsonEventStream3 as parseJsonEventStream,\n parsePartialJson,\n pipeAgentUIStreamToResponse,\n pipeTextStreamToResponse,\n pipeUIMessageStreamToResponse,\n pruneMessages,\n readUIMessageStream,\n registerTelemetryIntegration,\n rerank,\n safeValidateUIMessages,\n simulateReadableStream,\n simulateStreamingMiddleware,\n smoothStream,\n stepCountIs,\n streamObject,\n streamText,\n systemModelMessageSchema,\n tool,\n toolModelMessageSchema,\n uiMessageChunkSchema,\n userModelMessageSchema,\n validateUIMessages,\n wrapEmbeddingModel,\n wrapImageModel,\n wrapLanguageModel,\n wrapProvider,\n zodSchema3 as zodSchema\n};\n//# sourceMappingURL=index.mjs.map","function throttle(function_, wait) {\n\tif (typeof function_ !== 'function') {\n\t\tthrow new TypeError(`Expected the first argument to be a \\`function\\`, got \\`${typeof function_}\\`.`);\n\t}\n\n\t// TODO: Add `wait` validation too in the next major version.\n\n\tlet timeoutId;\n\tlet lastCallTime = 0;\n\n\treturn function throttled(...arguments_) { // eslint-disable-line func-names\n\t\tclearTimeout(timeoutId);\n\n\t\tconst now = Date.now();\n\t\tconst timeSinceLastCall = now - lastCallTime;\n\t\tconst delayForNextCall = wait - timeSinceLastCall;\n\n\t\tif (delayForNextCall <= 0) {\n\t\t\tlastCallTime = now;\n\t\t\tfunction_.apply(this, arguments_);\n\t\t} else {\n\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\tlastCallTime = Date.now();\n\t\t\t\tfunction_.apply(this, arguments_);\n\t\t\t}, delayForNextCall);\n\t\t}\n\t};\n}\n\nmodule.exports = throttle;\n","var __accessCheck = (obj, member, msg) => {\n if (!member.has(obj))\n throw TypeError(\"Cannot \" + msg);\n};\nvar __privateGet = (obj, member, getter) => {\n __accessCheck(obj, member, \"read from private field\");\n return getter ? getter.call(obj) : member.get(obj);\n};\nvar __privateAdd = (obj, member, value) => {\n if (member.has(obj))\n throw TypeError(\"Cannot add the same private member more than once\");\n member instanceof WeakSet ? member.add(obj) : member.set(obj, value);\n};\nvar __privateSet = (obj, member, value, setter) => {\n __accessCheck(obj, member, \"write to private field\");\n setter ? setter.call(obj, value) : member.set(obj, value);\n return value;\n};\n\n// src/use-chat.ts\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from \"react\";\n\n// src/chat.react.ts\nimport { AbstractChat } from \"ai\";\n\n// src/throttle.ts\nimport throttleFunction from \"throttleit\";\nfunction throttle(fn, waitMs) {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n\n// src/chat.react.ts\nvar _messages, _status, _error, _messagesCallbacks, _statusCallbacks, _errorCallbacks, _callMessagesCallbacks, _callStatusCallbacks, _callErrorCallbacks;\nvar ReactChatState = class {\n constructor(initialMessages = []) {\n __privateAdd(this, _messages, void 0);\n __privateAdd(this, _status, \"ready\");\n __privateAdd(this, _error, void 0);\n __privateAdd(this, _messagesCallbacks, /* @__PURE__ */ new Set());\n __privateAdd(this, _statusCallbacks, /* @__PURE__ */ new Set());\n __privateAdd(this, _errorCallbacks, /* @__PURE__ */ new Set());\n this.pushMessage = (message) => {\n __privateSet(this, _messages, __privateGet(this, _messages).concat(message));\n __privateGet(this, _callMessagesCallbacks).call(this);\n };\n this.popMessage = () => {\n __privateSet(this, _messages, __privateGet(this, _messages).slice(0, -1));\n __privateGet(this, _callMessagesCallbacks).call(this);\n };\n this.replaceMessage = (index, message) => {\n __privateSet(this, _messages, [\n ...__privateGet(this, _messages).slice(0, index),\n // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:\n this.snapshot(message),\n ...__privateGet(this, _messages).slice(index + 1)\n ]);\n __privateGet(this, _callMessagesCallbacks).call(this);\n };\n this.snapshot = (value) => structuredClone(value);\n this[\"~registerMessagesCallback\"] = (onChange, throttleWaitMs) => {\n const callback = throttleWaitMs ? throttle(onChange, throttleWaitMs) : onChange;\n __privateGet(this, _messagesCallbacks).add(callback);\n return () => {\n __privateGet(this, _messagesCallbacks).delete(callback);\n };\n };\n this[\"~registerStatusCallback\"] = (onChange) => {\n __privateGet(this, _statusCallbacks).add(onChange);\n return () => {\n __privateGet(this, _statusCallbacks).delete(onChange);\n };\n };\n this[\"~registerErrorCallback\"] = (onChange) => {\n __privateGet(this, _errorCallbacks).add(onChange);\n return () => {\n __privateGet(this, _errorCallbacks).delete(onChange);\n };\n };\n __privateAdd(this, _callMessagesCallbacks, () => {\n __privateGet(this, _messagesCallbacks).forEach((callback) => callback());\n });\n __privateAdd(this, _callStatusCallbacks, () => {\n __privateGet(this, _statusCallbacks).forEach((callback) => callback());\n });\n __privateAdd(this, _callErrorCallbacks, () => {\n __privateGet(this, _errorCallbacks).forEach((callback) => callback());\n });\n __privateSet(this, _messages, initialMessages);\n }\n get status() {\n return __privateGet(this, _status);\n }\n set status(newStatus) {\n __privateSet(this, _status, newStatus);\n __privateGet(this, _callStatusCallbacks).call(this);\n }\n get error() {\n return __privateGet(this, _error);\n }\n set error(newError) {\n __privateSet(this, _error, newError);\n __privateGet(this, _callErrorCallbacks).call(this);\n }\n get messages() {\n return __privateGet(this, _messages);\n }\n set messages(newMessages) {\n __privateSet(this, _messages, [...newMessages]);\n __privateGet(this, _callMessagesCallbacks).call(this);\n }\n};\n_messages = new WeakMap();\n_status = new WeakMap();\n_error = new WeakMap();\n_messagesCallbacks = new WeakMap();\n_statusCallbacks = new WeakMap();\n_errorCallbacks = new WeakMap();\n_callMessagesCallbacks = new WeakMap();\n_callStatusCallbacks = new WeakMap();\n_callErrorCallbacks = new WeakMap();\nvar _state;\nvar Chat = class extends AbstractChat {\n constructor({ messages, ...init }) {\n const state = new ReactChatState(messages);\n super({ ...init, state });\n __privateAdd(this, _state, void 0);\n this[\"~registerMessagesCallback\"] = (onChange, throttleWaitMs) => __privateGet(this, _state)[\"~registerMessagesCallback\"](onChange, throttleWaitMs);\n this[\"~registerStatusCallback\"] = (onChange) => __privateGet(this, _state)[\"~registerStatusCallback\"](onChange);\n this[\"~registerErrorCallback\"] = (onChange) => __privateGet(this, _state)[\"~registerErrorCallback\"](onChange);\n __privateSet(this, _state, state);\n }\n};\n_state = new WeakMap();\n\n// src/use-chat.ts\nfunction useChat({\n experimental_throttle: throttleWaitMs,\n resume = false,\n ...options\n} = {}) {\n const callbacksRef = useRef(\n !(\"chat\" in options) ? {\n onToolCall: options.onToolCall,\n onData: options.onData,\n onFinish: options.onFinish,\n onError: options.onError,\n sendAutomaticallyWhen: options.sendAutomaticallyWhen\n } : {}\n );\n if (!(\"chat\" in options)) {\n callbacksRef.current = {\n onToolCall: options.onToolCall,\n onData: options.onData,\n onFinish: options.onFinish,\n onError: options.onError,\n sendAutomaticallyWhen: options.sendAutomaticallyWhen\n };\n }\n const optionsWithCallbacks = {\n ...options,\n onToolCall: (arg) => {\n var _a, _b;\n return (_b = (_a = callbacksRef.current).onToolCall) == null ? void 0 : _b.call(_a, arg);\n },\n onData: (arg) => {\n var _a, _b;\n return (_b = (_a = callbacksRef.current).onData) == null ? void 0 : _b.call(_a, arg);\n },\n onFinish: (arg) => {\n var _a, _b;\n return (_b = (_a = callbacksRef.current).onFinish) == null ? void 0 : _b.call(_a, arg);\n },\n onError: (arg) => {\n var _a, _b;\n return (_b = (_a = callbacksRef.current).onError) == null ? void 0 : _b.call(_a, arg);\n },\n sendAutomaticallyWhen: (arg) => {\n var _a, _b, _c;\n return (_c = (_b = (_a = callbacksRef.current).sendAutomaticallyWhen) == null ? void 0 : _b.call(_a, arg)) != null ? _c : false;\n }\n };\n const chatRef = useRef(\n \"chat\" in options ? options.chat : new Chat(optionsWithCallbacks)\n );\n const shouldRecreateChat = \"chat\" in options && options.chat !== chatRef.current || \"id\" in options && chatRef.current.id !== options.id;\n if (shouldRecreateChat) {\n chatRef.current = \"chat\" in options ? options.chat : new Chat(optionsWithCallbacks);\n }\n const subscribeToMessages = useCallback(\n (update) => chatRef.current[\"~registerMessagesCallback\"](update, throttleWaitMs),\n // `chatRef.current.id` is required to trigger re-subscription when the chat ID changes\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [throttleWaitMs, chatRef.current.id]\n );\n const messages = useSyncExternalStore(\n subscribeToMessages,\n () => chatRef.current.messages,\n () => chatRef.current.messages\n );\n const status = useSyncExternalStore(\n chatRef.current[\"~registerStatusCallback\"],\n () => chatRef.current.status,\n () => chatRef.current.status\n );\n const error = useSyncExternalStore(\n chatRef.current[\"~registerErrorCallback\"],\n () => chatRef.current.error,\n () => chatRef.current.error\n );\n const setMessages = useCallback(\n (messagesParam) => {\n if (typeof messagesParam === \"function\") {\n messagesParam = messagesParam(chatRef.current.messages);\n }\n chatRef.current.messages = messagesParam;\n },\n [chatRef]\n );\n useEffect(() => {\n if (resume) {\n chatRef.current.resumeStream();\n }\n }, [resume, chatRef]);\n return {\n id: chatRef.current.id,\n messages,\n setMessages,\n sendMessage: chatRef.current.sendMessage,\n regenerate: chatRef.current.regenerate,\n clearError: chatRef.current.clearError,\n stop: chatRef.current.stop,\n error,\n resumeStream: chatRef.current.resumeStream,\n status,\n /**\n * @deprecated Use `addToolOutput` instead.\n */\n addToolResult: chatRef.current.addToolOutput,\n addToolOutput: chatRef.current.addToolOutput,\n addToolApprovalResponse: chatRef.current.addToolApprovalResponse\n };\n}\n\n// src/use-completion.ts\nimport {\n callCompletionApi\n} from \"ai\";\nimport { useCallback as useCallback2, useEffect as useEffect2, useId, useRef as useRef2, useState } from \"react\";\nimport useSWR from \"swr\";\nfunction useCompletion({\n api = \"/api/completion\",\n id,\n initialCompletion = \"\",\n initialInput = \"\",\n credentials,\n headers,\n body,\n streamProtocol = \"data\",\n fetch: fetch2,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs\n} = {}) {\n const hookId = useId();\n const completionId = id || hookId;\n const { data, mutate } = useSWR([api, completionId], null, {\n fallbackData: initialCompletion\n });\n const { data: isLoading = false, mutate: mutateLoading } = useSWR(\n [completionId, \"loading\"],\n null\n );\n const [error, setError] = useState(void 0);\n const completion = data;\n const [abortController, setAbortController] = useState(null);\n const extraMetadataRef = useRef2({\n credentials,\n headers,\n body\n });\n useEffect2(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body\n };\n }, [credentials, headers, body]);\n const triggerRequest = useCallback2(\n async (prompt, options) => callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options == null ? void 0 : options.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options == null ? void 0 : options.body\n },\n streamProtocol,\n fetch: fetch2,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion2) => mutate(completion2, false),\n throttleWaitMs\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onFinish,\n onError\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch2,\n throttleWaitMs\n ]\n );\n const stop = useCallback2(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n const setCompletion = useCallback2(\n (completion2) => {\n mutate(completion2, false);\n },\n [mutate]\n );\n const complete = useCallback2(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest]\n );\n const [input, setInput] = useState(initialInput);\n const handleSubmit = useCallback2(\n (event) => {\n var _a;\n (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);\n return input ? complete(input) : void 0;\n },\n [input, complete]\n );\n const handleInputChange = useCallback2(\n (e) => {\n setInput(e.target.value);\n },\n [setInput]\n );\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading\n };\n}\n\n// src/use-object.ts\nimport {\n isAbortError,\n resolve,\n normalizeHeaders,\n safeValidateTypes\n} from \"@ai-sdk/provider-utils\";\nimport { asSchema, isDeepEqualData, parsePartialJson } from \"ai\";\nimport { useCallback as useCallback3, useId as useId2, useRef as useRef3, useState as useState2 } from \"react\";\nimport useSWR2 from \"swr\";\nvar getOriginalFetch = () => fetch;\nfunction useObject({\n api,\n id,\n schema,\n // required, in the future we will use it for validation\n initialValue,\n fetch: fetch2,\n onError,\n onFinish,\n headers,\n credentials\n}) {\n const hookId = useId2();\n const completionId = id != null ? id : hookId;\n const { data, mutate } = useSWR2(\n [api, completionId],\n null,\n { fallbackData: initialValue }\n );\n const [error, setError] = useState2(void 0);\n const [isLoading, setIsLoading] = useState2(false);\n const abortControllerRef = useRef3(null);\n const stop = useCallback3(() => {\n var _a;\n try {\n (_a = abortControllerRef.current) == null ? void 0 : _a.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n const submit = async (input) => {\n var _a;\n try {\n clearObject();\n setIsLoading(true);\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n const resolvedHeaders = await resolve(headers);\n const actualFetch = fetch2 != null ? fetch2 : getOriginalFetch();\n const response = await actualFetch(api, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...normalizeHeaders(resolvedHeaders)\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input)\n });\n if (!response.ok) {\n throw new Error(\n (_a = await response.text()) != null ? _a : \"Failed to fetch the response.\"\n );\n }\n if (response.body == null) {\n throw new Error(\"The response body is empty.\");\n }\n let accumulatedText = \"\";\n let latestObject = void 0;\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream({\n async write(chunk) {\n accumulatedText += chunk;\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value;\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n mutate(currentObject);\n }\n },\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema)\n });\n onFinish(\n validationResult.success ? { object: validationResult.value, error: void 0 } : { object: void 0, error: validationResult.error }\n );\n }\n }\n })\n );\n } catch (error2) {\n if (isAbortError(error2)) {\n return;\n }\n if (onError && error2 instanceof Error) {\n onError(error2);\n }\n setIsLoading(false);\n setError(error2 instanceof Error ? error2 : new Error(String(error2)));\n }\n };\n const clear = () => {\n stop();\n clearObject();\n };\n const clearObject = () => {\n setError(void 0);\n setIsLoading(false);\n mutate(void 0);\n };\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n clear\n };\n}\nvar experimental_useObject = useObject;\nexport {\n Chat,\n experimental_useObject,\n useChat,\n useCompletion\n};\n//# sourceMappingURL=index.mjs.map","/**\n * 嵌入 OMS 时可通过此配置指定 Agent 后端地址。\n * - 未设置时使用相对路径,即与当前页同源(开发时 Vite proxy 或同机后端)。\n * - 集成到 OMS 且后端独立部署时,设为该后端的完整 origin,如 https://oms-agent.example.com\n */\ndeclare global {\n interface Window {\n __OMS_AGENT_API_BASE__?: string;\n }\n}\n\nconst meta = typeof import.meta !== \"undefined\" ? (import.meta as { env?: Record<string, unknown> }) : undefined;\nconst VITE_BASE =\n meta?.env?.VITE_OMS_AGENT_API_BASE != null\n ? String(meta.env.VITE_OMS_AGENT_API_BASE).replace(/\\/$/, \"\")\n : \"\";\n\nexport function getAgentApiBase(): string {\n if (typeof window !== \"undefined\" && window.__OMS_AGENT_API_BASE__ != null) {\n return String(window.__OMS_AGENT_API_BASE__).replace(/\\/$/, \"\");\n }\n return VITE_BASE;\n}\n","import { z } from \"zod\";\n\nexport const knowledgeSourceTypeSchema = z.enum([\n \"page-map\",\n \"manual\",\n \"product-doc\",\n \"faq\",\n \"error-guide\",\n \"glossary\",\n]);\n\nexport const runtimePageContextSchema = z.object({\n pageId: z.string(),\n pageName: z.string(),\n moduleName: z.string(),\n routePath: z.string(),\n currentUrl: z.string(),\n title: z.string(),\n visibleTexts: z.array(z.string()),\n});\n\nexport const runtimeNodeContextSchema = z.object({\n tagName: z.string(),\n text: z.string(),\n domPath: z.string(),\n classNames: z.array(z.string()),\n nearbyHeading: z.string().optional(),\n componentName: z.string().optional(),\n});\n\nexport const runtimeContextSchema = z.object({\n page: runtimePageContextSchema,\n selectedNode: runtimeNodeContextSchema.nullable(),\n});\n\nexport const codeSearchTaskTypeSchema = z.enum([\n \"route-match\",\n \"text-search\",\n \"component-trace\",\n \"api-trace\",\n \"error-code-search\",\n \"symbol-search\",\n]);\n\nexport const codeSearchTaskSchema = z.object({\n type: codeSearchTaskTypeSchema,\n payload: z.record(z.string(), z.unknown()),\n});\n\nexport const codeSearchQuerySchema = z.object({\n queryId: z.string(),\n workspace: z.object({\n repo: z.string(),\n revision: z.string(),\n }),\n runtimeContext: runtimeContextSchema,\n tasks: z.array(codeSearchTaskSchema),\n});\n\nexport const codeSearchHitSchema = z.object({\n filePath: z.string(),\n symbol: z.string().optional(),\n matchType: z.string(),\n score: z.number(),\n snippet: z.string(),\n reason: z.string(),\n lineStart: z.number().optional(),\n lineEnd: z.number().optional(),\n relatedRoute: z.string().optional(),\n relatedComponent: z.string().optional(),\n relatedApis: z.array(z.string()).optional(),\n});\n\nexport const apiCandidateSchema = z.object({\n filePath: z.string(),\n method: z.string(),\n path: z.string(),\n requestName: z.string().optional(),\n calledBy: z.array(z.string()),\n score: z.number(),\n});\n\nexport const codeSearchTaskResultSchema = z.object({\n task: codeSearchTaskTypeSchema,\n hits: z.array(codeSearchHitSchema),\n});\n\nexport const codeSearchResponseSchema = z.object({\n queryId: z.string(),\n results: z.array(codeSearchTaskResultSchema),\n apiCandidates: z.array(apiCandidateSchema),\n});\n\nexport const docsSearchModeSchema = z.enum([\"semantic\", \"keyword\", \"hybrid\"]);\n\nexport const docsSearchQuerySchema = z.object({\n queryId: z.string(),\n mode: docsSearchModeSchema,\n question: z.string(),\n runtimeContext: runtimeContextSchema,\n});\n\nexport const docsSearchHitSchema = z.object({\n docId: z.string(),\n title: z.string(),\n sourceType: knowledgeSourceTypeSchema,\n excerpt: z.string(),\n score: z.number(),\n updatedAt: z.string(),\n});\n\nexport const docsSearchResponseSchema = z.object({\n queryId: z.string(),\n hits: z.array(docsSearchHitSchema),\n});\n\nexport const agentQuerySchema = z.object({\n question: z.string().min(1),\n runtimeContext: runtimeContextSchema,\n});\n\nexport const agentResponseSchema = z.object({\n answer: z.string(),\n confidence: z.number().min(0).max(1),\n sources: z.array(\n z.object({\n id: z.string(),\n title: z.string(),\n sourceType: knowledgeSourceTypeSchema,\n excerpt: z.string(),\n }),\n ),\n codeCandidates: z.array(codeSearchHitSchema),\n apiCandidates: z.array(apiCandidateSchema),\n docCandidates: z.array(docsSearchHitSchema),\n});\n\nexport type RuntimeContextPayload = z.infer<typeof runtimeContextSchema>;\nexport type CodeSearchQuery = z.infer<typeof codeSearchQuerySchema>;\nexport type CodeSearchHit = z.infer<typeof codeSearchHitSchema>;\nexport type CodeSearchTask = z.infer<typeof codeSearchTaskSchema>;\nexport type CodeSearchResponse = z.infer<typeof codeSearchResponseSchema>;\nexport type DocsSearchQuery = z.infer<typeof docsSearchQuerySchema>;\nexport type DocsSearchHit = z.infer<typeof docsSearchHitSchema>;\nexport type DocsSearchResponse = z.infer<typeof docsSearchResponseSchema>;\nexport type AgentQuery = z.infer<typeof agentQuerySchema>;\nexport type AgentResponse = z.infer<typeof agentResponseSchema>;\n","import { useMemo } from \"react\";\nimport { useChat } from \"@ai-sdk/react\";\nimport type { ChatTransport, UIMessage, UIMessageChunk } from \"ai\";\n\nimport type { KnowledgeCitation } from \"@/integrations/knowledge/types\";\nimport { getAgentApiBase } from \"@/integrations/oms/config\";\nimport type { OmsRuntimeContext } from \"@/integrations/oms/types\";\nimport { sleep } from \"@/shared/lib/utils\";\nimport {\n agentResponseSchema,\n type AgentResponse,\n} from \"@/shared/schemas/agent\";\n\ninterface OmsMessageMetadata {\n sources?: KnowledgeCitation[];\n confidence?: number;\n}\n\nexport type OmsUIMessage = UIMessage<OmsMessageMetadata>;\n\ninterface RuntimeBody {\n runtimeContext?: OmsRuntimeContext;\n}\n\nfunction extractText(message: OmsUIMessage) {\n return message.parts\n .filter((part): part is Extract<(typeof message.parts)[number], { type: \"text\" }> => {\n return part.type === \"text\";\n })\n .map((part) => part.text)\n .join(\"\\n\")\n .trim();\n}\n\nclass MockOmsChatTransport implements ChatTransport<OmsUIMessage> {\n private async askAgent(\n question: string,\n runtimeContext: OmsRuntimeContext,\n ): Promise<AgentResponse> {\n const base = getAgentApiBase();\n const response = await fetch(`${base}/api/agent/query`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n question,\n runtimeContext: {\n page: {\n pageId: runtimeContext.page.pageId,\n pageName: runtimeContext.page.pageName,\n moduleName: runtimeContext.page.moduleName,\n routePath: runtimeContext.page.routePath,\n currentUrl: runtimeContext.page.currentUrl,\n title: runtimeContext.page.title,\n visibleTexts: runtimeContext.page.visibleTexts,\n },\n selectedNode: runtimeContext.selectedNode\n ? {\n tagName: runtimeContext.selectedNode.tagName,\n text: runtimeContext.selectedNode.text,\n domPath: runtimeContext.selectedNode.domPath,\n classNames: runtimeContext.selectedNode.classNames,\n nearbyHeading: runtimeContext.selectedNode.nearbyHeading,\n componentName: runtimeContext.selectedNode.componentName,\n }\n : null,\n },\n }),\n });\n\n if (!response.ok) {\n throw new Error(\"Agent 服务暂时不可用,请确认本地后端已经启动。\");\n }\n\n const json = await response.json();\n return agentResponseSchema.parse(json);\n }\n\n async sendMessages(options: {\n trigger: \"submit-message\" | \"regenerate-message\";\n chatId: string;\n messageId: string | undefined;\n messages: OmsUIMessage[];\n abortSignal: AbortSignal | undefined;\n body?: object;\n headers?: Headers | Record<string, string>;\n metadata?: unknown;\n }): Promise<ReadableStream<UIMessageChunk<OmsMessageMetadata>>> {\n const body = (options.body ?? {}) as RuntimeBody;\n const runtimeContext = body.runtimeContext;\n const userMessage = options.messages.at(-1);\n\n if (!runtimeContext || !userMessage) {\n throw new Error(\"缺少运行时上下文,暂时无法回答这个问题。\");\n }\n\n const text = extractText(userMessage);\n const answer = await this.askAgent(text, runtimeContext);\n const textId = `assistant-${Date.now()}`;\n const segments = answer.answer\n .replaceAll(\"\\r\\n\", \"\\n\")\n .split(/(?<=[。!?,\\n])/)\n .map((segment: string) => segment.trim())\n .filter(Boolean);\n\n return new ReadableStream<UIMessageChunk<OmsMessageMetadata>>({\n start: async (controller) => {\n controller.enqueue({\n type: \"message-metadata\",\n messageMetadata: {\n sources: answer.sources,\n confidence: answer.confidence,\n },\n });\n controller.enqueue({ type: \"text-start\", id: textId });\n\n for (const segment of segments) {\n if (options.abortSignal?.aborted) {\n controller.close();\n return;\n }\n\n controller.enqueue({\n type: \"text-delta\",\n id: textId,\n delta: `${segment}${segment.endsWith(\"\\n\") ? \"\" : \" \"}`,\n });\n await sleep(45);\n }\n\n controller.enqueue({ type: \"text-end\", id: textId });\n controller.close();\n },\n });\n }\n\n async reconnectToStream() {\n return null;\n }\n}\n\nexport function useOmsAgentChat(runtimeContext: OmsRuntimeContext) {\n const transport = useMemo(() => new MockOmsChatTransport(), []);\n const chat = useChat<OmsUIMessage>({\n id: \"oms-agent-playground\",\n transport,\n });\n\n return {\n ...chat,\n sendQuestion: (text: string) =>\n chat.sendMessage(\n {\n text,\n },\n {\n body: {\n runtimeContext,\n },\n },\n ),\n };\n}\n","import { Bot, Crosshair, FileCode2, Send, X } from \"lucide-react\";\nimport { useEffect, useRef, useState } from \"react\";\n\nimport type { OmsRuntimeContext } from \"@/integrations/oms/types\";\nimport { cn } from \"@/shared/lib/utils\";\nimport { useOmsAgentChat } from \"@/features/agent/hooks/useOmsAgentChat\";\n\ninterface OmsAgentPanelProps {\n open: boolean;\n runtimeContext: OmsRuntimeContext;\n inspecting: boolean;\n panelStyle: {\n left: number;\n top: number;\n };\n onClose: () => void;\n onStartInspecting: () => void;\n onClearSelection: () => void;\n}\n\nconst quickPrompts = [\n \"这个节点来自哪个前端文件?\",\n \"这里用到的后端数据来源于哪里?\",\n \"页面上这个值是什么意思?\",\n \"订单出现 E2003 错误通常是什么原因?\",\n];\n\nfunction sourceLabel(sourceType: string) {\n switch (sourceType) {\n case \"manual\":\n return \"用户手册\";\n case \"product-doc\":\n return \"产品文档\";\n case \"faq\":\n return \"FAQ\";\n case \"error-guide\":\n return \"错误说明\";\n case \"glossary\":\n return \"术语表\";\n default:\n return \"知识源\";\n }\n}\n\nexport function OmsAgentPanel({\n open,\n runtimeContext,\n inspecting,\n panelStyle,\n onClose,\n onStartInspecting,\n onClearSelection,\n}: OmsAgentPanelProps) {\n const [input, setInput] = useState(\"\");\n const { messages, status, error, sendQuestion } = useOmsAgentChat(runtimeContext);\n const messagesViewportRef = useRef<HTMLDivElement | null>(null);\n\n const submit = async (text: string) => {\n const normalized = text.trim();\n\n if (!normalized) {\n return;\n }\n\n await sendQuestion(normalized);\n setInput(\"\");\n };\n\n useEffect(() => {\n const viewport = messagesViewportRef.current;\n\n if (!viewport) {\n return;\n }\n\n viewport.scrollTo({\n top: viewport.scrollHeight,\n behavior: \"smooth\",\n });\n }, [messages, status]);\n\n return (\n <aside\n className={cn(\n \"fixed z-50 flex h-[min(76vh,680px)] w-[min(392px,calc(100vw-24px))] flex-col overflow-hidden rounded-[24px] border border-[#4B8BFF]/18 bg-[linear-gradient(180deg,rgba(10,20,40,0.97),rgba(7,14,28,0.985))] shadow-[0_24px_72px_rgba(22,93,255,0.18)] backdrop-blur-2xl transition-all\",\n open\n ? \"translate-y-0 opacity-100\"\n : \"pointer-events-none translate-y-4 opacity-0\",\n )}\n data-oms-agent-root\n style={panelStyle}\n >\n <header className=\"border-b border-white/10 bg-[linear-gradient(135deg,rgba(22,93,255,0.16),rgba(72,128,255,0.1),rgba(10,20,40,0.24))] px-4 py-3\">\n <div className=\"flex items-start justify-between gap-4\">\n <div className=\"space-y-1.5\">\n <div className=\"flex items-center gap-2 text-xs text-[#79A9FF]\">\n <Bot className=\"size-3.5\" />\n OMS Agent Playground\n </div>\n <div>\n <h2 className=\"m-0 text-base font-semibold text-white\">\n {runtimeContext.page.pageName}\n </h2>\n <p className=\"m-0 text-xs text-slate-400\">\n {runtimeContext.page.moduleName} · {runtimeContext.page.routePath}\n </p>\n </div>\n </div>\n\n <button\n className=\"rounded-full border border-white/10 p-1.5 text-slate-400 transition hover:border-white/20 hover:text-white\"\n onClick={onClose}\n type=\"button\"\n >\n <X className=\"size-3.5\" />\n </button>\n </div>\n </header>\n\n <div className=\"flex-1 space-y-3 overflow-y-auto px-4 py-3\" ref={messagesViewportRef}>\n {messages.length === 0 ? (\n <div className=\"space-y-3\">\n <div className=\"rounded-2xl border border-dashed border-[#4B8BFF]/18 bg-[linear-gradient(135deg,rgba(22,93,255,0.08),rgba(72,128,255,0.05))] px-3 py-2.5 text-xs leading-6 text-slate-300\">\n 这个助手当前能结合页面 URL、选中节点、模拟源码映射、接口来源和文档知识来回答问题。\n </div>\n <div className=\"flex flex-wrap gap-2\">\n {quickPrompts.map((prompt) => (\n <button\n key={prompt}\n className=\"rounded-full border border-white/10 bg-white/[0.03] px-2.5 py-1.5 text-left text-xs text-slate-200 transition hover:border-[#4B8BFF]/60 hover:bg-[#165DFF]/10\"\n onClick={() => void submit(prompt)}\n type=\"button\"\n >\n {prompt}\n </button>\n ))}\n </div>\n </div>\n ) : null}\n\n {messages.map((message) => (\n <div\n className={cn(\n \"rounded-2xl px-3 py-2.5 text-sm leading-6\",\n message.role === \"user\"\n ? \"ml-6 border border-[#4B8BFF]/14 bg-[linear-gradient(135deg,rgba(22,93,255,0.18),rgba(56,118,255,0.1))] text-[#EEF4FF]\"\n : \"mr-6 border border-white/10 bg-[linear-gradient(135deg,rgba(255,255,255,0.06),rgba(22,93,255,0.04))] text-slate-100\",\n )}\n key={message.id}\n >\n <div className=\"mb-1.5 text-[10px] uppercase tracking-[0.18em] text-slate-400\">\n {message.role === \"user\" ? \"开发者\" : \"OMS Agent\"}\n </div>\n\n {message.parts.map((part, index) => {\n if (part.type !== \"text\") {\n return null;\n }\n\n return (\n <p className=\"m-0 whitespace-pre-wrap\" key={`${message.id}-${index}`}>\n {part.text}\n </p>\n );\n })}\n\n {message.role === \"assistant\" && message.metadata?.sources?.length ? (\n <div className=\"mt-2.5 border-t border-white/10 pt-2.5\">\n <div className=\"mb-2 text-[10px] uppercase tracking-[0.18em] text-slate-500\">\n Sources\n </div>\n <div className=\"flex flex-col gap-2\">\n {message.metadata.sources.map((source) => (\n <div\n className=\"rounded-xl border border-white/8 bg-slate-900/70 px-2.5 py-2\"\n key={source.id}\n >\n <div className=\"text-[11px] text-[#79A9FF]\">\n {sourceLabel(source.sourceType)}\n </div>\n <div className=\"text-sm font-medium text-white\">{source.title}</div>\n <div className=\"text-[11px] text-slate-400\">{source.excerpt}</div>\n </div>\n ))}\n </div>\n </div>\n ) : null}\n </div>\n ))}\n\n {status === \"streaming\" ? (\n <div className=\"text-sm text-[#79A9FF]\">正在分析页面上下文和知识源...</div>\n ) : null}\n\n {error ? <div className=\"text-sm text-rose-300\">{error.message}</div> : null}\n </div>\n\n <footer className=\"border-t border-white/10 p-3\">\n <form\n className=\"rounded-2xl border border-[#4B8BFF]/14 bg-[linear-gradient(135deg,rgba(255,255,255,0.05),rgba(22,93,255,0.06),rgba(72,128,255,0.05))] p-2.5\"\n onSubmit={(event) => {\n event.preventDefault();\n void submit(input);\n }}\n >\n {runtimeContext.selectedNode ? (\n <div className=\"mb-2.5\">\n <div className=\"inline-flex max-w-full items-center gap-2 rounded-lg border border-[#4B8BFF]/24 bg-[#165DFF]/10 px-2.5 py-1.5 text-xs text-[#EEF4FF]\">\n <FileCode2 className=\"size-3.5 shrink-0 text-[#79A9FF]\" />\n <span className=\"truncate\">\n {runtimeContext.selectedNode.text || runtimeContext.selectedNode.tagName}\n </span>\n <button\n className=\"inline-flex size-4.5 items-center justify-center rounded-full text-[#9EC0FF] transition hover:bg-white/10 hover:text-white\"\n onClick={onClearSelection}\n aria-label=\"移除已选节点\"\n type=\"button\"\n >\n <X className=\"size-3\" />\n </button>\n </div>\n </div>\n ) : null}\n\n <textarea\n className=\"min-h-20 w-full resize-none bg-transparent text-sm text-white outline-none placeholder:text-slate-500\"\n onChange={(event) => setInput(event.target.value)}\n placeholder=\"问我:这个节点在哪个文件?这个值是什么意思?这个错误为什么出现?\"\n value={input}\n />\n\n <div className=\"mt-2.5 flex items-center justify-between\">\n <button\n className={cn(\n \"inline-flex h-8.5 items-center gap-1.5 rounded-lg border px-2.5 text-xs transition\",\n inspecting\n ? \"border-amber-300/40 bg-amber-400/85 text-slate-950\"\n : \"border-[#4B8BFF]/24 bg-white/5 text-slate-200 hover:border-[#4B8BFF]/50 hover:bg-[#165DFF]/10\",\n )}\n onClick={onStartInspecting}\n type=\"button\"\n >\n <Crosshair className=\"size-3.5\" />\n {inspecting ? \"点击页面节点\" : \"选点\"}\n </button>\n\n <button\n className=\"inline-flex size-8.5 items-center justify-center rounded-lg bg-[linear-gradient(135deg,rgba(22,93,255,0.98),rgba(72,128,255,0.94))] text-white transition hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-40\"\n disabled={!input.trim() || status === \"streaming\"}\n type=\"submit\"\n >\n <Send className=\"size-3.5\" />\n </button>\n </div>\n </form>\n </footer>\n </aside>\n );\n}\n","import type { OmsBridge, OmsRuntimeContext } from \"@/integrations/oms/types\";\n\nexport function collectRuntimeContext(\n bridge: OmsBridge,\n selectedNode: HTMLElement | null,\n): OmsRuntimeContext {\n return {\n page: bridge.getPageContext(),\n selectedNode: selectedNode ? bridge.resolveNodeContext(selectedNode) : null,\n };\n}\n","import type {\n ApiSourceCandidate,\n FrontendFileCandidate,\n} from \"@/integrations/oms/types\";\n\nexport interface OmsPageDefinition {\n pageId: string;\n pageName: string;\n moduleName: string;\n routePath: string;\n frontendFiles: FrontendFileCandidate[];\n apiSources: ApiSourceCandidate[];\n domHints: Array<{\n keywords: string[];\n componentName: string;\n frontendFiles: FrontendFileCandidate[];\n apiSources: ApiSourceCandidate[];\n }>;\n}\n\nexport const omsPages: OmsPageDefinition[] = [\n {\n pageId: \"order-detail\",\n pageName: \"订单详情页\",\n moduleName: \"订单中心\",\n routePath: \"/oms/orders/detail/2026001\",\n frontendFiles: [\n {\n filePath: \"src/pages/orders/detail/index.tsx\",\n reason: \"订单详情页主入口\",\n },\n {\n filePath: \"src/pages/orders/detail/components/OrderStatusCard.tsx\",\n reason: \"状态卡片与异常提示常驻在详情页首屏\",\n },\n ],\n apiSources: [\n {\n name: \"查询订单详情\",\n method: \"GET\",\n path: \"/api/orders/:orderId\",\n purpose: \"加载订单基本信息、履约状态和异常信息\",\n },\n {\n name: \"查询风控标签\",\n method: \"GET\",\n path: \"/api/orders/:orderId/risk-tags\",\n purpose: \"展示风控状态、人工复核标签和风控备注\",\n },\n ],\n domHints: [\n {\n keywords: [\"异常待处理\", \"渠道库存锁定失败\", \"重新推单\"],\n componentName: \"OrderStatusCard\",\n frontendFiles: [\n {\n filePath: \"src/pages/orders/detail/components/OrderStatusCard.tsx\",\n symbol: \"OrderStatusCard\",\n reason: \"命中状态卡片的文案与异常操作按钮\",\n },\n ],\n apiSources: [\n {\n name: \"查询订单详情\",\n method: \"GET\",\n path: \"/api/orders/:orderId\",\n purpose: \"异常状态和错误信息来自订单详情接口\",\n },\n ],\n },\n {\n keywords: [\"待人工复核\", \"风控状态\", \"复核说明\"],\n componentName: \"RiskReviewPanel\",\n frontendFiles: [\n {\n filePath: \"src/pages/orders/detail/components/RiskReviewPanel.tsx\",\n symbol: \"RiskReviewPanel\",\n reason: \"命中风控状态区块的字段和标签\",\n },\n ],\n apiSources: [\n {\n name: \"查询风控标签\",\n method: \"GET\",\n path: \"/api/orders/:orderId/risk-tags\",\n purpose: \"风控状态与说明由风控标签接口提供\",\n },\n ],\n },\n ],\n },\n];\n\nexport function matchOmsPage(pathname: string) {\n return (\n omsPages.find((page) => pathname.startsWith(page.routePath)) ?? omsPages[0]\n );\n}\n\nexport function matchNodeHints(text: string) {\n const normalized = text.trim().toLowerCase();\n\n return omsPages\n .flatMap((page) => page.domHints)\n .filter((hint) =>\n hint.keywords.some((keyword) =>\n normalized.includes(keyword.toLowerCase()),\n ),\n );\n}\n","import { matchNodeHints } from \"@/mocks/omsKnowledge\";\nimport {\n getCurrentDemoRouteOption,\n getCurrentDemoRoutePath,\n} from \"@/integrations/oms/demoRoutes\";\nimport type { OmsBridge, OmsNodeContext, OmsPageContext } from \"@/integrations/oms/types\";\n\nfunction compactText(value: string) {\n return value.replace(/\\s+/g, \" \").trim();\n}\n\nfunction getVisibleTexts() {\n const selectors = [\"h1\", \"h2\", \"h3\", \"button\", \"[data-oms-copy]\"];\n const texts = Array.from(document.querySelectorAll<HTMLElement>(selectors.join(\",\")))\n .map((element) => compactText(element.innerText || element.textContent || \"\"))\n .filter(Boolean);\n\n return Array.from(new Set(texts)).slice(0, 12);\n}\n\nfunction getDomPath(node: HTMLElement) {\n const segments: string[] = [];\n let current: HTMLElement | null = node;\n\n while (current && current !== document.body && segments.length < 5) {\n const id = current.id ? `#${current.id}` : \"\";\n const className =\n current.classList.length > 0\n ? `.${Array.from(current.classList).slice(0, 2).join(\".\")}`\n : \"\";\n\n segments.unshift(`${current.tagName.toLowerCase()}${id}${className}`);\n current = current.parentElement;\n }\n\n return segments.join(\" > \");\n}\n\nfunction getNearbyHeading(node: HTMLElement) {\n const heading = node.closest<HTMLElement>(\"section,article,div\")?.querySelector(\"h2, h3\");\n\n return heading ? compactText(heading.textContent || \"\") : undefined;\n}\n\nexport const omsBridge: OmsBridge = {\n getPageContext(): OmsPageContext {\n const demoPath = getCurrentDemoRoutePath();\n const demoRoute = getCurrentDemoRouteOption();\n\n if (demoPath && demoRoute) {\n const origin = typeof window !== \"undefined\" ? window.location.origin : \"\";\n const currentUrl = `${origin}${demoPath}`;\n const visibleTexts = getVisibleTexts();\n const texts =\n visibleTexts.length > 0 ? visibleTexts : demoRoute.sampleTexts.slice(0, 8);\n\n return {\n pageId: demoRoute.pageId,\n pageName: demoRoute.title,\n moduleName: demoRoute.moduleName,\n routePath: demoPath,\n currentUrl,\n title: `${demoRoute.title} - OMS`,\n visibleTexts: texts,\n frontendFiles: [],\n apiSources: [],\n };\n }\n\n const origin = typeof window !== \"undefined\" ? window.location.origin : \"\";\n const path = typeof window !== \"undefined\" ? window.location.pathname : \"/\";\n return {\n pageId: \"unknown\",\n pageName: \"当前页\",\n moduleName: \"\",\n routePath: path,\n currentUrl: `${origin}${path}`,\n title: document.title,\n visibleTexts: getVisibleTexts(),\n frontendFiles: [],\n apiSources: [],\n };\n },\n resolveNodeContext(node: HTMLElement): OmsNodeContext {\n const text = compactText(node.innerText || node.textContent || \"\");\n const hints = matchNodeHints(text);\n const datasetComponent = node.dataset.omsComponent;\n\n return {\n tagName: node.tagName.toLowerCase(),\n text,\n domPath: getDomPath(node),\n classNames: Array.from(node.classList),\n nearbyHeading: getNearbyHeading(node),\n componentName: datasetComponent ?? hints[0]?.componentName,\n frontendFiles: [],\n apiSources: [],\n };\n },\n};\n","import { Bot } from \"lucide-react\";\nimport { useEffect, useMemo, useRef, useState } from \"react\";\n\nimport { OmsAgentPanel } from \"@/features/chat/components/OmsAgentPanel\";\nimport { collectRuntimeContext } from \"@/features/context/services/contextCollector\";\nimport { omsBridge } from \"@/integrations/oms/bridge\";\nimport { cn } from \"@/shared/lib/utils\";\n\ninterface OmsAgentWidgetProps {\n selectedElement: HTMLElement | null;\n inspecting: boolean;\n onStartInspecting: () => void;\n onStopInspecting: () => void;\n onClearSelection: () => void;\n}\n\nconst WIDGET_SIZE = 48;\nconst VIEWPORT_PADDING = 20;\nconst PANEL_GAP = 12;\nconst PANEL_MAX_WIDTH = 392;\nconst PANEL_MAX_HEIGHT = 680;\nconst PANEL_MIN_PADDING = 12;\nconst STORAGE_KEY = \"oms-agent-widget-position\";\n\ninterface WidgetPosition {\n x: number;\n y: number;\n}\n\nfunction getDefaultPosition(): WidgetPosition {\n return {\n x: window.innerWidth - WIDGET_SIZE - VIEWPORT_PADDING,\n y: window.innerHeight - WIDGET_SIZE - VIEWPORT_PADDING,\n };\n}\n\nfunction clampPosition(position: WidgetPosition): WidgetPosition {\n return {\n x: Math.min(\n Math.max(position.x, VIEWPORT_PADDING),\n window.innerWidth - WIDGET_SIZE - VIEWPORT_PADDING,\n ),\n y: Math.min(\n Math.max(position.y, VIEWPORT_PADDING),\n window.innerHeight - WIDGET_SIZE - VIEWPORT_PADDING,\n ),\n };\n}\n\nfunction snapToEdge(position: WidgetPosition): WidgetPosition {\n const snappedX =\n position.x + WIDGET_SIZE / 2 < window.innerWidth / 2\n ? VIEWPORT_PADDING\n : window.innerWidth - WIDGET_SIZE - VIEWPORT_PADDING;\n\n return clampPosition({\n x: snappedX,\n y: position.y,\n });\n}\n\nfunction readStoredPosition() {\n const raw = window.localStorage.getItem(STORAGE_KEY);\n\n if (!raw) {\n return null;\n }\n\n try {\n const parsed = JSON.parse(raw) as Partial<WidgetPosition>;\n\n if (typeof parsed.x !== \"number\" || typeof parsed.y !== \"number\") {\n return null;\n }\n\n return clampPosition({\n x: parsed.x,\n y: parsed.y,\n });\n } catch {\n return null;\n }\n}\n\nexport function OmsAgentWidget({\n selectedElement,\n inspecting,\n onStartInspecting,\n onStopInspecting,\n onClearSelection,\n}: OmsAgentWidgetProps) {\n const [open, setOpen] = useState(true);\n const [viewport, setViewport] = useState(() => ({\n width: window.innerWidth,\n height: window.innerHeight,\n }));\n const [position, setPosition] = useState<WidgetPosition>(() => {\n return readStoredPosition() ?? getDefaultPosition();\n });\n const suppressClickRef = useRef(false);\n const dragStateRef = useRef({\n pointerId: -1,\n startX: 0,\n startY: 0,\n originX: 0,\n originY: 0,\n moved: false,\n });\n const runtimeContext = useMemo(\n () => collectRuntimeContext(omsBridge, selectedElement),\n [selectedElement],\n );\n const panelStyle = useMemo(() => {\n const panelWidth = Math.min(PANEL_MAX_WIDTH, viewport.width - 24);\n const panelHeight = Math.min(Math.round(viewport.height * 0.76), PANEL_MAX_HEIGHT);\n const preferredLeft =\n position.x > viewport.width / 2 ? position.x + WIDGET_SIZE - panelWidth : position.x;\n const maxLeft = Math.max(PANEL_MIN_PADDING, viewport.width - panelWidth - PANEL_MIN_PADDING);\n const maxTop = Math.max(PANEL_MIN_PADDING, viewport.height - panelHeight - PANEL_MIN_PADDING);\n\n return {\n left: Math.min(Math.max(preferredLeft, PANEL_MIN_PADDING), maxLeft),\n top: Math.min(\n Math.max(position.y - panelHeight - PANEL_GAP, PANEL_MIN_PADDING),\n maxTop,\n ),\n };\n }, [position, viewport.height, viewport.width]);\n\n useEffect(() => {\n const onResize = () => {\n setViewport({\n width: window.innerWidth,\n height: window.innerHeight,\n });\n setPosition((current) => {\n const next = clampPosition(current);\n window.localStorage.setItem(STORAGE_KEY, JSON.stringify(next));\n return next;\n });\n };\n\n window.addEventListener(\"resize\", onResize);\n\n return () => window.removeEventListener(\"resize\", onResize);\n }, []);\n\n const persistPosition = (next: WidgetPosition) => {\n window.localStorage.setItem(STORAGE_KEY, JSON.stringify(next));\n };\n\n const closePanel = () => {\n onStopInspecting();\n setOpen(false);\n };\n\n return (\n <div data-oms-agent-root>\n <OmsAgentPanel\n inspecting={inspecting}\n onClearSelection={onClearSelection}\n onClose={closePanel}\n onStartInspecting={onStartInspecting}\n open={open}\n panelStyle={panelStyle}\n runtimeContext={runtimeContext}\n />\n\n <button\n className={cn(\n \"fixed z-50 inline-flex size-12 items-center justify-center rounded-full border border-[#4B8BFF]/45 bg-[linear-gradient(135deg,rgba(22,93,255,0.92),rgba(74,132,255,0.72),rgba(12,25,52,0.98))] text-white shadow-[0_14px_36px_rgba(22,93,255,0.3)] backdrop-blur-xl transition hover:border-[#8AB1FF]/80 hover:shadow-[0_18px_42px_rgba(22,93,255,0.34)]\",\n open && \"ring-1 ring-[#6FA2FF]/45\",\n )}\n aria-label=\"打开 OMS 智能助手\"\n onClick={() => {\n if (suppressClickRef.current) {\n suppressClickRef.current = false;\n return;\n }\n\n setOpen((value) => {\n if (value) {\n onStopInspecting();\n }\n\n return !value;\n });\n }}\n onPointerDown={(event) => {\n dragStateRef.current = {\n pointerId: event.pointerId,\n startX: event.clientX,\n startY: event.clientY,\n originX: position.x,\n originY: position.y,\n moved: false,\n };\n event.currentTarget.setPointerCapture(event.pointerId);\n }}\n onPointerMove={(event) => {\n if (dragStateRef.current.pointerId !== event.pointerId) {\n return;\n }\n\n const deltaX = event.clientX - dragStateRef.current.startX;\n const deltaY = event.clientY - dragStateRef.current.startY;\n const next = clampPosition({\n x: dragStateRef.current.originX + deltaX,\n y: dragStateRef.current.originY + deltaY,\n });\n\n if (Math.abs(deltaX) > 3 || Math.abs(deltaY) > 3) {\n dragStateRef.current.moved = true;\n }\n\n setPosition(next);\n }}\n onPointerUp={(event) => {\n if (dragStateRef.current.pointerId !== event.pointerId) {\n return;\n }\n\n if (dragStateRef.current.moved) {\n const deltaX = event.clientX - dragStateRef.current.startX;\n const deltaY = event.clientY - dragStateRef.current.startY;\n const next = snapToEdge({\n x: dragStateRef.current.originX + deltaX,\n y: dragStateRef.current.originY + deltaY,\n });\n\n suppressClickRef.current = true;\n setPosition(next);\n persistPosition(next);\n }\n\n dragStateRef.current.pointerId = -1;\n event.currentTarget.releasePointerCapture(event.pointerId);\n }}\n onPointerCancel={(event) => {\n if (dragStateRef.current.pointerId !== event.pointerId) {\n return;\n }\n\n dragStateRef.current.pointerId = -1;\n event.currentTarget.releasePointerCapture(event.pointerId);\n }}\n style={{\n left: position.x,\n top: position.y,\n touchAction: \"none\",\n }}\n type=\"button\"\n >\n <Bot className=\"size-4.5\" />\n </button>\n </div>\n );\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\n\nexport interface InspectRect {\n top: number;\n left: number;\n width: number;\n height: number;\n}\n\nfunction toRect(element: HTMLElement): InspectRect {\n const rect = element.getBoundingClientRect();\n\n return {\n top: rect.top + window.scrollY,\n left: rect.left + window.scrollX,\n width: rect.width,\n height: rect.height,\n };\n}\n\nfunction isAgentElement(target: EventTarget | null) {\n return target instanceof HTMLElement && Boolean(target.closest(\"[data-oms-agent-root]\"));\n}\n\nexport function useElementInspector() {\n const [isInspecting, setIsInspecting] = useState(false);\n const [hoveredElement, setHoveredElement] = useState<HTMLElement | null>(null);\n const [selectedElement, setSelectedElement] = useState<HTMLElement | null>(null);\n\n const stopInspecting = useCallback(() => {\n setIsInspecting(false);\n setHoveredElement(null);\n }, []);\n\n useEffect(() => {\n if (!isInspecting) {\n return undefined;\n }\n\n const onMouseMove = (event: MouseEvent) => {\n if (!(event.target instanceof HTMLElement) || isAgentElement(event.target)) {\n return;\n }\n\n setHoveredElement(event.target);\n };\n\n const onClick = (event: MouseEvent) => {\n if (!(event.target instanceof HTMLElement) || isAgentElement(event.target)) {\n return;\n }\n\n event.preventDefault();\n event.stopPropagation();\n setSelectedElement(event.target);\n stopInspecting();\n };\n\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === \"Escape\") {\n stopInspecting();\n }\n };\n\n document.addEventListener(\"mousemove\", onMouseMove, true);\n document.addEventListener(\"click\", onClick, true);\n document.addEventListener(\"keydown\", onKeyDown, true);\n\n return () => {\n document.removeEventListener(\"mousemove\", onMouseMove, true);\n document.removeEventListener(\"click\", onClick, true);\n document.removeEventListener(\"keydown\", onKeyDown, true);\n };\n }, [isInspecting, stopInspecting]);\n\n const hoverRect = useMemo(\n () => (hoveredElement ? toRect(hoveredElement) : null),\n [hoveredElement],\n );\n\n const selectedRect = useMemo(\n () => (selectedElement ? toRect(selectedElement) : null),\n [selectedElement],\n );\n\n return {\n isInspecting,\n hoverRect,\n selectedRect,\n selectedElement,\n startInspecting: () => setIsInspecting(true),\n stopInspecting,\n clearSelection: () => setSelectedElement(null),\n };\n}\n"],"names":["REACT_ELEMENT_TYPE","REACT_FRAGMENT_TYPE","jsxProd","type","config","maybeKey","key","propName","reactJsxRuntime_production","getComponentNameFromType","REACT_CLIENT_REFERENCE","REACT_PROFILER_TYPE","REACT_STRICT_MODE_TYPE","REACT_SUSPENSE_TYPE","REACT_SUSPENSE_LIST_TYPE","REACT_ACTIVITY_TYPE","REACT_PORTAL_TYPE","REACT_CONTEXT_TYPE","REACT_CONSUMER_TYPE","REACT_FORWARD_REF_TYPE","innerType","REACT_MEMO_TYPE","REACT_LAZY_TYPE","testStringCoercion","value","checkKeyStringCoercion","JSCompiler_inline_result","JSCompiler_temp_const","JSCompiler_inline_result$jscomp$0","getTaskName","name","getOwner","dispatcher","ReactSharedInternals","UnknownOwner","hasValidKey","hasOwnProperty","getter","defineKeyPropWarningGetter","props","displayName","warnAboutAccessingKey","specialPropKeyWarningShown","elementRefGetterWithDeprecationWarning","componentName","didWarnAboutElementRef","ReactElement","owner","debugStack","debugTask","refProp","jsxDEVImpl","isStaticChildren","children","isArrayImpl","validateChildKeys","keys","k","didWarnAboutKeySpread","node","isValidElement","object","React","require$$0","createTask","callStackForError","unknownOwnerDebugStack","unknownOwnerDebugTask","reactJsxRuntime_development","trackActualOwner","jsxRuntimeModule","require$$1","mergeClasses","classes","className","index","array","toKebabCase","string","toCamelCase","match","p1","p2","toPascalCase","camelCase","defaultAttributes","hasA11yProp","prop","Icon","forwardRef","color","size","strokeWidth","absoluteStrokeWidth","iconNode","rest","ref","createElement","tag","attrs","createLucideIcon","iconName","Component","__iconNode","Bot","Crosshair","FileCodeCorner","Send","X","r","f","clsx","concatArrays","array1","array2","combinedArray","i","createClassValidatorObject","classGroupId","validator","createClassPartObject","nextPart","validators","CLASS_PART_SEPARATOR","EMPTY_CONFLICTS","ARBITRARY_PROPERTY_PREFIX","createClassGroupUtils","classMap","createClassMap","conflictingClassGroups","conflictingClassGroupModifiers","getGroupIdForArbitraryProperty","classParts","startIndex","getGroupRecursive","hasPostfixModifier","modifierConflicts","baseConflicts","classPartObject","currentClassPart","nextClassPartObject","result","classRest","validatorsLength","validatorObj","content","colonIndex","property","theme","classGroups","processClassGroups","group","processClassesRecursively","classGroup","len","classDefinition","processClassDefinition","processStringDefinition","processFunctionDefinition","processObjectDefinition","classPartObjectToEdit","getPart","isThemeGetter","entries","path","current","parts","part","next","func","createLruCache","maxCacheSize","cacheSize","cache","previousCache","update","IMPORTANT_MODIFIER","MODIFIER_SEPARATOR","EMPTY_MODIFIERS","createResultObject","modifiers","hasImportantModifier","baseClassName","maybePostfixModifierPosition","isExternal","createParseClassName","prefix","experimentalParseClassName","parseClassName","bracketDepth","parenDepth","modifierStart","postfixModifierPosition","currentCharacter","baseClassNameWithImportantModifier","fullPrefix","parseClassNameOriginal","createSortModifiers","modifierWeights","mod","currentSegment","modifier","isArbitrary","isOrderSensitive","createConfigUtils","SPLIT_CLASSES_REGEX","mergeClassList","classList","configUtils","getClassGroupId","getConflictingClassGroupIds","sortModifiers","classGroupsInConflict","classNames","originalClassName","variantModifier","modifierId","classId","conflictGroups","twJoin","classLists","argument","resolvedValue","toValue","mix","createTailwindMerge","createConfigFirst","createConfigRest","cacheGet","cacheSet","functionToCall","initTailwindMerge","previousConfig","createConfigCurrent","tailwindMerge","cachedResult","args","fallbackThemeArr","fromTheme","themeGetter","arbitraryValueRegex","arbitraryVariableRegex","fractionRegex","tshirtUnitRegex","lengthUnitRegex","colorFunctionRegex","shadowRegex","imageRegex","isFraction","isNumber","isInteger","isPercent","isTshirtSize","isAny","isLengthOnly","isNever","isShadow","isImage","isAnyNonArbitrary","isArbitraryValue","isArbitraryVariable","isArbitrarySize","getIsArbitraryValue","isLabelSize","isArbitraryLength","isLabelLength","isArbitraryNumber","isLabelNumber","isArbitraryWeight","isLabelWeight","isArbitraryFamilyName","isLabelFamilyName","isArbitraryPosition","isLabelPosition","isArbitraryImage","isLabelImage","isArbitraryShadow","isLabelShadow","isArbitraryVariableLength","getIsArbitraryVariable","isArbitraryVariableFamilyName","isArbitraryVariablePosition","isArbitraryVariableSize","isArbitraryVariableImage","isArbitraryVariableShadow","isArbitraryVariableWeight","testLabel","testValue","shouldMatchNoLabel","label","getDefaultConfig","themeColor","themeFont","themeText","themeFontWeight","themeTracking","themeLeading","themeBreakpoint","themeContainer","themeSpacing","themeRadius","themeShadow","themeInsetShadow","themeTextShadow","themeDropShadow","themeBlur","themePerspective","themeAspect","themeEase","themeAnimate","scaleBreak","scalePosition","scalePositionWithArbitrary","scaleOverflow","scaleOverscroll","scaleUnambiguousSpacing","scaleInset","scaleGridTemplateColsRows","scaleGridColRowStartAndEnd","scaleGridColRowStartOrEnd","scaleGridAutoColsRows","scaleAlignPrimaryAxis","scaleAlignSecondaryAxis","scaleMargin","scaleSizing","scaleSizingInline","scaleSizingBlock","scaleColor","scaleBgPosition","scaleBgRepeat","scaleBgSize","scaleGradientStopPosition","scaleRadius","scaleBorderWidth","scaleLineStyle","scaleBlendMode","scaleMaskImagePosition","scaleBlur","scaleRotate","scaleScale","scaleSkew","scaleTranslate","twMerge","cn","inputs","sleep","ms","resolve","marker","symbol","_a","_b","AISDKError","_AISDKError","name14","message","cause","error","marker15","markerSymbol","getErrorMessage","name3","marker4","symbol4","_a4","_b4","InvalidArgumentError","name6","marker7","symbol7","_a7","_b7","JSONParseError","text","name12","marker13","symbol13","_a13","_b13","TypeValidationError","_TypeValidationError","context","contextPrefix","_a15","_b15","_c","$constructor","initializer","params","init","inst","def","_","proto","Parent","Definition","fn","$ZodAsyncError","$ZodEncodeError","globalConfig","newConfig","getEnumValues","numericValues","v","jsonStringifyReplacer","cached","nullish","input","cleanRegex","source","start","end","floatSafeRemainder","val","step","valDecCount","stepString","stepDecCount","decCount","valInt","stepInt","EVALUATING","defineLazy","assignProp","target","mergeDefs","defs","mergedDescriptors","descriptors","esc","str","slugify","captureStackTrace","_args","isObject","data","allowsEval","F","isPlainObject","o","ctor","prot","shallowClone","propertyKeyTypes","escapeRegex","clone","cl","normalizeParams","_params","optionalKeys","shape","NUMBER_FORMAT_RANGES","pick","schema","mask","currDef","checks","newShape","omit","extend","existingShape","_shape","safeExtend","merge","a","b","partial","Class","oldShape","required","aborted","x","prefixIssues","issues","iss","unwrapMessage","finalizeIssue","ctx","full","_d","_e","_f","getLengthableOrigin","issue","util.jsonStringifyReplacer","$ZodError","$ZodRealError","flattenError","mapper","fieldErrors","formErrors","sub","formatError","processError","curr","el","_parse","_Err","_ctx","core.$ZodAsyncError","e","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","version","email","_emoji","emoji","ipv4","ipv6","cidrv4","cidrv6","base64","base64url","e164","dateSource","date","timeSource","hhmm","time","datetime","opts","timeRegex","regex","integer","number","boolean","_null","lowercase","uppercase","$ZodCheck","core.$constructor","numericOriginMap","$ZodCheckLessThan","origin","bag","payload","$ZodCheckGreaterThan","$ZodCheckMultipleOf","util.floatSafeRemainder","$ZodCheckNumberFormat","isInt","minimum","maximum","util.NUMBER_FORMAT_RANGES","regexes.integer","$ZodCheckMaxLength","util.nullish","util.getLengthableOrigin","$ZodCheckMinLength","$ZodCheckLengthEquals","length","tooBig","$ZodCheckStringFormat","$ZodCheckRegex","$ZodCheckLowerCase","regexes.lowercase","$ZodCheckUpperCase","regexes.uppercase","$ZodCheckIncludes","escapedRegex","util.escapeRegex","pattern","$ZodCheckStartsWith","$ZodCheckEndsWith","$ZodCheckOverwrite","Doc","arg","lines","minIndent","dedented","line","$ZodType","ch","runChecks","isAborted","util.aborted","asyncResult","currLen","handleCanaryResult","canary","checkResult","util.defineLazy","$ZodString","regexes.string","$ZodStringFormat","checks.$ZodCheckStringFormat","$ZodGUID","regexes.guid","$ZodUUID","regexes.uuid","$ZodEmail","regexes.email","$ZodURL","trimmed","url","$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","address","prefixNum","isValidBase64","$ZodBase64","regexes.base64","isValidBase64URL","regexes.base64url","c","padded","$ZodBase64URL","$ZodE164","regexes.e164","isValidJWT","token","algorithm","tokensParts","header","parsedHeader","$ZodJWT","$ZodNumber","regexes.number","received","$ZodNumberFormat","checks.$ZodCheckNumberFormat","$ZodBoolean","regexes.boolean","$ZodNull","regexes.null","$ZodUnknown","$ZodNever","handleArrayResult","final","util.prefixIssues","$ZodArray","proms","item","handlePropertyResult","isOptionalOut","normalizeDef","okeys","util.optionalKeys","handleCatchall","unrecognized","keySet","_catchall","t","$ZodObject","desc","sh","newSh","_normalized","util.cached","propValues","field","util.isObject","catchall","$ZodObjectJIT","superParse","generateFastpass","doc","normalized","parseStr","util.esc","ids","counter","id","fastpass","jit","core.globalConfig","fastEnabled","util.allowsEval","handleUnionResults","results","nonaborted","$ZodUnion","option","patterns","p","util.cleanRegex","single","first","async","$ZodDiscriminatedUnion","_super","pv","disc","map","values","opt","$ZodIntersection","left","right","handleIntersectionResults","mergeValues","util.isPlainObject","bKeys","sharedKeys","newObj","sharedValue","newArray","itemA","itemB","unrecKeys","unrecIssue","bothKeys","merged","$ZodRecord","recordKeys","keyResult","retryResult","$ZodEnum","util.getEnumValues","valuesSet","util.propertyKeyTypes","$ZodLiteral","$ZodTransform","core.$ZodEncodeError","_out","output","handleOptionalResult","$ZodOptional","$ZodExactOptional","$ZodNullable","$ZodDefault","handleDefaultResult","$ZodPrefault","$ZodNonOptional","handleNonOptionalResult","$ZodCatch","$ZodPipe","handlePipeResult","$ZodReadonly","handleReadonlyResult","$ZodLazy","$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","_number","_int","_boolean","_unknown","_never","_lt","checks.$ZodCheckLessThan","_lte","_gt","checks.$ZodCheckGreaterThan","_gte","_multipleOf","checks.$ZodCheckMultipleOf","_maxLength","checks.$ZodCheckMaxLength","_minLength","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","element","_custom","norm","_refine","_superRefine","_check","_issue","initializeContext","process","seen","overrideSchema","_json","processor","parent","isTransforming","extractDefs","root","idToSchema","entry","existing","makeURI","defsSegment","externalId","uriGenerator","defUriPrefix","defId","extractToDef","ext","finalize","flattenRef","zodSchema","_cached","refSeen","refSchema","parentSeen","finalized","createStandardJSONSchemaMethod","_schema","createToJSONSchemaMethod","processors","io","libraryOptions","formatMap","stringProcessor","json","format","contentEncoding","regexes","numberProcessor","multipleOf","exclusiveMaximum","exclusiveMinimum","booleanProcessor","bigintProcessor","symbolProcessor","nullProcessor","undefinedProcessor","voidProcessor","neverProcessor","anyProcessor","unknownProcessor","dateProcessor","enumProcessor","literalProcessor","vals","nanProcessor","templateLiteralProcessor","fileProcessor","file","mime","m","successProcessor","customProcessor","functionProcessor","transformProcessor","mapProcessor","setProcessor","arrayProcessor","objectProcessor","allKeys","requiredKeys","unionProcessor","isExclusive","options","intersectionProcessor","isSimpleIntersection","allOf","tupleProcessor","prefixPath","restPath","prefixItems","recordProcessor","keyType","keyBag","valueSchema","keyValues","validKeyValues","nullableProcessor","inner","nonoptionalProcessor","defaultProcessor","prefaultProcessor","catchProcessor","catchValue","pipeProcessor","readonlyProcessor","promiseProcessor","optionalProcessor","lazyProcessor","allProcessors","toJSONSchema","schemas","external","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","ZodType","core.$ZodType","util.mergeDefs","core.clone","reg","parse.parse","parse.safeParse","parse.parseAsync","parse.safeParseAsync","parse.encode","parse.decode","parse.encodeAsync","parse.decodeAsync","parse.safeEncode","parse.safeDecode","parse.safeEncodeAsync","parse.safeDecodeAsync","check","refine","refinement","superRefine","checks.overwrite","optional","exactOptional","nullable","nonoptional","union","intersection","pipe","transform","_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","ZodNumber","core.$ZodNumber","processors.numberProcessor","checks.gt","checks.gte","checks.lt","checks.lte","int","checks.multipleOf","core._number","ZodNumberFormat","core.$ZodNumberFormat","core._int","ZodBoolean","core.$ZodBoolean","processors.booleanProcessor","core._boolean","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","minLength","maxLength","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","strictObject","ZodUnion","core.$ZodUnion","processors.unionProcessor","ZodDiscriminatedUnion","core.$ZodDiscriminatedUnion","discriminatedUnion","discriminator","ZodIntersection","core.$ZodIntersection","processors.intersectionProcessor","ZodRecord","core.$ZodRecord","processors.recordProcessor","record","valueType","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_","out","ZodReadonly","core.$ZodReadonly","processors.readonlyProcessor","ZodLazy","core.$ZodLazy","processors.lazyProcessor","lazy","ZodCustom","core.$ZodCustom","processors.customProcessor","custom","core._custom","core._refine","core._superRefine","_instanceof","cls","util","assertIs","_arg","assertNever","_x","items","obj","validKeys","filtered","arr","checker","joinValues","separator","objectUtil","second","ZodError","subs","actualProto","_mapper","firstEl","errorUtil","ZodFirstPartyTypeKind","ParseError","noop","createParser","callbacks","onEvent","onError","onRetry","onComment","incompleteLine","isFirstChunk","eventType","feed","newChunk","chunk","complete","incomplete","splitLines","parseLine","dispatchEvent","fieldSeparatorIndex","offset","processField","reset","searchIndex","crIndex","lfIndex","lineEnd","EventSourceParserStream","parser","controller","event","createIdGenerator","alphabet","generator","alphabetLength","chars","generateId","getRuntimeEnvironmentUserAgent","globalThisAny","_a2","_b2","normalizeHeaders","headers","withUserAgentSuffix","userAgentSuffixParts","normalizedHeaders","currentUserAgentHeader","suspectProtoRx","suspectConstructorRx","filter","nodes","secureJsonParse","stackTraceLimit","addAdditionalPropertiesToJsonSchema","jsonSchema2","properties","visit","definitions","ignoreOverride","defaultOptions","getDefaultOptions","parseAnyDef","parseArrayDef","refs","res","parseDef","parseBigintDef","parseBooleanDef","parseBrandedDef","_def","parseCatchDef","parseDateDef","overrideDateStrategy","strategy","integerDateParser","parseDefaultDef","parseEffectsDef","parseEnumDef","isJsonSchema7AllOfType","parseIntersectionDef","mergedAllOf","nestedSchema","additionalProperties","parseLiteralDef","parsedType","emojiRegex","zodPatterns","parseStringDef","addFormat","addPattern","escapeLiteralCheckValue","escapeNonAlphaNumeric","ALPHA_NUMERIC","stringifyRegExpWithFlags","flags","isEscaped","inCharGroup","inCharRange","parseRecordDef","ZodFirstPartyTypeKind2","parseMapDef","parseNativeEnumDef","actualValues","parsedTypes","parseNeverDef","parseNullDef","primitiveMappings","parseUnionDef","types","types2","acc","uniqueTypes","x2","asAnyOf","anyOf","parseNullableDef","base","parseNumberDef","parseObjectDef","propDef","propOptional","safeIsOptional","parsedDef","decideAdditionalProperties","parseOptionalDef","innerSchema","parsePipelineDef","parsePromiseDef","parseSetDef","parseTupleDef","parseUndefinedDef","parseUnknownDef","parseReadonlyDef","selectParser","typeName","ZodFirstPartyTypeKind3","getRelativePath","pathA","pathB","forceResolution","seenItem","overrideResult","seenSchema","get$ref","newItem","jsonSchemaOrGetter","addMeta","postProcessResult","getRefs","_options","currentPath","name2","zod3ToJsonSchema","schema2","_a3","main","title","combined","schemaSymbol","lazySchema","createSchema","jsonSchema","validate","isSchema","asSchema","standardSchema","standardSchema2","zod3Schema","zodSchema2","useReferences","zod4Schema","z4.toJSONSchema","z4.safeParseAsync","isZod4Schema","validateTypes","safeValidateTypes","TypeValidationError2","actualSchema","safeParseJSON","parseJsonEventStream","stream","__defProp","__export","all","name21","name8","marker8","symbol8","_a8","NoObjectGeneratedError","AISDKError8","text2","response","usage","finishReason","name15","symbol15","UIMessageStreamError","AISDKError16","chunkType","chunkId","VERSION","dataContentSchema","z.union","z.string","z.instanceof","z.custom","_a21","jsonValueSchema","z2.lazy","z2.union","z2.null","z2.string","z2.number","z2.boolean","z2.record","z2.array","providerMetadataSchema","z3.record","z3.string","textPartSchema","z4.object","z4.literal","z4.string","imagePartSchema","z4.union","z4.instanceof","filePartSchema","reasoningPartSchema","toolCallPartSchema","z4.unknown","z4.boolean","outputSchema","z4.discriminatedUnion","z4.array","z4.record","toolResultPartSchema","toolApprovalRequestSchema","toolApprovalResponseSchema","systemModelMessageSchema","z5.object","z5.literal","z5.string","userModelMessageSchema","z5.union","z5.array","assistantModelMessageSchema","toolModelMessageSchema","mergeObjects","overrides","overridesValue","baseValue","isSourceObject","isTargetObject","output_exports","choice","fixJson","stack","lastValidIndex","literalStart","processValueStart","char","swapState","processAfterObjectValue","processAfterArrayValue","partialLiteral","parsePartialJson","jsonText","inputSchema","asSchema2","context2","parseResult","safeParseJSON2","validationResult","safeValidateTypes2","inputElementSchema","elementSchema","$schema","itemSchema","outerValue","rawElements","parsedElements","rawElement","publishedElements","partialOutput","choiceOptions","potentialMatches","choiceOption","uiMessageChunkSchema","z7.union","z7.strictObject","z7.literal","z7.string","z7.boolean","z7.unknown","z7.custom","z7.enum","isDataUIMessageChunk","isStaticToolUIPart","isDynamicToolUIPart","isToolUIPart","getStaticToolName","createStreamingUIMessageState","lastMessage","messageId","processUIMessageStream","messageMetadataSchema","dataPartSchemas","runUpdateMessageJob","onToolCall","onData","state","write","getToolInvocation","toolCallId","toolInvocation","invocation","updateToolPart","_a22","part2","anyOptions","anyPart","updateDynamicToolPart","updateMessageMetadata","metadata","mergedMetadata","textPart","reasoningPart","toolInvocations","partialToolCall","partialArgs","existingPart","partIdx","actualPartIdx","dataChunk","existingUIPart","chunkArg","consumeStream","reader","done","createIdGenerator2","createIdGenerator3","SerialJobExecutor","job","resolve3","reject","createIdGenerator4","convertFileListToFileUIParts","files","dataUrl","readerEvent","HttpChatTransport","api","credentials","body","fetch2","prepareSendMessagesRequest","prepareReconnectToStreamRequest","abortSignal","resolvedBody","resolve2","resolvedHeaders","resolvedCredentials","baseHeaders","preparedRequest","withUserAgentSuffix11","getRuntimeEnvironmentUserAgent3","DefaultChatTransport","parseJsonEventStream2","AbstractChat","generateId2","generateIdFunc2","transport","onFinish","sendAutomaticallyWhen","uiMessage","messageIndex","approved","reason","messages","updatePart","shouldSend","tool2","errorText","status","trigger","resumeStream","reconnect","err","isAbort","isDisconnect","isError","activeResponse","throttle","function_","wait","timeoutId","lastCallTime","arguments_","now","timeSinceLastCall","delayForNextCall","throttleit","__accessCheck","member","msg","__privateGet","__privateAdd","__privateSet","setter","waitMs","throttleFunction","_messages","_status","_error","_messagesCallbacks","_statusCallbacks","_errorCallbacks","_callMessagesCallbacks","_callStatusCallbacks","_callErrorCallbacks","ReactChatState","initialMessages","onChange","throttleWaitMs","callback","newStatus","newError","newMessages","_state","Chat","useChat","resume","callbacksRef","useRef","optionsWithCallbacks","chatRef","subscribeToMessages","useCallback","useSyncExternalStore","setMessages","messagesParam","useEffect","_documentCurrentScript","VITE_BASE","getAgentApiBase","knowledgeSourceTypeSchema","z.enum","runtimePageContextSchema","z.object","z.array","runtimeNodeContextSchema","runtimeContextSchema","codeSearchTaskTypeSchema","codeSearchTaskSchema","z.record","z.unknown","codeSearchHitSchema","z.number","apiCandidateSchema","codeSearchTaskResultSchema","docsSearchModeSchema","docsSearchHitSchema","agentResponseSchema","extractText","MockOmsChatTransport","question","runtimeContext","userMessage","answer","textId","segments","segment","useOmsAgentChat","useMemo","chat","quickPrompts","sourceLabel","sourceType","OmsAgentPanel","open","inspecting","panelStyle","onClose","onStartInspecting","onClearSelection","setInput","useState","sendQuestion","messagesViewportRef","submit","viewport","jsxs","jsx","prompt","FileCode2","collectRuntimeContext","bridge","selectedNode","omsPages","matchNodeHints","page","hint","keyword","compactText","getVisibleTexts","selectors","texts","getDomPath","getNearbyHeading","heading","omsBridge","hints","datasetComponent","WIDGET_SIZE","VIEWPORT_PADDING","PANEL_GAP","PANEL_MAX_WIDTH","PANEL_MAX_HEIGHT","PANEL_MIN_PADDING","STORAGE_KEY","getDefaultPosition","clampPosition","position","snapToEdge","snappedX","readStoredPosition","raw","parsed","OmsAgentWidget","selectedElement","onStopInspecting","setOpen","setViewport","setPosition","suppressClickRef","dragStateRef","panelWidth","panelHeight","preferredLeft","maxLeft","maxTop","onResize","persistPosition","closePanel","deltaX","deltaY","toRect","rect","isAgentElement","useElementInspector","isInspecting","setIsInspecting","hoveredElement","setHoveredElement","setSelectedElement","stopInspecting","onMouseMove","onClick","onKeyDown","hoverRect","selectedRect"],"mappings":";;;;;;;;6CAWA,IAAIA,EAAqB,OAAO,IAAI,4BAA4B,EAC9DC,EAAsB,OAAO,IAAI,gBAAgB,EACnD,SAASC,EAAQC,EAAMC,EAAQC,EAAU,CACvC,IAAIC,EAAM,KAGV,GAFWD,IAAX,SAAwBC,EAAM,GAAKD,GACxBD,EAAO,MAAlB,SAA0BE,EAAM,GAAKF,EAAO,KACxC,QAASA,EAAQ,CACnBC,EAAW,CAAA,EACX,QAASE,KAAYH,EACTG,IAAV,QAAuBF,EAASE,CAAQ,EAAIH,EAAOG,CAAQ,EACjE,MAASF,EAAWD,EAClB,OAAAA,EAASC,EAAS,IACX,CACL,SAAUL,EACV,KAAMG,EACN,IAAKG,EACL,IAAgBF,IAAX,OAAoBA,EAAS,KAClC,MAAOC,EAEX,CACA,OAAAG,GAAA,SAAmBP,EACnBO,GAAA,IAAcN,EACdM,GAAA,KAAeN;;;;;;;;yCCtBE,QAAQ,IAAI,WAA7B,eACG,UAAY,CACX,SAASO,EAAyBN,EAAM,CACtC,GAAYA,GAAR,KAAc,OAAO,KACzB,GAAmB,OAAOA,GAAtB,WACF,OAAOA,EAAK,WAAaO,GACrB,KACAP,EAAK,aAAeA,EAAK,MAAQ,KACvC,GAAiB,OAAOA,GAApB,SAA0B,OAAOA,EACrC,OAAQA,EAAI,CACV,KAAKF,EACH,MAAO,WACT,KAAKU,EACH,MAAO,WACT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