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