@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
|
+
(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))n(s);new MutationObserver(s=>{for(const a of s)if(a.type==="childList")for(const i of a.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&n(i)}).observe(document,{childList:!0,subtree:!0});function r(s){const a={};return s.integrity&&(a.integrity=s.integrity),s.referrerPolicy&&(a.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?a.credentials="include":s.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function n(s){if(s.ep)return;s.ep=!0;const a=r(s);fetch(s.href,a)}})();/**
|
2
|
+
* @license
|
3
|
+
* Copyright 2019 Google LLC
|
4
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
5
|
+
*/const Nr=globalThis,as=Nr.ShadowRoot&&(Nr.ShadyCSS===void 0||Nr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,_a=Symbol(),Es=new WeakMap;let po=class{constructor(e,r,n){if(this._$cssResult$=!0,n!==_a)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(as&&e===void 0){const n=r!==void 0&&r.length===1;n&&(e=Es.get(r)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&Es.set(r,e))}return e}toString(){return this.cssText}};const ho=t=>new po(typeof t=="string"?t:t+"",void 0,_a),fo=(t,e)=>{if(as)t.adoptedStyleSheets=e.map(r=>r instanceof CSSStyleSheet?r:r.styleSheet);else for(const r of e){const n=document.createElement("style"),s=Nr.litNonce;s!==void 0&&n.setAttribute("nonce",s),n.textContent=r.cssText,t.appendChild(n)}},Ts=as?t=>t:t=>t instanceof CSSStyleSheet?(e=>{let r="";for(const n of e.cssRules)r+=n.cssText;return ho(r)})(t):t;/**
|
6
|
+
* @license
|
7
|
+
* Copyright 2017 Google LLC
|
8
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
9
|
+
*/const{is:mo,defineProperty:go,getOwnPropertyDescriptor:yo,getOwnPropertyNames:vo,getOwnPropertySymbols:_o,getPrototypeOf:bo}=Object,ze=globalThis,$s=ze.trustedTypes,wo=$s?$s.emptyScript:"",An=ze.reactiveElementPolyfillSupport,Jt=(t,e)=>t,Ur={toAttribute(t,e){switch(e){case Boolean:t=t?wo: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}},is=(t,e)=>!mo(t,e),Is={attribute:!0,type:String,converter:Ur,reflect:!1,hasChanged:is};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),ze.litPropertyMetadata??(ze.litPropertyMetadata=new WeakMap);class vt 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=Is){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&&go(this.prototype,e,s)}}static getPropertyDescriptor(e,r,n){const{get:s,set:a}=yo(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)??Is}static _$Ei(){if(this.hasOwnProperty(Jt("elementProperties")))return;const e=bo(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Jt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Jt("properties"))){const r=this.properties,n=[...vo(r),..._o(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(Ts(s))}else e!==void 0&&r.push(Ts(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 fo(e,this.constructor.elementStyles),e}connectedCallback(){var e;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$EO)==null||e.forEach(r=>{var n;return(n=r.hostConnected)==null?void 0:n.call(r)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$EO)==null||e.forEach(r=>{var n;return(n=r.hostDisconnected)==null?void 0:n.call(r)})}attributeChangedCallback(e,r,n){this._$AK(e,n)}_$EC(e,r){var a;const n=this.constructor.elementProperties.get(e),s=this.constructor._$Eu(e,n);if(s!==void 0&&n.reflect===!0){const i=(((a=n.converter)==null?void 0:a.toAttribute)!==void 0?n.converter:Ur).toAttribute(r,n.type);this._$Em=e,i==null?this.removeAttribute(s):this.setAttribute(s,i),this._$Em=null}}_$AK(e,r){var a;const n=this.constructor,s=n._$Eh.get(e);if(s!==void 0&&this._$Em!==s){const i=n.getPropertyOptions(s),o=typeof i.converter=="function"?{fromAttribute:i.converter}:((a=i.converter)==null?void 0:a.fromAttribute)!==void 0?i.converter:Ur;this._$Em=s,this[s]=o.fromAttribute(r,i.type),this._$Em=null}}requestUpdate(e,r,n){if(e!==void 0){if(n??(n=this.constructor.getPropertyOptions(e)),!(n.hasChanged??is)(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){}}vt.elementStyles=[],vt.shadowRootOptions={mode:"open"},vt[Jt("elementProperties")]=new Map,vt[Jt("finalized")]=new Map,An==null||An({ReactiveElement:vt}),(ze.reactiveElementVersions??(ze.reactiveElementVersions=[])).push("2.0.4");/**
|
10
|
+
* @license
|
11
|
+
* Copyright 2017 Google LLC
|
12
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
13
|
+
*/const Wt=globalThis,Lr=Wt.trustedTypes,Cs=Lr?Lr.createPolicy("lit-html",{createHTML:t=>t}):void 0,ba="$lit$",De=`lit$${Math.random().toFixed(9).slice(2)}$`,wa="?"+De,xo=`<${wa}>`,it=document,er=()=>it.createComment(""),tr=t=>t===null||typeof t!="object"&&typeof t!="function",os=Array.isArray,Ao=t=>os(t)||typeof(t==null?void 0:t[Symbol.iterator])=="function",Sn=`[
|
14
|
+
\f\r]`,Lt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Os=/-->/g,Ps=/>/g,Xe=RegExp(`>|${Sn}(?:([^\\s"'>=/]+)(${Sn}*=${Sn}*(?:[^
|
15
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),Rs=/'/g,js=/"/g,xa=/^(?:script|style|textarea|title)$/i,So=t=>(e,...r)=>({_$litType$:t,strings:e,values:r}),U=So(1),ot=Symbol.for("lit-noChange"),F=Symbol.for("lit-nothing"),Ns=new WeakMap,rt=it.createTreeWalker(it,129);function Aa(t,e){if(!os(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return Cs!==void 0?Cs.createHTML(e):e}const ko=(t,e)=>{const r=t.length-1,n=[];let s,a=e===2?"<svg>":e===3?"<math>":"",i=Lt;for(let o=0;o<r;o++){const l=t[o];let c,d,p=-1,g=0;for(;g<l.length&&(i.lastIndex=g,d=i.exec(l),d!==null);)g=i.lastIndex,i===Lt?d[1]==="!--"?i=Os:d[1]!==void 0?i=Ps:d[2]!==void 0?(xa.test(d[2])&&(s=RegExp("</"+d[2],"g")),i=Xe):d[3]!==void 0&&(i=Xe):i===Xe?d[0]===">"?(i=s??Lt,p=-1):d[1]===void 0?p=-2:(p=i.lastIndex-d[2].length,c=d[1],i=d[3]===void 0?Xe:d[3]==='"'?js:Rs):i===js||i===Rs?i=Xe:i===Os||i===Ps?i=Lt:(i=Xe,s=void 0);const w=i===Xe&&t[o+1].startsWith("/>")?" ":"";a+=i===Lt?l+xo:p>=0?(n.push(c),l.slice(0,p)+ba+l.slice(p)+De+w):l+De+(p===-2?o:w)}return[Aa(t,a+(t[r]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]};class rr{constructor({strings:e,_$litType$:r},n){let s;this.parts=[];let a=0,i=0;const o=e.length-1,l=this.parts,[c,d]=ko(e,r);if(this.el=rr.createElement(c,n),rt.currentNode=this.el.content,r===2||r===3){const p=this.el.content.firstChild;p.replaceWith(...p.childNodes)}for(;(s=rt.nextNode())!==null&&l.length<o;){if(s.nodeType===1){if(s.hasAttributes())for(const p of s.getAttributeNames())if(p.endsWith(ba)){const g=d[i++],w=s.getAttribute(p).split(De),y=/([.?@])?(.*)/.exec(g);l.push({type:1,index:a,name:y[2],strings:w,ctor:y[1]==="."?To:y[1]==="?"?$o:y[1]==="@"?Io:fn}),s.removeAttribute(p)}else p.startsWith(De)&&(l.push({type:6,index:a}),s.removeAttribute(p));if(xa.test(s.tagName)){const p=s.textContent.split(De),g=p.length-1;if(g>0){s.textContent=Lr?Lr.emptyScript:"";for(let w=0;w<g;w++)s.append(p[w],er()),rt.nextNode(),l.push({type:2,index:++a});s.append(p[g],er())}}}else if(s.nodeType===8)if(s.data===wa)l.push({type:2,index:a});else{let p=-1;for(;(p=s.data.indexOf(De,p+1))!==-1;)l.push({type:7,index:a}),p+=De.length-1}a++}}static createElement(e,r){const n=it.createElement("template");return n.innerHTML=e,n}}function Tt(t,e,r=t,n){var i,o;if(e===ot)return e;let s=n!==void 0?(i=r._$Co)==null?void 0:i[n]:r._$Cl;const a=tr(e)?void 0:e._$litDirective$;return(s==null?void 0:s.constructor)!==a&&((o=s==null?void 0:s._$AO)==null||o.call(s,!1),a===void 0?s=void 0:(s=new a(t),s._$AT(t,r,n)),n!==void 0?(r._$Co??(r._$Co=[]))[n]=s:r._$Cl=s),s!==void 0&&(e=Tt(t,s._$AS(t,e.values),s,n)),e}class Eo{constructor(e,r){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=r}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:r},parts:n}=this._$AD,s=((e==null?void 0:e.creationScope)??it).importNode(r,!0);rt.currentNode=s;let a=rt.nextNode(),i=0,o=0,l=n[0];for(;l!==void 0;){if(i===l.index){let c;l.type===2?c=new $r(a,a.nextSibling,this,e):l.type===1?c=new l.ctor(a,l.name,l.strings,this,e):l.type===6&&(c=new Co(a,this,e)),this._$AV.push(c),l=n[++o]}i!==(l==null?void 0:l.index)&&(a=rt.nextNode(),i++)}return rt.currentNode=it,s}p(e){let r=0;for(const n of this._$AV)n!==void 0&&(n.strings!==void 0?(n._$AI(e,n,r),r+=n.strings.length-2):n._$AI(e[r])),r++}}class $r{get _$AU(){var e;return((e=this._$AM)==null?void 0:e._$AU)??this._$Cv}constructor(e,r,n,s){this.type=2,this._$AH=F,this._$AN=void 0,this._$AA=e,this._$AB=r,this._$AM=n,this.options=s,this._$Cv=(s==null?void 0:s.isConnected)??!0}get parentNode(){let e=this._$AA.parentNode;const r=this._$AM;return r!==void 0&&(e==null?void 0:e.nodeType)===11&&(e=r.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,r=this){e=Tt(this,e,r),tr(e)?e===F||e==null||e===""?(this._$AH!==F&&this._$AR(),this._$AH=F):e!==this._$AH&&e!==ot&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Ao(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==F&&tr(this._$AH)?this._$AA.nextSibling.data=e:this.T(it.createTextNode(e)),this._$AH=e}$(e){var a;const{values:r,_$litType$:n}=e,s=typeof n=="number"?this._$AC(e):(n.el===void 0&&(n.el=rr.createElement(Aa(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 Eo(s,this),o=i.u(this.options);i.p(r),this.T(o),this._$AH=i}}_$AC(e){let r=Ns.get(e.strings);return r===void 0&&Ns.set(e.strings,r=new rr(e)),r}k(e){os(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 $r(this.O(er()),this.O(er()),this,this.options)):n=r[s],n._$AI(a),s++;s<r.length&&(this._$AR(n&&n._$AB.nextSibling,s),r.length=s)}_$AR(e=this._$AA.nextSibling,r){var n;for((n=this._$AP)==null?void 0:n.call(this,!1,!0,r);e&&e!==this._$AB;){const s=e.nextSibling;e.remove(),e=s}}setConnected(e){var r;this._$AM===void 0&&(this._$Cv=e,(r=this._$AP)==null||r.call(this,e))}}class fn{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,r,n,s,a){this.type=1,this._$AH=F,this._$AN=void 0,this.element=e,this.name=r,this._$AM=s,this.options=a,n.length>2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=F}_$AI(e,r=this,n,s){const a=this.strings;let i=!1;if(a===void 0)e=Tt(this,e,r,0),i=!tr(e)||e!==this._$AH&&e!==ot,i&&(this._$AH=e);else{const o=e;let l,c;for(e=a[0],l=0;l<a.length-1;l++)c=Tt(this,o[n+l],r,l),c===ot&&(c=this._$AH[l]),i||(i=!tr(c)||c!==this._$AH[l]),c===F?e=F:e!==F&&(e+=(c??"")+a[l+1]),this._$AH[l]=c}i&&!s&&this.j(e)}j(e){e===F?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class To extends fn{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===F?void 0:e}}class $o extends fn{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==F)}}class Io extends fn{constructor(e,r,n,s,a){super(e,r,n,s,a),this.type=5}_$AI(e,r=this){if((e=Tt(this,e,r,0)??F)===ot)return;const n=this._$AH,s=e===F&&n!==F||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,a=e!==F&&(n===F||s);s&&this.element.removeEventListener(this.name,this,n),a&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){var r;typeof this._$AH=="function"?this._$AH.call(((r=this.options)==null?void 0:r.host)??this.element,e):this._$AH.handleEvent(e)}}let Co=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){Tt(this,e)}};const kn=Wt.litHtmlPolyfillSupport;kn==null||kn(rr,$r),(Wt.litHtmlVersions??(Wt.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 $r(e.insertBefore(er(),a),a,void 0,r??{})}return s._$AI(t),s};/**
|
16
|
+
* @license
|
17
|
+
* Copyright 2017 Google LLC
|
18
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
19
|
+
*/let re=class extends vt{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 ot}};var va;re._$litElement$=!0,re.finalized=!0,(va=globalThis.litElementHydrateSupport)==null||va.call(globalThis,{LitElement:re});const En=globalThis.litElementPolyfillSupport;En==null||En({LitElement:re});(globalThis.litElementVersions??(globalThis.litElementVersions=[])).push("4.1.1");/**
|
20
|
+
* @license
|
21
|
+
* Copyright 2017 Google LLC
|
22
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
23
|
+
*/const xe=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 Po={attribute:!0,type:String,converter:Ur,reflect:!1,hasChanged:is},Ro=(t=Po,e,r)=>{const{kind:n,metadata:s}=r;let a=globalThis.litPropertyMetadata.get(s);if(a===void 0&&globalThis.litPropertyMetadata.set(s,a=new Map),a.set(r.name,t),n==="accessor"){const{name:i}=r;return{set(o){const l=e.get.call(this);e.set.call(this,o),this.requestUpdate(i,l,t)},init(o){return o!==void 0&&this.P(i,void 0,t),o}}}if(n==="setter"){const{name:i}=r;return function(o){const l=this[i];e.call(this,o),this.requestUpdate(i,l,t)}}throw Error("Unsupported decorator location: "+n)};function ee(t){return(e,r)=>typeof r=="object"?Ro(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 jo(t){return ee({...t,state:!0,attribute:!1})}let Ze={appletUrl:"",settings:{},settingsDialogOpen:!1};localStorage.getItem("data")&&(Ze=JSON.parse(localStorage.getItem("data")));const ls=new Set;function No(t){Ze={...Ze,...t},localStorage.setItem("data",JSON.stringify({appletUrl:Ze.appletUrl,settings:Ze.settings})),ls.forEach(e=>e(Ze))}function Mo(){return Ze}function Do(t){return t(Ze),ls.add(t),()=>Sa(t)}function Sa(t){ls.delete(t)}const ae={get:Mo,update:No,subscribe:Do,unsubscribe:Sa};var Zo=Object.getOwnPropertyDescriptor,Uo=(t,e,r,n)=>{for(var s=n>1?void 0:n?Zo(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=i(s)||s);return s};let Ms=class extends re{createRenderRoot(){return this}connectedCallback(){super.connectedCallback()}handleKeyDown(e){if(e.key==="Enter"){const r=e.target;r.value&&!r.value.startsWith("http://")&&!r.value.startsWith("https://")&&(r.value=`http://${r.value}`),ae.update({appletUrl:r.value})}}render(){return U`<input
|
32
|
+
value=${ae.get().appletUrl}
|
33
|
+
type="text"
|
34
|
+
placeholder="Enter an applet URL to inspect..."
|
35
|
+
@keydown=${this.handleKeyDown.bind(this)}
|
36
|
+
/>`}};Ms=Uo([xe("url-input")],Ms);var Lo=Object.getOwnPropertyDescriptor,Fo=(t,e,r,n)=>{for(var s=n>1?void 0:n?Lo(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=i(s)||s);return s};let Ds=class extends re{createRenderRoot(){return this}openDialog(){ae.update({settingsDialogOpen:!0})}render(){return U`
|
37
|
+
<button
|
38
|
+
aria-label="open settings"
|
39
|
+
class="menu-button"
|
40
|
+
@click="${this.openDialog}"
|
41
|
+
>
|
42
|
+
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
43
|
+
<path d="M10.0001 16.6667C11.7682 16.6667 13.4639 15.9643 14.7141 14.7141C15.9644 13.4638 16.6667 11.7681 16.6667 10C16.6667 8.23191 15.9644 6.53622 14.7141 5.28598C13.4639 4.03573 11.7682 3.33335 10.0001 3.33335M10.0001 16.6667C8.23197 16.6667 6.53628 15.9643 5.28604 14.7141C4.03579 13.4638 3.33341 11.7681 3.33341 10M10.0001 16.6667V18.3334M10.0001 3.33335C8.23197 3.33335 6.53628 4.03573 5.28604 5.28598C4.03579 6.53622 3.33341 8.23191 3.33341 10M10.0001 3.33335V1.66669M3.33341 10H1.66675M11.6667 10C11.6667 10.442 11.4912 10.866 11.1786 11.1785C10.866 11.4911 10.4421 11.6667 10.0001 11.6667C9.55805 11.6667 9.13413 11.4911 8.82157 11.1785C8.50901 10.866 8.33341 10.442 8.33341 10C8.33341 9.55799 8.50901 9.13407 8.82157 8.82151C9.13413 8.50895 9.55805 8.33335 10.0001 8.33335C10.4421 8.33335 10.866 8.50895 11.1786 8.82151C11.4912 9.13407 11.6667 9.55799 11.6667 10ZM11.6667 10H18.3334M14.1667 17.2166L13.3334 15.775M9.16675 8.55843L5.83341 2.78343M17.2169 14.1667L15.7752 13.3334M2.78328 5.83335L4.22495 6.66669M17.2169 5.83335L15.7752 6.66669M2.78328 14.1667L4.22495 13.3334M14.1667 2.78343L13.3334 4.22509M9.16675 11.4417L5.83341 17.2167" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
|
44
|
+
</svg>
|
45
|
+
</button>
|
46
|
+
`}};Ds=Fo([xe("settings-button")],Ds);/**
|
47
|
+
* @license
|
48
|
+
* Copyright 2017 Google LLC
|
49
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
50
|
+
*/const ka={CHILD:2},Ea=t=>(...e)=>({_$litDirective$:t,values:e});class Ta{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 Vn=class extends Ta{constructor(e){if(super(e),this.it=F,e.type!==ka.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===F||e==null)return this._t=void 0,this.it=e;if(e===ot)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:[]}}};Vn.directiveName="unsafeHTML",Vn.resultType=1;const Vo=Ea(Vn);var zo=Object.defineProperty,Bo=Object.getOwnPropertyDescriptor,mn=(t,e,r,n)=>{for(var s=n>1?void 0:n?Bo(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&&zo(e,r,s),s};const qo=`<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 nr=class extends re{constructor(){super(...arguments),this.variableName="",this.defaultValue="1fr",this.icon=qo}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 U`
|
58
|
+
<button class="menu-button" @click=${this.toggle}>
|
59
|
+
${Vo(this.icon)}
|
60
|
+
</button>
|
61
|
+
`}};mn([ee({type:String})],nr.prototype,"variableName",2);mn([ee({type:String})],nr.prototype,"defaultValue",2);mn([ee({type:String})],nr.prototype,"icon",2);nr=mn([xe("toggle-css-variable-button")],nr);var Ho=Object.getOwnPropertyDescriptor,Jo=(t,e,r,n)=>{for(var s=n>1?void 0:n?Ho(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=i(s)||s);return s};let Zs=class extends re{createRenderRoot(){return this}render(){return U`
|
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
|
+
`}};Zs=Jo([xe("app-header")],Zs);const Us=10*1e3,Ls=10*1e3;class Fs extends Error{constructor(e){super(e),this.name="AppletExecutionError"}}class Wo extends Error{constructor(e){super(e),this.name="AppletConnectionError"}}function cs(t){typeof this[`on${t.type}`]=="function"&&this[`on${t.type}`](t),this.dispatchEvent(t)}class nt extends Event{constructor(e,r){super(e,{bubbles:r==null?void 0:r.bubbles,composed:r==null?void 0:r.composed,cancelable:r==null?void 0:r.cancelable}),this.data=r==null?void 0:r.data,this.actions=r==null?void 0:r.actions}}function Go(t,...e){console.log(`[${t}]`,...e)}const he={log:Go};var pe=function(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r},Z=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Re,bt,Gt,Fr,At,tt,ke,Yt,Vr,zr,zn,Vs,Tn,$n;class Yo extends EventTarget{constructor(e){super(),Re.add(this),bt.set(this,void 0),Gt.set(this,{}),Fr.set(this,void 0),At.set(this,void 0),tt.set(this,void 0),ke.set(this,void 0),Yt.set(this,void 0),Vr.set(this,void 0),zr.set(this,void 0),he.log("Applet","Constructor called"),pe(this,bt,e,"f"),pe(this,tt,cs.bind(this),"f"),Z(this,Re,"m",zn).call(this);const r=n=>{n.source===Z(this,bt,"f")&&"type"in n.data&&n.data.type==="appletconnect"&&(he.log("Applet","Recieved message",n.data),Z(this,Re,"m",zn).call(this),this.removeEventListener("message",r))};window.addEventListener("message",r)}async sendAction(e,r){const n={id:crypto.randomUUID(),type:"action",actionId:e,arguments:r};return new Promise((s,a)=>{Z(this,Yt,"f").call(this,n);const i=setTimeout(()=>{a(new Fs(`Applet action handler failed to complete before timeout (${Us}ms)`))},Us),o=l=>{const c=l.data;if(["actioncomplete","actionerror"].includes(c.type)&&"id"in c&&c.id===n.id)if(Z(this,ke,"f").removeEventListener("message",o),clearTimeout(i),c.type==="actionerror"){const d=c;a(new Fs(d.message))}else s()};Z(this,ke,"f").addEventListener("message",o)})}get data(){return Z(this,At,"f")}set data(e){pe(this,At,e,"f");const r={type:"data",data:e};Z(this,Yt,"f").call(this,r)}get window(){return Z(this,bt,"f")}get manifest(){return Z(this,Fr,"f")}get actions(){return Z(this,Gt,"f")}get width(){return Z(this,Vr,"f")}get height(){return Z(this,zr,"f")}}bt=new WeakMap,Gt=new WeakMap,Fr=new WeakMap,At=new WeakMap,tt=new WeakMap,ke=new WeakMap,Yt=new WeakMap,Vr=new WeakMap,zr=new WeakMap,Re=new WeakSet,zn=function(){Z(this,ke,"f")&&Z(this,ke,"f").close();const e=new MessageChannel,r={type:"appletconnect"};he.log("Applet","Send message",r),pe(this,ke,e.port1,"f"),Z(this,ke,"f").onmessage=Z(this,Re,"m",Vs).bind(this),Z(this,bt,"f").postMessage(r,"*",[e.port2]),pe(this,Yt,Z(this,ke,"f").postMessage.bind(Z(this,ke,"f")),"f")},Vs=function(e){const r=e.data;switch(he.log("Applet","Recieved message",r),r.type){case"register":const n=r;pe(this,Fr,n.manifest,"f");const s=new nt("connect");Z(this,tt,"f").call(this,s),pe(this,Gt,n.actions,"f"),Z(this,Re,"m",$n).call(this,n.actions),pe(this,At,n.data,"f"),Z(this,Re,"m",Tn).call(this,n.data);break;case"data":const a=r;pe(this,At,a.data,"f"),Z(this,Re,"m",Tn).call(this,a.data);break;case"resize":const i=r;pe(this,Vr,i.width,"f"),pe(this,zr,i.height,"f");const o=new nt("resize");Z(this,tt,"f").call(this,o);break;case"actions":const l=r;pe(this,Gt,l.actions,"f"),Z(this,Re,"m",$n).call(this,l.actions);break}},Tn=function(e){const r=new nt("data",{data:e});Z(this,tt,"f").call(this,r)},$n=function(e){const r=new nt("actions",{actions:e});Z(this,tt,"f").call(this,r)};var Te=function(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r},j=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Ue,Le,St,Ve,Kt,wt,ye,Br,qr,$a,Ia,zs,Bs,qs,Hs;class Ko extends EventTarget{constructor(e){super(),Ue.add(this),Le.set(this,{}),St.set(this,void 0),Ve.set(this,void 0),Kt.set(this,void 0),wt.set(this,void 0),ye.set(this,void 0),Br.set(this,void 0),qr.set(this,void 0),he.log("AppletScope","Constructor called"),Te(this,wt,cs.bind(this),"f"),e&&Te(this,St,e,"f");const r=s=>{if(s.source===window.parent&&s.data.type==="appletconnect"&&s.ports&&s.ports.length>0){he.log("AppletScope","Recieved message",s.data);const a=s.ports[0];Te(this,ye,a.postMessage.bind(a),"f"),a.onmessage=j(this,Ue,"m",Ia).bind(this),this.removeEventListener("message",r),j(this,Ue,"m",$a).call(this)}};window.addEventListener("message",r);const n={type:"appletconnect"};window.parent.postMessage(n,"*"),he.log("AppletScope","Send message",n)}setActionHandler(e,r){j(this,Le,"f")[e]=r}defineAction(e,r){const{handler:n,...s}=r;n&&(j(this,Le,"f")[e]=n),this.actions={...this.actions,[e]:s}}set actions(e){if(!e)return;Te(this,Ve,e,"f");const r={type:"actions",actions:j(this,Ve,"f")};he.log("AppletScope","Send message",r),j(this,ye,"f")&&j(this,ye,"f").call(this,r);const n=new nt("actions",{actions:e});setTimeout(()=>j(this,wt,"f").call(this,n),1)}get actions(){return j(this,Ve,"f")}get manifest(){return j(this,St,"f")}get actionHandlers(){return j(this,Le,"f")}set actionHandlers(e){Te(this,Le,e,"f")}set data(e){Te(this,Kt,e,"f");const r={type:"data",data:e};he.log("AppletScope","Send message",r),j(this,ye,"f")&&j(this,ye,"f").call(this,r);const n=new nt("data",{data:e});setTimeout(()=>j(this,wt,"f").call(this,n),1)}get data(){return j(this,Kt,"f")}get width(){return j(this,Br,"f")}get height(){return j(this,qr,"f")}}Le=new WeakMap,St=new WeakMap,Ve=new WeakMap,Kt=new WeakMap,wt=new WeakMap,ye=new WeakMap,Br=new WeakMap,qr=new WeakMap,Ue=new WeakSet,$a=async function(){const e=this.manifest??await j(this,Ue,"m",Hs).call(this);Te(this,St,e||{},"f"),Te(this,Ve,j(this,Ve,"f")||(e==null?void 0:e.actions)||{},"f");const r={type:"register",manifest:j(this,St,"f"),actions:j(this,Ve,"f"),data:j(this,Kt,"f")};j(this,ye,"f").call(this,r),he.log("AppletScope","Send message",r);const n=new nt("connect");j(this,wt,"f").call(this,n),j(this,Ue,"m",Bs).call(this)},Ia=function(e){const r=e.data;switch(he.log("AppletScope","Recieved message",r),r.type){case"data":"data"in r&&(this.data=r.data);break;case"action":"type"in r&&r.type==="action"&&"id"in r&&typeof r.id=="string"&&"actionId"in r&&typeof r.actionId=="string"&&"arguments"in r&&j(this,Ue,"m",zs).call(this,r);break}},zs=async function(e){if(Object.keys(j(this,Le,"f")).includes(e.actionId))try{await j(this,Le,"f")[e.actionId](e.arguments);const r={type:"actioncomplete",id:e.id};j(this,ye,"f").call(this,r)}catch(r){const n={type:"actionerror",id:e.id,message:r.message};j(this,ye,"f").call(this,n),console.error(r)}},Bs=function(){new ResizeObserver(r=>{for(let n of r)j(this,Ue,"m",qs).call(this,{width:n.contentRect.width,height:n.contentRect.height})}).observe(document.querySelector("html"))},qs=function({width:e,height:r}){Te(this,Br,e,"f"),Te(this,qr,r,"f");const n={type:"resize",width:e,height:r};he.log("AppletScope","Send message",n),j(this,ye,"f").call(this,n)},Hs=async function(){const e=document.querySelector('link[rel="manifest"]');if(e)try{const n=await(await fetch(e.href)).json();for(const s in n.actions){const a=n.actions[s];a.params_schema&&!Object.keys(a.params_schema).length&&(a.params_schema=void 0)}return n}catch{return}};class Xo{async connect(e){return new Promise((r,n)=>{const s=new Yo(e),a=setTimeout(()=>{n(new Wo(`Applet failed to connect before the timeout was reached (${Ls}ms)`))},Ls),i=()=>{r(s),s.removeEventListener("connect",i),clearTimeout(a)};s.addEventListener("connect",i)})}register(e){return new Ko(e)}}const Qo=new Xo;var Mr=function(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r},W=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Hr,zt,Dr,Ee,Bt,kt,Ca,Js;class Oa extends HTMLElement{constructor(){super(...arguments),Hr.add(this),zt.set(this,void 0),Dr.set(this,void 0),Ee.set(this,void 0),Bt.set(this,cs.bind(this)),kt.set(this,document.createElement("iframe"))}connectedCallback(){Mr(this,zt,this.attachShadow({mode:"closed"}),"f"),W(this,zt,"f").appendChild(W(this,kt,"f"));const e=document.createElement("style");e.textContent=this.styles,W(this,zt,"f").appendChild(e),this.src=this.getAttribute("src")}get contentWindow(){return W(this,kt,"f").contentWindow}set src(e){Mr(this,Dr,e,"f"),Mr(this,Ee,void 0,"f"),W(this,Hr,"m",Ca).call(this,e)}get src(){return W(this,Dr,"f")||""}attributeChangedCallback(e,r,n){e==="src"&&(this.src=n)}get applet(){return W(this,Ee,"f")}set data(e){if(this.applet)this.applet.data=e;else{const r=()=>{this.applet&&(this.applet.data=e),this.removeEventListener("load",r)};this.addEventListener("load",r)}}get styles(){return`
|
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
|
+
`}}zt=new WeakMap,Dr=new WeakMap,Ee=new WeakMap,Bt=new WeakMap,kt=new WeakMap,Hr=new WeakSet,Ca=async function(e){W(this,kt,"f").src=e;const r=W(this,kt,"f").contentWindow;r&&(Mr(this,Ee,await Qo.connect(r),"f"),W(this,Ee,"f").ondata=n=>{W(this,Bt,"f").call(this,n)},W(this,Ee,"f").onresize=n=>{W(this,Hr,"m",Js).call(this,{width:W(this,Ee,"f").width,height:W(this,Ee,"f").height})},W(this,Ee,"f").onactions=n=>{W(this,Bt,"f").call(this,n)},W(this,Bt,"f").call(this,new Event("load")),this.load&&typeof this.load=="function"&&this.onload(new Event("load")))},Js=function(e){this.style.height=`${e.height}px`};Oa.observedAttributes=["src"];customElements.define("applet-frame",Oa);var el=Object.defineProperty,tl=Object.getOwnPropertyDescriptor,gn=(t,e,r,n)=>{for(var s=n>1?void 0:n?tl(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&&el(e,r,s),s};let sr=class extends re{constructor(){super(...arguments),this.renderRoot=this,this.appletUrl="",this.mode="gui",this.data={}}connectedCallback(){ae.subscribe(t=>{this.appletUrl=t.appletUrl,t.applet&&(this.data=t.applet.data,t.applet.ondata=()=>this.data=t.applet.data)}),super.connectedCallback()}updated(){const t=document.querySelector("applet-frame");t&&(t.onload=()=>{ae.update({applet:t.applet}),window.applet=t.applet,window.applet.ondata=e=>this.data=e.data})}render(){var e,r,n,s,a;const t=U`<div class="applet-header">
|
94
|
+
${(r=(e=window.applet)==null?void 0:e.manifest)!=null&&r.icons?U`<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 U`
|
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
|
+
`}};gn([ee()],sr.prototype,"appletUrl",2);gn([ee()],sr.prototype,"mode",2);gn([ee({attribute:!1})],sr.prototype,"data",2);sr=gn([xe("app-viewer")],sr);class rl{constructor(){this.interactions=[],this.subscribers=new Set}addInteraction(e){this.interactions.push(e),this.notify()}getAllInteractions(){return[...this.interactions]}getRecentInteractions(e=10){return this.interactions.slice(-e)}clearHistory(){this.interactions=[],this.notify()}subscribe(e){return this.subscribers.add(e),e([...this.interactions]),()=>{this.subscribers.delete(e)}}notify(){for(const e of this.subscribers)e([...this.interactions])}}const Jr=new rl;var nl=Object.defineProperty,sl=Object.getOwnPropertyDescriptor,pt=(t,e,r,n)=>{for(var s=n>1?void 0:n?sl(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=(n?i(e,r,s):i(s))||s);return n&&s&&nl(e,r,s),s};let ar=class extends re{constructor(){super(...arguments),this.renderRoot=this,this.selected=0,this.actions={},this.schemaError=""}connectedCallback(){ae.subscribe(t=>{t.applet&&(this.actions=t.applet.actions,t.applet.onactions=e=>this.actions=e.actions)}),super.connectedCallback()}handleSelect(t){const e=t.target;this.selected=e.selectedIndex}handleSchemaChange(t){const e=t.target,r=e.value.trim();if(!r){this.schemaError="",e.setCustomValidity("");return}try{const n=JSON.parse(r),s=JSON.stringify(n,null,2);e.value=s,this.schemaError="",e.setCustomValidity("")}catch(n){this.schemaError=n.message,e.setCustomValidity("Invalid JSON")}}handleSchemaFocus(t){t.target.setCustomValidity("")}async handleSubmit(t){t.preventDefault();const e=t.target,r=new FormData(e),n=r.get("action-id"),s=r.get("params");await window.applet.sendAction(n,JSON.parse(s)),Jr.addInteraction({input:{type:"action",text:n},outputs:[{type:n,...JSON.parse(s)},{type:"data",content:window.applet.data}],timestamp:Date.now()})}render(){if(!this.actions||Object.keys(this.actions).length===0)return U`<p class="status-message">No actions available.</p>`;const t=Object.values(this.actions)[this.selected],e=JSON.stringify(t==null?void 0:t.params_schema,null,2)??"None";return U`
|
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?U`<div class="error-message">${this.schemaError}</div>`:""}
|
153
|
+
</fieldset>
|
154
|
+
<fieldset>
|
155
|
+
<input type="submit" value="Dispatch action" />
|
156
|
+
</fieldset>
|
157
|
+
</form>
|
158
|
+
`}};pt([ee({type:Number})],ar.prototype,"selected",2);pt([ee({attribute:!1})],ar.prototype,"actions",2);pt([ee({type:String})],ar.prototype,"schemaError",2);ar=pt([xe("app-sidebar")],ar);let Wr=class extends re{constructor(){super(...arguments),this.renderRoot=this}render(){return U`
|
159
|
+
<select name=${this.name}>
|
160
|
+
${Object.keys(this.actions).map(t=>U`<option id="action">${t}</option>`)}
|
161
|
+
</select>
|
162
|
+
`}};pt([ee({type:String})],Wr.prototype,"name",2);pt([ee({attribute:!1})],Wr.prototype,"actions",2);Wr=pt([xe("action-select")],Wr);var Pa="vercel.ai.error",al=Symbol.for(Pa),Ra,il=class ja extends Error{constructor({name:e,message:r,cause:n}){super(r),this[Ra]=!0,this.name=e,this.cause=n}static isInstance(e){return ja.hasMarker(e,Pa)}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}};Ra=al;var O=il,Na="AI_APICallError",Ma=`vercel.ai.error.${Na}`,ol=Symbol.for(Ma),Da,$e=class extends O{constructor({message:t,url:e,requestBodyValues:r,statusCode:n,responseHeaders:s,responseBody:a,cause:i,isRetryable:o=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:Na,message:t,cause:i}),this[Da]=!0,this.url=e,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=s,this.responseBody=a,this.isRetryable=o,this.data=l}static isInstance(t){return O.hasMarker(t,Ma)}};Da=ol;var Za="AI_EmptyResponseBodyError",Ua=`vercel.ai.error.${Za}`,ll=Symbol.for(Ua),La,cl=class extends O{constructor({message:t="Empty response body"}={}){super({name:Za,message:t}),this[La]=!0}static isInstance(t){return O.hasMarker(t,Ua)}};La=ll;function Fa(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var Va="AI_InvalidArgumentError",za=`vercel.ai.error.${Va}`,ul=Symbol.for(za),Ba,dl=class extends O{constructor({message:e,cause:r,argument:n}){super({name:Va,message:e,cause:r}),this[Ba]=!0,this.argument=n}static isInstance(e){return O.hasMarker(e,za)}};Ba=ul;var qa="AI_InvalidPromptError",Ha=`vercel.ai.error.${qa}`,pl=Symbol.for(Ha),Ja,et=class extends O{constructor({prompt:t,message:e,cause:r}){super({name:qa,message:`Invalid prompt: ${e}`,cause:r}),this[Ja]=!0,this.prompt=t}static isInstance(t){return O.hasMarker(t,Ha)}};Ja=pl;var Wa="AI_InvalidResponseDataError",Ga=`vercel.ai.error.${Wa}`,hl=Symbol.for(Ga),Ya,In=class extends O{constructor({data:t,message:e=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:Wa,message:e}),this[Ya]=!0,this.data=t}static isInstance(t){return O.hasMarker(t,Ga)}};Ya=hl;var Ka="AI_JSONParseError",Xa=`vercel.ai.error.${Ka}`,fl=Symbol.for(Xa),Qa,ir=class extends O{constructor({text:t,cause:e}){super({name:Ka,message:`JSON parsing failed: Text: ${t}.
|
163
|
+
Error message: ${Fa(e)}`,cause:e}),this[Qa]=!0,this.text=t}static isInstance(t){return O.hasMarker(t,Xa)}};Qa=fl;var ei="AI_LoadAPIKeyError",ti=`vercel.ai.error.${ei}`,ml=Symbol.for(ti),ri,Pr=class extends O{constructor({message:t}){super({name:ei,message:t}),this[ri]=!0}static isInstance(t){return O.hasMarker(t,ti)}};ri=ml;var ni="AI_TooManyEmbeddingValuesForCallError",si=`vercel.ai.error.${ni}`,gl=Symbol.for(si),ai,yl=class extends O{constructor(t){super({name:ni,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[ai]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return O.hasMarker(t,si)}};ai=gl;var ii="AI_TypeValidationError",oi=`vercel.ai.error.${ii}`,vl=Symbol.for(oi),li,_l=class Bn extends O{constructor({value:e,cause:r}){super({name:ii,message:`Type validation failed: Value: ${JSON.stringify(e)}.
|
164
|
+
Error message: ${Fa(r)}`,cause:r}),this[li]=!0,this.value=e}static isInstance(e){return O.hasMarker(e,oi)}static wrap({value:e,cause:r}){return Bn.isInstance(r)&&r.value===e?r:new Bn({value:e,cause:r})}};li=vl;var Ne=_l,ci="AI_UnsupportedFunctionalityError",ui=`vercel.ai.error.${ci}`,bl=Symbol.for(ui),di,G=class extends O{constructor({functionality:t,message:e=`'${t}' functionality not supported.`}){super({name:ci,message:e}),this[di]=!0,this.functionality=t}static isInstance(t){return O.hasMarker(t,ui)}};di=bl;function Gr(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"?!0:Array.isArray(t)?t.every(Gr):typeof t=="object"?Object.entries(t).every(([e,r])=>typeof e=="string"&&Gr(r)):!1}function Ws(t){return Array.isArray(t)&&t.every(Gr)}function qn(t){return t!=null&&typeof t=="object"&&Object.entries(t).every(([e,r])=>typeof e=="string"&&Gr(r))}let wl=(t,e=21)=>(r=e)=>{let n="",s=r|0;for(;s--;)n+=t[Math.random()*t.length|0];return n};function xl(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Qe={exports:{}},Gs;function Al(){if(Gs)return Qe.exports;Gs=1;const t=typeof Buffer<"u",e=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,r=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function n(o,l,c){c==null&&l!==null&&typeof l=="object"&&(c=l,l=void 0),t&&Buffer.isBuffer(o)&&(o=o.toString()),o&&o.charCodeAt(0)===65279&&(o=o.slice(1));const d=JSON.parse(o,l);if(d===null||typeof d!="object")return d;const p=c&&c.protoAction||"error",g=c&&c.constructorAction||"error";if(p==="ignore"&&g==="ignore")return d;if(p!=="ignore"&&g!=="ignore"){if(e.test(o)===!1&&r.test(o)===!1)return d}else if(p!=="ignore"&&g==="ignore"){if(e.test(o)===!1)return d}else if(r.test(o)===!1)return d;return s(d,{protoAction:p,constructorAction:g,safe:c&&c.safe})}function s(o,{protoAction:l="error",constructorAction:c="error",safe:d}={}){let p=[o];for(;p.length;){const g=p;p=[];for(const w of g){if(l!=="ignore"&&Object.prototype.hasOwnProperty.call(w,"__proto__")){if(d===!0)return null;if(l==="error")throw new SyntaxError("Object contains forbidden prototype property");delete w.__proto__}if(c!=="ignore"&&Object.prototype.hasOwnProperty.call(w,"constructor")&&Object.prototype.hasOwnProperty.call(w.constructor,"prototype")){if(d===!0)return null;if(c==="error")throw new SyntaxError("Object contains forbidden prototype property");delete w.constructor}for(const y in w){const m=w[y];m&&typeof m=="object"&&p.push(m)}}}return o}function a(o,l,c){const d=Error.stackTraceLimit;Error.stackTraceLimit=0;try{return n(o,l,c)}finally{Error.stackTraceLimit=d}}function i(o,l){const c=Error.stackTraceLimit;Error.stackTraceLimit=0;try{return n(o,l,{safe:!0})}catch{return null}finally{Error.stackTraceLimit=c}}return Qe.exports=a,Qe.exports.default=a,Qe.exports.parse=a,Qe.exports.safeParse=i,Qe.exports.scan=s,Qe.exports}var Sl=Al();const us=xl(Sl);var kl=Object.defineProperty,El=(t,e,r)=>e in t?kl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rr=(t,e,r)=>El(t,typeof e!="symbol"?e+"":e,r);class Ys extends Error{constructor(e,r){super(e),Rr(this,"type"),Rr(this,"field"),Rr(this,"value"),Rr(this,"line"),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function Cn(t){}function Tl(t){const{onEvent:e=Cn,onError:r=Cn,onRetry:n=Cn,onComment:s}=t;let a="",i=!0,o,l="",c="";function d(m){const v=i?m.replace(/^\xEF\xBB\xBF/,""):m,[A,k]=$l(`${a}${v}`);for(const T of A)p(T);a=k,i=!1}function p(m){if(m===""){w();return}if(m.startsWith(":")){s&&s(m.slice(m.startsWith(": ")?2:1));return}const v=m.indexOf(":");if(v!==-1){const A=m.slice(0,v),k=m[v+1]===" "?2:1,T=m.slice(v+k);g(A,T,m);return}g(m,"",m)}function g(m,v,A){switch(m){case"event":c=v;break;case"data":l=`${l}${v}
|
165
|
+
`;break;case"id":o=v.includes("\0")?void 0:v;break;case"retry":/^\d+$/.test(v)?n(parseInt(v,10)):r(new Ys(`Invalid \`retry\` value: "${v}"`,{type:"invalid-retry",value:v,line:A}));break;default:r(new Ys(`Unknown field "${m.length>20?`${m.slice(0,20)}…`:m}"`,{type:"unknown-field",field:m,value:v,line:A}));break}}function w(){l.length>0&&e({id:o,event:c||void 0,data:l.endsWith(`
|
166
|
+
`)?l.slice(0,-1):l}),o=void 0,l="",c=""}function y(m={}){a&&m.consume&&p(a),o=void 0,l="",c="",a=""}return{feed:d,reset:y}}function $l(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 Il extends TransformStream{constructor({onError:e,onRetry:r,onComment:n}={}){let s;super({start(a){s=Tl({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 Cl={};function $t(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}function Ol(t){return new ReadableStream({async pull(e){try{const{value:r,done:n}=await t.next();n?e.close():e.enqueue(r)}catch(r){e.error(r)}},cancel(){}})}async function Pl(t){return t==null?Promise.resolve():new Promise(e=>setTimeout(e,t))}function yn(t){const e={};return t.headers.forEach((r,n)=>{e[n]=r}),e}var ht=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const s=wl(r,e);if(t==null)return s;if(r.includes(n))throw new dl({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return a=>`${t}${n}${s(a)}`},Ft=ht();function Rl(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}function jl(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>r!=null))}function Zr(t){return t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")}function Nl({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:n}){if(typeof t=="string")return t;if(t!=null)throw new Pr({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Pr({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=Cl[e],t==null)throw new Pr({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new Pr({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}var Yr=Symbol.for("vercel.ai.validator");function Ml(t){return{[Yr]:!0,validate:t}}function Dl(t){return typeof t=="object"&&t!==null&&Yr in t&&t[Yr]===!0&&"validate"in t}function Zl(t){return Dl(t)?t:Ul(t)}function Ul(t){return Ml(e=>{const r=t.safeParse(e);return r.success?{success:!0,value:r.data}:{success:!1,error:r.error}})}function Ll({value:t,schema:e}){const r=lt({value:t,schema:e});if(!r.success)throw Ne.wrap({value:t,cause:r.error});return r.value}function lt({value:t,schema:e}){const r=Zl(e);try{if(r.validate==null)return{success:!0,value:t};const n=r.validate(t);return n.success?n:{success:!1,error:Ne.wrap({value:t,cause:n.error})}}catch(n){return{success:!1,error:Ne.wrap({value:t,cause:n})}}}function Fl({text:t,schema:e}){try{const r=us.parse(t);return e==null?r:Ll({value:r,schema:e})}catch(r){throw ir.isInstance(r)||Ne.isInstance(r)?r:new ir({text:t,cause:r})}}function It({text:t,schema:e}){try{const r=us.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:ir.isInstance(r)?r:new ir({text:t,cause:r})}}}function Ks(t){try{return us.parse(t),!0}catch{return!1}}var Vl=()=>globalThis.fetch,Ct=async({url:t,headers:e,body:r,failedResponseHandler:n,successfulResponseHandler:s,abortSignal:a,fetch:i})=>zl({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:s,abortSignal:a,fetch:i}),zl=async({url:t,headers:e={},body:r,successfulResponseHandler:n,failedResponseHandler:s,abortSignal:a,fetch:i=Vl()})=>{try{const o=await i(t,{method:"POST",headers:jl(e),body:r.content,signal:a}),l=yn(o);if(!o.ok){let c;try{c=await s({response:o,url:t,requestBodyValues:r.values})}catch(d){throw Zr(d)||$e.isInstance(d)?d:new $e({message:"Failed to process error response",cause:d,statusCode:o.status,url:t,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:o,url:t,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Zr(c)||$e.isInstance(c))?c:new $e({message:"Failed to process successful response",cause:c,statusCode:o.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(o){if(Zr(o))throw o;if(o instanceof TypeError&&o.message==="fetch failed"){const l=o.cause;if(l!=null)throw new $e({message:`Cannot connect to API: ${l.message}`,cause:l,url:t,requestBodyValues:r.values,isRetryable:!0})}throw o}},Bl=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:n,url:s,requestBodyValues:a})=>{const i=await n.text(),o=yn(n);if(i.trim()==="")return{responseHeaders:o,value:new $e({message:n.statusText,url:s,requestBodyValues:a,statusCode:n.status,responseHeaders:o,responseBody:i,isRetryable:r==null?void 0:r(n)})};try{const l=Fl({text:i,schema:t});return{responseHeaders:o,value:new $e({message:e(l),url:s,requestBodyValues:a,statusCode:n.status,responseHeaders:o,responseBody:i,data:l,isRetryable:r==null?void 0:r(n,l)})}}catch{return{responseHeaders:o,value:new $e({message:n.statusText,url:s,requestBodyValues:a,statusCode:n.status,responseHeaders:o,responseBody:i,isRetryable:r==null?void 0:r(n)})}}},pi=t=>async({response:e})=>{const r=yn(e);if(e.body==null)throw new cl({});return{responseHeaders:r,value:e.body.pipeThrough(new TextDecoderStream).pipeThrough(new Il).pipeThrough(new TransformStream({transform({data:n},s){n!=="[DONE]"&&s.enqueue(It({text:n,schema:t}))}}))}},vn=t=>async({response:e,url:r,requestBodyValues:n})=>{const s=await e.text(),a=It({text:s,schema:t}),i=yn(e);if(!a.success)throw new $e({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:ql,atob:Hl}=globalThis;function Jl(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=Hl(e);return Uint8Array.from(r,n=>n.codePointAt(0))}function Hn(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return ql(e)}function Wl(t){return t==null?void 0:t.replace(/\/$/,"")}var C;(function(t){t.assertEqual=s=>s;function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{const a={};for(const i of s)a[i]=i;return a},t.getValidEnumValues=s=>{const a=t.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(const o of a)i[o]=s[o];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(a){return s[a]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const a=[];for(const i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},t.find=(s,a)=>{for(const i of s)if(a(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function n(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}t.joinValues=n,t.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(C||(C={}));var Jn;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Jn||(Jn={}));const b=C.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),je=t=>{switch(typeof t){case"undefined":return b.undefined;case"string":return b.string;case"number":return isNaN(t)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":return Array.isArray(t)?b.array:t===null?b.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?b.promise:typeof Map<"u"&&t instanceof Map?b.map:typeof Set<"u"&&t instanceof Set?b.set:typeof Date<"u"&&t instanceof Date?b.date:b.object;default:return b.unknown}},h=C.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Gl=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class le extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(a){return a.message},n={_errors:[]},s=a=>{for(const i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let o=n,l=0;for(;l<i.path.length;){const c=i.path[l];l===i.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(r(i))):o[c]=o[c]||{_errors:[]},o=o[c],l++}}};return s(this),n}static assert(e){if(!(e instanceof le))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,C.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},n=[];for(const s of this.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}le.create=t=>new le(t);const Ot=(t,e)=>{let r;switch(t.code){case h.invalid_type:t.received===b.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case h.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,C.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:r=`Unrecognized key(s) in object: ${C.joinValues(t.keys,", ")}`;break;case h.invalid_union:r="Invalid input";break;case h.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${C.joinValues(t.options)}`;break;case h.invalid_enum_value:r=`Invalid enum value. Expected ${C.joinValues(t.options)}, received '${t.received}'`;break;case h.invalid_arguments:r="Invalid function arguments";break;case h.invalid_return_type:r="Invalid function return type";break;case h.invalid_date:r="Invalid date";break;case h.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:C.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case h.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case h.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case h.custom:r="Invalid input";break;case h.invalid_intersection_types:r="Intersection results could not be merged";break;case h.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case h.not_finite:r="Number must be finite";break;default:r=e.defaultError,C.assertNever(t)}return{message:r}};let hi=Ot;function Yl(t){hi=t}function Kr(){return hi}const Xr=t=>{const{data:e,path:r,errorMaps:n,issueData:s}=t,a=[...r,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)o=c(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}},Kl=[];function _(t,e){const r=Kr(),n=Xr({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ot?void 0:Ot].filter(s=>!!s)});t.common.issues.push(n)}class Q{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const s of r){if(s.status==="aborted")return S;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const s of r){const a=await s.key,i=await s.value;n.push({key:a,value:i})}return Q.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const s of r){const{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return S;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[a.value]=i.value)}return{status:e.value,value:n}}}const S=Object.freeze({status:"aborted"}),xt=t=>({status:"dirty",value:t}),ne=t=>({status:"valid",value:t}),Wn=t=>t.status==="aborted",Gn=t=>t.status==="dirty",ct=t=>t.status==="valid",or=t=>typeof Promise<"u"&&t instanceof Promise;function Qr(t,e,r,n){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(t)}function fi(t,e,r,n,s){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,r),r}var x;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(x||(x={}));var qt,Ht;class Ie{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(ct(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new le(t.common.issues);return this._error=r,this._error}}};function E(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,o)=>{var l,c;const{message:d}=t;return i.code==="invalid_enum_value"?{message:d??o.defaultError}:typeof o.data>"u"?{message:(l=d??n)!==null&&l!==void 0?l:o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:(c=d??r)!==null&&c!==void 0?c:o.defaultError}},description:s}}class ${get description(){return this._def.description}_getType(e){return je(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:je(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Q,ctx:{common:e.parent.common,data:e.data,parsedType:je(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(or(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:je(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:je(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:s});return ct(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=>ct(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:je(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(or(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(l=>l?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new we({schema:this,typeName:f.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return be.create(this,this._def)}nullable(){return Je.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return _e.create(this)}promise(){return Rt.create(this,this._def)}or(e){return dr.create([this,e],this._def)}and(e){return pr.create(this,e,this._def)}transform(e){return new we({...E(this._def),schema:this,typeName:f.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new yr({...E(this._def),innerType:this,defaultValue:r,typeName:f.ZodDefault})}brand(){return new ds({typeName:f.ZodBranded,type:this,...E(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new vr({...E(this._def),innerType:this,catchValue:r,typeName:f.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Ir.create(this,e)}readonly(){return _r.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Xl=/^c[^\s-]{8,}$/i,Ql=/^[0-9a-z]+$/,ec=/^[0-9A-HJKMNP-TV-Z]{26}$/i,tc=/^[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,rc=/^[a-z0-9_-]{21}$/i,nc=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,sc=/^[-+]?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)?)??$/,ac=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ic="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let On;const oc=/^(?:(?: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])$/,lc=/^(?:(?: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])$/,cc=/^(([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]))$/,uc=/^(([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])$/,dc=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,pc=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,mi="((\\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])))",hc=new RegExp(`^${mi}$`);function gi(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 fc(t){return new RegExp(`^${gi(t)}$`)}function yi(t){let e=`${mi}T${gi(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 mc(t,e){return!!((e==="v4"||!e)&&oc.test(t)||(e==="v6"||!e)&&cc.test(t))}function gc(t,e){if(!nc.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 yc(t,e){return!!((e==="v4"||!e)&&lc.test(t)||(e==="v6"||!e)&&uc.test(t))}class ve extends ${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==b.string){const a=this._getOrReturnCtx(e);return _(a,{code:h.invalid_type,expected:b.string,received:a.parsedType}),S}const n=new Q;let s;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),_(s,{code:h.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),_(s,{code:h.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){const i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(s=this._getOrReturnCtx(e,s),i?_(s,{code:h.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&_(s,{code:h.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")ac.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"email",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")On||(On=new RegExp(ic,"u")),On.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"emoji",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")tc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"uuid",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")rc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"nanoid",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")Xl.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"cuid",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")Ql.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"cuid2",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")ec.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"ulid",code:h.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),_(s,{validation:"url",code:h.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"regex",code:h.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?yi(a).test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?hc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?fc(a).test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{code:h.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?sc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"duration",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?mc(e.data,a.version)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"ip",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?gc(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"jwt",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?yc(e.data,a.version)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"cidr",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?dc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"base64",code:h.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?pc.test(e.data)||(s=this._getOrReturnCtx(e,s),_(s,{validation:"base64url",code:h.invalid_string,message:a.message}),n.dirty()):C.assertNever(a);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:h.invalid_string,...x.errToObj(n)})}_addCheck(e){return new ve({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...x.errToObj(e)})}url(e){return this._addCheck({kind:"url",...x.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...x.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...x.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...x.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...x.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...x.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...x.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...x.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...x.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...x.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...x.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...x.errToObj(e)})}datetime(e){var r,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(r=e==null?void 0:e.offset)!==null&&r!==void 0?r:!1,local:(n=e==null?void 0:e.local)!==null&&n!==void 0?n:!1,...x.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...x.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...x.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...x.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r==null?void 0:r.position,...x.errToObj(r==null?void 0:r.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...x.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...x.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...x.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...x.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...x.errToObj(r)})}nonempty(e){return this.min(1,x.errToObj(e))}trim(){return new ve({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ve({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ve({...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}}ve.create=t=>{var e;return new ve({checks:[],typeName:f.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...E(t)})};function vc(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 Be extends ${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==b.number){const a=this._getOrReturnCtx(e);return _(a,{code:h.invalid_type,expected:b.number,received:a.parsedType}),S}let n;const s=new Q;for(const a of this._def.checks)a.kind==="int"?C.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{code:h.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),_(n,{code:h.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),_(n,{code:h.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?vc(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),_(n,{code:h.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{code:h.not_finite,message:a.message}),s.dirty()):C.assertNever(a);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,x.toString(r))}gt(e,r){return this.setLimit("min",e,!1,x.toString(r))}lte(e,r){return this.setLimit("max",e,!0,x.toString(r))}lt(e,r){return this.setLimit("max",e,!1,x.toString(r))}setLimit(e,r,n,s){return new Be({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:x.toString(s)}]})}_addCheck(e){return new Be({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:x.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:x.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:x.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:x.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:x.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:x.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:x.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:x.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:x.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&C.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}}Be.create=t=>new Be({checks:[],typeName:f.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...E(t)});class qe extends ${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==b.bigint)return this._getInvalidInput(e);let n;const s=new Q;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),_(n,{code:h.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),_(n,{code:h.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),_(n,{code:h.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):C.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return _(r,{code:h.invalid_type,expected:b.bigint,received:r.parsedType}),S}gte(e,r){return this.setLimit("min",e,!0,x.toString(r))}gt(e,r){return this.setLimit("min",e,!1,x.toString(r))}lte(e,r){return this.setLimit("max",e,!0,x.toString(r))}lt(e,r){return this.setLimit("max",e,!1,x.toString(r))}setLimit(e,r,n,s){return new qe({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:x.toString(s)}]})}_addCheck(e){return new qe({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:x.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:x.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:x.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:x.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:x.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}qe.create=t=>{var e;return new qe({checks:[],typeName:f.ZodBigInt,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...E(t)})};class lr extends ${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==b.boolean){const n=this._getOrReturnCtx(e);return _(n,{code:h.invalid_type,expected:b.boolean,received:n.parsedType}),S}return ne(e.data)}}lr.create=t=>new lr({typeName:f.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...E(t)});class ut extends ${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==b.date){const a=this._getOrReturnCtx(e);return _(a,{code:h.invalid_type,expected:b.date,received:a.parsedType}),S}if(isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return _(a,{code:h.invalid_date}),S}const n=new Q;let s;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),_(s,{code:h.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),_(s,{code:h.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):C.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ut({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:x.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:x.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}ut.create=t=>new ut({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:f.ZodDate,...E(t)});class en extends ${_parse(e){if(this._getType(e)!==b.symbol){const n=this._getOrReturnCtx(e);return _(n,{code:h.invalid_type,expected:b.symbol,received:n.parsedType}),S}return ne(e.data)}}en.create=t=>new en({typeName:f.ZodSymbol,...E(t)});class cr extends ${_parse(e){if(this._getType(e)!==b.undefined){const n=this._getOrReturnCtx(e);return _(n,{code:h.invalid_type,expected:b.undefined,received:n.parsedType}),S}return ne(e.data)}}cr.create=t=>new cr({typeName:f.ZodUndefined,...E(t)});class ur extends ${_parse(e){if(this._getType(e)!==b.null){const n=this._getOrReturnCtx(e);return _(n,{code:h.invalid_type,expected:b.null,received:n.parsedType}),S}return ne(e.data)}}ur.create=t=>new ur({typeName:f.ZodNull,...E(t)});class Pt extends ${constructor(){super(...arguments),this._any=!0}_parse(e){return ne(e.data)}}Pt.create=t=>new Pt({typeName:f.ZodAny,...E(t)});class at extends ${constructor(){super(...arguments),this._unknown=!0}_parse(e){return ne(e.data)}}at.create=t=>new at({typeName:f.ZodUnknown,...E(t)});class Me extends ${_parse(e){const r=this._getOrReturnCtx(e);return _(r,{code:h.invalid_type,expected:b.never,received:r.parsedType}),S}}Me.create=t=>new Me({typeName:f.ZodNever,...E(t)});class tn extends ${_parse(e){if(this._getType(e)!==b.undefined){const n=this._getOrReturnCtx(e);return _(n,{code:h.invalid_type,expected:b.void,received:n.parsedType}),S}return ne(e.data)}}tn.create=t=>new tn({typeName:f.ZodVoid,...E(t)});class _e extends ${_parse(e){const{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==b.array)return _(r,{code:h.invalid_type,expected:b.array,received:r.parsedType}),S;if(s.exactLength!==null){const i=r.data.length>s.exactLength.value,o=r.data.length<s.exactLength.value;(i||o)&&(_(r,{code:i?h.too_big:h.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(_(r,{code:h.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(_(r,{code:h.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,o)=>s.type._parseAsync(new Ie(r,i,r.path,o)))).then(i=>Q.mergeArray(n,i));const a=[...r.data].map((i,o)=>s.type._parseSync(new Ie(r,i,r.path,o)));return Q.mergeArray(n,a)}get element(){return this._def.type}min(e,r){return new _e({...this._def,minLength:{value:e,message:x.toString(r)}})}max(e,r){return new _e({...this._def,maxLength:{value:e,message:x.toString(r)}})}length(e,r){return new _e({...this._def,exactLength:{value:e,message:x.toString(r)}})}nonempty(e){return this.min(1,e)}}_e.create=(t,e)=>new _e({type:t,minLength:null,maxLength:null,exactLength:null,typeName:f.ZodArray,...E(e)});function _t(t){if(t instanceof z){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=be.create(_t(n))}return new z({...t._def,shape:()=>e})}else return t instanceof _e?new _e({...t._def,type:_t(t.element)}):t instanceof be?be.create(_t(t.unwrap())):t instanceof Je?Je.create(_t(t.unwrap())):t instanceof Ce?Ce.create(t.items.map(e=>_t(e))):t}class z extends ${constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=C.objectKeys(e);return this._cached={shape:e,keys:r}}_parse(e){if(this._getType(e)!==b.object){const c=this._getOrReturnCtx(e);return _(c,{code:h.invalid_type,expected:b.object,received:c.parsedType}),S}const{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof Me&&this._def.unknownKeys==="strip"))for(const c in s.data)i.includes(c)||o.push(c);const l=[];for(const c of i){const d=a[c],p=s.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new Ie(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Me){const c=this._def.unknownKeys;if(c==="passthrough")for(const d of o)l.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(c==="strict")o.length>0&&(_(s,{code:h.unrecognized_keys,keys:o}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const d of o){const p=s.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new Ie(s,p,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const c=[];for(const d of l){const p=await d.key,g=await d.value;c.push({key:p,value:g,alwaysSet:d.alwaysSet})}return c}).then(c=>Q.mergeObjectSync(n,c)):Q.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return x.errToObj,new z({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{var s,a,i,o;const l=(i=(a=(s=this._def).errorMap)===null||a===void 0?void 0:a.call(s,r,n).message)!==null&&i!==void 0?i:n.defaultError;return r.code==="unrecognized_keys"?{message:(o=x.errToObj(e).message)!==null&&o!==void 0?o:l}:{message:l}}}:{}})}strip(){return new z({...this._def,unknownKeys:"strip"})}passthrough(){return new z({...this._def,unknownKeys:"passthrough"})}extend(e){return new z({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new z({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:f.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new z({...this._def,catchall:e})}pick(e){const r={};return C.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(r[n]=this.shape[n])}),new z({...this._def,shape:()=>r})}omit(e){const r={};return C.objectKeys(this.shape).forEach(n=>{e[n]||(r[n]=this.shape[n])}),new z({...this._def,shape:()=>r})}deepPartial(){return _t(this)}partial(e){const r={};return C.objectKeys(this.shape).forEach(n=>{const s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}),new z({...this._def,shape:()=>r})}required(e){const r={};return C.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof be;)a=a._def.innerType;r[n]=a}}),new z({...this._def,shape:()=>r})}keyof(){return vi(C.objectKeys(this.shape))}}z.create=(t,e)=>new z({shape:()=>t,unknownKeys:"strip",catchall:Me.create(),typeName:f.ZodObject,...E(e)});z.strictCreate=(t,e)=>new z({shape:()=>t,unknownKeys:"strict",catchall:Me.create(),typeName:f.ZodObject,...E(e)});z.lazycreate=(t,e)=>new z({shape:t,unknownKeys:"strip",catchall:Me.create(),typeName:f.ZodObject,...E(e)});class dr extends ${_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function s(a){for(const o of a)if(o.result.status==="valid")return o.result;for(const o of a)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(o=>new le(o.ctx.common.issues));return _(r,{code:h.invalid_union,unionErrors:i}),S}if(r.common.async)return Promise.all(n.map(async a=>{const i={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let a;const i=[];for(const l of n){const c={...r,common:{...r.common,issues:[]},parent:null},d=l._parseSync({data:r.data,path:r.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!a&&(a={result:d,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(l=>new le(l));return _(r,{code:h.invalid_union,unionErrors:o}),S}}get options(){return this._def.options}}dr.create=(t,e)=>new dr({options:t,typeName:f.ZodUnion,...E(e)});const Pe=t=>t instanceof fr?Pe(t.schema):t instanceof we?Pe(t.innerType()):t instanceof mr?[t.value]:t instanceof He?t.options:t instanceof gr?C.objectValues(t.enum):t instanceof yr?Pe(t._def.innerType):t instanceof cr?[void 0]:t instanceof ur?[null]:t instanceof be?[void 0,...Pe(t.unwrap())]:t instanceof Je?[null,...Pe(t.unwrap())]:t instanceof ds||t instanceof _r?Pe(t.unwrap()):t instanceof vr?Pe(t._def.innerType):[];class _n extends ${_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==b.object)return _(r,{code:h.invalid_type,expected:b.object,received:r.parsedType}),S;const n=this.discriminator,s=r.data[n],a=this.optionsMap.get(s);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(_(r,{code:h.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),S)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){const s=new Map;for(const a of r){const i=Pe(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 _n({typeName:f.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...E(n)})}}function Yn(t,e){const r=je(t),n=je(e);if(t===e)return{valid:!0,data:t};if(r===b.object&&n===b.object){const s=C.objectKeys(e),a=C.objectKeys(t).filter(o=>s.indexOf(o)!==-1),i={...t,...e};for(const o of a){const l=Yn(t[o],e[o]);if(!l.valid)return{valid:!1};i[o]=l.data}return{valid:!0,data:i}}else if(r===b.array&&n===b.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let a=0;a<t.length;a++){const i=t[a],o=e[a],l=Yn(i,o);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return r===b.date&&n===b.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class pr extends ${_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=(a,i)=>{if(Wn(a)||Wn(i))return S;const o=Yn(a.value,i.value);return o.valid?((Gn(a)||Gn(i))&&r.dirty(),{status:r.value,value:o.data}):(_(n,{code:h.invalid_intersection_types}),S)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,i])=>s(a,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}pr.create=(t,e,r)=>new pr({left:t,right:e,typeName:f.ZodIntersection,...E(r)});class Ce extends ${_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.array)return _(n,{code:h.invalid_type,expected:b.array,received:n.parsedType}),S;if(n.data.length<this._def.items.length)return _(n,{code:h.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;!this._def.rest&&n.data.length>this._def.items.length&&(_(n,{code:h.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const a=[...n.data].map((i,o)=>{const l=this._def.items[o]||this._def.rest;return l?l._parse(new Ie(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>Q.mergeArray(r,i)):Q.mergeArray(r,a)}get items(){return this._def.items}rest(e){return new Ce({...this._def,rest:e})}}Ce.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ce({items:t,typeName:f.ZodTuple,rest:null,...E(e)})};class hr extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.object)return _(n,{code:h.invalid_type,expected:b.object,received:n.parsedType}),S;const s=[],a=this._def.keyType,i=this._def.valueType;for(const o in n.data)s.push({key:a._parse(new Ie(n,o,n.path,o)),value:i._parse(new Ie(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?Q.mergeObjectAsync(r,s):Q.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof $?new hr({keyType:e,valueType:r,typeName:f.ZodRecord,...E(n)}):new hr({keyType:ve.create(),valueType:e,typeName:f.ZodRecord,...E(r)})}}class rn extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.map)return _(n,{code:h.invalid_type,expected:b.map,received:n.parsedType}),S;const s=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([o,l],c)=>({key:s._parse(new Ie(n,o,n.path,[c,"key"])),value:a._parse(new Ie(n,l,n.path,[c,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const l of i){const c=await l.key,d=await l.value;if(c.status==="aborted"||d.status==="aborted")return S;(c.status==="dirty"||d.status==="dirty")&&r.dirty(),o.set(c.value,d.value)}return{status:r.value,value:o}})}else{const o=new Map;for(const l of i){const c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return S;(c.status==="dirty"||d.status==="dirty")&&r.dirty(),o.set(c.value,d.value)}return{status:r.value,value:o}}}}rn.create=(t,e,r)=>new rn({valueType:e,keyType:t,typeName:f.ZodMap,...E(r)});class dt extends ${_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.set)return _(n,{code:h.invalid_type,expected:b.set,received:n.parsedType}),S;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(_(n,{code:h.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(_(n,{code:h.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());const a=this._def.valueType;function i(l){const c=new Set;for(const d of l){if(d.status==="aborted")return S;d.status==="dirty"&&r.dirty(),c.add(d.value)}return{status:r.value,value:c}}const o=[...n.data.values()].map((l,c)=>a._parse(new Ie(n,l,n.path,c)));return n.common.async?Promise.all(o).then(l=>i(l)):i(o)}min(e,r){return new dt({...this._def,minSize:{value:e,message:x.toString(r)}})}max(e,r){return new dt({...this._def,maxSize:{value:e,message:x.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}dt.create=(t,e)=>new dt({valueType:t,minSize:null,maxSize:null,typeName:f.ZodSet,...E(e)});class Et extends ${constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==b.function)return _(r,{code:h.invalid_type,expected:b.function,received:r.parsedType}),S;function n(o,l){return Xr({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Kr(),Ot].filter(c=>!!c),issueData:{code:h.invalid_arguments,argumentsError:l}})}function s(o,l){return Xr({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Kr(),Ot].filter(c=>!!c),issueData:{code:h.invalid_return_type,returnTypeError:l}})}const a={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Rt){const o=this;return ne(async function(...l){const c=new le([]),d=await o._def.args.parseAsync(l,a).catch(w=>{throw c.addIssue(n(l,w)),c}),p=await Reflect.apply(i,this,d);return await o._def.returns._def.type.parseAsync(p,a).catch(w=>{throw c.addIssue(s(p,w)),c})})}else{const o=this;return ne(function(...l){const c=o._def.args.safeParse(l,a);if(!c.success)throw new le([n(l,c.error)]);const d=Reflect.apply(i,this,c.data),p=o._def.returns.safeParse(d,a);if(!p.success)throw new le([s(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Et({...this._def,args:Ce.create(e).rest(at.create())})}returns(e){return new Et({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new Et({args:e||Ce.create([]).rest(at.create()),returns:r||at.create(),typeName:f.ZodFunction,...E(n)})}}class fr extends ${get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}fr.create=(t,e)=>new fr({getter:t,typeName:f.ZodLazy,...E(e)});class mr extends ${_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return _(r,{received:r.data,code:h.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:e.data}}get value(){return this._def.value}}mr.create=(t,e)=>new mr({value:t,typeName:f.ZodLiteral,...E(e)});function vi(t,e){return new He({values:t,typeName:f.ZodEnum,...E(e)})}class He extends ${constructor(){super(...arguments),qt.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return _(r,{expected:C.joinValues(n),received:r.parsedType,code:h.invalid_type}),S}if(Qr(this,qt)||fi(this,qt,new Set(this._def.values)),!Qr(this,qt).has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return _(r,{received:r.data,code:h.invalid_enum_value,options:n}),S}return ne(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return He.create(e,{...this._def,...r})}exclude(e,r=this._def){return He.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}qt=new WeakMap;He.create=vi;class gr extends ${constructor(){super(...arguments),Ht.set(this,void 0)}_parse(e){const r=C.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==b.string&&n.parsedType!==b.number){const s=C.objectValues(r);return _(n,{expected:C.joinValues(s),received:n.parsedType,code:h.invalid_type}),S}if(Qr(this,Ht)||fi(this,Ht,new Set(C.getValidEnumValues(this._def.values))),!Qr(this,Ht).has(e.data)){const s=C.objectValues(r);return _(n,{received:n.data,code:h.invalid_enum_value,options:s}),S}return ne(e.data)}get enum(){return this._def.values}}Ht=new WeakMap;gr.create=(t,e)=>new gr({values:t,typeName:f.ZodNativeEnum,...E(e)});class Rt extends ${unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==b.promise&&r.common.async===!1)return _(r,{code:h.invalid_type,expected:b.promise,received:r.parsedType}),S;const n=r.parsedType===b.promise?r.data:Promise.resolve(r.data);return ne(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Rt.create=(t,e)=>new Rt({type:t,typeName:f.ZodPromise,...E(e)});class we extends ${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===f.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{_(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){const i=s.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async o=>{if(r.value==="aborted")return S;const l=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return l.status==="aborted"?S:l.status==="dirty"||r.value==="dirty"?xt(l.value):l});{if(r.value==="aborted")return S;const o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?S:o.status==="dirty"||r.value==="dirty"?xt(o.value):o}}if(s.type==="refinement"){const i=o=>{const l=s.refinement(o,a);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?S:(o.status==="dirty"&&r.dirty(),i(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?S:(o.status==="dirty"&&r.dirty(),i(o.value).then(()=>({status:r.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ct(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=>ct(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:r.value,value:o})):i);C.assertNever(s)}}we.create=(t,e,r)=>new we({schema:t,typeName:f.ZodEffects,effect:e,...E(r)});we.createWithPreprocess=(t,e,r)=>new we({schema:e,effect:{type:"preprocess",transform:t},typeName:f.ZodEffects,...E(r)});class be extends ${_parse(e){return this._getType(e)===b.undefined?ne(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}be.create=(t,e)=>new be({innerType:t,typeName:f.ZodOptional,...E(e)});class Je extends ${_parse(e){return this._getType(e)===b.null?ne(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Je.create=(t,e)=>new Je({innerType:t,typeName:f.ZodNullable,...E(e)});class yr extends ${_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===b.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}yr.create=(t,e)=>new yr({innerType:t,typeName:f.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...E(e)});class vr extends ${_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return or(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new le(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new le(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}vr.create=(t,e)=>new vr({innerType:t,typeName:f.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...E(e)});class nn extends ${_parse(e){if(this._getType(e)!==b.nan){const n=this._getOrReturnCtx(e);return _(n,{code:h.invalid_type,expected:b.nan,received:n.parsedType}),S}return{status:"valid",value:e.data}}}nn.create=t=>new nn({typeName:f.ZodNaN,...E(t)});const _c=Symbol("zod_brand");class ds extends ${_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class Ir extends ${_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?S:a.status==="dirty"?(r.dirty(),xt(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?S:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new Ir({in:e,out:r,typeName:f.ZodPipeline})}}class _r extends ${_parse(e){const r=this._def.innerType._parse(e),n=s=>(ct(s)&&(s.value=Object.freeze(s.value)),s);return or(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}}_r.create=(t,e)=>new _r({innerType:t,typeName:f.ZodReadonly,...E(e)});function Qs(t,e){const r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function _i(t,e={},r){return t?Pt.create().superRefine((n,s)=>{var a,i;const o=t(n);if(o instanceof Promise)return o.then(l=>{var c,d;if(!l){const p=Qs(e,n),g=(d=(c=p.fatal)!==null&&c!==void 0?c:r)!==null&&d!==void 0?d:!0;s.addIssue({code:"custom",...p,fatal:g})}});if(!o){const l=Qs(e,n),c=(i=(a=l.fatal)!==null&&a!==void 0?a:r)!==null&&i!==void 0?i:!0;s.addIssue({code:"custom",...l,fatal:c})}}):Pt.create()}const bc={object:z.lazycreate};var f;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(f||(f={}));const wc=(t,e={message:`Input not instance of ${t.name}`})=>_i(r=>r instanceof t,e),bi=ve.create,wi=Be.create,xc=nn.create,Ac=qe.create,xi=lr.create,Sc=ut.create,kc=en.create,Ec=cr.create,Tc=ur.create,$c=Pt.create,Ic=at.create,Cc=Me.create,Oc=tn.create,Pc=_e.create,Rc=z.create,jc=z.strictCreate,Nc=dr.create,Mc=_n.create,Dc=pr.create,Zc=Ce.create,Uc=hr.create,Lc=rn.create,Fc=dt.create,Vc=Et.create,zc=fr.create,Bc=mr.create,qc=He.create,Hc=gr.create,Jc=Rt.create,ea=we.create,Wc=be.create,Gc=Je.create,Yc=we.createWithPreprocess,Kc=Ir.create,Xc=()=>bi().optional(),Qc=()=>wi().optional(),eu=()=>xi().optional(),tu={string:t=>ve.create({...t,coerce:!0}),number:t=>Be.create({...t,coerce:!0}),boolean:t=>lr.create({...t,coerce:!0}),bigint:t=>qe.create({...t,coerce:!0}),date:t=>ut.create({...t,coerce:!0})},ru=S;var u=Object.freeze({__proto__:null,defaultErrorMap:Ot,setErrorMap:Yl,getErrorMap:Kr,makeIssue:Xr,EMPTY_PATH:Kl,addIssueToContext:_,ParseStatus:Q,INVALID:S,DIRTY:xt,OK:ne,isAborted:Wn,isDirty:Gn,isValid:ct,isAsync:or,get util(){return C},get objectUtil(){return Jn},ZodParsedType:b,getParsedType:je,ZodType:$,datetimeRegex:yi,ZodString:ve,ZodNumber:Be,ZodBigInt:qe,ZodBoolean:lr,ZodDate:ut,ZodSymbol:en,ZodUndefined:cr,ZodNull:ur,ZodAny:Pt,ZodUnknown:at,ZodNever:Me,ZodVoid:tn,ZodArray:_e,ZodObject:z,ZodUnion:dr,ZodDiscriminatedUnion:_n,ZodIntersection:pr,ZodTuple:Ce,ZodRecord:hr,ZodMap:rn,ZodSet:dt,ZodFunction:Et,ZodLazy:fr,ZodLiteral:mr,ZodEnum:He,ZodNativeEnum:gr,ZodPromise:Rt,ZodEffects:we,ZodTransformer:we,ZodOptional:be,ZodNullable:Je,ZodDefault:yr,ZodCatch:vr,ZodNaN:nn,BRAND:_c,ZodBranded:ds,ZodPipeline:Ir,ZodReadonly:_r,custom:_i,Schema:$,ZodSchema:$,late:bc,get ZodFirstPartyTypeKind(){return f},coerce:tu,any:$c,array:Pc,bigint:Ac,boolean:xi,date:Sc,discriminatedUnion:Mc,effect:ea,enum:qc,function:Vc,instanceof:wc,intersection:Dc,lazy:zc,literal:Bc,map:Lc,nan:xc,nativeEnum:Hc,never:Cc,null:Tc,nullable:Gc,number:wi,object:Rc,oboolean:eu,onumber:Qc,optional:Wc,ostring:Xc,pipeline:Kc,preprocess:Yc,promise:Jc,record:Uc,set:Fc,strictObject:jc,string:bi,symbol:kc,transformer:ea,tuple:Zc,undefined:Ec,union:Nc,unknown:Ic,void:Oc,NEVER:ru,ZodIssueCode:h,quotelessJson:Gl,ZodError:le});function nu({prompt:t,useLegacyFunctionCalling:e=!1,systemMessageMode:r="system"}){const n=[];for(const{role:s,content:a}of t)switch(s){case"system":{switch(r){case"system":{n.push({role:"system",content:a});break}case"developer":{n.push({role:"developer",content:a});break}case"remove":break;default:{const i=r;throw new Error(`Unsupported system message mode: ${i}`)}}break}case"user":{if(a.length===1&&a[0].type==="text"){n.push({role:"user",content:a[0].text});break}n.push({role:"user",content:a.map(i=>{var o,l,c;switch(i.type){case"text":return{type:"text",text:i.text};case"image":return{type:"image_url",image_url:{url:i.image instanceof URL?i.image.toString():`data:${(o=i.mimeType)!=null?o:"image/jpeg"};base64,${Hn(i.image)}`,detail:(c=(l=i.providerMetadata)==null?void 0:l.openai)==null?void 0:c.imageDetail}};case"file":{if(i.data instanceof URL)throw new G({functionality:"'File content parts with URL data' functionality not supported."});switch(i.mimeType){case"audio/wav":return{type:"input_audio",input_audio:{data:i.data,format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:i.data,format:"mp3"}};default:throw new G({functionality:`File content part type ${i.mimeType} in user messages`})}}}})});break}case"assistant":{let i="";const o=[];for(const l of a)switch(l.type){case"text":{i+=l.text;break}case"redacted-reasoning":case"reasoning":break;case"tool-call":{o.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.args)}});break}default:{const c=l;throw new Error(`Unsupported part: ${c}`)}}if(e){if(o.length>1)throw new G({functionality:"useLegacyFunctionCalling with multiple tool calls in one message"});n.push({role:"assistant",content:i,function_call:o.length>0?o[0].function:void 0})}else n.push({role:"assistant",content:i,tool_calls:o.length>0?o:void 0});break}case"tool":{for(const i of a)e?n.push({role:"function",name:i.toolName,content:JSON.stringify(i.result)}):n.push({role:"tool",tool_call_id:i.toolCallId,content:JSON.stringify(i.result)});break}default:{const i=s;throw new Error(`Unsupported role: ${i}`)}}return n}function ta(t){var e,r;return(r=(e=t==null?void 0:t.content)==null?void 0:e.map(({token:n,logprob:s,top_logprobs:a})=>({token:n,logprob:s,topLogprobs:a?a.map(({token:i,logprob:o})=>({token:i,logprob:o})):[]})))!=null?r:void 0}function sn(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var ps=u.object({error:u.object({message:u.string(),type:u.string().nullish(),param:u.any().nullish(),code:u.union([u.string(),u.number()]).nullish()})}),jt=Bl({errorSchema:ps,errorToMessage:t=>t.error.message});function an({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function su({mode:t,useLegacyFunctionCalling:e=!1,structuredOutputs:r}){var n;const s=(n=t.tools)!=null&&n.length?t.tools:void 0,a=[];if(s==null)return{tools:void 0,tool_choice:void 0,toolWarnings:a};const i=t.toolChoice;if(e){const c=[];for(const p of s)p.type==="provider-defined"?a.push({type:"unsupported-tool",tool:p}):c.push({name:p.name,description:p.description,parameters:p.parameters});if(i==null)return{functions:c,function_call:void 0,toolWarnings:a};switch(i.type){case"auto":case"none":case void 0:return{functions:c,function_call:void 0,toolWarnings:a};case"required":throw new G({functionality:"useLegacyFunctionCalling and toolChoice: required"});default:return{functions:c,function_call:{name:i.toolName},toolWarnings:a}}}const o=[];for(const c of s)c.type==="provider-defined"?a.push({type:"unsupported-tool",tool:c}):o.push({type:"function",function:{name:c.name,description:c.description,parameters:c.parameters,strict:r?!0:void 0}});if(i==null)return{tools:o,tool_choice:void 0,toolWarnings:a};const l=i.type;switch(l){case"auto":case"none":case"required":return{tools:o,tool_choice:l,toolWarnings:a};case"tool":return{tools:o,tool_choice:{type:"function",function:{name:i.toolName}},toolWarnings:a};default:{const c=l;throw new G({functionality:`Unsupported tool choice type: ${c}`})}}}var au=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:Kn(this.modelId)}get defaultObjectGenerationMode(){return lu(this.modelId)?"tool":this.supportsStructuredOutputs?"json":"tool"}get provider(){return this.config.provider}get supportsImageUrls(){return!this.settings.downloadImages}getArgs({mode:t,prompt:e,maxTokens:r,temperature:n,topP:s,topK:a,frequencyPenalty:i,presencePenalty:o,stopSequences:l,responseFormat:c,seed:d,providerMetadata:p}){var g,w,y,m,v,A,k,T;const P=t.type,R=[];a!=null&&R.push({type:"unsupported-setting",setting:"topK"}),(c==null?void 0:c.type)==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&R.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const B=this.settings.useLegacyFunctionCalling;if(B&&this.settings.parallelToolCalls===!0)throw new G({functionality:"useLegacyFunctionCalling with parallelToolCalls"});if(B&&this.supportsStructuredOutputs)throw new G({functionality:"structuredOutputs with useLegacyFunctionCalling"});ra(this.modelId)==="remove"&&e.some(Y=>Y.role==="system")&&R.push({type:"other",message:"system messages are removed for this model"});const I={model:this.modelId,logit_bias:this.settings.logitBias,logprobs:this.settings.logprobs===!0||typeof this.settings.logprobs=="number"?!0:void 0,top_logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,user:this.settings.user,parallel_tool_calls:this.settings.parallelToolCalls,max_tokens:r,temperature:n,top_p:s,frequency_penalty:i,presence_penalty:o,response_format:(c==null?void 0:c.type)==="json"?this.supportsStructuredOutputs&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,strict:!0,name:(g=c.name)!=null?g:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:d,max_completion_tokens:(w=p==null?void 0:p.openai)==null?void 0:w.maxCompletionTokens,store:(y=p==null?void 0:p.openai)==null?void 0:y.store,metadata:(m=p==null?void 0:p.openai)==null?void 0:m.metadata,prediction:(v=p==null?void 0:p.openai)==null?void 0:v.prediction,reasoning_effort:(k=(A=p==null?void 0:p.openai)==null?void 0:A.reasoningEffort)!=null?k:this.settings.reasoningEffort,messages:nu({prompt:e,useLegacyFunctionCalling:B,systemMessageMode:ra(this.modelId)})};switch(Kn(this.modelId)&&(I.temperature!=null&&(I.temperature=void 0,R.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),I.top_p!=null&&(I.top_p=void 0,R.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),I.frequency_penalty!=null&&(I.frequency_penalty=void 0,R.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),I.presence_penalty!=null&&(I.presence_penalty=void 0,R.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),I.logit_bias!=null&&(I.logit_bias=void 0,R.push({type:"other",message:"logitBias is not supported for reasoning models"})),I.logprobs!=null&&(I.logprobs=void 0,R.push({type:"other",message:"logprobs is not supported for reasoning models"})),I.top_logprobs!=null&&(I.top_logprobs=void 0,R.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),I.max_tokens!=null&&(I.max_completion_tokens==null&&(I.max_completion_tokens=I.max_tokens),I.max_tokens=void 0)),P){case"regular":{const{tools:Y,tool_choice:ft,functions:We,function_call:Ge,toolWarnings:Ye}=su({mode:t,useLegacyFunctionCalling:B,structuredOutputs:this.supportsStructuredOutputs});return{args:{...I,tools:Y,tool_choice:ft,functions:We,function_call:Ge},warnings:[...R,...Ye]}}case"object-json":return{args:{...I,response_format:this.supportsStructuredOutputs&&t.schema!=null?{type:"json_schema",json_schema:{schema:t.schema,strict:!0,name:(T=t.name)!=null?T:"response",description:t.description}}:{type:"json_object"}},warnings:R};case"object-tool":return{args:B?{...I,function_call:{name:t.tool.name},functions:[{name:t.tool.name,description:t.tool.description,parameters:t.tool.parameters}]}:{...I,tool_choice:{type:"function",function:{name:t.tool.name}},tools:[{type:"function",function:{name:t.tool.name,description:t.tool.description,parameters:t.tool.parameters,strict:this.supportsStructuredOutputs?!0:void 0}}]},warnings:R};default:{const Y=P;throw new Error(`Unsupported type: ${Y}`)}}}async doGenerate(t){var e,r,n,s,a,i,o,l;const{args:c,warnings:d}=this.getArgs(t),{responseHeaders:p,value:g,rawValue:w}=await Ct({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:$t(this.config.headers(),t.headers),body:c,failedResponseHandler:jt,successfulResponseHandler:vn(iu),abortSignal:t.abortSignal,fetch:this.config.fetch}),{messages:y,...m}=c,v=g.choices[0],A=(e=g.usage)==null?void 0:e.completion_tokens_details,k=(r=g.usage)==null?void 0:r.prompt_tokens_details,T={openai:{}};return(A==null?void 0:A.reasoning_tokens)!=null&&(T.openai.reasoningTokens=A==null?void 0:A.reasoning_tokens),(A==null?void 0:A.accepted_prediction_tokens)!=null&&(T.openai.acceptedPredictionTokens=A==null?void 0:A.accepted_prediction_tokens),(A==null?void 0:A.rejected_prediction_tokens)!=null&&(T.openai.rejectedPredictionTokens=A==null?void 0:A.rejected_prediction_tokens),(k==null?void 0:k.cached_tokens)!=null&&(T.openai.cachedPromptTokens=k==null?void 0:k.cached_tokens),{text:(n=v.message.content)!=null?n:void 0,toolCalls:this.settings.useLegacyFunctionCalling&&v.message.function_call?[{toolCallType:"function",toolCallId:Ft(),toolName:v.message.function_call.name,args:v.message.function_call.arguments}]:(s=v.message.tool_calls)==null?void 0:s.map(P=>{var R;return{toolCallType:"function",toolCallId:(R=P.id)!=null?R:Ft(),toolName:P.function.name,args:P.function.arguments}}),finishReason:sn(v.finish_reason),usage:{promptTokens:(i=(a=g.usage)==null?void 0:a.prompt_tokens)!=null?i:NaN,completionTokens:(l=(o=g.usage)==null?void 0:o.completion_tokens)!=null?l:NaN},rawCall:{rawPrompt:y,rawSettings:m},rawResponse:{headers:p,body:w},request:{body:JSON.stringify(c)},response:an(g),warnings:d,logprobs:ta(v.logprobs),providerMetadata:T}}async doStream(t){if(this.settings.simulateStreaming){const m=await this.doGenerate(t);return{stream:new ReadableStream({start(A){if(A.enqueue({type:"response-metadata",...m.response}),m.text&&A.enqueue({type:"text-delta",textDelta:m.text}),m.toolCalls)for(const k of m.toolCalls)A.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:k.toolCallId,toolName:k.toolName,argsTextDelta:k.args}),A.enqueue({type:"tool-call",...k});A.enqueue({type:"finish",finishReason:m.finishReason,usage:m.usage,logprobs:m.logprobs,providerMetadata:m.providerMetadata}),A.close()}}),rawCall:m.rawCall,rawResponse:m.rawResponse,warnings:m.warnings}}const{args:e,warnings:r}=this.getArgs(t),n={...e,stream:!0,stream_options:this.config.compatibility==="strict"?{include_usage:!0}:void 0},{responseHeaders:s,value:a}=await Ct({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:$t(this.config.headers(),t.headers),body:n,failedResponseHandler:jt,successfulResponseHandler:pi(ou),abortSignal:t.abortSignal,fetch:this.config.fetch}),{messages:i,...o}=e,l=[];let c="unknown",d={promptTokens:void 0,completionTokens:void 0},p,g=!0;const{useLegacyFunctionCalling:w}=this.settings,y={openai:{}};return{stream:a.pipeThrough(new TransformStream({transform(m,v){var A,k,T,P,R,B,I,Y,ft,We,Ge,Ye;if(!m.success){c="error",v.enqueue({type:"error",error:m.error});return}const Oe=m.value;if("error"in Oe){c="error",v.enqueue({type:"error",error:Oe.error});return}if(g&&(g=!1,v.enqueue({type:"response-metadata",...an(Oe)})),Oe.usage!=null){const{prompt_tokens:V,completion_tokens:se,prompt_tokens_details:H,completion_tokens_details:D}=Oe.usage;d={promptTokens:V??void 0,completionTokens:se??void 0},(D==null?void 0:D.reasoning_tokens)!=null&&(y.openai.reasoningTokens=D==null?void 0:D.reasoning_tokens),(D==null?void 0:D.accepted_prediction_tokens)!=null&&(y.openai.acceptedPredictionTokens=D==null?void 0:D.accepted_prediction_tokens),(D==null?void 0:D.rejected_prediction_tokens)!=null&&(y.openai.rejectedPredictionTokens=D==null?void 0:D.rejected_prediction_tokens),(H==null?void 0:H.cached_tokens)!=null&&(y.openai.cachedPromptTokens=H==null?void 0:H.cached_tokens)}const ie=Oe.choices[0];if((ie==null?void 0:ie.finish_reason)!=null&&(c=sn(ie.finish_reason)),(ie==null?void 0:ie.delta)==null)return;const Ae=ie.delta;Ae.content!=null&&v.enqueue({type:"text-delta",textDelta:Ae.content});const ce=ta(ie==null?void 0:ie.logprobs);ce!=null&&ce.length&&(p===void 0&&(p=[]),p.push(...ce));const mt=w&&Ae.function_call!=null?[{type:"function",id:Ft(),function:Ae.function_call,index:0}]:Ae.tool_calls;if(mt!=null)for(const V of mt){const se=V.index;if(l[se]==null){if(V.type!=="function")throw new In({data:V,message:"Expected 'function' type."});if(V.id==null)throw new In({data:V,message:"Expected 'id' to be a string."});if(((A=V.function)==null?void 0:A.name)==null)throw new In({data:V,message:"Expected 'function.name' to be a string."});l[se]={id:V.id,type:"function",function:{name:V.function.name,arguments:(k=V.function.arguments)!=null?k:""},hasFinished:!1};const D=l[se];((T=D.function)==null?void 0:T.name)!=null&&((P=D.function)==null?void 0:P.arguments)!=null&&(D.function.arguments.length>0&&v.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:D.id,toolName:D.function.name,argsTextDelta:D.function.arguments}),Ks(D.function.arguments)&&(v.enqueue({type:"tool-call",toolCallType:"function",toolCallId:(R=D.id)!=null?R:Ft(),toolName:D.function.name,args:D.function.arguments}),D.hasFinished=!0));continue}const H=l[se];H.hasFinished||(((B=V.function)==null?void 0:B.arguments)!=null&&(H.function.arguments+=(Y=(I=V.function)==null?void 0:I.arguments)!=null?Y:""),v.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:H.id,toolName:H.function.name,argsTextDelta:(ft=V.function.arguments)!=null?ft:""}),((We=H.function)==null?void 0:We.name)!=null&&((Ge=H.function)==null?void 0:Ge.arguments)!=null&&Ks(H.function.arguments)&&(v.enqueue({type:"tool-call",toolCallType:"function",toolCallId:(Ye=H.id)!=null?Ye:Ft(),toolName:H.function.name,args:H.function.arguments}),H.hasFinished=!0))}},flush(m){var v,A;m.enqueue({type:"finish",finishReason:c,logprobs:p,usage:{promptTokens:(v=d.promptTokens)!=null?v:NaN,completionTokens:(A=d.completionTokens)!=null?A:NaN},...y!=null?{providerMetadata:y}:{}})}})),rawCall:{rawPrompt:i,rawSettings:o},rawResponse:{headers:s},request:{body:JSON.stringify(n)},warnings:r}}},Ai=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(),iu=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:Ai}),ou=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:Ai}),ps]);function Kn(t){return t==="o1"||t.startsWith("o1-")||t==="o3"||t.startsWith("o3-")}function lu(t){return t.startsWith("gpt-4o-audio-preview")}function ra(t){var e,r;return Kn(t)?(r=(e=cu[t])==null?void 0:e.systemMessageMode)!=null?r:"developer":"system"}var cu={"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 uu({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 et({message:"Unexpected system message in prompt: ${content}",prompt:t});case"user":{const o=i.map(l=>{switch(l.type){case"text":return l.text;case"image":throw new G({functionality:"images"})}}).join("");s+=`${r}:
|
171
|
+
${o}
|
172
|
+
|
173
|
+
`;break}case"assistant":{const o=i.map(l=>{switch(l.type){case"text":return l.text;case"tool-call":throw new G({functionality:"tool-call messages"})}}).join("");s+=`${n}:
|
174
|
+
${o}
|
175
|
+
|
176
|
+
`;break}case"tool":throw new G({functionality:"tool messages"});default:{const o=a;throw new Error(`Unsupported role: ${o}`)}}return s+=`${n}:
|
177
|
+
`,{prompt:s,stopSequences:[`
|
178
|
+
${r}:`]}}function na(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 du=class{constructor(t,e,r){this.specificationVersion="v1",this.defaultObjectGenerationMode=void 0,this.modelId=t,this.settings=e,this.config=r}get provider(){return this.config.provider}getArgs({mode:t,inputFormat:e,prompt:r,maxTokens:n,temperature:s,topP:a,topK:i,frequencyPenalty:o,presencePenalty:l,stopSequences:c,responseFormat:d,seed:p}){var g;const w=t.type,y=[];i!=null&&y.push({type:"unsupported-setting",setting:"topK"}),d!=null&&d.type!=="text"&&y.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:m,stopSequences:v}=uu({prompt:r,inputFormat:e}),A=[...v??[],...c??[]],k={model:this.modelId,echo:this.settings.echo,logit_bias:this.settings.logitBias,logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,suffix:this.settings.suffix,user:this.settings.user,max_tokens:n,temperature:s,top_p:a,frequency_penalty:o,presence_penalty:l,seed:p,prompt:m,stop:A.length>0?A:void 0};switch(w){case"regular":{if((g=t.tools)!=null&&g.length)throw new G({functionality:"tools"});if(t.toolChoice)throw new G({functionality:"toolChoice"});return{args:k,warnings:y}}case"object-json":throw new G({functionality:"object-json mode"});case"object-tool":throw new G({functionality:"object-tool mode"});default:{const T=w;throw new Error(`Unsupported type: ${T}`)}}}async doGenerate(t){const{args:e,warnings:r}=this.getArgs(t),{responseHeaders:n,value:s,rawValue:a}=await Ct({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:$t(this.config.headers(),t.headers),body:e,failedResponseHandler:jt,successfulResponseHandler:vn(pu),abortSignal:t.abortSignal,fetch:this.config.fetch}),{prompt:i,...o}=e,l=s.choices[0];return{text:l.text,usage:{promptTokens:s.usage.prompt_tokens,completionTokens:s.usage.completion_tokens},finishReason:sn(l.finish_reason),logprobs:na(l.logprobs),rawCall:{rawPrompt:i,rawSettings:o},rawResponse:{headers:n,body:a},response:an(s),warnings:r,request:{body:JSON.stringify(e)}}}async doStream(t){const{args:e,warnings:r}=this.getArgs(t),n={...e,stream:!0,stream_options:this.config.compatibility==="strict"?{include_usage:!0}:void 0},{responseHeaders:s,value:a}=await Ct({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:$t(this.config.headers(),t.headers),body:n,failedResponseHandler:jt,successfulResponseHandler:pi(hu),abortSignal:t.abortSignal,fetch:this.config.fetch}),{prompt:i,...o}=e;let l="unknown",c={promptTokens:Number.NaN,completionTokens:Number.NaN},d,p=!0;return{stream:a.pipeThrough(new TransformStream({transform(g,w){if(!g.success){l="error",w.enqueue({type:"error",error:g.error});return}const y=g.value;if("error"in y){l="error",w.enqueue({type:"error",error:y.error});return}p&&(p=!1,w.enqueue({type:"response-metadata",...an(y)})),y.usage!=null&&(c={promptTokens:y.usage.prompt_tokens,completionTokens:y.usage.completion_tokens});const m=y.choices[0];(m==null?void 0:m.finish_reason)!=null&&(l=sn(m.finish_reason)),(m==null?void 0:m.text)!=null&&w.enqueue({type:"text-delta",textDelta:m.text});const v=na(m==null?void 0:m.logprobs);v!=null&&v.length&&(d===void 0&&(d=[]),d.push(...v))},flush(g){g.enqueue({type:"finish",finishReason:l,logprobs:d,usage:c})}})),rawCall:{rawPrompt:i,rawSettings:o},rawResponse:{headers:s},warnings:r,request:{body:JSON.stringify(n)}}}},pu=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()})}),hu=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()}),ps]),fu=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 yl({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const{responseHeaders:n,value:s}=await Ct({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:$t(this.config.headers(),e),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:this.settings.dimensions,user:this.settings.user},failedResponseHandler:jt,successfulResponseHandler:vn(mu),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}}}},mu=u.object({data:u.array(u.object({embedding:u.array(u.number())})),usage:u.object({prompt_tokens:u.number()}).nullish()}),gu={"dall-e-3":1,"dall-e-2":10},yu=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:gu[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:n,seed:s,providerOptions:a,headers:i,abortSignal:o}){var l,c,d,p;const g=[];n!=null&&g.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),s!=null&&g.push({type:"unsupported-setting",setting:"seed"});const w=(d=(c=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:c.call(l))!=null?d:new Date,{value:y,responseHeaders:m}=await Ct({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:$t(this.config.headers(),i),body:{model:this.modelId,prompt:t,n:e,size:r,...(p=a.openai)!=null?p:{},response_format:"b64_json"},failedResponseHandler:jt,successfulResponseHandler:vn(vu),abortSignal:o,fetch:this.config.fetch});return{images:y.data.map(v=>v.b64_json),warnings:g,response:{timestamp:w,modelId:this.modelId,headers:m}}}},vu=u.object({data:u.array(u.object({b64_json:u.string()}))});function Si(t={}){var e,r,n;const s=(e=Wl(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 ${Nl({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers}),l=(y,m={})=>new au(y,m,{provider:`${i}.chat`,url:({path:v})=>`${s}${v}`,headers:o,compatibility:a,fetch:t.fetch}),c=(y,m={})=>new du(y,m,{provider:`${i}.completion`,url:({path:v})=>`${s}${v}`,headers:o,compatibility:a,fetch:t.fetch}),d=(y,m={})=>new fu(y,m,{provider:`${i}.embedding`,url:({path:v})=>`${s}${v}`,headers:o,fetch:t.fetch}),p=(y,m={})=>new yu(y,m,{provider:`${i}.image`,url:({path:v})=>`${s}${v}`,headers:o,fetch:t.fetch}),g=(y,m)=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return y==="gpt-3.5-turbo-instruct"?c(y,m):l(y,m)},w=function(y,m){return g(y,m)};return w.languageModel=g,w.chat=l,w.completion=c,w.embedding=d,w.textEmbedding=d,w.textEmbeddingModel=d,w.image=p,w.imageModel=p,w}Si({compatibility:"strict"});const _u=Symbol("Let zodToJsonSchema decide on which parser to use"),sa={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"},bu=t=>typeof t=="string"?{...sa,name:t}:{...sa,...t},wu=t=>{const e=bu(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 ki(t,e,r,n){n!=null&&n.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function M(t,e,r,n,s){t[e]=r,ki(t,e,n,s)}function xu(){return{}}function Au(t,e){var n,s,a;const r={type:"array"};return(n=t.type)!=null&&n._def&&((a=(s=t.type)==null?void 0:s._def)==null?void 0:a.typeName)!==f.ZodAny&&(r.items=N(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&M(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&M(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(M(r,"minItems",t.exactLength.value,t.exactLength.message,e),M(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Su(t,e){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?M(r,"minimum",n.value,n.message,e):M(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),M(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?M(r,"maximum",n.value,n.message,e):M(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),M(r,"maximum",n.value,n.message,e));break;case"multipleOf":M(r,"multipleOf",n.value,n.message,e);break}return r}function ku(){return{type:"boolean"}}function Ei(t,e){return N(t.type._def,e)}const Eu=(t,e)=>N(t.innerType._def,e);function Ti(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,a)=>Ti(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 Tu(t,e)}}const Tu=(t,e)=>{const r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(const n of t.checks)switch(n.kind){case"min":M(r,"minimum",n.value,n.message,e);break;case"max":M(r,"maximum",n.value,n.message,e);break}return r};function $u(t,e){return{...N(t.innerType._def,e),default:t.defaultValue()}}function Iu(t,e){return e.effectStrategy==="input"?N(t.schema._def,e):{}}function Cu(t){return{type:"string",enum:Array.from(t.values)}}const Ou=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Pu(t,e){const r=[N(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),N(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return r.forEach(a=>{if(Ou(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(n=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...l}=a;i=l}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}function Ru(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 Pn;const me={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:()=>(Pn===void 0&&(Pn=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Pn),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 $i(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":M(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":M(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":ge(r,"email",n.message,e);break;case"format:idn-email":ge(r,"idn-email",n.message,e);break;case"pattern:zod":te(r,me.email,n.message,e);break}break;case"url":ge(r,"uri",n.message,e);break;case"uuid":ge(r,"uuid",n.message,e);break;case"regex":te(r,n.regex,n.message,e);break;case"cuid":te(r,me.cuid,n.message,e);break;case"cuid2":te(r,me.cuid2,n.message,e);break;case"startsWith":te(r,RegExp(`^${Rn(n.value,e)}`),n.message,e);break;case"endsWith":te(r,RegExp(`${Rn(n.value,e)}$`),n.message,e);break;case"datetime":ge(r,"date-time",n.message,e);break;case"date":ge(r,"date",n.message,e);break;case"time":ge(r,"time",n.message,e);break;case"duration":ge(r,"duration",n.message,e);break;case"length":M(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),M(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{te(r,RegExp(Rn(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&ge(r,"ipv4",n.message,e),n.version!=="v4"&&ge(r,"ipv6",n.message,e);break}case"base64url":te(r,me.base64url,n.message,e);break;case"jwt":te(r,me.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&te(r,me.ipv4Cidr,n.message,e),n.version!=="v4"&&te(r,me.ipv6Cidr,n.message,e);break}case"emoji":te(r,me.emoji(),n.message,e);break;case"ulid":{te(r,me.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{ge(r,"binary",n.message,e);break}case"contentEncoding:base64":{M(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{te(r,me.base64,n.message,e);break}}break}case"nanoid":te(r,me.nanoid,n.message,e)}return r}function Rn(t,e){return e.patternStrategy==="escape"?Nu(t):t}const ju=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Nu(t){let e="";for(let r=0;r<t.length;r++)ju.has(t[r])||(e+="\\"),e+=t[r];return e}function ge(t,e,r,n){var s;t.format||(s=t.anyOf)!=null&&s.some(a=>a.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):M(t,"format",e,r,n)}function te(t,e,r,n){var s;t.pattern||(s=t.allOf)!=null&&s.some(a=>a.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:aa(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):M(t,"pattern",aa(e,n),r,n)}function aa(t,e){var l;if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source;let s="",a=!1,i=!1,o=!1;for(let c=0;c<n.length;c++){if(a){s+=n[c],a=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){o?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),o=!1):n[c+1]==="-"&&((l=n[c+2])!=null&&l.match(/[a-z]/))?(s+=n[c],o=!0):s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){s+=`(^|(?<=[\r
|
179
|
+
]))`;continue}else if(n[c]==="$"){s+=`($|(?=[\r
|
180
|
+
]))`;continue}}if(r.s&&n[c]==="."){s+=i?`${n[c]}\r
|
181
|
+
`:`[${n[c]}\r
|
182
|
+
]`;continue}s+=n[c],n[c]==="\\"?a=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function Ii(t,e){var n,s,a,i,o,l;if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&((n=t.keyType)==null?void 0:n._def.typeName)===f.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((c,d)=>({...c,[d]:N(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",d]})??{}}),{}),additionalProperties:!1};const r={type:"object",additionalProperties:N(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(((s=t.keyType)==null?void 0:s._def.typeName)===f.ZodString&&((a=t.keyType._def.checks)!=null&&a.length)){const{type:c,...d}=$i(t.keyType._def,e);return{...r,propertyNames:d}}else{if(((i=t.keyType)==null?void 0:i._def.typeName)===f.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(((o=t.keyType)==null?void 0:o._def.typeName)===f.ZodBranded&&t.keyType._def.type._def.typeName===f.ZodString&&((l=t.keyType._def.type._def.checks)!=null&&l.length)){const{type:c,...d}=Ei(t.keyType._def,e);return{...r,propertyNames:d}}}return r}function Mu(t,e){if(e.mapStrategy==="record")return Ii(t,e);const r=N(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=N(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Du(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 Zu(){return{not:{}}}function Uu(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const on={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Lu(t,e){if(e.target==="openApi3")return ia(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in on&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((s,a)=>{const i=on[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((s,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(a._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){const s=n.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:r.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(a=>!n.includes(a))],[])};return ia(t,e)}const ia=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>N(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Fu(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:on[t.innerType._def.typeName],nullable:!0}:{type:[on[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=N(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=N(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Vu(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",ki(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?M(r,"minimum",n.value,n.message,e):M(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),M(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?M(r,"maximum",n.value,n.message,e):M(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),M(r,"maximum",n.value,n.message,e));break;case"multipleOf":M(r,"multipleOf",n.value,n.message,e);break}return r}function zu(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":N(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":N(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Bu(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 be&&(i=i._def.innerType),i.isNullable()||(i=i.nullable()),o=!1);const l=N(i._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});return l===void 0?s:{properties:{...s.properties,[a]:l},required:o?s.required:[...s.required,a]}},{properties:{},required:[]}),additionalProperties:zu(t,e)};return n.required.length||delete n.required,n}const qu=(t,e)=>{var n;if(e.currentPath.toString()===((n=e.propertyPath)==null?void 0:n.toString()))return N(t.innerType._def,e);const r=N(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}},Hu=(t,e)=>{if(e.pipeStrategy==="input")return N(t.in._def,e);if(e.pipeStrategy==="output")return N(t.out._def,e);const r=N(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=N(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function Ju(t,e){return N(t.type._def,e)}function Wu(t,e){const n={type:"array",uniqueItems:!0,items:N(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&M(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&M(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Gu(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>N(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:N(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>N(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Yu(){return{not:{}}}function Ku(){return{}}const Xu=(t,e)=>N(t.innerType._def,e),Qu=(t,e,r)=>{switch(e){case f.ZodString:return $i(t,r);case f.ZodNumber:return Vu(t,r);case f.ZodObject:return Bu(t,r);case f.ZodBigInt:return Su(t,r);case f.ZodBoolean:return ku();case f.ZodDate:return Ti(t,r);case f.ZodUndefined:return Yu();case f.ZodNull:return Uu(r);case f.ZodArray:return Au(t,r);case f.ZodUnion:case f.ZodDiscriminatedUnion:return Lu(t,r);case f.ZodIntersection:return Pu(t,r);case f.ZodTuple:return Gu(t,r);case f.ZodRecord:return Ii(t,r);case f.ZodLiteral:return Ru(t,r);case f.ZodEnum:return Cu(t);case f.ZodNativeEnum:return Du(t);case f.ZodNullable:return Fu(t,r);case f.ZodOptional:return qu(t,r);case f.ZodMap:return Mu(t,r);case f.ZodSet:return Wu(t,r);case f.ZodLazy:return()=>t.getter()._def;case f.ZodPromise:return Ju(t,r);case f.ZodNaN:case f.ZodNever:return Zu();case f.ZodEffects:return Iu(t,r);case f.ZodAny:return xu();case f.ZodUnknown:return Ku();case f.ZodDefault:return $u(t,r);case f.ZodBranded:return Ei(t,r);case f.ZodReadonly:return Xu(t,r);case f.ZodCatch:return Eu(t,r);case f.ZodPipeline:return Hu(t,r);case f.ZodFunction:case f.ZodVoid:case f.ZodSymbol:return;default:return(n=>{})()}};function N(t,e,r=!1){var o;const n=e.seen.get(t);if(e.override){const l=(o=e.override)==null?void 0:o.call(e,t,e,n,r);if(l!==_u)return l}if(n&&!r){const l=ed(n,e);if(l!==void 0)return l}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const a=Qu(t,t.typeName,e),i=typeof a=="function"?N(a(),e):a;if(i&&rd(t,e,i),e.postProcess){const l=e.postProcess(i,t,e);return s.jsonSchema=i,l}return s.jsonSchema=i,i}const ed=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:td(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}},td=(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("/")},rd=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),nd=(t,e)=>{const r=wu(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[c,d])=>({...l,[c]:N(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??{}}),{}):void 0,s=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,a=N(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??{},i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(a.title=i);const o=s===void 0?n?{...a,[r.definitionPath]:n}:a:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:a}};return r.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o};var br={code:"0",name:"text",parse:t=>{if(typeof t!="string")throw new Error('"text" parts expect a string value.');return{type:"text",value:t}}},wr={code:"3",name:"error",parse:t=>{if(typeof t!="string")throw new Error('"error" parts expect a string value.');return{type:"error",value:t}}},xr={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}}},Ar={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}}}},Sr={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}}},sd=[br,wr,xr,Ar,Sr];br.code+"",wr.code+"",xr.code+"",Ar.code+"",Sr.code+"";br.name+"",br.code,wr.name+"",wr.code,xr.name+"",xr.code,Ar.name+"",Ar.code,Sr.name+"",Sr.code;sd.map(t=>t.code);function ad(t){const e=["ROOT"];let r=-1,n=null;function s(l,c,d){switch(l){case'"':{r=c,e.pop(),e.push(d),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,n=c,e.pop(),e.push(d),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(d),e.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c,e.pop(),e.push(d),e.push("INSIDE_NUMBER");break}case"{":{r=c,e.pop(),e.push(d),e.push("INSIDE_OBJECT_START");break}case"[":{r=c,e.pop(),e.push(d),e.push("INSIDE_ARRAY_START");break}}}function a(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,e.pop();break}}}function i(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,e.pop();break}}}for(let l=0;l<t.length;l++){const c=t[l];switch(e[e.length-1]){case"ROOT":s(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{a(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{e.pop(),r=l;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,e.pop();break}default:{r=l,s(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,e.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.pop(),r=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l;break}case"e":case"E":case"-":case".":break;case",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&a(c,l);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&a(c,l);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{const p=t.substring(n,l+1);!"false".startsWith(p)&&!"true".startsWith(p)&&!"null".startsWith(p)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?a(c,l):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(c,l)):r=l;break}}}let o=t.slice(0,r+1);for(let l=e.length-1;l>=0;l--)switch(e[l]){case"INSIDE_STRING":{o+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{o+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{o+="]";break}case"INSIDE_LITERAL":{const d=t.substring(n,t.length);"true".startsWith(d)?o+="true".slice(d.length):"false".startsWith(d)?o+="false".slice(d.length):"null".startsWith(d)&&(o+="null".slice(d.length))}}return o}function id(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let e=It({text:t});return e.success?{value:e.value,state:"successful-parse"}:(e=It({text:ad(t)}),e.success?{value:e.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var od={code:"0",name:"text",parse:t=>{if(typeof t!="string")throw new Error('"text" parts expect a string value.');return{type:"text",value:t}}},ld={code:"2",name:"data",parse:t=>{if(!Array.isArray(t))throw new Error('"data" parts expect an array value.');return{type:"data",value:t}}},cd={code:"3",name:"error",parse:t=>{if(typeof t!="string")throw new Error('"error" parts expect a string value.');return{type:"error",value:t}}},ud={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}}},dd={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}}},pd={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}}},hd={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}}},fd={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}}},md={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}}},gd={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}}},yd={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}}}},vd={code:"g",name:"reasoning",parse:t=>{if(typeof t!="string")throw new Error('"reasoning" parts expect a string value.');return{type:"reasoning",value:t}}},_d={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}}},bd={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}}}},wd={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}}}},bn=[od,ld,cd,ud,dd,pd,hd,fd,md,gd,yd,vd,_d,bd,wd];Object.fromEntries(bn.map(t=>[t.code,t]));Object.fromEntries(bn.map(t=>[t.name,t.code]));bn.map(t=>t.code);function Ci(t,e){const r=bn.find(n=>n.name===t);if(!r)throw new Error(`Invalid stream part type: ${t}`);return`${r.code}:${JSON.stringify(e)}
|
183
|
+
`}function xd(t,e){var r;const n=(r=void 0)!=null?r:!1;return Qn(nd(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 Xn=Symbol.for("vercel.ai.schema");function Qn(t,{validate:e}={}){return{[Xn]:!0,_type:void 0,[Yr]:!0,jsonSchema:t,validate:e}}function Ad(t){return typeof t=="object"&&t!==null&&Xn in t&&t[Xn]===!0&&"jsonSchema"in t&&"validate"in t}function es(t){return Ad(t)?t:xd(t)}var Sd=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},st="1.9.0",oa=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function kd(t){var e=new Set([t]),r=new Set,n=t.match(oa);if(!n)return function(){return!1};var s={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(s.prerelease!=null)return function(l){return l===t};function a(o){return r.add(o),!1}function i(o){return e.add(o),!0}return function(l){if(e.has(l))return!0;if(r.has(l))return!1;var c=l.match(oa);if(!c)return a(l);var d={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return d.prerelease!=null||s.major!==d.major?a(l):s.major===0?s.minor===d.minor&&s.patch<=d.patch?i(l):a(l):s.minor<=d.minor?i(l):a(l)}}var Ed=kd(st),Td=st.split(".")[0],kr=Symbol.for("opentelemetry.js.api."+Td),Er=Sd;function hs(t,e,r,n){var s;n===void 0&&(n=!1);var a=Er[kr]=(s=Er[kr])!==null&&s!==void 0?s:{version:st};if(!n&&a[t]){var i=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(i.stack||i.message),!1}if(a.version!==st){var i=new Error("@opentelemetry/api: Registration of version v"+a.version+" for "+t+" does not match previously registered API v"+st);return r.error(i.stack||i.message),!1}return a[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+st+"."),!0}function Tr(t){var e,r,n=(e=Er[kr])===null||e===void 0?void 0:e.version;if(!(!n||!Ed(n)))return(r=Er[kr])===null||r===void 0?void 0:r[t]}function fs(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+st+".");var r=Er[kr];r&&delete r[t]}var $d=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},Id=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))},Cd=function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Vt("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Vt("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Vt("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Vt("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Vt("verbose",this._namespace,e)},t}();function Vt(t,e,r){var n=Tr("diag");if(n)return r.unshift(e),n[t].apply(n,Id([],$d(r),!1))}var oe;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(oe||(oe={}));function Od(t,e){t<oe.NONE?t=oe.NONE:t>oe.ALL&&(t=oe.ALL),e=e||{};function r(n,s){var a=e[n];return typeof a=="function"&&t>=s?a.bind(e):function(){}}return{error:r("error",oe.ERROR),warn:r("warn",oe.WARN),info:r("info",oe.INFO),debug:r("debug",oe.DEBUG),verbose:r("verbose",oe.VERBOSE)}}var 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},Rd=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))},jd="diag",ln=function(){function t(){function e(s){return function(){for(var a=[],i=0;i<arguments.length;i++)a[i]=arguments[i];var o=Tr("diag");if(o)return o[s].apply(o,Rd([],Pd(a),!1))}}var r=this,n=function(s,a){var i,o,l;if(a===void 0&&(a={logLevel:oe.INFO}),s===r){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((i=c.stack)!==null&&i!==void 0?i:c.message),!1}typeof a=="number"&&(a={logLevel:a});var d=Tr("diag"),p=Od((o=a.logLevel)!==null&&o!==void 0?o:oe.INFO,s);if(d&&!a.suppressOverrideMessage){var g=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+g),p.warn("Current logger will overwrite one already registered from "+g)}return hs("diag",p,r,!0)};r.setLogger=n,r.disable=function(){fs(jd,r)},r.createComponentLogger=function(s){return new Cd(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 Nd(t){return Symbol.for(t)}var Md=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}(),Dd=new Md,Zd=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,a=[],i;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)a.push(s.value)}catch(o){i={error:o}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a},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))},Ld=function(){function t(){}return t.prototype.active=function(){return Dd},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],Zd(s),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}(),Fd=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,a=[],i;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)a.push(s.value)}catch(o){i={error:o}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return a},Vd=function(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,a;n<s;n++)(a||!(n in e))&&(a||(a=Array.prototype.slice.call(e,0,n)),a[n]=e[n]);return t.concat(a||Array.prototype.slice.call(e))},jn="context",zd=new Ld,Oi=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return hs(jn,e,ln.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,n){for(var s,a=[],i=3;i<arguments.length;i++)a[i-3]=arguments[i];return(s=this._getContextManager()).with.apply(s,Vd([e,r,n],Fd(a),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return Tr(jn)||zd},t.prototype.disable=function(){this._getContextManager().disable(),fs(jn,ln.instance())},t}(),ts;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(ts||(ts={}));var Pi="0000000000000000",Ri="00000000000000000000000000000000",Bd={traceId:Ri,spanId:Pi,traceFlags:ts.NONE},Xt=function(){function t(e){e===void 0&&(e=Bd),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}(),ms=Nd("OpenTelemetry Context Key SPAN");function gs(t){return t.getValue(ms)||void 0}function qd(){return gs(Oi.getInstance().active())}function ys(t,e){return t.setValue(ms,e)}function Hd(t){return t.deleteValue(ms)}function Jd(t,e){return ys(t,new Xt(e))}function ji(t){var e;return(e=gs(t))===null||e===void 0?void 0:e.spanContext()}var Wd=/^([0-9a-f]{32})$/i,Gd=/^[0-9a-f]{16}$/i;function Yd(t){return Wd.test(t)&&t!==Ri}function Kd(t){return Gd.test(t)&&t!==Pi}function Ni(t){return Yd(t.traceId)&&Kd(t.spanId)}function Xd(t){return new Xt(t)}var Nn=Oi.getInstance(),Mi=function(){function t(){}return t.prototype.startSpan=function(e,r,n){n===void 0&&(n=Nn.active());var s=!!(r!=null&&r.root);if(s)return new Xt;var a=n&&ji(n);return Qd(a)&&Ni(a)?new Xt(a):new Xt},t.prototype.startActiveSpan=function(e,r,n,s){var a,i,o;if(!(arguments.length<2)){arguments.length===2?o=r:arguments.length===3?(a=r,o=n):(a=r,i=n,o=s);var l=i??Nn.active(),c=this.startSpan(e,a,l),d=ys(l,c);return Nn.with(d,o,void 0,c)}},t}();function Qd(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var ep=new Mi,tp=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):ep},t}(),rp=function(){function t(){}return t.prototype.getTracer=function(e,r,n){return new Mi},t}(),np=new rp,la=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 tp(this,e,r,n)},t.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:np},t.prototype.setDelegate=function(e){this._delegate=e},t.prototype.getDelegateTracer=function(e,r,n){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(e,r,n)},t}(),cn;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(cn||(cn={}));var Mn="trace",sp=function(){function t(){this._proxyTracerProvider=new la,this.wrapSpanContext=Xd,this.isSpanContextValid=Ni,this.deleteSpan=Hd,this.getSpan=gs,this.getActiveSpan=qd,this.getSpanContext=ji,this.setSpan=ys,this.setSpanContext=Jd}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(e){var r=hs(Mn,this._proxyTracerProvider,ln.instance());return r&&this._proxyTracerProvider.setDelegate(e),r},t.prototype.getTracerProvider=function(){return Tr(Mn)||this._proxyTracerProvider},t.prototype.getTracer=function(e,r){return this.getTracerProvider().getTracer(e,r)},t.prototype.disable=function(){fs(Mn,ln.instance()),this._proxyTracerProvider=new la},t}(),ap=sp.getInstance(),ip=Object.defineProperty,vs=(t,e)=>{for(var r in e)ip(t,r,{get:e[r],enumerable:!0})};function _s(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 Di="AI_InvalidArgumentError",Zi=`vercel.ai.error.${Di}`,op=Symbol.for(Zi),Ui,L=class extends O{constructor({parameter:t,value:e,message:r}){super({name:Di,message:`Invalid argument for parameter ${t}: ${r}`}),this[Ui]=!0,this.parameter=t,this.value=e}static isInstance(t){return O.hasMarker(t,Zi)}};Ui=op;var Li="AI_RetryError",Fi=`vercel.ai.error.${Li}`,lp=Symbol.for(Fi),Vi,ca=class extends O{constructor({message:t,reason:e,errors:r}){super({name:Li,message:t}),this[Vi]=!0,this.reason=e,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return O.hasMarker(t,Fi)}};Vi=lp;var cp=({maxRetries:t=2,initialDelayInMs:e=2e3,backoffFactor:r=2}={})=>async n=>zi(n,{maxRetries:t,delayInMs:e,backoffFactor:r});async function zi(t,{maxRetries:e,delayInMs:r,backoffFactor:n},s=[]){try{return await t()}catch(a){if(Zr(a)||e===0)throw a;const i=Rl(a),o=[...s,a],l=o.length;if(l>e)throw new ca({message:`Failed after ${l} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:o});if(a instanceof Error&&$e.isInstance(a)&&a.isRetryable===!0&&l<=e)return await Pl(r),zi(t,{maxRetries:e,delayInMs:n*r,backoffFactor:n},o);throw l===1?a:new ca({message:`Failed after ${l} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:o})}}function up({maxRetries:t}){if(t!=null){if(!Number.isInteger(t))throw new L({parameter:"maxRetries",value:t,message:"maxRetries must be an integer"});if(t<0)throw new L({parameter:"maxRetries",value:t,message:"maxRetries must be >= 0"})}const e=t??2;return{maxRetries:e,retry:cp({maxRetries:e})}}function Dn({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 dp({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 pp={startSpan(){return jr},startActiveSpan(t,e,r,n){if(typeof e=="function")return e(jr);if(typeof r=="function")return r(jr);if(typeof n=="function")return n(jr)}},jr={spanContext(){return hp},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}},hp={traceId:"",spanId:"",traceFlags:0};function fp({isEnabled:t=!1,tracer:e}={}){return t?e||ap.getTracer("ai"):pp}function Zn({name:t,tracer:e,attributes:r,fn:n,endWhenDone:s=!0}){return e.startActiveSpan(t,{attributes:r},async a=>{try{const i=await n(a);return s&&a.end(),i}catch(i){try{i instanceof Error?(a.recordException({name:i.name,message:i.message,stack:i.stack}),a.setStatus({code:cn.ERROR,message:i.message})):a.setStatus({code:cn.ERROR})}finally{a.end()}throw i}})}function gt({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",qi=`vercel.ai.error.${Bi}`,mp=Symbol.for(qi),Hi,Fe=class extends O{constructor({message:t="No object generated.",cause:e,text:r,response:n,usage:s}){super({name:Bi,message:t,cause:e}),this[Hi]=!0,this.text=r,this.response=n,this.usage=s}static isInstance(t){return O.hasMarker(t,qi)}};Hi=mp;var Ji="AI_DownloadError",Wi=`vercel.ai.error.${Ji}`,gp=Symbol.for(Wi),Gi,Un=class extends O{constructor({url:t,statusCode:e,statusText:r,cause:n,message:s=n==null?`Failed to download ${t}: ${e} ${r}`:`Failed to download ${t}: ${n}`}){super({name:Ji,message:s,cause:n}),this[Gi]=!0,this.url=t,this.statusCode=e,this.statusText=r}static isInstance(t){return O.hasMarker(t,Wi)}};Gi=gp;async function yp({url:t,fetchImplementation:e=fetch}){var r;const n=t.toString();try{const s=await e(n);if(!s.ok)throw new Un({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 Un.isInstance(s)?s:new Un({url:n,cause:s})}}var vp=[{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 _p(t){for(const{bytes:e,mimeType:r}of vp)if(t.length>=e.length&&e.every((n,s)=>t[s]===n))return r}var Yi="AI_InvalidDataContentError",Ki=`vercel.ai.error.${Yi}`,bp=Symbol.for(Ki),Xi,ua=class extends O{constructor({content:t,cause:e,message:r=`Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof t}.`}){super({name:Yi,message:r,cause:e}),this[Xi]=!0,this.content=t}static isInstance(t){return O.hasMarker(t,Ki)}};Xi=bp;var Qi=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 wp(t){return typeof t=="string"?t:t instanceof ArrayBuffer?Hn(new Uint8Array(t)):Hn(t)}function un(t){if(t instanceof Uint8Array)return t;if(typeof t=="string")try{return Jl(t)}catch(e){throw new ua({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 ua({content:t})}function xp(t){try{return new TextDecoder().decode(t)}catch{throw new Error("Error decoding Uint8Array to text")}}var eo="AI_InvalidMessageRoleError",to=`vercel.ai.error.${eo}`,Ap=Symbol.for(to),ro,Sp=class extends O{constructor({role:t,message:e=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:eo,message:e}),this[ro]=!0,this.role=t}static isInstance(t){return O.hasMarker(t,to)}};ro=Ap;function kp(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 da({prompt:t,modelSupportsImageUrls:e=!0,modelSupportsUrl:r=()=>!1,downloadImplementation:n=yp}){const s=await Tp(t.messages,n,e,r);return[...t.system!=null?[{role:"system",content:t.system}]:[],...t.messages.map(a=>Ep(a,s))]}function Ep(t,e){var r,n,s,a,i,o;const l=t.role;switch(l){case"system":return{role:"system",content:t.content,providerMetadata:(r=t.providerOptions)!=null?r:t.experimental_providerMetadata};case"user":return typeof t.content=="string"?{role:"user",content:[{type:"text",text:t.content}],providerMetadata:(n=t.providerOptions)!=null?n:t.experimental_providerMetadata}:{role:"user",content:t.content.map(c=>$p(c,e)).filter(c=>c.type!=="text"||c.text!==""),providerMetadata:(s=t.providerOptions)!=null?s:t.experimental_providerMetadata};case"assistant":return typeof t.content=="string"?{role:"assistant",content:[{type:"text",text:t.content}],providerMetadata:(a=t.providerOptions)!=null?a:t.experimental_providerMetadata}:{role:"assistant",content:t.content.filter(c=>c.type!=="text"||c.text!=="").map(c=>{const{experimental_providerMetadata:d,providerOptions:p,...g}=c;return{...g,providerMetadata:p??d}}),providerMetadata:(i=t.providerOptions)!=null?i:t.experimental_providerMetadata};case"tool":return{role:"tool",content:t.content.map(c=>{var d;return{type:"tool-result",toolCallId:c.toolCallId,toolName:c.toolName,result:c.result,content:c.experimental_content,isError:c.isError,providerMetadata:(d=c.providerOptions)!=null?d:c.experimental_providerMetadata}}),providerMetadata:(o=t.providerOptions)!=null?o:t.experimental_providerMetadata};default:{const c=l;throw new Sp({role:c})}}}async function Tp(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 $p(t,e){var r,n,s,a;if(t.type==="text")return{type:"text",text:t.text,providerMetadata:(r=t.providerOptions)!=null?r:t.experimental_providerMetadata};let i=t.mimeType,o,l,c;const d=t.type;switch(d){case"image":o=t.image;break;case"file":o=t.data;break;default:throw new Error(`Unsupported part type: ${d}`)}try{l=typeof o=="string"?new URL(o):o}catch{l=o}if(l instanceof URL)if(l.protocol==="data:"){const{mimeType:p,base64Content:g}=kp(l.toString());if(p==null||g==null)throw new Error(`Invalid data URL format in part ${d}`);i=p,c=un(g)}else{const p=e[l.toString()];p?(c=p.data,i??(i=p.mimeType)):c=l}else c=un(l);switch(d){case"image":return c instanceof Uint8Array&&(i=(n=_p(c))!=null?n:i),{type:"image",image:c,mimeType:i,providerMetadata:(s=t.providerOptions)!=null?s:t.experimental_providerMetadata};case"file":{if(i==null)throw new Error("Mime type is missing for file part");return{type:"file",data:c instanceof Uint8Array?wp(c):c,mimeType:i,providerMetadata:(a=t.providerOptions)!=null?a:t.experimental_providerMetadata}}}}function pa({maxTokens:t,temperature:e,topP:r,topK:n,presencePenalty:s,frequencyPenalty:a,stopSequences:i,seed:o}){if(t!=null){if(!Number.isInteger(t))throw new L({parameter:"maxTokens",value:t,message:"maxTokens must be an integer"});if(t<1)throw new L({parameter:"maxTokens",value:t,message:"maxTokens must be >= 1"})}if(e!=null&&typeof e!="number")throw new L({parameter:"temperature",value:e,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new L({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new L({parameter:"topK",value:n,message:"topK must be a number"});if(s!=null&&typeof s!="number")throw new L({parameter:"presencePenalty",value:s,message:"presencePenalty must be a number"});if(a!=null&&typeof a!="number")throw new L({parameter:"frequencyPenalty",value:a,message:"frequencyPenalty must be a number"});if(o!=null&&!Number.isInteger(o))throw new L({parameter:"seed",value:o,message:"seed must be an integer"});return{maxTokens:t,temperature:e??0,topP:r,topK:n,presencePenalty:s,frequencyPenalty:a,stopSequences:i!=null&&i.length>0?i:void 0,seed:o}}function Ip(t){var e,r,n;const s=[];for(const a of t){let i;try{i=new URL(a.url)}catch{throw new Error(`Invalid URL: ${a.url}`)}switch(i.protocol){case"http:":case"https:":{if((e=a.contentType)!=null&&e.startsWith("image/"))s.push({type:"image",image:i});else{if(!a.contentType)throw new Error("If the attachment is not an image, it must specify a content type");s.push({type:"file",data:i,mimeType:a.contentType})}break}case"data:":{let o,l,c;try{[o,l]=a.url.split(","),c=o.split(";")[0].split(":")[1]}catch{throw new Error(`Error processing data URL: ${a.url}`)}if(c==null||l==null)throw new Error(`Invalid data URL format: ${a.url}`);if((r=a.contentType)!=null&&r.startsWith("image/"))s.push({type:"image",image:un(l)});else if((n=a.contentType)!=null&&n.startsWith("text/"))s.push({type:"text",text:xp(un(l))});else{if(!a.contentType)throw new Error("If the attachment is not an image or text, it must specify a content type");s.push({type:"file",data:l,mimeType:a.contentType})}break}default:throw new Error(`Unsupported URL protocol: ${i.protocol}`)}}return s}var no="AI_MessageConversionError",so=`vercel.ai.error.${no}`,Cp=Symbol.for(so),ao,Ln=class extends O{constructor({originalMessage:t,message:e}){super({name:no,message:e}),this[ao]=!0,this.originalMessage=t}static isInstance(t){return O.hasMarker(t,so)}};ao=Cp;function Op(t,e){var r,n;const s=(r=e==null?void 0:e.tools)!=null?r:{},a=[];for(let i=0;i<t.length;i++){const o=t[i],l=i===t.length-1,{role:c,content:d,experimental_attachments:p}=o;switch(c){case"system":{a.push({role:"system",content:d});break}case"user":{a.push({role:"user",content:p?[{type:"text",text:d},...Ip(p)]:d});break}case"assistant":{if(o.parts!=null){let y=function(){const k=[];for(const P of A)switch(P.type){case"text":k.push({type:"text",text:P.text});break;case"reasoning":{for(const R of P.details)switch(R.type){case"text":k.push({type:"reasoning",text:R.text,signature:R.signature});break;case"redacted":k.push({type:"redacted-reasoning",data:R.data});break}break}case"tool-invocation":k.push({type:"tool-call",toolCallId:P.toolInvocation.toolCallId,toolName:P.toolInvocation.toolName,args:P.toolInvocation.args});break;default:{const R=P;throw new Error(`Unsupported part: ${R}`)}}a.push({role:"assistant",content:k});const T=A.filter(P=>P.type==="tool-invocation").map(P=>P.toolInvocation);T.length>0&&a.push({role:"tool",content:T.map(P=>{if(!("result"in P))throw new Ln({originalMessage:o,message:"ToolInvocation must have a result: "+JSON.stringify(P)});const{toolCallId:R,toolName:B,result:I}=P,Y=s[B];return(Y==null?void 0:Y.experimental_toToolResultContent)!=null?{type:"tool-result",toolCallId:R,toolName:B,result:Y.experimental_toToolResultContent(I),experimental_content:Y.experimental_toToolResultContent(I)}:{type:"tool-result",toolCallId:R,toolName:B,result:I}})}),A=[],v=!1,m++},m=0,v=!1,A=[];for(const k of o.parts)switch(k.type){case"reasoning":A.push(k);break;case"text":{v&&y(),A.push(k);break}case"tool-invocation":{((n=k.toolInvocation.step)!=null?n:0)!==m&&y(),A.push(k),v=!0;break}}y();break}const g=o.toolInvocations;if(g==null||g.length===0){a.push({role:"assistant",content:d});break}const w=g.reduce((y,m)=>{var v;return Math.max(y,(v=m.step)!=null?v:0)},0);for(let y=0;y<=w;y++){const m=g.filter(v=>{var A;return((A=v.step)!=null?A:0)===y});m.length!==0&&(a.push({role:"assistant",content:[...l&&d&&y===0?[{type:"text",text:d}]:[],...m.map(({toolCallId:v,toolName:A,args:k})=>({type:"tool-call",toolCallId:v,toolName:A,args:k}))]}),a.push({role:"tool",content:m.map(v=>{if(!("result"in v))throw new Ln({originalMessage:o,message:"ToolInvocation must have a result: "+JSON.stringify(v)});const{toolCallId:A,toolName:k,result:T}=v,P=s[k];return(P==null?void 0:P.experimental_toToolResultContent)!=null?{type:"tool-result",toolCallId:A,toolName:k,result:P.experimental_toToolResultContent(T),experimental_content:P.experimental_toToolResultContent(T)}:{type:"tool-result",toolCallId:A,toolName:k,result:T}})}))}d&&!l&&a.push({role:"assistant",content:d});break}case"data":break;default:{const g=c;throw new Ln({originalMessage:o,message:`Unsupported role: ${g}`})}}}return a}function Pp(t){if(!Array.isArray(t))return"other";if(t.length===0)return"messages";const e=t.map(Rp);return e.some(r=>r==="has-ui-specific-parts")?"ui-messages":e.every(r=>r==="has-core-specific-parts"||r==="message")?"messages":"other"}function Rp(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 rs=u.lazy(()=>u.union([u.null(),u.string(),u.number(),u.boolean(),u.record(u.string(),rs),u.array(rs)])),q=u.record(u.string(),u.record(u.string(),rs)),jp=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()})])),io=u.object({type:u.literal("text"),text:u.string(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Np=u.object({type:u.literal("image"),image:u.union([Qi,u.instanceof(URL)]),mimeType:u.string().optional(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Mp=u.object({type:u.literal("file"),data:u.union([Qi,u.instanceof(URL)]),mimeType:u.string(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Dp=u.object({type:u.literal("reasoning"),text:u.string(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Zp=u.object({type:u.literal("redacted-reasoning"),data:u.string(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Up=u.object({type:u.literal("tool-call"),toolCallId:u.string(),toolName:u.string(),args:u.unknown(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Lp=u.object({type:u.literal("tool-result"),toolCallId:u.string(),toolName:u.string(),result:u.unknown(),content:jp.optional(),isError:u.boolean().optional(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Fp=u.object({role:u.literal("system"),content:u.string(),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Vp=u.object({role:u.literal("user"),content:u.union([u.string(),u.array(u.union([io,Np,Mp]))]),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),zp=u.object({role:u.literal("assistant"),content:u.union([u.string(),u.array(u.union([io,Dp,Zp,Up]))]),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),Bp=u.object({role:u.literal("tool"),content:u.array(Lp),providerOptions:q.optional(),experimental_providerMetadata:q.optional()}),qp=u.union([Fp,Vp,zp,Bp]);function ha({prompt:t,tools:e}){if(t.prompt==null&&t.messages==null)throw new et({prompt:t,message:"prompt or messages must be defined"});if(t.prompt!=null&&t.messages!=null)throw new et({prompt:t,message:"prompt and messages cannot be defined at the same time"});if(t.system!=null&&typeof t.system!="string")throw new et({prompt:t,message:"system must be a string"});if(t.prompt!=null){if(typeof t.prompt!="string")throw new et({prompt:t,message:"prompt must be a string"});return{type:"prompt",system:t.system,messages:[{role:"user",content:t.prompt}]}}if(t.messages!=null){const r=Pp(t.messages);if(r==="other")throw new et({prompt:t,message:"messages must be an array of CoreMessage or UIMessage"});const n=r==="ui-messages"?Op(t.messages,{tools:e}):t.messages,s=lt({value:n,schema:u.array(qp)});if(!s.success)throw new et({prompt:t,message:"messages must be an array of CoreMessage or UIMessage",cause:s.error});return{type:"messages",messages:n,system:t.system}}throw new Error("unreachable")}function yt({promptTokens:t,completionTokens:e}){return{promptTokens:t,completionTokens:e,totalTokens:t+e}}var Hp="JSON schema:",Jp="You MUST answer with a JSON object that matches the JSON schema above.",Wp="You MUST answer with JSON.";function ns({prompt:t,schema:e,schemaPrefix:r=e!=null?Hp:void 0,schemaSuffix:n=e!=null?Jp:Wp}){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 Gp(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 Yp={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 Fe({message:"No object generated: response did not match schema.",text:e.text,response:e.response,usage:e.usage})}:{success:!0,value:t}},createElementStream(){throw new G({functionality:"element streams in no-schema mode"})}},Kp=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 G({functionality:"element streams in object mode"})}}),Xp=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(!qn(n)||!Ws(n.elements))return{success:!1,error:new Ne({value:n,cause:"value must be an object that contains an array of elements"})};const l=n.elements,c=[];for(let g=0;g<l.length;g++){const w=l[g],y=lt({value:w,schema:t});if(!(g===l.length-1&&!i)){if(!y.success)return y;c.push(y.value)}}const d=(o=s==null?void 0:s.length)!=null?o:0;let p="";return a&&(p+="["),d>0&&(p+=","),p+=c.slice(d).map(g=>JSON.stringify(g)).join(","),i&&(p+="]"),{success:!0,value:{partial:c,textDelta:p}}},validateFinalResult(n){if(!qn(n)||!Ws(n.elements))return{success:!1,error:new Ne({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 Gp(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}`)}}}})))}}},Qp=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(!qn(e)||typeof e.result!="string")return{success:!1,error:new Ne({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 Ne({value:e,cause:"value must be a string in the enum"})}},validatePartialResult(){throw new G({functionality:"partial results in enum mode"})},createElementStream(){throw new G({functionality:"element streams in enum mode"})}});function eh({output:t,schema:e,enumValues:r}){switch(t){case"object":return Kp(es(e));case"array":return Xp(es(e));case"enum":return Qp(r);case"no-schema":return Yp;default:{const n=t;throw new Error(`Unsupported output: ${n}`)}}}function th({output:t,mode:e,schema:r,schemaName:n,schemaDescription:s,enumValues:a}){if(t!=null&&t!=="object"&&t!=="array"&&t!=="enum"&&t!=="no-schema")throw new L({parameter:"output",value:t,message:"Invalid output type."});if(t==="no-schema"){if(e==="auto"||e==="tool")throw new L({parameter:"mode",value:e,message:'Mode must be "json" for no-schema output.'});if(r!=null)throw new L({parameter:"schema",value:r,message:"Schema is not supported for no-schema output."});if(s!=null)throw new L({parameter:"schemaDescription",value:s,message:"Schema description is not supported for no-schema output."});if(n!=null)throw new L({parameter:"schemaName",value:n,message:"Schema name is not supported for no-schema output."});if(a!=null)throw new L({parameter:"enumValues",value:a,message:"Enum values are not supported for no-schema output."})}if(t==="object"){if(r==null)throw new L({parameter:"schema",value:r,message:"Schema is required for object output."});if(a!=null)throw new L({parameter:"enumValues",value:a,message:"Enum values are not supported for object output."})}if(t==="array"){if(r==null)throw new L({parameter:"schema",value:r,message:"Element schema is required for array output."});if(a!=null)throw new L({parameter:"enumValues",value:a,message:"Enum values are not supported for array output."})}if(t==="enum"){if(r!=null)throw new L({parameter:"schema",value:r,message:"Schema is not supported for enum output."});if(s!=null)throw new L({parameter:"schemaDescription",value:s,message:"Schema description is not supported for enum output."});if(n!=null)throw new L({parameter:"schemaName",value:n,message:"Schema name is not supported for enum output."});if(a==null)throw new L({parameter:"enumValues",value:a,message:"Enum values are required for enum output."});for(const i of a)if(typeof i!="string")throw new L({parameter:"enumValues",value:i,message:"Enum values must be strings."})}}var rh=ht({prefix:"aiobj",size:24});async function nh({model:t,enum:e,schema:r,schemaName:n,schemaDescription:s,mode:a,output:i="object",system:o,prompt:l,messages:c,maxRetries:d,abortSignal:p,headers:g,experimental_repairText:w,experimental_telemetry:y,experimental_providerMetadata:m,providerOptions:v=m,_internal:{generateId:A=rh,currentDate:k=()=>new Date}={},...T}){th({output:i,mode:a,schema:r,schemaName:n,schemaDescription:s,enumValues:e});const{maxRetries:P,retry:R}=up({maxRetries:d}),B=eh({output:i,schema:r,enumValues:e});B.type==="no-schema"&&a===void 0&&(a="json");const I=dp({model:t,telemetry:y,headers:g,settings:{...T,maxRetries:P}}),Y=fp(y);return Zn({name:"ai.generateObject",attributes:gt({telemetry:y,attributes:{...Dn({operationId:"ai.generateObject",telemetry:y}),...I,"ai.prompt":{input:()=>JSON.stringify({system:o,prompt:l,messages:c})},"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:Y,fn:async ft=>{var We,Ge,Ye,Oe;(a==="auto"||a==null)&&(a=t.defaultObjectGenerationMode);let ie,Ae,ce,mt,V,se,H,D,wn;switch(a){case"json":{const J=ha({prompt:{system:B.jsonSchema==null?ns({prompt:o}):t.supportsStructuredOutputs?o:ns({prompt:o,schema:B.jsonSchema}),prompt:l,messages:c},tools:void 0}),ue=await da({prompt:J,modelSupportsImageUrls:t.supportsImageUrls,modelSupportsUrl:(We=t.supportsUrl)==null?void 0:We.bind(t)}),X=await R(()=>Zn({name:"ai.generateObject.doGenerate",attributes:gt({telemetry:y,attributes:{...Dn({operationId:"ai.generateObject.doGenerate",telemetry:y}),...I,"ai.prompt.format":{input:()=>J.type},"ai.prompt.messages":{input:()=>JSON.stringify(ue)},"ai.settings.mode":a,"gen_ai.system":t.provider,"gen_ai.request.model":t.modelId,"gen_ai.request.frequency_penalty":T.frequencyPenalty,"gen_ai.request.max_tokens":T.maxTokens,"gen_ai.request.presence_penalty":T.presencePenalty,"gen_ai.request.temperature":T.temperature,"gen_ai.request.top_k":T.topK,"gen_ai.request.top_p":T.topP}}),tracer:Y,fn:async fe=>{var Or,Nt,Mt,Dt,Zt,Ut;const K=await t.doGenerate({mode:{type:"object-json",schema:B.jsonSchema,name:n,description:s},...pa(T),inputFormat:J.type,prompt:ue,providerMetadata:v,abortSignal:p,headers:g}),Se={id:(Nt=(Or=K.response)==null?void 0:Or.id)!=null?Nt:A(),timestamp:(Dt=(Mt=K.response)==null?void 0:Mt.timestamp)!=null?Dt:k(),modelId:(Ut=(Zt=K.response)==null?void 0:Zt.modelId)!=null?Ut:t.modelId};if(K.text===void 0)throw new Fe({message:"No object generated: the model did not return a response.",response:Se,usage:yt(K.usage)});return fe.setAttributes(gt({telemetry:y,attributes:{"ai.response.finishReason":K.finishReason,"ai.response.object":{output:()=>K.text},"ai.response.id":Se.id,"ai.response.model":Se.modelId,"ai.response.timestamp":Se.timestamp.toISOString(),"ai.usage.promptTokens":K.usage.promptTokens,"ai.usage.completionTokens":K.usage.completionTokens,"gen_ai.response.finish_reasons":[K.finishReason],"gen_ai.response.id":Se.id,"gen_ai.response.model":Se.modelId,"gen_ai.usage.prompt_tokens":K.usage.promptTokens,"gen_ai.usage.completion_tokens":K.usage.completionTokens}})),{...K,objectText:K.text,responseData:Se}}}));ie=X.objectText,Ae=X.finishReason,ce=X.usage,mt=X.warnings,V=X.rawResponse,D=X.logprobs,wn=X.providerMetadata,H=(Ge=X.request)!=null?Ge:{},se=X.responseData;break}case"tool":{const J=ha({prompt:{system:o,prompt:l,messages:c},tools:void 0}),ue=await da({prompt:J,modelSupportsImageUrls:t.supportsImageUrls,modelSupportsUrl:(Ye=t.supportsUrl)==null?void 0:Ye.bind(t)}),X=J.type,fe=await R(()=>Zn({name:"ai.generateObject.doGenerate",attributes:gt({telemetry:y,attributes:{...Dn({operationId:"ai.generateObject.doGenerate",telemetry:y}),...I,"ai.prompt.format":{input:()=>X},"ai.prompt.messages":{input:()=>JSON.stringify(ue)},"ai.settings.mode":a,"gen_ai.system":t.provider,"gen_ai.request.model":t.modelId,"gen_ai.request.frequency_penalty":T.frequencyPenalty,"gen_ai.request.max_tokens":T.maxTokens,"gen_ai.request.presence_penalty":T.presencePenalty,"gen_ai.request.temperature":T.temperature,"gen_ai.request.top_k":T.topK,"gen_ai.request.top_p":T.topP}}),tracer:Y,fn:async Or=>{var Nt,Mt,Dt,Zt,Ut,K,Se,ks;const de=await t.doGenerate({mode:{type:"object-tool",tool:{type:"function",name:n??"json",description:s??"Respond with a JSON object.",parameters:B.jsonSchema}},...pa(T),inputFormat:X,prompt:ue,providerMetadata:v,abortSignal:p,headers:g}),xn=(Mt=(Nt=de.toolCalls)==null?void 0:Nt[0])==null?void 0:Mt.args,Ke={id:(Zt=(Dt=de.response)==null?void 0:Dt.id)!=null?Zt:A(),timestamp:(K=(Ut=de.response)==null?void 0:Ut.timestamp)!=null?K:k(),modelId:(ks=(Se=de.response)==null?void 0:Se.modelId)!=null?ks:t.modelId};if(xn===void 0)throw new Fe({message:"No object generated: the tool was not called.",response:Ke,usage:yt(de.usage)});return Or.setAttributes(gt({telemetry:y,attributes:{"ai.response.finishReason":de.finishReason,"ai.response.object":{output:()=>xn},"ai.response.id":Ke.id,"ai.response.model":Ke.modelId,"ai.response.timestamp":Ke.timestamp.toISOString(),"ai.usage.promptTokens":de.usage.promptTokens,"ai.usage.completionTokens":de.usage.completionTokens,"gen_ai.response.finish_reasons":[de.finishReason],"gen_ai.response.id":Ke.id,"gen_ai.response.model":Ke.modelId,"gen_ai.usage.input_tokens":de.usage.promptTokens,"gen_ai.usage.output_tokens":de.usage.completionTokens}})),{...de,objectText:xn,responseData:Ke}}}));ie=fe.objectText,Ae=fe.finishReason,ce=fe.usage,mt=fe.warnings,V=fe.rawResponse,D=fe.logprobs,wn=fe.providerMetadata,H=(Oe=fe.request)!=null?Oe:{},se=fe.responseData;break}case void 0:throw new Error("Model does not have a default object generation mode.");default:{const J=a;throw new Error(`Unsupported mode: ${J}`)}}function Ss(J){const ue=It({text:J});if(!ue.success)throw new Fe({message:"No object generated: could not parse the response.",cause:ue.error,text:J,response:se,usage:yt(ce)});const X=B.validateFinalResult(ue.value,{text:J,response:se,usage:yt(ce)});if(!X.success)throw new Fe({message:"No object generated: response did not match schema.",cause:X.error,text:J,response:se,usage:yt(ce)});return X.value}let Cr;try{Cr=Ss(ie)}catch(J){if(w!=null&&Fe.isInstance(J)&&(ir.isInstance(J.cause)||Ne.isInstance(J.cause))){const ue=await w({text:ie,error:J.cause});if(ue===null)throw J;Cr=Ss(ue)}else throw J}return ft.setAttributes(gt({telemetry:y,attributes:{"ai.response.finishReason":Ae,"ai.response.object":{output:()=>JSON.stringify(Cr)},"ai.usage.promptTokens":ce.promptTokens,"ai.usage.completionTokens":ce.completionTokens}})),new sh({object:Cr,finishReason:Ae,usage:yt(ce),warnings:mt,request:H,response:{...se,headers:V==null?void 0:V.headers,body:V==null?void 0:V.body},logprobs:D,providerMetadata:wn})}})}var sh=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:_s(t==null?void 0:t.headers,{contentType:"application/json; charset=utf-8"})})}};ht({prefix:"aiobj",size:24});ht({prefix:"aitxt",size:24});ht({prefix:"msg",size:24});var ah={};vs(ah,{object:()=>oh,text:()=>ih});var ih=()=>({type:"text",responseFormat:()=>({type:"text"}),injectIntoSystemPrompt({system:t}){return t},parsePartial({text:t}){return{partial:t}},parseOutput({text:t}){return t}}),oh=({schema:t})=>{const e=es(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:ns({prompt:r,schema:e.jsonSchema})},parsePartial({text:r}){const n=id(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:n.value};default:{const s=n.state;throw new Error(`Unsupported parse state: ${s}`)}}},parseOutput({text:r},n){const s=It({text:r});if(!s.success)throw new Fe({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 Fe({message:"No object generated: response did not match schema.",cause:a.error,text:r,response:n.response,usage:n.usage});return a.value}}};function oo(t,e){const r=t.getReader(),n=e.getReader();let s,a,i=!1,o=!1;async function l(d){try{s==null&&(s=r.read());const p=await s;s=void 0,p.done?d.close():d.enqueue(p.value)}catch(p){d.error(p)}}async function c(d){try{a==null&&(a=n.read());const p=await a;a=void 0,p.done?d.close():d.enqueue(p.value)}catch(p){d.error(p)}}return new ReadableStream({async pull(d){try{if(i){await c(d);return}if(o){await l(d);return}s==null&&(s=r.read()),a==null&&(a=n.read());const{result:p,reader:g}=await Promise.race([s.then(w=>({result:w,reader:r})),a.then(w=>({result:w,reader:n}))]);p.done||d.enqueue(p.value),g===r?(s=void 0,p.done&&(await c(d),i=!0)):(a=void 0,p.done&&(o=!0,await l(d)))}catch(p){d.error(p)}},cancel(){r.cancel(),n.cancel()}})}ht({prefix:"aitxt",size:24});ht({prefix:"msg",size:24});var lh={};vs(lh,{mergeIntoDataStream:()=>dh,toDataStream:()=>ch,toDataStreamResponse:()=>uh});function lo(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 bs(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"&&fa((s=r.data)==null?void 0:s.chunk,n);return}fa(r,n)}})).pipeThrough(lo(e)).pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform:async(r,n)=>{n.enqueue(Ci("text",r))}}))}function ch(t,e){return bs(t,e).pipeThrough(new TextEncoderStream)}function uh(t,e){var r;const n=bs(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?oo(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:_s(a==null?void 0:a.headers,{contentType:"text/plain; charset=utf-8",dataStreamVersion:"v1"})})}function dh(t,e){e.dataStream.merge(bs(t,e.callbacks))}function fa(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 ph={};vs(ph,{mergeIntoDataStream:()=>mh,toDataStream:()=>hh,toDataStreamResponse:()=>fh});function ws(t,e){const r=gh();return Ol(t[Symbol.asyncIterator]()).pipeThrough(new TransformStream({async transform(n,s){s.enqueue(r(n.delta))}})).pipeThrough(lo(e)).pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform:async(n,s)=>{s.enqueue(Ci("text",n))}}))}function hh(t,e){return ws(t,e).pipeThrough(new TextEncoderStream)}function fh(t,e={}){var r;const{init:n,data:s,callbacks:a}=e,i=ws(t,a).pipeThrough(new TextEncoderStream),o=s?oo(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:_s(n==null?void 0:n.headers,{contentType:"text/plain; charset=utf-8",dataStreamVersion:"v1"})})}function mh(t,e){e.dataStream.merge(ws(t,e.callbacks))}function gh(){let t=!0;return e=>(t&&(e=e.trimStart(),e&&(t=!1)),e)}function yh(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 vh(t){if(!t)return Qn({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&&Object.keys(n.params_schema).length>0&&(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 Qn(e)}async function _h(t,e,r){var p;const n=JSON.stringify(e),s=n?`${n}
|
189
|
+
${t}`:t,a=(p=ae.get().settings)==null?void 0:p.openAIAPIToken,o=Si({apiKey:a,compatibility:"strict"})("gpt-4o-mini"),l=yh(r),c=vh(r),{object:d}=await nh({model:o,prompt:s,system:l,schema:c});return d}const bh={getModelResponse:_h};var wh=Object.defineProperty,xh=Object.getOwnPropertyDescriptor,xs=(t,e,r,n)=>{for(var s=n>1?void 0:n?xh(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&&wh(e,r,s),s};let dn=class extends re{constructor(){super(...arguments),this.openAIAPIToken="",this.promptState="idle"}createRenderRoot(){return this}connectedCallback(){ae.subscribe(t=>{var e;this.openAIAPIToken=(e=t.settings)==null?void 0:e.openAIAPIToken}),super.connectedCallback()}async onSubmit(t){t.preventDefault();const r=t.target.elements.namedItem("prompt"),n=r.value.trim();if(!n)return;const s=Jr.getRecentInteractions();this.promptState="thinking",r.value="";const a=await bh.getModelResponse(n,s,window.applet),i=[];a.text&&i.push({type:"text",content:a.text}),a.tools&&a.tools.length>0&&await Promise.all(a.tools.map(async o=>{await window.applet.sendAction(o.id,o.arguments),i.push({type:o.id,arguments:o.arguments}),window.applet.data&&i.push({type:"data",content:window.applet.data})})),Jr.addInteraction({input:{type:"command",text:n},outputs:i,timestamp:Date.now()}),this.promptState="idle",setTimeout(()=>document.getElementById("prompt").focus())}render(){return U`
|
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"?U`
|
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
|
+
`:F}
|
215
|
+
</form>
|
216
|
+
`}};xs([ee({type:String})],dn.prototype,"openAIAPIToken",2);xs([ee({type:String})],dn.prototype,"promptState",2);dn=xs([xe("app-prompt")],dn);var Ah=Object.defineProperty,Sh=Object.getOwnPropertyDescriptor,co=(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=(n?i(e,r,s):i(s))||s);return n&&s&&Ah(e,r,s),s};let ss=class extends re{constructor(){super(...arguments),this.interactions=[]}createRenderRoot(){return this}connectedCallback(){super.connectedCallback(),this.unsubscribe=Jr.subscribe(t=>{this.interactions=[...t]})}disconnectedCallback(){this.unsubscribe&&this.unsubscribe(),super.disconnectedCallback()}render(){const t=e=>Object.entries(e).filter(([r])=>r!=="type").map(([r,n])=>typeof n=="object"&&n!==null?`${r}: ${JSON.stringify(n)}`:`${r}: ${n}`).join(", ");return U`
|
217
|
+
<div class="history">
|
218
|
+
${this.interactions.length<=0?U`
|
219
|
+
<div class="action-output">
|
220
|
+
<span class="status-message">Enter a message below to interact</span>
|
221
|
+
</div>
|
222
|
+
`:U``}
|
223
|
+
${this.interactions.map(e=>{const r=e.input.type==="command"?U`
|
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
|
+
`:U``,n=e.outputs.filter(s=>s.type!=="data").map(s=>e.input.type==="command"?s.type==="text"?U`
|
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
|
+
`:U`
|
238
|
+
<div class="action-output">
|
239
|
+
<strong>Action: ${s.type}</strong>
|
240
|
+
<span>${t(s)}</span>
|
241
|
+
</div>
|
242
|
+
`:e.input.type==="action"?U`
|
243
|
+
<div class="action-output">
|
244
|
+
<strong>Action: ${e.input.text}</strong>
|
245
|
+
<span>{${t(s)}}</span>
|
246
|
+
</div>
|
247
|
+
`:U``);return U`${r}${n}`})}
|
248
|
+
</div>
|
249
|
+
`}};co([jo()],ss.prototype,"interactions",2);ss=co([xe("app-history")],ss);/**
|
250
|
+
* @license
|
251
|
+
* Copyright 2020 Google LLC
|
252
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
253
|
+
*/const kh=t=>t.strings===void 0;/**
|
254
|
+
* @license
|
255
|
+
* Copyright 2017 Google LLC
|
256
|
+
* SPDX-License-Identifier: BSD-3-Clause
|
257
|
+
*/const Qt=(t,e)=>{var n;const r=t._$AN;if(r===void 0)return!1;for(const s of r)(n=s._$AO)==null||n.call(s,e,!1),Qt(s,e);return!0},pn=t=>{let e,r;do{if((e=t._$AM)===void 0)break;r=e._$AN,r.delete(t),t=e}while((r==null?void 0:r.size)===0)},uo=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),$h(e)}};function Eh(t){this._$AN!==void 0?(pn(this),this._$AM=t,uo(this)):this._$AM=t}function Th(t,e=!1,r=0){const n=this._$AH,s=this._$AN;if(s!==void 0&&s.size!==0)if(e)if(Array.isArray(n))for(let a=r;a<n.length;a++)Qt(n[a],!1),pn(n[a]);else n!=null&&(Qt(n,!1),pn(n));else Qt(this,t)}const $h=t=>{t.type==ka.CHILD&&(t._$AP??(t._$AP=Th),t._$AQ??(t._$AQ=Eh))};class Ih extends Ta{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,r,n){super._$AT(e,r,n),uo(this),this.isConnected=e._$AU}_$AO(e,r=!0){var n,s;e!==this.isConnected&&(this.isConnected=e,e?(n=this.reconnected)==null||n.call(this):(s=this.disconnected)==null||s.call(this)),r&&(Qt(this,e),pn(this))}setValue(e){if(kh(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 ma=()=>new Ch;class Ch{}const Fn=new WeakMap,ga=Ea(class extends Ih{render(t){return F}update(t,[e]){var n;const r=e!==this.Y;return r&&this.Y!==void 0&&this.rt(void 0),(r||this.lt!==this.ct)&&(this.Y=e,this.ht=(n=t.options)==null?void 0:n.host,this.rt(this.ct=t.element)),F}rt(t){if(this.isConnected||(t=void 0),typeof this.Y=="function"){const e=this.ht??globalThis;let r=Fn.get(e);r===void 0&&(r=new WeakMap,Fn.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=Fn.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 Oh=Object.defineProperty,Ph=Object.getOwnPropertyDescriptor,As=(t,e,r,n)=>{for(var s=n>1?void 0:n?Ph(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&&Oh(e,r,s),s};let hn=class extends re{constructor(){super(...arguments),this.open=!1,this.openAIAPIToken="",this.dialogRef=ma(),this.formRef=ma()}createRenderRoot(){return this}connectedCallback(){ae.subscribe(t=>{var e;this.openAIAPIToken=(e=t.settings)==null?void 0:e.openAIAPIToken,this.open=t.settingsDialogOpen}),super.connectedCallback()}updated(t){var e,r;t.has("open")&&(this.open?(e=this.dialogRef.value)==null||e.showModal():(r=this.dialogRef.value)==null||r.close())}onSave(t){t.preventDefault();const n=t.target.elements.namedItem("openAIAPIToken").value,s=ae.get().settings;ae.update({settings:{openAIAPIToken:n,...s}}),this.onDismiss()}onClear(t){t.preventDefault();const e=ae.get().settings;delete e.openAIAPIToken,ae.update({settings:e})}onDismiss(){var t;(t=this.formRef.value)==null||t.reset(),ae.update({settingsDialogOpen:!1})}render(){return U`
|
262
|
+
<dialog ${ga(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
|
+
${ga(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?U`<button
|
304
|
+
class="clear-button"
|
305
|
+
?disabled=${!1}
|
306
|
+
@click="${this.onClear}"
|
307
|
+
>
|
308
|
+
Clear
|
309
|
+
</button>`:F}
|
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
|
+
`}};As([ee({type:Boolean})],hn.prototype,"open",2);As([ee({type:String})],hn.prototype,"openAIAPIToken",2);hn=As([xe("settings-dialog")],hn);var Rh=Object.getOwnPropertyDescriptor,jh=(t,e,r,n)=>{for(var s=n>1?void 0:n?Rh(e,r):e,a=t.length-1,i;a>=0;a--)(i=t[a])&&(s=i(s)||s);return s};let ya=class extends re{createRenderRoot(){return this}render(){return U`
|
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
|
+
`}};ya=jh([xe("app-root")],ya);
|