@web-applets/inspector 0.1.3 → 0.2.0-alpha.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,266 +0,0 @@
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 Sr=globalThis,Ln=Sr.ShadowRoot&&(Sr.ShadyCSS===void 0||Sr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,qs=Symbol(),is=new WeakMap;let Di=class{constructor(e,r,n){if(this._$cssResult$=!0,n!==qs)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(Ln&&e===void 0){const n=r!==void 0&&r.length===1;n&&(e=is.get(r)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&is.set(r,e))}return e}toString(){return this.cssText}};const Zi=t=>new Di(typeof t=="string"?t:t+"",void 0,qs),Ui=(t,e)=>{if(Ln)t.adoptedStyleSheets=e.map(r=>r instanceof CSSStyleSheet?r:r.styleSheet);else for(const r of e){const n=document.createElement("style"),s=Sr.litNonce;s!==void 0&&n.setAttribute("nonce",s),n.textContent=r.cssText,t.appendChild(n)}},os=Ln?t=>t:t=>t instanceof CSSStyleSheet?(e=>{let r="";for(const n of e.cssRules)r+=n.cssText;return Zi(r)})(t):t;/**
6
- * @license
7
- * Copyright 2017 Google LLC
8
- * SPDX-License-Identifier: BSD-3-Clause
9
- */const{is:Li,defineProperty:Fi,getOwnPropertyDescriptor:Vi,getOwnPropertyNames:Bi,getOwnPropertySymbols:zi,getPrototypeOf:qi}=Object,Ce=globalThis,ls=Ce.trustedTypes,Ji=ls?ls.emptyScript:"",on=Ce.reactiveElementPolyfillSupport,It=(t,e)=>t,Or={toAttribute(t,e){switch(e){case Boolean:t=t?Ji: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}},Fn=(t,e)=>!Li(t,e),cs={attribute:!0,type:String,converter:Or,reflect:!1,hasChanged:Fn};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Ce.litPropertyMetadata??(Ce.litPropertyMetadata=new WeakMap);class nt 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=cs){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&&Fi(this.prototype,e,s)}}static getPropertyDescriptor(e,r,n){const{get:s,set:a}=Vi(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)??cs}static _$Ei(){if(this.hasOwnProperty(It("elementProperties")))return;const e=qi(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(It("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(It("properties"))){const r=this.properties,n=[...Bi(r),...zi(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(os(s))}else e!==void 0&&r.push(os(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 Ui(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:Or).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:Or;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??Fn)(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){}}nt.elementStyles=[],nt.shadowRootOptions={mode:"open"},nt[It("elementProperties")]=new Map,nt[It("finalized")]=new Map,on==null||on({ReactiveElement:nt}),(Ce.reactiveElementVersions??(Ce.reactiveElementVersions=[])).push("2.0.4");/**
10
- * @license
11
- * Copyright 2017 Google LLC
12
- * SPDX-License-Identifier: BSD-3-Clause
13
- */const $t=globalThis,Rr=$t.trustedTypes,us=Rr?Rr.createPolicy("lit-html",{createHTML:t=>t}):void 0,Js="$lit$",Ie=`lit$${Math.random().toFixed(9).slice(2)}$`,Hs="?"+Ie,Hi=`<${Hs}>`,We=document,Pt=()=>We.createComment(""),jt=t=>t===null||typeof t!="object"&&typeof t!="function",Vn=Array.isArray,Wi=t=>Vn(t)||typeof(t==null?void 0:t[Symbol.iterator])=="function",ln=`[
14
- \f\r]`,xt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ds=/-->/g,ps=/>/g,Fe=RegExp(`>|${ln}(?:([^\\s"'>=/]+)(${ln}*=${ln}*(?:[^
15
- \f\r"'\`<>=]|("|')|))|$)`,"g"),hs=/'/g,fs=/"/g,Ws=/^(?:script|style|textarea|title)$/i,Gi=t=>(e,...r)=>({_$litType$:t,strings:e,values:r}),H=Gi(1),ot=Symbol.for("lit-noChange"),Z=Symbol.for("lit-nothing"),ms=new WeakMap,ze=We.createTreeWalker(We,129);function Gs(t,e){if(!Vn(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return us!==void 0?us.createHTML(e):e}const Yi=(t,e)=>{const r=t.length-1,n=[];let s,a=e===2?"<svg>":e===3?"<math>":"",i=xt;for(let o=0;o<r;o++){const l=t[o];let c,d,p=-1,y=0;for(;y<l.length&&(i.lastIndex=y,d=i.exec(l),d!==null);)y=i.lastIndex,i===xt?d[1]==="!--"?i=ds:d[1]!==void 0?i=ps:d[2]!==void 0?(Ws.test(d[2])&&(s=RegExp("</"+d[2],"g")),i=Fe):d[3]!==void 0&&(i=Fe):i===Fe?d[0]===">"?(i=s??xt,p=-1):d[1]===void 0?p=-2:(p=i.lastIndex-d[2].length,c=d[1],i=d[3]===void 0?Fe:d[3]==='"'?fs:hs):i===fs||i===hs?i=Fe:i===ds||i===ps?i=xt:(i=Fe,s=void 0);const v=i===Fe&&t[o+1].startsWith("/>")?" ":"";a+=i===xt?l+Hi:p>=0?(n.push(c),l.slice(0,p)+Js+l.slice(p)+Ie+v):l+Ie+(p===-2?o:v)}return[Gs(t,a+(t[r]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]};class Nt{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]=Yi(e,r);if(this.el=Nt.createElement(c,n),ze.currentNode=this.el.content,r===2||r===3){const p=this.el.content.firstChild;p.replaceWith(...p.childNodes)}for(;(s=ze.nextNode())!==null&&l.length<o;){if(s.nodeType===1){if(s.hasAttributes())for(const p of s.getAttributeNames())if(p.endsWith(Js)){const y=d[i++],v=s.getAttribute(p).split(Ie),x=/([.?@])?(.*)/.exec(y);l.push({type:1,index:a,name:x[2],strings:v,ctor:x[1]==="."?Xi:x[1]==="?"?Qi:x[1]==="@"?eo:en}),s.removeAttribute(p)}else p.startsWith(Ie)&&(l.push({type:6,index:a}),s.removeAttribute(p));if(Ws.test(s.tagName)){const p=s.textContent.split(Ie),y=p.length-1;if(y>0){s.textContent=Rr?Rr.emptyScript:"";for(let v=0;v<y;v++)s.append(p[v],Pt()),ze.nextNode(),l.push({type:2,index:++a});s.append(p[y],Pt())}}}else if(s.nodeType===8)if(s.data===Hs)l.push({type:2,index:a});else{let p=-1;for(;(p=s.data.indexOf(Ie,p+1))!==-1;)l.push({type:7,index:a}),p+=Ie.length-1}a++}}static createElement(e,r){const n=We.createElement("template");return n.innerHTML=e,n}}function lt(t,e,r=t,n){var i,o;if(e===ot)return e;let s=n!==void 0?(i=r._$Co)==null?void 0:i[n]:r._$Cl;const a=jt(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=lt(t,s._$AS(t,e.values),s,n)),e}class Ki{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)??We).importNode(r,!0);ze.currentNode=s;let a=ze.nextNode(),i=0,o=0,l=n[0];for(;l!==void 0;){if(i===l.index){let c;l.type===2?c=new yr(a,a.nextSibling,this,e):l.type===1?c=new l.ctor(a,l.name,l.strings,this,e):l.type===6&&(c=new to(a,this,e)),this._$AV.push(c),l=n[++o]}i!==(l==null?void 0:l.index)&&(a=ze.nextNode(),i++)}return ze.currentNode=We,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 yr{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=Z,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=lt(this,e,r),jt(e)?e===Z||e==null||e===""?(this._$AH!==Z&&this._$AR(),this._$AH=Z):e!==this._$AH&&e!==ot&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Wi(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!==Z&&jt(this._$AH)?this._$AA.nextSibling.data=e:this.T(We.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=Nt.createElement(Gs(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 Ki(s,this),o=i.u(this.options);i.p(r),this.T(o),this._$AH=i}}_$AC(e){let r=ms.get(e.strings);return r===void 0&&ms.set(e.strings,r=new Nt(e)),r}k(e){Vn(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 yr(this.O(Pt()),this.O(Pt()),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 en{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,r,n,s,a){this.type=1,this._$AH=Z,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=Z}_$AI(e,r=this,n,s){const a=this.strings;let i=!1;if(a===void 0)e=lt(this,e,r,0),i=!jt(e)||e!==this._$AH&&e!==ot,i&&(this._$AH=e);else{const o=e;let l,c;for(e=a[0],l=0;l<a.length-1;l++)c=lt(this,o[n+l],r,l),c===ot&&(c=this._$AH[l]),i||(i=!jt(c)||c!==this._$AH[l]),c===Z?e=Z:e!==Z&&(e+=(c??"")+a[l+1]),this._$AH[l]=c}i&&!s&&this.j(e)}j(e){e===Z?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class Xi extends en{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===Z?void 0:e}}class Qi extends en{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==Z)}}class eo extends en{constructor(e,r,n,s,a){super(e,r,n,s,a),this.type=5}_$AI(e,r=this){if((e=lt(this,e,r,0)??Z)===ot)return;const n=this._$AH,s=e===Z&&n!==Z||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,a=e!==Z&&(n===Z||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 to=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){lt(this,e)}};const cn=$t.litHtmlPolyfillSupport;cn==null||cn(Nt,yr),($t.litHtmlVersions??($t.litHtmlVersions=[])).push("3.2.1");const ro=(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 yr(e.insertBefore(Pt(),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 K=class extends nt{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=ro(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 ot}};var zs;K._$litElement$=!0,K.finalized=!0,(zs=globalThis.litElementHydrateSupport)==null||zs.call(globalThis,{LitElement:K});const un=globalThis.litElementPolyfillSupport;un==null||un({LitElement:K});(globalThis.litElementVersions??(globalThis.litElementVersions=[])).push("4.1.1");/**
20
- * @license
21
- * Copyright 2017 Google LLC
22
- * SPDX-License-Identifier: BSD-3-Clause
23
- */const ke=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 no={attribute:!0,type:String,converter:Or,reflect:!1,hasChanged:Fn},so=(t=no,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 re(t){return(e,r)=>typeof r=="object"?so(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)}let $e={appletUrl:"",settings:{},settingsDialogOpen:!1};localStorage.getItem("data")&&($e=JSON.parse(localStorage.getItem("data")));const Bn=new Set;function ao(t){$e={...$e,...t},localStorage.setItem("data",JSON.stringify({appletUrl:$e.appletUrl,settings:$e.settings})),Bn.forEach(e=>e($e))}function io(){return $e}function oo(t){return t($e),Bn.add(t),()=>Ys(t)}function Ys(t){Bn.delete(t)}const G={get:io,update:ao,subscribe:oo,unsubscribe:Ys};var lo=Object.defineProperty,co=Object.getOwnPropertyDescriptor,uo=(t,e,r,n)=>{for(var s=n>1?void 0:n?co(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&&lo(e,r,s),s};let gs=class extends K{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}`),G.update({appletUrl:r.value})}}render(){return H`<input
28
- value=${G.get().appletUrl}
29
- type="text"
30
- placeholder="Enter an applet URL to inspect..."
31
- @keydown=${this.handleKeyDown.bind(this)}
32
- />`}};gs=uo([ke("url-input")],gs);var po=Object.defineProperty,ho=Object.getOwnPropertyDescriptor,fo=(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&&po(e,r,s),s};let ys=class extends K{createRenderRoot(){return this}openDialog(){G.update({settingsDialogOpen:!0})}render(){return H`
33
- <button
34
- aria-label="open settings"
35
- class="menu-button"
36
- @click="${this.openDialog}"
37
- >
38
- <svg
39
- focusable="false"
40
- xmlns="http://www.w3.org/2000/svg"
41
- width="24"
42
- height="24"
43
- viewBox="0 0 24 24"
44
- fill="none"
45
- stroke="currentColor"
46
- stroke-width="1.5"
47
- stroke-linecap="round"
48
- stroke-linejoin="round"
49
- >
50
- <path
51
- d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"
52
- />
53
- <circle cx="12" cy="12" r="3" />
54
- </svg>
55
- </button>
56
- `}};ys=fo([ke("settings-button")],ys);var mo=Object.defineProperty,go=Object.getOwnPropertyDescriptor,yo=(t,e,r,n)=>{for(var s=n>1?void 0:n?go(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&&mo(e,r,s),s};let vs=class extends K{createRenderRoot(){return this}render(){return H`
57
- <h1>Applet Inspector</h1>
58
- <url-input></url-input>
59
- <settings-button></settings-button>
60
- `}};vs=yo([ke("app-header")],vs);function kr(t,e){if(!t)return"";try{e&&(e.match(/\.[a-zA-Z0-9]+$/)||(e=e.endsWith("/")?e:e+"/"));const r=new URL(t,e??window.location.href);return vo(r.href)}catch(r){return console.warn("Failed to parse URL:",r),t}}function vo(t){return t.endsWith("/")?t.slice(0,-1):t}async function _o(t){t=kr(t);let e;try{const n=await(await fetch(t)).text(),o=new DOMParser().parseFromString(n,"text/html").querySelector('link[rel="manifest"]').getAttribute("href"),l=kr(o,t);e=await(await fetch(l)).json(),e.icons=e.icons.map(d=>(d.src=kr(d.src,t),d))}catch{return}return e}class Ks{constructor(e){this.target=e}async send(e,r){if(this.target.postMessage(e.toJson(),"*"),!(r&&r.resolves===!1))return new Promise(n=>{const s=a=>{const i=new ge(a.data.type,a.data);i.type==="resolve"&&i.id===e.id&&(window.removeEventListener("message",s),n(i))};window.addEventListener("message",s)})}async on(e,r){const n=async s=>{if(s.source===window.self||s.data.type!==e||s.source!==this.target)return;const a=new ge(s.data.type,s.data);await r(a);const i=new bo({id:a.id});this.send(i,{resolves:!1})};window.addEventListener("message",n)}}class ge{constructor(e,r){this.timeStamp=Date.now(),this.type=e,this.id=crypto.randomUUID(),r&&Object.assign(this,r)}toJson(){return Object.fromEntries(Object.entries(this).filter(([e,r])=>{try{return JSON.stringify(r),!0}catch{return!1}}))}}class bo extends ge{constructor({id:e}){super("resolve"),this.id=e}}class wo extends ge{constructor({actions:e}){super("actions"),this.actions=e}}class xo extends ge{constructor({data:e}){super("data"),this.data=e}}class Ao extends ge{constructor(){super("ready")}}class So extends ge{constructor({actionId:e,params:r}){super("action"),this.actionId=e,this.params=r}}class ko extends ge{constructor(){super("init")}}class Xs extends Event{constructor({data:e}){super("data",{bubbles:!1,cancelable:!1,composed:!1}),this.data=e}}class Qs extends Event{constructor(){super("ready",{bubbles:!1,cancelable:!1,composed:!1})}}class Eo extends Event{constructor(){super("load",{bubbles:!1,cancelable:!1,composed:!1})}}class To extends Event{constructor({actions:e}){super("actions",{bubbles:!1,cancelable:!1,composed:!1}),this.actions=e}}class Io extends Event{constructor({dimensions:e}){super("resize",{bubbles:!1,cancelable:!1,composed:!1}),this.dimensions=e}}var En=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},dn=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)},Tn,Er,Ct,ea;const zn=document.createElement("iframe");zn.style.display="none";document.body.appendChild(zn);async function $o(t,e){e||(e=zn),t=kr(t);const r=await _o(t);e.setAttribute("sandbox","allow-scripts allow-forms allow-same-origin"),e.src=t;const n=new Co(r,e.contentWindow);return new Promise(s=>{n.onready=()=>s(n)})}class Co extends EventTarget{constructor(e,r){super(),Tn.add(this),this.actions=[],Er.set(this,void 0),Ct.set(this,void 0),this.messageRelay=new Ks(r),En(this,Er,e,"f"),dn(this,Tn,"m",ea).call(this),this.messageRelay.on("ready",()=>{this.messageRelay.send(new ko)})}async dispatchAction(e,r){const n=new So({actionId:e,params:r});return await this.messageRelay.send(n)}get data(){return dn(this,Ct,"f")}set data(e){En(this,Ct,e,"f"),this.messageRelay.send(new xo({data:e}))}get manifest(){return dn(this,Er,"f")}onready(e){}onresize(e){}onactions(e){}ondata(e){}}Er=new WeakMap,Ct=new WeakMap,Tn=new WeakSet,ea=function(){this.messageRelay.on("ready",e=>{const r=new Qs;typeof this.onready=="function"&&this.onready(r),this.dispatchEvent(r)}),this.messageRelay.on("data",e=>{En(this,Ct,e.data,"f");const r=new Xs({data:e.data});typeof this.ondata=="function"&&this.ondata(r),this.dispatchEvent(r)}),this.messageRelay.on("resize",e=>{const r=new Io({dimensions:e.dimensions});typeof this.onresize=="function"&&this.onresize(r),this.dispatchEvent(r)}),this.messageRelay.on("actions",e=>{this.actions=e.actions;const r=new To({actions:e.actions});typeof this.onactions=="function"&&this.onactions(r),this.dispatchEvent(r)})};var pn=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)},Oo=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},Tr,Ir;class Ro extends EventTarget{constructor(){super(),this.actionHandlers={},Tr.set(this,{}),Ir.set(this,void 0),this.connect()}connect(){this.messageRelay=new Ks(window.parent),document.readyState==="complete"||document.readyState==="interactive"?setTimeout(this.initialize.bind(this),1):window.addEventListener("DOMContentLoaded",this.initialize.bind(this)),this.attachListeners()}async initialize(){const e=document.querySelector('link[rel="manifest"]');if(!e)return;try{const a=await(await fetch(e.href)).json();this.manifest=a,this.actions=a.actions??[]}catch{return}const r=new Eo;this.dispatchEvent(r),typeof this.onload=="function"&&await this.onload(r),this.messageRelay.send(new Ao);const n=new Qs;this.dispatchEvent(n),typeof this.onready=="function"&&this.onready(n),this.createResizeObserver()}createResizeObserver(){new ResizeObserver(r=>{for(let n of r){const s=new ge("resize",{dimensions:{width:n.contentRect.width,height:n.contentRect.height}});this.messageRelay.send(s)}}).observe(document.querySelector("html"))}attachListeners(){this.messageRelay.on("init",e=>{var r;this.manifest=e.manifest,this.actions=((r=this.manifest)==null?void 0:r.actions)||[]}),this.messageRelay.on("data",e=>{this.setData(e.data)}),this.messageRelay.on("action",async e=>{Object.keys(this.actionHandlers).includes(e.actionId)&&await this.actionHandlers[e.actionId](e.params)})}setActionHandler(e,r){this.actionHandlers[e]=r}defineAction(e,r){const{handler:n,...s}=r;this.actions=[...this.actions,{id:e,...s}],this.setActionHandler(e,n)}set actions(e){if(e){for(let r of e)pn(this,Tr,"f")[r.id]=r;this.messageRelay.send(new wo({actions:this.actions}))}}get actions(){return Object.values(pn(this,Tr,"f"))}set data(e){this.setData(e)}get data(){return pn(this,Ir,"f")}async setData(e){const r=new ge("data",{data:e});await this.messageRelay.send(r),Oo(this,Ir,e,"f");const n=new Xs({data:e});this.dispatchEvent(n),this.ondata(n)}onload(e){}onready(e){}ondata(e){}}Tr=new WeakMap,Ir=new WeakMap;function Po(){return new Ro}const jo={load:$o,getContext:Po};var _s=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},hn=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)},kt,$r;class ta extends HTMLElement{constructor(){super(...arguments),kt.set(this,void 0),$r.set(this,void 0)}connectedCallback(){_s(this,kt,this.attachShadow({mode:"open"}),"f"),this.container=document.createElement("iframe"),hn(this,kt,"f").appendChild(this.container);const e=document.createElement("style");e.textContent=this.styles,hn(this,kt,"f").appendChild(e);const r=this.getAttribute("src");r&&this.loadApplet(r)}set src(e){_s(this,$r,e,"f"),this.loadApplet(e)}get src(){return hn(this,$r,"f")}attributeChangedCallback(e,r,n){e==="src"&&(this.src=n)}async loadApplet(e){this.container&&(this.applet=await jo.load(e,this.container),this.applet.ondata=r=>{this.dispatchEvent(r)},this.applet.onresize=r=>{this.resizeContainer(r.dimensions)},this.applet.onactions=r=>{},this.dispatchEvent(new Event("load")),this.loaded=!0)}set data(e){if(this.applet&&this.loaded)this.applet.data=e;else{const r=()=>{this.applet.data=e,this.removeEventListener("load",r)};this.addEventListener("load",r)}}resizeContainer(e){this.style.height=`${e.height}px`}get styles(){return`
61
- :host {
62
- display: flex;
63
- flex-direction: column;
64
- height: 350px;
65
- }
66
-
67
- iframe {
68
- border: none;
69
- height: 100%;
70
- width: 100%;
71
- }
72
- `}}kt=new WeakMap,$r=new WeakMap;ta.observedAttributes=["src"];customElements.define("applet-frame",ta);var No=Object.defineProperty,Mo=Object.getOwnPropertyDescriptor,tn=(t,e,r,n)=>{for(var s=n>1?void 0:n?Mo(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&&No(e,r,s),s};let Mt=class extends K{constructor(){super(...arguments),this.renderRoot=this,this.appletUrl="",this.mode="gui",this.data={}}connectedCallback(){G.subscribe(t=>{this.appletUrl=t.appletUrl}),super.connectedCallback()}updated(){const t=document.querySelector("applet-frame");t&&(t.onload=()=>{var e;console.log("onload",(e=window.applet)==null?void 0:e.data,this.data),G.update({applet:t.applet}),window.applet=t.applet,window.applet.ondata=r=>this.data=r.data})}render(){const t=H`<div class="applet-footer">
73
- <label>View as:</label>
74
- <div class="toggle">
75
- <button
76
- data-selected=${this.mode==="gui"}
77
- @mousedown=${()=>this.mode="gui"}
78
- >
79
- GUI
80
- </button>
81
- <button
82
- data-selected=${this.mode==="data"}
83
- @mousedown=${()=>this.mode="data"}
84
- >
85
- Data
86
- </button>
87
- </div>
88
- </div>`;return H`
89
- <div class="container">
90
- <applet-frame
91
- src=${this.appletUrl}
92
- class=${this.mode==="gui"?"":"hidden"}
93
- ></applet-frame>
94
- <pre class=${this.mode==="gui"?"hidden":"data-view"}>
95
- ${JSON.stringify(this.data,null,2)}</pre
96
- >
97
- ${t}
98
- </div>
99
- `}};tn([re()],Mt.prototype,"appletUrl",2);tn([re()],Mt.prototype,"mode",2);tn([re({attribute:!1})],Mt.prototype,"data",2);Mt=tn([ke("app-viewer")],Mt);var Do=Object.defineProperty,Zo=Object.getOwnPropertyDescriptor,Qe=(t,e,r,n)=>{for(var s=n>1?void 0:n?Zo(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&&Do(e,r,s),s};let Dt=class extends K{constructor(){super(...arguments),this.renderRoot=this,this.selected=0,this.actions=[],this.schemaError=""}connectedCallback(){G.subscribe(t=>{t.applet&&(this.actions=t.applet.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("")}handleSubmit(t){t.preventDefault();const e=t.target,r=new FormData(e);console.log(r.get("action-id"));const n=r.get("action-id"),s=r.get("params");window.applet.dispatchAction(n,JSON.parse(s))}render(){if(!this.actions.length)return H`<p class="status-message">No actions available.</p>`;const t=JSON.stringify(this.actions[this.selected].parameters,null,2)??"None";return H`
100
- <form @submit=${this.handleSubmit.bind(this)}>
101
- <fieldset>
102
- <label>Action ID</label>
103
- <action-select
104
- .actions=${this.actions}
105
- name="action-id"
106
- @change=${this.handleSelect.bind(this)}
107
- ></action-select>
108
- </fieldset>
109
- <fieldset>
110
- <label>Schema</label>
111
- <pre class="schema">${t}</pre>
112
- </fieldset>
113
- <fieldset>
114
- <label>Params</label>
115
- <textarea
116
- rows=${6}
117
- name="params"
118
- @focus=${this.handleSchemaFocus}
119
- @change=${this.handleSchemaChange.bind(this)}
120
- >
121
- {}</textarea
122
- >
123
- ${this.schemaError?H`<div class="error-message">${this.schemaError}</div>`:""}
124
- </fieldset>
125
- <fieldset>
126
- <input type="submit" value="Dispatch action" />
127
- </fieldset>
128
- </form>
129
- `}};Qe([re({type:Number})],Dt.prototype,"selected",2);Qe([re({attribute:!1})],Dt.prototype,"actions",2);Qe([re({type:String})],Dt.prototype,"schemaError",2);Dt=Qe([ke("app-sidebar")],Dt);let Pr=class extends K{constructor(){super(...arguments),this.renderRoot=this,this.actions=[]}render(){return H`
130
- <select name=${this.name}>
131
- ${this.actions.map(t=>H`<option id="action">${t.id}</option>`)}
132
- </select>
133
- `}};Qe([re({type:String})],Pr.prototype,"name",2);Qe([re({attribute:!1})],Pr.prototype,"actions",2);Pr=Qe([ke("action-select")],Pr);var ra="vercel.ai.error",Uo=Symbol.for(ra),na,Lo=class sa extends Error{constructor({name:e,message:r,cause:n}){super(r),this[na]=!0,this.name=e,this.cause=n}static isInstance(e){return sa.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}};na=Uo;var $=Lo,aa="AI_APICallError",ia=`vercel.ai.error.${aa}`,Fo=Symbol.for(ia),oa,me=class extends ${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:aa,message:t,cause:i}),this[oa]=!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 $.hasMarker(t,ia)}};oa=Fo;var la="AI_EmptyResponseBodyError",ca=`vercel.ai.error.${la}`,Vo=Symbol.for(ca),ua,Bo=class extends ${constructor({message:t="Empty response body"}={}){super({name:la,message:t}),this[ua]=!0}static isInstance(t){return $.hasMarker(t,ca)}};ua=Vo;function da(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var pa="AI_InvalidArgumentError",ha=`vercel.ai.error.${pa}`,zo=Symbol.for(ha),fa,qo=class extends ${constructor({message:e,cause:r,argument:n}){super({name:pa,message:e,cause:r}),this[fa]=!0,this.argument=n}static isInstance(e){return $.hasMarker(e,ha)}};fa=zo;var ma="AI_InvalidPromptError",ga=`vercel.ai.error.${ma}`,Jo=Symbol.for(ga),ya,Be=class extends ${constructor({prompt:t,message:e,cause:r}){super({name:ma,message:`Invalid prompt: ${e}`,cause:r}),this[ya]=!0,this.prompt=t}static isInstance(t){return $.hasMarker(t,ga)}};ya=Jo;var va="AI_InvalidResponseDataError",_a=`vercel.ai.error.${va}`,Ho=Symbol.for(_a),ba,fn=class extends ${constructor({data:t,message:e=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:va,message:e}),this[ba]=!0,this.data=t}static isInstance(t){return $.hasMarker(t,_a)}};ba=Ho;var wa="AI_JSONParseError",xa=`vercel.ai.error.${wa}`,Wo=Symbol.for(xa),Aa,jr=class extends ${constructor({text:t,cause:e}){super({name:wa,message:`JSON parsing failed: Text: ${t}.
134
- Error message: ${da(e)}`,cause:e}),this[Aa]=!0,this.text=t}static isInstance(t){return $.hasMarker(t,xa)}};Aa=Wo;var Sa="AI_LoadAPIKeyError",ka=`vercel.ai.error.${Sa}`,Go=Symbol.for(ka),Ea,wr=class extends ${constructor({message:t}){super({name:Sa,message:t}),this[Ea]=!0}static isInstance(t){return $.hasMarker(t,ka)}};Ea=Go;var Ta="AI_TooManyEmbeddingValuesForCallError",Ia=`vercel.ai.error.${Ta}`,Yo=Symbol.for(Ia),$a,Ko=class extends ${constructor(t){super({name:Ta,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[$a]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return $.hasMarker(t,Ia)}};$a=Yo;var Ca="AI_TypeValidationError",Oa=`vercel.ai.error.${Ca}`,Xo=Symbol.for(Oa),Ra,Qo=class In extends ${constructor({value:e,cause:r}){super({name:Ca,message:`Type validation failed: Value: ${JSON.stringify(e)}.
135
- Error message: ${da(r)}`,cause:r}),this[Ra]=!0,this.value=e}static isInstance(e){return $.hasMarker(e,Oa)}static wrap({value:e,cause:r}){return In.isInstance(r)&&r.value===e?r:new In({value:e,cause:r})}};Ra=Xo;var Oe=Qo,Pa="AI_UnsupportedFunctionalityError",ja=`vercel.ai.error.${Pa}`,el=Symbol.for(ja),Na,F=class extends ${constructor({functionality:t,message:e=`'${t}' functionality not supported.`}){super({name:Pa,message:e}),this[Na]=!0,this.functionality=t}static isInstance(t){return $.hasMarker(t,ja)}};Na=el;function Nr(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"?!0:Array.isArray(t)?t.every(Nr):typeof t=="object"?Object.entries(t).every(([e,r])=>typeof e=="string"&&Nr(r)):!1}function bs(t){return Array.isArray(t)&&t.every(Nr)}function $n(t){return t!=null&&typeof t=="object"&&Object.entries(t).every(([e,r])=>typeof e=="string"&&Nr(r))}let tl=(t,e=21)=>(r=e)=>{let n="",s=r|0;for(;s--;)n+=t[Math.random()*t.length|0];return n};function rl(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ve={exports:{}},ws;function nl(){if(ws)return Ve.exports;ws=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",y=c&&c.constructorAction||"error";if(p==="ignore"&&y==="ignore")return d;if(p!=="ignore"&&y!=="ignore"){if(e.test(o)===!1&&r.test(o)===!1)return d}else if(p!=="ignore"&&y==="ignore"){if(e.test(o)===!1)return d}else if(r.test(o)===!1)return d;return s(d,{protoAction:p,constructorAction:y,safe:c&&c.safe})}function s(o,{protoAction:l="error",constructorAction:c="error",safe:d}={}){let p=[o];for(;p.length;){const y=p;p=[];for(const v of y){if(l!=="ignore"&&Object.prototype.hasOwnProperty.call(v,"__proto__")){if(d===!0)return null;if(l==="error")throw new SyntaxError("Object contains forbidden prototype property");delete v.__proto__}if(c!=="ignore"&&Object.prototype.hasOwnProperty.call(v,"constructor")&&Object.prototype.hasOwnProperty.call(v.constructor,"prototype")){if(d===!0)return null;if(c==="error")throw new SyntaxError("Object contains forbidden prototype property");delete v.constructor}for(const x in v){const m=v[x];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 Ve.exports=a,Ve.exports.default=a,Ve.exports.parse=a,Ve.exports.safeParse=i,Ve.exports.scan=s,Ve.exports}var sl=nl();const qn=rl(sl);var al=Object.defineProperty,il=(t,e,r)=>e in t?al(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xr=(t,e,r)=>il(t,typeof e!="symbol"?e+"":e,r);class xs extends Error{constructor(e,r){super(e),xr(this,"type"),xr(this,"field"),xr(this,"value"),xr(this,"line"),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function mn(t){}function ol(t){const{onEvent:e=mn,onError:r=mn,onRetry:n=mn,onComment:s}=t;let a="",i=!0,o,l="",c="";function d(m){const g=i?m.replace(/^\xEF\xBB\xBF/,""):m,[T,S]=ll(`${a}${g}`);for(const j of T)p(j);a=S,i=!1}function p(m){if(m===""){v();return}if(m.startsWith(":")){s&&s(m.slice(m.startsWith(": ")?2:1));return}const g=m.indexOf(":");if(g!==-1){const T=m.slice(0,g),S=m[g+1]===" "?2:1,j=m.slice(g+S);y(T,j,m);return}y(m,"",m)}function y(m,g,T){switch(m){case"event":c=g;break;case"data":l=`${l}${g}
136
- `;break;case"id":o=g.includes("\0")?void 0:g;break;case"retry":/^\d+$/.test(g)?n(parseInt(g,10)):r(new xs(`Invalid \`retry\` value: "${g}"`,{type:"invalid-retry",value:g,line:T}));break;default:r(new xs(`Unknown field "${m.length>20?`${m.slice(0,20)}…`:m}"`,{type:"unknown-field",field:m,value:g,line:T}));break}}function v(){l.length>0&&e({id:o,event:c||void 0,data:l.endsWith(`
137
- `)?l.slice(0,-1):l}),o=void 0,l="",c=""}function x(m={}){a&&m.consume&&p(a),o=void 0,l="",c="",a=""}return{feed:d,reset:x}}function ll(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]===`
138
- `?(e.push(r),r="",s++):a==="\r"||a===`
139
- `?(e.push(r),r=""):r+=a}return[e,r]}class cl extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let s;super({start(a){s=ol({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 ul={};function ct(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}function dl(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 pl(t){return t==null?Promise.resolve():new Promise(e=>setTimeout(e,t))}function rn(t){const e={};return t.headers.forEach((r,n)=>{e[n]=r}),e}var et=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const s=tl(r,e);if(t==null)return s;if(r.includes(n))throw new qo({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return a=>`${t}${n}${s(a)}`},At=et();function hl(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}function fl(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>r!=null))}function Cr(t){return t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")}function ml({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:n}){if(typeof t=="string")return t;if(t!=null)throw new wr({message:`${n} API key must be a string.`});if(typeof process>"u")throw new wr({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=ul[e],t==null)throw new wr({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new wr({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}var Mr=Symbol.for("vercel.ai.validator");function gl(t){return{[Mr]:!0,validate:t}}function yl(t){return typeof t=="object"&&t!==null&&Mr in t&&t[Mr]===!0&&"validate"in t}function vl(t){return yl(t)?t:_l(t)}function _l(t){return gl(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=Ge({value:t,schema:e});if(!r.success)throw Oe.wrap({value:t,cause:r.error});return r.value}function Ge({value:t,schema:e}){const r=vl(e);try{if(r.validate==null)return{success:!0,value:t};const n=r.validate(t);return n.success?n:{success:!1,error:Oe.wrap({value:t,cause:n.error})}}catch(n){return{success:!1,error:Oe.wrap({value:t,cause:n})}}}function wl({text:t,schema:e}){try{const r=qn.parse(t);return e==null?r:bl({value:r,schema:e})}catch(r){throw jr.isInstance(r)||Oe.isInstance(r)?r:new jr({text:t,cause:r})}}function ut({text:t,schema:e}){try{const r=qn.parse(t);if(e==null)return{success:!0,value:r,rawValue:r};const n=Ge({value:r,schema:e});return n.success?{...n,rawValue:r}:n}catch(r){return{success:!1,error:jr.isInstance(r)?r:new jr({text:t,cause:r})}}}function As(t){try{return qn.parse(t),!0}catch{return!1}}var xl=()=>globalThis.fetch,dt=async({url:t,headers:e,body:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:a,fetch:i})=>Al({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:a,fetch:i}),Al=async({url:t,headers:e={},body:r,successfulResponseHandler:n,failedResponseHandler:s,abortSignal:a,fetch:i=xl()})=>{try{const o=await i(t,{method:"POST",headers:fl(e),body:r.content,signal:a}),l=rn(o);if(!o.ok){let c;try{c=await s({response:o,url:t,requestBodyValues:r.values})}catch(d){throw Cr(d)||me.isInstance(d)?d:new me({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&&(Cr(c)||me.isInstance(c))?c:new me({message:"Failed to process successful response",cause:c,statusCode:o.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(o){if(Cr(o))throw o;if(o instanceof TypeError&&o.message==="fetch failed"){const l=o.cause;if(l!=null)throw new me({message:`Cannot connect to API: ${l.message}`,cause:l,url:t,requestBodyValues:r.values,isRetryable:!0})}throw o}},Sl=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:n,url:s,requestBodyValues:a})=>{const i=await n.text(),o=rn(n);if(i.trim()==="")return{responseHeaders:o,value:new me({message:n.statusText,url:s,requestBodyValues:a,statusCode:n.status,responseHeaders:o,responseBody:i,isRetryable:r==null?void 0:r(n)})};try{const l=wl({text:i,schema:t});return{responseHeaders:o,value:new me({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 me({message:n.statusText,url:s,requestBodyValues:a,statusCode:n.status,responseHeaders:o,responseBody:i,isRetryable:r==null?void 0:r(n)})}}},Ma=t=>async({response:e})=>{const r=rn(e);if(e.body==null)throw new Bo({});return{responseHeaders:r,value:e.body.pipeThrough(new TextDecoderStream).pipeThrough(new cl).pipeThrough(new TransformStream({transform({data:n},s){n!=="[DONE]"&&s.enqueue(ut({text:n,schema:t}))}}))}},nn=t=>async({response:e,url:r,requestBodyValues:n})=>{const s=await e.text(),a=ut({text:s,schema:t}),i=rn(e);if(!a.success)throw new me({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:kl,atob:El}=globalThis;function Tl(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=El(e);return Uint8Array.from(r,n=>n.codePointAt(0))}function Cn(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return kl(e)}function Il(t){return t==null?void 0:t.replace(/\/$/,"")}var I;(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})(I||(I={}));var On;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(On||(On={}));const b=I.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ae=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=I.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"]),$l=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class X 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 X))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,I.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()}}X.create=t=>new X(t);const pt=(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,I.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:r=`Unrecognized key(s) in object: ${I.joinValues(t.keys,", ")}`;break;case h.invalid_union:r="Invalid input";break;case h.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${I.joinValues(t.options)}`;break;case h.invalid_enum_value:r=`Invalid enum value. Expected ${I.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}"`:I.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,I.assertNever(t)}return{message:r}};let Da=pt;function Cl(t){Da=t}function Dr(){return Da}const Zr=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}},Ol=[];function _(t,e){const r=Dr(),n=Zr({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===pt?void 0:pt].filter(s=>!!s)});t.common.issues.push(n)}class q{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 A;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 q.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 A;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 A=Object.freeze({status:"aborted"}),at=t=>({status:"dirty",value:t}),W=t=>({status:"valid",value:t}),Rn=t=>t.status==="aborted",Pn=t=>t.status==="dirty",Ye=t=>t.status==="valid",Zt=t=>typeof Promise<"u"&&t instanceof Promise;function Ur(t,e,r,n){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 e.get(t)}function Za(t,e,r,n,s){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 e.set(t,r),r}var w;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(w||(w={}));var Et,Tt;class ye{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 Ss=(t,e)=>{if(Ye(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 X(t.common.issues);return this._error=r,this._error}}};function k(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 E{get description(){return this._def.description}_getType(e){return Ae(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Ae(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new q,ctx:{common:e.parent.common,data:e.data,parsedType:Ae(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(Zt(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:Ae(e)},a=this._parseSync({data:e,path:s.path,parent:s});return Ss(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:Ae(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:s});return Ye(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=>Ye(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:Ae(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(Zt(s)?s:Promise.resolve(s));return Ss(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 pe({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 de.create(this,this._def)}nullable(){return Ne.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ue.create(this)}promise(){return ft.create(this,this._def)}or(e){return Vt.create([this,e],this._def)}and(e){return Bt.create(this,e,this._def)}transform(e){return new pe({...k(this._def),schema:this,typeName:f.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new Wt({...k(this._def),innerType:this,defaultValue:r,typeName:f.ZodDefault})}brand(){return new Jn({typeName:f.ZodBranded,type:this,...k(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new Gt({...k(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 vr.create(this,e)}readonly(){return Yt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Rl=/^c[^\s-]{8,}$/i,Pl=/^[0-9a-z]+$/,jl=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Nl=/^[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,Ml=/^[a-z0-9_-]{21}$/i,Dl=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Zl=/^[-+]?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)?)??$/,Ul=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ll="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let gn;const Fl=/^(?:(?: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])$/,Vl=/^(?:(?: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])$/,Bl=/^(([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]))$/,zl=/^(([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])$/,ql=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Jl=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ua="((\\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])))",Hl=new RegExp(`^${Ua}$`);function La(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 Wl(t){return new RegExp(`^${La(t)}$`)}function Fa(t){let e=`${Ua}T${La(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 Gl(t,e){return!!((e==="v4"||!e)&&Fl.test(t)||(e==="v6"||!e)&&Bl.test(t))}function Yl(t,e){if(!Dl.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 Kl(t,e){return!!((e==="v4"||!e)&&Vl.test(t)||(e==="v6"||!e)&&zl.test(t))}class ce extends E{_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}),A}const n=new q;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")Ul.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")gn||(gn=new RegExp(Ll,"u")),gn.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")Nl.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")Ml.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")Rl.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")Pl.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")jl.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"?Fa(a).test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?Hl.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?Wl(a).test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?Zl.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"duration",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?Gl(e.data,a.version)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"ip",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?Yl(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"jwt",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?Kl(e.data,a.version)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"cidr",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?ql.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"base64",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?Jl.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"base64url",code:h.invalid_string,message:a.message}),n.dirty()):I.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,...w.errToObj(n)})}_addCheck(e){return new ce({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...w.errToObj(e)})}url(e){return this._addCheck({kind:"url",...w.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...w.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...w.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...w.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...w.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...w.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...w.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...w.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...w.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...w.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...w.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...w.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,...w.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,...w.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...w.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...w.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r==null?void 0:r.position,...w.errToObj(r==null?void 0:r.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...w.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...w.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...w.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...w.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...w.errToObj(r)})}nonempty(e){return this.min(1,w.errToObj(e))}trim(){return new ce({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ce({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ce({...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}}ce.create=t=>{var e;return new ce({checks:[],typeName:f.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...k(t)})};function Xl(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 Re extends E{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}),A}let n;const s=new q;for(const a of this._def.checks)a.kind==="int"?I.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"?Xl(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()):I.assertNever(a);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,w.toString(r))}gt(e,r){return this.setLimit("min",e,!1,w.toString(r))}lte(e,r){return this.setLimit("max",e,!0,w.toString(r))}lt(e,r){return this.setLimit("max",e,!1,w.toString(r))}setLimit(e,r,n,s){return new Re({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:w.toString(s)}]})}_addCheck(e){return new Re({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:w.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:w.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:w.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:w.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:w.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:w.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:w.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:w.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:w.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"&&I.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)}}Re.create=t=>new Re({checks:[],typeName:f.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...k(t)});class Pe extends E{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 q;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()):I.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}),A}gte(e,r){return this.setLimit("min",e,!0,w.toString(r))}gt(e,r){return this.setLimit("min",e,!1,w.toString(r))}lte(e,r){return this.setLimit("max",e,!0,w.toString(r))}lt(e,r){return this.setLimit("max",e,!1,w.toString(r))}setLimit(e,r,n,s){return new Pe({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:w.toString(s)}]})}_addCheck(e){return new Pe({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:w.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:w.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:w.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:w.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:w.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}}Pe.create=t=>{var e;return new Pe({checks:[],typeName:f.ZodBigInt,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...k(t)})};class Ut extends E{_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}),A}return W(e.data)}}Ut.create=t=>new Ut({typeName:f.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...k(t)});class Ke extends E{_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}),A}if(isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return _(a,{code:h.invalid_date}),A}const n=new q;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()):I.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Ke({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:w.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:w.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}}Ke.create=t=>new Ke({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:f.ZodDate,...k(t)});class Lr extends E{_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}),A}return W(e.data)}}Lr.create=t=>new Lr({typeName:f.ZodSymbol,...k(t)});class Lt extends E{_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}),A}return W(e.data)}}Lt.create=t=>new Lt({typeName:f.ZodUndefined,...k(t)});class Ft extends E{_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}),A}return W(e.data)}}Ft.create=t=>new Ft({typeName:f.ZodNull,...k(t)});class ht extends E{constructor(){super(...arguments),this._any=!0}_parse(e){return W(e.data)}}ht.create=t=>new ht({typeName:f.ZodAny,...k(t)});class He extends E{constructor(){super(...arguments),this._unknown=!0}_parse(e){return W(e.data)}}He.create=t=>new He({typeName:f.ZodUnknown,...k(t)});class Se extends E{_parse(e){const r=this._getOrReturnCtx(e);return _(r,{code:h.invalid_type,expected:b.never,received:r.parsedType}),A}}Se.create=t=>new Se({typeName:f.ZodNever,...k(t)});class Fr extends E{_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}),A}return W(e.data)}}Fr.create=t=>new Fr({typeName:f.ZodVoid,...k(t)});class ue extends E{_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}),A;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 ye(r,i,r.path,o)))).then(i=>q.mergeArray(n,i));const a=[...r.data].map((i,o)=>s.type._parseSync(new ye(r,i,r.path,o)));return q.mergeArray(n,a)}get element(){return this._def.type}min(e,r){return new ue({...this._def,minLength:{value:e,message:w.toString(r)}})}max(e,r){return new ue({...this._def,maxLength:{value:e,message:w.toString(r)}})}length(e,r){return new ue({...this._def,exactLength:{value:e,message:w.toString(r)}})}nonempty(e){return this.min(1,e)}}ue.create=(t,e)=>new ue({type:t,minLength:null,maxLength:null,exactLength:null,typeName:f.ZodArray,...k(e)});function st(t){if(t instanceof D){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=de.create(st(n))}return new D({...t._def,shape:()=>e})}else return t instanceof ue?new ue({...t._def,type:st(t.element)}):t instanceof de?de.create(st(t.unwrap())):t instanceof Ne?Ne.create(st(t.unwrap())):t instanceof ve?ve.create(t.items.map(e=>st(e))):t}class D extends E{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=I.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}),A}const{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof Se&&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 ye(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Se){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 ye(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,y=await d.value;c.push({key:p,value:y,alwaysSet:d.alwaysSet})}return c}).then(c=>q.mergeObjectSync(n,c)):q.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return w.errToObj,new D({...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=w.errToObj(e).message)!==null&&o!==void 0?o:l}:{message:l}}}:{}})}strip(){return new D({...this._def,unknownKeys:"strip"})}passthrough(){return new D({...this._def,unknownKeys:"passthrough"})}extend(e){return new D({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new D({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 D({...this._def,catchall:e})}pick(e){const r={};return I.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(r[n]=this.shape[n])}),new D({...this._def,shape:()=>r})}omit(e){const r={};return I.objectKeys(this.shape).forEach(n=>{e[n]||(r[n]=this.shape[n])}),new D({...this._def,shape:()=>r})}deepPartial(){return st(this)}partial(e){const r={};return I.objectKeys(this.shape).forEach(n=>{const s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}),new D({...this._def,shape:()=>r})}required(e){const r={};return I.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof de;)a=a._def.innerType;r[n]=a}}),new D({...this._def,shape:()=>r})}keyof(){return Va(I.objectKeys(this.shape))}}D.create=(t,e)=>new D({shape:()=>t,unknownKeys:"strip",catchall:Se.create(),typeName:f.ZodObject,...k(e)});D.strictCreate=(t,e)=>new D({shape:()=>t,unknownKeys:"strict",catchall:Se.create(),typeName:f.ZodObject,...k(e)});D.lazycreate=(t,e)=>new D({shape:t,unknownKeys:"strip",catchall:Se.create(),typeName:f.ZodObject,...k(e)});class Vt extends E{_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 X(o.ctx.common.issues));return _(r,{code:h.invalid_union,unionErrors:i}),A}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 X(l));return _(r,{code:h.invalid_union,unionErrors:o}),A}}get options(){return this._def.options}}Vt.create=(t,e)=>new Vt({options:t,typeName:f.ZodUnion,...k(e)});const xe=t=>t instanceof qt?xe(t.schema):t instanceof pe?xe(t.innerType()):t instanceof Jt?[t.value]:t instanceof je?t.options:t instanceof Ht?I.objectValues(t.enum):t instanceof Wt?xe(t._def.innerType):t instanceof Lt?[void 0]:t instanceof Ft?[null]:t instanceof de?[void 0,...xe(t.unwrap())]:t instanceof Ne?[null,...xe(t.unwrap())]:t instanceof Jn||t instanceof Yt?xe(t.unwrap()):t instanceof Gt?xe(t._def.innerType):[];class sn extends E{_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}),A;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]}),A)}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=xe(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 sn({typeName:f.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...k(n)})}}function jn(t,e){const r=Ae(t),n=Ae(e);if(t===e)return{valid:!0,data:t};if(r===b.object&&n===b.object){const s=I.objectKeys(e),a=I.objectKeys(t).filter(o=>s.indexOf(o)!==-1),i={...t,...e};for(const o of a){const l=jn(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=jn(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 Bt extends E{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=(a,i)=>{if(Rn(a)||Rn(i))return A;const o=jn(a.value,i.value);return o.valid?((Pn(a)||Pn(i))&&r.dirty(),{status:r.value,value:o.data}):(_(n,{code:h.invalid_intersection_types}),A)};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}))}}Bt.create=(t,e,r)=>new Bt({left:t,right:e,typeName:f.ZodIntersection,...k(r)});class ve extends E{_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}),A;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"}),A;!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 ye(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>q.mergeArray(r,i)):q.mergeArray(r,a)}get items(){return this._def.items}rest(e){return new ve({...this._def,rest:e})}}ve.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ve({items:t,typeName:f.ZodTuple,rest:null,...k(e)})};class zt extends E{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}),A;const s=[],a=this._def.keyType,i=this._def.valueType;for(const o in n.data)s.push({key:a._parse(new ye(n,o,n.path,o)),value:i._parse(new ye(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?q.mergeObjectAsync(r,s):q.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof E?new zt({keyType:e,valueType:r,typeName:f.ZodRecord,...k(n)}):new zt({keyType:ce.create(),valueType:e,typeName:f.ZodRecord,...k(r)})}}class Vr extends E{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}),A;const s=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([o,l],c)=>({key:s._parse(new ye(n,o,n.path,[c,"key"])),value:a._parse(new ye(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 A;(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 A;(c.status==="dirty"||d.status==="dirty")&&r.dirty(),o.set(c.value,d.value)}return{status:r.value,value:o}}}}Vr.create=(t,e,r)=>new Vr({valueType:e,keyType:t,typeName:f.ZodMap,...k(r)});class Xe extends E{_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}),A;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 A;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 ye(n,l,n.path,c)));return n.common.async?Promise.all(o).then(l=>i(l)):i(o)}min(e,r){return new Xe({...this._def,minSize:{value:e,message:w.toString(r)}})}max(e,r){return new Xe({...this._def,maxSize:{value:e,message:w.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}Xe.create=(t,e)=>new Xe({valueType:t,minSize:null,maxSize:null,typeName:f.ZodSet,...k(e)});class it extends E{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}),A;function n(o,l){return Zr({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Dr(),pt].filter(c=>!!c),issueData:{code:h.invalid_arguments,argumentsError:l}})}function s(o,l){return Zr({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Dr(),pt].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 ft){const o=this;return W(async function(...l){const c=new X([]),d=await o._def.args.parseAsync(l,a).catch(v=>{throw c.addIssue(n(l,v)),c}),p=await Reflect.apply(i,this,d);return await o._def.returns._def.type.parseAsync(p,a).catch(v=>{throw c.addIssue(s(p,v)),c})})}else{const o=this;return W(function(...l){const c=o._def.args.safeParse(l,a);if(!c.success)throw new X([n(l,c.error)]);const d=Reflect.apply(i,this,c.data),p=o._def.returns.safeParse(d,a);if(!p.success)throw new X([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new it({...this._def,args:ve.create(e).rest(He.create())})}returns(e){return new it({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new it({args:e||ve.create([]).rest(He.create()),returns:r||He.create(),typeName:f.ZodFunction,...k(n)})}}class qt extends E{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})}}qt.create=(t,e)=>new qt({getter:t,typeName:f.ZodLazy,...k(e)});class Jt extends E{_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}),A}return{status:"valid",value:e.data}}get value(){return this._def.value}}Jt.create=(t,e)=>new Jt({value:t,typeName:f.ZodLiteral,...k(e)});function Va(t,e){return new je({values:t,typeName:f.ZodEnum,...k(e)})}class je extends E{constructor(){super(...arguments),Et.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return _(r,{expected:I.joinValues(n),received:r.parsedType,code:h.invalid_type}),A}if(Ur(this,Et)||Za(this,Et,new Set(this._def.values)),!Ur(this,Et).has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return _(r,{received:r.data,code:h.invalid_enum_value,options:n}),A}return W(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 je.create(e,{...this._def,...r})}exclude(e,r=this._def){return je.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}Et=new WeakMap;je.create=Va;class Ht extends E{constructor(){super(...arguments),Tt.set(this,void 0)}_parse(e){const r=I.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==b.string&&n.parsedType!==b.number){const s=I.objectValues(r);return _(n,{expected:I.joinValues(s),received:n.parsedType,code:h.invalid_type}),A}if(Ur(this,Tt)||Za(this,Tt,new Set(I.getValidEnumValues(this._def.values))),!Ur(this,Tt).has(e.data)){const s=I.objectValues(r);return _(n,{received:n.data,code:h.invalid_enum_value,options:s}),A}return W(e.data)}get enum(){return this._def.values}}Tt=new WeakMap;Ht.create=(t,e)=>new Ht({values:t,typeName:f.ZodNativeEnum,...k(e)});class ft extends E{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}),A;const n=r.parsedType===b.promise?r.data:Promise.resolve(r.data);return W(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}}ft.create=(t,e)=>new ft({type:t,typeName:f.ZodPromise,...k(e)});class pe extends E{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 A;const l=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return l.status==="aborted"?A:l.status==="dirty"||r.value==="dirty"?at(l.value):l});{if(r.value==="aborted")return A;const o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?A:o.status==="dirty"||r.value==="dirty"?at(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"?A:(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"?A:(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(!Ye(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=>Ye(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:r.value,value:o})):i);I.assertNever(s)}}pe.create=(t,e,r)=>new pe({schema:t,typeName:f.ZodEffects,effect:e,...k(r)});pe.createWithPreprocess=(t,e,r)=>new pe({schema:e,effect:{type:"preprocess",transform:t},typeName:f.ZodEffects,...k(r)});class de extends E{_parse(e){return this._getType(e)===b.undefined?W(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}de.create=(t,e)=>new de({innerType:t,typeName:f.ZodOptional,...k(e)});class Ne extends E{_parse(e){return this._getType(e)===b.null?W(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ne.create=(t,e)=>new Ne({innerType:t,typeName:f.ZodNullable,...k(e)});class Wt extends E{_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}}Wt.create=(t,e)=>new Wt({innerType:t,typeName:f.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...k(e)});class Gt extends E{_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 Zt(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new X(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new X(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Gt.create=(t,e)=>new Gt({innerType:t,typeName:f.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...k(e)});class Br extends E{_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}),A}return{status:"valid",value:e.data}}}Br.create=t=>new Br({typeName:f.ZodNaN,...k(t)});const Ql=Symbol("zod_brand");class Jn extends E{_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 vr extends E{_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"?A:a.status==="dirty"?(r.dirty(),at(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"?A: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 vr({in:e,out:r,typeName:f.ZodPipeline})}}class Yt extends E{_parse(e){const r=this._def.innerType._parse(e),n=s=>(Ye(s)&&(s.value=Object.freeze(s.value)),s);return Zt(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}}Yt.create=(t,e)=>new Yt({innerType:t,typeName:f.ZodReadonly,...k(e)});function Ba(t,e={},r){return t?ht.create().superRefine((n,s)=>{var a,i;if(!t(n)){const o=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,l=(i=(a=o.fatal)!==null&&a!==void 0?a:r)!==null&&i!==void 0?i:!0,c=typeof o=="string"?{message:o}:o;s.addIssue({code:"custom",...c,fatal:l})}}):ht.create()}const ec={object:D.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 tc=(t,e={message:`Input not instance of ${t.name}`})=>Ba(r=>r instanceof t,e),za=ce.create,qa=Re.create,rc=Br.create,nc=Pe.create,Ja=Ut.create,sc=Ke.create,ac=Lr.create,ic=Lt.create,oc=Ft.create,lc=ht.create,cc=He.create,uc=Se.create,dc=Fr.create,pc=ue.create,hc=D.create,fc=D.strictCreate,mc=Vt.create,gc=sn.create,yc=Bt.create,vc=ve.create,_c=zt.create,bc=Vr.create,wc=Xe.create,xc=it.create,Ac=qt.create,Sc=Jt.create,kc=je.create,Ec=Ht.create,Tc=ft.create,ks=pe.create,Ic=de.create,$c=Ne.create,Cc=pe.createWithPreprocess,Oc=vr.create,Rc=()=>za().optional(),Pc=()=>qa().optional(),jc=()=>Ja().optional(),Nc={string:t=>ce.create({...t,coerce:!0}),number:t=>Re.create({...t,coerce:!0}),boolean:t=>Ut.create({...t,coerce:!0}),bigint:t=>Pe.create({...t,coerce:!0}),date:t=>Ke.create({...t,coerce:!0})},Mc=A;var u=Object.freeze({__proto__:null,defaultErrorMap:pt,setErrorMap:Cl,getErrorMap:Dr,makeIssue:Zr,EMPTY_PATH:Ol,addIssueToContext:_,ParseStatus:q,INVALID:A,DIRTY:at,OK:W,isAborted:Rn,isDirty:Pn,isValid:Ye,isAsync:Zt,get util(){return I},get objectUtil(){return On},ZodParsedType:b,getParsedType:Ae,ZodType:E,datetimeRegex:Fa,ZodString:ce,ZodNumber:Re,ZodBigInt:Pe,ZodBoolean:Ut,ZodDate:Ke,ZodSymbol:Lr,ZodUndefined:Lt,ZodNull:Ft,ZodAny:ht,ZodUnknown:He,ZodNever:Se,ZodVoid:Fr,ZodArray:ue,ZodObject:D,ZodUnion:Vt,ZodDiscriminatedUnion:sn,ZodIntersection:Bt,ZodTuple:ve,ZodRecord:zt,ZodMap:Vr,ZodSet:Xe,ZodFunction:it,ZodLazy:qt,ZodLiteral:Jt,ZodEnum:je,ZodNativeEnum:Ht,ZodPromise:ft,ZodEffects:pe,ZodTransformer:pe,ZodOptional:de,ZodNullable:Ne,ZodDefault:Wt,ZodCatch:Gt,ZodNaN:Br,BRAND:Ql,ZodBranded:Jn,ZodPipeline:vr,ZodReadonly:Yt,custom:Ba,Schema:E,ZodSchema:E,late:ec,get ZodFirstPartyTypeKind(){return f},coerce:Nc,any:lc,array:pc,bigint:nc,boolean:Ja,date:sc,discriminatedUnion:gc,effect:ks,enum:kc,function:xc,instanceof:tc,intersection:yc,lazy:Ac,literal:Sc,map:bc,nan:rc,nativeEnum:Ec,never:uc,null:oc,nullable:$c,number:qa,object:hc,oboolean:jc,onumber:Pc,optional:Ic,ostring:Rc,pipeline:Oc,preprocess:Cc,promise:Tc,record:_c,set:wc,strictObject:fc,string:za,symbol:ac,transformer:ks,tuple:vc,undefined:ic,union:mc,unknown:cc,void:dc,NEVER:Mc,ZodIssueCode:h,quotelessJson:$l,ZodError:X});function Dc({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,${Cn(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 F({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 F({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"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 F({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 Es(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 zr(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 Hn=u.object({error:u.object({message:u.string(),type:u.string().nullish(),param:u.any().nullish(),code:u.union([u.string(),u.number()]).nullish()})}),mt=Sl({errorSchema:Hn,errorToMessage:t=>t.error.message});function qr({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 Zc({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 F({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 F({functionality:`Unsupported tool choice type: ${c}`})}}}var Uc=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:Jr(this.modelId)}get defaultObjectGenerationMode(){return Vc(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 y,v,x,m,g,T,S,j;const ne=t.type,N=[];a!=null&&N.push({type:"unsupported-setting",setting:"topK"}),(c==null?void 0:c.type)==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&N.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const Q=this.settings.useLegacyFunctionCalling;if(Q&&this.settings.parallelToolCalls===!0)throw new F({functionality:"useLegacyFunctionCalling with parallelToolCalls"});if(Q&&this.supportsStructuredOutputs)throw new F({functionality:"structuredOutputs with useLegacyFunctionCalling"});Ts(this.modelId)==="remove"&&e.some(he=>he.role==="system")&&N.push({type:"other",message:"system messages are removed for this model"});const O={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:(y=c.name)!=null?y:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:d,max_completion_tokens:(v=p==null?void 0:p.openai)==null?void 0:v.maxCompletionTokens,store:(x=p==null?void 0:p.openai)==null?void 0:x.store,metadata:(m=p==null?void 0:p.openai)==null?void 0:m.metadata,prediction:(g=p==null?void 0:p.openai)==null?void 0:g.prediction,reasoning_effort:(S=(T=p==null?void 0:p.openai)==null?void 0:T.reasoningEffort)!=null?S:this.settings.reasoningEffort,messages:Dc({prompt:e,useLegacyFunctionCalling:Q,systemMessageMode:Ts(this.modelId)})};switch(Jr(this.modelId)&&(O.temperature!=null&&(O.temperature=void 0,N.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),O.top_p!=null&&(O.top_p=void 0,N.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),O.frequency_penalty!=null&&(O.frequency_penalty=void 0,N.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),O.presence_penalty!=null&&(O.presence_penalty=void 0,N.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),O.logit_bias!=null&&(O.logit_bias=void 0,N.push({type:"other",message:"logitBias is not supported for reasoning models"})),O.logprobs!=null&&(O.logprobs=void 0,N.push({type:"other",message:"logprobs is not supported for reasoning models"})),O.top_logprobs!=null&&(O.top_logprobs=void 0,N.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),O.max_tokens!=null&&(O.max_completion_tokens==null&&(O.max_completion_tokens=O.max_tokens),O.max_tokens=void 0)),ne){case"regular":{const{tools:he,tool_choice:Me,functions:De,function_call:Ze,toolWarnings:Ue}=Zc({mode:t,useLegacyFunctionCalling:Q,structuredOutputs:this.supportsStructuredOutputs});return{args:{...O,tools:he,tool_choice:Me,functions:De,function_call:Ze},warnings:[...N,...Ue]}}case"object-json":return{args:{...O,response_format:this.supportsStructuredOutputs&&t.schema!=null?{type:"json_schema",json_schema:{schema:t.schema,strict:!0,name:(j=t.name)!=null?j:"response",description:t.description}}:{type:"json_object"}},warnings:N};case"object-tool":return{args:Q?{...O,function_call:{name:t.tool.name},functions:[{name:t.tool.name,description:t.tool.description,parameters:t.tool.parameters}]}:{...O,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:N};default:{const he=ne;throw new Error(`Unsupported type: ${he}`)}}}async doGenerate(t){var e,r,n,s,a,i,o,l;const{args:c,warnings:d}=this.getArgs(t),{responseHeaders:p,value:y}=await dt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:ct(this.config.headers(),t.headers),body:c,failedResponseHandler:mt,successfulResponseHandler:nn(Lc),abortSignal:t.abortSignal,fetch:this.config.fetch}),{messages:v,...x}=c,m=y.choices[0],g=(e=y.usage)==null?void 0:e.completion_tokens_details,T=(r=y.usage)==null?void 0:r.prompt_tokens_details,S={openai:{}};return(g==null?void 0:g.reasoning_tokens)!=null&&(S.openai.reasoningTokens=g==null?void 0:g.reasoning_tokens),(g==null?void 0:g.accepted_prediction_tokens)!=null&&(S.openai.acceptedPredictionTokens=g==null?void 0:g.accepted_prediction_tokens),(g==null?void 0:g.rejected_prediction_tokens)!=null&&(S.openai.rejectedPredictionTokens=g==null?void 0:g.rejected_prediction_tokens),(T==null?void 0:T.cached_tokens)!=null&&(S.openai.cachedPromptTokens=T==null?void 0:T.cached_tokens),{text:(n=m.message.content)!=null?n:void 0,toolCalls:this.settings.useLegacyFunctionCalling&&m.message.function_call?[{toolCallType:"function",toolCallId:At(),toolName:m.message.function_call.name,args:m.message.function_call.arguments}]:(s=m.message.tool_calls)==null?void 0:s.map(j=>{var ne;return{toolCallType:"function",toolCallId:(ne=j.id)!=null?ne:At(),toolName:j.function.name,args:j.function.arguments}}),finishReason:zr(m.finish_reason),usage:{promptTokens:(i=(a=y.usage)==null?void 0:a.prompt_tokens)!=null?i:NaN,completionTokens:(l=(o=y.usage)==null?void 0:o.completion_tokens)!=null?l:NaN},rawCall:{rawPrompt:v,rawSettings:x},rawResponse:{headers:p},request:{body:JSON.stringify(c)},response:qr(y),warnings:d,logprobs:Es(m.logprobs),providerMetadata:S}}async doStream(t){var e;if((e=this.settings.simulateStreaming)!=null?e:Bc(this.modelId)){const g=await this.doGenerate(t);return{stream:new ReadableStream({start(S){if(S.enqueue({type:"response-metadata",...g.response}),g.text&&S.enqueue({type:"text-delta",textDelta:g.text}),g.toolCalls)for(const j of g.toolCalls)S.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:j.toolCallId,toolName:j.toolName,argsTextDelta:j.args}),S.enqueue({type:"tool-call",...j});S.enqueue({type:"finish",finishReason:g.finishReason,usage:g.usage,logprobs:g.logprobs,providerMetadata:g.providerMetadata}),S.close()}}),rawCall:g.rawCall,rawResponse:g.rawResponse,warnings:g.warnings}}const{args:r,warnings:n}=this.getArgs(t),s={...r,stream:!0,stream_options:this.config.compatibility==="strict"?{include_usage:!0}:void 0},{responseHeaders:a,value:i}=await dt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:ct(this.config.headers(),t.headers),body:s,failedResponseHandler:mt,successfulResponseHandler:Ma(Fc),abortSignal:t.abortSignal,fetch:this.config.fetch}),{messages:o,...l}=r,c=[];let d="unknown",p={promptTokens:void 0,completionTokens:void 0},y,v=!0;const{useLegacyFunctionCalling:x}=this.settings,m={openai:{}};return{stream:i.pipeThrough(new TransformStream({transform(g,T){var S,j,ne,N,Q,O,he,Me,De,Ze,Ue,_e;if(!g.success){d="error",T.enqueue({type:"error",error:g.error});return}const se=g.value;if("error"in se){d="error",T.enqueue({type:"error",error:se.error});return}if(v&&(v=!1,T.enqueue({type:"response-metadata",...qr(se)})),se.usage!=null){const{prompt_tokens:U,completion_tokens:ae,prompt_tokens_details:L,completion_tokens_details:P}=se.usage;p={promptTokens:U??void 0,completionTokens:ae??void 0},(P==null?void 0:P.reasoning_tokens)!=null&&(m.openai.reasoningTokens=P==null?void 0:P.reasoning_tokens),(P==null?void 0:P.accepted_prediction_tokens)!=null&&(m.openai.acceptedPredictionTokens=P==null?void 0:P.accepted_prediction_tokens),(P==null?void 0:P.rejected_prediction_tokens)!=null&&(m.openai.rejectedPredictionTokens=P==null?void 0:P.rejected_prediction_tokens),(L==null?void 0:L.cached_tokens)!=null&&(m.openai.cachedPromptTokens=L==null?void 0:L.cached_tokens)}const B=se.choices[0];if((B==null?void 0:B.finish_reason)!=null&&(d=zr(B.finish_reason)),(B==null?void 0:B.delta)==null)return;const be=B.delta;be.content!=null&&T.enqueue({type:"text-delta",textDelta:be.content});const Ee=Es(B==null?void 0:B.logprobs);Ee!=null&&Ee.length&&(y===void 0&&(y=[]),y.push(...Ee));const we=x&&be.function_call!=null?[{type:"function",id:At(),function:be.function_call,index:0}]:be.tool_calls;if(we!=null)for(const U of we){const ae=U.index;if(c[ae]==null){if(U.type!=="function")throw new fn({data:U,message:"Expected 'function' type."});if(U.id==null)throw new fn({data:U,message:"Expected 'id' to be a string."});if(((S=U.function)==null?void 0:S.name)==null)throw new fn({data:U,message:"Expected 'function.name' to be a string."});c[ae]={id:U.id,type:"function",function:{name:U.function.name,arguments:(j=U.function.arguments)!=null?j:""},hasFinished:!1};const P=c[ae];((ne=P.function)==null?void 0:ne.name)!=null&&((N=P.function)==null?void 0:N.arguments)!=null&&(P.function.arguments.length>0&&T.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:P.id,toolName:P.function.name,argsTextDelta:P.function.arguments}),As(P.function.arguments)&&(T.enqueue({type:"tool-call",toolCallType:"function",toolCallId:(Q=P.id)!=null?Q:At(),toolName:P.function.name,args:P.function.arguments}),P.hasFinished=!0));continue}const L=c[ae];L.hasFinished||(((O=U.function)==null?void 0:O.arguments)!=null&&(L.function.arguments+=(Me=(he=U.function)==null?void 0:he.arguments)!=null?Me:""),T.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:L.id,toolName:L.function.name,argsTextDelta:(De=U.function.arguments)!=null?De:""}),((Ze=L.function)==null?void 0:Ze.name)!=null&&((Ue=L.function)==null?void 0:Ue.arguments)!=null&&As(L.function.arguments)&&(T.enqueue({type:"tool-call",toolCallType:"function",toolCallId:(_e=L.id)!=null?_e:At(),toolName:L.function.name,args:L.function.arguments}),L.hasFinished=!0))}},flush(g){var T,S;g.enqueue({type:"finish",finishReason:d,logprobs:y,usage:{promptTokens:(T=p.promptTokens)!=null?T:NaN,completionTokens:(S=p.completionTokens)!=null?S:NaN},...m!=null?{providerMetadata:m}:{}})}})),rawCall:{rawPrompt:o,rawSettings:l},rawResponse:{headers:a},request:{body:JSON.stringify(s)},warnings:n}}},Ha=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(),Lc=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:Ha}),Fc=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:Ha}),Hn]);function Jr(t){return t==="o1"||t.startsWith("o1-")||t==="o3"||t.startsWith("o3-")}function Vc(t){return t.startsWith("gpt-4o-audio-preview")}function Ts(t){var e,r;return Jr(t)?(r=(e=Wa[t])==null?void 0:e.systemMessageMode)!=null?r:"developer":"system"}function Bc(t){var e,r;return Jr(t)?(r=(e=Wa[t])==null?void 0:e.simulateStreamingByDefault)!=null?r:!0:!1}var Wa={"o1-mini":{systemMessageMode:"remove",simulateStreamingByDefault:!1},"o1-mini-2024-09-12":{systemMessageMode:"remove",simulateStreamingByDefault:!1},"o1-preview":{systemMessageMode:"remove",simulateStreamingByDefault:!1},"o1-preview-2024-09-12":{systemMessageMode:"remove",simulateStreamingByDefault:!1},"o3-mini":{systemMessageMode:"developer",simulateStreamingByDefault:!1},"o3-mini-2025-01-31":{systemMessageMode:"developer",simulateStreamingByDefault:!1}};function zc({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}
140
-
141
- `,t=t.slice(1));for(const{role:a,content:i}of t)switch(a){case"system":throw new Be({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 F({functionality:"images"})}}).join("");s+=`${r}:
142
- ${o}
143
-
144
- `;break}case"assistant":{const o=i.map(l=>{switch(l.type){case"text":return l.text;case"tool-call":throw new F({functionality:"tool-call messages"})}}).join("");s+=`${n}:
145
- ${o}
146
-
147
- `;break}case"tool":throw new F({functionality:"tool messages"});default:{const o=a;throw new Error(`Unsupported role: ${o}`)}}return s+=`${n}:
148
- `,{prompt:s,stopSequences:[`
149
- ${r}:`]}}function Is(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 qc=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 y;const v=t.type,x=[];i!=null&&x.push({type:"unsupported-setting",setting:"topK"}),d!=null&&d.type!=="text"&&x.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:m,stopSequences:g}=zc({prompt:r,inputFormat:e}),T=[...g??[],...c??[]],S={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:T.length>0?T:void 0};switch(v){case"regular":{if((y=t.tools)!=null&&y.length)throw new F({functionality:"tools"});if(t.toolChoice)throw new F({functionality:"toolChoice"});return{args:S,warnings:x}}case"object-json":throw new F({functionality:"object-json mode"});case"object-tool":throw new F({functionality:"object-tool mode"});default:{const j=v;throw new Error(`Unsupported type: ${j}`)}}}async doGenerate(t){const{args:e,warnings:r}=this.getArgs(t),{responseHeaders:n,value:s}=await dt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:ct(this.config.headers(),t.headers),body:e,failedResponseHandler:mt,successfulResponseHandler:nn(Jc),abortSignal:t.abortSignal,fetch:this.config.fetch}),{prompt:a,...i}=e,o=s.choices[0];return{text:o.text,usage:{promptTokens:s.usage.prompt_tokens,completionTokens:s.usage.completion_tokens},finishReason:zr(o.finish_reason),logprobs:Is(o.logprobs),rawCall:{rawPrompt:a,rawSettings:i},rawResponse:{headers:n},response:qr(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 dt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:ct(this.config.headers(),t.headers),body:n,failedResponseHandler:mt,successfulResponseHandler:Ma(Hc),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(y,v){if(!y.success){l="error",v.enqueue({type:"error",error:y.error});return}const x=y.value;if("error"in x){l="error",v.enqueue({type:"error",error:x.error});return}p&&(p=!1,v.enqueue({type:"response-metadata",...qr(x)})),x.usage!=null&&(c={promptTokens:x.usage.prompt_tokens,completionTokens:x.usage.completion_tokens});const m=x.choices[0];(m==null?void 0:m.finish_reason)!=null&&(l=zr(m.finish_reason)),(m==null?void 0:m.text)!=null&&v.enqueue({type:"text-delta",textDelta:m.text});const g=Is(m==null?void 0:m.logprobs);g!=null&&g.length&&(d===void 0&&(d=[]),d.push(...g))},flush(y){y.enqueue({type:"finish",finishReason:l,logprobs:d,usage:c})}})),rawCall:{rawPrompt:i,rawSettings:o},rawResponse:{headers:s},warnings:r,request:{body:JSON.stringify(n)}}}},Jc=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()})}),Hc=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()}),Hn]),Wc=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 Ko({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const{responseHeaders:n,value:s}=await dt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:ct(this.config.headers(),e),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:this.settings.dimensions,user:this.settings.user},failedResponseHandler:mt,successfulResponseHandler:nn(Gc),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}}}},Gc=u.object({data:u.array(u.object({embedding:u.array(u.number())})),usage:u.object({prompt_tokens:u.number()}).nullish()}),Yc={"dall-e-3":1,"dall-e-2":10},Kc=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:Yc[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 y=[];n!=null&&y.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),s!=null&&y.push({type:"unsupported-setting",setting:"seed"});const v=(d=(c=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:c.call(l))!=null?d:new Date,{value:x,responseHeaders:m}=await dt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:ct(this.config.headers(),i),body:{model:this.modelId,prompt:t,n:e,size:r,...(p=a.openai)!=null?p:{},response_format:"b64_json"},failedResponseHandler:mt,successfulResponseHandler:nn(Xc),abortSignal:o,fetch:this.config.fetch});return{images:x.data.map(g=>g.b64_json),warnings:y,response:{timestamp:v,modelId:this.modelId,headers:m}}}},Xc=u.object({data:u.array(u.object({b64_json:u.string()}))});function Ga(t={}){var e,r,n;const s=(e=Il(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 ${ml({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers}),l=(x,m={})=>new Uc(x,m,{provider:`${i}.chat`,url:({path:g})=>`${s}${g}`,headers:o,compatibility:a,fetch:t.fetch}),c=(x,m={})=>new qc(x,m,{provider:`${i}.completion`,url:({path:g})=>`${s}${g}`,headers:o,compatibility:a,fetch:t.fetch}),d=(x,m={})=>new Wc(x,m,{provider:`${i}.embedding`,url:({path:g})=>`${s}${g}`,headers:o,fetch:t.fetch}),p=(x,m={})=>new Kc(x,m,{provider:`${i}.image`,url:({path:g})=>`${s}${g}`,headers:o,fetch:t.fetch}),y=(x,m)=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return x==="gpt-3.5-turbo-instruct"?c(x,m):l(x,m)},v=function(x,m){return y(x,m)};return v.languageModel=y,v.chat=l,v.completion=c,v.embedding=d,v.textEmbedding=d,v.textEmbeddingModel=d,v.image=p,v.imageModel=p,v}Ga({compatibility:"strict"});const Qc=Symbol("Let zodToJsonSchema decide on which parser to use"),$s={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"},eu=t=>typeof t=="string"?{...$s,name:t}:{...$s,...t},tu=t=>{const e=eu(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 Ya(t,e,r,n){n!=null&&n.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function R(t,e,r,n,s){t[e]=r,Ya(t,e,n,s)}function ru(){return{}}function nu(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=C(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&R(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&R(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(R(r,"minItems",t.exactLength.value,t.exactLength.message,e),R(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function su(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?R(r,"minimum",n.value,n.message,e):R(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),R(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?R(r,"maximum",n.value,n.message,e):R(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),R(r,"maximum",n.value,n.message,e));break;case"multipleOf":R(r,"multipleOf",n.value,n.message,e);break}return r}function au(){return{type:"boolean"}}function Ka(t,e){return C(t.type._def,e)}const iu=(t,e)=>C(t.innerType._def,e);function Xa(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,a)=>Xa(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 ou(t,e)}}const ou=(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":R(r,"minimum",n.value,n.message,e);break;case"max":R(r,"maximum",n.value,n.message,e);break}return r};function lu(t,e){return{...C(t.innerType._def,e),default:t.defaultValue()}}function cu(t,e){return e.effectStrategy==="input"?C(t.schema._def,e):{}}function uu(t){return{type:"string",enum:Array.from(t.values)}}const du=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function pu(t,e){const r=[C(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),C(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(du(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 hu(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 yn;const oe={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:()=>(yn===void 0&&(yn=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),yn),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 Qa(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":R(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":R(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":le(r,"email",n.message,e);break;case"format:idn-email":le(r,"idn-email",n.message,e);break;case"pattern:zod":J(r,oe.email,n.message,e);break}break;case"url":le(r,"uri",n.message,e);break;case"uuid":le(r,"uuid",n.message,e);break;case"regex":J(r,n.regex,n.message,e);break;case"cuid":J(r,oe.cuid,n.message,e);break;case"cuid2":J(r,oe.cuid2,n.message,e);break;case"startsWith":J(r,RegExp(`^${vn(n.value,e)}`),n.message,e);break;case"endsWith":J(r,RegExp(`${vn(n.value,e)}$`),n.message,e);break;case"datetime":le(r,"date-time",n.message,e);break;case"date":le(r,"date",n.message,e);break;case"time":le(r,"time",n.message,e);break;case"duration":le(r,"duration",n.message,e);break;case"length":R(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),R(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{J(r,RegExp(vn(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&le(r,"ipv4",n.message,e),n.version!=="v4"&&le(r,"ipv6",n.message,e);break}case"base64url":J(r,oe.base64url,n.message,e);break;case"jwt":J(r,oe.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&J(r,oe.ipv4Cidr,n.message,e),n.version!=="v4"&&J(r,oe.ipv6Cidr,n.message,e);break}case"emoji":J(r,oe.emoji(),n.message,e);break;case"ulid":{J(r,oe.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{le(r,"binary",n.message,e);break}case"contentEncoding:base64":{R(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{J(r,oe.base64,n.message,e);break}}break}case"nanoid":J(r,oe.nanoid,n.message,e)}return r}function vn(t,e){return e.patternStrategy==="escape"?mu(t):t}const fu=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function mu(t){let e="";for(let r=0;r<t.length;r++)fu.has(t[r])||(e+="\\"),e+=t[r];return e}function le(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}}})):R(t,"format",e,r,n)}function J(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:Cs(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):R(t,"pattern",Cs(e,n),r,n)}function Cs(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
150
- ]))`;continue}else if(n[c]==="$"){s+=`($|(?=[\r
151
- ]))`;continue}}if(r.s&&n[c]==="."){s+=i?`${n[c]}\r
152
- `:`[${n[c]}\r
153
- ]`;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 ei(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]:C(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",d]})??{}}),{}),additionalProperties:!1};const r={type:"object",additionalProperties:C(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}=Qa(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}=Ka(t.keyType._def,e);return{...r,propertyNames:d}}}return r}function gu(t,e){if(e.mapStrategy==="record")return ei(t,e);const r=C(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=C(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 yu(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 vu(){return{not:{}}}function _u(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Hr={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function bu(t,e){if(e.target==="openApi3")return Os(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Hr&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,a)=>{const i=Hr[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 Os(t,e)}const Os=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>C(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 wu(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:Hr[t.innerType._def.typeName],nullable:!0}:{type:[Hr[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=C(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=C(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function xu(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",Ya(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?R(r,"minimum",n.value,n.message,e):R(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),R(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?R(r,"maximum",n.value,n.message,e):R(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),R(r,"maximum",n.value,n.message,e));break;case"multipleOf":R(r,"multipleOf",n.value,n.message,e);break}return r}function Au(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":C(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":C(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Su(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 de&&(i=i._def.innerType),i.isNullable()||(i=i.nullable()),o=!1);const l=C(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:Au(t,e)};return n.required.length||delete n.required,n}const ku=(t,e)=>{var n;if(e.currentPath.toString()===((n=e.propertyPath)==null?void 0:n.toString()))return C(t.innerType._def,e);const r=C(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}},Eu=(t,e)=>{if(e.pipeStrategy==="input")return C(t.in._def,e);if(e.pipeStrategy==="output")return C(t.out._def,e);const r=C(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=C(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function Tu(t,e){return C(t.type._def,e)}function Iu(t,e){const n={type:"array",uniqueItems:!0,items:C(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&R(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&R(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function $u(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>C(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:C(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>C(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Cu(){return{not:{}}}function Ou(){return{}}const Ru=(t,e)=>C(t.innerType._def,e);function C(t,e,r=!1){var i;const n=e.seen.get(t);if(e.override){const o=(i=e.override)==null?void 0:i.call(e,t,e,n,r);if(o!==Qc)return o}if(n&&!r){const o=Pu(n,e);if(o!==void 0)return o}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const a=Nu(t,t.typeName,e);return a&&Mu(t,e,a),s.jsonSchema=a,a}const Pu=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ju(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}},ju=(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("/")},Nu=(t,e,r)=>{switch(e){case f.ZodString:return Qa(t,r);case f.ZodNumber:return xu(t,r);case f.ZodObject:return Su(t,r);case f.ZodBigInt:return su(t,r);case f.ZodBoolean:return au();case f.ZodDate:return Xa(t,r);case f.ZodUndefined:return Cu();case f.ZodNull:return _u(r);case f.ZodArray:return nu(t,r);case f.ZodUnion:case f.ZodDiscriminatedUnion:return bu(t,r);case f.ZodIntersection:return pu(t,r);case f.ZodTuple:return $u(t,r);case f.ZodRecord:return ei(t,r);case f.ZodLiteral:return hu(t,r);case f.ZodEnum:return uu(t);case f.ZodNativeEnum:return yu(t);case f.ZodNullable:return wu(t,r);case f.ZodOptional:return ku(t,r);case f.ZodMap:return gu(t,r);case f.ZodSet:return Iu(t,r);case f.ZodLazy:return C(t.getter()._def,r);case f.ZodPromise:return Tu(t,r);case f.ZodNaN:case f.ZodNever:return vu();case f.ZodEffects:return cu(t,r);case f.ZodAny:return ru();case f.ZodUnknown:return Ou();case f.ZodDefault:return lu(t,r);case f.ZodBranded:return Ka(t,r);case f.ZodReadonly:return Ru(t,r);case f.ZodCatch:return iu(t,r);case f.ZodPipeline:return Eu(t,r);case f.ZodFunction:case f.ZodVoid:case f.ZodSymbol:return;default:return(n=>{})()}},Mu=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),Du=(t,e)=>{const r=tu(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[c,d])=>({...l,[c]:C(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=C(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 Kt={code:"0",name:"text",parse:t=>{if(typeof t!="string")throw new Error('"text" parts expect a string value.');return{type:"text",value:t}}},Xt={code:"3",name:"error",parse:t=>{if(typeof t!="string")throw new Error('"error" parts expect a string value.');return{type:"error",value:t}}},Qt={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}}},er={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}}}},tr={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}}},Zu=[Kt,Xt,Qt,er,tr];Kt.code+"",Xt.code+"",Qt.code+"",er.code+"",tr.code+"";Kt.name+"",Kt.code,Xt.name+"",Xt.code,Qt.name+"",Qt.code,er.name+"",er.code,tr.name+"",tr.code;Zu.map(t=>t.code);function Uu(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 Lu(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let e=ut({text:t});return e.success?{value:e.value,state:"successful-parse"}:(e=ut({text:Uu(t)}),e.success?{value:e.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var rr={code:"0",name:"text",parse:t=>{if(typeof t!="string")throw new Error('"text" parts expect a string value.');return{type:"text",value:t}}},nr={code:"2",name:"data",parse:t=>{if(!Array.isArray(t))throw new Error('"data" parts expect an array value.');return{type:"data",value:t}}},sr={code:"3",name:"error",parse:t=>{if(typeof t!="string")throw new Error('"error" parts expect a string value.');return{type:"error",value:t}}},ar={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}}},ir={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}}},or={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}}},lr={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}}},cr={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}}},ur={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}}},dr={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}}},pr={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}}}},hr={code:"g",name:"reasoning",parse:t=>{if(typeof t!="string")throw new Error('"reasoning" parts expect a string value.');return{type:"reasoning",value:t}}},ti=[rr,nr,sr,ar,ir,or,lr,cr,ur,dr,pr,hr];rr.code+"",nr.code+"",sr.code+"",ar.code+"",ir.code+"",or.code+"",lr.code+"",cr.code+"",ur.code+"",dr.code+"",pr.code+"",hr.code+"";rr.name+"",rr.code,nr.name+"",nr.code,sr.name+"",sr.code,ar.name+"",ar.code,ir.name+"",ir.code,or.name+"",or.code,lr.name+"",lr.code,cr.name+"",cr.code,ur.name+"",ur.code,dr.name+"",dr.code,pr.name+"",pr.code,hr.name+"",hr.code;ti.map(t=>t.code);function ri(t,e){const r=ti.find(n=>n.name===t);if(!r)throw new Error(`Invalid stream part type: ${t}`);return`${r.code}:${JSON.stringify(e)}
154
- `}function Fu(t){return ni(Du(t,{$refStrategy:"none",target:"jsonSchema7"}),{validate:e=>{const r=t.safeParse(e);return r.success?{success:!0,value:r.data}:{success:!1,error:r.error}}})}var Nn=Symbol.for("vercel.ai.schema");function ni(t,{validate:e}={}){return{[Nn]:!0,_type:void 0,[Mr]:!0,jsonSchema:t,validate:e}}function Vu(t){return typeof t=="object"&&t!==null&&Nn in t&&t[Nn]===!0&&"jsonSchema"in t&&"validate"in t}function Mn(t){return Vu(t)?t:Fu(t)}var Bu=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},qe="1.9.0",Rs=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function zu(t){var e=new Set([t]),r=new Set,n=t.match(Rs);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(Rs);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 qu=zu(qe),Ju=qe.split(".")[0],fr=Symbol.for("opentelemetry.js.api."+Ju),mr=Bu;function Wn(t,e,r,n){var s;n===void 0&&(n=!1);var a=mr[fr]=(s=mr[fr])!==null&&s!==void 0?s:{version:qe};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!==qe){var i=new Error("@opentelemetry/api: Registration of version v"+a.version+" for "+t+" does not match previously registered API v"+qe);return r.error(i.stack||i.message),!1}return a[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+qe+"."),!0}function gr(t){var e,r,n=(e=mr[fr])===null||e===void 0?void 0:e.version;if(!(!n||!qu(n)))return(r=mr[fr])===null||r===void 0?void 0:r[t]}function Gn(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+qe+".");var r=mr[fr];r&&delete r[t]}var Hu=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},Wu=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))},Gu=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 St("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return St("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return St("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return St("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return St("verbose",this._namespace,e)},t}();function St(t,e,r){var n=gr("diag");if(n)return r.unshift(e),n[t].apply(n,Wu([],Hu(r),!1))}var Y;(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"})(Y||(Y={}));function Yu(t,e){t<Y.NONE?t=Y.NONE:t>Y.ALL&&(t=Y.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",Y.ERROR),warn:r("warn",Y.WARN),info:r("info",Y.INFO),debug:r("debug",Y.DEBUG),verbose:r("verbose",Y.VERBOSE)}}var Ku=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},Xu=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))},Qu="diag",Wr=function(){function t(){function e(s){return function(){for(var a=[],i=0;i<arguments.length;i++)a[i]=arguments[i];var o=gr("diag");if(o)return o[s].apply(o,Xu([],Ku(a),!1))}}var r=this,n=function(s,a){var i,o,l;if(a===void 0&&(a={logLevel:Y.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=gr("diag"),p=Yu((o=a.logLevel)!==null&&o!==void 0?o:Y.INFO,s);if(d&&!a.suppressOverrideMessage){var y=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+y),p.warn("Current logger will overwrite one already registered from "+y)}return Wn("diag",p,r,!0)};r.setLogger=n,r.disable=function(){Gn(Qu,r)},r.createComponentLogger=function(s){return new Gu(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 ed(t){return Symbol.for(t)}var td=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}(),rd=new td,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},sd=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))},ad=function(){function t(){}return t.prototype.active=function(){return rd},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,sd([n],nd(s),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}(),id=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},od=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))},_n="context",ld=new ad,si=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return Wn(_n,e,Wr.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,od([e,r,n],id(a),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return gr(_n)||ld},t.prototype.disable=function(){this._getContextManager().disable(),Gn(_n,Wr.instance())},t}(),Dn;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(Dn||(Dn={}));var ai="0000000000000000",ii="00000000000000000000000000000000",cd={traceId:ii,spanId:ai,traceFlags:Dn.NONE},Ot=function(){function t(e){e===void 0&&(e=cd),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}(),Yn=ed("OpenTelemetry Context Key SPAN");function Kn(t){return t.getValue(Yn)||void 0}function ud(){return Kn(si.getInstance().active())}function Xn(t,e){return t.setValue(Yn,e)}function dd(t){return t.deleteValue(Yn)}function pd(t,e){return Xn(t,new Ot(e))}function oi(t){var e;return(e=Kn(t))===null||e===void 0?void 0:e.spanContext()}var hd=/^([0-9a-f]{32})$/i,fd=/^[0-9a-f]{16}$/i;function md(t){return hd.test(t)&&t!==ii}function gd(t){return fd.test(t)&&t!==ai}function li(t){return md(t.traceId)&&gd(t.spanId)}function yd(t){return new Ot(t)}var bn=si.getInstance(),ci=function(){function t(){}return t.prototype.startSpan=function(e,r,n){n===void 0&&(n=bn.active());var s=!!(r!=null&&r.root);if(s)return new Ot;var a=n&&oi(n);return vd(a)&&li(a)?new Ot(a):new Ot},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??bn.active(),c=this.startSpan(e,a,l),d=Xn(l,c);return bn.with(d,o,void 0,c)}},t}();function vd(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var _d=new ci,bd=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):_d},t}(),wd=function(){function t(){}return t.prototype.getTracer=function(e,r,n){return new ci},t}(),xd=new wd,Ps=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 bd(this,e,r,n)},t.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:xd},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}(),Gr;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(Gr||(Gr={}));var wn="trace",Ad=function(){function t(){this._proxyTracerProvider=new Ps,this.wrapSpanContext=yd,this.isSpanContextValid=li,this.deleteSpan=dd,this.getSpan=Kn,this.getActiveSpan=ud,this.getSpanContext=oi,this.setSpan=Xn,this.setSpanContext=pd}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(e){var r=Wn(wn,this._proxyTracerProvider,Wr.instance());return r&&this._proxyTracerProvider.setDelegate(e),r},t.prototype.getTracerProvider=function(){return gr(wn)||this._proxyTracerProvider},t.prototype.getTracer=function(e,r){return this.getTracerProvider().getTracer(e,r)},t.prototype.disable=function(){Gn(wn,Wr.instance()),this._proxyTracerProvider=new Ps},t}(),Sd=Ad.getInstance(),kd=Object.defineProperty,Qn=(t,e)=>{for(var r in e)kd(t,r,{get:e[r],enumerable:!0})};function es(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 ui="AI_InvalidArgumentError",di=`vercel.ai.error.${ui}`,Ed=Symbol.for(di),pi,M=class extends ${constructor({parameter:t,value:e,message:r}){super({name:ui,message:`Invalid argument for parameter ${t}: ${r}`}),this[pi]=!0,this.parameter=t,this.value=e}static isInstance(t){return $.hasMarker(t,di)}};pi=Ed;var hi="AI_RetryError",fi=`vercel.ai.error.${hi}`,Td=Symbol.for(fi),mi,js=class extends ${constructor({message:t,reason:e,errors:r}){super({name:hi,message:t}),this[mi]=!0,this.reason=e,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return $.hasMarker(t,fi)}};mi=Td;var Id=({maxRetries:t=2,initialDelayInMs:e=2e3,backoffFactor:r=2}={})=>async n=>gi(n,{maxRetries:t,delayInMs:e,backoffFactor:r});async function gi(t,{maxRetries:e,delayInMs:r,backoffFactor:n},s=[]){try{return await t()}catch(a){if(Cr(a)||e===0)throw a;const i=hl(a),o=[...s,a],l=o.length;if(l>e)throw new js({message:`Failed after ${l} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:o});if(a instanceof Error&&me.isInstance(a)&&a.isRetryable===!0&&l<=e)return await pl(r),gi(t,{maxRetries:e,delayInMs:n*r,backoffFactor:n},o);throw l===1?a:new js({message:`Failed after ${l} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:o})}}function $d({maxRetries:t}){if(t!=null){if(!Number.isInteger(t))throw new M({parameter:"maxRetries",value:t,message:"maxRetries must be an integer"});if(t<0)throw new M({parameter:"maxRetries",value:t,message:"maxRetries must be >= 0"})}const e=t??2;return{maxRetries:e,retry:Id({maxRetries:e})}}function xn({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 Cd({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 Od={startSpan(){return Ar},startActiveSpan(t,e,r,n){if(typeof e=="function")return e(Ar);if(typeof r=="function")return r(Ar);if(typeof n=="function")return n(Ar)}},Ar={spanContext(){return Rd},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}},Rd={traceId:"",spanId:"",traceFlags:0};function Pd({isEnabled:t=!1,tracer:e}={}){return t?e||Sd.getTracer("ai"):Od}function An({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:Gr.ERROR,message:i.message})):a.setStatus({code:Gr.ERROR})}finally{a.end()}throw i}})}function tt({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 yi="AI_NoObjectGeneratedError",vi=`vercel.ai.error.${yi}`,jd=Symbol.for(vi),_i,Je=class extends ${constructor({message:t="No object generated.",cause:e,text:r,response:n,usage:s}){super({name:yi,message:t,cause:e}),this[_i]=!0,this.text=r,this.response=n,this.usage=s}static isInstance(t){return $.hasMarker(t,vi)}};_i=jd;var bi="AI_DownloadError",wi=`vercel.ai.error.${bi}`,Nd=Symbol.for(wi),xi,Sn=class extends ${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:bi,message:s,cause:n}),this[xi]=!0,this.url=t,this.statusCode=e,this.statusText=r}static isInstance(t){return $.hasMarker(t,wi)}};xi=Nd;async function Md({url:t,fetchImplementation:e=fetch}){var r;const n=t.toString();try{const s=await e(n);if(!s.ok)throw new Sn({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 Sn.isInstance(s)?s:new Sn({url:n,cause:s})}}var Dd=[{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 Zd(t){for(const{bytes:e,mimeType:r}of Dd)if(t.length>=e.length&&e.every((n,s)=>t[s]===n))return r}var Ai="AI_InvalidDataContentError",Si=`vercel.ai.error.${Ai}`,Ud=Symbol.for(Si),ki,Ns=class extends ${constructor({content:t,cause:e,message:r=`Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof t}.`}){super({name:Ai,message:r,cause:e}),this[ki]=!0,this.content=t}static isInstance(t){return $.hasMarker(t,Si)}};ki=Ud;var Ei=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 Ld(t){return typeof t=="string"?t:t instanceof ArrayBuffer?Cn(new Uint8Array(t)):Cn(t)}function Yr(t){if(t instanceof Uint8Array)return t;if(typeof t=="string")try{return Tl(t)}catch(e){throw new Ns({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 Ns({content:t})}function Fd(t){try{return new TextDecoder().decode(t)}catch{throw new Error("Error decoding Uint8Array to text")}}var Ti="AI_InvalidMessageRoleError",Ii=`vercel.ai.error.${Ti}`,Vd=Symbol.for(Ii),$i,Bd=class extends ${constructor({role:t,message:e=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Ti,message:e}),this[$i]=!0,this.role=t}static isInstance(t){return $.hasMarker(t,Ii)}};$i=Vd;function zd(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 Ms({prompt:t,modelSupportsImageUrls:e=!0,modelSupportsUrl:r=()=>!1,downloadImplementation:n=Md}){const s=await Jd(t.messages,n,e,r);return[...t.system!=null?[{role:"system",content:t.system}]:[],...t.messages.map(a=>qd(a,s))]}function qd(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=>Hd(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,...y}=c;return{...y,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 Bd({role:c})}}}async function Jd(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 Hd(t,e){var r;if(t.type==="text")return{type:"text",text:t.text,providerMetadata:t.experimental_providerMetadata};let n=t.mimeType,s,a,i;const o=t.type;switch(o){case"image":s=t.image;break;case"file":s=t.data;break;default:throw new Error(`Unsupported part type: ${o}`)}try{a=typeof s=="string"?new URL(s):s}catch{a=s}if(a instanceof URL)if(a.protocol==="data:"){const{mimeType:l,base64Content:c}=zd(a.toString());if(l==null||c==null)throw new Error(`Invalid data URL format in part ${o}`);n=l,i=Yr(c)}else{const l=e[a.toString()];l?(i=l.data,n??(n=l.mimeType)):i=a}else i=Yr(a);switch(o){case"image":return i instanceof Uint8Array&&(n=(r=Zd(i))!=null?r:n),{type:"image",image:i,mimeType:n,providerMetadata:t.experimental_providerMetadata};case"file":{if(n==null)throw new Error("Mime type is missing for file part");return{type:"file",data:i instanceof Uint8Array?Ld(i):i,mimeType:n,providerMetadata:t.experimental_providerMetadata}}}}function Ds({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 M({parameter:"maxTokens",value:t,message:"maxTokens must be an integer"});if(t<1)throw new M({parameter:"maxTokens",value:t,message:"maxTokens must be >= 1"})}if(e!=null&&typeof e!="number")throw new M({parameter:"temperature",value:e,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new M({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new M({parameter:"topK",value:n,message:"topK must be a number"});if(s!=null&&typeof s!="number")throw new M({parameter:"presencePenalty",value:s,message:"presencePenalty must be a number"});if(a!=null&&typeof a!="number")throw new M({parameter:"frequencyPenalty",value:a,message:"frequencyPenalty must be a number"});if(o!=null&&!Number.isInteger(o))throw new M({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 Wd(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:Yr(l)});else if((n=a.contentType)!=null&&n.startsWith("text/"))s.push({type:"text",text:Fd(Yr(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 Ci="AI_MessageConversionError",Oi=`vercel.ai.error.${Ci}`,Gd=Symbol.for(Oi),Ri,Zs=class extends ${constructor({originalMessage:t,message:e}){super({name:Ci,message:e}),this[Ri]=!0,this.originalMessage=t}static isInstance(t){return $.hasMarker(t,Oi)}};Ri=Gd;function Yd(t,e){var r;const n=(r=e==null?void 0:e.tools)!=null?r:{},s=[];for(let a=0;a<t.length;a++){const i=t[a],o=a===t.length-1,{role:l,content:c,toolInvocations:d,experimental_attachments:p}=i;switch(l){case"system":{s.push({role:"system",content:c});break}case"user":{s.push({role:"user",content:p?[{type:"text",text:c},...Wd(p)]:c});break}case"assistant":{if(d==null||d.length===0){s.push({role:"assistant",content:c});break}const y=d.reduce((v,x)=>{var m;return Math.max(v,(m=x.step)!=null?m:0)},0);for(let v=0;v<=y;v++){const x=d.filter(m=>{var g;return((g=m.step)!=null?g:0)===v});x.length!==0&&(s.push({role:"assistant",content:[...o&&c&&v===0?[{type:"text",text:c}]:[],...x.map(({toolCallId:m,toolName:g,args:T})=>({type:"tool-call",toolCallId:m,toolName:g,args:T}))]}),s.push({role:"tool",content:x.map(m=>{if(!("result"in m))throw new Zs({originalMessage:i,message:"ToolInvocation must have a result: "+JSON.stringify(m)});const{toolCallId:g,toolName:T,result:S}=m,j=n[T];return(j==null?void 0:j.experimental_toToolResultContent)!=null?{type:"tool-result",toolCallId:g,toolName:T,result:j.experimental_toToolResultContent(S),experimental_content:j.experimental_toToolResultContent(S)}:{type:"tool-result",toolCallId:g,toolName:T,result:S}})}))}c&&!o&&s.push({role:"assistant",content:c});break}case"data":break;default:{const y=l;throw new Zs({originalMessage:i,message:`Unsupported role: ${y}`})}}}return s}function Kd(t){if(!Array.isArray(t))return"other";if(t.length===0)return"messages";const e=t.map(Xd);return e.some(r=>r==="has-ui-specific-parts")?"ui-messages":e.every(r=>r==="has-core-specific-parts"||r==="message")?"messages":"other"}function Xd(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 Zn=u.lazy(()=>u.union([u.null(),u.string(),u.number(),u.boolean(),u.record(u.string(),Zn),u.array(Zn)])),V=u.record(u.string(),u.record(u.string(),Zn)),Qd=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()})])),Pi=u.object({type:u.literal("text"),text:u.string(),providerOptions:V.optional(),experimental_providerMetadata:V.optional()}),ep=u.object({type:u.literal("image"),image:u.union([Ei,u.instanceof(URL)]),mimeType:u.string().optional(),providerOptions:V.optional(),experimental_providerMetadata:V.optional()}),tp=u.object({type:u.literal("file"),data:u.union([Ei,u.instanceof(URL)]),mimeType:u.string(),providerOptions:V.optional(),experimental_providerMetadata:V.optional()}),rp=u.object({type:u.literal("tool-call"),toolCallId:u.string(),toolName:u.string(),args:u.unknown(),providerOptions:V.optional(),experimental_providerMetadata:V.optional()}),np=u.object({type:u.literal("tool-result"),toolCallId:u.string(),toolName:u.string(),result:u.unknown(),content:Qd.optional(),isError:u.boolean().optional(),providerOptions:V.optional(),experimental_providerMetadata:V.optional()}),sp=u.object({role:u.literal("system"),content:u.string(),providerOptions:V.optional(),experimental_providerMetadata:V.optional()}),ap=u.object({role:u.literal("user"),content:u.union([u.string(),u.array(u.union([Pi,ep,tp]))]),providerOptions:V.optional(),experimental_providerMetadata:V.optional()}),ip=u.object({role:u.literal("assistant"),content:u.union([u.string(),u.array(u.union([Pi,rp]))]),providerOptions:V.optional(),experimental_providerMetadata:V.optional()}),op=u.object({role:u.literal("tool"),content:u.array(np),providerOptions:V.optional(),experimental_providerMetadata:V.optional()}),lp=u.union([sp,ap,ip,op]);function Us({prompt:t,tools:e}){if(t.prompt==null&&t.messages==null)throw new Be({prompt:t,message:"prompt or messages must be defined"});if(t.prompt!=null&&t.messages!=null)throw new Be({prompt:t,message:"prompt and messages cannot be defined at the same time"});if(t.system!=null&&typeof t.system!="string")throw new Be({prompt:t,message:"system must be a string"});if(t.prompt!=null){if(typeof t.prompt!="string")throw new Be({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=Kd(t.messages);if(r==="other")throw new Be({prompt:t,message:"messages must be an array of CoreMessage or UIMessage"});const n=r==="ui-messages"?Yd(t.messages,{tools:e}):t.messages,s=Ge({value:n,schema:u.array(lp)});if(!s.success)throw new Be({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 rt({promptTokens:t,completionTokens:e}){return{promptTokens:t,completionTokens:e,totalTokens:t+e}}var cp="JSON schema:",up="You MUST answer with a JSON object that matches the JSON schema above.",dp="You MUST answer with JSON.";function Un({prompt:t,schema:e,schemaPrefix:r=e!=null?cp:void 0,schemaSuffix:n=e!=null?up:dp}){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(`
155
- `)}function pp(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 hp={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 Je({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 F({functionality:"element streams in no-schema mode"})}},fp=t=>({type:"object",jsonSchema:t.jsonSchema,validatePartialResult({value:e,textDelta:r}){return{success:!0,value:{partial:e,textDelta:r}}},validateFinalResult(e){return Ge({value:e,schema:t})},createElementStream(){throw new F({functionality:"element streams in object mode"})}}),mp=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(!$n(n)||!bs(n.elements))return{success:!1,error:new Oe({value:n,cause:"value must be an object that contains an array of elements"})};const l=n.elements,c=[];for(let y=0;y<l.length;y++){const v=l[y],x=Ge({value:v,schema:t});if(!(y===l.length-1&&!i)){if(!x.success)return x;c.push(x.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(y=>JSON.stringify(y)).join(","),i&&(p+="]"),{success:!0,value:{partial:c,textDelta:p}}},validateFinalResult(n){if(!$n(n)||!bs(n.elements))return{success:!1,error:new Oe({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=Ge({value:a,schema:t});if(!i.success)return i}return{success:!0,value:s}},createElementStream(n){let s=0;return pp(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":break;case"error":i.error(a.error);break;default:{const o=a;throw new Error(`Unsupported chunk type: ${o}`)}}}})))}}},gp=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(!$n(e)||typeof e.result!="string")return{success:!1,error:new Oe({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 Oe({value:e,cause:"value must be a string in the enum"})}},validatePartialResult(){throw new F({functionality:"partial results in enum mode"})},createElementStream(){throw new F({functionality:"element streams in enum mode"})}});function yp({output:t,schema:e,enumValues:r}){switch(t){case"object":return fp(Mn(e));case"array":return mp(Mn(e));case"enum":return gp(r);case"no-schema":return hp;default:{const n=t;throw new Error(`Unsupported output: ${n}`)}}}function vp({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 M({parameter:"output",value:t,message:"Invalid output type."});if(t==="no-schema"){if(e==="auto"||e==="tool")throw new M({parameter:"mode",value:e,message:'Mode must be "json" for no-schema output.'});if(r!=null)throw new M({parameter:"schema",value:r,message:"Schema is not supported for no-schema output."});if(s!=null)throw new M({parameter:"schemaDescription",value:s,message:"Schema description is not supported for no-schema output."});if(n!=null)throw new M({parameter:"schemaName",value:n,message:"Schema name is not supported for no-schema output."});if(a!=null)throw new M({parameter:"enumValues",value:a,message:"Enum values are not supported for no-schema output."})}if(t==="object"){if(r==null)throw new M({parameter:"schema",value:r,message:"Schema is required for object output."});if(a!=null)throw new M({parameter:"enumValues",value:a,message:"Enum values are not supported for object output."})}if(t==="array"){if(r==null)throw new M({parameter:"schema",value:r,message:"Element schema is required for array output."});if(a!=null)throw new M({parameter:"enumValues",value:a,message:"Enum values are not supported for array output."})}if(t==="enum"){if(r!=null)throw new M({parameter:"schema",value:r,message:"Schema is not supported for enum output."});if(s!=null)throw new M({parameter:"schemaDescription",value:s,message:"Schema description is not supported for enum output."});if(n!=null)throw new M({parameter:"schemaName",value:n,message:"Schema name is not supported for enum output."});if(a==null)throw new M({parameter:"enumValues",value:a,message:"Enum values are required for enum output."});for(const i of a)if(typeof i!="string")throw new M({parameter:"enumValues",value:i,message:"Enum values must be strings."})}}var _p=et({prefix:"aiobj",size:24});async function bp({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:y,experimental_telemetry:v,experimental_providerMetadata:x,providerOptions:m=x,_internal:{generateId:g=_p,currentDate:T=()=>new Date}={},...S}){vp({output:i,mode:a,schema:r,schemaName:n,schemaDescription:s,enumValues:e});const{maxRetries:j,retry:ne}=$d({maxRetries:d}),N=yp({output:i,schema:r,enumValues:e});N.type==="no-schema"&&a===void 0&&(a="json");const Q=Cd({model:t,telemetry:v,headers:y,settings:{...S,maxRetries:j}}),O=Pd(v);return An({name:"ai.generateObject",attributes:tt({telemetry:v,attributes:{...xn({operationId:"ai.generateObject",telemetry:v}),...Q,"ai.prompt":{input:()=>JSON.stringify({system:o,prompt:l,messages:c})},"ai.schema":N.jsonSchema!=null?{input:()=>JSON.stringify(N.jsonSchema)}:void 0,"ai.schema.name":n,"ai.schema.description":s,"ai.settings.output":N.type,"ai.settings.mode":a}}),tracer:O,fn:async he=>{var Me,De,Ze,Ue;(a==="auto"||a==null)&&(a=t.defaultObjectGenerationMode);let _e,se,B,be,Ee,we,U,ae,L;switch(a){case"json":{const Te=Us({prompt:{system:N.jsonSchema==null?Un({prompt:o}):t.supportsStructuredOutputs?o:Un({prompt:o,schema:N.jsonSchema}),prompt:l,messages:c},tools:void 0}),gt=await Ms({prompt:Te,modelSupportsImageUrls:t.supportsImageUrls,modelSupportsUrl:(Me=t.supportsUrl)==null?void 0:Me.bind(t)}),ee=await ne(()=>An({name:"ai.generateObject.doGenerate",attributes:tt({telemetry:v,attributes:{...xn({operationId:"ai.generateObject.doGenerate",telemetry:v}),...Q,"ai.prompt.format":{input:()=>Te.type},"ai.prompt.messages":{input:()=>JSON.stringify(gt)},"ai.settings.mode":a,"gen_ai.system":t.provider,"gen_ai.request.model":t.modelId,"gen_ai.request.frequency_penalty":S.frequencyPenalty,"gen_ai.request.max_tokens":S.maxTokens,"gen_ai.request.presence_penalty":S.presencePenalty,"gen_ai.request.temperature":S.temperature,"gen_ai.request.top_k":S.topK,"gen_ai.request.top_p":S.topP}}),tracer:O,fn:async ie=>{var br,yt,vt,_t,bt,wt;const z=await t.doGenerate({mode:{type:"object-json",schema:N.jsonSchema,name:n,description:s},...Ds(S),inputFormat:Te.type,prompt:gt,providerMetadata:m,abortSignal:p,headers:y}),fe={id:(yt=(br=z.response)==null?void 0:br.id)!=null?yt:g(),timestamp:(_t=(vt=z.response)==null?void 0:vt.timestamp)!=null?_t:T(),modelId:(wt=(bt=z.response)==null?void 0:bt.modelId)!=null?wt:t.modelId};if(z.text===void 0)throw new Je({message:"No object generated: the model did not return a response.",response:fe,usage:rt(z.usage)});return ie.setAttributes(tt({telemetry:v,attributes:{"ai.response.finishReason":z.finishReason,"ai.response.object":{output:()=>z.text},"ai.response.id":fe.id,"ai.response.model":fe.modelId,"ai.response.timestamp":fe.timestamp.toISOString(),"ai.usage.promptTokens":z.usage.promptTokens,"ai.usage.completionTokens":z.usage.completionTokens,"gen_ai.response.finish_reasons":[z.finishReason],"gen_ai.response.id":fe.id,"gen_ai.response.model":fe.modelId,"gen_ai.usage.prompt_tokens":z.usage.promptTokens,"gen_ai.usage.completion_tokens":z.usage.completionTokens}})),{...z,objectText:z.text,responseData:fe}}}));_e=ee.objectText,se=ee.finishReason,B=ee.usage,be=ee.warnings,Ee=ee.rawResponse,ae=ee.logprobs,L=ee.providerMetadata,U=(De=ee.request)!=null?De:{},we=ee.responseData;break}case"tool":{const Te=Us({prompt:{system:o,prompt:l,messages:c},tools:void 0}),gt=await Ms({prompt:Te,modelSupportsImageUrls:t.supportsImageUrls,modelSupportsUrl:(Ze=t.supportsUrl)==null?void 0:Ze.bind(t)}),ee=Te.type,ie=await ne(()=>An({name:"ai.generateObject.doGenerate",attributes:tt({telemetry:v,attributes:{...xn({operationId:"ai.generateObject.doGenerate",telemetry:v}),...Q,"ai.prompt.format":{input:()=>ee},"ai.prompt.messages":{input:()=>JSON.stringify(gt)},"ai.settings.mode":a,"gen_ai.system":t.provider,"gen_ai.request.model":t.modelId,"gen_ai.request.frequency_penalty":S.frequencyPenalty,"gen_ai.request.max_tokens":S.maxTokens,"gen_ai.request.presence_penalty":S.presencePenalty,"gen_ai.request.temperature":S.temperature,"gen_ai.request.top_k":S.topK,"gen_ai.request.top_p":S.topP}}),tracer:O,fn:async br=>{var yt,vt,_t,bt,wt,z,fe,as;const te=await t.doGenerate({mode:{type:"object-tool",tool:{type:"function",name:n??"json",description:s??"Respond with a JSON object.",parameters:N.jsonSchema}},...Ds(S),inputFormat:ee,prompt:gt,providerMetadata:m,abortSignal:p,headers:y}),an=(vt=(yt=te.toolCalls)==null?void 0:yt[0])==null?void 0:vt.args,Le={id:(bt=(_t=te.response)==null?void 0:_t.id)!=null?bt:g(),timestamp:(z=(wt=te.response)==null?void 0:wt.timestamp)!=null?z:T(),modelId:(as=(fe=te.response)==null?void 0:fe.modelId)!=null?as:t.modelId};if(an===void 0)throw new Je({message:"No object generated: the tool was not called.",response:Le,usage:rt(te.usage)});return br.setAttributes(tt({telemetry:v,attributes:{"ai.response.finishReason":te.finishReason,"ai.response.object":{output:()=>an},"ai.response.id":Le.id,"ai.response.model":Le.modelId,"ai.response.timestamp":Le.timestamp.toISOString(),"ai.usage.promptTokens":te.usage.promptTokens,"ai.usage.completionTokens":te.usage.completionTokens,"gen_ai.response.finish_reasons":[te.finishReason],"gen_ai.response.id":Le.id,"gen_ai.response.model":Le.modelId,"gen_ai.usage.input_tokens":te.usage.promptTokens,"gen_ai.usage.output_tokens":te.usage.completionTokens}})),{...te,objectText:an,responseData:Le}}}));_e=ie.objectText,se=ie.finishReason,B=ie.usage,be=ie.warnings,Ee=ie.rawResponse,ae=ie.logprobs,L=ie.providerMetadata,U=(Ue=ie.request)!=null?Ue:{},we=ie.responseData;break}case void 0:throw new Error("Model does not have a default object generation mode.");default:{const Te=a;throw new Error(`Unsupported mode: ${Te}`)}}const P=ut({text:_e});if(!P.success)throw new Je({message:"No object generated: could not parse the response.",cause:P.error,text:_e,response:we,usage:rt(B)});const _r=N.validateFinalResult(P.value,{text:_e,response:we,usage:rt(B)});if(!_r.success)throw new Je({message:"No object generated: response did not match schema.",cause:_r.error,text:_e,response:we,usage:rt(B)});return he.setAttributes(tt({telemetry:v,attributes:{"ai.response.finishReason":se,"ai.response.object":{output:()=>JSON.stringify(_r.value)},"ai.usage.promptTokens":B.promptTokens,"ai.usage.completionTokens":B.completionTokens}})),new wp({object:_r.value,finishReason:se,usage:rt(B),warnings:be,request:U,response:{...we,headers:Ee==null?void 0:Ee.headers},logprobs:ae,providerMetadata:L})}})}var wp=class{constructor(t){this.object=t.object,this.finishReason=t.finishReason,this.usage=t.usage,this.warnings=t.warnings,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:es(t==null?void 0:t.headers,{contentType:"application/json; charset=utf-8"})})}};et({prefix:"aiobj",size:24});et({prefix:"aitxt",size:24});et({prefix:"msg",size:24});var xp={};Qn(xp,{object:()=>Sp,text:()=>Ap});var Ap=()=>({type:"text",responseFormat:()=>({type:"text"}),injectIntoSystemPrompt({system:t}){return t},parsePartial({text:t}){return{partial:t}},parseOutput({text:t}){return t}}),Sp=({schema:t})=>{const e=Mn(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:Un({prompt:r,schema:e.jsonSchema})},parsePartial({text:r}){const n=Lu(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=ut({text:r});if(!s.success)throw new Je({message:"No object generated: could not parse the response.",cause:s.error,text:r,response:n.response,usage:n.usage});const a=Ge({value:s.value,schema:e});if(!a.success)throw new Je({message:"No object generated: response did not match schema.",cause:a.error,text:r,response:n.response,usage:n.usage});return a.value}}};function ji(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:y}=await Promise.race([s.then(v=>({result:v,reader:r})),a.then(v=>({result:v,reader:n}))]);p.done||d.enqueue(p.value),y===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()}})}et({prefix:"aitxt",size:24});et({prefix:"msg",size:24});var kp={};Qn(kp,{mergeIntoDataStream:()=>Ip,toDataStream:()=>Ep,toDataStreamResponse:()=>Tp});function Ni(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 ts(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"&&Ls((s=r.data)==null?void 0:s.chunk,n);return}Ls(r,n)}})).pipeThrough(Ni(e)).pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform:async(r,n)=>{n.enqueue(ri("text",r))}}))}function Ep(t,e){return ts(t,e).pipeThrough(new TextEncoderStream)}function Tp(t,e){var r;const n=ts(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?ji(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:es(a==null?void 0:a.headers,{contentType:"text/plain; charset=utf-8",dataStreamVersion:"v1"})})}function Ip(t,e){e.dataStream.merge(ts(t,e.callbacks))}function Ls(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 $p={};Qn($p,{mergeIntoDataStream:()=>Rp,toDataStream:()=>Cp,toDataStreamResponse:()=>Op});function rs(t,e){const r=Pp();return dl(t[Symbol.asyncIterator]()).pipeThrough(new TransformStream({async transform(n,s){s.enqueue(r(n.delta))}})).pipeThrough(Ni(e)).pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform:async(n,s)=>{s.enqueue(ri("text",n))}}))}function Cp(t,e){return rs(t,e).pipeThrough(new TextEncoderStream)}function Op(t,e={}){var r;const{init:n,data:s,callbacks:a}=e,i=rs(t,a).pipeThrough(new TextEncoderStream),o=s?ji(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:es(n==null?void 0:n.headers,{contentType:"text/plain; charset=utf-8",dataStreamVersion:"v1"})})}function Rp(t,e){e.dataStream.merge(rs(t,e.callbacks))}function Pp(){let t=!0;return e=>(t&&(e=e.trimStart(),e&&(t=!1)),e)}function jp(t){return` In this environment you have access to a set of tools. Here are the functions available in JSONSchema format:
156
- ${t.actions}
157
- Choose one or more functions to call to respond to the user's query.
158
- `}function Np(t){const e={type:"object",properties:{tools:{type:"array",items:{anyOf:t.actions.map(r=>{const n={type:"object",properties:{id:{type:"string",enum:[r.id]}},additionalProperties:!1,required:["id"]};return r.parameters&&(n.properties.arguments=r.parameters,n.properties.arguments.required||(n.properties.arguments.required=Object.keys(n.properties.arguments.properties)),n.properties.arguments.additionalProperties=!1,n.required.push("arguments")),n})},additionalProperties:!1}},required:["tools"],additionalProperties:!1};return ni(e)}async function Mp(t,e){var l;const r=(l=G.get().settings)==null?void 0:l.openAIAPIToken,s=Ga({apiKey:r,compatibility:"strict"})("gpt-4o-mini"),a=jp(e),i=Np(e),{object:o}=await bp({model:s,prompt:t,system:a,schema:i});return o.tools[0]}const Dp={getModelResponse:Mp};var Zp=Object.defineProperty,Up=Object.getOwnPropertyDescriptor,ns=(t,e,r,n)=>{for(var s=n>1?void 0:n?Up(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&&Zp(e,r,s),s};let Kr=class extends K{constructor(){super(...arguments),this.openAIAPIToken="",this.promptState="idle"}createRenderRoot(){return this}connectedCallback(){G.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;this.promptState="thinking",r.value="";const s=await Dp.getModelResponse(n,window.applet);window.applet.dispatchAction(s.id,s.arguments),this.promptState="idle"}render(){return H`
159
- <form @submit="${this.onSubmit}">
160
- <input
161
- autocomplete="off"
162
- id="prompt"
163
- name="prompt"
164
- .disabled="${!this.openAIAPIToken||this.promptState==="thinking"}"
165
- 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."}"
166
- />
167
- ${this.promptState==="thinking"?H`
168
- <svg
169
- xmlns="http://www.w3.org/2000/svg"
170
- width="24"
171
- height="24"
172
- viewBox="0 0 24 24"
173
- fill="none"
174
- stroke="currentColor"
175
- stroke-width="1"
176
- stroke-linecap="round"
177
- stroke-linejoin="round"
178
- class="loader"
179
- >
180
- <circle cx="12" cy="12" r="9" />
181
- </svg>
182
- `:Z}
183
- </form>
184
- `}};ns([re({type:String})],Kr.prototype,"openAIAPIToken",2);ns([re({type:String})],Kr.prototype,"promptState",2);Kr=ns([ke("app-prompt")],Kr);/**
185
- * @license
186
- * Copyright 2020 Google LLC
187
- * SPDX-License-Identifier: BSD-3-Clause
188
- */const Lp=t=>t.strings===void 0;/**
189
- * @license
190
- * Copyright 2017 Google LLC
191
- * SPDX-License-Identifier: BSD-3-Clause
192
- */const Fp={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},Vp=t=>(...e)=>({_$litDirective$:t,values:e});class Bp{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)}}/**
193
- * @license
194
- * Copyright 2017 Google LLC
195
- * SPDX-License-Identifier: BSD-3-Clause
196
- */const Rt=(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),Rt(s,e);return!0},Xr=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)},Mi=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),Jp(e)}};function zp(t){this._$AN!==void 0?(Xr(this),this._$AM=t,Mi(this)):this._$AM=t}function qp(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++)Rt(n[a],!1),Xr(n[a]);else n!=null&&(Rt(n,!1),Xr(n));else Rt(this,t)}const Jp=t=>{t.type==Fp.CHILD&&(t._$AP??(t._$AP=qp),t._$AQ??(t._$AQ=zp))};class Hp extends Bp{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,r,n){super._$AT(e,r,n),Mi(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&&(Rt(this,e),Xr(this))}setValue(e){if(Lp(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(){}}/**
197
- * @license
198
- * Copyright 2020 Google LLC
199
- * SPDX-License-Identifier: BSD-3-Clause
200
- */const Fs=()=>new Wp;class Wp{}const kn=new WeakMap,Vs=Vp(class extends Hp{render(t){return Z}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)),Z}rt(t){if(this.isConnected||(t=void 0),typeof this.Y=="function"){const e=this.ht??globalThis;let r=kn.get(e);r===void 0&&(r=new WeakMap,kn.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=kn.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 Gp=Object.defineProperty,Yp=Object.getOwnPropertyDescriptor,ss=(t,e,r,n)=>{for(var s=n>1?void 0:n?Yp(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&&Gp(e,r,s),s};let Qr=class extends K{constructor(){super(...arguments),this.open=!1,this.openAIAPIToken="",this.dialogRef=Fs(),this.formRef=Fs()}createRenderRoot(){return this}connectedCallback(){G.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=G.get().settings;G.update({settings:{openAIAPIToken:n,...s}}),this.onDismiss()}onClear(t){t.preventDefault();const e=G.get().settings;delete e.openAIAPIToken,G.update({settings:e})}onDismiss(){var t;(t=this.formRef.value)==null||t.reset(),G.update({settingsDialogOpen:!1})}render(){return H`
201
- <dialog ${Vs(this.dialogRef)}>
202
- <div class="dialog-header">
203
- <h2>Settings</h2>
204
- <button
205
- aria-label="close dialog"
206
- class="close-dialog-button"
207
- @click="${this.onDismiss}"
208
- >
209
- <svg
210
- focusable="false"
211
- xmlns="http://www.w3.org/2000/svg"
212
- width="24"
213
- height="24"
214
- viewBox="0 0 24 24"
215
- fill="none"
216
- stroke="currentColor"
217
- stroke-width="1"
218
- stroke-linecap="round"
219
- stroke-linejoin="round"
220
- >
221
- <path d="M18 6 6 18" />
222
- <path d="m6 6 12 12" />
223
- </svg>
224
- </button>
225
- </div>
226
- <div class="dialog-content">
227
- <form
228
- ${Vs(this.formRef)}
229
- id="settings-form"
230
- class="settings-form"
231
- @submit="${this.onSave}"
232
- >
233
- <fieldset .disabled=${!!this.openAIAPIToken}>
234
- <label for="openAIAPIToken">OpenAI API token</label>
235
-
236
- <input
237
- id="openAIAPIToken"
238
- name="openAIAPIToken"
239
- placeholder="${this.openAIAPIToken?"••••••••••••••••••••":""}"
240
- />
241
- </fieldset>
242
- ${this.openAIAPIToken?H`<button
243
- class="clear-button"
244
- ?disabled=${!1}
245
- @click="${this.onClear}"
246
- >
247
- Clear
248
- </button>`:Z}
249
- </form>
250
- </div>
251
- <div class="dialog-footer">
252
- <button type="submit" form="settings-form">Save</button>
253
- <button @click="${this.onDismiss}">Cancel</button>
254
- </div>
255
- </dialog>
256
- `}};ss([re({type:Boolean})],Qr.prototype,"open",2);ss([re({type:String})],Qr.prototype,"openAIAPIToken",2);Qr=ss([ke("settings-dialog")],Qr);var Kp=Object.defineProperty,Xp=Object.getOwnPropertyDescriptor,Qp=(t,e,r,n)=>{for(var s=n>1?void 0:n?Xp(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&&Kp(e,r,s),s};let Bs=class extends K{createRenderRoot(){return this}render(){return H`
257
- <app-header></app-header>
258
- <main>
259
- <app-sidebar></app-sidebar>
260
- <div class="column">
261
- <app-viewer></app-viewer>
262
- <app-prompt></app-prompt>
263
- </div>
264
- </main>
265
- <settings-dialog></settings-dialog>
266
- `}};Bs=Qp([ke("app-root")],Bs);