@web-applets/inspector 0.2.5 → 0.2.6

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.
@@ -0,0 +1 @@
1
+ app-root{width:100%;height:100%;display:flex;flex-direction:column}app-root main{flex-grow:1;overflow:auto;display:grid;grid-template-areas:"sidebar viewer history";grid-template-columns:auto 1fr auto}app-header{display:flex;align-items:center;border-bottom:var(--panel-border);padding:var(--space-xs) var(--space-lg);gap:var(--space-xs);flex-shrink:0}app-header h1{font-size:var(--text-lg);line-height:calc(var(--space-unit) * 6);display:flex;flex-shrink:0;margin-inline-end:auto}.center-group{flex-grow:1;display:flex;align-items:center;justify-content:center;margin-left:-70px}url-input{align-self:stretch;max-width:600px;width:100%}url-input input{height:100%;width:100%}.menu-button{display:flex;cursor:pointer;border:none;color:var(--color-text);border-radius:var(--rounded);border:1px solid transparent}.menu-button:hover{background:transparent;color:var(--color-action)}.menu-button.active{opacity:.5}app-viewer{background:var(--color-background);display:flex;overflow:auto;grid-area:viewer}app-viewer .hidden{display:none}app-viewer .container{display:flex;flex-direction:column;background:var(--color-raised);flex-grow:1;overflow:hidden}applet-frame{flex-grow:1}app-viewer .data-view{flex-grow:1;background:var(--color-raised);padding:var(--space-md);margin:0;white-space:pre-wrap;overflow:auto}app-viewer .applet-header{border-bottom:1px solid var(--color-border);padding:var(--space-unit) var(--space-md);display:flex;align-items:center;gap:var(--space-md);background:var(--color-background)}app-viewer .applet-header label{font-size:var(--text-sm)}app-viewer .applet-header .toggle{background:var(--color-neutral-50);border:var(--panel-border);display:flex;padding:1px;border-radius:var(--rounded);gap:var(--space-xxs)}app-viewer .applet-header button{cursor:pointer;border:none;padding:var(--space-xxs) var(--space-xs)}app-viewer .applet-header button[data-selected=true]{border:var(--button-border);background:var(--color-raised)}app-viewer .applet-header button[data-selected=true]:hover{color:var(--text-color)}applet-frame{width:100%;height:100%}app-viewer .applet-icon{width:18px}app-viewer .applet-title{font-weight:600;flex-grow:1}app-sidebar{border-right:var(--panel-border);padding:var(--space-lg);height:100%;grid-area:sidebar;display:flex;transition:width .3s ease}app-sidebar form{width:100%;height:100%;display:flex;gap:var(--space-lg);flex-direction:column}app-sidebar fieldset{display:flex;flex-direction:column;gap:var(--space-md);border:none;padding:0;margin:0;min-width:0}app-sidebar .status-message{display:flex;align-items:center;justify-content:center;flex-grow:1;padding:0;margin:0}app-sidebar select{width:100%}.schema{margin:0;background:var(--color-raised);padding:var(--space-md);font-size:var(--text-sm);border-radius:var(--rounded);border:1px solid var(--color-border);overflow:auto;white-space:pre-wrap}app-sidebar textarea{resize:none}app-sidebar .error-message{padding:var(--space-xs);border-radius:var(--rounded);color:var(--color-negative);border:solid 1px var(--color-negative)}app-sidebar.open{width:350px;transition:opacity .3s ease-in,width .3s ease}app-sidebar.closed{width:0px;padding:0;overflow:hidden;opacity:0}app-prompt form{position:relative}app-prompt input{width:100%}app-prompt .loader{position:absolute;inset-block-start:var(--space-sm);inset-inline-end:var(--space-sm);stroke-dasharray:40 56;stroke-dashoffset:0;animation:spin 1.5s linear infinite,dashOffset 2s ease-in-out infinite;transform-origin:center}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}@keyframes dashOffset{0%{stroke-dashoffset:0}to{stroke-dashoffset:-96}}app-history{border-left:var(--panel-border);padding:var(--space-lg);grid-area:history;display:flex;overflow:hidden;flex-direction:column-reverse;gap:var(--space-md);transition:width .3s ease}app-history .history{flex:1;display:flex;flex-direction:column;gap:var(--space-md);overflow-y:scroll;justify-content:end}app-history .bubble-container{display:flex;font-size:var(--text-base)}app-history .assistant-bubble-container{justify-content:flex-start}app-history .user-bubble-container{justify-content:flex-end}app-history .action-output{justify-content:center;display:flex;gap:var(--space-sm);color:var(--color-neutral-600);flex-direction:column}app-history .action-output span{word-break:break-all;font-family:monospace;font-size:11px}app-history .action-output:only-child{flex-grow:1;align-items:center}app-history .bubble{background-color:var(--color-neutral-0);border-radius:var(--rounded-md);padding:var(--space-sm) var(--space-md);max-width:64ch;text-align:left;word-break:break-word}app-history .user{background-color:var(--color-background);border:1px solid var(--color-border)}app-history .assistant{border:1px solid var(--color-border)}app-history span{white-space:pre-line}app-history.open{width:350px;transition:opacity .3s ease-in,width .3s ease}app-history.closed{width:0px;padding:0;overflow:hidden;opacity:0}settings-dialog dialog{display:none;flex-direction:column;border:1px solid var(--color-border);padding:0;border-radius:var(--rounded);pointer-events:none;width:400px;min-height:200px}settings-dialog dialog[open]{display:flex;pointer-events:auto}settings-dialog .dialog-header,settings-dialog .dialog-content,settings-dialog .dialog-footer{padding-block:var(--space-xs);padding-inline:var(--space-md)}settings-dialog .dialog-header{border-block-end:var(--panel-border);position:relative}settings-dialog .close-dialog-button{display:flex;position:absolute;inset-block-start:var(--space-xs);inset-inline-end:var(--space-sm);padding:0;border:none}settings-dialog .dialog-content{flex-grow:1}settings-dialog .dialog-footer{border-block-start:var(--panel-border);display:flex;flex-direction:row-reverse;gap:var(--space-sm)}settings-dialog .dialog-header h2{font-size:var(--text-md);margin:var(--space-xs) 0}settings-dialog form{display:flex;flex-direction:row;gap:var(--space-xs);padding-block:var(--space-sm)}settings-dialog fieldset{border:none;margin:0;padding:0;display:flex;flex-direction:column;flex-grow:1;gap:var(--space-sm)}settings-dialog input{width:100%}settings-dialog .clear-button{align-self:end}:root{--color-action: oklch(45.2% .313214 264.052);--color-highlight: oklch(93.59% .1528 101.65);--color-neutral-0: oklch(99.39% .002854 264.5422);--color-neutral-50: oklch(96.79% .0029 264.54);--color-neutral-100: oklch(92.17% .0029 264.54);--color-neutral-200: oklch(85.5% .0029 264.54);--color-neutral-300: oklch(77.32% .0044 271.36);--color-neutral-400: oklch(65.8% .0029 264.54);--color-neutral-500: oklch(53.92% .0046 286.24);--color-neutral-600: oklch(45.5% .0029 264.54);--color-neutral-700: oklch(38.2% .0029 264.54);--color-neutral-800: oklch(35.1% .0029 264.54);--color-neutral-900: oklch(32.11% .0029 264.54);--color-neutral-1000: oklch(24.11% .0029 264.54);--color-background: var(--color-neutral-50);--color-border: var(--color-neutral-200);--color-raised: var(--color-neutral-0);--color-text: var(--color-neutral-1000);--color-text-muted: var(--color-neutral-700);--color-text-disabled: var(--color-neutral-500);--color-button-text-hover: var(--color-neutral-0);--text-scale: 1.125;--text-lg: calc(var(--text-md) * var(--text-scale));--text-md: calc(var(--text-base) * var(--text-scale));--text-base: 14px;--text-sm: calc(var(--text-base) / var(--text-scale));--text-xs: calc(var(--text-sm) / var(--text-scale));--space-unit: 4px;--space-xxs: calc(var(--space-unit) * .5);--space-xs: var(--space-unit);--space-sm: calc(var(--space-unit) * 2);--space-md: calc(var(--space-unit) * 3);--space-lg: calc(var(--space-unit) * 4);--space-xl: calc(var(--space-unit) * 6);--space-2xl: calc(var(--space-unit) * 8);--space-3xl: calc(var(--space-unit) * 12);--space-4xl: calc(var(--space-unit) * 16);--rounded-sm: calc(var(--space-unit) / 1.5);--rounded: var(--space-unit);--rounded-md: calc(var(--space-unit) * 1.5);--rounded-lg: calc(var(--space-unit) * 2);--shadow: 0 2px 4px color-mix(in srgb, var(--color-neutral-1000), transparent 90%);--panel-border: 1px solid var(--color-border);--input-border: 1px solid var(--color-border);--button-border: 1px solid var(--color-border);--history-width: 300px}@media (prefers-color-scheme: dark){:root{--color-neutral-0: oklch(24.11% .0029 264.54);--color-neutral-50: oklch(32.11% .0029 264.54);--color-neutral-100: oklch(35.1% .0029 264.54);--color-neutral-200: oklch(38.2% .0029 264.54);--color-neutral-300: oklch(45.5% .0029 264.54);--color-neutral-400: oklch(53.92% .0046 286.24);--color-neutral-500: oklch(65.8% .0029 264.54);--color-neutral-600: oklch(77.32% .0044 271.36);--color-neutral-700: oklch(85.5% .0029 264.54);--color-neutral-800: oklch(92.17% .0029 264.54);--color-neutral-900: oklch(95.79% .0029 264.54);--color-neutral-1000: oklch(99.39% .002854 264.5422);--color-button-text-hover: var(--color-neutral-1000)}}*{box-sizing:border-box}html,body{width:100%;height:100%;padding:0;margin:0}input,button{color:inherit;background-color:inherit}label{font-size:var(--text-sm);font-weight:500}body{font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Open Sans,Helvetica Neue,sans-serif;font-size:var(--text-sm);text-rendering:geometricPrecision;line-height:var(--space-lg);background:var(--color-background);color:var(--color-text)}header{display:flex}h1,h2,h3,h4,h5{padding:0;margin:0}p{margin:0}select{-webkit-appearance:unset;-moz-appearance:unset;appearance:unset;color:var(--color-text);background-image:url("data:image/svg+xml,%3Csvg width='20' height='20' viewBox='0 0 20 20' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M5 7.5L10 12.5L15 7.5' stroke='currentColor' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");background-position:right var(--space-sm) center;background-repeat:no-repeat;cursor:pointer}textarea,input,select{background-color:var(--color-neutral-0);border:var(--input-border);border-radius:var(--rounded);padding:var(--space-sm)}input::placeholder,textarea::placeholder,select::placeholder{color:var(--color-neutral-500)}button,input[type=submit]{border:var(--button-border);border-radius:var(--rounded);cursor:pointer}button:hover,input[type=submit]:hover{background:var(--color-action);color:var(--color-button-text-hover)}.status-message{color:var(--color-neutral-700)}
@@ -0,0 +1,329 @@
1
+ (function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))n(s);new MutationObserver(s=>{for(const a of s)if(a.type==="childList")for(const i of a.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&n(i)}).observe(document,{childList:!0,subtree:!0});function r(s){const a={};return s.integrity&&(a.integrity=s.integrity),s.referrerPolicy&&(a.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?a.credentials="include":s.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function n(s){if(s.ep)return;s.ep=!0;const a=r(s);fetch(s.href,a)}})();/**
2
+ * @license
3
+ * Copyright 2019 Google LLC
4
+ * SPDX-License-Identifier: BSD-3-Clause
5
+ */const Nr=globalThis,ss=Nr.ShadowRoot&&(Nr.ShadyCSS===void 0||Nr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,wa=Symbol(),$s=new WeakMap;let ho=class{constructor(e,r,n){if(this._$cssResult$=!0,n!==wa)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=r}get styleSheet(){let e=this.o;const r=this.t;if(ss&&e===void 0){const n=r!==void 0&&r.length===1;n&&(e=$s.get(r)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&$s.set(r,e))}return e}toString(){return this.cssText}};const fo=t=>new ho(typeof t=="string"?t:t+"",void 0,wa),mo=(t,e)=>{if(ss)t.adoptedStyleSheets=e.map(r=>r instanceof CSSStyleSheet?r:r.styleSheet);else for(const r of e){const n=document.createElement("style"),s=Nr.litNonce;s!==void 0&&n.setAttribute("nonce",s),n.textContent=r.cssText,t.appendChild(n)}},Is=ss?t=>t:t=>t instanceof CSSStyleSheet?(e=>{let r="";for(const n of e.cssRules)r+=n.cssText;return fo(r)})(t):t;/**
6
+ * @license
7
+ * Copyright 2017 Google LLC
8
+ * SPDX-License-Identifier: BSD-3-Clause
9
+ */const{is:go,defineProperty:yo,getOwnPropertyDescriptor:vo,getOwnPropertyNames:_o,getOwnPropertySymbols:bo,getPrototypeOf:wo}=Object,Ve=globalThis,Cs=Ve.trustedTypes,xo=Cs?Cs.emptyScript:"",xn=Ve.reactiveElementPolyfillSupport,Jt=(t,e)=>t,Ur={toAttribute(t,e){switch(e){case Boolean:t=t?xo:null;break;case Object:case Array:t=t==null?t:JSON.stringify(t)}return t},fromAttribute(t,e){let r=t;switch(e){case Boolean:r=t!==null;break;case Number:r=t===null?null:Number(t);break;case Object:case Array:try{r=JSON.parse(t)}catch{r=null}}return r}},as=(t,e)=>!go(t,e),Os={attribute:!0,type:String,converter:Ur,reflect:!1,hasChanged:as};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Ve.litPropertyMetadata??(Ve.litPropertyMetadata=new WeakMap);class yt extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,r=Os){if(r.state&&(r.attribute=!1),this._$Ei(),this.elementProperties.set(e,r),!r.noAccessor){const n=Symbol(),s=this.getPropertyDescriptor(e,n,r);s!==void 0&&yo(this.prototype,e,s)}}static getPropertyDescriptor(e,r,n){const{get:s,set:a}=vo(this.prototype,e)??{get(){return this[r]},set(i){this[r]=i}};return{get(){return s==null?void 0:s.call(this)},set(i){const o=s==null?void 0:s.call(this);a.call(this,i),this.requestUpdate(e,o,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Os}static _$Ei(){if(this.hasOwnProperty(Jt("elementProperties")))return;const e=wo(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Jt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Jt("properties"))){const r=this.properties,n=[..._o(r),...bo(r)];for(const s of n)this.createProperty(s,r[s])}const e=this[Symbol.metadata];if(e!==null){const r=litPropertyMetadata.get(e);if(r!==void 0)for(const[n,s]of r)this.elementProperties.set(n,s)}this._$Eh=new Map;for(const[r,n]of this.elementProperties){const s=this._$Eu(r,n);s!==void 0&&this._$Eh.set(s,r)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const r=[];if(Array.isArray(e)){const n=new Set(e.flat(1/0).reverse());for(const s of n)r.unshift(Is(s))}else e!==void 0&&r.push(Is(e));return r}static _$Eu(e,r){const n=r.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var e;this._$ES=new Promise(r=>this.enableUpdating=r),this._$AL=new Map,this._$E_(),this.requestUpdate(),(e=this.constructor.l)==null||e.forEach(r=>r(this))}addController(e){var r;(this._$EO??(this._$EO=new Set)).add(e),this.renderRoot!==void 0&&this.isConnected&&((r=e.hostConnected)==null||r.call(e))}removeController(e){var r;(r=this._$EO)==null||r.delete(e)}_$E_(){const e=new Map,r=this.constructor.elementProperties;for(const n of r.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return mo(e,this.constructor.elementStyles),e}connectedCallback(){var e;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$EO)==null||e.forEach(r=>{var n;return(n=r.hostConnected)==null?void 0:n.call(r)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$EO)==null||e.forEach(r=>{var n;return(n=r.hostDisconnected)==null?void 0:n.call(r)})}attributeChangedCallback(e,r,n){this._$AK(e,n)}_$EC(e,r){var a;const n=this.constructor.elementProperties.get(e),s=this.constructor._$Eu(e,n);if(s!==void 0&&n.reflect===!0){const i=(((a=n.converter)==null?void 0:a.toAttribute)!==void 0?n.converter:Ur).toAttribute(r,n.type);this._$Em=e,i==null?this.removeAttribute(s):this.setAttribute(s,i),this._$Em=null}}_$AK(e,r){var a;const n=this.constructor,s=n._$Eh.get(e);if(s!==void 0&&this._$Em!==s){const i=n.getPropertyOptions(s),o=typeof i.converter=="function"?{fromAttribute:i.converter}:((a=i.converter)==null?void 0:a.fromAttribute)!==void 0?i.converter:Ur;this._$Em=s,this[s]=o.fromAttribute(r,i.type),this._$Em=null}}requestUpdate(e,r,n){if(e!==void 0){if(n??(n=this.constructor.getPropertyOptions(e)),!(n.hasChanged??as)(this[e],r))return;this.P(e,r,n)}this.isUpdatePending===!1&&(this._$ES=this._$ET())}P(e,r,n){this._$AL.has(e)||this._$AL.set(e,r),n.reflect===!0&&this._$Em!==e&&(this._$Ej??(this._$Ej=new Set)).add(e)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(r){Promise.reject(r)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var n;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[a,i]of this._$Ep)this[a]=i;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[a,i]of s)i.wrapped!==!0||this._$AL.has(a)||this[a]===void 0||this.P(a,this[a],i)}let e=!1;const r=this._$AL;try{e=this.shouldUpdate(r),e?(this.willUpdate(r),(n=this._$EO)==null||n.forEach(s=>{var a;return(a=s.hostUpdate)==null?void 0:a.call(s)}),this.update(r)):this._$EU()}catch(s){throw e=!1,this._$EU(),s}e&&this._$AE(r)}willUpdate(e){}_$AE(e){var r;(r=this._$EO)==null||r.forEach(n=>{var s;return(s=n.hostUpdated)==null?void 0:s.call(n)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Ej&&(this._$Ej=this._$Ej.forEach(r=>this._$EC(r,this[r]))),this._$EU()}updated(e){}firstUpdated(e){}}yt.elementStyles=[],yt.shadowRootOptions={mode:"open"},yt[Jt("elementProperties")]=new Map,yt[Jt("finalized")]=new Map,xn==null||xn({ReactiveElement:yt}),(Ve.reactiveElementVersions??(Ve.reactiveElementVersions=[])).push("2.0.4");/**
10
+ * @license
11
+ * Copyright 2017 Google LLC
12
+ * SPDX-License-Identifier: BSD-3-Clause
13
+ */const Wt=globalThis,Lr=Wt.trustedTypes,Ps=Lr?Lr.createPolicy("lit-html",{createHTML:t=>t}):void 0,xa="$lit$",Me=`lit$${Math.random().toFixed(9).slice(2)}$`,Aa="?"+Me,Ao=`<${Aa}>`,it=document,er=()=>it.createComment(""),tr=t=>t===null||typeof t!="object"&&typeof t!="function",is=Array.isArray,So=t=>is(t)||typeof(t==null?void 0:t[Symbol.iterator])=="function",An=`[
14
+ \f\r]`,Lt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Rs=/-->/g,js=/>/g,Xe=RegExp(`>|${An}(?:([^\\s"'>=/]+)(${An}*=${An}*(?:[^
15
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),Ns=/'/g,Ms=/"/g,Sa=/^(?:script|style|textarea|title)$/i,ko=t=>(e,...r)=>({_$litType$:t,strings:e,values:r}),U=ko(1),Be=Symbol.for("lit-noChange"),F=Symbol.for("lit-nothing"),Ds=new WeakMap,rt=it.createTreeWalker(it,129);function ka(t,e){if(!is(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return Ps!==void 0?Ps.createHTML(e):e}const Eo=(t,e)=>{const r=t.length-1,n=[];let s,a=e===2?"<svg>":e===3?"<math>":"",i=Lt;for(let o=0;o<r;o++){const l=t[o];let c,d,p=-1,g=0;for(;g<l.length&&(i.lastIndex=g,d=i.exec(l),d!==null);)g=i.lastIndex,i===Lt?d[1]==="!--"?i=Rs:d[1]!==void 0?i=js:d[2]!==void 0?(Sa.test(d[2])&&(s=RegExp("</"+d[2],"g")),i=Xe):d[3]!==void 0&&(i=Xe):i===Xe?d[0]===">"?(i=s??Lt,p=-1):d[1]===void 0?p=-2:(p=i.lastIndex-d[2].length,c=d[1],i=d[3]===void 0?Xe:d[3]==='"'?Ms:Ns):i===Ms||i===Ns?i=Xe:i===Rs||i===js?i=Lt:(i=Xe,s=void 0);const w=i===Xe&&t[o+1].startsWith("/>")?" ":"";a+=i===Lt?l+Ao:p>=0?(n.push(c),l.slice(0,p)+xa+l.slice(p)+Me+w):l+Me+(p===-2?o:w)}return[ka(t,a+(t[r]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]};class rr{constructor({strings:e,_$litType$:r},n){let s;this.parts=[];let a=0,i=0;const o=e.length-1,l=this.parts,[c,d]=Eo(e,r);if(this.el=rr.createElement(c,n),rt.currentNode=this.el.content,r===2||r===3){const p=this.el.content.firstChild;p.replaceWith(...p.childNodes)}for(;(s=rt.nextNode())!==null&&l.length<o;){if(s.nodeType===1){if(s.hasAttributes())for(const p of s.getAttributeNames())if(p.endsWith(xa)){const g=d[i++],w=s.getAttribute(p).split(Me),y=/([.?@])?(.*)/.exec(g);l.push({type:1,index:a,name:y[2],strings:w,ctor:y[1]==="."?$o:y[1]==="?"?Io:y[1]==="@"?Co:fn}),s.removeAttribute(p)}else p.startsWith(Me)&&(l.push({type:6,index:a}),s.removeAttribute(p));if(Sa.test(s.tagName)){const p=s.textContent.split(Me),g=p.length-1;if(g>0){s.textContent=Lr?Lr.emptyScript:"";for(let w=0;w<g;w++)s.append(p[w],er()),rt.nextNode(),l.push({type:2,index:++a});s.append(p[g],er())}}}else if(s.nodeType===8)if(s.data===Aa)l.push({type:2,index:a});else{let p=-1;for(;(p=s.data.indexOf(Me,p+1))!==-1;)l.push({type:7,index:a}),p+=Me.length-1}a++}}static createElement(e,r){const n=it.createElement("template");return n.innerHTML=e,n}}function Et(t,e,r=t,n){var i,o;if(e===Be)return e;let s=n!==void 0?(i=r._$Co)==null?void 0:i[n]:r._$Cl;const a=tr(e)?void 0:e._$litDirective$;return(s==null?void 0:s.constructor)!==a&&((o=s==null?void 0:s._$AO)==null||o.call(s,!1),a===void 0?s=void 0:(s=new a(t),s._$AT(t,r,n)),n!==void 0?(r._$Co??(r._$Co=[]))[n]=s:r._$Cl=s),s!==void 0&&(e=Et(t,s._$AS(t,e.values),s,n)),e}class To{constructor(e,r){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=r}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:r},parts:n}=this._$AD,s=((e==null?void 0:e.creationScope)??it).importNode(r,!0);rt.currentNode=s;let a=rt.nextNode(),i=0,o=0,l=n[0];for(;l!==void 0;){if(i===l.index){let c;l.type===2?c=new Tr(a,a.nextSibling,this,e):l.type===1?c=new l.ctor(a,l.name,l.strings,this,e):l.type===6&&(c=new Oo(a,this,e)),this._$AV.push(c),l=n[++o]}i!==(l==null?void 0:l.index)&&(a=rt.nextNode(),i++)}return rt.currentNode=it,s}p(e){let r=0;for(const n of this._$AV)n!==void 0&&(n.strings!==void 0?(n._$AI(e,n,r),r+=n.strings.length-2):n._$AI(e[r])),r++}}class Tr{get _$AU(){var e;return((e=this._$AM)==null?void 0:e._$AU)??this._$Cv}constructor(e,r,n,s){this.type=2,this._$AH=F,this._$AN=void 0,this._$AA=e,this._$AB=r,this._$AM=n,this.options=s,this._$Cv=(s==null?void 0:s.isConnected)??!0}get parentNode(){let e=this._$AA.parentNode;const r=this._$AM;return r!==void 0&&(e==null?void 0:e.nodeType)===11&&(e=r.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,r=this){e=Et(this,e,r),tr(e)?e===F||e==null||e===""?(this._$AH!==F&&this._$AR(),this._$AH=F):e!==this._$AH&&e!==Be&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):So(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==F&&tr(this._$AH)?this._$AA.nextSibling.data=e:this.T(it.createTextNode(e)),this._$AH=e}$(e){var a;const{values:r,_$litType$:n}=e,s=typeof n=="number"?this._$AC(e):(n.el===void 0&&(n.el=rr.createElement(ka(n.h,n.h[0]),this.options)),n);if(((a=this._$AH)==null?void 0:a._$AD)===s)this._$AH.p(r);else{const i=new To(s,this),o=i.u(this.options);i.p(r),this.T(o),this._$AH=i}}_$AC(e){let r=Ds.get(e.strings);return r===void 0&&Ds.set(e.strings,r=new rr(e)),r}k(e){is(this._$AH)||(this._$AH=[],this._$AR());const r=this._$AH;let n,s=0;for(const a of e)s===r.length?r.push(n=new Tr(this.O(er()),this.O(er()),this,this.options)):n=r[s],n._$AI(a),s++;s<r.length&&(this._$AR(n&&n._$AB.nextSibling,s),r.length=s)}_$AR(e=this._$AA.nextSibling,r){var n;for((n=this._$AP)==null?void 0:n.call(this,!1,!0,r);e&&e!==this._$AB;){const s=e.nextSibling;e.remove(),e=s}}setConnected(e){var r;this._$AM===void 0&&(this._$Cv=e,(r=this._$AP)==null||r.call(this,e))}}class fn{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,r,n,s,a){this.type=1,this._$AH=F,this._$AN=void 0,this.element=e,this.name=r,this._$AM=s,this.options=a,n.length>2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=F}_$AI(e,r=this,n,s){const a=this.strings;let i=!1;if(a===void 0)e=Et(this,e,r,0),i=!tr(e)||e!==this._$AH&&e!==Be,i&&(this._$AH=e);else{const o=e;let l,c;for(e=a[0],l=0;l<a.length-1;l++)c=Et(this,o[n+l],r,l),c===Be&&(c=this._$AH[l]),i||(i=!tr(c)||c!==this._$AH[l]),c===F?e=F:e!==F&&(e+=(c??"")+a[l+1]),this._$AH[l]=c}i&&!s&&this.j(e)}j(e){e===F?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class $o extends fn{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===F?void 0:e}}class Io extends fn{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==F)}}class Co extends fn{constructor(e,r,n,s,a){super(e,r,n,s,a),this.type=5}_$AI(e,r=this){if((e=Et(this,e,r,0)??F)===Be)return;const n=this._$AH,s=e===F&&n!==F||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,a=e!==F&&(n===F||s);s&&this.element.removeEventListener(this.name,this,n),a&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){var r;typeof this._$AH=="function"?this._$AH.call(((r=this.options)==null?void 0:r.host)??this.element,e):this._$AH.handleEvent(e)}}let Oo=class{constructor(e,r,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=r,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){Et(this,e)}};const Sn=Wt.litHtmlPolyfillSupport;Sn==null||Sn(rr,Tr),(Wt.litHtmlVersions??(Wt.litHtmlVersions=[])).push("3.2.1");const Po=(t,e,r)=>{const n=(r==null?void 0:r.renderBefore)??e;let s=n._$litPart$;if(s===void 0){const a=(r==null?void 0:r.renderBefore)??null;n._$litPart$=s=new Tr(e.insertBefore(er(),a),a,void 0,r??{})}return s._$AI(t),s};/**
16
+ * @license
17
+ * Copyright 2017 Google LLC
18
+ * SPDX-License-Identifier: BSD-3-Clause
19
+ */let re=class extends yt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var r;const e=super.createRenderRoot();return(r=this.renderOptions).renderBefore??(r.renderBefore=e.firstChild),e}update(e){const r=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=Po(r,this.renderRoot,this.renderOptions)}connectedCallback(){var e;super.connectedCallback(),(e=this._$Do)==null||e.setConnected(!0)}disconnectedCallback(){var e;super.disconnectedCallback(),(e=this._$Do)==null||e.setConnected(!1)}render(){return Be}};var ba;re._$litElement$=!0,re.finalized=!0,(ba=globalThis.litElementHydrateSupport)==null||ba.call(globalThis,{LitElement:re});const kn=globalThis.litElementPolyfillSupport;kn==null||kn({LitElement:re});(globalThis.litElementVersions??(globalThis.litElementVersions=[])).push("4.1.1");/**
20
+ * @license
21
+ * Copyright 2017 Google LLC
22
+ * SPDX-License-Identifier: BSD-3-Clause
23
+ */const we=t=>(e,r)=>{r!==void 0?r.addInitializer(()=>{customElements.define(t,e)}):customElements.define(t,e)};/**
24
+ * @license
25
+ * Copyright 2017 Google LLC
26
+ * SPDX-License-Identifier: BSD-3-Clause
27
+ */const Ro={attribute:!0,type:String,converter:Ur,reflect:!1,hasChanged:as},jo=(t=Ro,e,r)=>{const{kind:n,metadata:s}=r;let a=globalThis.litPropertyMetadata.get(s);if(a===void 0&&globalThis.litPropertyMetadata.set(s,a=new Map),a.set(r.name,t),n==="accessor"){const{name:i}=r;return{set(o){const l=e.get.call(this);e.set.call(this,o),this.requestUpdate(i,l,t)},init(o){return o!==void 0&&this.P(i,void 0,t),o}}}if(n==="setter"){const{name:i}=r;return function(o){const l=this[i];e.call(this,o),this.requestUpdate(i,l,t)}}throw Error("Unsupported decorator location: "+n)};function X(t){return(e,r)=>typeof r=="object"?jo(t,e,r):((n,s,a)=>{const i=s.hasOwnProperty(a);return s.constructor.createProperty(a,i?{...n,wrapped:!0}:n),i?Object.getOwnPropertyDescriptor(s,a):void 0})(t,e,r)}/**
28
+ * @license
29
+ * Copyright 2017 Google LLC
30
+ * SPDX-License-Identifier: BSD-3-Clause
31
+ */function No(t){return X({...t,state:!0,attribute:!1})}let De={appletUrl:"",settings:{},settingsDialogOpen:!1};localStorage.getItem("data")&&(De=JSON.parse(localStorage.getItem("data")));const os=new Set;function Mo(t){De={...De,...t},localStorage.setItem("data",JSON.stringify({appletUrl:De.appletUrl,settings:De.settings})),os.forEach(e=>e(De))}function Do(){return De}function Zo(t){return t(De),os.add(t),()=>Ea(t)}function Ea(t){os.delete(t)}const ae={get:Do,update:Mo,subscribe:Zo,unsubscribe:Ea};var Uo=Object.getOwnPropertyDescriptor,Lo=(t,e,r,n)=>{for(var s=n>1?void 0:n?Uo(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=i(s)||s);return s};let Zs=class extends re{createRenderRoot(){return this}connectedCallback(){super.connectedCallback()}handleKeyDown(e){if(e.key==="Enter"){const r=e.target;r.value&&!r.value.startsWith("http://")&&!r.value.startsWith("https://")&&(r.value=`http://${r.value}`),ae.update({appletUrl:r.value})}}render(){return U`<input
32
+ value=${ae.get().appletUrl}
33
+ type="text"
34
+ placeholder="Enter an applet URL to inspect..."
35
+ @keydown=${this.handleKeyDown.bind(this)}
36
+ />`}};Zs=Lo([we("url-input")],Zs);var Fo=Object.getOwnPropertyDescriptor,Vo=(t,e,r,n)=>{for(var s=n>1?void 0:n?Fo(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=i(s)||s);return s};let Us=class extends re{createRenderRoot(){return this}openDialog(){ae.update({settingsDialogOpen:!0})}render(){return U`
37
+ <button
38
+ aria-label="open settings"
39
+ class="menu-button"
40
+ @click="${this.openDialog}"
41
+ >
42
+ <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
43
+ <path d="M10.0001 16.6667C11.7682 16.6667 13.4639 15.9643 14.7141 14.7141C15.9644 13.4638 16.6667 11.7681 16.6667 10C16.6667 8.23191 15.9644 6.53622 14.7141 5.28598C13.4639 4.03573 11.7682 3.33335 10.0001 3.33335M10.0001 16.6667C8.23197 16.6667 6.53628 15.9643 5.28604 14.7141C4.03579 13.4638 3.33341 11.7681 3.33341 10M10.0001 16.6667V18.3334M10.0001 3.33335C8.23197 3.33335 6.53628 4.03573 5.28604 5.28598C4.03579 6.53622 3.33341 8.23191 3.33341 10M10.0001 3.33335V1.66669M3.33341 10H1.66675M11.6667 10C11.6667 10.442 11.4912 10.866 11.1786 11.1785C10.866 11.4911 10.4421 11.6667 10.0001 11.6667C9.55805 11.6667 9.13413 11.4911 8.82157 11.1785C8.50901 10.866 8.33341 10.442 8.33341 10C8.33341 9.55799 8.50901 9.13407 8.82157 8.82151C9.13413 8.50895 9.55805 8.33335 10.0001 8.33335C10.4421 8.33335 10.866 8.50895 11.1786 8.82151C11.4912 9.13407 11.6667 9.55799 11.6667 10ZM11.6667 10H18.3334M14.1667 17.2166L13.3334 15.775M9.16675 8.55843L5.83341 2.78343M17.2169 14.1667L15.7752 13.3334M2.78328 5.83335L4.22495 6.66669M17.2169 5.83335L15.7752 6.66669M2.78328 14.1667L4.22495 13.3334M14.1667 2.78343L13.3334 4.22509M9.16675 11.4417L5.83341 17.2167" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
44
+ </svg>
45
+ </button>
46
+ `}};Us=Vo([we("settings-button")],Us);/**
47
+ * @license
48
+ * Copyright 2017 Google LLC
49
+ * SPDX-License-Identifier: BSD-3-Clause
50
+ */const ls={ATTRIBUTE:1,CHILD:2},cs=t=>(...e)=>({_$litDirective$:t,values:e});class us{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,r,n){this._$Ct=e,this._$AM=r,this._$Ci=n}_$AS(e,r){return this.update(e,r)}update(e,r){return this.render(...r)}}/**
51
+ * @license
52
+ * Copyright 2017 Google LLC
53
+ * SPDX-License-Identifier: BSD-3-Clause
54
+ */let Fn=class extends us{constructor(e){if(super(e),this.it=F,e.type!==ls.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===F||e==null)return this._t=void 0,this.it=e;if(e===Be)return e;if(typeof e!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(e===this.it)return this._t;this.it=e;const r=[e];return r.raw=r,this._t={_$litType$:this.constructor.resultType,strings:r,values:[]}}};Fn.directiveName="unsafeHTML",Fn.resultType=1;const Bo=cs(Fn);/**
55
+ * @license
56
+ * Copyright 2018 Google LLC
57
+ * SPDX-License-Identifier: BSD-3-Clause
58
+ */const zo=cs(class extends us{constructor(t){var e;if(super(t),t.type!==ls.ATTRIBUTE||t.name!=="class"||((e=t.strings)==null?void 0:e.length)>2)throw Error("`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.")}render(t){return" "+Object.keys(t).filter(e=>t[e]).join(" ")+" "}update(t,[e]){var n,s;if(this.st===void 0){this.st=new Set,t.strings!==void 0&&(this.nt=new Set(t.strings.join(" ").split(/\s/).filter(a=>a!=="")));for(const a in e)e[a]&&!((n=this.nt)!=null&&n.has(a))&&this.st.add(a);return this.render(e)}const r=t.element.classList;for(const a of this.st)a in e||(r.remove(a),this.st.delete(a));for(const a in e){const i=!!e[a];i===this.st.has(a)||(s=this.nt)!=null&&s.has(a)||(i?(r.add(a),this.st.add(a)):(r.remove(a),this.st.delete(a)))}return Be}});var qo=Object.defineProperty,Ho=Object.getOwnPropertyDescriptor,$r=(t,e,r,n)=>{for(var s=n>1?void 0:n?Ho(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=(n?i(e,r,s):i(s))||s);return n&&s&&qo(e,r,s),s};const Jo=`<svg xmlns="http://www.w3.org/2000/svg" width="20" height="24" fill="currentColor" viewBox="0 0 24 24">
59
+ <path fill-rule="evenodd" d="M6 4a3 3 0 0 0-3 3v10a3 3 0 0 0 3 3h12a3 3 0 0 0 3-3V7a3 3 0 0 0-3-3H6ZM5 7a1 1 0 0 1 1-1h3v12H6a1 1 0 0 1-1-1V7Zm6 11h7a1 1 0 0 0 1-1V7a1 1 0 0 0-1-1h-7v12Z" clip-rule="evenodd"/>
60
+ </svg>`;let Tt=class extends re{constructor(){super(...arguments),this.componentName="",this.defaultValue="350px",this.icon=Jo,this.active=!0}createRenderRoot(){return this}toggle(){const t=document.querySelector(this.componentName);if(!t){console.error("Element to toggle not found.");return}t.classList.contains("open")?(t.classList.remove("open"),t.classList.add("closed"),this.active=!1):(t.classList.remove("closed"),t.classList.add("open"),this.active=!0)}render(){return U`
61
+ <button
62
+ class=${zo({"menu-button":!0,active:this.active})}
63
+ @click=${this.toggle}
64
+ >
65
+ ${Bo(this.icon)}
66
+ </button>
67
+ `}};$r([X({type:String})],Tt.prototype,"componentName",2);$r([X({type:String})],Tt.prototype,"defaultValue",2);$r([X({type:String})],Tt.prototype,"icon",2);$r([X({type:Boolean})],Tt.prototype,"active",2);Tt=$r([we("toggle-css-variable-button")],Tt);var Wo=Object.getOwnPropertyDescriptor,Go=(t,e,r,n)=>{for(var s=n>1?void 0:n?Wo(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=i(s)||s);return s};let Ls=class extends re{createRenderRoot(){return this}render(){return U`
68
+ <toggle-css-variable-button componentName="app-sidebar">
69
+ </toggle-css-variable-button>
70
+ <h1>Applet Inspector</h1>
71
+ <div class="center-group">
72
+ <url-input></url-input>
73
+ <settings-button></settings-button>
74
+ </div>
75
+ <toggle-css-variable-button
76
+ componentName="app-history"
77
+ icon='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="24" fill="currentColor" viewBox="0 0 24 24">
78
+ <path fill-rule="evenodd" d="M6 4a3 3 0 0 0-3 3v10a3 3 0 0 0 3 3h12a3 3 0 0 0 3-3V7a3 3 0 0 0-3-3H6ZM5 7a1 1 0 0 1 1-1h7v12H6a1 1 0 0 1-1-1V7Zm10 11h3a1 1 0 0 0 1-1V7a1 1 0 0 0-1-1h-3v12Z" clip-rule="evenodd"/>
79
+ </svg>'
80
+ >
81
+ </toggle-css-variable-button>
82
+ `}};Ls=Go([we("app-header")],Ls);const Fs=10*1e3,Vs=10*1e3;class Bs extends Error{constructor(e){super(e),this.name="AppletExecutionError"}}class Yo extends Error{constructor(e){super(e),this.name="AppletConnectionError"}}function ds(t){typeof this[`on${t.type}`]=="function"&&this[`on${t.type}`](t),this.dispatchEvent(t)}function Ko(t){return Object.keys(t).length===0}class nt extends Event{constructor(e,r){super(e,{bubbles:r==null?void 0:r.bubbles,composed:r==null?void 0:r.composed,cancelable:r==null?void 0:r.cancelable}),this.data=r==null?void 0:r.data,this.actions=r==null?void 0:r.actions}}function Xo(t,...e){}const Ta={log:Xo};var pe=function(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r},Z=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Pe,_t,Gt,Fr,xt,tt,Se,Yt,Vr,Br,Vn,zs,En,Tn;class Qo extends EventTarget{constructor(e){super(),Pe.add(this),_t.set(this,void 0),Gt.set(this,{}),Fr.set(this,void 0),xt.set(this,void 0),tt.set(this,void 0),Se.set(this,void 0),Yt.set(this,void 0),Vr.set(this,void 0),Br.set(this,void 0),pe(this,_t,e,"f"),pe(this,tt,ds.bind(this),"f"),Z(this,Pe,"m",Vn).call(this);const r=n=>{n.source===Z(this,_t,"f")&&"type"in n.data&&n.data.type==="appletconnect"&&(Ta.log("Applet","Recieved message",n.data),Z(this,Pe,"m",Vn).call(this),this.removeEventListener("message",r))};window.addEventListener("message",r)}async sendAction(e,r){const n={id:crypto.randomUUID(),type:"action",actionId:e,arguments:r};return new Promise((s,a)=>{Z(this,Yt,"f").call(this,n);const i=setTimeout(()=>{a(new Bs(`Applet action handler failed to complete before timeout (${Fs}ms)`))},Fs),o=l=>{const c=l.data;if(["actioncomplete","actionerror"].includes(c.type)&&"id"in c&&c.id===n.id)if(Z(this,Se,"f").removeEventListener("message",o),clearTimeout(i),c.type==="actionerror"){const d=c;a(new Bs(d.message))}else s()};Z(this,Se,"f").addEventListener("message",o)})}get data(){return Z(this,xt,"f")}set data(e){pe(this,xt,e,"f");const r={type:"data",data:e};Z(this,Yt,"f").call(this,r)}get window(){return Z(this,_t,"f")}get manifest(){return Z(this,Fr,"f")}get actions(){return Z(this,Gt,"f")}get width(){return Z(this,Vr,"f")}get height(){return Z(this,Br,"f")}}_t=new WeakMap,Gt=new WeakMap,Fr=new WeakMap,xt=new WeakMap,tt=new WeakMap,Se=new WeakMap,Yt=new WeakMap,Vr=new WeakMap,Br=new WeakMap,Pe=new WeakSet,Vn=function(){Z(this,Se,"f")&&Z(this,Se,"f").close();const e=new MessageChannel,r={type:"appletconnect"};pe(this,Se,e.port1,"f"),Z(this,Se,"f").onmessage=Z(this,Pe,"m",zs).bind(this),Z(this,_t,"f").postMessage(r,"*",[e.port2]),pe(this,Yt,Z(this,Se,"f").postMessage.bind(Z(this,Se,"f")),"f")},zs=function(e){const r=e.data;switch(r.type){case"register":const n=r;pe(this,Fr,n.manifest,"f");const s=new nt("connect");Z(this,tt,"f").call(this,s),pe(this,Gt,n.actions,"f"),Z(this,Pe,"m",Tn).call(this,n.actions),pe(this,xt,n.data,"f"),Z(this,Pe,"m",En).call(this,n.data);break;case"data":const a=r;pe(this,xt,a.data,"f"),Z(this,Pe,"m",En).call(this,a.data);break;case"resize":const i=r;pe(this,Vr,i.width,"f"),pe(this,Br,i.height,"f");const o=new nt("resize");Z(this,tt,"f").call(this,o);break;case"actions":const l=r;pe(this,Gt,l.actions,"f"),Z(this,Pe,"m",Tn).call(this,l.actions);break}},En=function(e){const r=new nt("data",{data:e});Z(this,tt,"f").call(this,r)},Tn=function(e){const r=new nt("actions",{actions:e});Z(this,tt,"f").call(this,r)};var Ee=function(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r},j=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Ze,Ue,At,Fe,Kt,bt,ge,zr,qr,$a,Ia,qs,Hs,Js,Ws;class el extends EventTarget{constructor(e){super(),Ze.add(this),Ue.set(this,{}),At.set(this,void 0),Fe.set(this,void 0),Kt.set(this,void 0),bt.set(this,void 0),ge.set(this,void 0),zr.set(this,void 0),qr.set(this,void 0),Ee(this,bt,ds.bind(this),"f"),e&&Ee(this,At,e,"f");const r=s=>{if(s.source===window.parent&&s.data.type==="appletconnect"&&s.ports&&s.ports.length>0){Ta.log("AppletScope","Recieved message",s.data);const a=s.ports[0];Ee(this,ge,a.postMessage.bind(a),"f"),a.onmessage=j(this,Ze,"m",Ia).bind(this),this.removeEventListener("message",r),j(this,Ze,"m",$a).call(this)}};window.addEventListener("message",r);const n={type:"appletconnect"};window.parent.postMessage(n,"*")}setActionHandler(e,r){j(this,Ue,"f")[e]=r}defineAction(e,r){const{handler:n,...s}=r;n&&(j(this,Ue,"f")[e]=n),this.actions={...this.actions,[e]:s}}set actions(e){if(!e)return;Ee(this,Fe,e,"f");const r={type:"actions",actions:j(this,Fe,"f")};j(this,ge,"f")&&j(this,ge,"f").call(this,r);const n=new nt("actions",{actions:e});setTimeout(()=>j(this,bt,"f").call(this,n),1)}get actions(){return j(this,Fe,"f")}get manifest(){return j(this,At,"f")}get actionHandlers(){return j(this,Ue,"f")}set actionHandlers(e){Ee(this,Ue,e,"f")}set data(e){Ee(this,Kt,e,"f");const r={type:"data",data:e};j(this,ge,"f")&&j(this,ge,"f").call(this,r);const n=new nt("data",{data:e});setTimeout(()=>j(this,bt,"f").call(this,n),1)}get data(){return j(this,Kt,"f")}get width(){return j(this,zr,"f")}get height(){return j(this,qr,"f")}}Ue=new WeakMap,At=new WeakMap,Fe=new WeakMap,Kt=new WeakMap,bt=new WeakMap,ge=new WeakMap,zr=new WeakMap,qr=new WeakMap,Ze=new WeakSet,$a=async function(){const e=this.manifest??await j(this,Ze,"m",Ws).call(this);Ee(this,At,e||{},"f"),Ee(this,Fe,j(this,Fe,"f")||(e==null?void 0:e.actions)||{},"f");const r={type:"register",manifest:j(this,At,"f"),actions:j(this,Fe,"f"),data:j(this,Kt,"f")};j(this,ge,"f").call(this,r);const n=new nt("connect");j(this,bt,"f").call(this,n),j(this,Ze,"m",Hs).call(this)},Ia=function(e){const r=e.data;switch(r.type){case"data":"data"in r&&(this.data=r.data);break;case"action":"type"in r&&r.type==="action"&&"id"in r&&typeof r.id=="string"&&"actionId"in r&&typeof r.actionId=="string"&&"arguments"in r&&j(this,Ze,"m",qs).call(this,r);break}},qs=async function(e){const{actionId:r,arguments:n,id:s}=e;if(Object.keys(j(this,Ue,"f")).includes(r))try{await j(this,Ue,"f")[r](n);const a={type:"actioncomplete",id:s};j(this,ge,"f").call(this,a)}catch(a){const i={type:"actionerror",id:s,message:a.message};j(this,ge,"f").call(this,i),console.error(a)}},Hs=function(){new ResizeObserver(r=>{for(let n of r)j(this,Ze,"m",Js).call(this,{width:n.contentRect.width,height:n.contentRect.height})}).observe(document.querySelector("html"))},Js=function({width:e,height:r}){Ee(this,zr,e,"f"),Ee(this,qr,r,"f");const n={type:"resize",width:e,height:r};j(this,ge,"f").call(this,n)},Ws=async function(){const e=document.querySelector('link[rel="manifest"]');if(!e){console.warn("No manifest link found");return}try{const n=await(await fetch(e.href)).json();for(const s in n.actions){const a=n.actions[s];a.params_schema&&Ko(a.params_schema)&&(a.params_schema=void 0)}return n}catch(r){console.warn("Failed to fetch manifest",r.message)}};class tl{async connect(e){return new Promise((r,n)=>{const s=new Qo(e),a=setTimeout(()=>{n(new Yo(`Applet failed to connect before the timeout was reached (${Vs}ms)`))},Vs),i=()=>{r(s),s.removeEventListener("connect",i),clearTimeout(a)};s.addEventListener("connect",i)})}register(e){return new el(e)}}const rl=new tl;var Mr=function(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r},W=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Hr,Bt,Dr,ke,zt,St,Ca,Gs;class Oa extends HTMLElement{constructor(){super(...arguments),Hr.add(this),Bt.set(this,void 0),Dr.set(this,void 0),ke.set(this,void 0),zt.set(this,ds.bind(this)),St.set(this,document.createElement("iframe"))}connectedCallback(){Mr(this,Bt,this.attachShadow({mode:"closed"}),"f"),W(this,Bt,"f").appendChild(W(this,St,"f"));const e=document.createElement("style");e.textContent=this.styles,W(this,Bt,"f").appendChild(e),this.src=this.getAttribute("src")}get contentWindow(){return W(this,St,"f").contentWindow}set src(e){Mr(this,Dr,e,"f"),Mr(this,ke,void 0,"f"),W(this,Hr,"m",Ca).call(this,e)}get src(){return W(this,Dr,"f")||""}attributeChangedCallback(e,r,n){e==="src"&&(this.src=n)}get applet(){return W(this,ke,"f")}set data(e){if(this.applet)this.applet.data=e;else{const r=()=>{this.applet&&(this.applet.data=e),this.removeEventListener("load",r)};this.addEventListener("load",r)}}get styles(){return`
83
+ :host {
84
+ background: white;
85
+ display: flex;
86
+ flex-direction: column;
87
+ height: 350px;
88
+ }
89
+
90
+ iframe {
91
+ border: none;
92
+ height: 100%;
93
+ width: 100%;
94
+ }
95
+ `}}Bt=new WeakMap,Dr=new WeakMap,ke=new WeakMap,zt=new WeakMap,St=new WeakMap,Hr=new WeakSet,Ca=async function(e){W(this,St,"f").src=e;const r=W(this,St,"f").contentWindow;r&&(Mr(this,ke,await rl.connect(r),"f"),W(this,ke,"f").ondata=n=>{W(this,zt,"f").call(this,n)},W(this,ke,"f").onresize=n=>{W(this,Hr,"m",Gs).call(this,{width:W(this,ke,"f").width,height:W(this,ke,"f").height})},W(this,ke,"f").onactions=n=>{W(this,zt,"f").call(this,n)},W(this,zt,"f").call(this,new Event("load")),this.load&&typeof this.load=="function"&&this.onload(new Event("load")))},Gs=function(e){this.style.height=`${e.height}px`};Oa.observedAttributes=["src"];customElements.define("applet-frame",Oa);var nl=Object.defineProperty,sl=Object.getOwnPropertyDescriptor,mn=(t,e,r,n)=>{for(var s=n>1?void 0:n?sl(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=(n?i(e,r,s):i(s))||s);return n&&s&&nl(e,r,s),s};let nr=class extends re{constructor(){super(...arguments),this.renderRoot=this,this.appletUrl="",this.mode="gui",this.data={}}connectedCallback(){ae.subscribe(t=>{this.appletUrl=t.appletUrl,t.applet&&(this.data=t.applet.data,t.applet.ondata=()=>this.data=t.applet.data)}),super.connectedCallback()}updated(){const t=document.querySelector("applet-frame");t&&(t.onload=()=>{ae.update({applet:t.applet}),window.applet=t.applet,window.applet.ondata=e=>this.data=e.data})}render(){var e,r,n,s,a;const t=U`<div class="applet-header">
96
+ ${(r=(e=window.applet)==null?void 0:e.manifest)!=null&&r.icons?U`<img
97
+ src="${this.appletUrl}/${(s=(n=window.applet)==null?void 0:n.manifest.icons[0])==null?void 0:s.src}"
98
+ class="applet-icon"
99
+ />`:""}
100
+ <div class="applet-title">${(a=window.applet)==null?void 0:a.manifest.name}</div>
101
+ <div class="toggle">
102
+ <button
103
+ data-selected=${this.mode==="gui"}
104
+ @mousedown=${()=>this.mode="gui"}
105
+ >
106
+ GUI
107
+ </button>
108
+ <button
109
+ data-selected=${this.mode==="data"}
110
+ @mousedown=${()=>this.mode="data"}
111
+ >
112
+ Data
113
+ </button>
114
+ </div>
115
+ </div>`;return U`
116
+ <div class="container">
117
+ ${t}
118
+ <applet-frame
119
+ src=${this.appletUrl}
120
+ class=${this.mode==="gui"?"":"hidden"}
121
+ ></applet-frame>
122
+ <pre class=${this.mode==="gui"?"hidden":"data-view"}>
123
+ ${JSON.stringify(this.data,null,2)}</pre
124
+ >
125
+ </div>
126
+ `}};mn([X()],nr.prototype,"appletUrl",2);mn([X()],nr.prototype,"mode",2);mn([X({attribute:!1})],nr.prototype,"data",2);nr=mn([we("app-viewer")],nr);function Pa(t){return Object.keys(t).length===0}class al{constructor(){this.interactions=[],this.subscribers=new Set}addInteraction(e){this.interactions.push(e),this.notify()}getAllInteractions(){return[...this.interactions]}getRecentInteractions(e=10){return this.interactions.slice(-e)}clearHistory(){this.interactions=[],this.notify()}subscribe(e){return this.subscribers.add(e),e([...this.interactions]),()=>{this.subscribers.delete(e)}}notify(){for(const e of this.subscribers)e([...this.interactions])}}const Jr=new al;var il=Object.defineProperty,ol=Object.getOwnPropertyDescriptor,dt=(t,e,r,n)=>{for(var s=n>1?void 0:n?ol(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=(n?i(e,r,s):i(s))||s);return n&&s&&il(e,r,s),s};let sr=class extends re{constructor(){super(...arguments),this.renderRoot=this,this.selected=0,this.actions={},this.schemaError=""}connectedCallback(){ae.subscribe(t=>{t.applet&&(this.actions=t.applet.actions,t.applet.onactions=e=>this.actions=e.actions)}),super.connectedCallback()}handleSelect(t){const e=t.target;this.selected=e.selectedIndex}handleSchemaChange(t){const e=t.target,r=e.value.trim();if(!r){this.schemaError="",e.setCustomValidity("");return}try{const n=JSON.parse(r),s=JSON.stringify(n,null,2);e.value=s,this.schemaError="",e.setCustomValidity("")}catch(n){this.schemaError=n.message,e.setCustomValidity("Invalid JSON")}}handleSchemaFocus(t){t.target.setCustomValidity("")}async handleSubmit(t){t.preventDefault();const e=t.target,r=new FormData(e),n=r.get("action-id"),s=r.get("params");await window.applet.sendAction(n,JSON.parse(s)),Jr.addInteraction({input:{type:"action",text:n},outputs:[{type:n,...JSON.parse(s)},{type:"data",content:window.applet.data}],timestamp:Date.now()})}render(){if(!this.actions||Pa(this.actions))return U`<p class="status-message">No actions available.</p>`;const t=Object.values(this.actions)[this.selected],e=JSON.stringify(t==null?void 0:t.params_schema,null,2)??"None";return U`
127
+ <form @submit=${this.handleSubmit.bind(this)}>
128
+ <fieldset class="select">
129
+ <label>Select an action</label>
130
+ <action-select
131
+ .actions=${this.actions}
132
+ name="action-id"
133
+ @change=${this.handleSelect.bind(this)}
134
+ ></action-select>
135
+ </fieldset>
136
+ <fieldset>
137
+ <label>Description</label>
138
+ <p class="description">${t==null?void 0:t.description}</p>
139
+ </fieldset>
140
+ <fieldset>
141
+ <label>Schema</label>
142
+ <pre class="schema">${e}</pre>
143
+ </fieldset>
144
+ <fieldset>
145
+ <label>Parameters</label>
146
+ <textarea
147
+ rows=${6}
148
+ name="params"
149
+ @focus=${this.handleSchemaFocus}
150
+ @change=${this.handleSchemaChange.bind(this)}
151
+ >
152
+ {}</textarea
153
+ >
154
+ ${this.schemaError?U`<div class="error-message">${this.schemaError}</div>`:""}
155
+ </fieldset>
156
+ <fieldset>
157
+ <input type="submit" value="Dispatch action" />
158
+ </fieldset>
159
+ </form>
160
+ `}};dt([X({type:Number})],sr.prototype,"selected",2);dt([X({attribute:!1})],sr.prototype,"actions",2);dt([X({type:String})],sr.prototype,"schemaError",2);sr=dt([we("app-sidebar")],sr);let Wr=class extends re{constructor(){super(...arguments),this.renderRoot=this}render(){return U`
161
+ <select name=${this.name}>
162
+ ${Object.keys(this.actions).map(t=>U`<option id="action">${t}</option>`)}
163
+ </select>
164
+ `}};dt([X({type:String})],Wr.prototype,"name",2);dt([X({attribute:!1})],Wr.prototype,"actions",2);Wr=dt([we("action-select")],Wr);var Ra="vercel.ai.error",ll=Symbol.for(Ra),ja,cl=class Na extends Error{constructor({name:e,message:r,cause:n}){super(r),this[ja]=!0,this.name=e,this.cause=n}static isInstance(e){return Na.hasMarker(e,Ra)}static hasMarker(e,r){const n=Symbol.for(r);return e!=null&&typeof e=="object"&&n in e&&typeof e[n]=="boolean"&&e[n]===!0}};ja=ll;var O=cl,Ma="AI_APICallError",Da=`vercel.ai.error.${Ma}`,ul=Symbol.for(Da),Za,Te=class extends O{constructor({message:t,url:e,requestBodyValues:r,statusCode:n,responseHeaders:s,responseBody:a,cause:i,isRetryable:o=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:Ma,message:t,cause:i}),this[Za]=!0,this.url=e,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=s,this.responseBody=a,this.isRetryable=o,this.data=l}static isInstance(t){return O.hasMarker(t,Da)}};Za=ul;var Ua="AI_EmptyResponseBodyError",La=`vercel.ai.error.${Ua}`,dl=Symbol.for(La),Fa,pl=class extends O{constructor({message:t="Empty response body"}={}){super({name:Ua,message:t}),this[Fa]=!0}static isInstance(t){return O.hasMarker(t,La)}};Fa=dl;function Va(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var Ba="AI_InvalidArgumentError",za=`vercel.ai.error.${Ba}`,hl=Symbol.for(za),qa,fl=class extends O{constructor({message:e,cause:r,argument:n}){super({name:Ba,message:e,cause:r}),this[qa]=!0,this.argument=n}static isInstance(e){return O.hasMarker(e,za)}};qa=hl;var Ha="AI_InvalidPromptError",Ja=`vercel.ai.error.${Ha}`,ml=Symbol.for(Ja),Wa,et=class extends O{constructor({prompt:t,message:e,cause:r}){super({name:Ha,message:`Invalid prompt: ${e}`,cause:r}),this[Wa]=!0,this.prompt=t}static isInstance(t){return O.hasMarker(t,Ja)}};Wa=ml;var Ga="AI_InvalidResponseDataError",Ya=`vercel.ai.error.${Ga}`,gl=Symbol.for(Ya),Ka,$n=class extends O{constructor({data:t,message:e=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:Ga,message:e}),this[Ka]=!0,this.data=t}static isInstance(t){return O.hasMarker(t,Ya)}};Ka=gl;var Xa="AI_JSONParseError",Qa=`vercel.ai.error.${Xa}`,yl=Symbol.for(Qa),ei,ar=class extends O{constructor({text:t,cause:e}){super({name:Xa,message:`JSON parsing failed: Text: ${t}.
165
+ Error message: ${Va(e)}`,cause:e}),this[ei]=!0,this.text=t}static isInstance(t){return O.hasMarker(t,Qa)}};ei=yl;var ti="AI_LoadAPIKeyError",ri=`vercel.ai.error.${ti}`,vl=Symbol.for(ri),ni,Pr=class extends O{constructor({message:t}){super({name:ti,message:t}),this[ni]=!0}static isInstance(t){return O.hasMarker(t,ri)}};ni=vl;var si="AI_TooManyEmbeddingValuesForCallError",ai=`vercel.ai.error.${si}`,_l=Symbol.for(ai),ii,bl=class extends O{constructor(t){super({name:si,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[ii]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return O.hasMarker(t,ai)}};ii=_l;var oi="AI_TypeValidationError",li=`vercel.ai.error.${oi}`,wl=Symbol.for(li),ci,xl=class Bn extends O{constructor({value:e,cause:r}){super({name:oi,message:`Type validation failed: Value: ${JSON.stringify(e)}.
166
+ Error message: ${Va(r)}`,cause:r}),this[ci]=!0,this.value=e}static isInstance(e){return O.hasMarker(e,li)}static wrap({value:e,cause:r}){return Bn.isInstance(r)&&r.value===e?r:new Bn({value:e,cause:r})}};ci=wl;var je=xl,ui="AI_UnsupportedFunctionalityError",di=`vercel.ai.error.${ui}`,Al=Symbol.for(di),pi,G=class extends O{constructor({functionality:t,message:e=`'${t}' functionality not supported.`}){super({name:ui,message:e}),this[pi]=!0,this.functionality=t}static isInstance(t){return O.hasMarker(t,di)}};pi=Al;function Gr(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"?!0:Array.isArray(t)?t.every(Gr):typeof t=="object"?Object.entries(t).every(([e,r])=>typeof e=="string"&&Gr(r)):!1}function Ys(t){return Array.isArray(t)&&t.every(Gr)}function zn(t){return t!=null&&typeof t=="object"&&Object.entries(t).every(([e,r])=>typeof e=="string"&&Gr(r))}let Sl=(t,e=21)=>(r=e)=>{let n="",s=r|0;for(;s--;)n+=t[Math.random()*t.length|0];return n};function kl(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Qe={exports:{}},Ks;function El(){if(Ks)return Qe.exports;Ks=1;const t=typeof Buffer<"u",e=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,r=/"(?: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*:/;function n(o,l,c){c==null&&l!==null&&typeof l=="object"&&(c=l,l=void 0),t&&Buffer.isBuffer(o)&&(o=o.toString()),o&&o.charCodeAt(0)===65279&&(o=o.slice(1));const d=JSON.parse(o,l);if(d===null||typeof d!="object")return d;const p=c&&c.protoAction||"error",g=c&&c.constructorAction||"error";if(p==="ignore"&&g==="ignore")return d;if(p!=="ignore"&&g!=="ignore"){if(e.test(o)===!1&&r.test(o)===!1)return d}else if(p!=="ignore"&&g==="ignore"){if(e.test(o)===!1)return d}else if(r.test(o)===!1)return d;return s(d,{protoAction:p,constructorAction:g,safe:c&&c.safe})}function s(o,{protoAction:l="error",constructorAction:c="error",safe:d}={}){let p=[o];for(;p.length;){const g=p;p=[];for(const w of g){if(l!=="ignore"&&Object.prototype.hasOwnProperty.call(w,"__proto__")){if(d===!0)return null;if(l==="error")throw new SyntaxError("Object contains forbidden prototype property");delete w.__proto__}if(c!=="ignore"&&Object.prototype.hasOwnProperty.call(w,"constructor")&&Object.prototype.hasOwnProperty.call(w.constructor,"prototype")){if(d===!0)return null;if(c==="error")throw new SyntaxError("Object contains forbidden prototype property");delete w.constructor}for(const y in w){const m=w[y];m&&typeof m=="object"&&p.push(m)}}}return o}function a(o,l,c){const d=Error.stackTraceLimit;Error.stackTraceLimit=0;try{return n(o,l,c)}finally{Error.stackTraceLimit=d}}function i(o,l){const c=Error.stackTraceLimit;Error.stackTraceLimit=0;try{return n(o,l,{safe:!0})}catch{return null}finally{Error.stackTraceLimit=c}}return Qe.exports=a,Qe.exports.default=a,Qe.exports.parse=a,Qe.exports.safeParse=i,Qe.exports.scan=s,Qe.exports}var Tl=El();const ps=kl(Tl);var $l=Object.defineProperty,Il=(t,e,r)=>e in t?$l(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rr=(t,e,r)=>Il(t,typeof e!="symbol"?e+"":e,r);class Xs extends Error{constructor(e,r){super(e),Rr(this,"type"),Rr(this,"field"),Rr(this,"value"),Rr(this,"line"),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function In(t){}function Cl(t){const{onEvent:e=In,onError:r=In,onRetry:n=In,onComment:s}=t;let a="",i=!0,o,l="",c="";function d(m){const v=i?m.replace(/^\xEF\xBB\xBF/,""):m,[A,k]=Ol(`${a}${v}`);for(const T of A)p(T);a=k,i=!1}function p(m){if(m===""){w();return}if(m.startsWith(":")){s&&s(m.slice(m.startsWith(": ")?2:1));return}const v=m.indexOf(":");if(v!==-1){const A=m.slice(0,v),k=m[v+1]===" "?2:1,T=m.slice(v+k);g(A,T,m);return}g(m,"",m)}function g(m,v,A){switch(m){case"event":c=v;break;case"data":l=`${l}${v}
167
+ `;break;case"id":o=v.includes("\0")?void 0:v;break;case"retry":/^\d+$/.test(v)?n(parseInt(v,10)):r(new Xs(`Invalid \`retry\` value: "${v}"`,{type:"invalid-retry",value:v,line:A}));break;default:r(new Xs(`Unknown field "${m.length>20?`${m.slice(0,20)}…`:m}"`,{type:"unknown-field",field:m,value:v,line:A}));break}}function w(){l.length>0&&e({id:o,event:c||void 0,data:l.endsWith(`
168
+ `)?l.slice(0,-1):l}),o=void 0,l="",c=""}function y(m={}){a&&m.consume&&p(a),o=void 0,l="",c="",a=""}return{feed:d,reset:y}}function Ol(t){const e=[];let r="";const n=t.length;for(let s=0;s<n;s++){const a=t[s];a==="\r"&&t[s+1]===`
169
+ `?(e.push(r),r="",s++):a==="\r"||a===`
170
+ `?(e.push(r),r=""):r+=a}return[e,r]}class Pl extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let s;super({start(a){s=Cl({onEvent:i=>{a.enqueue(i)},onError(i){e==="terminate"?a.error(i):typeof e=="function"&&e(i)},onRetry:r,onComment:n})},transform(a){s.feed(a)}})}}var Rl={};function $t(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}function jl(t){return new ReadableStream({async pull(e){try{const{value:r,done:n}=await t.next();n?e.close():e.enqueue(r)}catch(r){e.error(r)}},cancel(){}})}async function Nl(t){return t==null?Promise.resolve():new Promise(e=>setTimeout(e,t))}function gn(t){const e={};return t.headers.forEach((r,n)=>{e[n]=r}),e}var pt=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const s=Sl(r,e);if(t==null)return s;if(r.includes(n))throw new fl({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return a=>`${t}${n}${s(a)}`},Ft=pt();function Ml(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}function Dl(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>r!=null))}function Zr(t){return t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")}function Zl({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:n}){if(typeof t=="string")return t;if(t!=null)throw new Pr({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Pr({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=Rl[e],t==null)throw new Pr({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new Pr({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}var Yr=Symbol.for("vercel.ai.validator");function Ul(t){return{[Yr]:!0,validate:t}}function Ll(t){return typeof t=="object"&&t!==null&&Yr in t&&t[Yr]===!0&&"validate"in t}function Fl(t){return Ll(t)?t:Vl(t)}function Vl(t){return Ul(e=>{const r=t.safeParse(e);return r.success?{success:!0,value:r.data}:{success:!1,error:r.error}})}function Bl({value:t,schema:e}){const r=ot({value:t,schema:e});if(!r.success)throw je.wrap({value:t,cause:r.error});return r.value}function ot({value:t,schema:e}){const r=Fl(e);try{if(r.validate==null)return{success:!0,value:t};const n=r.validate(t);return n.success?n:{success:!1,error:je.wrap({value:t,cause:n.error})}}catch(n){return{success:!1,error:je.wrap({value:t,cause:n})}}}function zl({text:t,schema:e}){try{const r=ps.parse(t);return e==null?r:Bl({value:r,schema:e})}catch(r){throw ar.isInstance(r)||je.isInstance(r)?r:new ar({text:t,cause:r})}}function It({text:t,schema:e}){try{const r=ps.parse(t);if(e==null)return{success:!0,value:r,rawValue:r};const n=ot({value:r,schema:e});return n.success?{...n,rawValue:r}:n}catch(r){return{success:!1,error:ar.isInstance(r)?r:new ar({text:t,cause:r})}}}function Qs(t){try{return ps.parse(t),!0}catch{return!1}}var ql=()=>globalThis.fetch,Ct=async({url:t,headers:e,body:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:a,fetch:i})=>Hl({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:a,fetch:i}),Hl=async({url:t,headers:e={},body:r,successfulResponseHandler:n,failedResponseHandler:s,abortSignal:a,fetch:i=ql()})=>{try{const o=await i(t,{method:"POST",headers:Dl(e),body:r.content,signal:a}),l=gn(o);if(!o.ok){let c;try{c=await s({response:o,url:t,requestBodyValues:r.values})}catch(d){throw Zr(d)||Te.isInstance(d)?d:new Te({message:"Failed to process error response",cause:d,statusCode:o.status,url:t,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:o,url:t,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Zr(c)||Te.isInstance(c))?c:new Te({message:"Failed to process successful response",cause:c,statusCode:o.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(o){if(Zr(o))throw o;if(o instanceof TypeError&&o.message==="fetch failed"){const l=o.cause;if(l!=null)throw new Te({message:`Cannot connect to API: ${l.message}`,cause:l,url:t,requestBodyValues:r.values,isRetryable:!0})}throw o}},Jl=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:n,url:s,requestBodyValues:a})=>{const i=await n.text(),o=gn(n);if(i.trim()==="")return{responseHeaders:o,value:new Te({message:n.statusText,url:s,requestBodyValues:a,statusCode:n.status,responseHeaders:o,responseBody:i,isRetryable:r==null?void 0:r(n)})};try{const l=zl({text:i,schema:t});return{responseHeaders:o,value:new Te({message:e(l),url:s,requestBodyValues:a,statusCode:n.status,responseHeaders:o,responseBody:i,data:l,isRetryable:r==null?void 0:r(n,l)})}}catch{return{responseHeaders:o,value:new Te({message:n.statusText,url:s,requestBodyValues:a,statusCode:n.status,responseHeaders:o,responseBody:i,isRetryable:r==null?void 0:r(n)})}}},hi=t=>async({response:e})=>{const r=gn(e);if(e.body==null)throw new pl({});return{responseHeaders:r,value:e.body.pipeThrough(new TextDecoderStream).pipeThrough(new Pl).pipeThrough(new TransformStream({transform({data:n},s){n!=="[DONE]"&&s.enqueue(It({text:n,schema:t}))}}))}},yn=t=>async({response:e,url:r,requestBodyValues:n})=>{const s=await e.text(),a=It({text:s,schema:t}),i=gn(e);if(!a.success)throw new Te({message:"Invalid JSON response",cause:a.error,statusCode:e.status,responseHeaders:i,responseBody:s,url:r,requestBodyValues:n});return{responseHeaders:i,value:a.value,rawValue:a.rawValue}},{btoa:Wl,atob:Gl}=globalThis;function Yl(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=Gl(e);return Uint8Array.from(r,n=>n.codePointAt(0))}function qn(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return Wl(e)}function Kl(t){return t==null?void 0:t.replace(/\/$/,"")}var C;(function(t){t.assertEqual=s=>s;function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{const a={};for(const i of s)a[i]=i;return a},t.getValidEnumValues=s=>{const a=t.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(const o of a)i[o]=s[o];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(a){return s[a]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const a=[];for(const i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},t.find=(s,a)=>{for(const i of s)if(a(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function n(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}t.joinValues=n,t.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(C||(C={}));var Hn;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Hn||(Hn={}));const b=C.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Re=t=>{switch(typeof t){case"undefined":return b.undefined;case"string":return b.string;case"number":return isNaN(t)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":return Array.isArray(t)?b.array:t===null?b.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?b.promise:typeof Map<"u"&&t instanceof Map?b.map:typeof Set<"u"&&t instanceof Set?b.set:typeof Date<"u"&&t instanceof Date?b.date:b.object;default:return b.unknown}},h=C.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Xl=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class le extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(a){return a.message},n={_errors:[]},s=a=>{for(const i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let o=n,l=0;for(;l<i.path.length;){const c=i.path[l];l===i.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(r(i))):o[c]=o[c]||{_errors:[]},o=o[c],l++}}};return s(this),n}static assert(e){if(!(e instanceof le))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,C.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const s of this.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}le.create=t=>new le(t);const Ot=(t,e)=>{let r;switch(t.code){case h.invalid_type:t.received===b.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case h.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,C.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:r=`Unrecognized key(s) in object: ${C.joinValues(t.keys,", ")}`;break;case h.invalid_union:r="Invalid input";break;case h.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${C.joinValues(t.options)}`;break;case h.invalid_enum_value:r=`Invalid enum value. Expected ${C.joinValues(t.options)}, received '${t.received}'`;break;case h.invalid_arguments:r="Invalid function arguments";break;case h.invalid_return_type:r="Invalid function return type";break;case h.invalid_date:r="Invalid date";break;case h.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:C.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case h.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case h.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case h.custom:r="Invalid input";break;case h.invalid_intersection_types:r="Intersection results could not be merged";break;case h.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case h.not_finite:r="Number must be finite";break;default:r=e.defaultError,C.assertNever(t)}return{message:r}};let fi=Ot;function Ql(t){fi=t}function Kr(){return fi}const Xr=t=>{const{data:e,path:r,errorMaps:n,issueData:s}=t,a=[...r,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)o=c(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}},ec=[];function _(t,e){const r=Kr(),n=Xr({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ot?void 0:Ot].filter(s=>!!s)});t.common.issues.push(n)}class ee{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const s of r){if(s.status==="aborted")return S;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const s of r){const a=await s.key,i=await s.value;n.push({key:a,value:i})}return ee.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const s of r){const{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return S;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[a.value]=i.value)}return{status:e.value,value:n}}}const S=Object.freeze({status:"aborted"}),wt=t=>({status:"dirty",value:t}),ne=t=>({status:"valid",value:t}),Jn=t=>t.status==="aborted",Wn=t=>t.status==="dirty",lt=t=>t.status==="valid",ir=t=>typeof Promise<"u"&&t instanceof Promise;function Qr(t,e,r,n){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(t)}function mi(t,e,r,n,s){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,r),r}var x;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(x||(x={}));var qt,Ht;class $e{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const ea=(t,e)=>{if(lt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new le(t.common.issues);return this._error=r,this._error}}};function E(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,o)=>{var l,c;const{message:d}=t;return i.code==="invalid_enum_value"?{message:d??o.defaultError}:typeof o.data>"u"?{message:(l=d??n)!==null&&l!==void 0?l:o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:(c=d??r)!==null&&c!==void 0?c:o.defaultError}},description:s}}class ${get description(){return this._def.description}_getType(e){return Re(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Re(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ee,ctx:{common:e.parent.common,data:e.data,parsedType:Re(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(ir(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){var n;const s={common:{issues:[],async:(n=r==null?void 0:r.async)!==null&&n!==void 0?n:!1,contextualErrorMap:r==null?void 0:r.errorMap},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Re(e)},a=this._parseSync({data:e,path:s.path,parent:s});return ea(s,a)}"~validate"(e){var r,n;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Re(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:s});return lt(a)?{value:a.value}:{issues:s.common.issues}}catch(a){!((n=(r=a==null?void 0:a.message)===null||r===void 0?void 0:r.toLowerCase())===null||n===void 0)&&n.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:s}).then(a=>lt(a)?{value:a.value}:{issues:s.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r==null?void 0:r.errorMap,async:!0},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Re(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(ir(s)?s:Promise.resolve(s));return ea(n,a)}refine(e,r){const n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,a)=>{const i=e(s),o=()=>a.addIssue({code:h.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new be({schema:this,typeName:f.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return _e.create(this,this._def)}nullable(){return Je.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ve.create(this)}promise(){return Rt.create(this,this._def)}or(e){return ur.create([this,e],this._def)}and(e){return dr.create(this,e,this._def)}transform(e){return new be({...E(this._def),schema:this,typeName:f.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new gr({...E(this._def),innerType:this,defaultValue:r,typeName:f.ZodDefault})}brand(){return new hs({typeName:f.ZodBranded,type:this,...E(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new yr({...E(this._def),innerType:this,catchValue:r,typeName:f.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Ir.create(this,e)}readonly(){return vr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const tc=/^c[^\s-]{8,}$/i,rc=/^[0-9a-z]+$/,nc=/^[0-9A-HJKMNP-TV-Z]{26}$/i,sc=/^[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,ac=/^[a-z0-9_-]{21}$/i,ic=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,oc=/^[-+]?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)?)??$/,lc=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,cc="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Cn;const uc=/^(?:(?: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])$/,dc=/^(?:(?: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])$/,pc=/^(([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]))$/,hc=/^(([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])$/,fc=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,mc=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,gi="((\\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])))",gc=new RegExp(`^${gi}$`);function yi(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function yc(t){return new RegExp(`^${yi(t)}$`)}function vi(t){let e=`${gi}T${yi(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function vc(t,e){return!!((e==="v4"||!e)&&uc.test(t)||(e==="v6"||!e)&&pc.test(t))}function _c(t,e){if(!ic.test(t))return!1;try{const[r]=t.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||!s.typ||!s.alg||e&&s.alg!==e)}catch{return!1}}function bc(t,e){return!!((e==="v4"||!e)&&dc.test(t)||(e==="v6"||!e)&&hc.test(t))}class ye extends ${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==b.string){const a=this._getOrReturnCtx(e);return _(a,{code:h.invalid_type,expected:b.string,received:a.parsedType}),S}const n=new ee;let s;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),_(s,{code:h.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),_(s,{code:h.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){const i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(s=this._getOrReturnCtx(e,s),i?_(s,{code:h.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&_(s,{code:h.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")lc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"email",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")Cn||(Cn=new RegExp(cc,"u")),Cn.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"emoji",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")sc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"uuid",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")ac.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"nanoid",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")tc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"cuid",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")rc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"cuid2",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")nc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"ulid",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),_(s,{validation:"url",code:h.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"regex",code:h.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?vi(a).test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?gc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?yc(a).test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?oc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"duration",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?vc(e.data,a.version)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"ip",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?_c(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"jwt",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?bc(e.data,a.version)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"cidr",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?fc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"base64",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?mc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"base64url",code:h.invalid_string,message:a.message}),n.dirty()):C.assertNever(a);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:h.invalid_string,...x.errToObj(n)})}_addCheck(e){return new ye({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...x.errToObj(e)})}url(e){return this._addCheck({kind:"url",...x.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...x.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...x.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...x.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...x.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...x.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...x.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...x.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...x.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...x.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...x.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...x.errToObj(e)})}datetime(e){var r,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(r=e==null?void 0:e.offset)!==null&&r!==void 0?r:!1,local:(n=e==null?void 0:e.local)!==null&&n!==void 0?n:!1,...x.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...x.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...x.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...x.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r==null?void 0:r.position,...x.errToObj(r==null?void 0:r.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...x.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...x.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...x.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...x.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...x.errToObj(r)})}nonempty(e){return this.min(1,x.errToObj(e))}trim(){return new ye({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ye({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ye({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}ye.create=t=>{var e;return new ye({checks:[],typeName:f.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...E(t)})};function wc(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,a=parseInt(t.toFixed(s).replace(".","")),i=parseInt(e.toFixed(s).replace(".",""));return a%i/Math.pow(10,s)}class ze extends ${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==b.number){const a=this._getOrReturnCtx(e);return _(a,{code:h.invalid_type,expected:b.number,received:a.parsedType}),S}let n;const s=new ee;for(const a of this._def.checks)a.kind==="int"?C.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{code:h.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),_(n,{code:h.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),_(n,{code:h.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?wc(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),_(n,{code:h.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{code:h.not_finite,message:a.message}),s.dirty()):C.assertNever(a);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,x.toString(r))}gt(e,r){return this.setLimit("min",e,!1,x.toString(r))}lte(e,r){return this.setLimit("max",e,!0,x.toString(r))}lt(e,r){return this.setLimit("max",e,!1,x.toString(r))}setLimit(e,r,n,s){return new ze({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:x.toString(s)}]})}_addCheck(e){return new ze({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:x.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:x.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:x.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:x.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:x.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:x.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:x.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:x.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:x.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&C.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}}ze.create=t=>new ze({checks:[],typeName:f.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...E(t)});class qe extends ${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==b.bigint)return this._getInvalidInput(e);let n;const s=new ee;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),_(n,{code:h.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),_(n,{code:h.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),_(n,{code:h.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):C.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return _(r,{code:h.invalid_type,expected:b.bigint,received:r.parsedType}),S}gte(e,r){return this.setLimit("min",e,!0,x.toString(r))}gt(e,r){return this.setLimit("min",e,!1,x.toString(r))}lte(e,r){return this.setLimit("max",e,!0,x.toString(r))}lt(e,r){return this.setLimit("max",e,!1,x.toString(r))}setLimit(e,r,n,s){return new qe({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:x.toString(s)}]})}_addCheck(e){return new qe({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:x.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:x.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:x.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:x.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:x.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}qe.create=t=>{var e;return new qe({checks:[],typeName:f.ZodBigInt,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...E(t)})};class or extends ${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==b.boolean){const n=this._getOrReturnCtx(e);return _(n,{code:h.invalid_type,expected:b.boolean,received:n.parsedType}),S}return ne(e.data)}}or.create=t=>new or({typeName:f.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...E(t)});class ct extends ${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==b.date){const a=this._getOrReturnCtx(e);return _(a,{code:h.invalid_type,expected:b.date,received:a.parsedType}),S}if(isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return _(a,{code:h.invalid_date}),S}const n=new ee;let s;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),_(s,{code:h.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),_(s,{code:h.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):C.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ct({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:x.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:x.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}ct.create=t=>new ct({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:f.ZodDate,...E(t)});class en extends ${_parse(e){if(this._getType(e)!==b.symbol){const n=this._getOrReturnCtx(e);return _(n,{code:h.invalid_type,expected:b.symbol,received:n.parsedType}),S}return ne(e.data)}}en.create=t=>new en({typeName:f.ZodSymbol,...E(t)});class lr extends ${_parse(e){if(this._getType(e)!==b.undefined){const n=this._getOrReturnCtx(e);return _(n,{code:h.invalid_type,expected:b.undefined,received:n.parsedType}),S}return ne(e.data)}}lr.create=t=>new lr({typeName:f.ZodUndefined,...E(t)});class cr extends ${_parse(e){if(this._getType(e)!==b.null){const n=this._getOrReturnCtx(e);return _(n,{code:h.invalid_type,expected:b.null,received:n.parsedType}),S}return ne(e.data)}}cr.create=t=>new cr({typeName:f.ZodNull,...E(t)});class Pt extends ${constructor(){super(...arguments),this._any=!0}_parse(e){return ne(e.data)}}Pt.create=t=>new Pt({typeName:f.ZodAny,...E(t)});class at extends ${constructor(){super(...arguments),this._unknown=!0}_parse(e){return ne(e.data)}}at.create=t=>new at({typeName:f.ZodUnknown,...E(t)});class Ne extends ${_parse(e){const r=this._getOrReturnCtx(e);return _(r,{code:h.invalid_type,expected:b.never,received:r.parsedType}),S}}Ne.create=t=>new Ne({typeName:f.ZodNever,...E(t)});class tn extends ${_parse(e){if(this._getType(e)!==b.undefined){const n=this._getOrReturnCtx(e);return _(n,{code:h.invalid_type,expected:b.void,received:n.parsedType}),S}return ne(e.data)}}tn.create=t=>new tn({typeName:f.ZodVoid,...E(t)});class ve extends ${_parse(e){const{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==b.array)return _(r,{code:h.invalid_type,expected:b.array,received:r.parsedType}),S;if(s.exactLength!==null){const i=r.data.length>s.exactLength.value,o=r.data.length<s.exactLength.value;(i||o)&&(_(r,{code:i?h.too_big:h.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(_(r,{code:h.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(_(r,{code:h.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,o)=>s.type._parseAsync(new $e(r,i,r.path,o)))).then(i=>ee.mergeArray(n,i));const a=[...r.data].map((i,o)=>s.type._parseSync(new $e(r,i,r.path,o)));return ee.mergeArray(n,a)}get element(){return this._def.type}min(e,r){return new ve({...this._def,minLength:{value:e,message:x.toString(r)}})}max(e,r){return new ve({...this._def,maxLength:{value:e,message:x.toString(r)}})}length(e,r){return new ve({...this._def,exactLength:{value:e,message:x.toString(r)}})}nonempty(e){return this.min(1,e)}}ve.create=(t,e)=>new ve({type:t,minLength:null,maxLength:null,exactLength:null,typeName:f.ZodArray,...E(e)});function vt(t){if(t instanceof B){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=_e.create(vt(n))}return new B({...t._def,shape:()=>e})}else return t instanceof ve?new ve({...t._def,type:vt(t.element)}):t instanceof _e?_e.create(vt(t.unwrap())):t instanceof Je?Je.create(vt(t.unwrap())):t instanceof Ie?Ie.create(t.items.map(e=>vt(e))):t}class B extends ${constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=C.objectKeys(e);return this._cached={shape:e,keys:r}}_parse(e){if(this._getType(e)!==b.object){const c=this._getOrReturnCtx(e);return _(c,{code:h.invalid_type,expected:b.object,received:c.parsedType}),S}const{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof Ne&&this._def.unknownKeys==="strip"))for(const c in s.data)i.includes(c)||o.push(c);const l=[];for(const c of i){const d=a[c],p=s.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new $e(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Ne){const c=this._def.unknownKeys;if(c==="passthrough")for(const d of o)l.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(c==="strict")o.length>0&&(_(s,{code:h.unrecognized_keys,keys:o}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const d of o){const p=s.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new $e(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const c=[];for(const d of l){const p=await d.key,g=await d.value;c.push({key:p,value:g,alwaysSet:d.alwaysSet})}return c}).then(c=>ee.mergeObjectSync(n,c)):ee.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return x.errToObj,new B({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{var s,a,i,o;const l=(i=(a=(s=this._def).errorMap)===null||a===void 0?void 0:a.call(s,r,n).message)!==null&&i!==void 0?i:n.defaultError;return r.code==="unrecognized_keys"?{message:(o=x.errToObj(e).message)!==null&&o!==void 0?o:l}:{message:l}}}:{}})}strip(){return new B({...this._def,unknownKeys:"strip"})}passthrough(){return new B({...this._def,unknownKeys:"passthrough"})}extend(e){return new B({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new B({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:f.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new B({...this._def,catchall:e})}pick(e){const r={};return C.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(r[n]=this.shape[n])}),new B({...this._def,shape:()=>r})}omit(e){const r={};return C.objectKeys(this.shape).forEach(n=>{e[n]||(r[n]=this.shape[n])}),new B({...this._def,shape:()=>r})}deepPartial(){return vt(this)}partial(e){const r={};return C.objectKeys(this.shape).forEach(n=>{const s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}),new B({...this._def,shape:()=>r})}required(e){const r={};return C.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof _e;)a=a._def.innerType;r[n]=a}}),new B({...this._def,shape:()=>r})}keyof(){return _i(C.objectKeys(this.shape))}}B.create=(t,e)=>new B({shape:()=>t,unknownKeys:"strip",catchall:Ne.create(),typeName:f.ZodObject,...E(e)});B.strictCreate=(t,e)=>new B({shape:()=>t,unknownKeys:"strict",catchall:Ne.create(),typeName:f.ZodObject,...E(e)});B.lazycreate=(t,e)=>new B({shape:t,unknownKeys:"strip",catchall:Ne.create(),typeName:f.ZodObject,...E(e)});class ur extends ${_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function s(a){for(const o of a)if(o.result.status==="valid")return o.result;for(const o of a)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(o=>new le(o.ctx.common.issues));return _(r,{code:h.invalid_union,unionErrors:i}),S}if(r.common.async)return Promise.all(n.map(async a=>{const i={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let a;const i=[];for(const l of n){const c={...r,common:{...r.common,issues:[]},parent:null},d=l._parseSync({data:r.data,path:r.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!a&&(a={result:d,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(l=>new le(l));return _(r,{code:h.invalid_union,unionErrors:o}),S}}get options(){return this._def.options}}ur.create=(t,e)=>new ur({options:t,typeName:f.ZodUnion,...E(e)});const Oe=t=>t instanceof hr?Oe(t.schema):t instanceof be?Oe(t.innerType()):t instanceof fr?[t.value]:t instanceof He?t.options:t instanceof mr?C.objectValues(t.enum):t instanceof gr?Oe(t._def.innerType):t instanceof lr?[void 0]:t instanceof cr?[null]:t instanceof _e?[void 0,...Oe(t.unwrap())]:t instanceof Je?[null,...Oe(t.unwrap())]:t instanceof hs||t instanceof vr?Oe(t.unwrap()):t instanceof yr?Oe(t._def.innerType):[];class vn extends ${_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==b.object)return _(r,{code:h.invalid_type,expected:b.object,received:r.parsedType}),S;const n=this.discriminator,s=r.data[n],a=this.optionsMap.get(s);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(_(r,{code:h.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),S)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){const s=new Map;for(const a of r){const i=Oe(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of i){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,a)}}return new vn({typeName:f.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...E(n)})}}function Gn(t,e){const r=Re(t),n=Re(e);if(t===e)return{valid:!0,data:t};if(r===b.object&&n===b.object){const s=C.objectKeys(e),a=C.objectKeys(t).filter(o=>s.indexOf(o)!==-1),i={...t,...e};for(const o of a){const l=Gn(t[o],e[o]);if(!l.valid)return{valid:!1};i[o]=l.data}return{valid:!0,data:i}}else if(r===b.array&&n===b.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let a=0;a<t.length;a++){const i=t[a],o=e[a],l=Gn(i,o);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return r===b.date&&n===b.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class dr extends ${_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=(a,i)=>{if(Jn(a)||Jn(i))return S;const o=Gn(a.value,i.value);return o.valid?((Wn(a)||Wn(i))&&r.dirty(),{status:r.value,value:o.data}):(_(n,{code:h.invalid_intersection_types}),S)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,i])=>s(a,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}dr.create=(t,e,r)=>new dr({left:t,right:e,typeName:f.ZodIntersection,...E(r)});class Ie extends ${_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.array)return _(n,{code:h.invalid_type,expected:b.array,received:n.parsedType}),S;if(n.data.length<this._def.items.length)return _(n,{code:h.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;!this._def.rest&&n.data.length>this._def.items.length&&(_(n,{code:h.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const a=[...n.data].map((i,o)=>{const l=this._def.items[o]||this._def.rest;return l?l._parse(new $e(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>ee.mergeArray(r,i)):ee.mergeArray(r,a)}get items(){return this._def.items}rest(e){return new Ie({...this._def,rest:e})}}Ie.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ie({items:t,typeName:f.ZodTuple,rest:null,...E(e)})};class pr extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.object)return _(n,{code:h.invalid_type,expected:b.object,received:n.parsedType}),S;const s=[],a=this._def.keyType,i=this._def.valueType;for(const o in n.data)s.push({key:a._parse(new $e(n,o,n.path,o)),value:i._parse(new $e(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?ee.mergeObjectAsync(r,s):ee.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof $?new pr({keyType:e,valueType:r,typeName:f.ZodRecord,...E(n)}):new pr({keyType:ye.create(),valueType:e,typeName:f.ZodRecord,...E(r)})}}class rn extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.map)return _(n,{code:h.invalid_type,expected:b.map,received:n.parsedType}),S;const s=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([o,l],c)=>({key:s._parse(new $e(n,o,n.path,[c,"key"])),value:a._parse(new $e(n,l,n.path,[c,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const l of i){const c=await l.key,d=await l.value;if(c.status==="aborted"||d.status==="aborted")return S;(c.status==="dirty"||d.status==="dirty")&&r.dirty(),o.set(c.value,d.value)}return{status:r.value,value:o}})}else{const o=new Map;for(const l of i){const c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return S;(c.status==="dirty"||d.status==="dirty")&&r.dirty(),o.set(c.value,d.value)}return{status:r.value,value:o}}}}rn.create=(t,e,r)=>new rn({valueType:e,keyType:t,typeName:f.ZodMap,...E(r)});class ut extends ${_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.set)return _(n,{code:h.invalid_type,expected:b.set,received:n.parsedType}),S;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(_(n,{code:h.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(_(n,{code:h.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());const a=this._def.valueType;function i(l){const c=new Set;for(const d of l){if(d.status==="aborted")return S;d.status==="dirty"&&r.dirty(),c.add(d.value)}return{status:r.value,value:c}}const o=[...n.data.values()].map((l,c)=>a._parse(new $e(n,l,n.path,c)));return n.common.async?Promise.all(o).then(l=>i(l)):i(o)}min(e,r){return new ut({...this._def,minSize:{value:e,message:x.toString(r)}})}max(e,r){return new ut({...this._def,maxSize:{value:e,message:x.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}ut.create=(t,e)=>new ut({valueType:t,minSize:null,maxSize:null,typeName:f.ZodSet,...E(e)});class kt extends ${constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==b.function)return _(r,{code:h.invalid_type,expected:b.function,received:r.parsedType}),S;function n(o,l){return Xr({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Kr(),Ot].filter(c=>!!c),issueData:{code:h.invalid_arguments,argumentsError:l}})}function s(o,l){return Xr({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Kr(),Ot].filter(c=>!!c),issueData:{code:h.invalid_return_type,returnTypeError:l}})}const a={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Rt){const o=this;return ne(async function(...l){const c=new le([]),d=await o._def.args.parseAsync(l,a).catch(w=>{throw c.addIssue(n(l,w)),c}),p=await Reflect.apply(i,this,d);return await o._def.returns._def.type.parseAsync(p,a).catch(w=>{throw c.addIssue(s(p,w)),c})})}else{const o=this;return ne(function(...l){const c=o._def.args.safeParse(l,a);if(!c.success)throw new le([n(l,c.error)]);const d=Reflect.apply(i,this,c.data),p=o._def.returns.safeParse(d,a);if(!p.success)throw new le([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new kt({...this._def,args:Ie.create(e).rest(at.create())})}returns(e){return new kt({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new kt({args:e||Ie.create([]).rest(at.create()),returns:r||at.create(),typeName:f.ZodFunction,...E(n)})}}class hr extends ${get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}hr.create=(t,e)=>new hr({getter:t,typeName:f.ZodLazy,...E(e)});class fr extends ${_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return _(r,{received:r.data,code:h.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:e.data}}get value(){return this._def.value}}fr.create=(t,e)=>new fr({value:t,typeName:f.ZodLiteral,...E(e)});function _i(t,e){return new He({values:t,typeName:f.ZodEnum,...E(e)})}class He extends ${constructor(){super(...arguments),qt.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return _(r,{expected:C.joinValues(n),received:r.parsedType,code:h.invalid_type}),S}if(Qr(this,qt)||mi(this,qt,new Set(this._def.values)),!Qr(this,qt).has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return _(r,{received:r.data,code:h.invalid_enum_value,options:n}),S}return ne(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return He.create(e,{...this._def,...r})}exclude(e,r=this._def){return He.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}qt=new WeakMap;He.create=_i;class mr extends ${constructor(){super(...arguments),Ht.set(this,void 0)}_parse(e){const r=C.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==b.string&&n.parsedType!==b.number){const s=C.objectValues(r);return _(n,{expected:C.joinValues(s),received:n.parsedType,code:h.invalid_type}),S}if(Qr(this,Ht)||mi(this,Ht,new Set(C.getValidEnumValues(this._def.values))),!Qr(this,Ht).has(e.data)){const s=C.objectValues(r);return _(n,{received:n.data,code:h.invalid_enum_value,options:s}),S}return ne(e.data)}get enum(){return this._def.values}}Ht=new WeakMap;mr.create=(t,e)=>new mr({values:t,typeName:f.ZodNativeEnum,...E(e)});class Rt extends ${unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==b.promise&&r.common.async===!1)return _(r,{code:h.invalid_type,expected:b.promise,received:r.parsedType}),S;const n=r.parsedType===b.promise?r.data:Promise.resolve(r.data);return ne(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Rt.create=(t,e)=>new Rt({type:t,typeName:f.ZodPromise,...E(e)});class be extends ${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===f.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{_(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){const i=s.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async o=>{if(r.value==="aborted")return S;const l=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return l.status==="aborted"?S:l.status==="dirty"||r.value==="dirty"?wt(l.value):l});{if(r.value==="aborted")return S;const o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?S:o.status==="dirty"||r.value==="dirty"?wt(o.value):o}}if(s.type==="refinement"){const i=o=>{const l=s.refinement(o,a);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?S:(o.status==="dirty"&&r.dirty(),i(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?S:(o.status==="dirty"&&r.dirty(),i(o.value).then(()=>({status:r.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!lt(i))return i;const o=s.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>lt(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:r.value,value:o})):i);C.assertNever(s)}}be.create=(t,e,r)=>new be({schema:t,typeName:f.ZodEffects,effect:e,...E(r)});be.createWithPreprocess=(t,e,r)=>new be({schema:e,effect:{type:"preprocess",transform:t},typeName:f.ZodEffects,...E(r)});class _e extends ${_parse(e){return this._getType(e)===b.undefined?ne(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}_e.create=(t,e)=>new _e({innerType:t,typeName:f.ZodOptional,...E(e)});class Je extends ${_parse(e){return this._getType(e)===b.null?ne(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Je.create=(t,e)=>new Je({innerType:t,typeName:f.ZodNullable,...E(e)});class gr extends ${_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===b.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}gr.create=(t,e)=>new gr({innerType:t,typeName:f.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...E(e)});class yr extends ${_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ir(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new le(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new le(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}yr.create=(t,e)=>new yr({innerType:t,typeName:f.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...E(e)});class nn extends ${_parse(e){if(this._getType(e)!==b.nan){const n=this._getOrReturnCtx(e);return _(n,{code:h.invalid_type,expected:b.nan,received:n.parsedType}),S}return{status:"valid",value:e.data}}}nn.create=t=>new nn({typeName:f.ZodNaN,...E(t)});const xc=Symbol("zod_brand");class hs extends ${_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class Ir extends ${_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?S:a.status==="dirty"?(r.dirty(),wt(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?S:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new Ir({in:e,out:r,typeName:f.ZodPipeline})}}class vr extends ${_parse(e){const r=this._def.innerType._parse(e),n=s=>(lt(s)&&(s.value=Object.freeze(s.value)),s);return ir(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}}vr.create=(t,e)=>new vr({innerType:t,typeName:f.ZodReadonly,...E(e)});function ta(t,e){const r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function bi(t,e={},r){return t?Pt.create().superRefine((n,s)=>{var a,i;const o=t(n);if(o instanceof Promise)return o.then(l=>{var c,d;if(!l){const p=ta(e,n),g=(d=(c=p.fatal)!==null&&c!==void 0?c:r)!==null&&d!==void 0?d:!0;s.addIssue({code:"custom",...p,fatal:g})}});if(!o){const l=ta(e,n),c=(i=(a=l.fatal)!==null&&a!==void 0?a:r)!==null&&i!==void 0?i:!0;s.addIssue({code:"custom",...l,fatal:c})}}):Pt.create()}const Ac={object:B.lazycreate};var f;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(f||(f={}));const Sc=(t,e={message:`Input not instance of ${t.name}`})=>bi(r=>r instanceof t,e),wi=ye.create,xi=ze.create,kc=nn.create,Ec=qe.create,Ai=or.create,Tc=ct.create,$c=en.create,Ic=lr.create,Cc=cr.create,Oc=Pt.create,Pc=at.create,Rc=Ne.create,jc=tn.create,Nc=ve.create,Mc=B.create,Dc=B.strictCreate,Zc=ur.create,Uc=vn.create,Lc=dr.create,Fc=Ie.create,Vc=pr.create,Bc=rn.create,zc=ut.create,qc=kt.create,Hc=hr.create,Jc=fr.create,Wc=He.create,Gc=mr.create,Yc=Rt.create,ra=be.create,Kc=_e.create,Xc=Je.create,Qc=be.createWithPreprocess,eu=Ir.create,tu=()=>wi().optional(),ru=()=>xi().optional(),nu=()=>Ai().optional(),su={string:t=>ye.create({...t,coerce:!0}),number:t=>ze.create({...t,coerce:!0}),boolean:t=>or.create({...t,coerce:!0}),bigint:t=>qe.create({...t,coerce:!0}),date:t=>ct.create({...t,coerce:!0})},au=S;var u=Object.freeze({__proto__:null,defaultErrorMap:Ot,setErrorMap:Ql,getErrorMap:Kr,makeIssue:Xr,EMPTY_PATH:ec,addIssueToContext:_,ParseStatus:ee,INVALID:S,DIRTY:wt,OK:ne,isAborted:Jn,isDirty:Wn,isValid:lt,isAsync:ir,get util(){return C},get objectUtil(){return Hn},ZodParsedType:b,getParsedType:Re,ZodType:$,datetimeRegex:vi,ZodString:ye,ZodNumber:ze,ZodBigInt:qe,ZodBoolean:or,ZodDate:ct,ZodSymbol:en,ZodUndefined:lr,ZodNull:cr,ZodAny:Pt,ZodUnknown:at,ZodNever:Ne,ZodVoid:tn,ZodArray:ve,ZodObject:B,ZodUnion:ur,ZodDiscriminatedUnion:vn,ZodIntersection:dr,ZodTuple:Ie,ZodRecord:pr,ZodMap:rn,ZodSet:ut,ZodFunction:kt,ZodLazy:hr,ZodLiteral:fr,ZodEnum:He,ZodNativeEnum:mr,ZodPromise:Rt,ZodEffects:be,ZodTransformer:be,ZodOptional:_e,ZodNullable:Je,ZodDefault:gr,ZodCatch:yr,ZodNaN:nn,BRAND:xc,ZodBranded:hs,ZodPipeline:Ir,ZodReadonly:vr,custom:bi,Schema:$,ZodSchema:$,late:Ac,get ZodFirstPartyTypeKind(){return f},coerce:su,any:Oc,array:Nc,bigint:Ec,boolean:Ai,date:Tc,discriminatedUnion:Uc,effect:ra,enum:Wc,function:qc,instanceof:Sc,intersection:Lc,lazy:Hc,literal:Jc,map:Bc,nan:kc,nativeEnum:Gc,never:Rc,null:Cc,nullable:Xc,number:xi,object:Mc,oboolean:nu,onumber:ru,optional:Kc,ostring:tu,pipeline:eu,preprocess:Qc,promise:Yc,record:Vc,set:zc,strictObject:Dc,string:wi,symbol:$c,transformer:ra,tuple:Fc,undefined:Ic,union:Zc,unknown:Pc,void:jc,NEVER:au,ZodIssueCode:h,quotelessJson:Xl,ZodError:le});function iu({prompt:t,useLegacyFunctionCalling:e=!1,systemMessageMode:r="system"}){const n=[];for(const{role:s,content:a}of t)switch(s){case"system":{switch(r){case"system":{n.push({role:"system",content:a});break}case"developer":{n.push({role:"developer",content:a});break}case"remove":break;default:{const i=r;throw new Error(`Unsupported system message mode: ${i}`)}}break}case"user":{if(a.length===1&&a[0].type==="text"){n.push({role:"user",content:a[0].text});break}n.push({role:"user",content:a.map(i=>{var o,l,c;switch(i.type){case"text":return{type:"text",text:i.text};case"image":return{type:"image_url",image_url:{url:i.image instanceof URL?i.image.toString():`data:${(o=i.mimeType)!=null?o:"image/jpeg"};base64,${qn(i.image)}`,detail:(c=(l=i.providerMetadata)==null?void 0:l.openai)==null?void 0:c.imageDetail}};case"file":{if(i.data instanceof URL)throw new G({functionality:"'File content parts with URL data' functionality not supported."});switch(i.mimeType){case"audio/wav":return{type:"input_audio",input_audio:{data:i.data,format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:i.data,format:"mp3"}};default:throw new G({functionality:`File content part type ${i.mimeType} in user messages`})}}}})});break}case"assistant":{let i="";const o=[];for(const l of a)switch(l.type){case"text":{i+=l.text;break}case"redacted-reasoning":case"reasoning":break;case"tool-call":{o.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.args)}});break}default:{const c=l;throw new Error(`Unsupported part: ${c}`)}}if(e){if(o.length>1)throw new G({functionality:"useLegacyFunctionCalling with multiple tool calls in one message"});n.push({role:"assistant",content:i,function_call:o.length>0?o[0].function:void 0})}else n.push({role:"assistant",content:i,tool_calls:o.length>0?o:void 0});break}case"tool":{for(const i of a)e?n.push({role:"function",name:i.toolName,content:JSON.stringify(i.result)}):n.push({role:"tool",tool_call_id:i.toolCallId,content:JSON.stringify(i.result)});break}default:{const i=s;throw new Error(`Unsupported role: ${i}`)}}return n}function na(t){var e,r;return(r=(e=t==null?void 0:t.content)==null?void 0:e.map(({token:n,logprob:s,top_logprobs:a})=>({token:n,logprob:s,topLogprobs:a?a.map(({token:i,logprob:o})=>({token:i,logprob:o})):[]})))!=null?r:void 0}function sn(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var fs=u.object({error:u.object({message:u.string(),type:u.string().nullish(),param:u.any().nullish(),code:u.union([u.string(),u.number()]).nullish()})}),jt=Jl({errorSchema:fs,errorToMessage:t=>t.error.message});function an({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function ou({mode:t,useLegacyFunctionCalling:e=!1,structuredOutputs:r}){var n;const s=(n=t.tools)!=null&&n.length?t.tools:void 0,a=[];if(s==null)return{tools:void 0,tool_choice:void 0,toolWarnings:a};const i=t.toolChoice;if(e){const c=[];for(const p of s)p.type==="provider-defined"?a.push({type:"unsupported-tool",tool:p}):c.push({name:p.name,description:p.description,parameters:p.parameters});if(i==null)return{functions:c,function_call:void 0,toolWarnings:a};switch(i.type){case"auto":case"none":case void 0:return{functions:c,function_call:void 0,toolWarnings:a};case"required":throw new G({functionality:"useLegacyFunctionCalling and toolChoice: required"});default:return{functions:c,function_call:{name:i.toolName},toolWarnings:a}}}const o=[];for(const c of s)c.type==="provider-defined"?a.push({type:"unsupported-tool",tool:c}):o.push({type:"function",function:{name:c.name,description:c.description,parameters:c.parameters,strict:r?!0:void 0}});if(i==null)return{tools:o,tool_choice:void 0,toolWarnings:a};const l=i.type;switch(l){case"auto":case"none":case"required":return{tools:o,tool_choice:l,toolWarnings:a};case"tool":return{tools:o,tool_choice:{type:"function",function:{name:i.toolName}},toolWarnings:a};default:{const c=l;throw new G({functionality:`Unsupported tool choice type: ${c}`})}}}var lu=class{constructor(t,e,r){this.specificationVersion="v1",this.modelId=t,this.settings=e,this.config=r}get supportsStructuredOutputs(){var t;return(t=this.settings.structuredOutputs)!=null?t:Yn(this.modelId)}get defaultObjectGenerationMode(){return du(this.modelId)?"tool":this.supportsStructuredOutputs?"json":"tool"}get provider(){return this.config.provider}get supportsImageUrls(){return!this.settings.downloadImages}getArgs({mode:t,prompt:e,maxTokens:r,temperature:n,topP:s,topK:a,frequencyPenalty:i,presencePenalty:o,stopSequences:l,responseFormat:c,seed:d,providerMetadata:p}){var g,w,y,m,v,A,k,T;const P=t.type,R=[];a!=null&&R.push({type:"unsupported-setting",setting:"topK"}),(c==null?void 0:c.type)==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&R.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const z=this.settings.useLegacyFunctionCalling;if(z&&this.settings.parallelToolCalls===!0)throw new G({functionality:"useLegacyFunctionCalling with parallelToolCalls"});if(z&&this.supportsStructuredOutputs)throw new G({functionality:"structuredOutputs with useLegacyFunctionCalling"});sa(this.modelId)==="remove"&&e.some(Y=>Y.role==="system")&&R.push({type:"other",message:"system messages are removed for this model"});const I={model:this.modelId,logit_bias:this.settings.logitBias,logprobs:this.settings.logprobs===!0||typeof this.settings.logprobs=="number"?!0:void 0,top_logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,user:this.settings.user,parallel_tool_calls:this.settings.parallelToolCalls,max_tokens:r,temperature:n,top_p:s,frequency_penalty:i,presence_penalty:o,response_format:(c==null?void 0:c.type)==="json"?this.supportsStructuredOutputs&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,strict:!0,name:(g=c.name)!=null?g:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:d,max_completion_tokens:(w=p==null?void 0:p.openai)==null?void 0:w.maxCompletionTokens,store:(y=p==null?void 0:p.openai)==null?void 0:y.store,metadata:(m=p==null?void 0:p.openai)==null?void 0:m.metadata,prediction:(v=p==null?void 0:p.openai)==null?void 0:v.prediction,reasoning_effort:(k=(A=p==null?void 0:p.openai)==null?void 0:A.reasoningEffort)!=null?k:this.settings.reasoningEffort,messages:iu({prompt:e,useLegacyFunctionCalling:z,systemMessageMode:sa(this.modelId)})};switch(Yn(this.modelId)&&(I.temperature!=null&&(I.temperature=void 0,R.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),I.top_p!=null&&(I.top_p=void 0,R.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),I.frequency_penalty!=null&&(I.frequency_penalty=void 0,R.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),I.presence_penalty!=null&&(I.presence_penalty=void 0,R.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),I.logit_bias!=null&&(I.logit_bias=void 0,R.push({type:"other",message:"logitBias is not supported for reasoning models"})),I.logprobs!=null&&(I.logprobs=void 0,R.push({type:"other",message:"logprobs is not supported for reasoning models"})),I.top_logprobs!=null&&(I.top_logprobs=void 0,R.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),I.max_tokens!=null&&(I.max_completion_tokens==null&&(I.max_completion_tokens=I.max_tokens),I.max_tokens=void 0)),P){case"regular":{const{tools:Y,tool_choice:ht,functions:We,function_call:Ge,toolWarnings:Ye}=ou({mode:t,useLegacyFunctionCalling:z,structuredOutputs:this.supportsStructuredOutputs});return{args:{...I,tools:Y,tool_choice:ht,functions:We,function_call:Ge},warnings:[...R,...Ye]}}case"object-json":return{args:{...I,response_format:this.supportsStructuredOutputs&&t.schema!=null?{type:"json_schema",json_schema:{schema:t.schema,strict:!0,name:(T=t.name)!=null?T:"response",description:t.description}}:{type:"json_object"}},warnings:R};case"object-tool":return{args:z?{...I,function_call:{name:t.tool.name},functions:[{name:t.tool.name,description:t.tool.description,parameters:t.tool.parameters}]}:{...I,tool_choice:{type:"function",function:{name:t.tool.name}},tools:[{type:"function",function:{name:t.tool.name,description:t.tool.description,parameters:t.tool.parameters,strict:this.supportsStructuredOutputs?!0:void 0}}]},warnings:R};default:{const Y=P;throw new Error(`Unsupported type: ${Y}`)}}}async doGenerate(t){var e,r,n,s,a,i,o,l;const{args:c,warnings:d}=this.getArgs(t),{responseHeaders:p,value:g,rawValue:w}=await Ct({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:$t(this.config.headers(),t.headers),body:c,failedResponseHandler:jt,successfulResponseHandler:yn(cu),abortSignal:t.abortSignal,fetch:this.config.fetch}),{messages:y,...m}=c,v=g.choices[0],A=(e=g.usage)==null?void 0:e.completion_tokens_details,k=(r=g.usage)==null?void 0:r.prompt_tokens_details,T={openai:{}};return(A==null?void 0:A.reasoning_tokens)!=null&&(T.openai.reasoningTokens=A==null?void 0:A.reasoning_tokens),(A==null?void 0:A.accepted_prediction_tokens)!=null&&(T.openai.acceptedPredictionTokens=A==null?void 0:A.accepted_prediction_tokens),(A==null?void 0:A.rejected_prediction_tokens)!=null&&(T.openai.rejectedPredictionTokens=A==null?void 0:A.rejected_prediction_tokens),(k==null?void 0:k.cached_tokens)!=null&&(T.openai.cachedPromptTokens=k==null?void 0:k.cached_tokens),{text:(n=v.message.content)!=null?n:void 0,toolCalls:this.settings.useLegacyFunctionCalling&&v.message.function_call?[{toolCallType:"function",toolCallId:Ft(),toolName:v.message.function_call.name,args:v.message.function_call.arguments}]:(s=v.message.tool_calls)==null?void 0:s.map(P=>{var R;return{toolCallType:"function",toolCallId:(R=P.id)!=null?R:Ft(),toolName:P.function.name,args:P.function.arguments}}),finishReason:sn(v.finish_reason),usage:{promptTokens:(i=(a=g.usage)==null?void 0:a.prompt_tokens)!=null?i:NaN,completionTokens:(l=(o=g.usage)==null?void 0:o.completion_tokens)!=null?l:NaN},rawCall:{rawPrompt:y,rawSettings:m},rawResponse:{headers:p,body:w},request:{body:JSON.stringify(c)},response:an(g),warnings:d,logprobs:na(v.logprobs),providerMetadata:T}}async doStream(t){if(this.settings.simulateStreaming){const m=await this.doGenerate(t);return{stream:new ReadableStream({start(A){if(A.enqueue({type:"response-metadata",...m.response}),m.text&&A.enqueue({type:"text-delta",textDelta:m.text}),m.toolCalls)for(const k of m.toolCalls)A.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:k.toolCallId,toolName:k.toolName,argsTextDelta:k.args}),A.enqueue({type:"tool-call",...k});A.enqueue({type:"finish",finishReason:m.finishReason,usage:m.usage,logprobs:m.logprobs,providerMetadata:m.providerMetadata}),A.close()}}),rawCall:m.rawCall,rawResponse:m.rawResponse,warnings:m.warnings}}const{args:e,warnings:r}=this.getArgs(t),n={...e,stream:!0,stream_options:this.config.compatibility==="strict"?{include_usage:!0}:void 0},{responseHeaders:s,value:a}=await Ct({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:$t(this.config.headers(),t.headers),body:n,failedResponseHandler:jt,successfulResponseHandler:hi(uu),abortSignal:t.abortSignal,fetch:this.config.fetch}),{messages:i,...o}=e,l=[];let c="unknown",d={promptTokens:void 0,completionTokens:void 0},p,g=!0;const{useLegacyFunctionCalling:w}=this.settings,y={openai:{}};return{stream:a.pipeThrough(new TransformStream({transform(m,v){var A,k,T,P,R,z,I,Y,ht,We,Ge,Ye;if(!m.success){c="error",v.enqueue({type:"error",error:m.error});return}const Ce=m.value;if("error"in Ce){c="error",v.enqueue({type:"error",error:Ce.error});return}if(g&&(g=!1,v.enqueue({type:"response-metadata",...an(Ce)})),Ce.usage!=null){const{prompt_tokens:V,completion_tokens:se,prompt_tokens_details:H,completion_tokens_details:D}=Ce.usage;d={promptTokens:V??void 0,completionTokens:se??void 0},(D==null?void 0:D.reasoning_tokens)!=null&&(y.openai.reasoningTokens=D==null?void 0:D.reasoning_tokens),(D==null?void 0:D.accepted_prediction_tokens)!=null&&(y.openai.acceptedPredictionTokens=D==null?void 0:D.accepted_prediction_tokens),(D==null?void 0:D.rejected_prediction_tokens)!=null&&(y.openai.rejectedPredictionTokens=D==null?void 0:D.rejected_prediction_tokens),(H==null?void 0:H.cached_tokens)!=null&&(y.openai.cachedPromptTokens=H==null?void 0:H.cached_tokens)}const ie=Ce.choices[0];if((ie==null?void 0:ie.finish_reason)!=null&&(c=sn(ie.finish_reason)),(ie==null?void 0:ie.delta)==null)return;const xe=ie.delta;xe.content!=null&&v.enqueue({type:"text-delta",textDelta:xe.content});const ce=na(ie==null?void 0:ie.logprobs);ce!=null&&ce.length&&(p===void 0&&(p=[]),p.push(...ce));const ft=w&&xe.function_call!=null?[{type:"function",id:Ft(),function:xe.function_call,index:0}]:xe.tool_calls;if(ft!=null)for(const V of ft){const se=V.index;if(l[se]==null){if(V.type!=="function")throw new $n({data:V,message:"Expected 'function' type."});if(V.id==null)throw new $n({data:V,message:"Expected 'id' to be a string."});if(((A=V.function)==null?void 0:A.name)==null)throw new $n({data:V,message:"Expected 'function.name' to be a string."});l[se]={id:V.id,type:"function",function:{name:V.function.name,arguments:(k=V.function.arguments)!=null?k:""},hasFinished:!1};const D=l[se];((T=D.function)==null?void 0:T.name)!=null&&((P=D.function)==null?void 0:P.arguments)!=null&&(D.function.arguments.length>0&&v.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:D.id,toolName:D.function.name,argsTextDelta:D.function.arguments}),Qs(D.function.arguments)&&(v.enqueue({type:"tool-call",toolCallType:"function",toolCallId:(R=D.id)!=null?R:Ft(),toolName:D.function.name,args:D.function.arguments}),D.hasFinished=!0));continue}const H=l[se];H.hasFinished||(((z=V.function)==null?void 0:z.arguments)!=null&&(H.function.arguments+=(Y=(I=V.function)==null?void 0:I.arguments)!=null?Y:""),v.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:H.id,toolName:H.function.name,argsTextDelta:(ht=V.function.arguments)!=null?ht:""}),((We=H.function)==null?void 0:We.name)!=null&&((Ge=H.function)==null?void 0:Ge.arguments)!=null&&Qs(H.function.arguments)&&(v.enqueue({type:"tool-call",toolCallType:"function",toolCallId:(Ye=H.id)!=null?Ye:Ft(),toolName:H.function.name,args:H.function.arguments}),H.hasFinished=!0))}},flush(m){var v,A;m.enqueue({type:"finish",finishReason:c,logprobs:p,usage:{promptTokens:(v=d.promptTokens)!=null?v:NaN,completionTokens:(A=d.completionTokens)!=null?A:NaN},...y!=null?{providerMetadata:y}:{}})}})),rawCall:{rawPrompt:i,rawSettings:o},rawResponse:{headers:s},request:{body:JSON.stringify(n)},warnings:r}}},Si=u.object({prompt_tokens:u.number().nullish(),completion_tokens:u.number().nullish(),prompt_tokens_details:u.object({cached_tokens:u.number().nullish()}).nullish(),completion_tokens_details:u.object({reasoning_tokens:u.number().nullish(),accepted_prediction_tokens:u.number().nullish(),rejected_prediction_tokens:u.number().nullish()}).nullish()}).nullish(),cu=u.object({id:u.string().nullish(),created:u.number().nullish(),model:u.string().nullish(),choices:u.array(u.object({message:u.object({role:u.literal("assistant").nullish(),content:u.string().nullish(),function_call:u.object({arguments:u.string(),name:u.string()}).nullish(),tool_calls:u.array(u.object({id:u.string().nullish(),type:u.literal("function"),function:u.object({name:u.string(),arguments:u.string()})})).nullish()}),index:u.number(),logprobs:u.object({content:u.array(u.object({token:u.string(),logprob:u.number(),top_logprobs:u.array(u.object({token:u.string(),logprob:u.number()}))})).nullable()}).nullish(),finish_reason:u.string().nullish()})),usage:Si}),uu=u.union([u.object({id:u.string().nullish(),created:u.number().nullish(),model:u.string().nullish(),choices:u.array(u.object({delta:u.object({role:u.enum(["assistant"]).nullish(),content:u.string().nullish(),function_call:u.object({name:u.string().optional(),arguments:u.string().optional()}).nullish(),tool_calls:u.array(u.object({index:u.number(),id:u.string().nullish(),type:u.literal("function").optional(),function:u.object({name:u.string().nullish(),arguments:u.string().nullish()})})).nullish()}).nullish(),logprobs:u.object({content:u.array(u.object({token:u.string(),logprob:u.number(),top_logprobs:u.array(u.object({token:u.string(),logprob:u.number()}))})).nullable()}).nullish(),finish_reason:u.string().nullable().optional(),index:u.number()})),usage:Si}),fs]);function Yn(t){return t==="o1"||t.startsWith("o1-")||t==="o3"||t.startsWith("o3-")}function du(t){return t.startsWith("gpt-4o-audio-preview")}function sa(t){var e,r;return Yn(t)?(r=(e=pu[t])==null?void 0:e.systemMessageMode)!=null?r:"developer":"system"}var pu={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"}};function hu({prompt:t,inputFormat:e,user:r="user",assistant:n="assistant"}){if(e==="prompt"&&t.length===1&&t[0].role==="user"&&t[0].content.length===1&&t[0].content[0].type==="text")return{prompt:t[0].content[0].text};let s="";t[0].role==="system"&&(s+=`${t[0].content}
171
+
172
+ `,t=t.slice(1));for(const{role:a,content:i}of t)switch(a){case"system":throw new et({message:"Unexpected system message in prompt: ${content}",prompt:t});case"user":{const o=i.map(l=>{switch(l.type){case"text":return l.text;case"image":throw new G({functionality:"images"})}}).join("");s+=`${r}:
173
+ ${o}
174
+
175
+ `;break}case"assistant":{const o=i.map(l=>{switch(l.type){case"text":return l.text;case"tool-call":throw new G({functionality:"tool-call messages"})}}).join("");s+=`${n}:
176
+ ${o}
177
+
178
+ `;break}case"tool":throw new G({functionality:"tool messages"});default:{const o=a;throw new Error(`Unsupported role: ${o}`)}}return s+=`${n}:
179
+ `,{prompt:s,stopSequences:[`
180
+ ${r}:`]}}function aa(t){return t==null?void 0:t.tokens.map((e,r)=>({token:e,logprob:t.token_logprobs[r],topLogprobs:t.top_logprobs?Object.entries(t.top_logprobs[r]).map(([n,s])=>({token:n,logprob:s})):[]}))}var fu=class{constructor(t,e,r){this.specificationVersion="v1",this.defaultObjectGenerationMode=void 0,this.modelId=t,this.settings=e,this.config=r}get provider(){return this.config.provider}getArgs({mode:t,inputFormat:e,prompt:r,maxTokens:n,temperature:s,topP:a,topK:i,frequencyPenalty:o,presencePenalty:l,stopSequences:c,responseFormat:d,seed:p}){var g;const w=t.type,y=[];i!=null&&y.push({type:"unsupported-setting",setting:"topK"}),d!=null&&d.type!=="text"&&y.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:m,stopSequences:v}=hu({prompt:r,inputFormat:e}),A=[...v??[],...c??[]],k={model:this.modelId,echo:this.settings.echo,logit_bias:this.settings.logitBias,logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,suffix:this.settings.suffix,user:this.settings.user,max_tokens:n,temperature:s,top_p:a,frequency_penalty:o,presence_penalty:l,seed:p,prompt:m,stop:A.length>0?A:void 0};switch(w){case"regular":{if((g=t.tools)!=null&&g.length)throw new G({functionality:"tools"});if(t.toolChoice)throw new G({functionality:"toolChoice"});return{args:k,warnings:y}}case"object-json":throw new G({functionality:"object-json mode"});case"object-tool":throw new G({functionality:"object-tool mode"});default:{const T=w;throw new Error(`Unsupported type: ${T}`)}}}async doGenerate(t){const{args:e,warnings:r}=this.getArgs(t),{responseHeaders:n,value:s,rawValue:a}=await Ct({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:$t(this.config.headers(),t.headers),body:e,failedResponseHandler:jt,successfulResponseHandler:yn(mu),abortSignal:t.abortSignal,fetch:this.config.fetch}),{prompt:i,...o}=e,l=s.choices[0];return{text:l.text,usage:{promptTokens:s.usage.prompt_tokens,completionTokens:s.usage.completion_tokens},finishReason:sn(l.finish_reason),logprobs:aa(l.logprobs),rawCall:{rawPrompt:i,rawSettings:o},rawResponse:{headers:n,body:a},response:an(s),warnings:r,request:{body:JSON.stringify(e)}}}async doStream(t){const{args:e,warnings:r}=this.getArgs(t),n={...e,stream:!0,stream_options:this.config.compatibility==="strict"?{include_usage:!0}:void 0},{responseHeaders:s,value:a}=await Ct({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:$t(this.config.headers(),t.headers),body:n,failedResponseHandler:jt,successfulResponseHandler:hi(gu),abortSignal:t.abortSignal,fetch:this.config.fetch}),{prompt:i,...o}=e;let l="unknown",c={promptTokens:Number.NaN,completionTokens:Number.NaN},d,p=!0;return{stream:a.pipeThrough(new TransformStream({transform(g,w){if(!g.success){l="error",w.enqueue({type:"error",error:g.error});return}const y=g.value;if("error"in y){l="error",w.enqueue({type:"error",error:y.error});return}p&&(p=!1,w.enqueue({type:"response-metadata",...an(y)})),y.usage!=null&&(c={promptTokens:y.usage.prompt_tokens,completionTokens:y.usage.completion_tokens});const m=y.choices[0];(m==null?void 0:m.finish_reason)!=null&&(l=sn(m.finish_reason)),(m==null?void 0:m.text)!=null&&w.enqueue({type:"text-delta",textDelta:m.text});const v=aa(m==null?void 0:m.logprobs);v!=null&&v.length&&(d===void 0&&(d=[]),d.push(...v))},flush(g){g.enqueue({type:"finish",finishReason:l,logprobs:d,usage:c})}})),rawCall:{rawPrompt:i,rawSettings:o},rawResponse:{headers:s},warnings:r,request:{body:JSON.stringify(n)}}}},mu=u.object({id:u.string().nullish(),created:u.number().nullish(),model:u.string().nullish(),choices:u.array(u.object({text:u.string(),finish_reason:u.string(),logprobs:u.object({tokens:u.array(u.string()),token_logprobs:u.array(u.number()),top_logprobs:u.array(u.record(u.string(),u.number())).nullable()}).nullish()})),usage:u.object({prompt_tokens:u.number(),completion_tokens:u.number()})}),gu=u.union([u.object({id:u.string().nullish(),created:u.number().nullish(),model:u.string().nullish(),choices:u.array(u.object({text:u.string(),finish_reason:u.string().nullish(),index:u.number(),logprobs:u.object({tokens:u.array(u.string()),token_logprobs:u.array(u.number()),top_logprobs:u.array(u.record(u.string(),u.number())).nullable()}).nullish()})),usage:u.object({prompt_tokens:u.number(),completion_tokens:u.number()}).nullish()}),fs]),yu=class{constructor(t,e,r){this.specificationVersion="v1",this.modelId=t,this.settings=e,this.config=r}get provider(){return this.config.provider}get maxEmbeddingsPerCall(){var t;return(t=this.settings.maxEmbeddingsPerCall)!=null?t:2048}get supportsParallelCalls(){var t;return(t=this.settings.supportsParallelCalls)!=null?t:!0}async doEmbed({values:t,headers:e,abortSignal:r}){if(t.length>this.maxEmbeddingsPerCall)throw new bl({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const{responseHeaders:n,value:s}=await Ct({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:$t(this.config.headers(),e),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:this.settings.dimensions,user:this.settings.user},failedResponseHandler:jt,successfulResponseHandler:yn(vu),abortSignal:r,fetch:this.config.fetch});return{embeddings:s.data.map(a=>a.embedding),usage:s.usage?{tokens:s.usage.prompt_tokens}:void 0,rawResponse:{headers:n}}}},vu=u.object({data:u.array(u.object({embedding:u.array(u.number())})),usage:u.object({prompt_tokens:u.number()}).nullish()}),_u={"dall-e-3":1,"dall-e-2":10},bu=class{constructor(t,e,r){this.modelId=t,this.settings=e,this.config=r,this.specificationVersion="v1"}get maxImagesPerCall(){var t,e;return(e=(t=this.settings.maxImagesPerCall)!=null?t:_u[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:s,providerOptions:a,headers:i,abortSignal:o}){var l,c,d,p;const g=[];n!=null&&g.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),s!=null&&g.push({type:"unsupported-setting",setting:"seed"});const w=(d=(c=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:c.call(l))!=null?d:new Date,{value:y,responseHeaders:m}=await Ct({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:$t(this.config.headers(),i),body:{model:this.modelId,prompt:t,n:e,size:r,...(p=a.openai)!=null?p:{},response_format:"b64_json"},failedResponseHandler:jt,successfulResponseHandler:yn(wu),abortSignal:o,fetch:this.config.fetch});return{images:y.data.map(v=>v.b64_json),warnings:g,response:{timestamp:w,modelId:this.modelId,headers:m}}}},wu=u.object({data:u.array(u.object({b64_json:u.string()}))});function ki(t={}){var e,r,n;const s=(e=Kl(t.baseURL))!=null?e:"https://api.openai.com/v1",a=(r=t.compatibility)!=null?r:"compatible",i=(n=t.name)!=null?n:"openai",o=()=>({Authorization:`Bearer ${Zl({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers}),l=(y,m={})=>new lu(y,m,{provider:`${i}.chat`,url:({path:v})=>`${s}${v}`,headers:o,compatibility:a,fetch:t.fetch}),c=(y,m={})=>new fu(y,m,{provider:`${i}.completion`,url:({path:v})=>`${s}${v}`,headers:o,compatibility:a,fetch:t.fetch}),d=(y,m={})=>new yu(y,m,{provider:`${i}.embedding`,url:({path:v})=>`${s}${v}`,headers:o,fetch:t.fetch}),p=(y,m={})=>new bu(y,m,{provider:`${i}.image`,url:({path:v})=>`${s}${v}`,headers:o,fetch:t.fetch}),g=(y,m)=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return y==="gpt-3.5-turbo-instruct"?c(y,m):l(y,m)},w=function(y,m){return g(y,m)};return w.languageModel=g,w.chat=l,w.completion=c,w.embedding=d,w.textEmbedding=d,w.textEmbeddingModel=d,w.image=p,w.imageModel=p,w}ki({compatibility:"strict"});const xu=Symbol("Let zodToJsonSchema decide on which parser to use"),ia={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},Au=t=>typeof t=="string"?{...ia,name:t}:{...ia,...t},Su=t=>{const e=Au(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Ei(t,e,r,n){n!=null&&n.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function M(t,e,r,n,s){t[e]=r,Ei(t,e,n,s)}function ku(){return{}}function Eu(t,e){var n,s,a;const r={type:"array"};return(n=t.type)!=null&&n._def&&((a=(s=t.type)==null?void 0:s._def)==null?void 0:a.typeName)!==f.ZodAny&&(r.items=N(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&M(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&M(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(M(r,"minItems",t.exactLength.value,t.exactLength.message,e),M(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Tu(t,e){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?M(r,"minimum",n.value,n.message,e):M(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),M(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?M(r,"maximum",n.value,n.message,e):M(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),M(r,"maximum",n.value,n.message,e));break;case"multipleOf":M(r,"multipleOf",n.value,n.message,e);break}return r}function $u(){return{type:"boolean"}}function Ti(t,e){return N(t.type._def,e)}const Iu=(t,e)=>N(t.innerType._def,e);function $i(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,a)=>$i(t,e,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Cu(t,e)}}const Cu=(t,e)=>{const r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(const n of t.checks)switch(n.kind){case"min":M(r,"minimum",n.value,n.message,e);break;case"max":M(r,"maximum",n.value,n.message,e);break}return r};function Ou(t,e){return{...N(t.innerType._def,e),default:t.defaultValue()}}function Pu(t,e){return e.effectStrategy==="input"?N(t.schema._def,e):{}}function Ru(t){return{type:"string",enum:Array.from(t.values)}}const ju=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Nu(t,e){const r=[N(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),N(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return r.forEach(a=>{if(ju(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(n=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...l}=a;i=l}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}function Mu(t,e){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}let On;const fe={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(On===void 0&&(On=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),On),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}$/,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])$/,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])$/,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})))$/,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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Ii(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":M(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":M(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":me(r,"email",n.message,e);break;case"format:idn-email":me(r,"idn-email",n.message,e);break;case"pattern:zod":te(r,fe.email,n.message,e);break}break;case"url":me(r,"uri",n.message,e);break;case"uuid":me(r,"uuid",n.message,e);break;case"regex":te(r,n.regex,n.message,e);break;case"cuid":te(r,fe.cuid,n.message,e);break;case"cuid2":te(r,fe.cuid2,n.message,e);break;case"startsWith":te(r,RegExp(`^${Pn(n.value,e)}`),n.message,e);break;case"endsWith":te(r,RegExp(`${Pn(n.value,e)}$`),n.message,e);break;case"datetime":me(r,"date-time",n.message,e);break;case"date":me(r,"date",n.message,e);break;case"time":me(r,"time",n.message,e);break;case"duration":me(r,"duration",n.message,e);break;case"length":M(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),M(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{te(r,RegExp(Pn(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&me(r,"ipv4",n.message,e),n.version!=="v4"&&me(r,"ipv6",n.message,e);break}case"base64url":te(r,fe.base64url,n.message,e);break;case"jwt":te(r,fe.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&te(r,fe.ipv4Cidr,n.message,e),n.version!=="v4"&&te(r,fe.ipv6Cidr,n.message,e);break}case"emoji":te(r,fe.emoji(),n.message,e);break;case"ulid":{te(r,fe.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{me(r,"binary",n.message,e);break}case"contentEncoding:base64":{M(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{te(r,fe.base64,n.message,e);break}}break}case"nanoid":te(r,fe.nanoid,n.message,e)}return r}function Pn(t,e){return e.patternStrategy==="escape"?Zu(t):t}const Du=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Zu(t){let e="";for(let r=0;r<t.length;r++)Du.has(t[r])||(e+="\\"),e+=t[r];return e}function me(t,e,r,n){var s;t.format||(s=t.anyOf)!=null&&s.some(a=>a.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):M(t,"format",e,r,n)}function te(t,e,r,n){var s;t.pattern||(s=t.allOf)!=null&&s.some(a=>a.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:oa(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):M(t,"pattern",oa(e,n),r,n)}function oa(t,e){var l;if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source;let s="",a=!1,i=!1,o=!1;for(let c=0;c<n.length;c++){if(a){s+=n[c],a=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){o?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),o=!1):n[c+1]==="-"&&((l=n[c+2])!=null&&l.match(/[a-z]/))?(s+=n[c],o=!0):s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){s+=`(^|(?<=[\r
181
+ ]))`;continue}else if(n[c]==="$"){s+=`($|(?=[\r
182
+ ]))`;continue}}if(r.s&&n[c]==="."){s+=i?`${n[c]}\r
183
+ `:`[${n[c]}\r
184
+ ]`;continue}s+=n[c],n[c]==="\\"?a=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function Ci(t,e){var n,s,a,i,o,l;if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&((n=t.keyType)==null?void 0:n._def.typeName)===f.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((c,d)=>({...c,[d]:N(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",d]})??{}}),{}),additionalProperties:!1};const r={type:"object",additionalProperties:N(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(((s=t.keyType)==null?void 0:s._def.typeName)===f.ZodString&&((a=t.keyType._def.checks)!=null&&a.length)){const{type:c,...d}=Ii(t.keyType._def,e);return{...r,propertyNames:d}}else{if(((i=t.keyType)==null?void 0:i._def.typeName)===f.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(((o=t.keyType)==null?void 0:o._def.typeName)===f.ZodBranded&&t.keyType._def.type._def.typeName===f.ZodString&&((l=t.keyType._def.type._def.checks)!=null&&l.length)){const{type:c,...d}=Ti(t.keyType._def,e);return{...r,propertyNames:d}}}return r}function Uu(t,e){if(e.mapStrategy==="record")return Ci(t,e);const r=N(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=N(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Lu(t){const e=t.values,n=Object.keys(t.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),s=Array.from(new Set(n.map(a=>typeof a)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function Fu(){return{not:{}}}function Vu(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const on={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Bu(t,e){if(e.target==="openApi3")return la(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in on&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,a)=>{const i=on[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((s,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(a._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:r.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(a=>!n.includes(a))],[])};return la(t,e)}const la=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>N(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function zu(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:on[t.innerType._def.typeName],nullable:!0}:{type:[on[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=N(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=N(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function qu(t,e){const r={type:"number"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"int":r.type="integer",Ei(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?M(r,"minimum",n.value,n.message,e):M(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),M(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?M(r,"maximum",n.value,n.message,e):M(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),M(r,"maximum",n.value,n.message,e));break;case"multipleOf":M(r,"multipleOf",n.value,n.message,e);break}return r}function Hu(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":N(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":N(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Ju(t,e){const r=e.target==="openAi",n={type:"object",...Object.entries(t.shape()).reduce((s,[a,i])=>{if(i===void 0||i._def===void 0)return s;let o=i.isOptional();o&&r&&(i instanceof _e&&(i=i._def.innerType),i.isNullable()||(i=i.nullable()),o=!1);const l=N(i._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});return l===void 0?s:{properties:{...s.properties,[a]:l},required:o?s.required:[...s.required,a]}},{properties:{},required:[]}),additionalProperties:Hu(t,e)};return n.required.length||delete n.required,n}const Wu=(t,e)=>{var n;if(e.currentPath.toString()===((n=e.propertyPath)==null?void 0:n.toString()))return N(t.innerType._def,e);const r=N(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}},Gu=(t,e)=>{if(e.pipeStrategy==="input")return N(t.in._def,e);if(e.pipeStrategy==="output")return N(t.out._def,e);const r=N(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=N(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function Yu(t,e){return N(t.type._def,e)}function Ku(t,e){const n={type:"array",uniqueItems:!0,items:N(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&M(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&M(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Xu(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>N(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:N(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>N(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Qu(){return{not:{}}}function ed(){return{}}const td=(t,e)=>N(t.innerType._def,e),rd=(t,e,r)=>{switch(e){case f.ZodString:return Ii(t,r);case f.ZodNumber:return qu(t,r);case f.ZodObject:return Ju(t,r);case f.ZodBigInt:return Tu(t,r);case f.ZodBoolean:return $u();case f.ZodDate:return $i(t,r);case f.ZodUndefined:return Qu();case f.ZodNull:return Vu(r);case f.ZodArray:return Eu(t,r);case f.ZodUnion:case f.ZodDiscriminatedUnion:return Bu(t,r);case f.ZodIntersection:return Nu(t,r);case f.ZodTuple:return Xu(t,r);case f.ZodRecord:return Ci(t,r);case f.ZodLiteral:return Mu(t,r);case f.ZodEnum:return Ru(t);case f.ZodNativeEnum:return Lu(t);case f.ZodNullable:return zu(t,r);case f.ZodOptional:return Wu(t,r);case f.ZodMap:return Uu(t,r);case f.ZodSet:return Ku(t,r);case f.ZodLazy:return()=>t.getter()._def;case f.ZodPromise:return Yu(t,r);case f.ZodNaN:case f.ZodNever:return Fu();case f.ZodEffects:return Pu(t,r);case f.ZodAny:return ku();case f.ZodUnknown:return ed();case f.ZodDefault:return Ou(t,r);case f.ZodBranded:return Ti(t,r);case f.ZodReadonly:return td(t,r);case f.ZodCatch:return Iu(t,r);case f.ZodPipeline:return Gu(t,r);case f.ZodFunction:case f.ZodVoid:case f.ZodSymbol:return;default:return(n=>{})()}};function N(t,e,r=!1){var o;const n=e.seen.get(t);if(e.override){const l=(o=e.override)==null?void 0:o.call(e,t,e,n,r);if(l!==xu)return l}if(n&&!r){const l=nd(n,e);if(l!==void 0)return l}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const a=rd(t,t.typeName,e),i=typeof a=="function"?N(a(),e):a;if(i&&ad(t,e,i),e.postProcess){const l=e.postProcess(i,t,e);return s.jsonSchema=i,l}return s.jsonSchema=i,i}const nd=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:sd(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},sd=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},ad=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),id=(t,e)=>{const r=Su(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[c,d])=>({...l,[c]:N(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??{}}),{}):void 0,s=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,a=N(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??{},i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(a.title=i);const o=s===void 0?n?{...a,[r.definitionPath]:n}:a:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:a}};return r.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o};var _r={code:"0",name:"text",parse:t=>{if(typeof t!="string")throw new Error('"text" parts expect a string value.');return{type:"text",value:t}}},br={code:"3",name:"error",parse:t=>{if(typeof t!="string")throw new Error('"error" parts expect a string value.');return{type:"error",value:t}}},wr={code:"4",name:"assistant_message",parse:t=>{if(t==null||typeof t!="object"||!("id"in t)||!("role"in t)||!("content"in t)||typeof t.id!="string"||typeof t.role!="string"||t.role!=="assistant"||!Array.isArray(t.content)||!t.content.every(e=>e!=null&&typeof e=="object"&&"type"in e&&e.type==="text"&&"text"in e&&e.text!=null&&typeof e.text=="object"&&"value"in e.text&&typeof e.text.value=="string"))throw new Error('"assistant_message" parts expect an object with an "id", "role", and "content" property.');return{type:"assistant_message",value:t}}},xr={code:"5",name:"assistant_control_data",parse:t=>{if(t==null||typeof t!="object"||!("threadId"in t)||!("messageId"in t)||typeof t.threadId!="string"||typeof t.messageId!="string")throw new Error('"assistant_control_data" parts expect an object with a "threadId" and "messageId" property.');return{type:"assistant_control_data",value:{threadId:t.threadId,messageId:t.messageId}}}},Ar={code:"6",name:"data_message",parse:t=>{if(t==null||typeof t!="object"||!("role"in t)||!("data"in t)||typeof t.role!="string"||t.role!=="data")throw new Error('"data_message" parts expect an object with a "role" and "data" property.');return{type:"data_message",value:t}}},od=[_r,br,wr,xr,Ar];_r.code+"",br.code+"",wr.code+"",xr.code+"",Ar.code+"";_r.name+"",_r.code,br.name+"",br.code,wr.name+"",wr.code,xr.name+"",xr.code,Ar.name+"",Ar.code;od.map(t=>t.code);function ld(t){const e=["ROOT"];let r=-1,n=null;function s(l,c,d){switch(l){case'"':{r=c,e.pop(),e.push(d),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,n=c,e.pop(),e.push(d),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(d),e.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c,e.pop(),e.push(d),e.push("INSIDE_NUMBER");break}case"{":{r=c,e.pop(),e.push(d),e.push("INSIDE_OBJECT_START");break}case"[":{r=c,e.pop(),e.push(d),e.push("INSIDE_ARRAY_START");break}}}function a(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,e.pop();break}}}function i(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,e.pop();break}}}for(let l=0;l<t.length;l++){const c=t[l];switch(e[e.length-1]){case"ROOT":s(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{a(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{e.pop(),r=l;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,e.pop();break}default:{r=l,s(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,e.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.pop(),r=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l;break}case"e":case"E":case"-":case".":break;case",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&a(c,l);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&a(c,l);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{const p=t.substring(n,l+1);!"false".startsWith(p)&&!"true".startsWith(p)&&!"null".startsWith(p)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?a(c,l):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l)):r=l;break}}}let o=t.slice(0,r+1);for(let l=e.length-1;l>=0;l--)switch(e[l]){case"INSIDE_STRING":{o+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{o+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{o+="]";break}case"INSIDE_LITERAL":{const d=t.substring(n,t.length);"true".startsWith(d)?o+="true".slice(d.length):"false".startsWith(d)?o+="false".slice(d.length):"null".startsWith(d)&&(o+="null".slice(d.length))}}return o}function cd(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let e=It({text:t});return e.success?{value:e.value,state:"successful-parse"}:(e=It({text:ld(t)}),e.success?{value:e.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var ud={code:"0",name:"text",parse:t=>{if(typeof t!="string")throw new Error('"text" parts expect a string value.');return{type:"text",value:t}}},dd={code:"2",name:"data",parse:t=>{if(!Array.isArray(t))throw new Error('"data" parts expect an array value.');return{type:"data",value:t}}},pd={code:"3",name:"error",parse:t=>{if(typeof t!="string")throw new Error('"error" parts expect a string value.');return{type:"error",value:t}}},hd={code:"8",name:"message_annotations",parse:t=>{if(!Array.isArray(t))throw new Error('"message_annotations" parts expect an array value.');return{type:"message_annotations",value:t}}},fd={code:"9",name:"tool_call",parse:t=>{if(t==null||typeof t!="object"||!("toolCallId"in t)||typeof t.toolCallId!="string"||!("toolName"in t)||typeof t.toolName!="string"||!("args"in t)||typeof t.args!="object")throw new Error('"tool_call" parts expect an object with a "toolCallId", "toolName", and "args" property.');return{type:"tool_call",value:t}}},md={code:"a",name:"tool_result",parse:t=>{if(t==null||typeof t!="object"||!("toolCallId"in t)||typeof t.toolCallId!="string"||!("result"in t))throw new Error('"tool_result" parts expect an object with a "toolCallId" and a "result" property.');return{type:"tool_result",value:t}}},gd={code:"b",name:"tool_call_streaming_start",parse:t=>{if(t==null||typeof t!="object"||!("toolCallId"in t)||typeof t.toolCallId!="string"||!("toolName"in t)||typeof t.toolName!="string")throw new Error('"tool_call_streaming_start" parts expect an object with a "toolCallId" and "toolName" property.');return{type:"tool_call_streaming_start",value:t}}},yd={code:"c",name:"tool_call_delta",parse:t=>{if(t==null||typeof t!="object"||!("toolCallId"in t)||typeof t.toolCallId!="string"||!("argsTextDelta"in t)||typeof t.argsTextDelta!="string")throw new Error('"tool_call_delta" parts expect an object with a "toolCallId" and "argsTextDelta" property.');return{type:"tool_call_delta",value:t}}},vd={code:"d",name:"finish_message",parse:t=>{if(t==null||typeof t!="object"||!("finishReason"in t)||typeof t.finishReason!="string")throw new Error('"finish_message" parts expect an object with a "finishReason" property.');const e={finishReason:t.finishReason};return"usage"in t&&t.usage!=null&&typeof t.usage=="object"&&"promptTokens"in t.usage&&"completionTokens"in t.usage&&(e.usage={promptTokens:typeof t.usage.promptTokens=="number"?t.usage.promptTokens:Number.NaN,completionTokens:typeof t.usage.completionTokens=="number"?t.usage.completionTokens:Number.NaN}),{type:"finish_message",value:e}}},_d={code:"e",name:"finish_step",parse:t=>{if(t==null||typeof t!="object"||!("finishReason"in t)||typeof t.finishReason!="string")throw new Error('"finish_step" parts expect an object with a "finishReason" property.');const e={finishReason:t.finishReason,isContinued:!1};return"usage"in t&&t.usage!=null&&typeof t.usage=="object"&&"promptTokens"in t.usage&&"completionTokens"in t.usage&&(e.usage={promptTokens:typeof t.usage.promptTokens=="number"?t.usage.promptTokens:Number.NaN,completionTokens:typeof t.usage.completionTokens=="number"?t.usage.completionTokens:Number.NaN}),"isContinued"in t&&typeof t.isContinued=="boolean"&&(e.isContinued=t.isContinued),{type:"finish_step",value:e}}},bd={code:"f",name:"start_step",parse:t=>{if(t==null||typeof t!="object"||!("messageId"in t)||typeof t.messageId!="string")throw new Error('"start_step" parts expect an object with an "id" property.');return{type:"start_step",value:{messageId:t.messageId}}}},wd={code:"g",name:"reasoning",parse:t=>{if(typeof t!="string")throw new Error('"reasoning" parts expect a string value.');return{type:"reasoning",value:t}}},xd={code:"h",name:"source",parse:t=>{if(t==null||typeof t!="object")throw new Error('"source" parts expect a Source object.');return{type:"source",value:t}}},Ad={code:"i",name:"redacted_reasoning",parse:t=>{if(t==null||typeof t!="object"||!("data"in t)||typeof t.data!="string")throw new Error('"redacted_reasoning" parts expect an object with a "data" property.');return{type:"redacted_reasoning",value:{data:t.data}}}},Sd={code:"j",name:"reasoning_signature",parse:t=>{if(t==null||typeof t!="object"||!("signature"in t)||typeof t.signature!="string")throw new Error('"reasoning_signature" parts expect an object with a "signature" property.');return{type:"reasoning_signature",value:{signature:t.signature}}}},_n=[ud,dd,pd,hd,fd,md,gd,yd,vd,_d,bd,wd,xd,Ad,Sd];Object.fromEntries(_n.map(t=>[t.code,t]));Object.fromEntries(_n.map(t=>[t.name,t.code]));_n.map(t=>t.code);function Oi(t,e){const r=_n.find(n=>n.name===t);if(!r)throw new Error(`Invalid stream part type: ${t}`);return`${r.code}:${JSON.stringify(e)}
185
+ `}function kd(t,e){var r;const n=(r=void 0)!=null?r:!1;return Xn(id(t,{$refStrategy:n?"root":"none",target:"jsonSchema7"}),{validate:s=>{const a=t.safeParse(s);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}var Kn=Symbol.for("vercel.ai.schema");function Xn(t,{validate:e}={}){return{[Kn]:!0,_type:void 0,[Yr]:!0,jsonSchema:t,validate:e}}function Ed(t){return typeof t=="object"&&t!==null&&Kn in t&&t[Kn]===!0&&"jsonSchema"in t&&"validate"in t}function Qn(t){return Ed(t)?t:kd(t)}var Td=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},st="1.9.0",ca=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function $d(t){var e=new Set([t]),r=new Set,n=t.match(ca);if(!n)return function(){return!1};var s={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(s.prerelease!=null)return function(l){return l===t};function a(o){return r.add(o),!1}function i(o){return e.add(o),!0}return function(l){if(e.has(l))return!0;if(r.has(l))return!1;var c=l.match(ca);if(!c)return a(l);var d={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return d.prerelease!=null||s.major!==d.major?a(l):s.major===0?s.minor===d.minor&&s.patch<=d.patch?i(l):a(l):s.minor<=d.minor?i(l):a(l)}}var Id=$d(st),Cd=st.split(".")[0],Sr=Symbol.for("opentelemetry.js.api."+Cd),kr=Td;function ms(t,e,r,n){var s;n===void 0&&(n=!1);var a=kr[Sr]=(s=kr[Sr])!==null&&s!==void 0?s:{version:st};if(!n&&a[t]){var i=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(i.stack||i.message),!1}if(a.version!==st){var i=new Error("@opentelemetry/api: Registration of version v"+a.version+" for "+t+" does not match previously registered API v"+st);return r.error(i.stack||i.message),!1}return a[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+st+"."),!0}function Er(t){var e,r,n=(e=kr[Sr])===null||e===void 0?void 0:e.version;if(!(!n||!Id(n)))return(r=kr[Sr])===null||r===void 0?void 0:r[t]}function gs(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+st+".");var r=kr[Sr];r&&delete r[t]}var Od=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,a=[],i;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)a.push(s.value)}catch(o){i={error:o}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a},Pd=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,a;n<s;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},Rd=function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Vt("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Vt("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Vt("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Vt("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Vt("verbose",this._namespace,e)},t}();function Vt(t,e,r){var n=Er("diag");if(n)return r.unshift(e),n[t].apply(n,Pd([],Od(r),!1))}var oe;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(oe||(oe={}));function jd(t,e){t<oe.NONE?t=oe.NONE:t>oe.ALL&&(t=oe.ALL),e=e||{};function r(n,s){var a=e[n];return typeof a=="function"&&t>=s?a.bind(e):function(){}}return{error:r("error",oe.ERROR),warn:r("warn",oe.WARN),info:r("info",oe.INFO),debug:r("debug",oe.DEBUG),verbose:r("verbose",oe.VERBOSE)}}var Nd=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,a=[],i;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)a.push(s.value)}catch(o){i={error:o}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a},Md=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,a;n<s;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},Dd="diag",ln=function(){function t(){function e(s){return function(){for(var a=[],i=0;i<arguments.length;i++)a[i]=arguments[i];var o=Er("diag");if(o)return o[s].apply(o,Md([],Nd(a),!1))}}var r=this,n=function(s,a){var i,o,l;if(a===void 0&&(a={logLevel:oe.INFO}),s===r){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((i=c.stack)!==null&&i!==void 0?i:c.message),!1}typeof a=="number"&&(a={logLevel:a});var d=Er("diag"),p=jd((o=a.logLevel)!==null&&o!==void 0?o:oe.INFO,s);if(d&&!a.suppressOverrideMessage){var g=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+g),p.warn("Current logger will overwrite one already registered from "+g)}return ms("diag",p,r,!0)};r.setLogger=n,r.disable=function(){gs(Dd,r)},r.createComponentLogger=function(s){return new Rd(s)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t}();function Zd(t){return Symbol.for(t)}var Ud=function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,s){var a=new t(r._currentContext);return a._currentContext.set(n,s),a},r.deleteValue=function(n){var s=new t(r._currentContext);return s._currentContext.delete(n),s}}return t}(),Ld=new Ud,Fd=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,a=[],i;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)a.push(s.value)}catch(o){i={error:o}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a},Vd=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,a;n<s;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},Bd=function(){function t(){}return t.prototype.active=function(){return Ld},t.prototype.with=function(e,r,n){for(var s=[],a=3;a<arguments.length;a++)s[a-3]=arguments[a];return r.call.apply(r,Vd([n],Fd(s),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}(),zd=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,a=[],i;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)a.push(s.value)}catch(o){i={error:o}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a},qd=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,a;n<s;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},Rn="context",Hd=new Bd,Pi=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return ms(Rn,e,ln.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,n){for(var s,a=[],i=3;i<arguments.length;i++)a[i-3]=arguments[i];return(s=this._getContextManager()).with.apply(s,qd([e,r,n],zd(a),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return Er(Rn)||Hd},t.prototype.disable=function(){this._getContextManager().disable(),gs(Rn,ln.instance())},t}(),es;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(es||(es={}));var Ri="0000000000000000",ji="00000000000000000000000000000000",Jd={traceId:ji,spanId:Ri,traceFlags:es.NONE},Xt=function(){function t(e){e===void 0&&(e=Jd),this._spanContext=e}return t.prototype.spanContext=function(){return this._spanContext},t.prototype.setAttribute=function(e,r){return this},t.prototype.setAttributes=function(e){return this},t.prototype.addEvent=function(e,r){return this},t.prototype.addLink=function(e){return this},t.prototype.addLinks=function(e){return this},t.prototype.setStatus=function(e){return this},t.prototype.updateName=function(e){return this},t.prototype.end=function(e){},t.prototype.isRecording=function(){return!1},t.prototype.recordException=function(e,r){},t}(),ys=Zd("OpenTelemetry Context Key SPAN");function vs(t){return t.getValue(ys)||void 0}function Wd(){return vs(Pi.getInstance().active())}function _s(t,e){return t.setValue(ys,e)}function Gd(t){return t.deleteValue(ys)}function Yd(t,e){return _s(t,new Xt(e))}function Ni(t){var e;return(e=vs(t))===null||e===void 0?void 0:e.spanContext()}var Kd=/^([0-9a-f]{32})$/i,Xd=/^[0-9a-f]{16}$/i;function Qd(t){return Kd.test(t)&&t!==ji}function ep(t){return Xd.test(t)&&t!==Ri}function Mi(t){return Qd(t.traceId)&&ep(t.spanId)}function tp(t){return new Xt(t)}var jn=Pi.getInstance(),Di=function(){function t(){}return t.prototype.startSpan=function(e,r,n){n===void 0&&(n=jn.active());var s=!!(r!=null&&r.root);if(s)return new Xt;var a=n&&Ni(n);return rp(a)&&Mi(a)?new Xt(a):new Xt},t.prototype.startActiveSpan=function(e,r,n,s){var a,i,o;if(!(arguments.length<2)){arguments.length===2?o=r:arguments.length===3?(a=r,o=n):(a=r,i=n,o=s);var l=i??jn.active(),c=this.startSpan(e,a,l),d=_s(l,c);return jn.with(d,o,void 0,c)}},t}();function rp(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var np=new Di,sp=function(){function t(e,r,n,s){this._provider=e,this.name=r,this.version=n,this.options=s}return t.prototype.startSpan=function(e,r,n){return this._getTracer().startSpan(e,r,n)},t.prototype.startActiveSpan=function(e,r,n,s){var a=this._getTracer();return Reflect.apply(a.startActiveSpan,a,arguments)},t.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):np},t}(),ap=function(){function t(){}return t.prototype.getTracer=function(e,r,n){return new Di},t}(),ip=new ap,ua=function(){function t(){}return t.prototype.getTracer=function(e,r,n){var s;return(s=this.getDelegateTracer(e,r,n))!==null&&s!==void 0?s:new sp(this,e,r,n)},t.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:ip},t.prototype.setDelegate=function(e){this._delegate=e},t.prototype.getDelegateTracer=function(e,r,n){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(e,r,n)},t}(),cn;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(cn||(cn={}));var Nn="trace",op=function(){function t(){this._proxyTracerProvider=new ua,this.wrapSpanContext=tp,this.isSpanContextValid=Mi,this.deleteSpan=Gd,this.getSpan=vs,this.getActiveSpan=Wd,this.getSpanContext=Ni,this.setSpan=_s,this.setSpanContext=Yd}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(e){var r=ms(Nn,this._proxyTracerProvider,ln.instance());return r&&this._proxyTracerProvider.setDelegate(e),r},t.prototype.getTracerProvider=function(){return Er(Nn)||this._proxyTracerProvider},t.prototype.getTracer=function(e,r){return this.getTracerProvider().getTracer(e,r)},t.prototype.disable=function(){gs(Nn,ln.instance()),this._proxyTracerProvider=new ua},t}(),lp=op.getInstance(),cp=Object.defineProperty,bs=(t,e)=>{for(var r in e)cp(t,r,{get:e[r],enumerable:!0})};function ws(t,{contentType:e,dataStreamVersion:r}){const n=new Headers(t??{});return n.has("Content-Type")||n.set("Content-Type",e),r!==void 0&&n.set("X-Vercel-AI-Data-Stream",r),n}var Zi="AI_InvalidArgumentError",Ui=`vercel.ai.error.${Zi}`,up=Symbol.for(Ui),Li,L=class extends O{constructor({parameter:t,value:e,message:r}){super({name:Zi,message:`Invalid argument for parameter ${t}: ${r}`}),this[Li]=!0,this.parameter=t,this.value=e}static isInstance(t){return O.hasMarker(t,Ui)}};Li=up;var Fi="AI_RetryError",Vi=`vercel.ai.error.${Fi}`,dp=Symbol.for(Vi),Bi,da=class extends O{constructor({message:t,reason:e,errors:r}){super({name:Fi,message:t}),this[Bi]=!0,this.reason=e,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return O.hasMarker(t,Vi)}};Bi=dp;var pp=({maxRetries:t=2,initialDelayInMs:e=2e3,backoffFactor:r=2}={})=>async n=>zi(n,{maxRetries:t,delayInMs:e,backoffFactor:r});async function zi(t,{maxRetries:e,delayInMs:r,backoffFactor:n},s=[]){try{return await t()}catch(a){if(Zr(a)||e===0)throw a;const i=Ml(a),o=[...s,a],l=o.length;if(l>e)throw new da({message:`Failed after ${l} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:o});if(a instanceof Error&&Te.isInstance(a)&&a.isRetryable===!0&&l<=e)return await Nl(r),zi(t,{maxRetries:e,delayInMs:n*r,backoffFactor:n},o);throw l===1?a:new da({message:`Failed after ${l} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:o})}}function hp({maxRetries:t}){if(t!=null){if(!Number.isInteger(t))throw new L({parameter:"maxRetries",value:t,message:"maxRetries must be an integer"});if(t<0)throw new L({parameter:"maxRetries",value:t,message:"maxRetries must be >= 0"})}const e=t??2;return{maxRetries:e,retry:pp({maxRetries:e})}}function Mn({operationId:t,telemetry:e}){return{"operation.name":`${t}${(e==null?void 0:e.functionId)!=null?` ${e.functionId}`:""}`,"resource.name":e==null?void 0:e.functionId,"ai.operationId":t,"ai.telemetry.functionId":e==null?void 0:e.functionId}}function fp({model:t,settings:e,telemetry:r,headers:n}){var s;return{"ai.model.provider":t.provider,"ai.model.id":t.modelId,...Object.entries(e).reduce((a,[i,o])=>(a[`ai.settings.${i}`]=o,a),{}),...Object.entries((s=r==null?void 0:r.metadata)!=null?s:{}).reduce((a,[i,o])=>(a[`ai.telemetry.metadata.${i}`]=o,a),{}),...Object.entries(n??{}).reduce((a,[i,o])=>(o!==void 0&&(a[`ai.request.headers.${i}`]=o),a),{})}}var mp={startSpan(){return jr},startActiveSpan(t,e,r,n){if(typeof e=="function")return e(jr);if(typeof r=="function")return r(jr);if(typeof n=="function")return n(jr)}},jr={spanContext(){return gp},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},gp={traceId:"",spanId:"",traceFlags:0};function yp({isEnabled:t=!1,tracer:e}={}){return t?e||lp.getTracer("ai"):mp}function Dn({name:t,tracer:e,attributes:r,fn:n,endWhenDone:s=!0}){return e.startActiveSpan(t,{attributes:r},async a=>{try{const i=await n(a);return s&&a.end(),i}catch(i){try{i instanceof Error?(a.recordException({name:i.name,message:i.message,stack:i.stack}),a.setStatus({code:cn.ERROR,message:i.message})):a.setStatus({code:cn.ERROR})}finally{a.end()}throw i}})}function mt({telemetry:t,attributes:e}){return(t==null?void 0:t.isEnabled)!==!0?{}:Object.entries(e).reduce((r,[n,s])=>{if(s===void 0)return r;if(typeof s=="object"&&"input"in s&&typeof s.input=="function"){if((t==null?void 0:t.recordInputs)===!1)return r;const a=s.input();return a===void 0?r:{...r,[n]:a}}if(typeof s=="object"&&"output"in s&&typeof s.output=="function"){if((t==null?void 0:t.recordOutputs)===!1)return r;const a=s.output();return a===void 0?r:{...r,[n]:a}}return{...r,[n]:s}},{})}var qi="AI_NoObjectGeneratedError",Hi=`vercel.ai.error.${qi}`,vp=Symbol.for(Hi),Ji,Le=class extends O{constructor({message:t="No object generated.",cause:e,text:r,response:n,usage:s}){super({name:qi,message:t,cause:e}),this[Ji]=!0,this.text=r,this.response=n,this.usage=s}static isInstance(t){return O.hasMarker(t,Hi)}};Ji=vp;var Wi="AI_DownloadError",Gi=`vercel.ai.error.${Wi}`,_p=Symbol.for(Gi),Yi,Zn=class extends O{constructor({url:t,statusCode:e,statusText:r,cause:n,message:s=n==null?`Failed to download ${t}: ${e} ${r}`:`Failed to download ${t}: ${n}`}){super({name:Wi,message:s,cause:n}),this[Yi]=!0,this.url=t,this.statusCode=e,this.statusText=r}static isInstance(t){return O.hasMarker(t,Gi)}};Yi=_p;async function bp({url:t,fetchImplementation:e=fetch}){var r;const n=t.toString();try{const s=await e(n);if(!s.ok)throw new Zn({url:n,statusCode:s.status,statusText:s.statusText});return{data:new Uint8Array(await s.arrayBuffer()),mimeType:(r=s.headers.get("content-type"))!=null?r:void 0}}catch(s){throw Zn.isInstance(s)?s:new Zn({url:n,cause:s})}}var wp=[{mimeType:"image/gif",bytes:[71,73,70]},{mimeType:"image/png",bytes:[137,80,78,71]},{mimeType:"image/jpeg",bytes:[255,216]},{mimeType:"image/webp",bytes:[82,73,70,70]}];function xp(t){for(const{bytes:e,mimeType:r}of wp)if(t.length>=e.length&&e.every((n,s)=>t[s]===n))return r}var Ki="AI_InvalidDataContentError",Xi=`vercel.ai.error.${Ki}`,Ap=Symbol.for(Xi),Qi,pa=class extends O{constructor({content:t,cause:e,message:r=`Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof t}.`}){super({name:Ki,message:r,cause:e}),this[Qi]=!0,this.content=t}static isInstance(t){return O.hasMarker(t,Xi)}};Qi=Ap;var eo=u.union([u.string(),u.instanceof(Uint8Array),u.instanceof(ArrayBuffer),u.custom(t=>{var e,r;return(r=(e=globalThis.Buffer)==null?void 0:e.isBuffer(t))!=null?r:!1},{message:"Must be a Buffer"})]);function Sp(t){return typeof t=="string"?t:t instanceof ArrayBuffer?qn(new Uint8Array(t)):qn(t)}function un(t){if(t instanceof Uint8Array)return t;if(typeof t=="string")try{return Yl(t)}catch(e){throw new pa({message:"Invalid data content. Content string is not a base64-encoded media.",content:t,cause:e})}if(t instanceof ArrayBuffer)return new Uint8Array(t);throw new pa({content:t})}function kp(t){try{return new TextDecoder().decode(t)}catch{throw new Error("Error decoding Uint8Array to text")}}var to="AI_InvalidMessageRoleError",ro=`vercel.ai.error.${to}`,Ep=Symbol.for(ro),no,Tp=class extends O{constructor({role:t,message:e=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:to,message:e}),this[no]=!0,this.role=t}static isInstance(t){return O.hasMarker(t,ro)}};no=Ep;function $p(t){try{const[e,r]=t.split(",");return{mimeType:e.split(";")[0].split(":")[1],base64Content:r}}catch{return{mimeType:void 0,base64Content:void 0}}}async function ha({prompt:t,modelSupportsImageUrls:e=!0,modelSupportsUrl:r=()=>!1,downloadImplementation:n=bp}){const s=await Cp(t.messages,n,e,r);return[...t.system!=null?[{role:"system",content:t.system}]:[],...t.messages.map(a=>Ip(a,s))]}function Ip(t,e){var r,n,s,a,i,o;const l=t.role;switch(l){case"system":return{role:"system",content:t.content,providerMetadata:(r=t.providerOptions)!=null?r:t.experimental_providerMetadata};case"user":return typeof t.content=="string"?{role:"user",content:[{type:"text",text:t.content}],providerMetadata:(n=t.providerOptions)!=null?n:t.experimental_providerMetadata}:{role:"user",content:t.content.map(c=>Op(c,e)).filter(c=>c.type!=="text"||c.text!==""),providerMetadata:(s=t.providerOptions)!=null?s:t.experimental_providerMetadata};case"assistant":return typeof t.content=="string"?{role:"assistant",content:[{type:"text",text:t.content}],providerMetadata:(a=t.providerOptions)!=null?a:t.experimental_providerMetadata}:{role:"assistant",content:t.content.filter(c=>c.type!=="text"||c.text!=="").map(c=>{const{experimental_providerMetadata:d,providerOptions:p,...g}=c;return{...g,providerMetadata:p??d}}),providerMetadata:(i=t.providerOptions)!=null?i:t.experimental_providerMetadata};case"tool":return{role:"tool",content:t.content.map(c=>{var d;return{type:"tool-result",toolCallId:c.toolCallId,toolName:c.toolName,result:c.result,content:c.experimental_content,isError:c.isError,providerMetadata:(d=c.providerOptions)!=null?d:c.experimental_providerMetadata}}),providerMetadata:(o=t.providerOptions)!=null?o:t.experimental_providerMetadata};default:{const c=l;throw new Tp({role:c})}}}async function Cp(t,e,r,n){const s=t.filter(i=>i.role==="user").map(i=>i.content).filter(i=>Array.isArray(i)).flat().filter(i=>i.type==="image"||i.type==="file").filter(i=>!(i.type==="image"&&r===!0)).map(i=>i.type==="image"?i.image:i.data).map(i=>typeof i=="string"&&(i.startsWith("http:")||i.startsWith("https:"))?new URL(i):i).filter(i=>i instanceof URL).filter(i=>!n(i)),a=await Promise.all(s.map(async i=>({url:i,data:await e({url:i})})));return Object.fromEntries(a.map(({url:i,data:o})=>[i.toString(),o]))}function Op(t,e){var r,n,s,a;if(t.type==="text")return{type:"text",text:t.text,providerMetadata:(r=t.providerOptions)!=null?r:t.experimental_providerMetadata};let i=t.mimeType,o,l,c;const d=t.type;switch(d){case"image":o=t.image;break;case"file":o=t.data;break;default:throw new Error(`Unsupported part type: ${d}`)}try{l=typeof o=="string"?new URL(o):o}catch{l=o}if(l instanceof URL)if(l.protocol==="data:"){const{mimeType:p,base64Content:g}=$p(l.toString());if(p==null||g==null)throw new Error(`Invalid data URL format in part ${d}`);i=p,c=un(g)}else{const p=e[l.toString()];p?(c=p.data,i??(i=p.mimeType)):c=l}else c=un(l);switch(d){case"image":return c instanceof Uint8Array&&(i=(n=xp(c))!=null?n:i),{type:"image",image:c,mimeType:i,providerMetadata:(s=t.providerOptions)!=null?s:t.experimental_providerMetadata};case"file":{if(i==null)throw new Error("Mime type is missing for file part");return{type:"file",data:c instanceof Uint8Array?Sp(c):c,mimeType:i,providerMetadata:(a=t.providerOptions)!=null?a:t.experimental_providerMetadata}}}}function fa({maxTokens:t,temperature:e,topP:r,topK:n,presencePenalty:s,frequencyPenalty:a,stopSequences:i,seed:o}){if(t!=null){if(!Number.isInteger(t))throw new L({parameter:"maxTokens",value:t,message:"maxTokens must be an integer"});if(t<1)throw new L({parameter:"maxTokens",value:t,message:"maxTokens must be >= 1"})}if(e!=null&&typeof e!="number")throw new L({parameter:"temperature",value:e,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new L({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new L({parameter:"topK",value:n,message:"topK must be a number"});if(s!=null&&typeof s!="number")throw new L({parameter:"presencePenalty",value:s,message:"presencePenalty must be a number"});if(a!=null&&typeof a!="number")throw new L({parameter:"frequencyPenalty",value:a,message:"frequencyPenalty must be a number"});if(o!=null&&!Number.isInteger(o))throw new L({parameter:"seed",value:o,message:"seed must be an integer"});return{maxTokens:t,temperature:e??0,topP:r,topK:n,presencePenalty:s,frequencyPenalty:a,stopSequences:i!=null&&i.length>0?i:void 0,seed:o}}function Pp(t){var e,r,n;const s=[];for(const a of t){let i;try{i=new URL(a.url)}catch{throw new Error(`Invalid URL: ${a.url}`)}switch(i.protocol){case"http:":case"https:":{if((e=a.contentType)!=null&&e.startsWith("image/"))s.push({type:"image",image:i});else{if(!a.contentType)throw new Error("If the attachment is not an image, it must specify a content type");s.push({type:"file",data:i,mimeType:a.contentType})}break}case"data:":{let o,l,c;try{[o,l]=a.url.split(","),c=o.split(";")[0].split(":")[1]}catch{throw new Error(`Error processing data URL: ${a.url}`)}if(c==null||l==null)throw new Error(`Invalid data URL format: ${a.url}`);if((r=a.contentType)!=null&&r.startsWith("image/"))s.push({type:"image",image:un(l)});else if((n=a.contentType)!=null&&n.startsWith("text/"))s.push({type:"text",text:kp(un(l))});else{if(!a.contentType)throw new Error("If the attachment is not an image or text, it must specify a content type");s.push({type:"file",data:l,mimeType:a.contentType})}break}default:throw new Error(`Unsupported URL protocol: ${i.protocol}`)}}return s}var so="AI_MessageConversionError",ao=`vercel.ai.error.${so}`,Rp=Symbol.for(ao),io,Un=class extends O{constructor({originalMessage:t,message:e}){super({name:so,message:e}),this[io]=!0,this.originalMessage=t}static isInstance(t){return O.hasMarker(t,ao)}};io=Rp;function jp(t,e){var r,n;const s=(r=e==null?void 0:e.tools)!=null?r:{},a=[];for(let i=0;i<t.length;i++){const o=t[i],l=i===t.length-1,{role:c,content:d,experimental_attachments:p}=o;switch(c){case"system":{a.push({role:"system",content:d});break}case"user":{a.push({role:"user",content:p?[{type:"text",text:d},...Pp(p)]:d});break}case"assistant":{if(o.parts!=null){let y=function(){const k=[];for(const P of A)switch(P.type){case"text":k.push({type:"text",text:P.text});break;case"reasoning":{for(const R of P.details)switch(R.type){case"text":k.push({type:"reasoning",text:R.text,signature:R.signature});break;case"redacted":k.push({type:"redacted-reasoning",data:R.data});break}break}case"tool-invocation":k.push({type:"tool-call",toolCallId:P.toolInvocation.toolCallId,toolName:P.toolInvocation.toolName,args:P.toolInvocation.args});break;default:{const R=P;throw new Error(`Unsupported part: ${R}`)}}a.push({role:"assistant",content:k});const T=A.filter(P=>P.type==="tool-invocation").map(P=>P.toolInvocation);T.length>0&&a.push({role:"tool",content:T.map(P=>{if(!("result"in P))throw new Un({originalMessage:o,message:"ToolInvocation must have a result: "+JSON.stringify(P)});const{toolCallId:R,toolName:z,result:I}=P,Y=s[z];return(Y==null?void 0:Y.experimental_toToolResultContent)!=null?{type:"tool-result",toolCallId:R,toolName:z,result:Y.experimental_toToolResultContent(I),experimental_content:Y.experimental_toToolResultContent(I)}:{type:"tool-result",toolCallId:R,toolName:z,result:I}})}),A=[],v=!1,m++},m=0,v=!1,A=[];for(const k of o.parts)switch(k.type){case"reasoning":A.push(k);break;case"text":{v&&y(),A.push(k);break}case"tool-invocation":{((n=k.toolInvocation.step)!=null?n:0)!==m&&y(),A.push(k),v=!0;break}}y();break}const g=o.toolInvocations;if(g==null||g.length===0){a.push({role:"assistant",content:d});break}const w=g.reduce((y,m)=>{var v;return Math.max(y,(v=m.step)!=null?v:0)},0);for(let y=0;y<=w;y++){const m=g.filter(v=>{var A;return((A=v.step)!=null?A:0)===y});m.length!==0&&(a.push({role:"assistant",content:[...l&&d&&y===0?[{type:"text",text:d}]:[],...m.map(({toolCallId:v,toolName:A,args:k})=>({type:"tool-call",toolCallId:v,toolName:A,args:k}))]}),a.push({role:"tool",content:m.map(v=>{if(!("result"in v))throw new Un({originalMessage:o,message:"ToolInvocation must have a result: "+JSON.stringify(v)});const{toolCallId:A,toolName:k,result:T}=v,P=s[k];return(P==null?void 0:P.experimental_toToolResultContent)!=null?{type:"tool-result",toolCallId:A,toolName:k,result:P.experimental_toToolResultContent(T),experimental_content:P.experimental_toToolResultContent(T)}:{type:"tool-result",toolCallId:A,toolName:k,result:T}})}))}d&&!l&&a.push({role:"assistant",content:d});break}case"data":break;default:{const g=c;throw new Un({originalMessage:o,message:`Unsupported role: ${g}`})}}}return a}function Np(t){if(!Array.isArray(t))return"other";if(t.length===0)return"messages";const e=t.map(Mp);return e.some(r=>r==="has-ui-specific-parts")?"ui-messages":e.every(r=>r==="has-core-specific-parts"||r==="message")?"messages":"other"}function Mp(t){return typeof t=="object"&&t!==null&&(t.role==="function"||t.role==="data"||"toolInvocations"in t||"experimental_attachments"in t)?"has-ui-specific-parts":typeof t=="object"&&t!==null&&"content"in t&&(Array.isArray(t.content)||"experimental_providerMetadata"in t||"providerOptions"in t)?"has-core-specific-parts":typeof t=="object"&&t!==null&&"role"in t&&"content"in t&&typeof t.content=="string"&&["system","user","assistant","tool"].includes(t.role)?"message":"other"}var ts=u.lazy(()=>u.union([u.null(),u.string(),u.number(),u.boolean(),u.record(u.string(),ts),u.array(ts)])),q=u.record(u.string(),u.record(u.string(),ts)),Dp=u.array(u.union([u.object({type:u.literal("text"),text:u.string()}),u.object({type:u.literal("image"),data:u.string(),mimeType:u.string().optional()})])),oo=u.object({type:u.literal("text"),text:u.string(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Zp=u.object({type:u.literal("image"),image:u.union([eo,u.instanceof(URL)]),mimeType:u.string().optional(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Up=u.object({type:u.literal("file"),data:u.union([eo,u.instanceof(URL)]),mimeType:u.string(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Lp=u.object({type:u.literal("reasoning"),text:u.string(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Fp=u.object({type:u.literal("redacted-reasoning"),data:u.string(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Vp=u.object({type:u.literal("tool-call"),toolCallId:u.string(),toolName:u.string(),args:u.unknown(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Bp=u.object({type:u.literal("tool-result"),toolCallId:u.string(),toolName:u.string(),result:u.unknown(),content:Dp.optional(),isError:u.boolean().optional(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),zp=u.object({role:u.literal("system"),content:u.string(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),qp=u.object({role:u.literal("user"),content:u.union([u.string(),u.array(u.union([oo,Zp,Up]))]),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Hp=u.object({role:u.literal("assistant"),content:u.union([u.string(),u.array(u.union([oo,Lp,Fp,Vp]))]),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Jp=u.object({role:u.literal("tool"),content:u.array(Bp),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Wp=u.union([zp,qp,Hp,Jp]);function ma({prompt:t,tools:e}){if(t.prompt==null&&t.messages==null)throw new et({prompt:t,message:"prompt or messages must be defined"});if(t.prompt!=null&&t.messages!=null)throw new et({prompt:t,message:"prompt and messages cannot be defined at the same time"});if(t.system!=null&&typeof t.system!="string")throw new et({prompt:t,message:"system must be a string"});if(t.prompt!=null){if(typeof t.prompt!="string")throw new et({prompt:t,message:"prompt must be a string"});return{type:"prompt",system:t.system,messages:[{role:"user",content:t.prompt}]}}if(t.messages!=null){const r=Np(t.messages);if(r==="other")throw new et({prompt:t,message:"messages must be an array of CoreMessage or UIMessage"});const n=r==="ui-messages"?jp(t.messages,{tools:e}):t.messages,s=ot({value:n,schema:u.array(Wp)});if(!s.success)throw new et({prompt:t,message:"messages must be an array of CoreMessage or UIMessage",cause:s.error});return{type:"messages",messages:n,system:t.system}}throw new Error("unreachable")}function gt({promptTokens:t,completionTokens:e}){return{promptTokens:t,completionTokens:e,totalTokens:t+e}}var Gp="JSON schema:",Yp="You MUST answer with a JSON object that matches the JSON schema above.",Kp="You MUST answer with JSON.";function rs({prompt:t,schema:e,schemaPrefix:r=e!=null?Gp:void 0,schemaSuffix:n=e!=null?Yp:Kp}){return[t!=null&&t.length>0?t:void 0,t!=null&&t.length>0?"":void 0,r,e!=null?JSON.stringify(e):void 0,n].filter(s=>s!=null).join(`
186
+ `)}function Xp(t){const e=t.pipeThrough(new TransformStream);return e[Symbol.asyncIterator]=()=>{const r=e.getReader();return{async next(){const{done:n,value:s}=await r.read();return n?{done:!0,value:void 0}:{done:!1,value:s}}}},e}var Qp={type:"no-schema",jsonSchema:void 0,validatePartialResult({value:t,textDelta:e}){return{success:!0,value:{partial:t,textDelta:e}}},validateFinalResult(t,e){return t===void 0?{success:!1,error:new Le({message:"No object generated: response did not match schema.",text:e.text,response:e.response,usage:e.usage})}:{success:!0,value:t}},createElementStream(){throw new G({functionality:"element streams in no-schema mode"})}},eh=t=>({type:"object",jsonSchema:t.jsonSchema,validatePartialResult({value:e,textDelta:r}){return{success:!0,value:{partial:e,textDelta:r}}},validateFinalResult(e){return ot({value:e,schema:t})},createElementStream(){throw new G({functionality:"element streams in object mode"})}}),th=t=>{const{$schema:e,...r}=t.jsonSchema;return{type:"enum",jsonSchema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:r}},required:["elements"],additionalProperties:!1},validatePartialResult({value:n,latestObject:s,isFirstDelta:a,isFinalDelta:i}){var o;if(!zn(n)||!Ys(n.elements))return{success:!1,error:new je({value:n,cause:"value must be an object that contains an array of elements"})};const l=n.elements,c=[];for(let g=0;g<l.length;g++){const w=l[g],y=ot({value:w,schema:t});if(!(g===l.length-1&&!i)){if(!y.success)return y;c.push(y.value)}}const d=(o=s==null?void 0:s.length)!=null?o:0;let p="";return a&&(p+="["),d>0&&(p+=","),p+=c.slice(d).map(g=>JSON.stringify(g)).join(","),i&&(p+="]"),{success:!0,value:{partial:c,textDelta:p}}},validateFinalResult(n){if(!zn(n)||!Ys(n.elements))return{success:!1,error:new je({value:n,cause:"value must be an object that contains an array of elements"})};const s=n.elements;for(const a of s){const i=ot({value:a,schema:t});if(!i.success)return i}return{success:!0,value:s}},createElementStream(n){let s=0;return Xp(n.pipeThrough(new TransformStream({transform(a,i){switch(a.type){case"object":{const o=a.object;for(;s<o.length;s++)i.enqueue(o[s]);break}case"text-delta":case"finish":case"error":break;default:{const o=a;throw new Error(`Unsupported chunk type: ${o}`)}}}})))}}},rh=t=>({type:"enum",jsonSchema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:t}},required:["result"],additionalProperties:!1},validateFinalResult(e){if(!zn(e)||typeof e.result!="string")return{success:!1,error:new je({value:e,cause:'value must be an object that contains a string in the "result" property.'})};const r=e.result;return t.includes(r)?{success:!0,value:r}:{success:!1,error:new je({value:e,cause:"value must be a string in the enum"})}},validatePartialResult(){throw new G({functionality:"partial results in enum mode"})},createElementStream(){throw new G({functionality:"element streams in enum mode"})}});function nh({output:t,schema:e,enumValues:r}){switch(t){case"object":return eh(Qn(e));case"array":return th(Qn(e));case"enum":return rh(r);case"no-schema":return Qp;default:{const n=t;throw new Error(`Unsupported output: ${n}`)}}}function sh({output:t,mode:e,schema:r,schemaName:n,schemaDescription:s,enumValues:a}){if(t!=null&&t!=="object"&&t!=="array"&&t!=="enum"&&t!=="no-schema")throw new L({parameter:"output",value:t,message:"Invalid output type."});if(t==="no-schema"){if(e==="auto"||e==="tool")throw new L({parameter:"mode",value:e,message:'Mode must be "json" for no-schema output.'});if(r!=null)throw new L({parameter:"schema",value:r,message:"Schema is not supported for no-schema output."});if(s!=null)throw new L({parameter:"schemaDescription",value:s,message:"Schema description is not supported for no-schema output."});if(n!=null)throw new L({parameter:"schemaName",value:n,message:"Schema name is not supported for no-schema output."});if(a!=null)throw new L({parameter:"enumValues",value:a,message:"Enum values are not supported for no-schema output."})}if(t==="object"){if(r==null)throw new L({parameter:"schema",value:r,message:"Schema is required for object output."});if(a!=null)throw new L({parameter:"enumValues",value:a,message:"Enum values are not supported for object output."})}if(t==="array"){if(r==null)throw new L({parameter:"schema",value:r,message:"Element schema is required for array output."});if(a!=null)throw new L({parameter:"enumValues",value:a,message:"Enum values are not supported for array output."})}if(t==="enum"){if(r!=null)throw new L({parameter:"schema",value:r,message:"Schema is not supported for enum output."});if(s!=null)throw new L({parameter:"schemaDescription",value:s,message:"Schema description is not supported for enum output."});if(n!=null)throw new L({parameter:"schemaName",value:n,message:"Schema name is not supported for enum output."});if(a==null)throw new L({parameter:"enumValues",value:a,message:"Enum values are required for enum output."});for(const i of a)if(typeof i!="string")throw new L({parameter:"enumValues",value:i,message:"Enum values must be strings."})}}var ah=pt({prefix:"aiobj",size:24});async function ih({model:t,enum:e,schema:r,schemaName:n,schemaDescription:s,mode:a,output:i="object",system:o,prompt:l,messages:c,maxRetries:d,abortSignal:p,headers:g,experimental_repairText:w,experimental_telemetry:y,experimental_providerMetadata:m,providerOptions:v=m,_internal:{generateId:A=ah,currentDate:k=()=>new Date}={},...T}){sh({output:i,mode:a,schema:r,schemaName:n,schemaDescription:s,enumValues:e});const{maxRetries:P,retry:R}=hp({maxRetries:d}),z=nh({output:i,schema:r,enumValues:e});z.type==="no-schema"&&a===void 0&&(a="json");const I=fp({model:t,telemetry:y,headers:g,settings:{...T,maxRetries:P}}),Y=yp(y);return Dn({name:"ai.generateObject",attributes:mt({telemetry:y,attributes:{...Mn({operationId:"ai.generateObject",telemetry:y}),...I,"ai.prompt":{input:()=>JSON.stringify({system:o,prompt:l,messages:c})},"ai.schema":z.jsonSchema!=null?{input:()=>JSON.stringify(z.jsonSchema)}:void 0,"ai.schema.name":n,"ai.schema.description":s,"ai.settings.output":z.type,"ai.settings.mode":a}}),tracer:Y,fn:async ht=>{var We,Ge,Ye,Ce;(a==="auto"||a==null)&&(a=t.defaultObjectGenerationMode);let ie,xe,ce,ft,V,se,H,D,bn;switch(a){case"json":{const J=ma({prompt:{system:z.jsonSchema==null?rs({prompt:o}):t.supportsStructuredOutputs?o:rs({prompt:o,schema:z.jsonSchema}),prompt:l,messages:c},tools:void 0}),ue=await ha({prompt:J,modelSupportsImageUrls:t.supportsImageUrls,modelSupportsUrl:(We=t.supportsUrl)==null?void 0:We.bind(t)}),Q=await R(()=>Dn({name:"ai.generateObject.doGenerate",attributes:mt({telemetry:y,attributes:{...Mn({operationId:"ai.generateObject.doGenerate",telemetry:y}),...I,"ai.prompt.format":{input:()=>J.type},"ai.prompt.messages":{input:()=>JSON.stringify(ue)},"ai.settings.mode":a,"gen_ai.system":t.provider,"gen_ai.request.model":t.modelId,"gen_ai.request.frequency_penalty":T.frequencyPenalty,"gen_ai.request.max_tokens":T.maxTokens,"gen_ai.request.presence_penalty":T.presencePenalty,"gen_ai.request.temperature":T.temperature,"gen_ai.request.top_k":T.topK,"gen_ai.request.top_p":T.topP}}),tracer:Y,fn:async he=>{var Or,Nt,Mt,Dt,Zt,Ut;const K=await t.doGenerate({mode:{type:"object-json",schema:z.jsonSchema,name:n,description:s},...fa(T),inputFormat:J.type,prompt:ue,providerMetadata:v,abortSignal:p,headers:g}),Ae={id:(Nt=(Or=K.response)==null?void 0:Or.id)!=null?Nt:A(),timestamp:(Dt=(Mt=K.response)==null?void 0:Mt.timestamp)!=null?Dt:k(),modelId:(Ut=(Zt=K.response)==null?void 0:Zt.modelId)!=null?Ut:t.modelId};if(K.text===void 0)throw new Le({message:"No object generated: the model did not return a response.",response:Ae,usage:gt(K.usage)});return he.setAttributes(mt({telemetry:y,attributes:{"ai.response.finishReason":K.finishReason,"ai.response.object":{output:()=>K.text},"ai.response.id":Ae.id,"ai.response.model":Ae.modelId,"ai.response.timestamp":Ae.timestamp.toISOString(),"ai.usage.promptTokens":K.usage.promptTokens,"ai.usage.completionTokens":K.usage.completionTokens,"gen_ai.response.finish_reasons":[K.finishReason],"gen_ai.response.id":Ae.id,"gen_ai.response.model":Ae.modelId,"gen_ai.usage.prompt_tokens":K.usage.promptTokens,"gen_ai.usage.completion_tokens":K.usage.completionTokens}})),{...K,objectText:K.text,responseData:Ae}}}));ie=Q.objectText,xe=Q.finishReason,ce=Q.usage,ft=Q.warnings,V=Q.rawResponse,D=Q.logprobs,bn=Q.providerMetadata,H=(Ge=Q.request)!=null?Ge:{},se=Q.responseData;break}case"tool":{const J=ma({prompt:{system:o,prompt:l,messages:c},tools:void 0}),ue=await ha({prompt:J,modelSupportsImageUrls:t.supportsImageUrls,modelSupportsUrl:(Ye=t.supportsUrl)==null?void 0:Ye.bind(t)}),Q=J.type,he=await R(()=>Dn({name:"ai.generateObject.doGenerate",attributes:mt({telemetry:y,attributes:{...Mn({operationId:"ai.generateObject.doGenerate",telemetry:y}),...I,"ai.prompt.format":{input:()=>Q},"ai.prompt.messages":{input:()=>JSON.stringify(ue)},"ai.settings.mode":a,"gen_ai.system":t.provider,"gen_ai.request.model":t.modelId,"gen_ai.request.frequency_penalty":T.frequencyPenalty,"gen_ai.request.max_tokens":T.maxTokens,"gen_ai.request.presence_penalty":T.presencePenalty,"gen_ai.request.temperature":T.temperature,"gen_ai.request.top_k":T.topK,"gen_ai.request.top_p":T.topP}}),tracer:Y,fn:async Or=>{var Nt,Mt,Dt,Zt,Ut,K,Ae,Ts;const de=await t.doGenerate({mode:{type:"object-tool",tool:{type:"function",name:n??"json",description:s??"Respond with a JSON object.",parameters:z.jsonSchema}},...fa(T),inputFormat:Q,prompt:ue,providerMetadata:v,abortSignal:p,headers:g}),wn=(Mt=(Nt=de.toolCalls)==null?void 0:Nt[0])==null?void 0:Mt.args,Ke={id:(Zt=(Dt=de.response)==null?void 0:Dt.id)!=null?Zt:A(),timestamp:(K=(Ut=de.response)==null?void 0:Ut.timestamp)!=null?K:k(),modelId:(Ts=(Ae=de.response)==null?void 0:Ae.modelId)!=null?Ts:t.modelId};if(wn===void 0)throw new Le({message:"No object generated: the tool was not called.",response:Ke,usage:gt(de.usage)});return Or.setAttributes(mt({telemetry:y,attributes:{"ai.response.finishReason":de.finishReason,"ai.response.object":{output:()=>wn},"ai.response.id":Ke.id,"ai.response.model":Ke.modelId,"ai.response.timestamp":Ke.timestamp.toISOString(),"ai.usage.promptTokens":de.usage.promptTokens,"ai.usage.completionTokens":de.usage.completionTokens,"gen_ai.response.finish_reasons":[de.finishReason],"gen_ai.response.id":Ke.id,"gen_ai.response.model":Ke.modelId,"gen_ai.usage.input_tokens":de.usage.promptTokens,"gen_ai.usage.output_tokens":de.usage.completionTokens}})),{...de,objectText:wn,responseData:Ke}}}));ie=he.objectText,xe=he.finishReason,ce=he.usage,ft=he.warnings,V=he.rawResponse,D=he.logprobs,bn=he.providerMetadata,H=(Ce=he.request)!=null?Ce:{},se=he.responseData;break}case void 0:throw new Error("Model does not have a default object generation mode.");default:{const J=a;throw new Error(`Unsupported mode: ${J}`)}}function Es(J){const ue=It({text:J});if(!ue.success)throw new Le({message:"No object generated: could not parse the response.",cause:ue.error,text:J,response:se,usage:gt(ce)});const Q=z.validateFinalResult(ue.value,{text:J,response:se,usage:gt(ce)});if(!Q.success)throw new Le({message:"No object generated: response did not match schema.",cause:Q.error,text:J,response:se,usage:gt(ce)});return Q.value}let Cr;try{Cr=Es(ie)}catch(J){if(w!=null&&Le.isInstance(J)&&(ar.isInstance(J.cause)||je.isInstance(J.cause))){const ue=await w({text:ie,error:J.cause});if(ue===null)throw J;Cr=Es(ue)}else throw J}return ht.setAttributes(mt({telemetry:y,attributes:{"ai.response.finishReason":xe,"ai.response.object":{output:()=>JSON.stringify(Cr)},"ai.usage.promptTokens":ce.promptTokens,"ai.usage.completionTokens":ce.completionTokens}})),new oh({object:Cr,finishReason:xe,usage:gt(ce),warnings:ft,request:H,response:{...se,headers:V==null?void 0:V.headers,body:V==null?void 0:V.body},logprobs:D,providerMetadata:bn})}})}var oh=class{constructor(t){this.object=t.object,this.finishReason=t.finishReason,this.usage=t.usage,this.warnings=t.warnings,this.providerMetadata=t.providerMetadata,this.experimental_providerMetadata=t.providerMetadata,this.response=t.response,this.request=t.request,this.logprobs=t.logprobs}toJsonResponse(t){var e;return new Response(JSON.stringify(this.object),{status:(e=t==null?void 0:t.status)!=null?e:200,headers:ws(t==null?void 0:t.headers,{contentType:"application/json; charset=utf-8"})})}};pt({prefix:"aiobj",size:24});pt({prefix:"aitxt",size:24});pt({prefix:"msg",size:24});var lh={};bs(lh,{object:()=>uh,text:()=>ch});var ch=()=>({type:"text",responseFormat:()=>({type:"text"}),injectIntoSystemPrompt({system:t}){return t},parsePartial({text:t}){return{partial:t}},parseOutput({text:t}){return t}}),uh=({schema:t})=>{const e=Qn(t);return{type:"object",responseFormat:({model:r})=>({type:"json",schema:r.supportsStructuredOutputs?e.jsonSchema:void 0}),injectIntoSystemPrompt({system:r,model:n}){return n.supportsStructuredOutputs?r:rs({prompt:r,schema:e.jsonSchema})},parsePartial({text:r}){const n=cd(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:n.value};default:{const s=n.state;throw new Error(`Unsupported parse state: ${s}`)}}},parseOutput({text:r},n){const s=It({text:r});if(!s.success)throw new Le({message:"No object generated: could not parse the response.",cause:s.error,text:r,response:n.response,usage:n.usage});const a=ot({value:s.value,schema:e});if(!a.success)throw new Le({message:"No object generated: response did not match schema.",cause:a.error,text:r,response:n.response,usage:n.usage});return a.value}}};function lo(t,e){const r=t.getReader(),n=e.getReader();let s,a,i=!1,o=!1;async function l(d){try{s==null&&(s=r.read());const p=await s;s=void 0,p.done?d.close():d.enqueue(p.value)}catch(p){d.error(p)}}async function c(d){try{a==null&&(a=n.read());const p=await a;a=void 0,p.done?d.close():d.enqueue(p.value)}catch(p){d.error(p)}}return new ReadableStream({async pull(d){try{if(i){await c(d);return}if(o){await l(d);return}s==null&&(s=r.read()),a==null&&(a=n.read());const{result:p,reader:g}=await Promise.race([s.then(w=>({result:w,reader:r})),a.then(w=>({result:w,reader:n}))]);p.done||d.enqueue(p.value),g===r?(s=void 0,p.done&&(await c(d),i=!0)):(a=void 0,p.done&&(o=!0,await l(d)))}catch(p){d.error(p)}},cancel(){r.cancel(),n.cancel()}})}pt({prefix:"aitxt",size:24});pt({prefix:"msg",size:24});var dh={};bs(dh,{mergeIntoDataStream:()=>fh,toDataStream:()=>ph,toDataStreamResponse:()=>hh});function co(t={}){const e=new TextEncoder;let r="";return new TransformStream({async start(){t.onStart&&await t.onStart()},async transform(n,s){s.enqueue(e.encode(n)),r+=n,t.onToken&&await t.onToken(n),t.onText&&typeof n=="string"&&await t.onText(n)},async flush(){t.onCompletion&&await t.onCompletion(r),t.onFinal&&await t.onFinal(r)}})}function xs(t,e){return t.pipeThrough(new TransformStream({transform:async(r,n)=>{var s;if(typeof r=="string"){n.enqueue(r);return}if("event"in r){r.event==="on_chat_model_stream"&&ga((s=r.data)==null?void 0:s.chunk,n);return}ga(r,n)}})).pipeThrough(co(e)).pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform:async(r,n)=>{n.enqueue(Oi("text",r))}}))}function ph(t,e){return xs(t,e).pipeThrough(new TextEncoderStream)}function hh(t,e){var r;const n=xs(t,e==null?void 0:e.callbacks).pipeThrough(new TextEncoderStream),s=e==null?void 0:e.data,a=e==null?void 0:e.init,i=s?lo(s.stream,n):n;return new Response(i,{status:(r=a==null?void 0:a.status)!=null?r:200,statusText:a==null?void 0:a.statusText,headers:ws(a==null?void 0:a.headers,{contentType:"text/plain; charset=utf-8",dataStreamVersion:"v1"})})}function fh(t,e){e.dataStream.merge(xs(t,e.callbacks))}function ga(t,e){if(typeof t.content=="string")e.enqueue(t.content);else{const r=t.content;for(const n of r)n.type==="text"&&e.enqueue(n.text)}}var mh={};bs(mh,{mergeIntoDataStream:()=>vh,toDataStream:()=>gh,toDataStreamResponse:()=>yh});function As(t,e){const r=_h();return jl(t[Symbol.asyncIterator]()).pipeThrough(new TransformStream({async transform(n,s){s.enqueue(r(n.delta))}})).pipeThrough(co(e)).pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform:async(n,s)=>{s.enqueue(Oi("text",n))}}))}function gh(t,e){return As(t,e).pipeThrough(new TextEncoderStream)}function yh(t,e={}){var r;const{init:n,data:s,callbacks:a}=e,i=As(t,a).pipeThrough(new TextEncoderStream),o=s?lo(s.stream,i):i;return new Response(o,{status:(r=n==null?void 0:n.status)!=null?r:200,statusText:n==null?void 0:n.statusText,headers:ws(n==null?void 0:n.headers,{contentType:"text/plain; charset=utf-8",dataStreamVersion:"v1"})})}function vh(t,e){e.dataStream.merge(As(t,e.callbacks))}function _h(){let t=!0;return e=>(t&&(e=e.trimStart(),e&&(t=!1)),e)}function bh(t){return t?` In this environment you have access to a set of tools. Here are the functions available in JSONSchema format:
187
+ ${JSON.stringify(t.actions)}
188
+ This is the start data that the tools have provided: ${JSON.stringify(t.data)}
189
+ Choose to respond as text and/or one or more functions to call to respond to the user's query.
190
+ `:void 0}function wh(t){if(!t)return Xn({type:"object",properties:{text:{type:"string"}},additionalProperties:!1});const e={type:"object",properties:{text:{type:"string"},tools:{type:"array",items:{anyOf:Object.keys(t.actions).map(r=>{const n=t.actions[r],s={type:"object",properties:{id:{type:"string",enum:[r]}},additionalProperties:!1,required:["id"]};return n.params_schema&&!Pa(n.params_schema.properties)&&(s.properties.arguments=n.params_schema,s.properties.arguments.required||(s.properties.arguments.required=Object.keys(s.properties.arguments.properties)),s.properties.arguments.additionalProperties=!1,s.required.push("arguments")),s})},additionalProperties:!1}},additionalProperties:!1};return Xn(e)}async function xh(t,e,r){var p;const n=JSON.stringify(e),s=n?`${n}
191
+ ${t}`:t,a=(p=ae.get().settings)==null?void 0:p.openAIAPIToken,o=ki({apiKey:a,compatibility:"strict"})("gpt-4o-mini"),l=bh(r),c=wh(r),{object:d}=await ih({model:o,prompt:s,system:l,schema:c});return d}const Ah={getModelResponse:xh};var Sh=Object.defineProperty,kh=Object.getOwnPropertyDescriptor,Ss=(t,e,r,n)=>{for(var s=n>1?void 0:n?kh(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=(n?i(e,r,s):i(s))||s);return n&&s&&Sh(e,r,s),s};let dn=class extends re{constructor(){super(...arguments),this.openAIAPIToken="",this.promptState="idle"}createRenderRoot(){return this}connectedCallback(){ae.subscribe(t=>{var e;this.openAIAPIToken=(e=t.settings)==null?void 0:e.openAIAPIToken}),super.connectedCallback()}async onSubmit(t){t.preventDefault();const r=t.target.elements.namedItem("prompt"),n=r.value.trim();if(!n)return;const s=Jr.getRecentInteractions();this.promptState="thinking",r.value="";const a=await Ah.getModelResponse(n,s,window.applet),i=[];a.text&&i.push({type:"text",content:a.text}),a.tools&&a.tools.length>0&&await Promise.all(a.tools.map(async o=>{await window.applet.sendAction(o.id,o.arguments),i.push({type:o.id,arguments:o.arguments}),window.applet.data&&i.push({type:"data",content:window.applet.data})})),Jr.addInteraction({input:{type:"command",text:n},outputs:i,timestamp:Date.now()}),this.promptState="idle",setTimeout(()=>document.getElementById("prompt").focus())}render(){return U`
192
+ <form @submit="${this.onSubmit}">
193
+ <input
194
+ autocomplete="off"
195
+ id="prompt"
196
+ name="prompt"
197
+ autofocus
198
+ .disabled="${!this.openAIAPIToken||this.promptState==="thinking"}"
199
+ placeholder="${this.openAIAPIToken?this.promptState==="thinking"?"Thinking…":"Start typing to interact…":"Update your OpenAI API key in the settings dialog to interact via the prompt."}"
200
+ />
201
+ ${this.promptState==="thinking"?U`
202
+ <svg
203
+ xmlns="http://www.w3.org/2000/svg"
204
+ width="24"
205
+ height="24"
206
+ viewBox="0 0 24 24"
207
+ fill="none"
208
+ stroke="currentColor"
209
+ stroke-width="1"
210
+ stroke-linecap="round"
211
+ stroke-linejoin="round"
212
+ class="loader"
213
+ >
214
+ <circle cx="12" cy="12" r="9" />
215
+ </svg>
216
+ `:F}
217
+ </form>
218
+ `}};Ss([X({type:String})],dn.prototype,"openAIAPIToken",2);Ss([X({type:String})],dn.prototype,"promptState",2);dn=Ss([we("app-prompt")],dn);var Eh=Object.defineProperty,Th=Object.getOwnPropertyDescriptor,uo=(t,e,r,n)=>{for(var s=n>1?void 0:n?Th(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=(n?i(e,r,s):i(s))||s);return n&&s&&Eh(e,r,s),s};let ns=class extends re{constructor(){super(...arguments),this.interactions=[]}createRenderRoot(){return this}connectedCallback(){super.connectedCallback(),this.unsubscribe=Jr.subscribe(t=>{this.interactions=[...t]})}disconnectedCallback(){this.unsubscribe&&this.unsubscribe(),super.disconnectedCallback()}render(){const t=e=>Object.entries(e).filter(([r])=>r!=="type").map(([r,n])=>typeof n=="object"&&n!==null?`${r}: ${JSON.stringify(n)}`:`${r}: ${n}`).join(", ");return U`
219
+ <div class="history">
220
+ ${this.interactions.length<=0?U`
221
+ <div class="action-output">
222
+ <span class="status-message">Enter a message below to interact</span>
223
+ </div>
224
+ `:U``}
225
+ ${this.interactions.map(e=>{const r=e.input.type==="command"?U`
226
+ <div class="bubble-container user-bubble-container">
227
+ <div class="bubble user">
228
+ <strong>You:</strong>
229
+ <span>${e.input.text}</span>
230
+ </div>
231
+ </div>
232
+ `:U``,n=e.outputs.filter(s=>s.type!=="data").map(s=>e.input.type==="command"?s.type==="text"?U`
233
+ <div class="bubble-container assistant-bubble-container">
234
+ <div class="bubble assistant">
235
+ <strong>Assistant:</strong>
236
+ <span>${s.content}</span>
237
+ </div>
238
+ </div>
239
+ `:U`
240
+ <div class="action-output">
241
+ <strong>Action: ${s.type}</strong>
242
+ <span>${t(s)}</span>
243
+ </div>
244
+ `:e.input.type==="action"?U`
245
+ <div class="action-output">
246
+ <strong>Action: ${e.input.text}</strong>
247
+ <span>{${t(s)}}</span>
248
+ </div>
249
+ `:U``);return U`${r}${n}`})}
250
+ </div>
251
+ `}};uo([No()],ns.prototype,"interactions",2);ns=uo([we("app-history")],ns);/**
252
+ * @license
253
+ * Copyright 2020 Google LLC
254
+ * SPDX-License-Identifier: BSD-3-Clause
255
+ */const $h=t=>t.strings===void 0;/**
256
+ * @license
257
+ * Copyright 2017 Google LLC
258
+ * SPDX-License-Identifier: BSD-3-Clause
259
+ */const Qt=(t,e)=>{var n;const r=t._$AN;if(r===void 0)return!1;for(const s of r)(n=s._$AO)==null||n.call(s,e,!1),Qt(s,e);return!0},pn=t=>{let e,r;do{if((e=t._$AM)===void 0)break;r=e._$AN,r.delete(t),t=e}while((r==null?void 0:r.size)===0)},po=t=>{for(let e;e=t._$AM;t=e){let r=e._$AN;if(r===void 0)e._$AN=r=new Set;else if(r.has(t))break;r.add(t),Oh(e)}};function Ih(t){this._$AN!==void 0?(pn(this),this._$AM=t,po(this)):this._$AM=t}function Ch(t,e=!1,r=0){const n=this._$AH,s=this._$AN;if(s!==void 0&&s.size!==0)if(e)if(Array.isArray(n))for(let a=r;a<n.length;a++)Qt(n[a],!1),pn(n[a]);else n!=null&&(Qt(n,!1),pn(n));else Qt(this,t)}const Oh=t=>{t.type==ls.CHILD&&(t._$AP??(t._$AP=Ch),t._$AQ??(t._$AQ=Ih))};class Ph extends us{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,r,n){super._$AT(e,r,n),po(this),this.isConnected=e._$AU}_$AO(e,r=!0){var n,s;e!==this.isConnected&&(this.isConnected=e,e?(n=this.reconnected)==null||n.call(this):(s=this.disconnected)==null||s.call(this)),r&&(Qt(this,e),pn(this))}setValue(e){if($h(this._$Ct))this._$Ct._$AI(e,this);else{const r=[...this._$Ct._$AH];r[this._$Ci]=e,this._$Ct._$AI(r,this,0)}}disconnected(){}reconnected(){}}/**
260
+ * @license
261
+ * Copyright 2020 Google LLC
262
+ * SPDX-License-Identifier: BSD-3-Clause
263
+ */const ya=()=>new Rh;class Rh{}const Ln=new WeakMap,va=cs(class extends Ph{render(t){return F}update(t,[e]){var n;const r=e!==this.Y;return r&&this.Y!==void 0&&this.rt(void 0),(r||this.lt!==this.ct)&&(this.Y=e,this.ht=(n=t.options)==null?void 0:n.host,this.rt(this.ct=t.element)),F}rt(t){if(this.isConnected||(t=void 0),typeof this.Y=="function"){const e=this.ht??globalThis;let r=Ln.get(e);r===void 0&&(r=new WeakMap,Ln.set(e,r)),r.get(this.Y)!==void 0&&this.Y.call(this.ht,void 0),r.set(this.Y,t),t!==void 0&&this.Y.call(this.ht,t)}else this.Y.value=t}get lt(){var t,e;return typeof this.Y=="function"?(t=Ln.get(this.ht??globalThis))==null?void 0:t.get(this.Y):(e=this.Y)==null?void 0:e.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});var jh=Object.defineProperty,Nh=Object.getOwnPropertyDescriptor,ks=(t,e,r,n)=>{for(var s=n>1?void 0:n?Nh(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=(n?i(e,r,s):i(s))||s);return n&&s&&jh(e,r,s),s};let hn=class extends re{constructor(){super(...arguments),this.open=!1,this.openAIAPIToken="",this.dialogRef=ya(),this.formRef=ya()}createRenderRoot(){return this}connectedCallback(){ae.subscribe(t=>{var e;this.openAIAPIToken=(e=t.settings)==null?void 0:e.openAIAPIToken,this.open=t.settingsDialogOpen}),super.connectedCallback()}updated(t){var e,r;t.has("open")&&(this.open?(e=this.dialogRef.value)==null||e.showModal():(r=this.dialogRef.value)==null||r.close())}onSave(t){t.preventDefault();const n=t.target.elements.namedItem("openAIAPIToken").value,s=ae.get().settings;ae.update({settings:{openAIAPIToken:n,...s}}),this.onDismiss()}onClear(t){t.preventDefault();const e=ae.get().settings;delete e.openAIAPIToken,ae.update({settings:e})}onDismiss(){var t;(t=this.formRef.value)==null||t.reset(),ae.update({settingsDialogOpen:!1})}render(){return U`
264
+ <dialog ${va(this.dialogRef)}>
265
+ <div class="dialog-header">
266
+ <h2>Settings</h2>
267
+ <button
268
+ aria-label="close dialog"
269
+ class="close-dialog-button"
270
+ @click="${this.onDismiss}"
271
+ >
272
+ <svg
273
+ focusable="false"
274
+ xmlns="http://www.w3.org/2000/svg"
275
+ width="24"
276
+ height="24"
277
+ viewBox="0 0 24 24"
278
+ fill="none"
279
+ stroke="currentColor"
280
+ stroke-width="1"
281
+ stroke-linecap="round"
282
+ stroke-linejoin="round"
283
+ >
284
+ <path d="M18 6 6 18" />
285
+ <path d="m6 6 12 12" />
286
+ </svg>
287
+ </button>
288
+ </div>
289
+ <div class="dialog-content">
290
+ <form
291
+ ${va(this.formRef)}
292
+ id="settings-form"
293
+ class="settings-form"
294
+ @submit="${this.onSave}"
295
+ >
296
+ <fieldset .disabled=${!!this.openAIAPIToken}>
297
+ <label for="openAIAPIToken">OpenAI API token</label>
298
+
299
+ <input
300
+ id="openAIAPIToken"
301
+ name="openAIAPIToken"
302
+ placeholder="${this.openAIAPIToken?"••••••••••••••••••••":""}"
303
+ />
304
+ </fieldset>
305
+ ${this.openAIAPIToken?U`<button
306
+ class="clear-button"
307
+ ?disabled=${!1}
308
+ @click="${this.onClear}"
309
+ >
310
+ Clear
311
+ </button>`:F}
312
+ </form>
313
+ </div>
314
+ <div class="dialog-footer">
315
+ <button type="submit" form="settings-form">Save</button>
316
+ <button @click="${this.onDismiss}">Cancel</button>
317
+ </div>
318
+ </dialog>
319
+ `}};ks([X({type:Boolean})],hn.prototype,"open",2);ks([X({type:String})],hn.prototype,"openAIAPIToken",2);hn=ks([we("settings-dialog")],hn);var Mh=Object.getOwnPropertyDescriptor,Dh=(t,e,r,n)=>{for(var s=n>1?void 0:n?Mh(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=i(s)||s);return s};let _a=class extends re{createRenderRoot(){return this}render(){return U`
320
+ <app-header></app-header>
321
+ <main>
322
+ <app-sidebar class="open"></app-sidebar>
323
+ <app-viewer></app-viewer>
324
+ <app-history class="open">
325
+ <app-prompt></app-prompt>
326
+ </app-history>
327
+ </main>
328
+ <settings-dialog></settings-dialog>
329
+ `}};_a=Dh([we("app-root")],_a);
@@ -4,8 +4,8 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>Web Applets Inspector</title>
7
- <script type="module" crossorigin src="/assets/index-Hy6Hlya-.js"></script>
8
- <link rel="stylesheet" crossorigin href="/assets/index-DGr96Ien.css">
7
+ <script type="module" crossorigin src="/assets/index-pfsnt6mc.js"></script>
8
+ <link rel="stylesheet" crossorigin href="/assets/index-DMvTov1R.css">
9
9
  </head>
10
10
  <body>
11
11
  <app-root></app-root>
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "license": "MIT",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
- "version": "0.2.5",
7
+ "version": "0.2.6",
8
8
  "description": "An inspector CLI for web applets.",
9
9
  "scripts": {
10
10
  "start": "npm run build && node dist/index.js",