pipane 0.1.4 → 0.1.5
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/client/assets/index-BtDAXAo1.css +1 -0
- package/dist/client/assets/{index-D16nGmo3.js → index-CAQqlK61.js} +1 -1
- package/dist/client/assets/{index-Bf_69wyB.js → index-CJEeBmBj.js} +1 -1
- package/dist/client/assets/{index-CekVLaL6.js → index-DUEhKmPQ.js} +1 -1
- package/dist/client/assets/{index-Cp2vV6HJ.js → index-XEVKscP-.js} +77 -67
- package/dist/client/assets/{index-D14II7Hd.js → index-woI4agCy.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/server/server/process-pool.js +18 -1
- package/dist/server/server/ws-handler.js +138 -75
- package/dist/server/shared/jsonl-sync.js +73 -3
- package/package.json +1 -1
- package/dist/client/assets/index-CUE9pgq9.css +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CJEeBmBj.js","assets/_node-stub_stream-DDexIdn_.js","assets/index-woI4agCy.js","assets/index-CAQqlK61.js","assets/_node-stub_node_http-CROXaVGJ.js","assets/_node-stub_node_crypto-C_7epg3G.js","assets/_node-stub_node_path-DJCJiKv7.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var WL=n=>{throw TypeError(n)};var Tx=(n,e,t)=>e.has(n)||WL("Cannot "+t);var xr=(n,e,t)=>(Tx(n,e,"read from private field"),t?t.call(n):e.get(n)),Sl=(n,e,t)=>e.has(n)?WL("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),ts=(n,e,t,r)=>(Tx(n,e,"write to private field"),r?r.call(n,t):e.set(n,t),t),Tl=(n,e,t)=>(Tx(n,e,"access private method"),t);var zL=(n,e,t,r)=>({set _(i){ts(n,e,i,t)},get _(){return xr(n,e,r)}});(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const s of a.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function t(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function r(i){if(i.ep)return;i.ep=!0;const a=t(i);fetch(i.href,a)}})();const kE=globalThis,kO=kE.ShadowRoot&&(kE.ShadyCSS===void 0||kE.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,IO=Symbol(),qL=new WeakMap;let vH=class{constructor(e,t,r){if(this._$cssResult$=!0,r!==IO)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(kO&&e===void 0){const r=t!==void 0&&t.length===1;r&&(e=qL.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),r&&qL.set(t,e))}return e}toString(){return this.cssText}};const zae=n=>new vH(typeof n=="string"?n:n+"",void 0,IO),bH=(n,...e)=>{const t=n.length===1?n[0]:e.reduce((r,i,a)=>r+(s=>{if(s._$cssResult$===!0)return s.cssText;if(typeof s=="number")return s;throw Error("Value passed to 'css' function must be a 'css' function result: "+s+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+n[a+1],n[0]);return new vH(t,n,IO)},qae=(n,e)=>{if(kO)n.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const r=document.createElement("style"),i=kE.litNonce;i!==void 0&&r.setAttribute("nonce",i),r.textContent=t.cssText,n.appendChild(r)}},HL=kO?n=>n:n=>n instanceof CSSStyleSheet?(e=>{let t="";for(const r of e.cssRules)t+=r.cssText;return zae(t)})(n):n;const{is:Hae,defineProperty:Vae,getOwnPropertyDescriptor:Yae,getOwnPropertyNames:Kae,getOwnPropertySymbols:Qae,getPrototypeOf:jae}=Object,gT=globalThis,VL=gT.trustedTypes,Xae=VL?VL.emptyScript:"",Zae=gT.reactiveElementPolyfillSupport,cg=(n,e)=>n,_S={toAttribute(n,e){switch(e){case Boolean:n=n?Xae:null;break;case Object:case Array:n=n==null?n:JSON.stringify(n)}return n},fromAttribute(n,e){let t=n;switch(e){case Boolean:t=n!==null;break;case Number:t=n===null?null:Number(n);break;case Object:case Array:try{t=JSON.parse(n)}catch{t=null}}return t}},NO=(n,e)=>!Hae(n,e),YL={attribute:!0,type:String,converter:_S,reflect:!1,useDefault:!1,hasChanged:NO};Symbol.metadata??=Symbol("metadata"),gT.litPropertyMetadata??=new WeakMap;let Uh=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=YL){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const r=Symbol(),i=this.getPropertyDescriptor(e,r,t);i!==void 0&&Vae(this.prototype,e,i)}}static getPropertyDescriptor(e,t,r){const{get:i,set:a}=Yae(this.prototype,e)??{get(){return this[t]},set(s){this[t]=s}};return{get:i,set(s){const o=i?.call(this);a?.call(this,s),this.requestUpdate(e,o,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??YL}static _$Ei(){if(this.hasOwnProperty(cg("elementProperties")))return;const e=jae(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(cg("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(cg("properties"))){const t=this.properties,r=[...Kae(t),...Qae(t)];for(const i of r)this.createProperty(i,t[i])}const e=this[Symbol.metadata];if(e!==null){const t=litPropertyMetadata.get(e);if(t!==void 0)for(const[r,i]of t)this.elementProperties.set(r,i)}this._$Eh=new Map;for(const[t,r]of this.elementProperties){const i=this._$Eu(t,r);i!==void 0&&this._$Eh.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const r=new Set(e.flat(1/0).reverse());for(const i of r)t.unshift(HL(i))}else e!==void 0&&t.push(HL(e));return t}static _$Eu(e,t){const r=t.attribute;return r===!1?void 0:typeof r=="string"?r: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(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const r of t.keys())this.hasOwnProperty(r)&&(e.set(r,this[r]),delete this[r]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return qae(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,r){this._$AK(e,r)}_$ET(e,t){const r=this.constructor.elementProperties.get(e),i=this.constructor._$Eu(e,r);if(i!==void 0&&r.reflect===!0){const a=(r.converter?.toAttribute!==void 0?r.converter:_S).toAttribute(t,r.type);this._$Em=e,a==null?this.removeAttribute(i):this.setAttribute(i,a),this._$Em=null}}_$AK(e,t){const r=this.constructor,i=r._$Eh.get(e);if(i!==void 0&&this._$Em!==i){const a=r.getPropertyOptions(i),s=typeof a.converter=="function"?{fromAttribute:a.converter}:a.converter?.fromAttribute!==void 0?a.converter:_S;this._$Em=i;const o=s.fromAttribute(t,a.type);this[i]=o??this._$Ej?.get(i)??o,this._$Em=null}}requestUpdate(e,t,r,i=!1,a){if(e!==void 0){const s=this.constructor;if(i===!1&&(a=this[e]),r??=s.getPropertyOptions(e),!((r.hasChanged??NO)(a,t)||r.useDefault&&r.reflect&&a===this._$Ej?.get(e)&&!this.hasAttribute(s._$Eu(e,r))))return;this.C(e,t,r)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:r,reflect:i,wrapped:a},s){r&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,s??t??this[e]),a!==!0||s!==void 0)||(this._$AL.has(e)||(this.hasUpdated||r||(t=void 0),this._$AL.set(e,t)),i===!0&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[i,a]of this._$Ep)this[i]=a;this._$Ep=void 0}const r=this.constructor.elementProperties;if(r.size>0)for(const[i,a]of r){const{wrapped:s}=a,o=this[i];s!==!0||this._$AL.has(i)||o===void 0||this.C(i,void 0,a,o)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(r=>r.hostUpdate?.()),this.update(t)):this._$EM()}catch(r){throw e=!1,this._$EM(),r}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(e){}firstUpdated(e){}};Uh.elementStyles=[],Uh.shadowRootOptions={mode:"open"},Uh[cg("elementProperties")]=new Map,Uh[cg("finalized")]=new Map,Zae?.({ReactiveElement:Uh}),(gT.reactiveElementVersions??=[]).push("2.1.2");const DO=globalThis,KL=n=>n,vS=DO.trustedTypes,QL=vS?vS.createPolicy("lit-html",{createHTML:n=>n}):void 0,yH="$lit$",Ou=`lit$${Math.random().toFixed(9).slice(2)}$`,EH="?"+Ou,Jae=`<${EH}>`,Sp=document,zg=()=>Sp.createComment(""),qg=n=>n===null||typeof n!="object"&&typeof n!="function",OO=Array.isArray,ese=n=>OO(n)||typeof n?.[Symbol.iterator]=="function",wx=`[
|
|
3
3
|
\f\r]`,Gm=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,jL=/-->/g,XL=/>/g,Cd=RegExp(`>|${wx}(?:([^\\s"'>=/]+)(${wx}*=${wx}*(?:[^
|
|
4
4
|
\f\r"'\`<>=]|("|')|))|$)`,"g"),ZL=/'/g,JL=/"/g,SH=/^(?:script|style|textarea|title)$/i,tse=n=>(e,...t)=>({_$litType$:n,strings:e,values:t}),Q=tse(1),Vu=Symbol.for("lit-noChange"),sr=Symbol.for("lit-nothing"),e5=new WeakMap,np=Sp.createTreeWalker(Sp,129);function TH(n,e){if(!OO(n)||!n.hasOwnProperty("raw"))throw Error("invalid template strings array");return QL!==void 0?QL.createHTML(e):e}const nse=(n,e)=>{const t=n.length-1,r=[];let i,a=e===2?"<svg>":e===3?"<math>":"",s=Gm;for(let o=0;o<t;o++){const l=n[o];let c,u,d=-1,p=0;for(;p<l.length&&(s.lastIndex=p,u=s.exec(l),u!==null);)p=s.lastIndex,s===Gm?u[1]==="!--"?s=jL:u[1]!==void 0?s=XL:u[2]!==void 0?(SH.test(u[2])&&(i=RegExp("</"+u[2],"g")),s=Cd):u[3]!==void 0&&(s=Cd):s===Cd?u[0]===">"?(s=i??Gm,d=-1):u[1]===void 0?d=-2:(d=s.lastIndex-u[2].length,c=u[1],s=u[3]===void 0?Cd:u[3]==='"'?JL:ZL):s===JL||s===ZL?s=Cd:s===jL||s===XL?s=Gm:(s=Cd,i=void 0);const h=s===Cd&&n[o+1].startsWith("/>")?" ":"";a+=s===Gm?l+Jae:d>=0?(r.push(c),l.slice(0,d)+yH+l.slice(d)+Ou+h):l+Ou+(d===-2?o:h)}return[TH(n,a+(n[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),r]};let HI=class wH{constructor({strings:e,_$litType$:t},r){let i;this.parts=[];let a=0,s=0;const o=e.length-1,l=this.parts,[c,u]=nse(e,t);if(this.el=wH.createElement(c,r),np.currentNode=this.el.content,t===2||t===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(i=np.nextNode())!==null&&l.length<o;){if(i.nodeType===1){if(i.hasAttributes())for(const d of i.getAttributeNames())if(d.endsWith(yH)){const p=u[s++],h=i.getAttribute(d).split(Ou),f=/([.?@])?(.*)/.exec(p);l.push({type:1,index:a,name:f[2],strings:h,ctor:f[1]==="."?ise:f[1]==="?"?ase:f[1]==="@"?sse:vT}),i.removeAttribute(d)}else d.startsWith(Ou)&&(l.push({type:6,index:a}),i.removeAttribute(d));if(SH.test(i.tagName)){const d=i.textContent.split(Ou),p=d.length-1;if(p>0){i.textContent=vS?vS.emptyScript:"";for(let h=0;h<p;h++)i.append(d[h],zg()),np.nextNode(),l.push({type:2,index:++a});i.append(d[p],zg())}}}else if(i.nodeType===8)if(i.data===EH)l.push({type:2,index:a});else{let d=-1;for(;(d=i.data.indexOf(Ou,d+1))!==-1;)l.push({type:7,index:a}),d+=Ou.length-1}a++}}static createElement(e,t){const r=Sp.createElement("template");return r.innerHTML=e,r}};function Df(n,e,t=n,r){if(e===Vu)return e;let i=r!==void 0?t._$Co?.[r]:t._$Cl;const a=qg(e)?void 0:e._$litDirective$;return i?.constructor!==a&&(i?._$AO?.(!1),a===void 0?i=void 0:(i=new a(n),i._$AT(n,t,r)),r!==void 0?(t._$Co??=[])[r]=i:t._$Cl=i),i!==void 0&&(e=Df(n,i._$AS(n,e.values),i,r)),e}class rse{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:t},parts:r}=this._$AD,i=(e?.creationScope??Sp).importNode(t,!0);np.currentNode=i;let a=np.nextNode(),s=0,o=0,l=r[0];for(;l!==void 0;){if(s===l.index){let c;l.type===2?c=new _T(a,a.nextSibling,this,e):l.type===1?c=new l.ctor(a,l.name,l.strings,this,e):l.type===6&&(c=new ose(a,this,e)),this._$AV.push(c),l=r[++o]}s!==l?.index&&(a=np.nextNode(),s++)}return np.currentNode=Sp,i}p(e){let t=0;for(const r of this._$AV)r!==void 0&&(r.strings!==void 0?(r._$AI(e,r,t),t+=r.strings.length-2):r._$AI(e[t])),t++}}let _T=class xH{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,r,i){this.type=2,this._$AH=sr,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=r,this.options=i,this._$Cv=i?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=Df(this,e,t),qg(e)?e===sr||e==null||e===""?(this._$AH!==sr&&this._$AR(),this._$AH=sr):e!==this._$AH&&e!==Vu&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):ese(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!==sr&&qg(this._$AH)?this._$AA.nextSibling.data=e:this.T(Sp.createTextNode(e)),this._$AH=e}$(e){const{values:t,_$litType$:r}=e,i=typeof r=="number"?this._$AC(e):(r.el===void 0&&(r.el=HI.createElement(TH(r.h,r.h[0]),this.options)),r);if(this._$AH?._$AD===i)this._$AH.p(t);else{const a=new rse(i,this),s=a.u(this.options);a.p(t),this.T(s),this._$AH=a}}_$AC(e){let t=e5.get(e.strings);return t===void 0&&e5.set(e.strings,t=new HI(e)),t}k(e){OO(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let r,i=0;for(const a of e)i===t.length?t.push(r=new xH(this.O(zg()),this.O(zg()),this,this.options)):r=t[i],r._$AI(a),i++;i<t.length&&(this._$AR(r&&r._$AB.nextSibling,i),t.length=i)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){const r=KL(e).nextSibling;KL(e).remove(),e=r}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}};class vT{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,r,i,a){this.type=1,this._$AH=sr,this._$AN=void 0,this.element=e,this.name=t,this._$AM=i,this.options=a,r.length>2||r[0]!==""||r[1]!==""?(this._$AH=Array(r.length-1).fill(new String),this.strings=r):this._$AH=sr}_$AI(e,t=this,r,i){const a=this.strings;let s=!1;if(a===void 0)e=Df(this,e,t,0),s=!qg(e)||e!==this._$AH&&e!==Vu,s&&(this._$AH=e);else{const o=e;let l,c;for(e=a[0],l=0;l<a.length-1;l++)c=Df(this,o[r+l],t,l),c===Vu&&(c=this._$AH[l]),s||=!qg(c)||c!==this._$AH[l],c===sr?e=sr:e!==sr&&(e+=(c??"")+a[l+1]),this._$AH[l]=c}s&&!i&&this.j(e)}j(e){e===sr?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}let ise=class extends vT{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===sr?void 0:e}},ase=class extends vT{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==sr)}},sse=class extends vT{constructor(e,t,r,i,a){super(e,t,r,i,a),this.type=5}_$AI(e,t=this){if((e=Df(this,e,t,0)??sr)===Vu)return;const r=this._$AH,i=e===sr&&r!==sr||e.capture!==r.capture||e.once!==r.once||e.passive!==r.passive,a=e!==sr&&(r===sr||i);i&&this.element.removeEventListener(this.name,this,r),a&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}};class ose{constructor(e,t,r){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=r}get _$AU(){return this._$AM._$AU}_$AI(e){Df(this,e)}}const lse={I:_T},cse=DO.litHtmlPolyfillSupport;cse?.(HI,_T),(DO.litHtmlVersions??=[]).push("3.3.2");const ol=(n,e,t)=>{const r=t?.renderBefore??e;let i=r._$litPart$;if(i===void 0){const a=t?.renderBefore??null;r._$litPart$=i=new _T(e.insertBefore(zg(),a),a,void 0,t??{})}return i._$AI(n),i};const PO=globalThis;let vn=class extends Uh{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=ol(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Vu}};vn._$litElement$=!0,vn.finalized=!0,PO.litElementHydrateSupport?.({LitElement:vn});const use=PO.litElementPolyfillSupport;use?.({LitElement:vn});(PO.litElementVersions??=[]).push("4.2.2");const sn=n=>(e,t)=>{t!==void 0?t.addInitializer(()=>{customElements.define(n,e)}):customElements.define(n,e)};const dse={attribute:!0,type:String,converter:_S,reflect:!1,hasChanged:NO},pse=(n=dse,e,t)=>{const{kind:r,metadata:i}=t;let a=globalThis.litPropertyMetadata.get(i);if(a===void 0&&globalThis.litPropertyMetadata.set(i,a=new Map),r==="setter"&&((n=Object.create(n)).wrapped=!0),a.set(t.name,n),r==="accessor"){const{name:s}=t;return{set(o){const l=e.get.call(this);e.set.call(this,o),this.requestUpdate(s,l,n,!0,o)},init(o){return o!==void 0&&this.C(s,void 0,n,o),o}}}if(r==="setter"){const{name:s}=t;return function(o){const l=this[s];e.call(this,o),this.requestUpdate(s,l,n,!0,o)}}throw Error("Unsupported decorator location: "+r)};function Ge(n){return(e,t)=>typeof t=="object"?pse(n,e,t):((r,i,a)=>{const s=i.hasOwnProperty(a);return i.constructor.createProperty(a,r),s?Object.getOwnPropertyDescriptor(i,a):void 0})(n,e,t)}function lt(n){return Ge({...n,state:!0,attribute:!1})}const hse=(n,e,t)=>(t.configurable=!0,t.enumerable=!0,Reflect.decorate&&typeof e!="object"&&Object.defineProperty(n,e,t),t);function CH(n,e){return(t,r,i)=>{const a=s=>s.renderRoot?.querySelector(n)??null;return hse(t,r,{get(){return a(this)}})}}const fse={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round"};const AH=([n,e,t])=>{const r=document.createElementNS("http://www.w3.org/2000/svg",n);return Object.keys(e).forEach(i=>{r.setAttribute(i,String(e[i]))}),t?.length&&t.forEach(i=>{const a=AH(i);r.appendChild(a)}),r},mse=(n,e={})=>{const r={...fse,...e};return AH(["svg",r,n])};const Kd=[["path",{d:"M12 18V5"}],["path",{d:"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4"}],["path",{d:"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5"}],["path",{d:"M17.997 5.125a4 4 0 0 1 2.526 5.77"}],["path",{d:"M18 18a4 4 0 0 0 2-7.464"}],["path",{d:"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517"}],["path",{d:"M6 18a4 4 0 0 1-2-7.464"}],["path",{d:"M6.003 5.125a4 4 0 0 0-2.526 5.77"}]];const RH=[["path",{d:"M20 6 9 17l-5-5"}]];const kH=[["path",{d:"m6 9 6 6 6-6"}]];const ic=[["path",{d:"m9 18 6-6-6-6"}]];const gse=[["path",{d:"m18 15-6-6-6 6"}]];const _se=[["path",{d:"m7 6 5 5 5-5"}],["path",{d:"m7 13 5 5 5-5"}]];const vse=[["path",{d:"m7 15 5 5 5-5"}],["path",{d:"m7 9 5-5 5 5"}]];const Fu=[["path",{d:"m16 18 6-6-6-6"}],["path",{d:"m8 6-6 6 6 6"}]];const IH=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];const NH=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];const bse=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];const ns=[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4"}],["path",{d:"m5 12-3 3 3 3"}],["path",{d:"m9 18 3-3-3-3"}]];const yse=[["path",{d:"M12.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v9.5"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4"}],["path",{d:"M13.378 15.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z"}]];const Ese=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4"}],["path",{d:"M9 15h6"}],["path",{d:"M12 18v-6"}]];const Sse=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];const ug=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];const t5=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}],["circle",{cx:"9",cy:"9",r:"2"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]];const Tse=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];const Jc=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];const wse=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];const xse=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];const Cse=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];const Ase=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M15 3v18"}]];const Rse=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];const kse=[["path",{d:"M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z"}]];const Ise=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];const n5=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];const Nse=[["path",{d:"m15 15 6 6m-6-6v4.8m0-4.8h4.8"}],["path",{d:"M9 19.8V15m0 0H4.2M9 15l-6 6"}],["path",{d:"M15 4.2V9m0 0h4.8M15 9l6-6"}],["path",{d:"M9 4.2V9m0 0H4.2M9 9 3 3"}]];const Dse=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}],["path",{d:"M20 2v4"}],["path",{d:"M22 4h-4"}],["circle",{cx:"4",cy:"20",r:"2"}]];const IE=[["path",{d:"m7 11 2-2-2-2"}],["path",{d:"M11 13h4"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}]];const Ose=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];const Pse=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M12 2v2"}],["path",{d:"M12 20v2"}],["path",{d:"m4.93 4.93 1.41 1.41"}],["path",{d:"m17.66 17.66 1.41 1.41"}],["path",{d:"M2 12h2"}],["path",{d:"M20 12h2"}],["path",{d:"m6.34 17.66-1.41 1.41"}],["path",{d:"m19.07 4.93-1.41 1.41"}]];const MO=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];const{I:Mse}=lse,r5=n=>n,Lse=n=>n.strings===void 0,i5=()=>document.createComment(""),Wm=(n,e,t)=>{const r=n._$AA.parentNode,i=e===void 0?n._$AB:e._$AA;if(t===void 0){const a=r.insertBefore(i5(),i),s=r.insertBefore(i5(),i);t=new Mse(a,s,n,n.options)}else{const a=t._$AB.nextSibling,s=t._$AM,o=s!==n;if(o){let l;t._$AQ?.(n),t._$AM=n,t._$AP!==void 0&&(l=n._$AU)!==s._$AU&&t._$AP(l)}if(a!==i||o){let l=t._$AA;for(;l!==a;){const c=r5(l).nextSibling;r5(r).insertBefore(l,i),l=c}}}return t},Ad=(n,e,t=n)=>(n._$AI(e,t),n),Fse={},Use=(n,e=Fse)=>n._$AH=e,Bse=n=>n._$AH,xx=n=>{n._$AR(),n._$AA.remove()};const LO={CHILD:2},FO=n=>(...e)=>({_$litDirective$:n,values:e});let UO=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,r){this._$Ct=e,this._$AM=t,this._$Ci=r}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}};const dg=(n,e)=>{const t=n._$AN;if(t===void 0)return!1;for(const r of t)r._$AO?.(e,!1),dg(r,e);return!0},bS=n=>{let e,t;do{if((e=n._$AM)===void 0)break;t=e._$AN,t.delete(n),n=e}while(t?.size===0)},DH=n=>{for(let e;e=n._$AM;n=e){let t=e._$AN;if(t===void 0)e._$AN=t=new Set;else if(t.has(n))break;t.add(n),Wse(e)}};function $se(n){this._$AN!==void 0?(bS(this),this._$AM=n,DH(this)):this._$AM=n}function Gse(n,e=!1,t=0){const r=this._$AH,i=this._$AN;if(i!==void 0&&i.size!==0)if(e)if(Array.isArray(r))for(let a=t;a<r.length;a++)dg(r[a],!1),bS(r[a]);else r!=null&&(dg(r,!1),bS(r));else dg(this,n)}const Wse=n=>{n.type==LO.CHILD&&(n._$AP??=Gse,n._$AQ??=$se)};let zse=class extends UO{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,t,r){super._$AT(e,t,r),DH(this),this.isConnected=e._$AU}_$AO(e,t=!0){e!==this.isConnected&&(this.isConnected=e,e?this.reconnected?.():this.disconnected?.()),t&&(dg(this,e),bS(this))}setValue(e){if(Lse(this._$Ct))this._$Ct._$AI(e,this);else{const t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0)}}disconnected(){}reconnected(){}};const wa=()=>new qse;let qse=class{};const Cx=new WeakMap,ir=FO(class extends zse{render(n){return sr}update(n,[e]){const t=e!==this.G;return t&&this.G!==void 0&&this.rt(void 0),(t||this.lt!==this.ct)&&(this.G=e,this.ht=n.options?.host,this.rt(this.ct=n.element)),sr}rt(n){if(this.isConnected||(n=void 0),typeof this.G=="function"){const e=this.ht??globalThis;let t=Cx.get(e);t===void 0&&(t=new WeakMap,Cx.set(e,t)),t.get(this.G)!==void 0&&this.G.call(this.ht,void 0),t.set(this.G,n),n!==void 0&&this.G.call(this.ht,n)}else this.G.value=n}get lt(){return typeof this.G=="function"?Cx.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});function fl(n){return e=>n(e||{})}const br=fl(({variant:n="default",size:e="md",disabled:t=!1,type:r="button",loading:i=!1,onClick:a,title:s,className:o="",children:l})=>{const c={sm:"h-8 rounded-md px-3 text-xs",md:"h-9 rounded-md px-4 text-sm",lg:"h-10 rounded-md px-8 text-sm",icon:"size-8 rounded-md"},u={default:"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-xs hover:bg-destructive/90",outline:"border border-input bg-background text-foreground shadow-xs hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",ghost:"text-foreground hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},d="inline-flex items-center justify-center whitespace-nowrap text-sm font-medium transition-all cursor-pointer disabled:cursor-not-allowed disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",p=e==="icon"?"":"gap-2",h=e==="icon"?"":"has-[>svg]:px-2.5",f=u[n]||u.default,m=g=>{if(t||i){g.preventDefault(),g.stopPropagation();return}a?.(g)};return Q`
|
|
@@ -69,22 +69,22 @@ If you understand the risks and have appropriate mitigations in place,
|
|
|
69
69
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
70
70
|
|
|
71
71
|
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
72
|
-
`);this.baseURL=a.baseURL,this.timeout=a.timeout??IP.DEFAULT_TIMEOUT,this.logger=a.logger??console;const s="warn";this.logLevel=s,this.logLevel=x5(a.logLevel,"ClientOptions.logLevel",this)??x5(Ab("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??s,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??uhe(),gt(this,ME,phe),this._options=a,this.apiKey=typeof t=="string"?t:null,this.authToken=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.get("x-api-key")||e.get("authorization"))&&!(this.apiKey&&e.get("x-api-key"))&&!t.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!t.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return In([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return In([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return In([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([t,r])=>typeof r<"u").map(([t,r])=>{if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(r)}`;if(r===null)return`${encodeURIComponent(t)}=`;throw new Zt(`Cannot stringify type ${typeof r}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Bh}`}defaultIdempotencyKey(){return`stainless-node-retry-${kV()}`}makeStatusError(e,t,r,i){return Xs.generate(e,t,r,i)}buildURL(e,t,r){const i=!Fe(this,cN,"m",gY).call(this)&&r||this.baseURL,a=ehe(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return the(s)||(t={...s,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t)),a.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new Zt("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(i=>({method:e,path:t,...i})))}request(e,t=null){return new qV(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){const i=await e,a=i.maxRetries??this.maxRetries;t==null&&(t=a),await this.prepareOptions(i);const{req:s,url:o,timeout:l}=await this.buildRequest(i,{retryCount:a-t});await this.prepareRequest(s,{url:o,options:i});const c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(Da(this).debug(`[${c}] sending request`,Wd({retryOfRequestLogID:r,method:i.method,url:o,options:i,headers:s.headers})),i.signal?.aborted)throw new el;const p=new AbortController,h=await this.fetchWithTimeout(o,s,l,p).catch(nN),f=Date.now();if(h instanceof globalThis.Error){const _=`retrying, ${t} attempts remaining`;if(i.signal?.aborted)throw new el;const v=Xg(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return Da(this).info(`[${c}] connection ${v?"timed out":"failed"} - ${_}`),Da(this).debug(`[${c}] connection ${v?"timed out":"failed"} (${_})`,Wd({retryOfRequestLogID:r,url:o,durationMs:f-d,message:h.message})),this.retryRequest(i,t,r??c);throw Da(this).info(`[${c}] connection ${v?"timed out":"failed"} - error; no more retries left`),Da(this).debug(`[${c}] connection ${v?"timed out":"failed"} (error; no more retries left)`,Wd({retryOfRequestLogID:r,url:o,durationMs:f-d,message:h.message})),v?new IV:new zT({cause:h})}const m=[...h.headers.entries()].filter(([_])=>_==="request-id").map(([_,v])=>", "+_+": "+JSON.stringify(v)).join(""),g=`[${c}${u}${m}] ${s.method} ${o} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${f-d}ms`;if(!h.ok){const _=await this.shouldRetry(h);if(t&&_){const x=`retrying, ${t} attempts remaining`;return await dhe(h.body),Da(this).info(`${g} - ${x}`),Da(this).debug(`[${c}] response error (${x})`,Wd({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:f-d})),this.retryRequest(i,t,r??c,h.headers)}const v=_?"error; no more retries left":"error; not retryable";Da(this).info(`${g} - ${v}`);const b=await h.text().catch(x=>nN(x).message),E=BV(b),S=E?void 0:b;throw Da(this).debug(`[${c}] response error (${v})`,Wd({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,message:S,durationMs:Date.now()-d})),this.makeStatusError(h.status,E,S,h.headers)}return Da(this).info(g),Da(this).debug(`[${c}] response start`,Wd({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:f-d})),{response:h,options:i,controller:p,requestLogID:c,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(i=>({method:"get",path:e,...i})):{method:"get",path:e,...r})}requestAPIList(e,t){const r=this.makeRequest(t,null,void 0);return new Ehe(this,r,e)}async fetchWithTimeout(e,t,r,i){const{signal:a,method:s,...o}=t||{},l=this._makeAbort(i);a&&a.addEventListener("abort",l,{once:!0});const c=setTimeout(l,r),u=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,d={signal:i.signal,...u?{duplex:"half"}:{},method:"GET",...o};s&&(d.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(c)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r,i){let a;const s=i?.get("retry-after-ms");if(s){const l=parseFloat(s);Number.isNaN(l)||(a=l)}const o=i?.get("retry-after");if(o&&!a){const l=parseFloat(o);Number.isNaN(l)?a=Date.parse(o)-Date.now():a=l*1e3}if(!(a&&0<=a&&a<60*1e3)){const l=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,l)}return await ihe(a),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){const a=t-e,s=Math.min(.5*Math.pow(2,a),8),o=1-Math.random()*.25;return s*o*1e3}calculateNonstreamingTimeout(e,t){if(36e5*e/128e3>6e5||t!=null&&e>t)throw new Zt("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:t=0}={}){const r={...e},{method:i,path:a,query:s,defaultBaseURL:o}=r,l=this.buildURL(a,s,o);"timeout"in r&&rhe("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:c,body:u}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:i,bodyHeaders:c,retryCount:t});return{req:{method:i,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...r.fetchOptions??{}},url:l,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:i}){let a={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const s=In([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...che(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(s),s.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const r=In([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:GV(e)}:Fe(this,ME,"f").call(this,{body:e,headers:r})}}IP=mi,ME=new WeakMap,cN=new WeakSet,gY=function(){return this.baseURL!=="https://api.anthropic.com"};mi.Anthropic=IP;mi.HUMAN_PROMPT=zhe;mi.AI_PROMPT=qhe;mi.DEFAULT_TIMEOUT=6e5;mi.AnthropicError=Zt;mi.APIError=Xs;mi.APIConnectionError=zT;mi.APIConnectionTimeoutError=IV;mi.APIUserAbortError=el;mi.NotFoundError=PV;mi.ConflictError=MV;mi.RateLimitError=FV;mi.BadRequestError=NV;mi.AuthenticationError=DV;mi.InternalServerError=UV;mi.PermissionDeniedError=OV;mi.UnprocessableEntityError=LV;mi.toFile=Ahe;class pp extends mi{constructor(){super(...arguments),this.completions=new dY(this),this.messages=new kP(this),this.models=new mY(this),this.beta=new dm(this)}}pp.Completions=dY;pp.Messages=kP;pp.Models=mY;pp.Beta=dm;let Hhe=class{isComplete;extractResult;queue=[];waiting=[];done=!1;finalResultPromise;resolveFinalResult;constructor(e,t){this.isComplete=e,this.extractResult=t,this.finalResultPromise=new Promise(r=>{this.resolveFinalResult=r})}push(e){if(this.done)return;this.isComplete(e)&&(this.done=!0,this.resolveFinalResult(this.extractResult(e)));const t=this.waiting.shift();t?t({value:e,done:!1}):this.queue.push(e)}end(e){for(this.done=!0,e!==void 0&&this.resolveFinalResult(e);this.waiting.length>0;)this.waiting.shift()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.shift();else{if(this.done)return;{const e=await new Promise(t=>this.waiting.push(t));if(e.done)return;yield e.value}}}result(){return this.finalResultPromise}};class nu extends Hhe{constructor(){super(e=>e.type==="done"||e.type==="error",e=>{if(e.type==="done")return e.message;if(e.type==="error")return e.error;throw new Error("Unexpected event type for final result")})}}var Rb=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ah(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function Oot(n){if(Object.prototype.hasOwnProperty.call(n,"__esModule"))return n;var e=n.default;if(typeof e=="function"){var t=function r(){var i=!1;try{i=this instanceof r}catch{}return i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(r){var i=Object.getOwnPropertyDescriptor(n,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return n[r]}})}),t}var Nd={},Ux={},q5;function H5(){return q5||(q5=1,(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.Allow=n.ALL=n.COLLECTION=n.ATOM=n.SPECIAL=n.INF=n._INFINITY=n.INFINITY=n.NAN=n.BOOL=n.NULL=n.OBJ=n.ARR=n.NUM=n.STR=void 0,n.STR=1,n.NUM=2,n.ARR=4,n.OBJ=8,n.NULL=16,n.BOOL=32,n.NAN=64,n.INFINITY=128,n._INFINITY=256,n.INF=n.INFINITY|n._INFINITY,n.SPECIAL=n.NULL|n.BOOL|n.INF|n.NAN,n.ATOM=n.STR|n.NUM|n.SPECIAL,n.COLLECTION=n.ARR|n.OBJ,n.ALL=n.ATOM|n.COLLECTION,n.Allow={STR:n.STR,NUM:n.NUM,ARR:n.ARR,OBJ:n.OBJ,NULL:n.NULL,BOOL:n.BOOL,NAN:n.NAN,INFINITY:n.INFINITY,_INFINITY:n._INFINITY,INF:n.INF,SPECIAL:n.SPECIAL,ATOM:n.ATOM,COLLECTION:n.COLLECTION,ALL:n.ALL},n.default=n.Allow})(Ux)),Ux}var V5;function Vhe(){return V5||(V5=1,(function(n){var e=Nd&&Nd.__createBinding||(Object.create?(function(c,u,d,p){p===void 0&&(p=d);var h=Object.getOwnPropertyDescriptor(u,d);(!h||("get"in h?!u.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return u[d]}}),Object.defineProperty(c,p,h)}):(function(c,u,d,p){p===void 0&&(p=d),c[p]=u[d]})),t=Nd&&Nd.__exportStar||function(c,u){for(var d in c)d!=="default"&&!Object.prototype.hasOwnProperty.call(u,d)&&e(u,c,d)};Object.defineProperty(n,"__esModule",{value:!0}),n.Allow=n.MalformedJSON=n.PartialJSON=n.parseJSON=n.parse=void 0;const r=H5();Object.defineProperty(n,"Allow",{enumerable:!0,get:function(){return r.Allow}}),t(H5(),n);class i extends Error{}n.PartialJSON=i;class a extends Error{}n.MalformedJSON=a;function s(c,u=r.Allow.ALL){if(typeof c!="string")throw new TypeError(`expecting str, got ${typeof c}`);if(!c.trim())throw new Error(`${c} is empty`);return o(c.trim(),u)}n.parseJSON=s;const o=(c,u)=>{const d=c.length;let p=0;const h=S=>{throw new i(`${S} at position ${p}`)},f=S=>{throw new a(`${S} at position ${p}`)},m=()=>(E(),p>=d&&h("Unexpected end of input"),c[p]==='"'?g():c[p]==="{"?_():c[p]==="["?v():c.substring(p,p+4)==="null"||r.Allow.NULL&u&&d-p<4&&"null".startsWith(c.substring(p))?(p+=4,null):c.substring(p,p+4)==="true"||r.Allow.BOOL&u&&d-p<4&&"true".startsWith(c.substring(p))?(p+=4,!0):c.substring(p,p+5)==="false"||r.Allow.BOOL&u&&d-p<5&&"false".startsWith(c.substring(p))?(p+=5,!1):c.substring(p,p+8)==="Infinity"||r.Allow.INFINITY&u&&d-p<8&&"Infinity".startsWith(c.substring(p))?(p+=8,1/0):c.substring(p,p+9)==="-Infinity"||r.Allow._INFINITY&u&&1<d-p&&d-p<9&&"-Infinity".startsWith(c.substring(p))?(p+=9,-1/0):c.substring(p,p+3)==="NaN"||r.Allow.NAN&u&&d-p<3&&"NaN".startsWith(c.substring(p))?(p+=3,NaN):b()),g=()=>{const S=p;let w=!1;for(p++;p<d&&(c[p]!=='"'||w&&c[p-1]==="\\");)w=c[p]==="\\"?!w:!1,p++;if(c.charAt(p)=='"')try{return JSON.parse(c.substring(S,++p-Number(w)))}catch(x){f(String(x))}else if(r.Allow.STR&u)try{return JSON.parse(c.substring(S,p-Number(w))+'"')}catch{return JSON.parse(c.substring(S,c.lastIndexOf("\\"))+'"')}h("Unterminated string literal")},_=()=>{p++,E();const S={};try{for(;c[p]!=="}";){if(E(),p>=d&&r.Allow.OBJ&u)return S;const w=g();E(),p++;try{const x=m();S[w]=x}catch(x){if(r.Allow.OBJ&u)return S;throw x}E(),c[p]===","&&p++}}catch{if(r.Allow.OBJ&u)return S;h("Expected '}' at end of object")}return p++,S},v=()=>{p++;const S=[];try{for(;c[p]!=="]";)S.push(m()),E(),c[p]===","&&p++}catch{if(r.Allow.ARR&u)return S;h("Expected ']' at end of array")}return p++,S},b=()=>{if(p===0){c==="-"&&f("Not sure what '-' is");try{return JSON.parse(c)}catch(w){if(r.Allow.NUM&u)try{return JSON.parse(c.substring(0,c.lastIndexOf("e")))}catch{}f(String(w))}}const S=p;for(c[p]==="-"&&p++;c[p]&&",]}".indexOf(c[p])===-1;)p++;p==d&&!(r.Allow.NUM&u)&&h("Unterminated number literal");try{return JSON.parse(c.substring(S,p))}catch{c.substring(S,p)==="-"&&h("Not sure what '-' is");try{return JSON.parse(c.substring(S,c.lastIndexOf("e")))}catch(x){f(String(x))}}},E=()=>{for(;p<d&&`
|
|
72
|
+
`);this.baseURL=a.baseURL,this.timeout=a.timeout??IP.DEFAULT_TIMEOUT,this.logger=a.logger??console;const s="warn";this.logLevel=s,this.logLevel=x5(a.logLevel,"ClientOptions.logLevel",this)??x5(Ab("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??s,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??uhe(),gt(this,ME,phe),this._options=a,this.apiKey=typeof t=="string"?t:null,this.authToken=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.get("x-api-key")||e.get("authorization"))&&!(this.apiKey&&e.get("x-api-key"))&&!t.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!t.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return In([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return In([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return In([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([t,r])=>typeof r<"u").map(([t,r])=>{if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(r)}`;if(r===null)return`${encodeURIComponent(t)}=`;throw new Zt(`Cannot stringify type ${typeof r}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Bh}`}defaultIdempotencyKey(){return`stainless-node-retry-${kV()}`}makeStatusError(e,t,r,i){return Xs.generate(e,t,r,i)}buildURL(e,t,r){const i=!Fe(this,cN,"m",gY).call(this)&&r||this.baseURL,a=ehe(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return the(s)||(t={...s,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t)),a.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new Zt("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(i=>({method:e,path:t,...i})))}request(e,t=null){return new qV(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){const i=await e,a=i.maxRetries??this.maxRetries;t==null&&(t=a),await this.prepareOptions(i);const{req:s,url:o,timeout:l}=await this.buildRequest(i,{retryCount:a-t});await this.prepareRequest(s,{url:o,options:i});const c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(Da(this).debug(`[${c}] sending request`,Wd({retryOfRequestLogID:r,method:i.method,url:o,options:i,headers:s.headers})),i.signal?.aborted)throw new el;const p=new AbortController,h=await this.fetchWithTimeout(o,s,l,p).catch(nN),f=Date.now();if(h instanceof globalThis.Error){const _=`retrying, ${t} attempts remaining`;if(i.signal?.aborted)throw new el;const v=Xg(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return Da(this).info(`[${c}] connection ${v?"timed out":"failed"} - ${_}`),Da(this).debug(`[${c}] connection ${v?"timed out":"failed"} (${_})`,Wd({retryOfRequestLogID:r,url:o,durationMs:f-d,message:h.message})),this.retryRequest(i,t,r??c);throw Da(this).info(`[${c}] connection ${v?"timed out":"failed"} - error; no more retries left`),Da(this).debug(`[${c}] connection ${v?"timed out":"failed"} (error; no more retries left)`,Wd({retryOfRequestLogID:r,url:o,durationMs:f-d,message:h.message})),v?new IV:new zT({cause:h})}const m=[...h.headers.entries()].filter(([_])=>_==="request-id").map(([_,v])=>", "+_+": "+JSON.stringify(v)).join(""),g=`[${c}${u}${m}] ${s.method} ${o} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${f-d}ms`;if(!h.ok){const _=await this.shouldRetry(h);if(t&&_){const x=`retrying, ${t} attempts remaining`;return await dhe(h.body),Da(this).info(`${g} - ${x}`),Da(this).debug(`[${c}] response error (${x})`,Wd({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:f-d})),this.retryRequest(i,t,r??c,h.headers)}const v=_?"error; no more retries left":"error; not retryable";Da(this).info(`${g} - ${v}`);const b=await h.text().catch(x=>nN(x).message),E=BV(b),S=E?void 0:b;throw Da(this).debug(`[${c}] response error (${v})`,Wd({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,message:S,durationMs:Date.now()-d})),this.makeStatusError(h.status,E,S,h.headers)}return Da(this).info(g),Da(this).debug(`[${c}] response start`,Wd({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:f-d})),{response:h,options:i,controller:p,requestLogID:c,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(i=>({method:"get",path:e,...i})):{method:"get",path:e,...r})}requestAPIList(e,t){const r=this.makeRequest(t,null,void 0);return new Ehe(this,r,e)}async fetchWithTimeout(e,t,r,i){const{signal:a,method:s,...o}=t||{},l=this._makeAbort(i);a&&a.addEventListener("abort",l,{once:!0});const c=setTimeout(l,r),u=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,d={signal:i.signal,...u?{duplex:"half"}:{},method:"GET",...o};s&&(d.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(c)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r,i){let a;const s=i?.get("retry-after-ms");if(s){const l=parseFloat(s);Number.isNaN(l)||(a=l)}const o=i?.get("retry-after");if(o&&!a){const l=parseFloat(o);Number.isNaN(l)?a=Date.parse(o)-Date.now():a=l*1e3}if(!(a&&0<=a&&a<60*1e3)){const l=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,l)}return await ihe(a),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){const a=t-e,s=Math.min(.5*Math.pow(2,a),8),o=1-Math.random()*.25;return s*o*1e3}calculateNonstreamingTimeout(e,t){if(36e5*e/128e3>6e5||t!=null&&e>t)throw new Zt("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:t=0}={}){const r={...e},{method:i,path:a,query:s,defaultBaseURL:o}=r,l=this.buildURL(a,s,o);"timeout"in r&&rhe("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:c,body:u}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:i,bodyHeaders:c,retryCount:t});return{req:{method:i,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...r.fetchOptions??{}},url:l,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:i}){let a={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const s=In([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...che(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(s),s.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const r=In([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:GV(e)}:Fe(this,ME,"f").call(this,{body:e,headers:r})}}IP=mi,ME=new WeakMap,cN=new WeakSet,gY=function(){return this.baseURL!=="https://api.anthropic.com"};mi.Anthropic=IP;mi.HUMAN_PROMPT=zhe;mi.AI_PROMPT=qhe;mi.DEFAULT_TIMEOUT=6e5;mi.AnthropicError=Zt;mi.APIError=Xs;mi.APIConnectionError=zT;mi.APIConnectionTimeoutError=IV;mi.APIUserAbortError=el;mi.NotFoundError=PV;mi.ConflictError=MV;mi.RateLimitError=FV;mi.BadRequestError=NV;mi.AuthenticationError=DV;mi.InternalServerError=UV;mi.PermissionDeniedError=OV;mi.UnprocessableEntityError=LV;mi.toFile=Ahe;class pp extends mi{constructor(){super(...arguments),this.completions=new dY(this),this.messages=new kP(this),this.models=new mY(this),this.beta=new dm(this)}}pp.Completions=dY;pp.Messages=kP;pp.Models=mY;pp.Beta=dm;let Hhe=class{isComplete;extractResult;queue=[];waiting=[];done=!1;finalResultPromise;resolveFinalResult;constructor(e,t){this.isComplete=e,this.extractResult=t,this.finalResultPromise=new Promise(r=>{this.resolveFinalResult=r})}push(e){if(this.done)return;this.isComplete(e)&&(this.done=!0,this.resolveFinalResult(this.extractResult(e)));const t=this.waiting.shift();t?t({value:e,done:!1}):this.queue.push(e)}end(e){for(this.done=!0,e!==void 0&&this.resolveFinalResult(e);this.waiting.length>0;)this.waiting.shift()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.shift();else{if(this.done)return;{const e=await new Promise(t=>this.waiting.push(t));if(e.done)return;yield e.value}}}result(){return this.finalResultPromise}};class nu extends Hhe{constructor(){super(e=>e.type==="done"||e.type==="error",e=>{if(e.type==="done")return e.message;if(e.type==="error")return e.error;throw new Error("Unexpected event type for final result")})}}var Rb=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ah(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function Pot(n){if(Object.prototype.hasOwnProperty.call(n,"__esModule"))return n;var e=n.default;if(typeof e=="function"){var t=function r(){var i=!1;try{i=this instanceof r}catch{}return i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(r){var i=Object.getOwnPropertyDescriptor(n,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return n[r]}})}),t}var Nd={},Ux={},q5;function H5(){return q5||(q5=1,(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.Allow=n.ALL=n.COLLECTION=n.ATOM=n.SPECIAL=n.INF=n._INFINITY=n.INFINITY=n.NAN=n.BOOL=n.NULL=n.OBJ=n.ARR=n.NUM=n.STR=void 0,n.STR=1,n.NUM=2,n.ARR=4,n.OBJ=8,n.NULL=16,n.BOOL=32,n.NAN=64,n.INFINITY=128,n._INFINITY=256,n.INF=n.INFINITY|n._INFINITY,n.SPECIAL=n.NULL|n.BOOL|n.INF|n.NAN,n.ATOM=n.STR|n.NUM|n.SPECIAL,n.COLLECTION=n.ARR|n.OBJ,n.ALL=n.ATOM|n.COLLECTION,n.Allow={STR:n.STR,NUM:n.NUM,ARR:n.ARR,OBJ:n.OBJ,NULL:n.NULL,BOOL:n.BOOL,NAN:n.NAN,INFINITY:n.INFINITY,_INFINITY:n._INFINITY,INF:n.INF,SPECIAL:n.SPECIAL,ATOM:n.ATOM,COLLECTION:n.COLLECTION,ALL:n.ALL},n.default=n.Allow})(Ux)),Ux}var V5;function Vhe(){return V5||(V5=1,(function(n){var e=Nd&&Nd.__createBinding||(Object.create?(function(c,u,d,p){p===void 0&&(p=d);var h=Object.getOwnPropertyDescriptor(u,d);(!h||("get"in h?!u.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return u[d]}}),Object.defineProperty(c,p,h)}):(function(c,u,d,p){p===void 0&&(p=d),c[p]=u[d]})),t=Nd&&Nd.__exportStar||function(c,u){for(var d in c)d!=="default"&&!Object.prototype.hasOwnProperty.call(u,d)&&e(u,c,d)};Object.defineProperty(n,"__esModule",{value:!0}),n.Allow=n.MalformedJSON=n.PartialJSON=n.parseJSON=n.parse=void 0;const r=H5();Object.defineProperty(n,"Allow",{enumerable:!0,get:function(){return r.Allow}}),t(H5(),n);class i extends Error{}n.PartialJSON=i;class a extends Error{}n.MalformedJSON=a;function s(c,u=r.Allow.ALL){if(typeof c!="string")throw new TypeError(`expecting str, got ${typeof c}`);if(!c.trim())throw new Error(`${c} is empty`);return o(c.trim(),u)}n.parseJSON=s;const o=(c,u)=>{const d=c.length;let p=0;const h=S=>{throw new i(`${S} at position ${p}`)},f=S=>{throw new a(`${S} at position ${p}`)},m=()=>(E(),p>=d&&h("Unexpected end of input"),c[p]==='"'?g():c[p]==="{"?_():c[p]==="["?v():c.substring(p,p+4)==="null"||r.Allow.NULL&u&&d-p<4&&"null".startsWith(c.substring(p))?(p+=4,null):c.substring(p,p+4)==="true"||r.Allow.BOOL&u&&d-p<4&&"true".startsWith(c.substring(p))?(p+=4,!0):c.substring(p,p+5)==="false"||r.Allow.BOOL&u&&d-p<5&&"false".startsWith(c.substring(p))?(p+=5,!1):c.substring(p,p+8)==="Infinity"||r.Allow.INFINITY&u&&d-p<8&&"Infinity".startsWith(c.substring(p))?(p+=8,1/0):c.substring(p,p+9)==="-Infinity"||r.Allow._INFINITY&u&&1<d-p&&d-p<9&&"-Infinity".startsWith(c.substring(p))?(p+=9,-1/0):c.substring(p,p+3)==="NaN"||r.Allow.NAN&u&&d-p<3&&"NaN".startsWith(c.substring(p))?(p+=3,NaN):b()),g=()=>{const S=p;let w=!1;for(p++;p<d&&(c[p]!=='"'||w&&c[p-1]==="\\");)w=c[p]==="\\"?!w:!1,p++;if(c.charAt(p)=='"')try{return JSON.parse(c.substring(S,++p-Number(w)))}catch(x){f(String(x))}else if(r.Allow.STR&u)try{return JSON.parse(c.substring(S,p-Number(w))+'"')}catch{return JSON.parse(c.substring(S,c.lastIndexOf("\\"))+'"')}h("Unterminated string literal")},_=()=>{p++,E();const S={};try{for(;c[p]!=="}";){if(E(),p>=d&&r.Allow.OBJ&u)return S;const w=g();E(),p++;try{const x=m();S[w]=x}catch(x){if(r.Allow.OBJ&u)return S;throw x}E(),c[p]===","&&p++}}catch{if(r.Allow.OBJ&u)return S;h("Expected '}' at end of object")}return p++,S},v=()=>{p++;const S=[];try{for(;c[p]!=="]";)S.push(m()),E(),c[p]===","&&p++}catch{if(r.Allow.ARR&u)return S;h("Expected ']' at end of array")}return p++,S},b=()=>{if(p===0){c==="-"&&f("Not sure what '-' is");try{return JSON.parse(c)}catch(w){if(r.Allow.NUM&u)try{return JSON.parse(c.substring(0,c.lastIndexOf("e")))}catch{}f(String(w))}}const S=p;for(c[p]==="-"&&p++;c[p]&&",]}".indexOf(c[p])===-1;)p++;p==d&&!(r.Allow.NUM&u)&&h("Unterminated number literal");try{return JSON.parse(c.substring(S,p))}catch{c.substring(S,p)==="-"&&h("Not sure what '-' is");try{return JSON.parse(c.substring(S,c.lastIndexOf("e")))}catch(x){f(String(x))}}},E=()=>{for(;p<d&&`
|
|
73
73
|
\r `.includes(c[p]);)p++};return m()},l=s;n.parse=l})(Nd)),Nd}var Yhe=Vhe();function Hl(n){if(!n||n.trim()==="")return{};try{return JSON.parse(n)}catch{try{return Yhe.parse(n)??{}}catch{return{}}}}function _n(n){return n.replace(new RegExp("[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]","g"),"")}function Khe(n){const e=n[n.length-1];return e&&e.role!=="user"?"agent":"user"}function NP(n){return n.some(e=>e.role==="user"&&Array.isArray(e.content)?e.content.some(t=>t.type==="image"):e.role==="toolResult"&&Array.isArray(e.content)?e.content.some(t=>t.type==="image"):!1)}function DP(n){const e={"X-Initiator":Khe(n.messages),"Openai-Intent":"conversation-edits"};return n.hasImages&&(e["Copilot-Vision-Request"]="true"),e}function ru(n,e,t){return{temperature:e?.temperature,maxTokens:e?.maxTokens||Math.min(n.maxTokens,32e3),signal:e?.signal,apiKey:t||e?.apiKey,cacheRetention:e?.cacheRetention,sessionId:e?.sessionId,headers:e?.headers,onPayload:e?.onPayload,maxRetryDelayMs:e?.maxRetryDelayMs,metadata:e?.metadata}}function iu(n){return n==="xhigh"?"high":n}function _Y(n,e,t,r){const a={...{minimal:1024,low:2048,medium:8192,high:16384},...r},s=1024,o=iu(t);let l=a[o];const c=Math.min(n+l,e);return c<=l&&(l=Math.max(0,c-s)),{maxTokens:c,thinkingBudget:l}}function Sv(n,e,t){const r=new Map,i=n.map(l=>{if(l.role==="user")return l;if(l.role==="toolResult"){const c=r.get(l.toolCallId);return c&&c!==l.toolCallId?{...l,toolCallId:c}:l}if(l.role==="assistant"){const c=l,u=c.provider===e.provider&&c.api===e.api&&c.model===e.id,d=c.content.flatMap(p=>{if(p.type==="thinking")return p.redacted?u?p:[]:u&&p.thinkingSignature?p:!p.thinking||p.thinking.trim()===""?[]:u?p:{type:"text",text:p.thinking};if(p.type==="text")return u?p:{type:"text",text:p.text};if(p.type==="toolCall"){const h=p;let f=h;if(!u&&h.thoughtSignature&&(f={...h},delete f.thoughtSignature),!u&&t){const m=t(h.id,e,c);m!==h.id&&(r.set(h.id,m),f={...f,id:m})}return f}return p});return{...c,content:d}}return l}),a=[];let s=[],o=new Set;for(let l=0;l<i.length;l++){const c=i[l];if(c.role==="assistant"){if(s.length>0){for(const p of s)o.has(p.id)||a.push({role:"toolResult",toolCallId:p.id,toolName:p.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});s=[],o=new Set}const u=c;if(u.stopReason==="error"||u.stopReason==="aborted")continue;const d=u.content.filter(p=>p.type==="toolCall");d.length>0&&(s=d,o=new Set),a.push(c)}else if(c.role==="toolResult")o.add(c.toolCallId),a.push(c);else if(c.role==="user"){if(s.length>0){for(const u of s)o.has(u.id)||a.push({role:"toolResult",toolCallId:u.id,toolName:u.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});s=[],o=new Set}a.push(c)}else a.push(c)}return a}var Qhe={};function jhe(n){return n||(typeof process<"u"&&Qhe.PI_CACHE_RETENTION==="long"?"long":"short")}function Xhe(n,e){const t=jhe(e);if(t==="none")return{retention:t};const r=t==="long"&&n.includes("api.anthropic.com")?"1h":void 0;return{retention:t,cacheControl:{type:"ephemeral",...r&&{ttl:r}}}}const Zhe="2.1.62",Jhe=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"],efe=new Map(Jhe.map(n=>[n.toLowerCase(),n])),vY=n=>efe.get(n.toLowerCase())??n,tfe=(n,e)=>{if(e&&e.length>0){const t=n.toLowerCase(),r=e.find(i=>i.name.toLowerCase()===t);if(r)return r.name}return n};function Y5(n){if(!n.some(i=>i.type==="image"))return _n(n.map(i=>i.text).join(`
|
|
74
74
|
`));const t=n.map(i=>i.type==="text"?{type:"text",text:_n(i.text)}:{type:"image",source:{type:"base64",media_type:i.mimeType,data:i.data}});return t.some(i=>i.type==="text")||t.unshift({type:"text",text:"(see attached image)"}),t}function Bx(...n){const e={};for(const t of n)t&&Object.assign(e,t);return e}const LE=(n,e,t)=>{const r=new nu;return(async()=>{const i={role:"assistant",content:[],api:n.api,provider:n.provider,model:n.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{const a=t?.apiKey??Mo(n.provider)??"";let s;if(n.provider==="github-copilot"){const p=NP(e.messages);s=DP({messages:e.messages,hasImages:p})}const{client:o,isOAuthToken:l}=afe(n,a,t?.interleavedThinking??!0,t?.headers,s),c=sfe(n,e,l,t);t?.onPayload?.(c);const u=o.messages.stream({...c,stream:!0},{signal:t?.signal});r.push({type:"start",partial:i});const d=i.content;for await(const p of u)if(p.type==="message_start")i.usage.input=p.message.usage.input_tokens||0,i.usage.output=p.message.usage.output_tokens||0,i.usage.cacheRead=p.message.usage.cache_read_input_tokens||0,i.usage.cacheWrite=p.message.usage.cache_creation_input_tokens||0,i.usage.totalTokens=i.usage.input+i.usage.output+i.usage.cacheRead+i.usage.cacheWrite,Yu(n,i.usage);else if(p.type==="content_block_start"){if(p.content_block.type==="text"){const h={type:"text",text:"",index:p.index};i.content.push(h),r.push({type:"text_start",contentIndex:i.content.length-1,partial:i})}else if(p.content_block.type==="thinking"){const h={type:"thinking",thinking:"",thinkingSignature:"",index:p.index};i.content.push(h),r.push({type:"thinking_start",contentIndex:i.content.length-1,partial:i})}else if(p.content_block.type==="redacted_thinking"){const h={type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:p.content_block.data,redacted:!0,index:p.index};i.content.push(h),r.push({type:"thinking_start",contentIndex:i.content.length-1,partial:i})}else if(p.content_block.type==="tool_use"){const h={type:"toolCall",id:p.content_block.id,name:l?tfe(p.content_block.name,e.tools):p.content_block.name,arguments:p.content_block.input??{},partialJson:"",index:p.index};i.content.push(h),r.push({type:"toolcall_start",contentIndex:i.content.length-1,partial:i})}}else if(p.type==="content_block_delta"){if(p.delta.type==="text_delta"){const h=d.findIndex(m=>m.index===p.index),f=d[h];f&&f.type==="text"&&(f.text+=p.delta.text,r.push({type:"text_delta",contentIndex:h,delta:p.delta.text,partial:i}))}else if(p.delta.type==="thinking_delta"){const h=d.findIndex(m=>m.index===p.index),f=d[h];f&&f.type==="thinking"&&(f.thinking+=p.delta.thinking,r.push({type:"thinking_delta",contentIndex:h,delta:p.delta.thinking,partial:i}))}else if(p.delta.type==="input_json_delta"){const h=d.findIndex(m=>m.index===p.index),f=d[h];f&&f.type==="toolCall"&&(f.partialJson+=p.delta.partial_json,f.arguments=Hl(f.partialJson),r.push({type:"toolcall_delta",contentIndex:h,delta:p.delta.partial_json,partial:i}))}else if(p.delta.type==="signature_delta"){const h=d.findIndex(m=>m.index===p.index),f=d[h];f&&f.type==="thinking"&&(f.thinkingSignature=f.thinkingSignature||"",f.thinkingSignature+=p.delta.signature)}}else if(p.type==="content_block_stop"){const h=d.findIndex(m=>m.index===p.index),f=d[h];f&&(delete f.index,f.type==="text"?r.push({type:"text_end",contentIndex:h,content:f.text,partial:i}):f.type==="thinking"?r.push({type:"thinking_end",contentIndex:h,content:f.thinking,partial:i}):f.type==="toolCall"&&(f.arguments=Hl(f.partialJson),delete f.partialJson,r.push({type:"toolcall_end",contentIndex:h,toolCall:f,partial:i})))}else p.type==="message_delta"&&(p.delta.stop_reason&&(i.stopReason=ufe(p.delta.stop_reason)),p.usage.input_tokens!=null&&(i.usage.input=p.usage.input_tokens),p.usage.output_tokens!=null&&(i.usage.output=p.usage.output_tokens),p.usage.cache_read_input_tokens!=null&&(i.usage.cacheRead=p.usage.cache_read_input_tokens),p.usage.cache_creation_input_tokens!=null&&(i.usage.cacheWrite=p.usage.cache_creation_input_tokens),i.usage.totalTokens=i.usage.input+i.usage.output+i.usage.cacheRead+i.usage.cacheWrite,Yu(n,i.usage));if(t?.signal?.aborted)throw new Error("Request was aborted");if(i.stopReason==="aborted"||i.stopReason==="error")throw new Error("An unknown error occurred");r.push({type:"done",reason:i.stopReason,message:i}),r.end()}catch(a){for(const s of i.content)delete s.index;i.stopReason=t?.signal?.aborted?"aborted":"error",i.errorMessage=a instanceof Error?a.message:JSON.stringify(a),r.push({type:"error",reason:i.stopReason,error:i}),r.end()}})(),r};function OP(n){return n.includes("opus-4-6")||n.includes("opus-4.6")||n.includes("sonnet-4-6")||n.includes("sonnet-4.6")}function nfe(n,e){switch(n){case"minimal":return"low";case"low":return"low";case"medium":return"medium";case"high":return"high";case"xhigh":return e.includes("opus-4-6")||e.includes("opus-4.6")?"max":"high";default:return"high"}}const rfe=(n,e,t)=>{const r=t?.apiKey||Mo(n.provider);if(!r)throw new Error(`No API key for provider: ${n.provider}`);const i=ru(n,t,r);if(!t?.reasoning)return LE(n,e,{...i,thinkingEnabled:!1});if(OP(n.id)){const s=nfe(t.reasoning,n.id);return LE(n,e,{...i,thinkingEnabled:!0,effort:s})}const a=_Y(i.maxTokens||0,n.maxTokens,t.reasoning,t.thinkingBudgets);return LE(n,e,{...i,maxTokens:a.maxTokens,thinkingEnabled:!0,thinkingBudgetTokens:a.thinkingBudget})};function ife(n){return n.includes("sk-ant-oat")}function afe(n,e,t,r,i){const a=t&&!OP(n.id);if(n.provider==="github-copilot"){const l=[];return a&&l.push("interleaved-thinking-2025-05-14"),{client:new pp({apiKey:null,authToken:e,baseURL:n.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Bx({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...l.length>0?{"anthropic-beta":l.join(",")}:{}},n.headers,i,r)}),isOAuthToken:!1}}const s=["fine-grained-tool-streaming-2025-05-14"];return a&&s.push("interleaved-thinking-2025-05-14"),ife(e)?{client:new pp({apiKey:null,authToken:e,baseURL:n.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Bx({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","anthropic-beta":`claude-code-20250219,oauth-2025-04-20,${s.join(",")}`,"user-agent":`claude-cli/${Zhe}`,"x-app":"cli"},n.headers,r)}),isOAuthToken:!0}:{client:new pp({apiKey:e,baseURL:n.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Bx({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","anthropic-beta":s.join(",")},n.headers,r)}),isOAuthToken:!1}}function sfe(n,e,t,r){const{cacheControl:i}=Xhe(n.baseUrl,r?.cacheRetention),a={model:n.id,messages:lfe(e.messages,n,t,i),max_tokens:r?.maxTokens||n.maxTokens/3|0,stream:!0};if(t?(a.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...i?{cache_control:i}:{}}],e.systemPrompt&&a.system.push({type:"text",text:_n(e.systemPrompt),...i?{cache_control:i}:{}})):e.systemPrompt&&(a.system=[{type:"text",text:_n(e.systemPrompt),...i?{cache_control:i}:{}}]),r?.temperature!==void 0&&!r?.thinkingEnabled&&(a.temperature=r.temperature),e.tools&&(a.tools=cfe(e.tools,t)),r?.thinkingEnabled&&n.reasoning&&(OP(n.id)?(a.thinking={type:"adaptive"},r.effort&&(a.output_config={effort:r.effort})):a.thinking={type:"enabled",budget_tokens:r.thinkingBudgetTokens||1024}),r?.metadata){const s=r.metadata.user_id;typeof s=="string"&&(a.metadata={user_id:s})}return r?.toolChoice&&(typeof r.toolChoice=="string"?a.tool_choice={type:r.toolChoice}:a.tool_choice=r.toolChoice),a}function ofe(n){return n.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function lfe(n,e,t,r){const i=[],a=Sv(n,e,ofe);for(let s=0;s<a.length;s++){const o=a[s];if(o.role==="user")if(typeof o.content=="string")o.content.trim().length>0&&i.push({role:"user",content:_n(o.content)});else{const l=o.content.map(u=>u.type==="text"?{type:"text",text:_n(u.text)}:{type:"image",source:{type:"base64",media_type:u.mimeType,data:u.data}});let c=e?.input.includes("image")?l:l.filter(u=>u.type!=="image");if(c=c.filter(u=>u.type==="text"?u.text.trim().length>0:!0),c.length===0)continue;i.push({role:"user",content:c})}else if(o.role==="assistant"){const l=[];for(const c of o.content)if(c.type==="text"){if(c.text.trim().length===0)continue;l.push({type:"text",text:_n(c.text)})}else if(c.type==="thinking"){if(c.redacted){l.push({type:"redacted_thinking",data:c.thinkingSignature});continue}if(c.thinking.trim().length===0)continue;!c.thinkingSignature||c.thinkingSignature.trim().length===0?l.push({type:"text",text:_n(c.thinking)}):l.push({type:"thinking",thinking:_n(c.thinking),signature:c.thinkingSignature})}else c.type==="toolCall"&&l.push({type:"tool_use",id:c.id,name:t?vY(c.name):c.name,input:c.arguments??{}});if(l.length===0)continue;i.push({role:"assistant",content:l})}else if(o.role==="toolResult"){const l=[];l.push({type:"tool_result",tool_use_id:o.toolCallId,content:Y5(o.content),is_error:o.isError});let c=s+1;for(;c<a.length&&a[c].role==="toolResult";){const u=a[c];l.push({type:"tool_result",tool_use_id:u.toolCallId,content:Y5(u.content),is_error:u.isError}),c++}s=c-1,i.push({role:"user",content:l})}}if(r&&i.length>0){const s=i[i.length-1];if(s.role==="user")if(Array.isArray(s.content)){const o=s.content[s.content.length-1];o&&(o.type==="text"||o.type==="image"||o.type==="tool_result")&&(o.cache_control=r)}else typeof s.content=="string"&&(s.content=[{type:"text",text:s.content,cache_control:r}])}return i}function cfe(n,e){return n?n.map(t=>{const r=t.parameters;return{name:e?vY(t.name):t.name,description:t.description,input_schema:{type:"object",properties:r.properties||{},required:r.required||[]}}}):[]}function ufe(n){switch(n){case"end_turn":return"stop";case"max_tokens":return"length";case"tool_use":return"toolUse";case"refusal":return"error";case"pause_turn":return"stop";case"stop_sequence":return"stop";case"sensitive":return"error";default:throw new Error(`Unhandled stop reason: ${n}`)}}function zt(n,e,t,r,i){if(typeof e=="function"?n!==e||!0:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(n,t),t}function Le(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}let bY=function(){const{crypto:n}=globalThis;if(n?.randomUUID)return bY=n.randomUUID.bind(n),n.randomUUID();const e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function uN(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}const dN=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){const e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};class Ot extends Error{}let Es=class pN extends Ot{constructor(e,t,r,i){super(`${pN.makeMessage(e,t,r)}`),this.status=e,this.headers=i,this.requestID=i?.get("x-request-id"),this.error=t;const a=t;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,r){const i=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,t,r,i){if(!e||!i)return new HT({message:r,cause:dN(t)});const a=t?.error;return e===400?new yY(e,a,r,i):e===401?new EY(e,a,r,i):e===403?new SY(e,a,r,i):e===404?new TY(e,a,r,i):e===409?new wY(e,a,r,i):e===422?new xY(e,a,r,i):e===429?new CY(e,a,r,i):e>=500?new AY(e,a,r,i):new pN(e,a,r,i)}},So=class extends Es{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},HT=class extends Es{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},PP=class extends HT{constructor({message:e}={}){super({message:e??"Request timed out."})}},yY=class extends Es{},EY=class extends Es{},SY=class extends Es{},TY=class extends Es{},wY=class extends Es{},xY=class extends Es{},CY=class extends Es{},AY=class extends Es{};class RY extends Ot{constructor(){super("Could not parse response content as the length limit was reached")}}class kY extends Ot{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class M0 extends Error{constructor(e){super(e)}}const dfe=/^[a-z][a-z0-9+.-]*:/i,pfe=n=>dfe.test(n);let ls=n=>(ls=Array.isArray,ls(n)),K5=ls;function IY(n){return typeof n!="object"?{}:n??{}}function hfe(n){if(!n)return!0;for(const e in n)return!1;return!0}function ffe(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function FE(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}const mfe=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Ot(`${n} must be an integer`);if(e<0)throw new Ot(`${n} must be a positive integer`);return e},gfe=n=>{try{return JSON.parse(n)}catch{return}},Tv=n=>new Promise(e=>setTimeout(e,n)),Gh="6.10.0",_fe=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function vfe(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const bfe=()=>{const n=vfe();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Gh,"X-Stainless-OS":j5(Deno.build.os),"X-Stainless-Arch":Q5(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Gh,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Gh,"X-Stainless-OS":j5(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Q5(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=yfe();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Gh,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Gh,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function yfe(){if(typeof navigator>"u"||!navigator)return null;const n=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of n){const r=t.exec(navigator.userAgent);if(r){const i=r[1]||0,a=r[2]||0,s=r[3]||0;return{browser:e,version:`${i}.${a}.${s}`}}}return null}const Q5=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",j5=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown");let X5;const Efe=()=>X5??(X5=bfe());function Sfe(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function NY(...n){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...n)}function DY(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return NY({start(){},async pull(t){const{done:r,value:i}=await e.next();r?t.close():t.enqueue(i)},async cancel(){await e.return?.()}})}function OY(n){if(n[Symbol.asyncIterator])return n;const e=n.getReader();return{async next(){try{const t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Tfe(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}const e=n.getReader(),t=e.cancel();e.releaseLock(),await t}const wfe=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),PY="RFC3986",MY=n=>String(n),Z5={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:MY},xfe="RFC1738";let hN=(n,e)=>(hN=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),hN(n,e));const wl=(()=>{const n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})(),$x=1024,Cfe=(n,e,t,r,i)=>{if(n.length===0)return n;let a=n;if(typeof n=="symbol"?a=Symbol.prototype.toString.call(n):typeof n!="string"&&(a=String(n)),t==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let s="";for(let o=0;o<a.length;o+=$x){const l=a.length>=$x?a.slice(o,o+$x):a,c=[];for(let u=0;u<l.length;++u){let d=l.charCodeAt(u);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||i===xfe&&(d===40||d===41)){c[c.length]=l.charAt(u);continue}if(d<128){c[c.length]=wl[d];continue}if(d<2048){c[c.length]=wl[192|d>>6]+wl[128|d&63];continue}if(d<55296||d>=57344){c[c.length]=wl[224|d>>12]+wl[128|d>>6&63]+wl[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|l.charCodeAt(u)&1023),c[c.length]=wl[240|d>>18]+wl[128|d>>12&63]+wl[128|d>>6&63]+wl[128|d&63]}s+=c.join("")}return s};function Afe(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function J5(n,e){if(ls(n)){const t=[];for(let r=0;r<n.length;r+=1)t.push(e(n[r]));return t}return e(n)}const LY={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},FY=function(n,e){Array.prototype.push.apply(n,ls(e)?e:[e])};let eF;const wi={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Cfe,encodeValuesOnly:!1,format:PY,formatter:MY,indices:!1,serializeDate(n){return(eF??(eF=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function Rfe(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}const Gx={};function UY(n,e,t,r,i,a,s,o,l,c,u,d,p,h,f,m,g,_){let v=n,b=_,E=0,S=!1;for(;(b=b.get(Gx))!==void 0&&!S;){const D=b.get(n);if(E+=1,typeof D<"u"){if(D===E)throw new RangeError("Cyclic object value");S=!0}typeof b.get(Gx)>"u"&&(E=0)}if(typeof c=="function"?v=c(e,v):v instanceof Date?v=p?.(v):t==="comma"&&ls(v)&&(v=J5(v,function(D){return D instanceof Date?p?.(D):D})),v===null){if(a)return l&&!m?l(e,wi.encoder,g,"key",h):e;v=""}if(Rfe(v)||Afe(v)){if(l){const D=m?e:l(e,wi.encoder,g,"key",h);return[f?.(D)+"="+f?.(l(v,wi.encoder,g,"value",h))]}return[f?.(e)+"="+f?.(String(v))]}const w=[];if(typeof v>"u")return w;let x;if(t==="comma"&&ls(v))m&&l&&(v=J5(v,l)),x=[{value:v.length>0?v.join(",")||null:void 0}];else if(ls(c))x=c;else{const D=Object.keys(v);x=u?D.sort(u):D}const A=o?String(e).replace(/\./g,"%2E"):String(e),C=r&&ls(v)&&v.length===1?A+"[]":A;if(i&&ls(v)&&v.length===0)return C+"[]";for(let D=0;D<x.length;++D){const N=x[D],O=typeof N=="object"&&typeof N.value<"u"?N.value:v[N];if(s&&O===null)continue;const F=d&&o?N.replace(/\./g,"%2E"):N,k=ls(v)?typeof t=="function"?t(C,F):C:C+(d?"."+F:"["+F+"]");_.set(n,E);const V=new WeakMap;V.set(Gx,_),FY(w,UY(O,k,t,r,i,a,s,o,t==="comma"&&m&&ls(v)?null:l,c,u,d,p,h,f,m,g,V))}return w}function kfe(n=wi){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=n.charset||wi.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=PY;if(typeof n.format<"u"){if(!hN(Z5,n.format))throw new TypeError("Unknown format option provided.");t=n.format}const r=Z5[t];let i=wi.filter;(typeof n.filter=="function"||ls(n.filter))&&(i=n.filter);let a;if(n.arrayFormat&&n.arrayFormat in LY?a=n.arrayFormat:"indices"in n?a=n.indices?"indices":"repeat":a=wi.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const s=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:wi.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:wi.addQueryPrefix,allowDots:s,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:wi.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:wi.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?wi.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:wi.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:wi.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:wi.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:wi.encodeValuesOnly,filter:i,format:t,formatter:r,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:wi.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:wi.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:wi.strictNullHandling}}function Ife(n,e={}){let t=n;const r=kfe(e);let i,a;typeof r.filter=="function"?(a=r.filter,t=a("",t)):ls(r.filter)&&(a=r.filter,i=a);const s=[];if(typeof t!="object"||t===null)return"";const o=LY[r.arrayFormat],l=o==="comma"&&r.commaRoundTrip;i||(i=Object.keys(t)),r.sort&&i.sort(r.sort);const c=new WeakMap;for(let p=0;p<i.length;++p){const h=i[p];r.skipNulls&&t[h]===null||FY(s,UY(t[h],h,o,l,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,c))}const u=s.join(r.delimiter);let d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}function Nfe(n){let e=0;for(const i of n)e+=i.length;const t=new Uint8Array(e);let r=0;for(const i of n)t.set(i,r),r+=i.length;return t}let tF;function MP(n){let e;return(tF??(e=new globalThis.TextEncoder,tF=e.encode.bind(e)))(n)}let nF;function rF(n){let e;return(nF??(e=new globalThis.TextDecoder,nF=e.decode.bind(e)))(n)}var Ds,Os;let VT=class{constructor(){Ds.set(this,void 0),Os.set(this,void 0),zt(this,Ds,new Uint8Array),zt(this,Os,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?MP(e):e;zt(this,Ds,Nfe([Le(this,Ds,"f"),t]));const r=[];let i;for(;(i=Dfe(Le(this,Ds,"f"),Le(this,Os,"f")))!=null;){if(i.carriage&&Le(this,Os,"f")==null){zt(this,Os,i.index);continue}if(Le(this,Os,"f")!=null&&(i.index!==Le(this,Os,"f")+1||i.carriage)){r.push(rF(Le(this,Ds,"f").subarray(0,Le(this,Os,"f")-1))),zt(this,Ds,Le(this,Ds,"f").subarray(Le(this,Os,"f"))),zt(this,Os,null);continue}const a=Le(this,Os,"f")!==null?i.preceding-1:i.preceding,s=rF(Le(this,Ds,"f").subarray(0,a));r.push(s),zt(this,Ds,Le(this,Ds,"f").subarray(i.index)),zt(this,Os,null)}return r}flush(){return Le(this,Ds,"f").length?this.decode(`
|
|
75
75
|
`):[]}};Ds=new WeakMap,Os=new WeakMap;VT.NEWLINE_CHARS=new Set([`
|
|
76
76
|
`,"\r"]);VT.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Dfe(n,e){for(let i=e??0;i<n.length;i++){if(n[i]===10)return{preceding:i,index:i+1,carriage:!1};if(n[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function Ofe(n){for(let r=0;r<n.length-1;r++){if(n[r]===10&&n[r+1]===10||n[r]===13&&n[r+1]===13)return r+2;if(n[r]===13&&n[r+1]===10&&r+3<n.length&&n[r+2]===13&&n[r+3]===10)return r+4}return-1}const NS={off:0,error:200,warn:300,info:400,debug:500},iF=(n,e,t)=>{if(n){if(ffe(NS,n))return n;Xi(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(NS))}`)}};function L0(){}function kb(n,e,t){return!e||NS[n]>NS[t]?L0:e[n].bind(e)}const Pfe={error:L0,warn:L0,info:L0,debug:L0};let aF=new WeakMap;function Xi(n){const e=n.logger,t=n.logLevel??"off";if(!e)return Pfe;const r=aF.get(e);if(r&&r[0]===t)return r[1];const i={error:kb("error",e,t),warn:kb("warn",e,t),info:kb("info",e,t),debug:kb("debug",e,t)};return aF.set(e,[t,i]),i}const zd=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);var l0;let Jg=class F0{constructor(e,t,r){this.iterator=e,l0.set(this,void 0),this.controller=t,zt(this,l0,r)}static fromSSEResponse(e,t,r){let i=!1;const a=r?Xi(r):console;async function*s(){if(i)throw new Ot("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let o=!1;try{for await(const l of Mfe(e,t))if(!o){if(l.data.startsWith("[DONE]")){o=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let c;try{c=JSON.parse(l.data)}catch(u){throw a.error("Could not parse message into JSON:",l.data),a.error("From chunk:",l.raw),u}if(c&&c.error)throw new Es(void 0,c.error,void 0,e.headers);yield c}else{let c;try{c=JSON.parse(l.data)}catch(u){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),u}if(l.event=="error")throw new Es(void 0,c.error,c.message,void 0);yield{event:l.event,data:c}}}o=!0}catch(l){if(uN(l))return;throw l}finally{o||t.abort()}}return new F0(s,t,r)}static fromReadableStream(e,t,r){let i=!1;async function*a(){const o=new VT,l=OY(e);for await(const c of l)for(const u of o.decode(c))yield u;for(const c of o.flush())yield c}async function*s(){if(i)throw new Ot("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let o=!1;try{for await(const l of a())o||l&&(yield JSON.parse(l));o=!0}catch(l){if(uN(l))return;throw l}finally{o||t.abort()}}return new F0(s,t,r)}[(l0=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],r=this.iterator(),i=a=>({next:()=>{if(a.length===0){const s=r.next();e.push(s),t.push(s)}return a.shift()}});return[new F0(()=>i(e),this.controller,Le(this,l0,"f")),new F0(()=>i(t),this.controller,Le(this,l0,"f"))]}toReadableStream(){const e=this;let t;return NY({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{const{value:i,done:a}=await t.next();if(a)return r.close();const s=MP(JSON.stringify(i)+`
|
|
77
77
|
`);r.enqueue(s)}catch(i){r.error(i)}},async cancel(){await t.return?.()}})}};async function*Mfe(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Ot("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new Ot("Attempted to iterate over a response with no body");const t=new Ffe,r=new VT,i=OY(n.body);for await(const a of Lfe(i))for(const s of r.decode(a)){const o=t.decode(s);o&&(yield o)}for(const a of r.flush()){const s=t.decode(a);s&&(yield s)}}async function*Lfe(n){let e=new Uint8Array;for await(const t of n){if(t==null)continue;const r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?MP(t):t;let i=new Uint8Array(e.length+r.length);i.set(e),i.set(r,e.length),e=i;let a;for(;(a=Ofe(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}let Ffe=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const a={event:this.event,data:this.data.join(`
|
|
78
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,i]=Ufe(e,":");return i.startsWith(" ")&&(i=i.substring(1)),t==="event"?this.event=i:t==="data"&&this.data.push(i),null}};function Ufe(n,e){const t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function BY(n,e){const{response:t,requestLogID:r,retryOfRequestLogID:i,startTime:a}=e,s=await(async()=>{if(e.options.stream)return Xi(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n):Jg.fromSSEResponse(t,e.controller,n);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const l=t.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){const d=await t.json();return $Y(d,t)}return await t.text()})();return Xi(n).debug(`[${r}] response parsed`,zd({retryOfRequestLogID:i,url:t.url,status:t.status,body:s,durationMs:Date.now()-a})),s}function $Y(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var U0;let GY=class WY extends Promise{constructor(e,t,r=BY){super(i=>{i(null)}),this.responsePromise=t,this.parseResponse=r,U0.set(this,void 0),zt(this,U0,e)}_thenUnwrap(e){return new WY(Le(this,U0,"f"),this.responsePromise,async(t,r)=>$Y(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(Le(this,U0,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};U0=new WeakMap;var Ib;class LP{constructor(e,t,r,i){Ib.set(this,void 0),zt(this,Ib,e),this.options=i,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new Ot("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Le(this,Ib,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ib=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Bfe extends GY{constructor(e,t,r){super(e,t,async(i,a)=>new r(i,a.response,await BY(i,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class YT extends LP{constructor(e,t,r,i){super(e,t,r,i),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class ui extends LP{constructor(e,t,r,i){super(e,t,r,i),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...IY(this.options.query),after:t}}:null}}class DS extends LP{constructor(e,t,r,i){super(e,t,r,i),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...IY(this.options.query),after:e}}:null}}const zY=()=>{if(typeof File>"u"){const{process:n}=globalThis,e=typeof n?.versions?.node=="string"&&parseInt(n.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function hg(n,e,t){return zY(),new File(n,e??"unknown_file",t)}function UE(n){return(typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0}const FP=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",sF=async(n,e)=>fN(n.body)?{...n,body:await qY(n.body,e)}:n,xp=async(n,e)=>({...n,body:await qY(n.body,e)}),oF=new WeakMap;function $fe(n){const e=typeof n=="function"?n:n.fetch,t=oF.get(e);if(t)return t;const r=(async()=>{try{const i="Response"in e?e.Response:(await e("data:,")).constructor,a=new FormData;return a.toString()!==await new i(a).text()}catch{return!0}})();return oF.set(e,r),r}const qY=async(n,e)=>{if(!await $fe(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(n||{}).map(([r,i])=>mN(t,r,i))),t},HY=n=>n instanceof Blob&&"name"in n,Gfe=n=>typeof n=="object"&&n!==null&&(n instanceof Response||FP(n)||HY(n)),fN=n=>{if(Gfe(n))return!0;if(Array.isArray(n))return n.some(fN);if(n&&typeof n=="object"){for(const e in n)if(fN(n[e]))return!0}return!1},mN=async(n,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(t instanceof Response)n.append(e,hg([await t.blob()],UE(t)));else if(FP(t))n.append(e,hg([await new Response(DY(t)).blob()],UE(t)));else if(HY(t))n.append(e,t,UE(t));else if(Array.isArray(t))await Promise.all(t.map(r=>mN(n,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,i])=>mN(n,`${e}[${r}]`,i)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},VY=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",Wfe=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&VY(n),zfe=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function qfe(n,e,t){if(zY(),n=await n,Wfe(n))return n instanceof File?n:hg([await n.arrayBuffer()],n.name);if(zfe(n)){const i=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),hg(await gN(i),e,t)}const r=await gN(n);if(e||(e=UE(n)),!t?.type){const i=r.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof i=="string"&&(t={...t,type:i})}return hg(r,e,t)}async function gN(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(VY(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(FP(n))for await(const t of n)e.push(...await gN(t));else{const t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${Hfe(n)}`)}return e}function Hfe(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}let
|
|
78
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,i]=Ufe(e,":");return i.startsWith(" ")&&(i=i.substring(1)),t==="event"?this.event=i:t==="data"&&this.data.push(i),null}};function Ufe(n,e){const t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function BY(n,e){const{response:t,requestLogID:r,retryOfRequestLogID:i,startTime:a}=e,s=await(async()=>{if(e.options.stream)return Xi(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n):Jg.fromSSEResponse(t,e.controller,n);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const l=t.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){const d=await t.json();return $Y(d,t)}return await t.text()})();return Xi(n).debug(`[${r}] response parsed`,zd({retryOfRequestLogID:i,url:t.url,status:t.status,body:s,durationMs:Date.now()-a})),s}function $Y(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var U0;let GY=class WY extends Promise{constructor(e,t,r=BY){super(i=>{i(null)}),this.responsePromise=t,this.parseResponse=r,U0.set(this,void 0),zt(this,U0,e)}_thenUnwrap(e){return new WY(Le(this,U0,"f"),this.responsePromise,async(t,r)=>$Y(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(Le(this,U0,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};U0=new WeakMap;var Ib;class LP{constructor(e,t,r,i){Ib.set(this,void 0),zt(this,Ib,e),this.options=i,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new Ot("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Le(this,Ib,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ib=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Bfe extends GY{constructor(e,t,r){super(e,t,async(i,a)=>new r(i,a.response,await BY(i,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class YT extends LP{constructor(e,t,r,i){super(e,t,r,i),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class ui extends LP{constructor(e,t,r,i){super(e,t,r,i),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...IY(this.options.query),after:t}}:null}}class DS extends LP{constructor(e,t,r,i){super(e,t,r,i),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...IY(this.options.query),after:e}}:null}}const zY=()=>{if(typeof File>"u"){const{process:n}=globalThis,e=typeof n?.versions?.node=="string"&&parseInt(n.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function hg(n,e,t){return zY(),new File(n,e??"unknown_file",t)}function UE(n){return(typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0}const FP=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",sF=async(n,e)=>fN(n.body)?{...n,body:await qY(n.body,e)}:n,xp=async(n,e)=>({...n,body:await qY(n.body,e)}),oF=new WeakMap;function $fe(n){const e=typeof n=="function"?n:n.fetch,t=oF.get(e);if(t)return t;const r=(async()=>{try{const i="Response"in e?e.Response:(await e("data:,")).constructor,a=new FormData;return a.toString()!==await new i(a).text()}catch{return!0}})();return oF.set(e,r),r}const qY=async(n,e)=>{if(!await $fe(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(n||{}).map(([r,i])=>mN(t,r,i))),t},HY=n=>n instanceof Blob&&"name"in n,Gfe=n=>typeof n=="object"&&n!==null&&(n instanceof Response||FP(n)||HY(n)),fN=n=>{if(Gfe(n))return!0;if(Array.isArray(n))return n.some(fN);if(n&&typeof n=="object"){for(const e in n)if(fN(n[e]))return!0}return!1},mN=async(n,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(t instanceof Response)n.append(e,hg([await t.blob()],UE(t)));else if(FP(t))n.append(e,hg([await new Response(DY(t)).blob()],UE(t)));else if(HY(t))n.append(e,t,UE(t));else if(Array.isArray(t))await Promise.all(t.map(r=>mN(n,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,i])=>mN(n,`${e}[${r}]`,i)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},VY=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",Wfe=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&VY(n),zfe=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function qfe(n,e,t){if(zY(),n=await n,Wfe(n))return n instanceof File?n:hg([await n.arrayBuffer()],n.name);if(zfe(n)){const i=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),hg(await gN(i),e,t)}const r=await gN(n);if(e||(e=UE(n)),!t?.type){const i=r.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof i=="string"&&(t={...t,type:i})}return hg(r,e,t)}async function gN(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(VY(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(FP(n))for await(const t of n)e.push(...await gN(t));else{const t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${Hfe(n)}`)}return e}function Hfe(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}let Mt=class{constructor(e){this._client=e}};function YY(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const lF=Object.freeze(Object.create(null)),Vfe=(n=YY)=>function(t,...r){if(t.length===1)return t[0];let i=!1;const a=[],s=t.reduce((u,d,p)=>{/[?#]/.test(d)&&(i=!0);const h=r[p];let f=(i?encodeURIComponent:n)(""+h);return p!==r.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??lF)??lF)?.toString)&&(f=h+"",a.push({start:u.length+d.length,length:f.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),u+d+(p===r.length?"":f)},""),o=s.split(/[?#]/,1)[0],l=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let c;for(;(c=l.exec(o))!==null;)a.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(a.sort((u,d)=>u.start-d.start),a.length>0){let u=0;const d=a.reduce((p,h)=>{const f=" ".repeat(h.start-u),m="^".repeat(h.length);return u=h.start+h.length,p+f+m},"");throw new Ot(`Path parameters result in path with invalid segments:
|
|
79
79
|
${a.map(p=>p.error).join(`
|
|
80
80
|
`)}
|
|
81
81
|
${s}
|
|
82
|
-
${d}`)}return s},Ke=Vfe(YY);let KY=class extends Pt{list(e,t={},r){return this._client.getAPIList(Ke`/chat/completions/${e}/messages`,ui,{query:t,...r})}};function OS(n){return n!==void 0&&"function"in n&&n.function!==void 0}function UP(n){return n?.$brand==="auto-parseable-response-format"}function wv(n){return n?.$brand==="auto-parseable-tool"}function Yfe(n,e){return!e||!QY(e)?{...n,choices:n.choices.map(t=>(jY(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:BP(n,e)}function BP(n,e){const t=n.choices.map(r=>{if(r.finish_reason==="length")throw new RY;if(r.finish_reason==="content_filter")throw new kY;return jY(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(i=>Qfe(e,i))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Kfe(e,r.message.content):null}}});return{...n,choices:t}}function Kfe(n,e){return n.response_format?.type!=="json_schema"?null:n.response_format?.type==="json_schema"?"$parseRaw"in n.response_format?n.response_format.$parseRaw(e):JSON.parse(e):null}function Qfe(n,e){const t=n.tools?.find(r=>OS(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:wv(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function jfe(n,e){if(!n||!("tools"in n)||!n.tools)return!1;const t=n.tools?.find(r=>OS(r)&&r.function?.name===e.function.name);return OS(t)&&(wv(t)||t?.function.strict||!1)}function QY(n){return UP(n.response_format)?!0:n.tools?.some(e=>wv(e)||e.type==="function"&&e.function.strict===!0)??!1}function jY(n){for(const e of n||[])if(e.type!=="function")throw new Ot(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Xfe(n){for(const e of n??[]){if(e.type!=="function")throw new Ot(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new Ot(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const PS=n=>n?.role==="assistant",XY=n=>n?.role==="tool";var _N,BE,$E,B0,$0,GE,G0,yc,W0,MS,LS,Wh,ZY;class $P{constructor(){_N.add(this),this.controller=new AbortController,BE.set(this,void 0),$E.set(this,()=>{}),B0.set(this,()=>{}),$0.set(this,void 0),GE.set(this,()=>{}),G0.set(this,()=>{}),yc.set(this,{}),W0.set(this,!1),MS.set(this,!1),LS.set(this,!1),Wh.set(this,!1),zt(this,BE,new Promise((e,t)=>{zt(this,$E,e,"f"),zt(this,B0,t,"f")})),zt(this,$0,new Promise((e,t)=>{zt(this,GE,e,"f"),zt(this,G0,t,"f")})),Le(this,BE,"f").catch(()=>{}),Le(this,$0,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},Le(this,_N,"m",ZY).bind(this))},0)}_connected(){this.ended||(Le(this,$E,"f").call(this),this._emit("connect"))}get ended(){return Le(this,W0,"f")}get errored(){return Le(this,MS,"f")}get aborted(){return Le(this,LS,"f")}abort(){this.controller.abort()}on(e,t){return(Le(this,yc,"f")[e]||(Le(this,yc,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=Le(this,yc,"f")[e];if(!r)return this;const i=r.findIndex(a=>a.listener===t);return i>=0&&r.splice(i,1),this}once(e,t){return(Le(this,yc,"f")[e]||(Le(this,yc,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{zt(this,Wh,!0),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){zt(this,Wh,!0),await Le(this,$0,"f")}_emit(e,...t){if(Le(this,W0,"f"))return;e==="end"&&(zt(this,W0,!0),Le(this,GE,"f").call(this));const r=Le(this,yc,"f")[e];if(r&&(Le(this,yc,"f")[e]=r.filter(i=>!i.once),r.forEach(({listener:i})=>i(...t))),e==="abort"){const i=t[0];!Le(this,Wh,"f")&&!r?.length&&Promise.reject(i),Le(this,B0,"f").call(this,i),Le(this,G0,"f").call(this,i),this._emit("end");return}if(e==="error"){const i=t[0];!Le(this,Wh,"f")&&!r?.length&&Promise.reject(i),Le(this,B0,"f").call(this,i),Le(this,G0,"f").call(this,i),this._emit("end")}}_emitFinal(){}}BE=new WeakMap,$E=new WeakMap,B0=new WeakMap,$0=new WeakMap,GE=new WeakMap,G0=new WeakMap,yc=new WeakMap,W0=new WeakMap,MS=new WeakMap,LS=new WeakMap,Wh=new WeakMap,_N=new WeakSet,ZY=function(e){if(zt(this,MS,!0),e instanceof Error&&e.name==="AbortError"&&(e=new So),e instanceof So)return zt(this,LS,!0),this._emit("abort",e);if(e instanceof Ot)return this._emit("error",e);if(e instanceof Error){const t=new Ot(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new Ot(String(e)))};function Zfe(n){return typeof n.parse=="function"}var Na,vN,FS,bN,yN,EN,JY,eK;const Jfe=10;class tK extends $P{constructor(){super(...arguments),Na.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),XY(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(PS(e)&&e.tool_calls)for(const r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new Ot("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),Le(this,Na,"m",vN).call(this)}async finalMessage(){return await this.done(),Le(this,Na,"m",FS).call(this)}async finalFunctionToolCall(){return await this.done(),Le(this,Na,"m",bN).call(this)}async finalFunctionToolCallResult(){return await this.done(),Le(this,Na,"m",yN).call(this)}async totalUsage(){return await this.done(),Le(this,Na,"m",EN).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=Le(this,Na,"m",FS).call(this);t&&this._emit("finalMessage",t);const r=Le(this,Na,"m",vN).call(this);r&&this._emit("finalContent",r);const i=Le(this,Na,"m",bN).call(this);i&&this._emit("finalFunctionToolCall",i);const a=Le(this,Na,"m",yN).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(s=>s.usage)&&this._emit("totalUsage",Le(this,Na,"m",EN).call(this))}async _createChatCompletion(e,t,r){const i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),Le(this,Na,"m",JY).call(this,t);const a=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(BP(a,t))}async _runChatCompletion(e,t,r){for(const i of t.messages)this._addMessage(i,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){const i="tool",{tool_choice:a="auto",stream:s,...o}=t,l=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:c=Jfe}=r||{},u=t.tools.map(h=>{if(wv(h)){if(!h.$callback)throw new Ot("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:h.$callback,name:h.function.name,description:h.function.description||"",parameters:h.function.parameters,parse:h.$parseRaw,strict:!0}}}return h}),d={};for(const h of u)h.type==="function"&&(d[h.function.name||h.function.function.name]=h.function);const p="tools"in t?u.map(h=>h.type==="function"?{type:"function",function:{name:h.function.name||h.function.function.name,parameters:h.function.parameters,description:h.function.description,strict:h.function.strict}}:h):void 0;for(const h of t.messages)this._addMessage(h,!1);for(let h=0;h<c;++h){const m=(await this._createChatCompletion(e,{...o,tool_choice:a,tools:p,messages:[...this.messages]},r)).choices[0]?.message;if(!m)throw new Ot("missing message in ChatCompletion response");if(!m.tool_calls?.length)return;for(const g of m.tool_calls){if(g.type!=="function")continue;const _=g.id,{name:v,arguments:b}=g.function,E=d[v];if(E){if(l&&l!==v){const A=`Invalid tool_call: ${JSON.stringify(v)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:i,tool_call_id:_,content:A});continue}}else{const A=`Invalid tool_call: ${JSON.stringify(v)}. Available options are: ${Object.keys(d).map(C=>JSON.stringify(C)).join(", ")}. Please try again`;this._addMessage({role:i,tool_call_id:_,content:A});continue}let S;try{S=Zfe(E)?await E.parse(b):b}catch(A){const C=A instanceof Error?A.message:String(A);this._addMessage({role:i,tool_call_id:_,content:C});continue}const w=await E.function(S,this),x=Le(this,Na,"m",eK).call(this,w);if(this._addMessage({role:i,tool_call_id:_,content:x}),l)return}}}}Na=new WeakSet,vN=function(){return Le(this,Na,"m",FS).call(this).content??null},FS=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(PS(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new Ot("stream ended without producing a ChatCompletionMessage with role=assistant")},bN=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(PS(t)&&t?.tool_calls?.length)return t.tool_calls.filter(r=>r.type==="function").at(-1)?.function}},yN=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(XY(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(i=>i.type==="function"&&i.id===t.tool_call_id)))return t.content}},EN=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},JY=function(e){if(e.n!=null&&e.n>1)throw new Ot("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},eK=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class GP extends tK{static runTools(e,t,r){const i=new GP,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,t,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),PS(e)&&e.content&&this._emit("content",e.content)}}const nK=1,rK=2,iK=4,aK=8,sK=16,oK=32,lK=64,cK=128,uK=256,dK=cK|uK,pK=sK|oK|dK|lK,hK=nK|rK|pK,fK=iK|aK,eme=hK|fK,Pi={STR:nK,NUM:rK,ARR:iK,OBJ:aK,NULL:sK,BOOL:oK,NAN:lK,INFINITY:cK,MINUS_INFINITY:uK,INF:dK,SPECIAL:pK,ATOM:hK,COLLECTION:fK,ALL:eme};class tme extends Error{}class nme extends Error{}function rme(n,e=Pi.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return ime(n.trim(),e)}const ime=(n,e)=>{const t=n.length;let r=0;const i=p=>{throw new tme(`${p} at position ${r}`)},a=p=>{throw new nme(`${p} at position ${r}`)},s=()=>(d(),r>=t&&i("Unexpected end of input"),n[r]==='"'?o():n[r]==="{"?l():n[r]==="["?c():n.substring(r,r+4)==="null"||Pi.NULL&e&&t-r<4&&"null".startsWith(n.substring(r))?(r+=4,null):n.substring(r,r+4)==="true"||Pi.BOOL&e&&t-r<4&&"true".startsWith(n.substring(r))?(r+=4,!0):n.substring(r,r+5)==="false"||Pi.BOOL&e&&t-r<5&&"false".startsWith(n.substring(r))?(r+=5,!1):n.substring(r,r+8)==="Infinity"||Pi.INFINITY&e&&t-r<8&&"Infinity".startsWith(n.substring(r))?(r+=8,1/0):n.substring(r,r+9)==="-Infinity"||Pi.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(n.substring(r))?(r+=9,-1/0):n.substring(r,r+3)==="NaN"||Pi.NAN&e&&t-r<3&&"NaN".startsWith(n.substring(r))?(r+=3,NaN):u()),o=()=>{const p=r;let h=!1;for(r++;r<t&&(n[r]!=='"'||h&&n[r-1]==="\\");)h=n[r]==="\\"?!h:!1,r++;if(n.charAt(r)=='"')try{return JSON.parse(n.substring(p,++r-Number(h)))}catch(f){a(String(f))}else if(Pi.STR&e)try{return JSON.parse(n.substring(p,r-Number(h))+'"')}catch{return JSON.parse(n.substring(p,n.lastIndexOf("\\"))+'"')}i("Unterminated string literal")},l=()=>{r++,d();const p={};try{for(;n[r]!=="}";){if(d(),r>=t&&Pi.OBJ&e)return p;const h=o();d(),r++;try{const f=s();Object.defineProperty(p,h,{value:f,writable:!0,enumerable:!0,configurable:!0})}catch(f){if(Pi.OBJ&e)return p;throw f}d(),n[r]===","&&r++}}catch{if(Pi.OBJ&e)return p;i("Expected '}' at end of object")}return r++,p},c=()=>{r++;const p=[];try{for(;n[r]!=="]";)p.push(s()),d(),n[r]===","&&r++}catch{if(Pi.ARR&e)return p;i("Expected ']' at end of array")}return r++,p},u=()=>{if(r===0){n==="-"&&Pi.NUM&e&&i("Not sure what '-' is");try{return JSON.parse(n)}catch(h){if(Pi.NUM&e)try{return n[n.length-1]==="."?JSON.parse(n.substring(0,n.lastIndexOf("."))):JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}a(String(h))}}const p=r;for(n[r]==="-"&&r++;n[r]&&!",]}".includes(n[r]);)r++;r==t&&!(Pi.NUM&e)&&i("Unterminated number literal");try{return JSON.parse(n.substring(p,r))}catch{n.substring(p,r)==="-"&&Pi.NUM&e&&i("Not sure what '-' is");try{return JSON.parse(n.substring(p,n.lastIndexOf("e")))}catch(f){a(String(f))}}},d=()=>{for(;r<t&&`
|
|
82
|
+
${d}`)}return s},Ke=Vfe(YY);let KY=class extends Mt{list(e,t={},r){return this._client.getAPIList(Ke`/chat/completions/${e}/messages`,ui,{query:t,...r})}};function OS(n){return n!==void 0&&"function"in n&&n.function!==void 0}function UP(n){return n?.$brand==="auto-parseable-response-format"}function wv(n){return n?.$brand==="auto-parseable-tool"}function Yfe(n,e){return!e||!QY(e)?{...n,choices:n.choices.map(t=>(jY(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:BP(n,e)}function BP(n,e){const t=n.choices.map(r=>{if(r.finish_reason==="length")throw new RY;if(r.finish_reason==="content_filter")throw new kY;return jY(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(i=>Qfe(e,i))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Kfe(e,r.message.content):null}}});return{...n,choices:t}}function Kfe(n,e){return n.response_format?.type!=="json_schema"?null:n.response_format?.type==="json_schema"?"$parseRaw"in n.response_format?n.response_format.$parseRaw(e):JSON.parse(e):null}function Qfe(n,e){const t=n.tools?.find(r=>OS(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:wv(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function jfe(n,e){if(!n||!("tools"in n)||!n.tools)return!1;const t=n.tools?.find(r=>OS(r)&&r.function?.name===e.function.name);return OS(t)&&(wv(t)||t?.function.strict||!1)}function QY(n){return UP(n.response_format)?!0:n.tools?.some(e=>wv(e)||e.type==="function"&&e.function.strict===!0)??!1}function jY(n){for(const e of n||[])if(e.type!=="function")throw new Ot(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Xfe(n){for(const e of n??[]){if(e.type!=="function")throw new Ot(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new Ot(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const PS=n=>n?.role==="assistant",XY=n=>n?.role==="tool";var _N,BE,$E,B0,$0,GE,G0,yc,W0,MS,LS,Wh,ZY;class $P{constructor(){_N.add(this),this.controller=new AbortController,BE.set(this,void 0),$E.set(this,()=>{}),B0.set(this,()=>{}),$0.set(this,void 0),GE.set(this,()=>{}),G0.set(this,()=>{}),yc.set(this,{}),W0.set(this,!1),MS.set(this,!1),LS.set(this,!1),Wh.set(this,!1),zt(this,BE,new Promise((e,t)=>{zt(this,$E,e,"f"),zt(this,B0,t,"f")})),zt(this,$0,new Promise((e,t)=>{zt(this,GE,e,"f"),zt(this,G0,t,"f")})),Le(this,BE,"f").catch(()=>{}),Le(this,$0,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},Le(this,_N,"m",ZY).bind(this))},0)}_connected(){this.ended||(Le(this,$E,"f").call(this),this._emit("connect"))}get ended(){return Le(this,W0,"f")}get errored(){return Le(this,MS,"f")}get aborted(){return Le(this,LS,"f")}abort(){this.controller.abort()}on(e,t){return(Le(this,yc,"f")[e]||(Le(this,yc,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=Le(this,yc,"f")[e];if(!r)return this;const i=r.findIndex(a=>a.listener===t);return i>=0&&r.splice(i,1),this}once(e,t){return(Le(this,yc,"f")[e]||(Le(this,yc,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{zt(this,Wh,!0),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){zt(this,Wh,!0),await Le(this,$0,"f")}_emit(e,...t){if(Le(this,W0,"f"))return;e==="end"&&(zt(this,W0,!0),Le(this,GE,"f").call(this));const r=Le(this,yc,"f")[e];if(r&&(Le(this,yc,"f")[e]=r.filter(i=>!i.once),r.forEach(({listener:i})=>i(...t))),e==="abort"){const i=t[0];!Le(this,Wh,"f")&&!r?.length&&Promise.reject(i),Le(this,B0,"f").call(this,i),Le(this,G0,"f").call(this,i),this._emit("end");return}if(e==="error"){const i=t[0];!Le(this,Wh,"f")&&!r?.length&&Promise.reject(i),Le(this,B0,"f").call(this,i),Le(this,G0,"f").call(this,i),this._emit("end")}}_emitFinal(){}}BE=new WeakMap,$E=new WeakMap,B0=new WeakMap,$0=new WeakMap,GE=new WeakMap,G0=new WeakMap,yc=new WeakMap,W0=new WeakMap,MS=new WeakMap,LS=new WeakMap,Wh=new WeakMap,_N=new WeakSet,ZY=function(e){if(zt(this,MS,!0),e instanceof Error&&e.name==="AbortError"&&(e=new So),e instanceof So)return zt(this,LS,!0),this._emit("abort",e);if(e instanceof Ot)return this._emit("error",e);if(e instanceof Error){const t=new Ot(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new Ot(String(e)))};function Zfe(n){return typeof n.parse=="function"}var Na,vN,FS,bN,yN,EN,JY,eK;const Jfe=10;class tK extends $P{constructor(){super(...arguments),Na.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),XY(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(PS(e)&&e.tool_calls)for(const r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new Ot("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),Le(this,Na,"m",vN).call(this)}async finalMessage(){return await this.done(),Le(this,Na,"m",FS).call(this)}async finalFunctionToolCall(){return await this.done(),Le(this,Na,"m",bN).call(this)}async finalFunctionToolCallResult(){return await this.done(),Le(this,Na,"m",yN).call(this)}async totalUsage(){return await this.done(),Le(this,Na,"m",EN).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=Le(this,Na,"m",FS).call(this);t&&this._emit("finalMessage",t);const r=Le(this,Na,"m",vN).call(this);r&&this._emit("finalContent",r);const i=Le(this,Na,"m",bN).call(this);i&&this._emit("finalFunctionToolCall",i);const a=Le(this,Na,"m",yN).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(s=>s.usage)&&this._emit("totalUsage",Le(this,Na,"m",EN).call(this))}async _createChatCompletion(e,t,r){const i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),Le(this,Na,"m",JY).call(this,t);const a=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(BP(a,t))}async _runChatCompletion(e,t,r){for(const i of t.messages)this._addMessage(i,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){const i="tool",{tool_choice:a="auto",stream:s,...o}=t,l=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:c=Jfe}=r||{},u=t.tools.map(h=>{if(wv(h)){if(!h.$callback)throw new Ot("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:h.$callback,name:h.function.name,description:h.function.description||"",parameters:h.function.parameters,parse:h.$parseRaw,strict:!0}}}return h}),d={};for(const h of u)h.type==="function"&&(d[h.function.name||h.function.function.name]=h.function);const p="tools"in t?u.map(h=>h.type==="function"?{type:"function",function:{name:h.function.name||h.function.function.name,parameters:h.function.parameters,description:h.function.description,strict:h.function.strict}}:h):void 0;for(const h of t.messages)this._addMessage(h,!1);for(let h=0;h<c;++h){const m=(await this._createChatCompletion(e,{...o,tool_choice:a,tools:p,messages:[...this.messages]},r)).choices[0]?.message;if(!m)throw new Ot("missing message in ChatCompletion response");if(!m.tool_calls?.length)return;for(const g of m.tool_calls){if(g.type!=="function")continue;const _=g.id,{name:v,arguments:b}=g.function,E=d[v];if(E){if(l&&l!==v){const A=`Invalid tool_call: ${JSON.stringify(v)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:i,tool_call_id:_,content:A});continue}}else{const A=`Invalid tool_call: ${JSON.stringify(v)}. Available options are: ${Object.keys(d).map(C=>JSON.stringify(C)).join(", ")}. Please try again`;this._addMessage({role:i,tool_call_id:_,content:A});continue}let S;try{S=Zfe(E)?await E.parse(b):b}catch(A){const C=A instanceof Error?A.message:String(A);this._addMessage({role:i,tool_call_id:_,content:C});continue}const w=await E.function(S,this),x=Le(this,Na,"m",eK).call(this,w);if(this._addMessage({role:i,tool_call_id:_,content:x}),l)return}}}}Na=new WeakSet,vN=function(){return Le(this,Na,"m",FS).call(this).content??null},FS=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(PS(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new Ot("stream ended without producing a ChatCompletionMessage with role=assistant")},bN=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(PS(t)&&t?.tool_calls?.length)return t.tool_calls.filter(r=>r.type==="function").at(-1)?.function}},yN=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(XY(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(i=>i.type==="function"&&i.id===t.tool_call_id)))return t.content}},EN=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},JY=function(e){if(e.n!=null&&e.n>1)throw new Ot("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},eK=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class GP extends tK{static runTools(e,t,r){const i=new GP,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,t,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),PS(e)&&e.content&&this._emit("content",e.content)}}const nK=1,rK=2,iK=4,aK=8,sK=16,oK=32,lK=64,cK=128,uK=256,dK=cK|uK,pK=sK|oK|dK|lK,hK=nK|rK|pK,fK=iK|aK,eme=hK|fK,Pi={STR:nK,NUM:rK,ARR:iK,OBJ:aK,NULL:sK,BOOL:oK,NAN:lK,INFINITY:cK,MINUS_INFINITY:uK,INF:dK,SPECIAL:pK,ATOM:hK,COLLECTION:fK,ALL:eme};class tme extends Error{}class nme extends Error{}function rme(n,e=Pi.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return ime(n.trim(),e)}const ime=(n,e)=>{const t=n.length;let r=0;const i=p=>{throw new tme(`${p} at position ${r}`)},a=p=>{throw new nme(`${p} at position ${r}`)},s=()=>(d(),r>=t&&i("Unexpected end of input"),n[r]==='"'?o():n[r]==="{"?l():n[r]==="["?c():n.substring(r,r+4)==="null"||Pi.NULL&e&&t-r<4&&"null".startsWith(n.substring(r))?(r+=4,null):n.substring(r,r+4)==="true"||Pi.BOOL&e&&t-r<4&&"true".startsWith(n.substring(r))?(r+=4,!0):n.substring(r,r+5)==="false"||Pi.BOOL&e&&t-r<5&&"false".startsWith(n.substring(r))?(r+=5,!1):n.substring(r,r+8)==="Infinity"||Pi.INFINITY&e&&t-r<8&&"Infinity".startsWith(n.substring(r))?(r+=8,1/0):n.substring(r,r+9)==="-Infinity"||Pi.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(n.substring(r))?(r+=9,-1/0):n.substring(r,r+3)==="NaN"||Pi.NAN&e&&t-r<3&&"NaN".startsWith(n.substring(r))?(r+=3,NaN):u()),o=()=>{const p=r;let h=!1;for(r++;r<t&&(n[r]!=='"'||h&&n[r-1]==="\\");)h=n[r]==="\\"?!h:!1,r++;if(n.charAt(r)=='"')try{return JSON.parse(n.substring(p,++r-Number(h)))}catch(f){a(String(f))}else if(Pi.STR&e)try{return JSON.parse(n.substring(p,r-Number(h))+'"')}catch{return JSON.parse(n.substring(p,n.lastIndexOf("\\"))+'"')}i("Unterminated string literal")},l=()=>{r++,d();const p={};try{for(;n[r]!=="}";){if(d(),r>=t&&Pi.OBJ&e)return p;const h=o();d(),r++;try{const f=s();Object.defineProperty(p,h,{value:f,writable:!0,enumerable:!0,configurable:!0})}catch(f){if(Pi.OBJ&e)return p;throw f}d(),n[r]===","&&r++}}catch{if(Pi.OBJ&e)return p;i("Expected '}' at end of object")}return r++,p},c=()=>{r++;const p=[];try{for(;n[r]!=="]";)p.push(s()),d(),n[r]===","&&r++}catch{if(Pi.ARR&e)return p;i("Expected ']' at end of array")}return r++,p},u=()=>{if(r===0){n==="-"&&Pi.NUM&e&&i("Not sure what '-' is");try{return JSON.parse(n)}catch(h){if(Pi.NUM&e)try{return n[n.length-1]==="."?JSON.parse(n.substring(0,n.lastIndexOf("."))):JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}a(String(h))}}const p=r;for(n[r]==="-"&&r++;n[r]&&!",]}".includes(n[r]);)r++;r==t&&!(Pi.NUM&e)&&i("Unterminated number literal");try{return JSON.parse(n.substring(p,r))}catch{n.substring(p,r)==="-"&&Pi.NUM&e&&i("Not sure what '-' is");try{return JSON.parse(n.substring(p,n.lastIndexOf("e")))}catch(f){a(String(f))}}},d=()=>{for(;r<t&&`
|
|
83
83
|
\r `.includes(n[r]);)r++};return s()},cF=n=>rme(n,Pi.ALL^Pi.NUM);var Ei,fc,Ch,yu,Wx,Nb,zx,qx,Hx,Db,Vx,uF;class e_ extends tK{constructor(e){super(),Ei.add(this),fc.set(this,void 0),Ch.set(this,void 0),yu.set(this,void 0),zt(this,fc,e),zt(this,Ch,[])}get currentChatCompletionSnapshot(){return Le(this,yu,"f")}static fromReadableStream(e){const t=new e_(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){const i=new e_(t);return i._run(()=>i._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createChatCompletion(e,t,r){super._createChatCompletion;const i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),Le(this,Ei,"m",Wx).call(this);const a=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const s of a)Le(this,Ei,"m",zx).call(this,s);if(a.controller.signal?.aborted)throw new So;return this._addChatCompletion(Le(this,Ei,"m",Db).call(this))}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),Le(this,Ei,"m",Wx).call(this),this._connected();const i=Jg.fromReadableStream(e,this.controller);let a;for await(const s of i)a&&a!==s.id&&this._addChatCompletion(Le(this,Ei,"m",Db).call(this)),Le(this,Ei,"m",zx).call(this,s),a=s.id;if(i.controller.signal?.aborted)throw new So;return this._addChatCompletion(Le(this,Ei,"m",Db).call(this))}[(fc=new WeakMap,Ch=new WeakMap,yu=new WeakMap,Ei=new WeakSet,Wx=function(){this.ended||zt(this,yu,void 0)},Nb=function(t){let r=Le(this,Ch,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},Le(this,Ch,"f")[t.index]=r,r)},zx=function(t){if(this.ended)return;const r=Le(this,Ei,"m",uF).call(this,t);this._emit("chunk",t,r);for(const i of t.choices){const a=r.choices[i.index];i.delta.content!=null&&a.message?.role==="assistant"&&a.message?.content&&(this._emit("content",i.delta.content,a.message.content),this._emit("content.delta",{delta:i.delta.content,snapshot:a.message.content,parsed:a.message.parsed})),i.delta.refusal!=null&&a.message?.role==="assistant"&&a.message?.refusal&&this._emit("refusal.delta",{delta:i.delta.refusal,snapshot:a.message.refusal}),i.logprobs?.content!=null&&a.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:i.logprobs?.content,snapshot:a.logprobs?.content??[]}),i.logprobs?.refusal!=null&&a.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:i.logprobs?.refusal,snapshot:a.logprobs?.refusal??[]});const s=Le(this,Ei,"m",Nb).call(this,a);a.finish_reason&&(Le(this,Ei,"m",Hx).call(this,a),s.current_tool_call_index!=null&&Le(this,Ei,"m",qx).call(this,a,s.current_tool_call_index));for(const o of i.delta.tool_calls??[])s.current_tool_call_index!==o.index&&(Le(this,Ei,"m",Hx).call(this,a),s.current_tool_call_index!=null&&Le(this,Ei,"m",qx).call(this,a,s.current_tool_call_index)),s.current_tool_call_index=o.index;for(const o of i.delta.tool_calls??[]){const l=a.message.tool_calls?.[o.index];l?.type&&(l?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:l.function?.name,index:o.index,arguments:l.function.arguments,parsed_arguments:l.function.parsed_arguments,arguments_delta:o.function?.arguments??""}):(l?.type,void 0))}}},qx=function(t,r){if(Le(this,Ei,"m",Nb).call(this,t).done_tool_calls.has(r))return;const a=t.message.tool_calls?.[r];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){const s=Le(this,fc,"f")?.tools?.find(o=>OS(o)&&o.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:r,arguments:a.function.arguments,parsed_arguments:wv(s)?s.$parseRaw(a.function.arguments):s?.function.strict?JSON.parse(a.function.arguments):null})}else a.type},Hx=function(t){const r=Le(this,Ei,"m",Nb).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;const i=Le(this,Ei,"m",Vx).call(this);this._emit("content.done",{content:t.message.content,parsed:i?i.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Db=function(){if(this.ended)throw new Ot("stream has ended, this shouldn't happen");const t=Le(this,yu,"f");if(!t)throw new Ot("request ended without sending any chunks");return zt(this,yu,void 0),zt(this,Ch,[]),ame(t,Le(this,fc,"f"))},Vx=function(){const t=Le(this,fc,"f")?.response_format;return UP(t)?t:null},uF=function(t){var r,i,a,s;let o=Le(this,yu,"f");const{choices:l,...c}=t;o?Object.assign(o,c):o=zt(this,yu,{...c,choices:[]});for(const{delta:u,finish_reason:d,index:p,logprobs:h=null,...f}of t.choices){let m=o.choices[p];if(m||(m=o.choices[p]={finish_reason:d,index:p,message:{},logprobs:h,...f}),h)if(!m.logprobs)m.logprobs=Object.assign({},h);else{const{content:w,refusal:x,...A}=h;Object.assign(m.logprobs,A),w&&((r=m.logprobs).content??(r.content=[]),m.logprobs.content.push(...w)),x&&((i=m.logprobs).refusal??(i.refusal=[]),m.logprobs.refusal.push(...x))}if(d&&(m.finish_reason=d,Le(this,fc,"f")&&QY(Le(this,fc,"f")))){if(d==="length")throw new RY;if(d==="content_filter")throw new kY}if(Object.assign(m,f),!u)continue;const{content:g,refusal:_,function_call:v,role:b,tool_calls:E,...S}=u;if(Object.assign(m.message,S),_&&(m.message.refusal=(m.message.refusal||"")+_),b&&(m.message.role=b),v&&(m.message.function_call?(v.name&&(m.message.function_call.name=v.name),v.arguments&&((a=m.message.function_call).arguments??(a.arguments=""),m.message.function_call.arguments+=v.arguments)):m.message.function_call=v),g&&(m.message.content=(m.message.content||"")+g,!m.message.refusal&&Le(this,Ei,"m",Vx).call(this)&&(m.message.parsed=cF(m.message.content))),E){m.message.tool_calls||(m.message.tool_calls=[]);for(const{index:w,id:x,type:A,function:C,...D}of E){const N=(s=m.message.tool_calls)[w]??(s[w]={});Object.assign(N,D),x&&(N.id=x),A&&(N.type=A),C&&(N.function??(N.function={name:C.name??"",arguments:""})),C?.name&&(N.function.name=C.name),C?.arguments&&(N.function.arguments+=C.arguments,jfe(Le(this,fc,"f"),N)&&(N.function.parsed_arguments=cF(N.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("chunk",i=>{const a=t.shift();a?a.resolve(i):e.push(i)}),this.on("end",()=>{r=!0;for(const i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{r=!0;for(const a of t)a.reject(i);t.length=0}),this.on("error",i=>{r=!0;for(const a of t)a.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((a,s)=>t.push({resolve:a,reject:s})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Jg(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function ame(n,e){const{id:t,choices:r,created:i,model:a,system_fingerprint:s,...o}=n,l={...o,id:t,choices:r.map(({message:c,finish_reason:u,index:d,logprobs:p,...h})=>{if(!u)throw new Ot(`missing finish_reason for choice ${d}`);const{content:f=null,function_call:m,tool_calls:g,..._}=c,v=c.role;if(!v)throw new Ot(`missing role for choice ${d}`);if(m){const{arguments:b,name:E}=m;if(b==null)throw new Ot(`missing function_call.arguments for choice ${d}`);if(!E)throw new Ot(`missing function_call.name for choice ${d}`);return{...h,message:{content:f,function_call:{arguments:b,name:E},role:v,refusal:c.refusal??null},finish_reason:u,index:d,logprobs:p}}return g?{...h,index:d,finish_reason:u,logprobs:p,message:{..._,role:v,content:f,refusal:c.refusal??null,tool_calls:g.map((b,E)=>{const{function:S,type:w,id:x,...A}=b,{arguments:C,name:D,...N}=S||{};if(x==null)throw new Ot(`missing choices[${d}].tool_calls[${E}].id
|
|
84
84
|
${Ob(n)}`);if(w==null)throw new Ot(`missing choices[${d}].tool_calls[${E}].type
|
|
85
85
|
${Ob(n)}`);if(D==null)throw new Ot(`missing choices[${d}].tool_calls[${E}].function.name
|
|
86
86
|
${Ob(n)}`);if(C==null)throw new Ot(`missing choices[${d}].tool_calls[${E}].function.arguments
|
|
87
|
-
${Ob(n)}`);return{...A,id:x,type:w,function:{...N,name:D,arguments:C}}})}}:{...h,message:{..._,content:f,role:v,refusal:c.refusal??null},finish_reason:u,index:d,logprobs:p}}),created:i,model:a,object:"chat.completion",...s?{system_fingerprint:s}:{}};return Yfe(l,e)}function Ob(n){return JSON.stringify(n)}class US extends e_{static fromReadableStream(e){const t=new US(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){const i=new US(t),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,t,a)),i}}let WP=class extends Pt{constructor(){super(...arguments),this.messages=new KY(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(Ke`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(Ke`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",ui,{query:e,...t})}delete(e,t){return this._client.delete(Ke`/chat/completions/${e}`,t)}parse(e,t){return Xfe(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>BP(r,e))}runTools(e,t){return e.stream?US.runTools(this._client,e,t):GP.runTools(this._client,e,t)}stream(e,t){return e_.createChatCompletion(this._client,e,t)}};WP.Messages=KY;let zP=class extends Pt{constructor(){super(...arguments),this.completions=new WP(this._client)}};zP.Completions=WP;const mK=Symbol("brand.privateNullableHeaders");function*sme(n){if(!n)return;if(mK in n){const{values:r,nulls:i}=n;yield*r.entries();for(const a of i)yield[a,null];return}let e=!1,t;n instanceof Headers?t=n.entries():K5(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let r of t){const i=r[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");const a=K5(r[1])?r[1]:[r[1]];let s=!1;for(const o of a)o!==void 0&&(e&&!s&&(s=!0,yield[i,null]),yield[i,o])}}const Tt=n=>{const e=new Headers,t=new Set;for(const r of n){const i=new Set;for(const[a,s]of sme(r)){const o=a.toLowerCase();i.has(o)||(e.delete(a),i.add(o)),s===null?(e.delete(a),t.add(o)):(e.append(a,s),t.delete(o))}}return{[mK]:!0,values:e,nulls:t}};class gK extends Pt{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:Tt([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class _K extends Pt{create(e,t){return this._client.post("/audio/transcriptions",xp({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class vK extends Pt{create(e,t){return this._client.post("/audio/translations",xp({body:e,...t,__metadata:{model:e.model}},this._client))}}class xv extends Pt{constructor(){super(...arguments),this.transcriptions=new _K(this._client),this.translations=new vK(this._client),this.speech=new gK(this._client)}}xv.Transcriptions=_K;xv.Translations=vK;xv.Speech=gK;let bK=class extends Pt{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(Ke`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",ui,{query:e,...t})}cancel(e,t){return this._client.post(Ke`/batches/${e}/cancel`,t)}};class yK extends Pt{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(Ke`/assistants/${e}`,{...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(Ke`/assistants/${e}`,{body:t,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",ui,{query:e,...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(Ke`/assistants/${e}`,{...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let EK=class extends Pt{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};class SK extends Pt{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let KT=class extends Pt{constructor(){super(...arguments),this.sessions=new EK(this._client),this.transcriptionSessions=new SK(this._client)}};KT.Sessions=EK;KT.TranscriptionSessions=SK;class TK extends Pt{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:Tt([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(Ke`/chatkit/sessions/${e}/cancel`,{...t,headers:Tt([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}}let wK=class extends Pt{retrieve(e,t){return this._client.get(Ke`/chatkit/threads/${e}`,{...t,headers:Tt([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",DS,{query:e,...t,headers:Tt([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(Ke`/chatkit/threads/${e}`,{...t,headers:Tt([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(Ke`/chatkit/threads/${e}/items`,DS,{query:t,...r,headers:Tt([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}};class QT extends Pt{constructor(){super(...arguments),this.sessions=new TK(this._client),this.threads=new wK(this._client)}}QT.Sessions=TK;QT.Threads=wK;let xK=class extends Pt{create(e,t,r){return this._client.post(Ke`/threads/${e}/messages`,{body:t,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{thread_id:i}=t;return this._client.get(Ke`/threads/${i}/messages/${e}`,{...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{thread_id:i,...a}=t;return this._client.post(Ke`/threads/${i}/messages/${e}`,{body:a,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(Ke`/threads/${e}/messages`,ui,{query:t,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){const{thread_id:i}=t;return this._client.delete(Ke`/threads/${i}/messages/${e}`,{...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};class CK extends Pt{retrieve(e,t,r){const{thread_id:i,run_id:a,...s}=t;return this._client.get(Ke`/threads/${i}/runs/${a}/steps/${e}`,{query:s,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){const{thread_id:i,...a}=t;return this._client.getAPIList(Ke`/threads/${i}/runs/${e}/steps`,ui,{query:a,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}const ome=n=>{if(typeof Buffer<"u"){const e=Buffer.from(n,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(n),t=e.length,r=new Uint8Array(t);for(let i=0;i<t;i++)r[i]=e.charCodeAt(i);return Array.from(new Float32Array(r.buffer))}};var lme={};const wc=n=>{if(typeof globalThis.process<"u")return lme?.[n]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()};var Zi,rp,SN,Ul,WE,Vo,ip,tf,Qd,BS,Ps,zE,qE,fg,z0,q0,dF,pF,hF,fF,mF,gF,_F;class mg extends $P{constructor(){super(...arguments),Zi.add(this),SN.set(this,[]),Ul.set(this,{}),WE.set(this,{}),Vo.set(this,void 0),ip.set(this,void 0),tf.set(this,void 0),Qd.set(this,void 0),BS.set(this,void 0),Ps.set(this,void 0),zE.set(this,void 0),qE.set(this,void 0),fg.set(this,void 0)}[(SN=new WeakMap,Ul=new WeakMap,WE=new WeakMap,Vo=new WeakMap,ip=new WeakMap,tf=new WeakMap,Qd=new WeakMap,BS=new WeakMap,Ps=new WeakMap,zE=new WeakMap,qE=new WeakMap,fg=new WeakMap,Zi=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",i=>{const a=t.shift();a?a.resolve(i):e.push(i)}),this.on("end",()=>{r=!0;for(const i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{r=!0;for(const a of t)a.reject(i);t.length=0}),this.on("error",i=>{r=!0;for(const a of t)a.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((a,s)=>t.push({resolve:a,reject:s})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new rp;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();const i=Jg.fromReadableStream(e,this.controller);for await(const a of i)Le(this,Zi,"m",z0).call(this,a);if(i.controller.signal?.aborted)throw new So;return this._addRun(Le(this,Zi,"m",q0).call(this))}toReadableStream(){return new Jg(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,i){const a=new rp;return a._run(()=>a._runToolAssistantStream(e,t,r,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,t,r,i){const a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const s={...r,stream:!0},o=await e.submitToolOutputs(t,s,{...i,signal:this.controller.signal});this._connected();for await(const l of o)Le(this,Zi,"m",z0).call(this,l);if(o.controller.signal?.aborted)throw new So;return this._addRun(Le(this,Zi,"m",q0).call(this))}static createThreadAssistantStream(e,t,r){const i=new rp;return i._run(()=>i._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}static createAssistantStream(e,t,r,i){const a=new rp;return a._run(()=>a._runAssistantStream(e,t,r,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return Le(this,zE,"f")}currentRun(){return Le(this,qE,"f")}currentMessageSnapshot(){return Le(this,Vo,"f")}currentRunStepSnapshot(){return Le(this,fg,"f")}async finalRunSteps(){return await this.done(),Object.values(Le(this,Ul,"f"))}async finalMessages(){return await this.done(),Object.values(Le(this,WE,"f"))}async finalRun(){if(await this.done(),!Le(this,ip,"f"))throw Error("Final run was not received.");return Le(this,ip,"f")}async _createThreadAssistantStream(e,t,r){const i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const a={...t,stream:!0},s=await e.createAndRun(a,{...r,signal:this.controller.signal});this._connected();for await(const o of s)Le(this,Zi,"m",z0).call(this,o);if(s.controller.signal?.aborted)throw new So;return this._addRun(Le(this,Zi,"m",q0).call(this))}async _createAssistantStream(e,t,r,i){const a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const s={...r,stream:!0},o=await e.create(t,s,{...i,signal:this.controller.signal});this._connected();for await(const l of o)Le(this,Zi,"m",z0).call(this,l);if(o.controller.signal?.aborted)throw new So;return this._addRun(Le(this,Zi,"m",q0).call(this))}static accumulateDelta(e,t){for(const[r,i]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=i;continue}let a=e[r];if(a==null){e[r]=i;continue}if(r==="index"||r==="type"){e[r]=i;continue}if(typeof a=="string"&&typeof i=="string")a+=i;else if(typeof a=="number"&&typeof i=="number")a+=i;else if(FE(a)&&FE(i))a=this.accumulateDelta(a,i);else if(Array.isArray(a)&&Array.isArray(i)){if(a.every(s=>typeof s=="string"||typeof s=="number")){a.push(...i);continue}for(const s of i){if(!FE(s))throw new Error(`Expected array delta entry to be an object but got: ${s}`);const o=s.index;if(o==null)throw console.error(s),new Error("Expected array delta entry to have an `index` property");if(typeof o!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${o}`);const l=a[o];l==null?a.push(s):a[o]=this.accumulateDelta(l,s)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${i}, accValue: ${a}`);e[r]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,i){return await this._createAssistantStream(t,e,r,i)}async _runToolAssistantStream(e,t,r,i){return await this._createToolAssistantStream(t,e,r,i)}}rp=mg,z0=function(e){if(!this.ended)switch(zt(this,zE,e),Le(this,Zi,"m",hF).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":Le(this,Zi,"m",_F).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Le(this,Zi,"m",pF).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":Le(this,Zi,"m",dF).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},q0=function(){if(this.ended)throw new Ot("stream has ended, this shouldn't happen");if(!Le(this,ip,"f"))throw Error("Final run has not been received");return Le(this,ip,"f")},dF=function(e){const[t,r]=Le(this,Zi,"m",mF).call(this,e,Le(this,Vo,"f"));zt(this,Vo,t),Le(this,WE,"f")[t.id]=t;for(const i of r){const a=t.content[i.index];a?.type=="text"&&this._emit("textCreated",a.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const i of e.data.delta.content){if(i.type=="text"&&i.text){let a=i.text,s=t.content[i.index];if(s&&s.type=="text")this._emit("textDelta",a,s.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(i.index!=Le(this,tf,"f")){if(Le(this,Qd,"f"))switch(Le(this,Qd,"f").type){case"text":this._emit("textDone",Le(this,Qd,"f").text,Le(this,Vo,"f"));break;case"image_file":this._emit("imageFileDone",Le(this,Qd,"f").image_file,Le(this,Vo,"f"));break}zt(this,tf,i.index)}zt(this,Qd,t.content[i.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(Le(this,tf,"f")!==void 0){const i=e.data.content[Le(this,tf,"f")];if(i)switch(i.type){case"image_file":this._emit("imageFileDone",i.image_file,Le(this,Vo,"f"));break;case"text":this._emit("textDone",i.text,Le(this,Vo,"f"));break}}Le(this,Vo,"f")&&this._emit("messageDone",e.data),zt(this,Vo,void 0)}},pF=function(e){const t=Le(this,Zi,"m",fF).call(this,e);switch(zt(this,fg,t),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const a of r.step_details.tool_calls)a.index==Le(this,BS,"f")?this._emit("toolCallDelta",a,t.step_details.tool_calls[a.index]):(Le(this,Ps,"f")&&this._emit("toolCallDone",Le(this,Ps,"f")),zt(this,BS,a.index),zt(this,Ps,t.step_details.tool_calls[a.index]),Le(this,Ps,"f")&&this._emit("toolCallCreated",Le(this,Ps,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":zt(this,fg,void 0),e.data.step_details.type=="tool_calls"&&Le(this,Ps,"f")&&(this._emit("toolCallDone",Le(this,Ps,"f")),zt(this,Ps,void 0)),this._emit("runStepDone",e.data,t);break}},hF=function(e){Le(this,SN,"f").push(e),this._emit("event",e)},fF=function(e){switch(e.event){case"thread.run.step.created":return Le(this,Ul,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=Le(this,Ul,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){const i=rp.accumulateDelta(t,r.delta);Le(this,Ul,"f")[e.data.id]=i}return Le(this,Ul,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":Le(this,Ul,"f")[e.data.id]=e.data;break}if(Le(this,Ul,"f")[e.data.id])return Le(this,Ul,"f")[e.data.id];throw new Error("No snapshot available")},mF=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let i=e.data;if(i.delta.content)for(const a of i.delta.content)if(a.index in t.content){let s=t.content[a.index];t.content[a.index]=Le(this,Zi,"m",gF).call(this,a,s)}else t.content[a.index]=a,r.push(a);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},gF=function(e,t){return rp.accumulateDelta(t,e)},_F=function(e){switch(zt(this,qE,e.data),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":zt(this,ip,e.data),Le(this,Ps,"f")&&(this._emit("toolCallDone",Le(this,Ps,"f")),zt(this,Ps,void 0));break}};let qP=class extends Pt{constructor(){super(...arguments),this.steps=new CK(this._client)}create(e,t,r){const{include:i,...a}=t;return this._client.post(Ke`/threads/${e}/runs`,{query:{include:i},body:a,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}retrieve(e,t,r){const{thread_id:i}=t;return this._client.get(Ke`/threads/${i}/runs/${e}`,{...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{thread_id:i,...a}=t;return this._client.post(Ke`/threads/${i}/runs/${e}`,{body:a,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(Ke`/threads/${e}/runs`,ui,{query:t,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){const{thread_id:i}=t;return this._client.post(Ke`/threads/${i}/runs/${e}/cancel`,{...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){const i=await this.create(e,t,r);return await this.poll(i.id,{thread_id:e},r)}createAndStream(e,t,r){return mg.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){const i=Tt([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:s}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...i}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{const l=s.headers.get("openai-poll-after-ms");if(l){const c=parseInt(l);isNaN(c)||(o=c)}}await Tv(o);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,t,r){return mg.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){const{thread_id:i,...a}=t;return this._client.post(Ke`/threads/${i}/runs/${e}/submit_tool_outputs`,{body:a,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,r){const i=await this.submitToolOutputs(e,t,r);return await this.poll(i.id,t,r)}submitToolOutputsStream(e,t,r){return mg.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};qP.Steps=CK;class jT extends Pt{constructor(){super(...arguments),this.runs=new qP(this._client),this.messages=new xK(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(Ke`/threads/${e}`,{...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(Ke`/threads/${e}`,{body:t,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(Ke`/threads/${e}`,{...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){const r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return mg.createThreadAssistantStream(e,this._client.beta.threads,t)}}jT.Runs=qP;jT.Messages=xK;class pm extends Pt{constructor(){super(...arguments),this.realtime=new KT(this._client),this.chatkit=new QT(this._client),this.assistants=new yK(this._client),this.threads=new jT(this._client)}}pm.Realtime=KT;pm.ChatKit=QT;pm.Assistants=yK;pm.Threads=jT;class AK extends Pt{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class RK extends Pt{retrieve(e,t,r){const{container_id:i}=t;return this._client.get(Ke`/containers/${i}/files/${e}/content`,{...r,headers:Tt([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}let HP=class extends Pt{constructor(){super(...arguments),this.content=new RK(this._client)}create(e,t,r){return this._client.post(Ke`/containers/${e}/files`,xp({body:t,...r},this._client))}retrieve(e,t,r){const{container_id:i}=t;return this._client.get(Ke`/containers/${i}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(Ke`/containers/${e}/files`,ui,{query:t,...r})}delete(e,t,r){const{container_id:i}=t;return this._client.delete(Ke`/containers/${i}/files/${e}`,{...r,headers:Tt([{Accept:"*/*"},r?.headers])})}};HP.Content=RK;class VP extends Pt{constructor(){super(...arguments),this.files=new HP(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(Ke`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",ui,{query:e,...t})}delete(e,t){return this._client.delete(Ke`/containers/${e}`,{...t,headers:Tt([{Accept:"*/*"},t?.headers])})}}VP.Files=HP;class kK extends Pt{create(e,t,r){const{include:i,...a}=t;return this._client.post(Ke`/conversations/${e}/items`,{query:{include:i},body:a,...r})}retrieve(e,t,r){const{conversation_id:i,...a}=t;return this._client.get(Ke`/conversations/${i}/items/${e}`,{query:a,...r})}list(e,t={},r){return this._client.getAPIList(Ke`/conversations/${e}/items`,DS,{query:t,...r})}delete(e,t,r){const{conversation_id:i}=t;return this._client.delete(Ke`/conversations/${i}/items/${e}`,r)}}class YP extends Pt{constructor(){super(...arguments),this.items=new kK(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(Ke`/conversations/${e}`,t)}update(e,t,r){return this._client.post(Ke`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(Ke`/conversations/${e}`,t)}}YP.Items=kK;class IK extends Pt{create(e,t){const r=!!e.encoding_format;let i=r?e.encoding_format:"base64";r&&Xi(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const a=this._client.post("/embeddings",{body:{...e,encoding_format:i},...t});return r?a:(Xi(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(s=>(s&&s.data&&s.data.forEach(o=>{const l=o.embedding;o.embedding=ome(l)}),s)))}}class NK extends Pt{retrieve(e,t,r){const{eval_id:i,run_id:a}=t;return this._client.get(Ke`/evals/${i}/runs/${a}/output_items/${e}`,r)}list(e,t,r){const{eval_id:i,...a}=t;return this._client.getAPIList(Ke`/evals/${i}/runs/${e}/output_items`,ui,{query:a,...r})}}class KP extends Pt{constructor(){super(...arguments),this.outputItems=new NK(this._client)}create(e,t,r){return this._client.post(Ke`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){const{eval_id:i}=t;return this._client.get(Ke`/evals/${i}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(Ke`/evals/${e}/runs`,ui,{query:t,...r})}delete(e,t,r){const{eval_id:i}=t;return this._client.delete(Ke`/evals/${i}/runs/${e}`,r)}cancel(e,t,r){const{eval_id:i}=t;return this._client.post(Ke`/evals/${i}/runs/${e}`,r)}}KP.OutputItems=NK;class QP extends Pt{constructor(){super(...arguments),this.runs=new KP(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(Ke`/evals/${e}`,t)}update(e,t,r){return this._client.post(Ke`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",ui,{query:e,...t})}delete(e,t){return this._client.delete(Ke`/evals/${e}`,t)}}QP.Runs=KP;let DK=class extends Pt{create(e,t){return this._client.post("/files",xp({body:e,...t},this._client))}retrieve(e,t){return this._client.get(Ke`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",ui,{query:e,...t})}delete(e,t){return this._client.delete(Ke`/files/${e}`,t)}content(e,t){return this._client.get(Ke`/files/${e}/content`,{...t,headers:Tt([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=1800*1e3}={}){const i=new Set(["processed","error","deleted"]),a=Date.now();let s=await this.retrieve(e);for(;!s.status||!i.has(s.status);)if(await Tv(t),s=await this.retrieve(e),Date.now()-a>r)throw new PP({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return s}};class OK extends Pt{}let PK=class extends Pt{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class jP extends Pt{constructor(){super(...arguments),this.graders=new PK(this._client)}}jP.Graders=PK;class MK extends Pt{create(e,t,r){return this._client.getAPIList(Ke`/fine_tuning/checkpoints/${e}/permissions`,YT,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(Ke`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){const{fine_tuned_model_checkpoint:i}=t;return this._client.delete(Ke`/fine_tuning/checkpoints/${i}/permissions/${e}`,r)}}let XP=class extends Pt{constructor(){super(...arguments),this.permissions=new MK(this._client)}};XP.Permissions=MK;class LK extends Pt{list(e,t={},r){return this._client.getAPIList(Ke`/fine_tuning/jobs/${e}/checkpoints`,ui,{query:t,...r})}}class ZP extends Pt{constructor(){super(...arguments),this.checkpoints=new LK(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(Ke`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",ui,{query:e,...t})}cancel(e,t){return this._client.post(Ke`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(Ke`/fine_tuning/jobs/${e}/events`,ui,{query:t,...r})}pause(e,t){return this._client.post(Ke`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(Ke`/fine_tuning/jobs/${e}/resume`,t)}}ZP.Checkpoints=LK;class hm extends Pt{constructor(){super(...arguments),this.methods=new OK(this._client),this.jobs=new ZP(this._client),this.checkpoints=new XP(this._client),this.alpha=new jP(this._client)}}hm.Methods=OK;hm.Jobs=ZP;hm.Checkpoints=XP;hm.Alpha=jP;class FK extends Pt{}class JP extends Pt{constructor(){super(...arguments),this.graderModels=new FK(this._client)}}JP.GraderModels=FK;class UK extends Pt{createVariation(e,t){return this._client.post("/images/variations",xp({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",xp({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}let BK=class extends Pt{retrieve(e,t){return this._client.get(Ke`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",YT,e)}delete(e,t){return this._client.delete(Ke`/models/${e}`,t)}};class $K extends Pt{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class GK extends Pt{accept(e,t,r){return this._client.post(Ke`/realtime/calls/${e}/accept`,{body:t,...r,headers:Tt([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(Ke`/realtime/calls/${e}/hangup`,{...t,headers:Tt([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(Ke`/realtime/calls/${e}/refer`,{body:t,...r,headers:Tt([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(Ke`/realtime/calls/${e}/reject`,{body:t,...r,headers:Tt([{Accept:"*/*"},r?.headers])})}}class WK extends Pt{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class XT extends Pt{constructor(){super(...arguments),this.clientSecrets=new WK(this._client),this.calls=new GK(this._client)}}XT.ClientSecrets=WK;XT.Calls=GK;function cme(n,e){return!e||!dme(e)?{...n,output_parsed:null,output:n.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:zK(n,e)}function zK(n,e){const t=n.output.map(i=>{if(i.type==="function_call")return{...i,parsed_arguments:fme(e,i)};if(i.type==="message"){const a=i.content.map(s=>s.type==="output_text"?{...s,parsed:ume(e,s.text)}:s);return{...i,content:a}}return i}),r=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||TN(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(const i of r.output)if(i.type==="message"){for(const a of i.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),r}function ume(n,e){return n.text?.format?.type!=="json_schema"?null:"$parseRaw"in n.text?.format?(n.text?.format).$parseRaw(e):JSON.parse(e)}function dme(n){return!!UP(n.text?.format)}function pme(n){return n?.$brand==="auto-parseable-tool"}function hme(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function fme(n,e){const t=hme(n.tools??[],e.name);return{...e,...e,parsed_arguments:pme(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function TN(n){const e=[];for(const t of n.output)if(t.type==="message")for(const r of t.content)r.type==="output_text"&&e.push(r.text);n.output_text=e.join("")}var Ah,Pb,Eu,Mb,vF,bF,yF,EF;class eM extends $P{constructor(e){super(),Ah.add(this),Pb.set(this,void 0),Eu.set(this,void 0),Mb.set(this,void 0),zt(this,Pb,e)}static createResponse(e,t,r){const i=new eM(t);return i._run(()=>i._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createOrRetrieveResponse(e,t,r){const i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),Le(this,Ah,"m",vF).call(this);let a,s=null;"response_id"in t?(a=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),s=t.starting_after??null):a=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const o of a)Le(this,Ah,"m",bF).call(this,o,s);if(a.controller.signal?.aborted)throw new So;return Le(this,Ah,"m",yF).call(this)}[(Pb=new WeakMap,Eu=new WeakMap,Mb=new WeakMap,Ah=new WeakSet,vF=function(){this.ended||zt(this,Eu,void 0)},bF=function(t,r){if(this.ended)return;const i=(s,o)=>{(r==null||o.sequence_number>r)&&this._emit(s,o)},a=Le(this,Ah,"m",EF).call(this,t);switch(i("event",t),t.type){case"response.output_text.delta":{const s=a.output[t.output_index];if(!s)throw new Ot(`missing output at index ${t.output_index}`);if(s.type==="message"){const o=s.content[t.content_index];if(!o)throw new Ot(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new Ot(`expected content to be 'output_text', got ${o.type}`);i("response.output_text.delta",{...t,snapshot:o.text})}break}case"response.function_call_arguments.delta":{const s=a.output[t.output_index];if(!s)throw new Ot(`missing output at index ${t.output_index}`);s.type==="function_call"&&i("response.function_call_arguments.delta",{...t,snapshot:s.arguments});break}default:i(t.type,t);break}},yF=function(){if(this.ended)throw new Ot("stream has ended, this shouldn't happen");const t=Le(this,Eu,"f");if(!t)throw new Ot("request ended without sending any events");zt(this,Eu,void 0);const r=mme(t,Le(this,Pb,"f"));return zt(this,Mb,r),r},EF=function(t){let r=Le(this,Eu,"f");if(!r){if(t.type!=="response.created")throw new Ot(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=zt(this,Eu,t.response),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{const i=r.output[t.output_index];if(!i)throw new Ot(`missing output at index ${t.output_index}`);const a=i.type,s=t.part;a==="message"&&s.type!=="reasoning_text"?i.content.push(s):a==="reasoning"&&s.type==="reasoning_text"&&(i.content||(i.content=[]),i.content.push(s));break}case"response.output_text.delta":{const i=r.output[t.output_index];if(!i)throw new Ot(`missing output at index ${t.output_index}`);if(i.type==="message"){const a=i.content[t.content_index];if(!a)throw new Ot(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new Ot(`expected content to be 'output_text', got ${a.type}`);a.text+=t.delta}break}case"response.function_call_arguments.delta":{const i=r.output[t.output_index];if(!i)throw new Ot(`missing output at index ${t.output_index}`);i.type==="function_call"&&(i.arguments+=t.delta);break}case"response.reasoning_text.delta":{const i=r.output[t.output_index];if(!i)throw new Ot(`missing output at index ${t.output_index}`);if(i.type==="reasoning"){const a=i.content?.[t.content_index];if(!a)throw new Ot(`missing content at index ${t.content_index}`);if(a.type!=="reasoning_text")throw new Ot(`expected content to be 'reasoning_text', got ${a.type}`);a.text+=t.delta}break}case"response.completed":{zt(this,Eu,t.response);break}}return r},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",i=>{const a=t.shift();a?a.resolve(i):e.push(i)}),this.on("end",()=>{r=!0;for(const i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{r=!0;for(const a of t)a.reject(i);t.length=0}),this.on("error",i=>{r=!0;for(const a of t)a.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((a,s)=>t.push({resolve:a,reject:s})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=Le(this,Mb,"f");if(!e)throw new Ot("stream ended without producing a ChatCompletion");return e}}function mme(n,e){return cme(n,e)}class qK extends Pt{list(e,t={},r){return this._client.getAPIList(Ke`/responses/${e}/input_items`,ui,{query:t,...r})}}class HK extends Pt{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class ZT extends Pt{constructor(){super(...arguments),this.inputItems=new qK(this._client),this.inputTokens=new HK(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&TN(r),r))}retrieve(e,t={},r){return this._client.get(Ke`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(i=>("object"in i&&i.object==="response"&&TN(i),i))}delete(e,t){return this._client.delete(Ke`/responses/${e}`,{...t,headers:Tt([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>zK(r,e))}stream(e,t){return eM.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(Ke`/responses/${e}/cancel`,t)}compact(e={},t){return this._client.post("/responses/compact",{body:e,...t})}}ZT.InputItems=qK;ZT.InputTokens=HK;class VK extends Pt{create(e,t,r){return this._client.post(Ke`/uploads/${e}/parts`,xp({body:t,...r},this._client))}}class tM extends Pt{constructor(){super(...arguments),this.parts=new VK(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(Ke`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(Ke`/uploads/${e}/complete`,{body:t,...r})}}tM.Parts=VK;const gme=async n=>{const e=await Promise.allSettled(n),t=e.filter(i=>i.status==="rejected");if(t.length){for(const i of t)console.error(i.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}const r=[];for(const i of e)i.status==="fulfilled"&&r.push(i.value);return r};class YK extends Pt{create(e,t,r){return this._client.post(Ke`/vector_stores/${e}/file_batches`,{body:t,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{vector_store_id:i}=t;return this._client.get(Ke`/vector_stores/${i}/file_batches/${e}`,{...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){const{vector_store_id:i}=t;return this._client.post(Ke`/vector_stores/${i}/file_batches/${e}/cancel`,{...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){const i=await this.create(e,t);return await this.poll(e,i.id,r)}listFiles(e,t,r){const{vector_store_id:i,...a}=t;return this._client.getAPIList(Ke`/vector_stores/${i}/file_batches/${e}/files`,ui,{query:a,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){const i=Tt([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:s}=await this.retrieve(t,{vector_store_id:e},{...r,headers:i}).withResponse();switch(a.status){case"in_progress":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{const l=s.headers.get("openai-poll-after-ms");if(l){const c=parseInt(l);isNaN(c)||(o=c)}}await Tv(o);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},i){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=i?.maxConcurrency??5,s=Math.min(a,t.length),o=this._client,l=t.values(),c=[...r];async function u(p){for(let h of p){const f=await o.files.create({file:h,purpose:"assistants"},i);c.push(f.id)}}const d=Array(s).fill(l).map(u);return await gme(d),await this.createAndPoll(e,{file_ids:c})}}let KK=class extends Pt{create(e,t,r){return this._client.post(Ke`/vector_stores/${e}/files`,{body:t,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{vector_store_id:i}=t;return this._client.get(Ke`/vector_stores/${i}/files/${e}`,{...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{vector_store_id:i,...a}=t;return this._client.post(Ke`/vector_stores/${i}/files/${e}`,{body:a,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(Ke`/vector_stores/${e}/files`,ui,{query:t,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){const{vector_store_id:i}=t;return this._client.delete(Ke`/vector_stores/${i}/files/${e}`,{...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){const i=await this.create(e,t,r);return await this.poll(e,i.id,r)}async poll(e,t,r){const i=Tt([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const a=await this.retrieve(t,{vector_store_id:e},{...r,headers:i}).withResponse(),s=a.data;switch(s.status){case"in_progress":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{const l=a.response.headers.get("openai-poll-after-ms");if(l){const c=parseInt(l);isNaN(c)||(o=c)}}await Tv(o);break;case"failed":case"completed":return s}}}async upload(e,t,r){const i=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:i.id},r)}async uploadAndPoll(e,t,r){const i=await this.upload(e,t,r);return await this.poll(e,i.id,r)}content(e,t,r){const{vector_store_id:i}=t;return this._client.getAPIList(Ke`/vector_stores/${i}/files/${e}/content`,YT,{...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};class JT extends Pt{constructor(){super(...arguments),this.files=new KK(this._client),this.fileBatches=new YK(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(Ke`/vector_stores/${e}`,{...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(Ke`/vector_stores/${e}`,{body:t,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",ui,{query:e,...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(Ke`/vector_stores/${e}`,{...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(Ke`/vector_stores/${e}/search`,YT,{body:t,method:"post",...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}JT.Files=KK;JT.FileBatches=YK;class QK extends Pt{create(e,t){return this._client.post("/videos",sF({body:e,...t},this._client))}retrieve(e,t){return this._client.get(Ke`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",DS,{query:e,...t})}delete(e,t){return this._client.delete(Ke`/videos/${e}`,t)}downloadContent(e,t={},r){return this._client.get(Ke`/videos/${e}/content`,{query:t,...r,headers:Tt([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,t,r){return this._client.post(Ke`/videos/${e}/remix`,sF({body:t,...r},this._client))}}var zh,jK,HE;class XK extends Pt{constructor(){super(...arguments),zh.add(this)}async unwrap(e,t,r=this._client.webhookSecret,i=300){return await this.verifySignature(e,t,r,i),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,i=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");Le(this,zh,"m",jK).call(this,r);const a=Tt([t]).values,s=Le(this,zh,"m",HE).call(this,a,"webhook-signature"),o=Le(this,zh,"m",HE).call(this,a,"webhook-timestamp"),l=Le(this,zh,"m",HE).call(this,a,"webhook-id"),c=parseInt(o,10);if(isNaN(c))throw new M0("Invalid webhook timestamp format");const u=Math.floor(Date.now()/1e3);if(u-c>i)throw new M0("Webhook timestamp is too old");if(c>u+i)throw new M0("Webhook timestamp is too new");const d=s.split(" ").map(m=>m.startsWith("v1,")?m.substring(3):m),p=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),h=l?`${l}.${o}.${e}`:`${o}.${e}`,f=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const m of d)try{const g=Buffer.from(m,"base64");if(await crypto.subtle.verify("HMAC",f,g,new TextEncoder().encode(h)))return}catch{continue}throw new M0("The given webhook signature does not match the expected signature")}}zh=new WeakSet,jK=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},HE=function(e,t){if(!e)throw new Error("Headers are required");const r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var wN,nM,VE,ZK;class un{constructor({baseURL:e=wc("OPENAI_BASE_URL"),apiKey:t=wc("OPENAI_API_KEY"),organization:r=wc("OPENAI_ORG_ID")??null,project:i=wc("OPENAI_PROJECT_ID")??null,webhookSecret:a=wc("OPENAI_WEBHOOK_SECRET")??null,...s}={}){if(wN.add(this),VE.set(this,void 0),this.completions=new AK(this),this.chat=new zP(this),this.embeddings=new IK(this),this.files=new DK(this),this.images=new UK(this),this.audio=new xv(this),this.moderations=new $K(this),this.models=new BK(this),this.fineTuning=new hm(this),this.graders=new JP(this),this.vectorStores=new JT(this),this.webhooks=new XK(this),this.beta=new pm(this),this.batches=new bK(this),this.uploads=new tM(this),this.responses=new ZT(this),this.realtime=new XT(this),this.conversations=new YP(this),this.evals=new QP(this),this.containers=new VP(this),this.videos=new QK(this),t===void 0)throw new Ot("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const o={apiKey:t,organization:r,project:i,webhookSecret:a,...s,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&_fe())throw new Ot(`It looks like you're running in a browser-like environment.
|
|
87
|
+
${Ob(n)}`);return{...A,id:x,type:w,function:{...N,name:D,arguments:C}}})}}:{...h,message:{..._,content:f,role:v,refusal:c.refusal??null},finish_reason:u,index:d,logprobs:p}}),created:i,model:a,object:"chat.completion",...s?{system_fingerprint:s}:{}};return Yfe(l,e)}function Ob(n){return JSON.stringify(n)}class US extends e_{static fromReadableStream(e){const t=new US(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){const i=new US(t),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,t,a)),i}}let WP=class extends Mt{constructor(){super(...arguments),this.messages=new KY(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(Ke`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(Ke`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",ui,{query:e,...t})}delete(e,t){return this._client.delete(Ke`/chat/completions/${e}`,t)}parse(e,t){return Xfe(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>BP(r,e))}runTools(e,t){return e.stream?US.runTools(this._client,e,t):GP.runTools(this._client,e,t)}stream(e,t){return e_.createChatCompletion(this._client,e,t)}};WP.Messages=KY;let zP=class extends Mt{constructor(){super(...arguments),this.completions=new WP(this._client)}};zP.Completions=WP;const mK=Symbol("brand.privateNullableHeaders");function*sme(n){if(!n)return;if(mK in n){const{values:r,nulls:i}=n;yield*r.entries();for(const a of i)yield[a,null];return}let e=!1,t;n instanceof Headers?t=n.entries():K5(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let r of t){const i=r[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");const a=K5(r[1])?r[1]:[r[1]];let s=!1;for(const o of a)o!==void 0&&(e&&!s&&(s=!0,yield[i,null]),yield[i,o])}}const Tt=n=>{const e=new Headers,t=new Set;for(const r of n){const i=new Set;for(const[a,s]of sme(r)){const o=a.toLowerCase();i.has(o)||(e.delete(a),i.add(o)),s===null?(e.delete(a),t.add(o)):(e.append(a,s),t.delete(o))}}return{[mK]:!0,values:e,nulls:t}};class gK extends Mt{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:Tt([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class _K extends Mt{create(e,t){return this._client.post("/audio/transcriptions",xp({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class vK extends Mt{create(e,t){return this._client.post("/audio/translations",xp({body:e,...t,__metadata:{model:e.model}},this._client))}}class xv extends Mt{constructor(){super(...arguments),this.transcriptions=new _K(this._client),this.translations=new vK(this._client),this.speech=new gK(this._client)}}xv.Transcriptions=_K;xv.Translations=vK;xv.Speech=gK;let bK=class extends Mt{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(Ke`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",ui,{query:e,...t})}cancel(e,t){return this._client.post(Ke`/batches/${e}/cancel`,t)}};class yK extends Mt{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(Ke`/assistants/${e}`,{...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(Ke`/assistants/${e}`,{body:t,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",ui,{query:e,...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(Ke`/assistants/${e}`,{...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let EK=class extends Mt{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};class SK extends Mt{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let KT=class extends Mt{constructor(){super(...arguments),this.sessions=new EK(this._client),this.transcriptionSessions=new SK(this._client)}};KT.Sessions=EK;KT.TranscriptionSessions=SK;class TK extends Mt{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:Tt([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(Ke`/chatkit/sessions/${e}/cancel`,{...t,headers:Tt([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}}let wK=class extends Mt{retrieve(e,t){return this._client.get(Ke`/chatkit/threads/${e}`,{...t,headers:Tt([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",DS,{query:e,...t,headers:Tt([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(Ke`/chatkit/threads/${e}`,{...t,headers:Tt([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(Ke`/chatkit/threads/${e}/items`,DS,{query:t,...r,headers:Tt([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}};class QT extends Mt{constructor(){super(...arguments),this.sessions=new TK(this._client),this.threads=new wK(this._client)}}QT.Sessions=TK;QT.Threads=wK;let xK=class extends Mt{create(e,t,r){return this._client.post(Ke`/threads/${e}/messages`,{body:t,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{thread_id:i}=t;return this._client.get(Ke`/threads/${i}/messages/${e}`,{...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{thread_id:i,...a}=t;return this._client.post(Ke`/threads/${i}/messages/${e}`,{body:a,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(Ke`/threads/${e}/messages`,ui,{query:t,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){const{thread_id:i}=t;return this._client.delete(Ke`/threads/${i}/messages/${e}`,{...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};class CK extends Mt{retrieve(e,t,r){const{thread_id:i,run_id:a,...s}=t;return this._client.get(Ke`/threads/${i}/runs/${a}/steps/${e}`,{query:s,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){const{thread_id:i,...a}=t;return this._client.getAPIList(Ke`/threads/${i}/runs/${e}/steps`,ui,{query:a,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}const ome=n=>{if(typeof Buffer<"u"){const e=Buffer.from(n,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(n),t=e.length,r=new Uint8Array(t);for(let i=0;i<t;i++)r[i]=e.charCodeAt(i);return Array.from(new Float32Array(r.buffer))}};var lme={};const wc=n=>{if(typeof globalThis.process<"u")return lme?.[n]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()};var Zi,rp,SN,Ul,WE,Vo,ip,tf,Qd,BS,Ps,zE,qE,fg,z0,q0,dF,pF,hF,fF,mF,gF,_F;class mg extends $P{constructor(){super(...arguments),Zi.add(this),SN.set(this,[]),Ul.set(this,{}),WE.set(this,{}),Vo.set(this,void 0),ip.set(this,void 0),tf.set(this,void 0),Qd.set(this,void 0),BS.set(this,void 0),Ps.set(this,void 0),zE.set(this,void 0),qE.set(this,void 0),fg.set(this,void 0)}[(SN=new WeakMap,Ul=new WeakMap,WE=new WeakMap,Vo=new WeakMap,ip=new WeakMap,tf=new WeakMap,Qd=new WeakMap,BS=new WeakMap,Ps=new WeakMap,zE=new WeakMap,qE=new WeakMap,fg=new WeakMap,Zi=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",i=>{const a=t.shift();a?a.resolve(i):e.push(i)}),this.on("end",()=>{r=!0;for(const i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{r=!0;for(const a of t)a.reject(i);t.length=0}),this.on("error",i=>{r=!0;for(const a of t)a.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((a,s)=>t.push({resolve:a,reject:s})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new rp;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();const i=Jg.fromReadableStream(e,this.controller);for await(const a of i)Le(this,Zi,"m",z0).call(this,a);if(i.controller.signal?.aborted)throw new So;return this._addRun(Le(this,Zi,"m",q0).call(this))}toReadableStream(){return new Jg(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,i){const a=new rp;return a._run(()=>a._runToolAssistantStream(e,t,r,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,t,r,i){const a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const s={...r,stream:!0},o=await e.submitToolOutputs(t,s,{...i,signal:this.controller.signal});this._connected();for await(const l of o)Le(this,Zi,"m",z0).call(this,l);if(o.controller.signal?.aborted)throw new So;return this._addRun(Le(this,Zi,"m",q0).call(this))}static createThreadAssistantStream(e,t,r){const i=new rp;return i._run(()=>i._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}static createAssistantStream(e,t,r,i){const a=new rp;return a._run(()=>a._runAssistantStream(e,t,r,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return Le(this,zE,"f")}currentRun(){return Le(this,qE,"f")}currentMessageSnapshot(){return Le(this,Vo,"f")}currentRunStepSnapshot(){return Le(this,fg,"f")}async finalRunSteps(){return await this.done(),Object.values(Le(this,Ul,"f"))}async finalMessages(){return await this.done(),Object.values(Le(this,WE,"f"))}async finalRun(){if(await this.done(),!Le(this,ip,"f"))throw Error("Final run was not received.");return Le(this,ip,"f")}async _createThreadAssistantStream(e,t,r){const i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const a={...t,stream:!0},s=await e.createAndRun(a,{...r,signal:this.controller.signal});this._connected();for await(const o of s)Le(this,Zi,"m",z0).call(this,o);if(s.controller.signal?.aborted)throw new So;return this._addRun(Le(this,Zi,"m",q0).call(this))}async _createAssistantStream(e,t,r,i){const a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const s={...r,stream:!0},o=await e.create(t,s,{...i,signal:this.controller.signal});this._connected();for await(const l of o)Le(this,Zi,"m",z0).call(this,l);if(o.controller.signal?.aborted)throw new So;return this._addRun(Le(this,Zi,"m",q0).call(this))}static accumulateDelta(e,t){for(const[r,i]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=i;continue}let a=e[r];if(a==null){e[r]=i;continue}if(r==="index"||r==="type"){e[r]=i;continue}if(typeof a=="string"&&typeof i=="string")a+=i;else if(typeof a=="number"&&typeof i=="number")a+=i;else if(FE(a)&&FE(i))a=this.accumulateDelta(a,i);else if(Array.isArray(a)&&Array.isArray(i)){if(a.every(s=>typeof s=="string"||typeof s=="number")){a.push(...i);continue}for(const s of i){if(!FE(s))throw new Error(`Expected array delta entry to be an object but got: ${s}`);const o=s.index;if(o==null)throw console.error(s),new Error("Expected array delta entry to have an `index` property");if(typeof o!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${o}`);const l=a[o];l==null?a.push(s):a[o]=this.accumulateDelta(l,s)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${i}, accValue: ${a}`);e[r]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,i){return await this._createAssistantStream(t,e,r,i)}async _runToolAssistantStream(e,t,r,i){return await this._createToolAssistantStream(t,e,r,i)}}rp=mg,z0=function(e){if(!this.ended)switch(zt(this,zE,e),Le(this,Zi,"m",hF).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":Le(this,Zi,"m",_F).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Le(this,Zi,"m",pF).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":Le(this,Zi,"m",dF).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},q0=function(){if(this.ended)throw new Ot("stream has ended, this shouldn't happen");if(!Le(this,ip,"f"))throw Error("Final run has not been received");return Le(this,ip,"f")},dF=function(e){const[t,r]=Le(this,Zi,"m",mF).call(this,e,Le(this,Vo,"f"));zt(this,Vo,t),Le(this,WE,"f")[t.id]=t;for(const i of r){const a=t.content[i.index];a?.type=="text"&&this._emit("textCreated",a.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const i of e.data.delta.content){if(i.type=="text"&&i.text){let a=i.text,s=t.content[i.index];if(s&&s.type=="text")this._emit("textDelta",a,s.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(i.index!=Le(this,tf,"f")){if(Le(this,Qd,"f"))switch(Le(this,Qd,"f").type){case"text":this._emit("textDone",Le(this,Qd,"f").text,Le(this,Vo,"f"));break;case"image_file":this._emit("imageFileDone",Le(this,Qd,"f").image_file,Le(this,Vo,"f"));break}zt(this,tf,i.index)}zt(this,Qd,t.content[i.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(Le(this,tf,"f")!==void 0){const i=e.data.content[Le(this,tf,"f")];if(i)switch(i.type){case"image_file":this._emit("imageFileDone",i.image_file,Le(this,Vo,"f"));break;case"text":this._emit("textDone",i.text,Le(this,Vo,"f"));break}}Le(this,Vo,"f")&&this._emit("messageDone",e.data),zt(this,Vo,void 0)}},pF=function(e){const t=Le(this,Zi,"m",fF).call(this,e);switch(zt(this,fg,t),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const a of r.step_details.tool_calls)a.index==Le(this,BS,"f")?this._emit("toolCallDelta",a,t.step_details.tool_calls[a.index]):(Le(this,Ps,"f")&&this._emit("toolCallDone",Le(this,Ps,"f")),zt(this,BS,a.index),zt(this,Ps,t.step_details.tool_calls[a.index]),Le(this,Ps,"f")&&this._emit("toolCallCreated",Le(this,Ps,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":zt(this,fg,void 0),e.data.step_details.type=="tool_calls"&&Le(this,Ps,"f")&&(this._emit("toolCallDone",Le(this,Ps,"f")),zt(this,Ps,void 0)),this._emit("runStepDone",e.data,t);break}},hF=function(e){Le(this,SN,"f").push(e),this._emit("event",e)},fF=function(e){switch(e.event){case"thread.run.step.created":return Le(this,Ul,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=Le(this,Ul,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){const i=rp.accumulateDelta(t,r.delta);Le(this,Ul,"f")[e.data.id]=i}return Le(this,Ul,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":Le(this,Ul,"f")[e.data.id]=e.data;break}if(Le(this,Ul,"f")[e.data.id])return Le(this,Ul,"f")[e.data.id];throw new Error("No snapshot available")},mF=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let i=e.data;if(i.delta.content)for(const a of i.delta.content)if(a.index in t.content){let s=t.content[a.index];t.content[a.index]=Le(this,Zi,"m",gF).call(this,a,s)}else t.content[a.index]=a,r.push(a);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},gF=function(e,t){return rp.accumulateDelta(t,e)},_F=function(e){switch(zt(this,qE,e.data),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":zt(this,ip,e.data),Le(this,Ps,"f")&&(this._emit("toolCallDone",Le(this,Ps,"f")),zt(this,Ps,void 0));break}};let qP=class extends Mt{constructor(){super(...arguments),this.steps=new CK(this._client)}create(e,t,r){const{include:i,...a}=t;return this._client.post(Ke`/threads/${e}/runs`,{query:{include:i},body:a,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}retrieve(e,t,r){const{thread_id:i}=t;return this._client.get(Ke`/threads/${i}/runs/${e}`,{...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{thread_id:i,...a}=t;return this._client.post(Ke`/threads/${i}/runs/${e}`,{body:a,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(Ke`/threads/${e}/runs`,ui,{query:t,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){const{thread_id:i}=t;return this._client.post(Ke`/threads/${i}/runs/${e}/cancel`,{...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){const i=await this.create(e,t,r);return await this.poll(i.id,{thread_id:e},r)}createAndStream(e,t,r){return mg.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){const i=Tt([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:s}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...i}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{const l=s.headers.get("openai-poll-after-ms");if(l){const c=parseInt(l);isNaN(c)||(o=c)}}await Tv(o);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,t,r){return mg.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){const{thread_id:i,...a}=t;return this._client.post(Ke`/threads/${i}/runs/${e}/submit_tool_outputs`,{body:a,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,r){const i=await this.submitToolOutputs(e,t,r);return await this.poll(i.id,t,r)}submitToolOutputsStream(e,t,r){return mg.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};qP.Steps=CK;class jT extends Mt{constructor(){super(...arguments),this.runs=new qP(this._client),this.messages=new xK(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(Ke`/threads/${e}`,{...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(Ke`/threads/${e}`,{body:t,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(Ke`/threads/${e}`,{...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){const r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return mg.createThreadAssistantStream(e,this._client.beta.threads,t)}}jT.Runs=qP;jT.Messages=xK;class pm extends Mt{constructor(){super(...arguments),this.realtime=new KT(this._client),this.chatkit=new QT(this._client),this.assistants=new yK(this._client),this.threads=new jT(this._client)}}pm.Realtime=KT;pm.ChatKit=QT;pm.Assistants=yK;pm.Threads=jT;class AK extends Mt{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class RK extends Mt{retrieve(e,t,r){const{container_id:i}=t;return this._client.get(Ke`/containers/${i}/files/${e}/content`,{...r,headers:Tt([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}let HP=class extends Mt{constructor(){super(...arguments),this.content=new RK(this._client)}create(e,t,r){return this._client.post(Ke`/containers/${e}/files`,xp({body:t,...r},this._client))}retrieve(e,t,r){const{container_id:i}=t;return this._client.get(Ke`/containers/${i}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(Ke`/containers/${e}/files`,ui,{query:t,...r})}delete(e,t,r){const{container_id:i}=t;return this._client.delete(Ke`/containers/${i}/files/${e}`,{...r,headers:Tt([{Accept:"*/*"},r?.headers])})}};HP.Content=RK;class VP extends Mt{constructor(){super(...arguments),this.files=new HP(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(Ke`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",ui,{query:e,...t})}delete(e,t){return this._client.delete(Ke`/containers/${e}`,{...t,headers:Tt([{Accept:"*/*"},t?.headers])})}}VP.Files=HP;class kK extends Mt{create(e,t,r){const{include:i,...a}=t;return this._client.post(Ke`/conversations/${e}/items`,{query:{include:i},body:a,...r})}retrieve(e,t,r){const{conversation_id:i,...a}=t;return this._client.get(Ke`/conversations/${i}/items/${e}`,{query:a,...r})}list(e,t={},r){return this._client.getAPIList(Ke`/conversations/${e}/items`,DS,{query:t,...r})}delete(e,t,r){const{conversation_id:i}=t;return this._client.delete(Ke`/conversations/${i}/items/${e}`,r)}}class YP extends Mt{constructor(){super(...arguments),this.items=new kK(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(Ke`/conversations/${e}`,t)}update(e,t,r){return this._client.post(Ke`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(Ke`/conversations/${e}`,t)}}YP.Items=kK;class IK extends Mt{create(e,t){const r=!!e.encoding_format;let i=r?e.encoding_format:"base64";r&&Xi(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const a=this._client.post("/embeddings",{body:{...e,encoding_format:i},...t});return r?a:(Xi(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(s=>(s&&s.data&&s.data.forEach(o=>{const l=o.embedding;o.embedding=ome(l)}),s)))}}class NK extends Mt{retrieve(e,t,r){const{eval_id:i,run_id:a}=t;return this._client.get(Ke`/evals/${i}/runs/${a}/output_items/${e}`,r)}list(e,t,r){const{eval_id:i,...a}=t;return this._client.getAPIList(Ke`/evals/${i}/runs/${e}/output_items`,ui,{query:a,...r})}}class KP extends Mt{constructor(){super(...arguments),this.outputItems=new NK(this._client)}create(e,t,r){return this._client.post(Ke`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){const{eval_id:i}=t;return this._client.get(Ke`/evals/${i}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(Ke`/evals/${e}/runs`,ui,{query:t,...r})}delete(e,t,r){const{eval_id:i}=t;return this._client.delete(Ke`/evals/${i}/runs/${e}`,r)}cancel(e,t,r){const{eval_id:i}=t;return this._client.post(Ke`/evals/${i}/runs/${e}`,r)}}KP.OutputItems=NK;class QP extends Mt{constructor(){super(...arguments),this.runs=new KP(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(Ke`/evals/${e}`,t)}update(e,t,r){return this._client.post(Ke`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",ui,{query:e,...t})}delete(e,t){return this._client.delete(Ke`/evals/${e}`,t)}}QP.Runs=KP;let DK=class extends Mt{create(e,t){return this._client.post("/files",xp({body:e,...t},this._client))}retrieve(e,t){return this._client.get(Ke`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",ui,{query:e,...t})}delete(e,t){return this._client.delete(Ke`/files/${e}`,t)}content(e,t){return this._client.get(Ke`/files/${e}/content`,{...t,headers:Tt([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=1800*1e3}={}){const i=new Set(["processed","error","deleted"]),a=Date.now();let s=await this.retrieve(e);for(;!s.status||!i.has(s.status);)if(await Tv(t),s=await this.retrieve(e),Date.now()-a>r)throw new PP({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return s}};class OK extends Mt{}let PK=class extends Mt{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class jP extends Mt{constructor(){super(...arguments),this.graders=new PK(this._client)}}jP.Graders=PK;class MK extends Mt{create(e,t,r){return this._client.getAPIList(Ke`/fine_tuning/checkpoints/${e}/permissions`,YT,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(Ke`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){const{fine_tuned_model_checkpoint:i}=t;return this._client.delete(Ke`/fine_tuning/checkpoints/${i}/permissions/${e}`,r)}}let XP=class extends Mt{constructor(){super(...arguments),this.permissions=new MK(this._client)}};XP.Permissions=MK;class LK extends Mt{list(e,t={},r){return this._client.getAPIList(Ke`/fine_tuning/jobs/${e}/checkpoints`,ui,{query:t,...r})}}class ZP extends Mt{constructor(){super(...arguments),this.checkpoints=new LK(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(Ke`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",ui,{query:e,...t})}cancel(e,t){return this._client.post(Ke`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(Ke`/fine_tuning/jobs/${e}/events`,ui,{query:t,...r})}pause(e,t){return this._client.post(Ke`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(Ke`/fine_tuning/jobs/${e}/resume`,t)}}ZP.Checkpoints=LK;class hm extends Mt{constructor(){super(...arguments),this.methods=new OK(this._client),this.jobs=new ZP(this._client),this.checkpoints=new XP(this._client),this.alpha=new jP(this._client)}}hm.Methods=OK;hm.Jobs=ZP;hm.Checkpoints=XP;hm.Alpha=jP;class FK extends Mt{}class JP extends Mt{constructor(){super(...arguments),this.graderModels=new FK(this._client)}}JP.GraderModels=FK;class UK extends Mt{createVariation(e,t){return this._client.post("/images/variations",xp({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",xp({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}let BK=class extends Mt{retrieve(e,t){return this._client.get(Ke`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",YT,e)}delete(e,t){return this._client.delete(Ke`/models/${e}`,t)}};class $K extends Mt{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class GK extends Mt{accept(e,t,r){return this._client.post(Ke`/realtime/calls/${e}/accept`,{body:t,...r,headers:Tt([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(Ke`/realtime/calls/${e}/hangup`,{...t,headers:Tt([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(Ke`/realtime/calls/${e}/refer`,{body:t,...r,headers:Tt([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(Ke`/realtime/calls/${e}/reject`,{body:t,...r,headers:Tt([{Accept:"*/*"},r?.headers])})}}class WK extends Mt{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class XT extends Mt{constructor(){super(...arguments),this.clientSecrets=new WK(this._client),this.calls=new GK(this._client)}}XT.ClientSecrets=WK;XT.Calls=GK;function cme(n,e){return!e||!dme(e)?{...n,output_parsed:null,output:n.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:zK(n,e)}function zK(n,e){const t=n.output.map(i=>{if(i.type==="function_call")return{...i,parsed_arguments:fme(e,i)};if(i.type==="message"){const a=i.content.map(s=>s.type==="output_text"?{...s,parsed:ume(e,s.text)}:s);return{...i,content:a}}return i}),r=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||TN(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(const i of r.output)if(i.type==="message"){for(const a of i.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),r}function ume(n,e){return n.text?.format?.type!=="json_schema"?null:"$parseRaw"in n.text?.format?(n.text?.format).$parseRaw(e):JSON.parse(e)}function dme(n){return!!UP(n.text?.format)}function pme(n){return n?.$brand==="auto-parseable-tool"}function hme(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function fme(n,e){const t=hme(n.tools??[],e.name);return{...e,...e,parsed_arguments:pme(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function TN(n){const e=[];for(const t of n.output)if(t.type==="message")for(const r of t.content)r.type==="output_text"&&e.push(r.text);n.output_text=e.join("")}var Ah,Pb,Eu,Mb,vF,bF,yF,EF;class eM extends $P{constructor(e){super(),Ah.add(this),Pb.set(this,void 0),Eu.set(this,void 0),Mb.set(this,void 0),zt(this,Pb,e)}static createResponse(e,t,r){const i=new eM(t);return i._run(()=>i._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createOrRetrieveResponse(e,t,r){const i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),Le(this,Ah,"m",vF).call(this);let a,s=null;"response_id"in t?(a=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),s=t.starting_after??null):a=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const o of a)Le(this,Ah,"m",bF).call(this,o,s);if(a.controller.signal?.aborted)throw new So;return Le(this,Ah,"m",yF).call(this)}[(Pb=new WeakMap,Eu=new WeakMap,Mb=new WeakMap,Ah=new WeakSet,vF=function(){this.ended||zt(this,Eu,void 0)},bF=function(t,r){if(this.ended)return;const i=(s,o)=>{(r==null||o.sequence_number>r)&&this._emit(s,o)},a=Le(this,Ah,"m",EF).call(this,t);switch(i("event",t),t.type){case"response.output_text.delta":{const s=a.output[t.output_index];if(!s)throw new Ot(`missing output at index ${t.output_index}`);if(s.type==="message"){const o=s.content[t.content_index];if(!o)throw new Ot(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new Ot(`expected content to be 'output_text', got ${o.type}`);i("response.output_text.delta",{...t,snapshot:o.text})}break}case"response.function_call_arguments.delta":{const s=a.output[t.output_index];if(!s)throw new Ot(`missing output at index ${t.output_index}`);s.type==="function_call"&&i("response.function_call_arguments.delta",{...t,snapshot:s.arguments});break}default:i(t.type,t);break}},yF=function(){if(this.ended)throw new Ot("stream has ended, this shouldn't happen");const t=Le(this,Eu,"f");if(!t)throw new Ot("request ended without sending any events");zt(this,Eu,void 0);const r=mme(t,Le(this,Pb,"f"));return zt(this,Mb,r),r},EF=function(t){let r=Le(this,Eu,"f");if(!r){if(t.type!=="response.created")throw new Ot(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=zt(this,Eu,t.response),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{const i=r.output[t.output_index];if(!i)throw new Ot(`missing output at index ${t.output_index}`);const a=i.type,s=t.part;a==="message"&&s.type!=="reasoning_text"?i.content.push(s):a==="reasoning"&&s.type==="reasoning_text"&&(i.content||(i.content=[]),i.content.push(s));break}case"response.output_text.delta":{const i=r.output[t.output_index];if(!i)throw new Ot(`missing output at index ${t.output_index}`);if(i.type==="message"){const a=i.content[t.content_index];if(!a)throw new Ot(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new Ot(`expected content to be 'output_text', got ${a.type}`);a.text+=t.delta}break}case"response.function_call_arguments.delta":{const i=r.output[t.output_index];if(!i)throw new Ot(`missing output at index ${t.output_index}`);i.type==="function_call"&&(i.arguments+=t.delta);break}case"response.reasoning_text.delta":{const i=r.output[t.output_index];if(!i)throw new Ot(`missing output at index ${t.output_index}`);if(i.type==="reasoning"){const a=i.content?.[t.content_index];if(!a)throw new Ot(`missing content at index ${t.content_index}`);if(a.type!=="reasoning_text")throw new Ot(`expected content to be 'reasoning_text', got ${a.type}`);a.text+=t.delta}break}case"response.completed":{zt(this,Eu,t.response);break}}return r},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",i=>{const a=t.shift();a?a.resolve(i):e.push(i)}),this.on("end",()=>{r=!0;for(const i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{r=!0;for(const a of t)a.reject(i);t.length=0}),this.on("error",i=>{r=!0;for(const a of t)a.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((a,s)=>t.push({resolve:a,reject:s})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=Le(this,Mb,"f");if(!e)throw new Ot("stream ended without producing a ChatCompletion");return e}}function mme(n,e){return cme(n,e)}class qK extends Mt{list(e,t={},r){return this._client.getAPIList(Ke`/responses/${e}/input_items`,ui,{query:t,...r})}}class HK extends Mt{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class ZT extends Mt{constructor(){super(...arguments),this.inputItems=new qK(this._client),this.inputTokens=new HK(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&TN(r),r))}retrieve(e,t={},r){return this._client.get(Ke`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(i=>("object"in i&&i.object==="response"&&TN(i),i))}delete(e,t){return this._client.delete(Ke`/responses/${e}`,{...t,headers:Tt([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>zK(r,e))}stream(e,t){return eM.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(Ke`/responses/${e}/cancel`,t)}compact(e={},t){return this._client.post("/responses/compact",{body:e,...t})}}ZT.InputItems=qK;ZT.InputTokens=HK;class VK extends Mt{create(e,t,r){return this._client.post(Ke`/uploads/${e}/parts`,xp({body:t,...r},this._client))}}class tM extends Mt{constructor(){super(...arguments),this.parts=new VK(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(Ke`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(Ke`/uploads/${e}/complete`,{body:t,...r})}}tM.Parts=VK;const gme=async n=>{const e=await Promise.allSettled(n),t=e.filter(i=>i.status==="rejected");if(t.length){for(const i of t)console.error(i.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}const r=[];for(const i of e)i.status==="fulfilled"&&r.push(i.value);return r};class YK extends Mt{create(e,t,r){return this._client.post(Ke`/vector_stores/${e}/file_batches`,{body:t,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{vector_store_id:i}=t;return this._client.get(Ke`/vector_stores/${i}/file_batches/${e}`,{...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){const{vector_store_id:i}=t;return this._client.post(Ke`/vector_stores/${i}/file_batches/${e}/cancel`,{...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){const i=await this.create(e,t);return await this.poll(e,i.id,r)}listFiles(e,t,r){const{vector_store_id:i,...a}=t;return this._client.getAPIList(Ke`/vector_stores/${i}/file_batches/${e}/files`,ui,{query:a,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){const i=Tt([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:s}=await this.retrieve(t,{vector_store_id:e},{...r,headers:i}).withResponse();switch(a.status){case"in_progress":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{const l=s.headers.get("openai-poll-after-ms");if(l){const c=parseInt(l);isNaN(c)||(o=c)}}await Tv(o);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},i){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=i?.maxConcurrency??5,s=Math.min(a,t.length),o=this._client,l=t.values(),c=[...r];async function u(p){for(let h of p){const f=await o.files.create({file:h,purpose:"assistants"},i);c.push(f.id)}}const d=Array(s).fill(l).map(u);return await gme(d),await this.createAndPoll(e,{file_ids:c})}}let KK=class extends Mt{create(e,t,r){return this._client.post(Ke`/vector_stores/${e}/files`,{body:t,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{vector_store_id:i}=t;return this._client.get(Ke`/vector_stores/${i}/files/${e}`,{...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{vector_store_id:i,...a}=t;return this._client.post(Ke`/vector_stores/${i}/files/${e}`,{body:a,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(Ke`/vector_stores/${e}/files`,ui,{query:t,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){const{vector_store_id:i}=t;return this._client.delete(Ke`/vector_stores/${i}/files/${e}`,{...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){const i=await this.create(e,t,r);return await this.poll(e,i.id,r)}async poll(e,t,r){const i=Tt([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const a=await this.retrieve(t,{vector_store_id:e},{...r,headers:i}).withResponse(),s=a.data;switch(s.status){case"in_progress":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{const l=a.response.headers.get("openai-poll-after-ms");if(l){const c=parseInt(l);isNaN(c)||(o=c)}}await Tv(o);break;case"failed":case"completed":return s}}}async upload(e,t,r){const i=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:i.id},r)}async uploadAndPoll(e,t,r){const i=await this.upload(e,t,r);return await this.poll(e,i.id,r)}content(e,t,r){const{vector_store_id:i}=t;return this._client.getAPIList(Ke`/vector_stores/${i}/files/${e}/content`,YT,{...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};class JT extends Mt{constructor(){super(...arguments),this.files=new KK(this._client),this.fileBatches=new YK(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(Ke`/vector_stores/${e}`,{...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(Ke`/vector_stores/${e}`,{body:t,...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",ui,{query:e,...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(Ke`/vector_stores/${e}`,{...t,headers:Tt([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(Ke`/vector_stores/${e}/search`,YT,{body:t,method:"post",...r,headers:Tt([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}JT.Files=KK;JT.FileBatches=YK;class QK extends Mt{create(e,t){return this._client.post("/videos",sF({body:e,...t},this._client))}retrieve(e,t){return this._client.get(Ke`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",DS,{query:e,...t})}delete(e,t){return this._client.delete(Ke`/videos/${e}`,t)}downloadContent(e,t={},r){return this._client.get(Ke`/videos/${e}/content`,{query:t,...r,headers:Tt([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,t,r){return this._client.post(Ke`/videos/${e}/remix`,sF({body:t,...r},this._client))}}var zh,jK,HE;class XK extends Mt{constructor(){super(...arguments),zh.add(this)}async unwrap(e,t,r=this._client.webhookSecret,i=300){return await this.verifySignature(e,t,r,i),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,i=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");Le(this,zh,"m",jK).call(this,r);const a=Tt([t]).values,s=Le(this,zh,"m",HE).call(this,a,"webhook-signature"),o=Le(this,zh,"m",HE).call(this,a,"webhook-timestamp"),l=Le(this,zh,"m",HE).call(this,a,"webhook-id"),c=parseInt(o,10);if(isNaN(c))throw new M0("Invalid webhook timestamp format");const u=Math.floor(Date.now()/1e3);if(u-c>i)throw new M0("Webhook timestamp is too old");if(c>u+i)throw new M0("Webhook timestamp is too new");const d=s.split(" ").map(m=>m.startsWith("v1,")?m.substring(3):m),p=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),h=l?`${l}.${o}.${e}`:`${o}.${e}`,f=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const m of d)try{const g=Buffer.from(m,"base64");if(await crypto.subtle.verify("HMAC",f,g,new TextEncoder().encode(h)))return}catch{continue}throw new M0("The given webhook signature does not match the expected signature")}}zh=new WeakSet,jK=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},HE=function(e,t){if(!e)throw new Error("Headers are required");const r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var wN,nM,VE,ZK;class un{constructor({baseURL:e=wc("OPENAI_BASE_URL"),apiKey:t=wc("OPENAI_API_KEY"),organization:r=wc("OPENAI_ORG_ID")??null,project:i=wc("OPENAI_PROJECT_ID")??null,webhookSecret:a=wc("OPENAI_WEBHOOK_SECRET")??null,...s}={}){if(wN.add(this),VE.set(this,void 0),this.completions=new AK(this),this.chat=new zP(this),this.embeddings=new IK(this),this.files=new DK(this),this.images=new UK(this),this.audio=new xv(this),this.moderations=new $K(this),this.models=new BK(this),this.fineTuning=new hm(this),this.graders=new JP(this),this.vectorStores=new JT(this),this.webhooks=new XK(this),this.beta=new pm(this),this.batches=new bK(this),this.uploads=new tM(this),this.responses=new ZT(this),this.realtime=new XT(this),this.conversations=new YP(this),this.evals=new QP(this),this.containers=new VP(this),this.videos=new QK(this),t===void 0)throw new Ot("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const o={apiKey:t,organization:r,project:i,webhookSecret:a,...s,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&_fe())throw new Ot(`It looks like you're running in a browser-like environment.
|
|
88
88
|
|
|
89
89
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
90
90
|
If you understand the risks and have appropriate mitigations in place,
|
|
@@ -126,7 +126,7 @@ ${s}`),r.push({type:"error",reason:i.stopReason,error:i}),r.end()}})(),r},USe=(n
|
|
|
126
126
|
If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body`);return i.stream()};return Object.assign(n,{transformToByteArray:t,transformToString:async i=>{const a=await t();if(i==="base64")return kp(a);if(i==="hex")return ps(a);if(i===void 0||i==="utf8"||i==="utf-8")return vm(a);if(typeof TextDecoder=="function")return new TextDecoder(i).decode(a);throw new Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(e)throw new Error(u9);if(e=!0,d9(n))return r(n);if(l9(n))return n;throw new Error(`Cannot transform payload to web stream, got ${n}`)}})},d9=n=>typeof Blob=="function"&&n instanceof Blob,V0=async(n=new Uint8Array,e)=>{if(n instanceof Uint8Array)return hp.mutate(n);if(!n)return hp.mutate(new Uint8Array);const t=e.streamCollector(n);return hp.mutate(await t)};function p9(n){return encodeURIComponent(n).replace(/[!'()*]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}const iC=n=>typeof n=="function"?n():n,ij=(n,e,t,r,i)=>({name:e,namespace:n,traits:t,input:r,output:i}),O1e=n=>(e,t)=>async r=>{const{response:i}=await e(r),{operationSchema:a}=_m(t),[,s,o,l,c,u]=a??[];try{const d=await n.protocol.deserializeResponse(ij(s,o,l,c,u),{...n,...t},i);return{response:i,output:d}}catch(d){if(Object.defineProperty(d,"$response",{value:i,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in d)){const p="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";try{d.message+=`
|
|
127
127
|
`+p}catch{!t.logger||t.logger?.constructor?.name==="NoOpLogger"?console.warn(p):t.logger?.warn?.(p)}typeof d.$responseBodyText<"u"&&d.$response&&(d.$response.body=d.$responseBodyText);try{if(Cp.isInstance(i)){const{headers:h={}}=i,f=Object.entries(h);d.$metadata={httpStatusCode:i.statusCode,requestId:aC(/^x-[\w-]+-request-?id$/,f),extendedRequestId:aC(/^x-[\w-]+-id-2$/,f),cfId:aC(/^x-[\w-]+-cf-id$/,f)}}}catch{}}throw d}},aC=(n,e)=>(e.find(([t])=>t.match(n))||[void 0,void 0])[1],P1e=n=>(e,t)=>async r=>{const{operationSchema:i}=_m(t),[,a,s,o,l,c]=i??[],u=t.endpointV2?.url&&n.urlParser?async()=>n.urlParser(t.endpointV2.url):n.endpoint,d=await n.protocol.serializeRequest(ij(a,s,o,l,c),r.input,{...n,...t,endpoint:u});return e({...r,request:d})},M1e={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},L1e={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function F1e(n){return{applyToStack:e=>{e.add(P1e(n),L1e),e.add(O1e(n),M1e),n.protocol.setSerdeContext(n)}}}function sf(n){if(typeof n=="object")return n;n=n|0;const e={};let t=0;for(const r of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])(n>>t++&1)===1&&(e[r]=1);return e}const h9={it:Symbol.for("@smithy/nor-struct-it")};class yr{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=yr.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(e,t){this.ref=e,this.memberName=t;const r=[];let i=e,a=e;for(this._isMemberSchema=!1;sC(i);)r.push(i[1]),i=i[0],a=iC(i),this._isMemberSchema=!0;if(r.length>0){this.memberTraits={};for(let s=r.length-1;s>=0;--s){const o=r[s];Object.assign(this.memberTraits,sf(o))}}else this.memberTraits=0;if(a instanceof yr){const s=this.memberTraits;Object.assign(this,a),this.memberTraits=Object.assign({},s,a.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=t??a.memberName;return}if(this.schema=iC(a),U1e(this.schema)?(this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3]):(this.name=this.memberName??String(a),this.traits=0),this._isMemberSchema&&!t)throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](e){const t=this.prototype.isPrototypeOf(e);return!t&&typeof e=="object"&&e!==null?e.symbol===this.symbol:t}static of(e){const t=iC(e);if(t instanceof yr)return t;if(sC(t)){const[r,i]=t;if(r instanceof yr)return Object.assign(r.getMergedTraits(),sf(i)),r;throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(e,null,2)}.`)}return new yr(t)}getSchema(){const e=this.schema;return Array.isArray(e)&&e[0]===0?e[4]:e}getName(e=!1){const{name:t}=this;return!e&&t&&t.includes("#")?t.split("#")[1]:t||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){const e=this.getSchema();return typeof e=="number"?e>=64&&e<128:e[0]===1}isMapSchema(){const e=this.getSchema();return typeof e=="number"?e>=128&&e<=255:e[0]===2}isStructSchema(){const e=this.getSchema();if(typeof e!="object")return!1;const t=e[0];return t===3||t===-3||t===4}isUnionSchema(){const e=this.getSchema();return typeof e!="object"?!1:e[0]===4}isBlobSchema(){const e=this.getSchema();return e===21||e===42}isTimestampSchema(){const e=this.getSchema();return typeof e=="number"&&e>=4&&e<=7}isUnitSchema(){return this.getSchema()==="unit"}isDocumentSchema(){return this.getSchema()===15}isStringSchema(){return this.getSchema()===0}isBooleanSchema(){return this.getSchema()===2}isNumericSchema(){return this.getSchema()===1}isBigIntegerSchema(){return this.getSchema()===17}isBigDecimalSchema(){return this.getSchema()===19}isStreaming(){const{streaming:e}=this.getMergedTraits();return!!e||this.getSchema()===42}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return sf(this.memberTraits)}getOwnTraits(){return sf(this.traits)}getKeySchema(){const[e,t]=[this.isDocumentSchema(),this.isMapSchema()];if(!e&&!t)throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);const r=this.getSchema(),i=e?15:r[4]??0;return p0([i,0],"key")}getValueSchema(){const e=this.getSchema(),[t,r,i]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],a=typeof e=="number"?63&e:e&&typeof e=="object"&&(r||i)?e[3+e[0]]:t?15:void 0;if(a!=null)return p0([a,0],r?"value":"member");throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(e){const t=this.getSchema();if(this.isStructSchema()&&t[4].includes(e)){const r=t[4].indexOf(e),i=t[5][r];return p0(sC(i)?i:[i,0],e)}if(this.isDocumentSchema())return p0([15,0],e);throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no no member=${e}.`)}getMemberSchemas(){const e={};try{for(const[t,r]of this.structIterator())e[t]=r}catch{}return e}getEventStreamMember(){if(this.isStructSchema()){for(const[e,t]of this.structIterator())if(t.isStreaming()&&t.isStructSchema())return e}return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw new Error("@smithy/core/schema - cannot iterate non-struct schema.");const e=this.getSchema(),t=e[4].length;let r=e[h9.it];if(r&&t===r.length){yield*r;return}r=Array(t);for(let i=0;i<t;++i){const a=e[4][i],s=p0([e[5][i],0],a);yield r[i]=[a,s]}e[h9.it]=r}}function p0(n,e){if(n instanceof yr)return Object.assign(n,{memberName:e,_isMemberSchema:!0});const t=yr;return new t(n,e)}const sC=n=>Array.isArray(n)&&n.length===2,U1e=n=>Array.isArray(n)&&n.length>=5;class cs{namespace;schemas;exceptions;static registries=new Map;constructor(e,t=new Map,r=new Map){this.namespace=e,this.schemas=t,this.exceptions=r}static for(e){return cs.registries.has(e)||cs.registries.set(e,new cs(e)),cs.registries.get(e)}copyFrom(e){const{schemas:t,exceptions:r}=this;for(const[i,a]of e.schemas)t.has(i)||t.set(i,a);for(const[i,a]of e.exceptions)r.has(i)||r.set(i,a)}register(e,t){const r=this.normalizeShapeId(e);for(const i of[this,cs.for(r.split("#")[0])])i.schemas.set(r,t)}getSchema(e){const t=this.normalizeShapeId(e);if(!this.schemas.has(t))throw new Error(`@smithy/core/schema - schema not found for ${t}`);return this.schemas.get(t)}registerError(e,t){const r=e,i=r[1];for(const a of[this,cs.for(i)])a.schemas.set(i+"#"+r[2],r),a.exceptions.set(r,t)}getErrorCtor(e){const t=e;return this.exceptions.has(t)?this.exceptions.get(t):cs.for(t[1]).exceptions.get(t)}getBaseException(){for(const e of this.exceptions.keys())if(Array.isArray(e)){const[,t,r]=e,i=t+"#"+r;if(i.startsWith("smithy.ts.sdk.synthetic.")&&i.endsWith("ServiceException"))return e}}find(e){return[...this.schemas.values()].find(e)}clear(){this.schemas.clear(),this.exceptions.clear()}normalizeShapeId(e){return e.includes("#")?e:this.namespace+"#"+e}}const qN=n=>{if(n!=null){if(typeof n=="string"){const e=parseFloat(n);if(!Number.isNaN(e))return String(e)!==String(n)&&Y1e.warn(V1e(`Expected number but observed string: ${n}`)),e}if(typeof n=="number")return n;throw new TypeError(`Expected number, got ${typeof n}: ${n}`)}},B1e=Math.ceil(2**127*(2-2**-23)),f9=n=>{const e=qN(n);if(e!==void 0&&!Number.isNaN(e)&&e!==1/0&&e!==-1/0&&Math.abs(e)>B1e)throw new TypeError(`Expected 32-bit float, got ${n}`);return e},$1e=n=>{if(n!=null){if(Number.isInteger(n)&&!Number.isNaN(n))return n;throw new TypeError(`Expected integer, got ${typeof n}: ${n}`)}},m9=n=>aj(n,16),g9=n=>aj(n,8),aj=(n,e)=>{const t=$1e(n);if(t!==void 0&&G1e(t,e)!==t)throw new TypeError(`Expected ${e}-bit integer, got ${n}`);return t},G1e=(n,e)=>{switch(e){case 32:return Int32Array.of(n)[0];case 16:return Int16Array.of(n)[0];case 8:return Int8Array.of(n)[0]}},W1e=n=>qN(typeof n=="string"?sw(n):n),z1e=n=>f9(typeof n=="string"?sw(n):n),q1e=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,sw=n=>{const e=n.match(q1e);if(e===null||e[0].length!==n.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(n)},YS=n=>m9(typeof n=="string"?sw(n):n),H1e=n=>g9(typeof n=="string"?sw(n):n),V1e=n=>String(new TypeError(n).stack||n).split(`
|
|
128
128
|
`).slice(0,5).filter(e=>!e.includes("stackTraceWarning")).join(`
|
|
129
|
-
`),Y1e={warn:console.warn},K1e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],yM=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function sj(n){const e=n.getUTCFullYear(),t=n.getUTCMonth(),r=n.getUTCDay(),i=n.getUTCDate(),a=n.getUTCHours(),s=n.getUTCMinutes(),o=n.getUTCSeconds(),l=i<10?`0${i}`:`${i}`,c=a<10?`0${a}`:`${a}`,u=s<10?`0${s}`:`${s}`,d=o<10?`0${o}`:`${o}`;return`${K1e[r]}, ${l} ${yM[t]} ${e} ${c}:${u}:${d} GMT`}const Q1e=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),j1e=n=>{if(n==null)return;if(typeof n!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");const e=Q1e.exec(n);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");const[t,r,i,a,s,o,l,c,u]=e,d=YS(s_(r)),p=zu(i,"month",1,12),h=zu(a,"day",1,31),f=ZE(d,p,h,{hours:s,minutes:o,seconds:l,fractionalMilliseconds:c});return u.toUpperCase()!="Z"&&f.setTime(f.getTime()-cTe(u)),f},X1e=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),Z1e=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),J1e=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),eTe=n=>{if(n==null)return;if(typeof n!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let e=X1e.exec(n);if(e){const[t,r,i,a,s,o,l,c]=e;return ZE(YS(s_(a)),oC(i),zu(r,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:c})}if(e=Z1e.exec(n),e){const[t,r,i,a,s,o,l,c]=e;return iTe(ZE(nTe(a),oC(i),zu(r,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:c}))}if(e=J1e.exec(n),e){const[t,r,i,a,s,o,l,c]=e;return ZE(YS(s_(c)),oC(r),zu(i.trimLeft(),"day",1,31),{hours:a,minutes:s,seconds:o,fractionalMilliseconds:l})}throw new TypeError("Invalid RFC-7231 date-time value")},tTe=n=>{if(n==null)return;let e;if(typeof n=="number")e=n;else if(typeof n=="string")e=W1e(n);else if(typeof n=="object"&&n.tag===1)e=n.value;else throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(e)||e===1/0||e===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(e*1e3))},ZE=(n,e,t,r)=>{const i=e-1;return sTe(n,i,t),new Date(Date.UTC(n,i,t,zu(r.hours,"hour",0,23),zu(r.minutes,"minute",0,59),zu(r.seconds,"seconds",0,60),lTe(r.fractionalMilliseconds)))},nTe=n=>{const e=new Date().getUTCFullYear(),t=Math.floor(e/100)*100+YS(s_(n));return t<e?t+100:t},rTe=50*365*24*60*60*1e3,iTe=n=>n.getTime()-new Date().getTime()>rTe?new Date(Date.UTC(n.getUTCFullYear()-100,n.getUTCMonth(),n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds())):n,oC=n=>{const e=yM.indexOf(n);if(e<0)throw new TypeError(`Invalid month: ${n}`);return e+1},aTe=[31,28,31,30,31,30,31,31,30,31,30,31],sTe=(n,e,t)=>{let r=aTe[e];if(e===1&&oTe(n)&&(r=29),t>r)throw new TypeError(`Invalid day for ${yM[e]} in ${n}: ${t}`)},oTe=n=>n%4===0&&(n%100!==0||n%400===0),zu=(n,e,t,r)=>{const i=H1e(s_(n));if(i<t||i>r)throw new TypeError(`${e} must be between ${t} and ${r}, inclusive`);return i},lTe=n=>n==null?0:z1e("0."+n)*1e3,cTe=n=>{const e=n[0];let t=1;if(e=="+")t=1;else if(e=="-")t=-1;else throw new TypeError(`Offset direction, ${e}, must be "+" or "-"`);const r=Number(n.substring(1,3)),i=Number(n.substring(4,6));return t*(r*60+i)*60*1e3},s_=n=>{let e=0;for(;e<n.length-1&&n.charAt(e)==="0";)e++;return e===0?n:n.slice(e)},_9=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ma=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0")),EM=()=>{if(_9)return _9();const n=new Uint8Array(16);return crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128,ma[n[0]]+ma[n[1]]+ma[n[2]]+ma[n[3]]+"-"+ma[n[4]]+ma[n[5]]+"-"+ma[n[6]]+ma[n[7]]+"-"+ma[n[8]]+ma[n[9]]+"-"+ma[n[10]]+ma[n[11]]+ma[n[12]]+ma[n[13]]+ma[n[14]]+ma[n[15]]},Vl=function(e){return Object.assign(new String(e),{deserializeJSON(){return JSON.parse(String(e))},toString(){return String(e)},toJSON(){return String(e)}})};Vl.from=n=>n&&typeof n=="object"&&(n instanceof Vl||"deserializeJSON"in n)?n:typeof n=="string"||Object.getPrototypeOf(n)===String.prototype?Vl(String(n)):Vl(JSON.stringify(n));Vl.fromObject=Vl.from;function uTe(n){return(n.includes(",")||n.includes('"'))&&(n=`"${n.replace(/"/g,'\\"')}"`),n}const SM="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",TM="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",wM="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",oj="(\\d?\\d)",lj="(\\d{4})",dTe=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),pTe=new RegExp(`^${SM}, ${oj} ${TM} ${lj} ${wM} GMT$`),hTe=new RegExp(`^${SM}, ${oj}-${TM}-(\\d\\d) ${wM} GMT$`),fTe=new RegExp(`^${SM} ${TM} ( [1-9]|\\d\\d) ${wM} ${lj}$`),mTe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],gTe=n=>{if(n==null)return;let e=NaN;if(typeof n=="number")e=n;else if(typeof n=="string"){if(!/^-?\d*\.?\d+$/.test(n))throw new TypeError("parseEpochTimestamp - numeric string invalid.");e=Number.parseFloat(n)}else typeof n=="object"&&n.tag===1&&(e=n.value);if(isNaN(e)||Math.abs(e)===1/0)throw new TypeError("Epoch timestamps must be valid finite numbers.");return new Date(Math.round(e*1e3))},_Te=n=>{if(n==null)return;if(typeof n!="string")throw new TypeError("RFC3339 timestamps must be strings");const e=dTe.exec(n);if(!e)throw new TypeError(`Invalid RFC3339 timestamp format ${n}`);const[,t,r,i,a,s,o,,l,c]=e;Ic(r,1,12),Ic(i,1,31),Ic(a,0,23),Ic(s,0,59),Ic(o,0,60);const u=new Date(Date.UTC(Number(t),Number(r)-1,Number(i),Number(a),Number(s),Number(o),Number(l)?Math.round(parseFloat(`0.${l}`)*1e3):0));if(u.setUTCFullYear(Number(t)),c.toUpperCase()!="Z"){const[,d,p,h]=/([+-])(\d\d):(\d\d)/.exec(c)||[void 0,"+",0,0],f=d==="-"?1:-1;u.setTime(u.getTime()+f*(Number(p)*60*60*1e3+Number(h)*60*1e3))}return u},vTe=n=>{if(n==null)return;if(typeof n!="string")throw new TypeError("RFC7231 timestamps must be strings.");let e,t,r,i,a,s,o,l;if((l=pTe.exec(n))?[,e,t,r,i,a,s,o]=l:(l=hTe.exec(n))?([,e,t,r,i,a,s,o]=l,r=(Number(r)+1900).toString()):(l=fTe.exec(n))&&([,t,e,i,a,s,o,r]=l),r&&s){const c=Date.UTC(Number(r),mTe.indexOf(t),Number(e),Number(i),Number(a),Number(s),o?Math.round(parseFloat(`0.${o}`)*1e3):0);Ic(e,1,31),Ic(i,0,23),Ic(a,0,59),Ic(s,0,60);const u=new Date(c);return u.setUTCFullYear(Number(r)),u}throw new TypeError(`Invalid RFC7231 date-time value ${n}.`)};function Ic(n,e,t){const r=Number(n);if(r<e||r>t)throw new Error(`Value ${r} out of range [${e}, ${t}]`)}function bTe(n,e,t){if(!Number.isInteger(t))throw new Error("Invalid number of delimiters ("+t+") for splitEvery.");const r=n.split(e),i=[];let a="";for(let s=0;s<r.length;s++)a===""?a=r[s]:a+=e+r[s],(s+1)%t===0&&(i.push(a),a="");return a!==""&&i.push(a),i}const cj=n=>{const e=n.length,t=[];let r=!1,i,a=0;for(let s=0;s<e;++s){const o=n[s];switch(o){case'"':i!=="\\"&&(r=!r);break;case",":r||(t.push(n.slice(a,s)),a=s+1);break}i=o}return t.push(n.slice(a)),t.map(s=>{s=s.trim();const o=s.length;return o<2?s:(s[0]==='"'&&s[o-1]==='"'&&(s=s.slice(1,o-1)),s.replace(/\\"/g,'"'))})},v9=/^-?\d*(\.\d+)?$/;class tl{string;type;constructor(e,t){if(this.string=e,this.type=t,!v9.test(e))throw new Error('@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".')}toString(){return this.string}static[Symbol.hasInstance](e){if(!e||typeof e!="object")return!1;const t=e;return tl.prototype.isPrototypeOf(e)||t.type==="bigDecimal"&&v9.test(t.string)}}class ow{serdeContext;setSerdeContext(e){this.serdeContext=e}}class yTe extends ow{options;compositeErrorRegistry;constructor(e){super(),this.options=e,this.compositeErrorRegistry=cs.for(e.defaultNamespace);for(const t of e.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(t)}getRequestType(){return Ka}getResponseType(){return Cp}setSerdeContext(e){this.serdeContext=e,this.serializer.setSerdeContext(e),this.deserializer.setSerdeContext(e),this.getPayloadCodec()&&this.getPayloadCodec().setSerdeContext(e)}updateServiceEndpoint(e,t){if("url"in t){e.protocol=t.url.protocol,e.hostname=t.url.hostname,e.port=t.url.port?Number(t.url.port):void 0,e.path=t.url.pathname,e.fragment=t.url.hash||void 0,e.username=t.url.username||void 0,e.password=t.url.password||void 0,e.query||(e.query={});for(const[r,i]of t.url.searchParams.entries())e.query[r]=i;return e}else return e.protocol=t.protocol,e.hostname=t.hostname,e.port=t.port?Number(t.port):void 0,e.path=t.path,e.query={...t.query},e}setHostPrefix(e,t,r){if(this.serdeContext?.disableHostPrefix)return;const i=yr.of(t.input),a=sf(t.traits??{});if(a.endpoint){let s=a.endpoint?.[0];if(typeof s=="string"){const o=[...i.structIterator()].filter(([,l])=>l.getMergedTraits().hostLabel);for(const[l]of o){const c=r[l];if(typeof c!="string")throw new Error(`@smithy/core/schema - ${l} in input must be a string as hostLabel.`);s=s.replace(`{${l}}`,c)}e.hostname=s+e.hostname}}}deserializeMetadata(e){return{httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream:e,requestSchema:t,initialRequest:r}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:e,requestSchema:t,initialRequest:r})}async deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:r}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:r})}async loadEventStreamCapability(){const{EventStreamSerde:e}=await _s(async()=>{const{EventStreamSerde:t}=await import("./index-CekVLaL6.js");return{EventStreamSerde:t}},[]);return new e({marshaller:this.getEventStreamMarshaller(),serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}getDefaultContentType(){throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(e,t,r,i,a){return[]}getEventStreamMarshaller(){const e=this.serdeContext;if(!e.eventStreamMarshaller)throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return e.eventStreamMarshaller}}class ETe extends yTe{async serializeRequest(e,t,r){const i={...t??{}},a=this.serializer,s={},o={},l=await r.endpoint(),c=yr.of(e?.input),u=[],d=[];let p=!1,h;const f=new Ka({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:s,headers:o,body:void 0});if(l){this.updateServiceEndpoint(f,l),this.setHostPrefix(f,e,i);const m=sf(e.traits);if(m.http){f.method=m.http[0];const[g,_]=m.http[1].split("?");f.path=="/"?f.path=g:f.path+=g;const v=new URLSearchParams(_??"");Object.assign(s,Object.fromEntries(v))}}for(const[m,g]of c.structIterator()){const _=g.getMergedTraits()??{},v=i[m];if(v==null&&!g.isIdempotencyToken()){if(_.httpLabel&&(f.path.includes(`{${m}+}`)||f.path.includes(`{${m}}`)))throw new Error(`No value provided for input HTTP label: ${m}.`);continue}if(_.httpPayload)g.isStreaming()?g.isStructSchema()?i[m]&&(h=await this.serializeEventStream({eventStream:i[m],requestSchema:c})):h=v:(a.write(g,v),h=a.flush()),delete i[m];else if(_.httpLabel){a.write(g,v);const b=a.flush();f.path.includes(`{${m}+}`)?f.path=f.path.replace(`{${m}+}`,b.split("/").map(p9).join("/")):f.path.includes(`{${m}}`)&&(f.path=f.path.replace(`{${m}}`,p9(b))),delete i[m]}else if(_.httpHeader)a.write(g,v),o[_.httpHeader.toLowerCase()]=String(a.flush()),delete i[m];else if(typeof _.httpPrefixHeaders=="string"){for(const[b,E]of Object.entries(v)){const S=_.httpPrefixHeaders+b;a.write([g.getValueSchema(),{httpHeader:S}],E),o[S.toLowerCase()]=a.flush()}delete i[m]}else _.httpQuery||_.httpQueryParams?(this.serializeQuery(g,v,s),delete i[m]):(p=!0,u.push(m),d.push(g))}if(p&&i){const[m,g]=(c.getName(!0)??"#Unknown").split("#"),_=c.getSchema()[6],v=[3,m,g,c.getMergedTraits(),u,d,void 0];_?v[6]=_:v.pop(),a.write(v,i),h=a.flush()}return f.headers=o,f.query=s,f.body=h,f}serializeQuery(e,t,r){const i=this.serializer,a=e.getMergedTraits();if(a.httpQueryParams){for(const[s,o]of Object.entries(t))if(!(s in r)){const l=e.getValueSchema();Object.assign(l.getMergedTraits(),{...a,httpQuery:s,httpQueryParams:void 0}),this.serializeQuery(l,o,r)}return}if(e.isListSchema()){const s=!!e.getMergedTraits().sparse,o=[];for(const l of t){i.write([e.getValueSchema(),a],l);const c=i.flush();(s||c!==void 0)&&o.push(c)}r[a.httpQuery]=o}else i.write([e,a],t),r[a.httpQuery]=i.flush()}async deserializeResponse(e,t,r){const i=this.deserializer,a=yr.of(e.output),s={};if(r.statusCode>=300){const l=await V0(r.body,t);throw l.byteLength>0&&Object.assign(s,await i.read(15,l)),await this.handleError(e,t,r,s,this.deserializeMetadata(r)),new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(const l in r.headers){const c=r.headers[l];delete r.headers[l],r.headers[l.toLowerCase()]=c}const o=await this.deserializeHttpMessage(a,t,r,s);if(o.length){const l=await V0(r.body,t);if(l.byteLength>0){const c=await i.read(a,l);for(const u of o)c[u]!=null&&(s[u]=c[u])}}else o.discardResponseBody&&await V0(r.body,t);return s.$metadata=this.deserializeMetadata(r),s}async deserializeHttpMessage(e,t,r,i,a){let s;i instanceof Set?s=a:s=i;let o=!0;const l=this.deserializer,c=yr.of(e),u=[];for(const[d,p]of c.structIterator()){const h=p.getMemberTraits();if(h.httpPayload){if(o=!1,p.isStreaming())p.isStructSchema()?s[d]=await this.deserializeEventStream({response:r,responseSchema:c}):s[d]=D1e(r.body);else if(r.body){const m=await V0(r.body,t);m.byteLength>0&&(s[d]=await l.read(p,m))}}else if(h.httpHeader){const f=String(h.httpHeader).toLowerCase(),m=r.headers[f];if(m!=null)if(p.isListSchema()){const g=p.getValueSchema();g.getMergedTraits().httpHeader=f;let _;g.isTimestampSchema()&&g.getSchema()===4?_=bTe(m,",",2):_=cj(m);const v=[];for(const b of _)v.push(await l.read(g,b.trim()));s[d]=v}else s[d]=await l.read(p,m)}else if(h.httpPrefixHeaders!==void 0){s[d]={};for(const[f,m]of Object.entries(r.headers))if(f.startsWith(h.httpPrefixHeaders)){const g=p.getValueSchema();g.getMergedTraits().httpHeader=f,s[d][f.slice(h.httpPrefixHeaders.length)]=await l.read(g,m)}}else h.httpResponseCode?s[d]=r.statusCode:u.push(d)}return u.discardResponseBody=o,u}}function lw(n,e){if(e.timestampFormat.useTrait&&n.isTimestampSchema()&&(n.getSchema()===5||n.getSchema()===6||n.getSchema()===7))return n.getSchema();const{httpLabel:t,httpPrefixHeaders:r,httpHeader:i,httpQuery:a}=n.getMergedTraits();return(e.httpBindings?typeof r=="string"||i?6:a||t?5:void 0:void 0)??e.timestampFormat.default}class STe extends ow{settings;constructor(e){super(),this.settings=e}read(e,t){const r=yr.of(e);if(r.isListSchema())return cj(t).map(i=>this.read(r.getValueSchema(),i));if(r.isBlobSchema())return(this.serdeContext?.base64Decoder??Ap)(t);if(r.isTimestampSchema())switch(lw(r,this.settings)){case 5:return _Te(t);case 6:return vTe(t);case 7:return gTe(t);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",t),new Date(t)}if(r.isStringSchema()){const i=r.getMergedTraits().mediaType;let a=t;if(i)return r.getMergedTraits().httpHeader&&(a=this.base64ToUtf8(a)),(i==="application/json"||i.endsWith("+json"))&&(a=Vl.from(a)),a}return r.isNumericSchema()?Number(t):r.isBigIntegerSchema()?BigInt(t):r.isBigDecimalSchema()?new tl(t,"bigDecimal"):r.isBooleanSchema()?String(t).toLowerCase()==="true":t}base64ToUtf8(e){return(this.serdeContext?.utf8Encoder??vm)((this.serdeContext?.base64Decoder??Ap)(e))}}class TTe extends ow{codecDeserializer;stringDeserializer;constructor(e,t){super(),this.codecDeserializer=e,this.stringDeserializer=new STe(t)}setSerdeContext(e){this.stringDeserializer.setSerdeContext(e),this.codecDeserializer.setSerdeContext(e),this.serdeContext=e}read(e,t){const r=yr.of(e),i=r.getMergedTraits(),a=this.serdeContext?.utf8Encoder??vm;if(i.httpHeader||i.httpResponseCode)return this.stringDeserializer.read(r,a(t));if(i.httpPayload){if(r.isBlobSchema()){const s=this.serdeContext?.utf8Decoder??Rp;return typeof t=="string"?s(t):t}else if(r.isStringSchema())return"byteLength"in t?a(t):t}return this.codecDeserializer.read(r,t)}}class wTe extends ow{settings;stringBuffer="";constructor(e){super(),this.settings=e}write(e,t){const r=yr.of(e);switch(typeof t){case"object":if(t===null){this.stringBuffer="null";return}if(r.isTimestampSchema()){if(!(t instanceof Date))throw new Error(`@smithy/core/protocols - received non-Date value ${t} when schema expected Date in ${r.getName(!0)}`);switch(lw(r,this.settings)){case 5:this.stringBuffer=t.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=sj(t);break;case 7:this.stringBuffer=String(t.getTime()/1e3);break;default:console.warn("Missing timestamp format, using epoch seconds",t),this.stringBuffer=String(t.getTime()/1e3)}return}if(r.isBlobSchema()&&"byteLength"in t){this.stringBuffer=(this.serdeContext?.base64Encoder??kp)(t);return}if(r.isListSchema()&&Array.isArray(t)){let s="";for(const o of t){this.write([r.getValueSchema(),r.getMergedTraits()],o);const l=this.flush(),c=r.getValueSchema().isTimestampSchema()?l:uTe(l);s!==""&&(s+=", "),s+=c}this.stringBuffer=s;return}this.stringBuffer=JSON.stringify(t,null,2);break;case"string":const i=r.getMergedTraits().mediaType;let a=t;if(i&&((i==="application/json"||i.endsWith("+json"))&&(a=Vl.from(a)),r.getMergedTraits().httpHeader)){this.stringBuffer=(this.serdeContext?.base64Encoder??kp)(a.toString());return}this.stringBuffer=t;break;default:r.isIdempotencyToken()?this.stringBuffer=EM():this.stringBuffer=String(t)}}flush(){const e=this.stringBuffer;return this.stringBuffer="",e}}class xTe{codecSerializer;stringSerializer;buffer;constructor(e,t,r=new wTe(t)){this.codecSerializer=e,this.stringSerializer=r}setSerdeContext(e){this.codecSerializer.setSerdeContext(e),this.stringSerializer.setSerdeContext(e)}write(e,t){const r=yr.of(e),i=r.getMergedTraits();if(i.httpHeader||i.httpLabel||i.httpQuery){this.stringSerializer.write(r,t),this.buffer=this.stringSerializer.flush();return}return this.codecSerializer.write(r,t)}flush(){if(this.buffer!==void 0){const e=this.buffer;return this.buffer=void 0,e}return this.codecSerializer.flush()}}function CTe(n,e,t){n.__smithy_context?n.__smithy_context.features||(n.__smithy_context.features={}):n.__smithy_context={features:{}},n.__smithy_context.features[e]=t}class ATe{authSchemes=new Map;constructor(e){for(const[t,r]of Object.entries(e))r!==void 0&&this.authSchemes.set(t,r)}getIdentityProvider(e){return this.authSchemes.get(e)}}class RTe{async sign(e,t,r){const i=Ka.clone(e);if(!t.token)throw new Error("request could not be signed with `token` since the `token` is not defined");return i.headers.Authorization=`Bearer ${t.token}`,i}}const kTe=n=>function(t){return xM(t)&&t.expiration.getTime()-Date.now()<n},ITe=3e5,uj=kTe(ITe),xM=n=>n.expiration!==void 0,dj=(n,e,t)=>{if(n===void 0)return;const r=typeof n!="function"?async()=>Promise.resolve(n):n;let i,a,s,o=!1;const l=async c=>{a||(a=r(c));try{i=await a,s=!0,o=!1}finally{a=void 0}return i};return e===void 0?async c=>((!s||c?.forceRefresh)&&(i=await l(c)),i):async c=>((!s||c?.forceRefresh)&&(i=await l(c)),o?i:t(i)?(e(i)&&await l(c),i):(o=!0,i))},NTe=void 0;function DTe(n){return n===void 0?!0:typeof n=="string"&&n.length<=50}function OTe(n){const e=gg(n.userAgentAppId??NTe),{customUserAgent:t}=n;return Object.assign(n,{customUserAgent:typeof t=="string"?[[t]]:t,userAgentAppId:async()=>{const r=await e();if(!DTe(r)){const i=n.logger?.constructor?.name==="NoOpLogger"||!n.logger?console:n.logger;typeof r!="string"?i?.warn("userAgentAppId must be a string or undefined."):r.length>50&&i?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return r}})}class PTe{capacity;data=new Map;parameters=[];constructor({size:e,params:t}){this.capacity=e??50,t&&(this.parameters=t)}get(e,t){const r=this.hash(e);if(r===!1)return t();if(!this.data.has(r)){if(this.data.size>this.capacity+10){const i=this.data.keys();let a=0;for(;;){const{value:s,done:o}=i.next();if(this.data.delete(s),o||++a>10)break}}this.data.set(r,t())}return this.data.get(r)}size(){return this.data.size}hash(e){let t="";const{parameters:r}=this;if(r.length===0)return!1;for(const i of r){const a=String(e[i]??"");if(a.includes("|;"))return!1;t+=a+"|;"}return t}}const MTe=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),pj=n=>MTe.test(n)||n.startsWith("[")&&n.endsWith("]"),LTe=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),cw=(n,e=!1)=>{if(!e)return LTe.test(n);const t=n.split(".");for(const r of t)if(!cw(r))return!1;return!0},KS={},o_="endpoints";function Ku(n){return typeof n!="object"||n==null?n:"ref"in n?`$${Ku(n.ref)}`:"fn"in n?`${n.fn}(${(n.argv||[]).map(Ku).join(", ")})`:JSON.stringify(n,null,2)}class Vs extends Error{constructor(e){super(e),this.name="EndpointError"}}const FTe=(n,e)=>n===e,UTe=n=>{const e=n.split("."),t=[];for(const r of e){const i=r.indexOf("[");if(i!==-1){if(r.indexOf("]")!==r.length-1)throw new Vs(`Path: '${n}' does not end with ']'`);const a=r.slice(i+1,-1);if(Number.isNaN(parseInt(a)))throw new Vs(`Invalid array index: '${a}' in path: '${n}'`);i!==0&&t.push(r.slice(0,i)),t.push(a)}else t.push(r)}return t},hj=(n,e)=>UTe(e).reduce((t,r)=>{if(typeof t!="object")throw new Vs(`Index '${r}' in '${e}' not found in '${JSON.stringify(n)}'`);return Array.isArray(t)?t[parseInt(r)]:t[r]},n),BTe=n=>n!=null,$Te=n=>!n,lC={[n_.HTTP]:80,[n_.HTTPS]:443},GTe=n=>{const e=(()=>{try{if(n instanceof URL)return n;if(typeof n=="object"&&"hostname"in n){const{hostname:p,port:h,protocol:f="",path:m="",query:g={}}=n,_=new URL(`${f}//${p}${h?`:${h}`:""}${m}`);return _.search=Object.entries(g).map(([v,b])=>`${v}=${b}`).join("&"),_}return new URL(n)}catch{return null}})();if(!e)return console.error(`Unable to parse ${JSON.stringify(n)} as a whatwg URL.`),null;const t=e.href,{host:r,hostname:i,pathname:a,protocol:s,search:o}=e;if(o)return null;const l=s.slice(0,-1);if(!Object.values(n_).includes(l))return null;const c=pj(i),u=t.includes(`${r}:${lC[l]}`)||typeof n=="string"&&n.includes(`${r}:${lC[l]}`),d=`${r}${u?`:${lC[l]}`:""}`;return{scheme:l,authority:d,path:a,normalizedPath:a.endsWith("/")?a:`${a}/`,isIp:c}},WTe=(n,e)=>n===e,zTe=(n,e,t,r)=>e>=t||n.length<t||/[^\u0000-\u007f]/.test(n)?null:r?n.substring(n.length-t,n.length-e):n.substring(e,t),qTe=n=>encodeURIComponent(n).replace(/[!*'()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),HTe={booleanEquals:FTe,getAttr:hj,isSet:BTe,isValidHostLabel:cw,not:$Te,parseURL:GTe,stringEquals:WTe,substring:zTe,uriEncode:qTe},fj=(n,e)=>{const t=[],r={...e.endpointParams,...e.referenceRecord};let i=0;for(;i<n.length;){const a=n.indexOf("{",i);if(a===-1){t.push(n.slice(i));break}t.push(n.slice(i,a));const s=n.indexOf("}",a);if(s===-1){t.push(n.slice(a));break}n[a+1]==="{"&&n[s+1]==="}"&&(t.push(n.slice(a+1,s)),i=s+2);const o=n.substring(a+1,s);if(o.includes("#")){const[l,c]=o.split("#");t.push(hj(r[l],c))}else t.push(r[o]);i=s+1}return t.join("")},VTe=({ref:n},e)=>({...e.endpointParams,...e.referenceRecord})[n],uw=(n,e,t)=>{if(typeof n=="string")return fj(n,t);if(n.fn)return gj.callFunction(n,t);if(n.ref)return VTe(n,t);throw new Vs(`'${e}': ${String(n)} is not a string, function or reference.`)},mj=({fn:n,argv:e},t)=>{const r=e.map(a=>["boolean","number"].includes(typeof a)?a:gj.evaluateExpression(a,"arg",t)),i=n.split(".");return i[0]in KS&&i[1]!=null?KS[i[0]][i[1]](...r):HTe[n](...r)},gj={evaluateExpression:uw,callFunction:mj},YTe=({assign:n,...e},t)=>{if(n&&n in t.referenceRecord)throw new Vs(`'${n}' is already defined in Reference Record.`);const r=mj(e,t);return t.logger?.debug?.(`${o_} evaluateCondition: ${Ku(e)} = ${Ku(r)}`),{result:r===""?!0:!!r,...n!=null&&{toAssign:{name:n,value:r}}}},CM=(n=[],e)=>{const t={};for(const r of n){const{result:i,toAssign:a}=YTe(r,{...e,referenceRecord:{...e.referenceRecord,...t}});if(!i)return{result:i};a&&(t[a.name]=a.value,e.logger?.debug?.(`${o_} assign: ${a.name} := ${Ku(a.value)}`))}return{result:!0,referenceRecord:t}},KTe=(n,e)=>Object.entries(n).reduce((t,[r,i])=>({...t,[r]:i.map(a=>{const s=uw(a,"Header value entry",e);if(typeof s!="string")throw new Vs(`Header '${r}' value '${s}' is not a string`);return s})}),{}),_j=(n,e)=>Object.entries(n).reduce((t,[r,i])=>({...t,[r]:bj.getEndpointProperty(i,e)}),{}),vj=(n,e)=>{if(Array.isArray(n))return n.map(t=>vj(t,e));switch(typeof n){case"string":return fj(n,e);case"object":if(n===null)throw new Vs(`Unexpected endpoint property: ${n}`);return bj.getEndpointProperties(n,e);case"boolean":return n;default:throw new Vs(`Unexpected endpoint property type: ${typeof n}`)}},bj={getEndpointProperty:vj,getEndpointProperties:_j},QTe=(n,e)=>{const t=uw(n,"Endpoint URL",e);if(typeof t=="string")try{return new URL(t)}catch(r){throw console.error(`Failed to construct URL with ${t}`,r),r}throw new Vs(`Endpoint URL must be a string, got ${typeof t}`)},jTe=(n,e)=>{const{conditions:t,endpoint:r}=n,{result:i,referenceRecord:a}=CM(t,e);if(!i)return;const s={...e,referenceRecord:{...e.referenceRecord,...a}},{url:o,properties:l,headers:c}=r;return e.logger?.debug?.(`${o_} Resolving endpoint from template: ${Ku(r)}`),{...c!=null&&{headers:KTe(c,s)},...l!=null&&{properties:_j(l,s)},url:QTe(o,s)}},XTe=(n,e)=>{const{conditions:t,error:r}=n,{result:i,referenceRecord:a}=CM(t,e);if(i)throw new Vs(uw(r,"Error",{...e,referenceRecord:{...e.referenceRecord,...a}}))},yj=(n,e)=>{for(const t of n)if(t.type==="endpoint"){const r=jTe(t,e);if(r)return r}else if(t.type==="error")XTe(t,e);else if(t.type==="tree"){const r=Ej.evaluateTreeRule(t,e);if(r)return r}else throw new Vs(`Unknown endpoint rule: ${t}`);throw new Vs("Rules evaluation failed")},ZTe=(n,e)=>{const{conditions:t,rules:r}=n,{result:i,referenceRecord:a}=CM(t,e);if(i)return Ej.evaluateRules(r,{...e,referenceRecord:{...e.referenceRecord,...a}})},Ej={evaluateRules:yj,evaluateTreeRule:ZTe},JTe=(n,e)=>{const{endpointParams:t,logger:r}=e,{parameters:i,rules:a}=n;e.logger?.debug?.(`${o_} Initial EndpointParams: ${Ku(t)}`);const s=Object.entries(i).filter(([,c])=>c.default!=null).map(([c,u])=>[c,u.default]);if(s.length>0)for(const[c,u]of s)t[c]=t[c]??u;const o=Object.entries(i).filter(([,c])=>c.required).map(([c])=>c);for(const c of o)if(t[c]==null)throw new Vs(`Missing required parameter: '${c}'`);const l=yj(a,{endpointParams:t,logger:r,referenceRecord:{}});return e.logger?.debug?.(`${o_} Resolved endpoint: ${Ku(l)}`),l},Sj=(n,e=!1)=>{if(e){for(const t of n.split("."))if(!Sj(t))return!1;return!0}return!(!cw(n)||n.length<3||n.length>63||n!==n.toLowerCase()||pj(n))},b9=":",ewe="/",twe=n=>{const e=n.split(b9);if(e.length<6)return null;const[t,r,i,a,s,...o]=e;if(t!=="arn"||r===""||i===""||o.join(b9)==="")return null;const l=o.map(c=>c.split(ewe)).flat();return{partition:r,service:i,region:a,accountId:s,resourceId:l}},nwe=[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",regions:{"af-south-1":{description:"Africa (Cape Town)"},"ap-east-1":{description:"Asia Pacific (Hong Kong)"},"ap-east-2":{description:"Asia Pacific (Taipei)"},"ap-northeast-1":{description:"Asia Pacific (Tokyo)"},"ap-northeast-2":{description:"Asia Pacific (Seoul)"},"ap-northeast-3":{description:"Asia Pacific (Osaka)"},"ap-south-1":{description:"Asia Pacific (Mumbai)"},"ap-south-2":{description:"Asia Pacific (Hyderabad)"},"ap-southeast-1":{description:"Asia Pacific (Singapore)"},"ap-southeast-2":{description:"Asia Pacific (Sydney)"},"ap-southeast-3":{description:"Asia Pacific (Jakarta)"},"ap-southeast-4":{description:"Asia Pacific (Melbourne)"},"ap-southeast-5":{description:"Asia Pacific (Malaysia)"},"ap-southeast-6":{description:"Asia Pacific (New Zealand)"},"ap-southeast-7":{description:"Asia Pacific (Thailand)"},"aws-global":{description:"aws global region"},"ca-central-1":{description:"Canada (Central)"},"ca-west-1":{description:"Canada West (Calgary)"},"eu-central-1":{description:"Europe (Frankfurt)"},"eu-central-2":{description:"Europe (Zurich)"},"eu-north-1":{description:"Europe (Stockholm)"},"eu-south-1":{description:"Europe (Milan)"},"eu-south-2":{description:"Europe (Spain)"},"eu-west-1":{description:"Europe (Ireland)"},"eu-west-2":{description:"Europe (London)"},"eu-west-3":{description:"Europe (Paris)"},"il-central-1":{description:"Israel (Tel Aviv)"},"me-central-1":{description:"Middle East (UAE)"},"me-south-1":{description:"Middle East (Bahrain)"},"mx-central-1":{description:"Mexico (Central)"},"sa-east-1":{description:"South America (Sao Paulo)"},"us-east-1":{description:"US East (N. Virginia)"},"us-east-2":{description:"US East (Ohio)"},"us-west-1":{description:"US West (N. California)"},"us-west-2":{description:"US West (Oregon)"}}},{id:"aws-cn",outputs:{dnsSuffix:"amazonaws.com.cn",dualStackDnsSuffix:"api.amazonwebservices.com.cn",implicitGlobalRegion:"cn-northwest-1",name:"aws-cn",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^cn\\-\\w+\\-\\d+$",regions:{"aws-cn-global":{description:"aws-cn global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-eusc",outputs:{dnsSuffix:"amazonaws.eu",dualStackDnsSuffix:"api.amazonwebservices.eu",implicitGlobalRegion:"eusc-de-east-1",name:"aws-eusc",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eusc\\-(de)\\-\\w+\\-\\d+$",regions:{"eusc-de-east-1":{description:"AWS European Sovereign Cloud (Germany)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"api.aws.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"aws-iso global region"},"us-iso-east-1":{description:"US ISO East"},"us-iso-west-1":{description:"US ISO WEST"}}},{id:"aws-iso-b",outputs:{dnsSuffix:"sc2s.sgov.gov",dualStackDnsSuffix:"api.aws.scloud",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"aws-iso-b global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"},"us-isob-west-1":{description:"US ISOB West"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"api.cloud-aws.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"aws-iso-e-global":{description:"aws-iso-e global region"},"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"api.aws.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{"aws-iso-f-global":{description:"aws-iso-f global region"},"us-isof-east-1":{description:"US ISOF EAST"},"us-isof-south-1":{description:"US ISOF SOUTH"}}},{id:"aws-us-gov",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-gov-west-1",name:"aws-us-gov",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-gov\\-\\w+\\-\\d+$",regions:{"aws-us-gov-global":{description:"aws-us-gov global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}}],rwe={partitions:nwe};let iwe=rwe;const awe=n=>{const{partitions:e}=iwe;for(const r of e){const{regions:i,outputs:a}=r;for(const[s,o]of Object.entries(i))if(s===n)return{...a,...o}}for(const r of e){const{regionRegex:i,outputs:a}=r;if(new RegExp(i).test(n))return{...a}}const t=e.find(r=>r.id==="aws");if(!t)throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...t.outputs}},Tj={isVirtualHostableS3Bucket:Sj,parseArn:twe,partition:awe};KS.aws=Tj;function swe(n){const e={};if(n=n.replace(/^\?/,""),n)for(const t of n.split("&")){let[r,i=null]=t.split("=");r=decodeURIComponent(r),i&&(i=decodeURIComponent(i)),r in e?Array.isArray(e[r])?e[r].push(i):e[r]=[e[r],i]:e[r]=i}return e}const QS=n=>{if(typeof n=="string")return QS(new URL(n));const{hostname:e,pathname:t,port:r,protocol:i,search:a}=n;let s;return a&&(s=swe(a)),{hostname:e,port:r?parseInt(r):void 0,protocol:i,path:t,query:s}};function owe(n,e,t){return n.$source||(n.$source={}),n.$source[e]=t,n}function xl(n,e,t){n.__aws_sdk_context?n.__aws_sdk_context.features||(n.__aws_sdk_context.features={}):n.__aws_sdk_context={features:{}},n.__aws_sdk_context.features[e]=t}const y9=n=>Cp.isInstance(n)?n.headers?.date??n.headers?.Date:void 0,wj=n=>new Date(Date.now()+n),lwe=(n,e)=>Math.abs(wj(e).getTime()-n)>=3e5,E9=(n,e)=>{const t=Date.parse(n);return lwe(t,e)?t-Date.now():e},vg=(n,e)=>{if(!e)throw new Error(`Property \`${n}\` is not resolved for AWS SDK SigV4Auth`);return e},cwe=async n=>{const e=vg("context",n.context),t=vg("config",n.config),r=e.endpointV2?.properties?.authSchemes?.[0],a=await vg("signer",t.signer)(r),s=n?.signingRegion,o=n?.signingRegionSet,l=n?.signingName;return{config:t,signer:a,signingRegion:s,signingRegionSet:o,signingName:l}};class uwe{async sign(e,t,r){if(!Ka.isInstance(e))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const i=await cwe(r),{config:a,signer:s}=i;let{signingRegion:o,signingName:l}=i;const c=r.context;if(c?.authSchemes?.length??!1){const[d,p]=c.authSchemes;d?.name==="sigv4a"&&p?.name==="sigv4"&&(o=p?.signingRegion??o,l=p?.signingName??l)}return await s.sign(e,{signingDate:wj(a.systemClockOffset),signingRegion:o,signingService:l})}errorHandler(e){return t=>{const r=t.ServerTime??y9(t.$response);if(r){const i=vg("config",e.config),a=i.systemClockOffset;i.systemClockOffset=E9(r,i.systemClockOffset),i.systemClockOffset!==a&&t.$metadata&&(t.$metadata.clockSkewCorrected=!0)}throw t}}successHandler(e,t){const r=y9(e);if(r){const i=vg("config",t.config);i.systemClockOffset=E9(r,i.systemClockOffset)}}}const dwe=(n,e,t)=>{let r,i,a,s=!1;const o=async()=>{i||(i=n());try{r=await i,a=!0,s=!1}finally{i=void 0}return r};return async l=>((!a||l?.forceRefresh)&&(r=await o()),r)},pwe="X-Amz-Algorithm",hwe="X-Amz-Credential",xj="X-Amz-Date",fwe="X-Amz-SignedHeaders",mwe="X-Amz-Expires",Cj="X-Amz-Signature",Aj="X-Amz-Security-Token",Rj="authorization",kj=xj.toLowerCase(),gwe="date",_we=[Rj,kj,gwe],vwe=Cj.toLowerCase(),HN="x-amz-content-sha256",bwe=Aj.toLowerCase(),ywe={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},Ewe=/^proxy-/,Swe=/^sec-/,cC="AWS4-HMAC-SHA256",Twe="AWS4-HMAC-SHA256-PAYLOAD",wwe="UNSIGNED-PAYLOAD",xwe=50,Ij="aws4_request",Cwe=3600*24*7,Gb={},uC=[],dC=(n,e,t)=>`${n}/${e}/${t}/${Ij}`,Awe=async(n,e,t,r,i)=>{const a=await S9(n,e.secretAccessKey,e.accessKeyId),s=`${t}:${r}:${i}:${ps(a)}:${e.sessionToken}`;if(s in Gb)return Gb[s];for(uC.push(s);uC.length>xwe;)delete Gb[uC.shift()];let o=`AWS4${e.secretAccessKey}`;for(const l of[t,r,i,Ij])o=await S9(n,o,l);return Gb[s]=o},S9=(n,e,t)=>{const r=new n(e);return r.update(i_(t)),r.digest()},T9=({headers:n},e,t)=>{const r={};for(const i of Object.keys(n).sort()){if(n[i]==null)continue;const a=i.toLowerCase();(a in ywe||e?.has(a)||Ewe.test(a)||Swe.test(a))&&(!t||t&&!t.has(a))||(r[a]=n[i].trim().replace(/\s+/g," "))}return r},Rwe=n=>typeof ArrayBuffer=="function"&&n instanceof ArrayBuffer||Object.prototype.toString.call(n)==="[object ArrayBuffer]",pC=async({headers:n,body:e},t)=>{for(const r of Object.keys(n))if(r.toLowerCase()===HN)return n[r];if(e==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if(typeof e=="string"||ArrayBuffer.isView(e)||Rwe(e)){const r=new t;return r.update(i_(e)),ps(await r.digest())}return wwe};class kwe{format(e){const t=[];for(const a of Object.keys(e)){const s=Rp(a);t.push(Uint8Array.from([s.byteLength]),s,this.formatHeaderValue(e[a]))}const r=new Uint8Array(t.reduce((a,s)=>a+s.byteLength,0));let i=0;for(const a of t)r.set(a,i),i+=a.byteLength;return r}formatHeaderValue(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":const t=new DataView(new ArrayBuffer(3));return t.setUint8(0,3),t.setInt16(1,e.value,!1),new Uint8Array(t.buffer);case"integer":const r=new DataView(new ArrayBuffer(5));return r.setUint8(0,4),r.setInt32(1,e.value,!1),new Uint8Array(r.buffer);case"long":const i=new Uint8Array(9);return i[0]=5,i.set(e.value.bytes,1),i;case"binary":const a=new DataView(new ArrayBuffer(3+e.value.byteLength));a.setUint8(0,6),a.setUint16(1,e.value.byteLength,!1);const s=new Uint8Array(a.buffer);return s.set(e.value,3),s;case"string":const o=Rp(e.value),l=new DataView(new ArrayBuffer(3+o.byteLength));l.setUint8(0,7),l.setUint16(1,o.byteLength,!1);const c=new Uint8Array(l.buffer);return c.set(o,3),c;case"timestamp":const u=new Uint8Array(9);return u[0]=8,u.set(Nwe.fromNumber(e.value.valueOf()).bytes,1),u;case"uuid":if(!Iwe.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(bM(e.value.replace(/\-/g,"")),1),d}}}var w9;(function(n){n[n.boolTrue=0]="boolTrue",n[n.boolFalse=1]="boolFalse",n[n.byte=2]="byte",n[n.short=3]="short",n[n.integer=4]="integer",n[n.long=5]="long",n[n.byteArray=6]="byteArray",n[n.string=7]="string",n[n.timestamp=8]="timestamp",n[n.uuid=9]="uuid"})(w9||(w9={}));const Iwe=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;let Nwe=class Nj{bytes;constructor(e){if(this.bytes=e,e.byteLength!==8)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>9223372036854776e3||e<-9223372036854776e3)throw new Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);const t=new Uint8Array(8);for(let r=7,i=Math.abs(Math.round(e));r>-1&&i>0;r--,i/=256)t[r]=i;return e<0&&x9(t),new Nj(t)}valueOf(){const e=this.bytes.slice(0),t=e[0]&128;return t&&x9(e),parseInt(ps(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}};function x9(n){for(let e=0;e<8;e++)n[e]^=255;for(let e=7;e>-1&&(n[e]++,n[e]===0);e--);}const Dwe=(n,e)=>{n=n.toLowerCase();for(const t of Object.keys(e))if(n===t.toLowerCase())return!0;return!1},Owe=(n,e={})=>{const{headers:t,query:r={}}=Ka.clone(n);for(const i of Object.keys(t)){const a=i.toLowerCase();(a.slice(0,6)==="x-amz-"&&!e.unhoistableHeaders?.has(a)||e.hoistableHeaders?.has(a))&&(r[i]=t[i],delete t[i])}return{...n,headers:t,query:r}},C9=n=>{n=Ka.clone(n);for(const e of Object.keys(n.headers))_we.indexOf(e.toLowerCase())>-1&&delete n.headers[e];return n},Pwe=({query:n={}})=>{const e=[],t={};for(const r of Object.keys(n)){if(r.toLowerCase()===vwe)continue;const i=fp(r);e.push(i);const a=n[r];typeof a=="string"?t[i]=`${i}=${fp(a)}`:Array.isArray(a)&&(t[i]=a.slice(0).reduce((s,o)=>s.concat([`${i}=${fp(o)}`]),[]).sort().join("&"))}return e.sort().map(r=>t[r]).filter(r=>r).join("&")},Mwe=n=>Lwe(n).toISOString().replace(/\.\d{3}Z$/,"Z"),Lwe=n=>typeof n=="number"?new Date(n*1e3):typeof n=="string"?Number(n)?new Date(Number(n)*1e3):new Date(n):n;class Fwe{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:e,credentials:t,region:r,service:i,sha256:a,uriEscapePath:s=!0}){this.service=i,this.sha256=a,this.uriEscapePath=s,this.applyChecksum=typeof e=="boolean"?e:!0,this.regionProvider=Uc(r),this.credentialProvider=Uc(t)}createCanonicalRequest(e,t,r){const i=Object.keys(t).sort();return`${e.method}
|
|
129
|
+
`),Y1e={warn:console.warn},K1e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],yM=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function sj(n){const e=n.getUTCFullYear(),t=n.getUTCMonth(),r=n.getUTCDay(),i=n.getUTCDate(),a=n.getUTCHours(),s=n.getUTCMinutes(),o=n.getUTCSeconds(),l=i<10?`0${i}`:`${i}`,c=a<10?`0${a}`:`${a}`,u=s<10?`0${s}`:`${s}`,d=o<10?`0${o}`:`${o}`;return`${K1e[r]}, ${l} ${yM[t]} ${e} ${c}:${u}:${d} GMT`}const Q1e=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),j1e=n=>{if(n==null)return;if(typeof n!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");const e=Q1e.exec(n);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");const[t,r,i,a,s,o,l,c,u]=e,d=YS(s_(r)),p=zu(i,"month",1,12),h=zu(a,"day",1,31),f=ZE(d,p,h,{hours:s,minutes:o,seconds:l,fractionalMilliseconds:c});return u.toUpperCase()!="Z"&&f.setTime(f.getTime()-cTe(u)),f},X1e=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),Z1e=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),J1e=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),eTe=n=>{if(n==null)return;if(typeof n!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let e=X1e.exec(n);if(e){const[t,r,i,a,s,o,l,c]=e;return ZE(YS(s_(a)),oC(i),zu(r,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:c})}if(e=Z1e.exec(n),e){const[t,r,i,a,s,o,l,c]=e;return iTe(ZE(nTe(a),oC(i),zu(r,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:c}))}if(e=J1e.exec(n),e){const[t,r,i,a,s,o,l,c]=e;return ZE(YS(s_(c)),oC(r),zu(i.trimLeft(),"day",1,31),{hours:a,minutes:s,seconds:o,fractionalMilliseconds:l})}throw new TypeError("Invalid RFC-7231 date-time value")},tTe=n=>{if(n==null)return;let e;if(typeof n=="number")e=n;else if(typeof n=="string")e=W1e(n);else if(typeof n=="object"&&n.tag===1)e=n.value;else throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(e)||e===1/0||e===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(e*1e3))},ZE=(n,e,t,r)=>{const i=e-1;return sTe(n,i,t),new Date(Date.UTC(n,i,t,zu(r.hours,"hour",0,23),zu(r.minutes,"minute",0,59),zu(r.seconds,"seconds",0,60),lTe(r.fractionalMilliseconds)))},nTe=n=>{const e=new Date().getUTCFullYear(),t=Math.floor(e/100)*100+YS(s_(n));return t<e?t+100:t},rTe=50*365*24*60*60*1e3,iTe=n=>n.getTime()-new Date().getTime()>rTe?new Date(Date.UTC(n.getUTCFullYear()-100,n.getUTCMonth(),n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds())):n,oC=n=>{const e=yM.indexOf(n);if(e<0)throw new TypeError(`Invalid month: ${n}`);return e+1},aTe=[31,28,31,30,31,30,31,31,30,31,30,31],sTe=(n,e,t)=>{let r=aTe[e];if(e===1&&oTe(n)&&(r=29),t>r)throw new TypeError(`Invalid day for ${yM[e]} in ${n}: ${t}`)},oTe=n=>n%4===0&&(n%100!==0||n%400===0),zu=(n,e,t,r)=>{const i=H1e(s_(n));if(i<t||i>r)throw new TypeError(`${e} must be between ${t} and ${r}, inclusive`);return i},lTe=n=>n==null?0:z1e("0."+n)*1e3,cTe=n=>{const e=n[0];let t=1;if(e=="+")t=1;else if(e=="-")t=-1;else throw new TypeError(`Offset direction, ${e}, must be "+" or "-"`);const r=Number(n.substring(1,3)),i=Number(n.substring(4,6));return t*(r*60+i)*60*1e3},s_=n=>{let e=0;for(;e<n.length-1&&n.charAt(e)==="0";)e++;return e===0?n:n.slice(e)},_9=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ma=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0")),EM=()=>{if(_9)return _9();const n=new Uint8Array(16);return crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128,ma[n[0]]+ma[n[1]]+ma[n[2]]+ma[n[3]]+"-"+ma[n[4]]+ma[n[5]]+"-"+ma[n[6]]+ma[n[7]]+"-"+ma[n[8]]+ma[n[9]]+"-"+ma[n[10]]+ma[n[11]]+ma[n[12]]+ma[n[13]]+ma[n[14]]+ma[n[15]]},Vl=function(e){return Object.assign(new String(e),{deserializeJSON(){return JSON.parse(String(e))},toString(){return String(e)},toJSON(){return String(e)}})};Vl.from=n=>n&&typeof n=="object"&&(n instanceof Vl||"deserializeJSON"in n)?n:typeof n=="string"||Object.getPrototypeOf(n)===String.prototype?Vl(String(n)):Vl(JSON.stringify(n));Vl.fromObject=Vl.from;function uTe(n){return(n.includes(",")||n.includes('"'))&&(n=`"${n.replace(/"/g,'\\"')}"`),n}const SM="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",TM="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",wM="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",oj="(\\d?\\d)",lj="(\\d{4})",dTe=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),pTe=new RegExp(`^${SM}, ${oj} ${TM} ${lj} ${wM} GMT$`),hTe=new RegExp(`^${SM}, ${oj}-${TM}-(\\d\\d) ${wM} GMT$`),fTe=new RegExp(`^${SM} ${TM} ( [1-9]|\\d\\d) ${wM} ${lj}$`),mTe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],gTe=n=>{if(n==null)return;let e=NaN;if(typeof n=="number")e=n;else if(typeof n=="string"){if(!/^-?\d*\.?\d+$/.test(n))throw new TypeError("parseEpochTimestamp - numeric string invalid.");e=Number.parseFloat(n)}else typeof n=="object"&&n.tag===1&&(e=n.value);if(isNaN(e)||Math.abs(e)===1/0)throw new TypeError("Epoch timestamps must be valid finite numbers.");return new Date(Math.round(e*1e3))},_Te=n=>{if(n==null)return;if(typeof n!="string")throw new TypeError("RFC3339 timestamps must be strings");const e=dTe.exec(n);if(!e)throw new TypeError(`Invalid RFC3339 timestamp format ${n}`);const[,t,r,i,a,s,o,,l,c]=e;Ic(r,1,12),Ic(i,1,31),Ic(a,0,23),Ic(s,0,59),Ic(o,0,60);const u=new Date(Date.UTC(Number(t),Number(r)-1,Number(i),Number(a),Number(s),Number(o),Number(l)?Math.round(parseFloat(`0.${l}`)*1e3):0));if(u.setUTCFullYear(Number(t)),c.toUpperCase()!="Z"){const[,d,p,h]=/([+-])(\d\d):(\d\d)/.exec(c)||[void 0,"+",0,0],f=d==="-"?1:-1;u.setTime(u.getTime()+f*(Number(p)*60*60*1e3+Number(h)*60*1e3))}return u},vTe=n=>{if(n==null)return;if(typeof n!="string")throw new TypeError("RFC7231 timestamps must be strings.");let e,t,r,i,a,s,o,l;if((l=pTe.exec(n))?[,e,t,r,i,a,s,o]=l:(l=hTe.exec(n))?([,e,t,r,i,a,s,o]=l,r=(Number(r)+1900).toString()):(l=fTe.exec(n))&&([,t,e,i,a,s,o,r]=l),r&&s){const c=Date.UTC(Number(r),mTe.indexOf(t),Number(e),Number(i),Number(a),Number(s),o?Math.round(parseFloat(`0.${o}`)*1e3):0);Ic(e,1,31),Ic(i,0,23),Ic(a,0,59),Ic(s,0,60);const u=new Date(c);return u.setUTCFullYear(Number(r)),u}throw new TypeError(`Invalid RFC7231 date-time value ${n}.`)};function Ic(n,e,t){const r=Number(n);if(r<e||r>t)throw new Error(`Value ${r} out of range [${e}, ${t}]`)}function bTe(n,e,t){if(!Number.isInteger(t))throw new Error("Invalid number of delimiters ("+t+") for splitEvery.");const r=n.split(e),i=[];let a="";for(let s=0;s<r.length;s++)a===""?a=r[s]:a+=e+r[s],(s+1)%t===0&&(i.push(a),a="");return a!==""&&i.push(a),i}const cj=n=>{const e=n.length,t=[];let r=!1,i,a=0;for(let s=0;s<e;++s){const o=n[s];switch(o){case'"':i!=="\\"&&(r=!r);break;case",":r||(t.push(n.slice(a,s)),a=s+1);break}i=o}return t.push(n.slice(a)),t.map(s=>{s=s.trim();const o=s.length;return o<2?s:(s[0]==='"'&&s[o-1]==='"'&&(s=s.slice(1,o-1)),s.replace(/\\"/g,'"'))})},v9=/^-?\d*(\.\d+)?$/;class tl{string;type;constructor(e,t){if(this.string=e,this.type=t,!v9.test(e))throw new Error('@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".')}toString(){return this.string}static[Symbol.hasInstance](e){if(!e||typeof e!="object")return!1;const t=e;return tl.prototype.isPrototypeOf(e)||t.type==="bigDecimal"&&v9.test(t.string)}}class ow{serdeContext;setSerdeContext(e){this.serdeContext=e}}class yTe extends ow{options;compositeErrorRegistry;constructor(e){super(),this.options=e,this.compositeErrorRegistry=cs.for(e.defaultNamespace);for(const t of e.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(t)}getRequestType(){return Ka}getResponseType(){return Cp}setSerdeContext(e){this.serdeContext=e,this.serializer.setSerdeContext(e),this.deserializer.setSerdeContext(e),this.getPayloadCodec()&&this.getPayloadCodec().setSerdeContext(e)}updateServiceEndpoint(e,t){if("url"in t){e.protocol=t.url.protocol,e.hostname=t.url.hostname,e.port=t.url.port?Number(t.url.port):void 0,e.path=t.url.pathname,e.fragment=t.url.hash||void 0,e.username=t.url.username||void 0,e.password=t.url.password||void 0,e.query||(e.query={});for(const[r,i]of t.url.searchParams.entries())e.query[r]=i;return e}else return e.protocol=t.protocol,e.hostname=t.hostname,e.port=t.port?Number(t.port):void 0,e.path=t.path,e.query={...t.query},e}setHostPrefix(e,t,r){if(this.serdeContext?.disableHostPrefix)return;const i=yr.of(t.input),a=sf(t.traits??{});if(a.endpoint){let s=a.endpoint?.[0];if(typeof s=="string"){const o=[...i.structIterator()].filter(([,l])=>l.getMergedTraits().hostLabel);for(const[l]of o){const c=r[l];if(typeof c!="string")throw new Error(`@smithy/core/schema - ${l} in input must be a string as hostLabel.`);s=s.replace(`{${l}}`,c)}e.hostname=s+e.hostname}}}deserializeMetadata(e){return{httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream:e,requestSchema:t,initialRequest:r}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:e,requestSchema:t,initialRequest:r})}async deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:r}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:r})}async loadEventStreamCapability(){const{EventStreamSerde:e}=await _s(async()=>{const{EventStreamSerde:t}=await import("./index-DUEhKmPQ.js");return{EventStreamSerde:t}},[]);return new e({marshaller:this.getEventStreamMarshaller(),serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}getDefaultContentType(){throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(e,t,r,i,a){return[]}getEventStreamMarshaller(){const e=this.serdeContext;if(!e.eventStreamMarshaller)throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return e.eventStreamMarshaller}}class ETe extends yTe{async serializeRequest(e,t,r){const i={...t??{}},a=this.serializer,s={},o={},l=await r.endpoint(),c=yr.of(e?.input),u=[],d=[];let p=!1,h;const f=new Ka({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:s,headers:o,body:void 0});if(l){this.updateServiceEndpoint(f,l),this.setHostPrefix(f,e,i);const m=sf(e.traits);if(m.http){f.method=m.http[0];const[g,_]=m.http[1].split("?");f.path=="/"?f.path=g:f.path+=g;const v=new URLSearchParams(_??"");Object.assign(s,Object.fromEntries(v))}}for(const[m,g]of c.structIterator()){const _=g.getMergedTraits()??{},v=i[m];if(v==null&&!g.isIdempotencyToken()){if(_.httpLabel&&(f.path.includes(`{${m}+}`)||f.path.includes(`{${m}}`)))throw new Error(`No value provided for input HTTP label: ${m}.`);continue}if(_.httpPayload)g.isStreaming()?g.isStructSchema()?i[m]&&(h=await this.serializeEventStream({eventStream:i[m],requestSchema:c})):h=v:(a.write(g,v),h=a.flush()),delete i[m];else if(_.httpLabel){a.write(g,v);const b=a.flush();f.path.includes(`{${m}+}`)?f.path=f.path.replace(`{${m}+}`,b.split("/").map(p9).join("/")):f.path.includes(`{${m}}`)&&(f.path=f.path.replace(`{${m}}`,p9(b))),delete i[m]}else if(_.httpHeader)a.write(g,v),o[_.httpHeader.toLowerCase()]=String(a.flush()),delete i[m];else if(typeof _.httpPrefixHeaders=="string"){for(const[b,E]of Object.entries(v)){const S=_.httpPrefixHeaders+b;a.write([g.getValueSchema(),{httpHeader:S}],E),o[S.toLowerCase()]=a.flush()}delete i[m]}else _.httpQuery||_.httpQueryParams?(this.serializeQuery(g,v,s),delete i[m]):(p=!0,u.push(m),d.push(g))}if(p&&i){const[m,g]=(c.getName(!0)??"#Unknown").split("#"),_=c.getSchema()[6],v=[3,m,g,c.getMergedTraits(),u,d,void 0];_?v[6]=_:v.pop(),a.write(v,i),h=a.flush()}return f.headers=o,f.query=s,f.body=h,f}serializeQuery(e,t,r){const i=this.serializer,a=e.getMergedTraits();if(a.httpQueryParams){for(const[s,o]of Object.entries(t))if(!(s in r)){const l=e.getValueSchema();Object.assign(l.getMergedTraits(),{...a,httpQuery:s,httpQueryParams:void 0}),this.serializeQuery(l,o,r)}return}if(e.isListSchema()){const s=!!e.getMergedTraits().sparse,o=[];for(const l of t){i.write([e.getValueSchema(),a],l);const c=i.flush();(s||c!==void 0)&&o.push(c)}r[a.httpQuery]=o}else i.write([e,a],t),r[a.httpQuery]=i.flush()}async deserializeResponse(e,t,r){const i=this.deserializer,a=yr.of(e.output),s={};if(r.statusCode>=300){const l=await V0(r.body,t);throw l.byteLength>0&&Object.assign(s,await i.read(15,l)),await this.handleError(e,t,r,s,this.deserializeMetadata(r)),new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(const l in r.headers){const c=r.headers[l];delete r.headers[l],r.headers[l.toLowerCase()]=c}const o=await this.deserializeHttpMessage(a,t,r,s);if(o.length){const l=await V0(r.body,t);if(l.byteLength>0){const c=await i.read(a,l);for(const u of o)c[u]!=null&&(s[u]=c[u])}}else o.discardResponseBody&&await V0(r.body,t);return s.$metadata=this.deserializeMetadata(r),s}async deserializeHttpMessage(e,t,r,i,a){let s;i instanceof Set?s=a:s=i;let o=!0;const l=this.deserializer,c=yr.of(e),u=[];for(const[d,p]of c.structIterator()){const h=p.getMemberTraits();if(h.httpPayload){if(o=!1,p.isStreaming())p.isStructSchema()?s[d]=await this.deserializeEventStream({response:r,responseSchema:c}):s[d]=D1e(r.body);else if(r.body){const m=await V0(r.body,t);m.byteLength>0&&(s[d]=await l.read(p,m))}}else if(h.httpHeader){const f=String(h.httpHeader).toLowerCase(),m=r.headers[f];if(m!=null)if(p.isListSchema()){const g=p.getValueSchema();g.getMergedTraits().httpHeader=f;let _;g.isTimestampSchema()&&g.getSchema()===4?_=bTe(m,",",2):_=cj(m);const v=[];for(const b of _)v.push(await l.read(g,b.trim()));s[d]=v}else s[d]=await l.read(p,m)}else if(h.httpPrefixHeaders!==void 0){s[d]={};for(const[f,m]of Object.entries(r.headers))if(f.startsWith(h.httpPrefixHeaders)){const g=p.getValueSchema();g.getMergedTraits().httpHeader=f,s[d][f.slice(h.httpPrefixHeaders.length)]=await l.read(g,m)}}else h.httpResponseCode?s[d]=r.statusCode:u.push(d)}return u.discardResponseBody=o,u}}function lw(n,e){if(e.timestampFormat.useTrait&&n.isTimestampSchema()&&(n.getSchema()===5||n.getSchema()===6||n.getSchema()===7))return n.getSchema();const{httpLabel:t,httpPrefixHeaders:r,httpHeader:i,httpQuery:a}=n.getMergedTraits();return(e.httpBindings?typeof r=="string"||i?6:a||t?5:void 0:void 0)??e.timestampFormat.default}class STe extends ow{settings;constructor(e){super(),this.settings=e}read(e,t){const r=yr.of(e);if(r.isListSchema())return cj(t).map(i=>this.read(r.getValueSchema(),i));if(r.isBlobSchema())return(this.serdeContext?.base64Decoder??Ap)(t);if(r.isTimestampSchema())switch(lw(r,this.settings)){case 5:return _Te(t);case 6:return vTe(t);case 7:return gTe(t);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",t),new Date(t)}if(r.isStringSchema()){const i=r.getMergedTraits().mediaType;let a=t;if(i)return r.getMergedTraits().httpHeader&&(a=this.base64ToUtf8(a)),(i==="application/json"||i.endsWith("+json"))&&(a=Vl.from(a)),a}return r.isNumericSchema()?Number(t):r.isBigIntegerSchema()?BigInt(t):r.isBigDecimalSchema()?new tl(t,"bigDecimal"):r.isBooleanSchema()?String(t).toLowerCase()==="true":t}base64ToUtf8(e){return(this.serdeContext?.utf8Encoder??vm)((this.serdeContext?.base64Decoder??Ap)(e))}}class TTe extends ow{codecDeserializer;stringDeserializer;constructor(e,t){super(),this.codecDeserializer=e,this.stringDeserializer=new STe(t)}setSerdeContext(e){this.stringDeserializer.setSerdeContext(e),this.codecDeserializer.setSerdeContext(e),this.serdeContext=e}read(e,t){const r=yr.of(e),i=r.getMergedTraits(),a=this.serdeContext?.utf8Encoder??vm;if(i.httpHeader||i.httpResponseCode)return this.stringDeserializer.read(r,a(t));if(i.httpPayload){if(r.isBlobSchema()){const s=this.serdeContext?.utf8Decoder??Rp;return typeof t=="string"?s(t):t}else if(r.isStringSchema())return"byteLength"in t?a(t):t}return this.codecDeserializer.read(r,t)}}class wTe extends ow{settings;stringBuffer="";constructor(e){super(),this.settings=e}write(e,t){const r=yr.of(e);switch(typeof t){case"object":if(t===null){this.stringBuffer="null";return}if(r.isTimestampSchema()){if(!(t instanceof Date))throw new Error(`@smithy/core/protocols - received non-Date value ${t} when schema expected Date in ${r.getName(!0)}`);switch(lw(r,this.settings)){case 5:this.stringBuffer=t.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=sj(t);break;case 7:this.stringBuffer=String(t.getTime()/1e3);break;default:console.warn("Missing timestamp format, using epoch seconds",t),this.stringBuffer=String(t.getTime()/1e3)}return}if(r.isBlobSchema()&&"byteLength"in t){this.stringBuffer=(this.serdeContext?.base64Encoder??kp)(t);return}if(r.isListSchema()&&Array.isArray(t)){let s="";for(const o of t){this.write([r.getValueSchema(),r.getMergedTraits()],o);const l=this.flush(),c=r.getValueSchema().isTimestampSchema()?l:uTe(l);s!==""&&(s+=", "),s+=c}this.stringBuffer=s;return}this.stringBuffer=JSON.stringify(t,null,2);break;case"string":const i=r.getMergedTraits().mediaType;let a=t;if(i&&((i==="application/json"||i.endsWith("+json"))&&(a=Vl.from(a)),r.getMergedTraits().httpHeader)){this.stringBuffer=(this.serdeContext?.base64Encoder??kp)(a.toString());return}this.stringBuffer=t;break;default:r.isIdempotencyToken()?this.stringBuffer=EM():this.stringBuffer=String(t)}}flush(){const e=this.stringBuffer;return this.stringBuffer="",e}}class xTe{codecSerializer;stringSerializer;buffer;constructor(e,t,r=new wTe(t)){this.codecSerializer=e,this.stringSerializer=r}setSerdeContext(e){this.codecSerializer.setSerdeContext(e),this.stringSerializer.setSerdeContext(e)}write(e,t){const r=yr.of(e),i=r.getMergedTraits();if(i.httpHeader||i.httpLabel||i.httpQuery){this.stringSerializer.write(r,t),this.buffer=this.stringSerializer.flush();return}return this.codecSerializer.write(r,t)}flush(){if(this.buffer!==void 0){const e=this.buffer;return this.buffer=void 0,e}return this.codecSerializer.flush()}}function CTe(n,e,t){n.__smithy_context?n.__smithy_context.features||(n.__smithy_context.features={}):n.__smithy_context={features:{}},n.__smithy_context.features[e]=t}class ATe{authSchemes=new Map;constructor(e){for(const[t,r]of Object.entries(e))r!==void 0&&this.authSchemes.set(t,r)}getIdentityProvider(e){return this.authSchemes.get(e)}}class RTe{async sign(e,t,r){const i=Ka.clone(e);if(!t.token)throw new Error("request could not be signed with `token` since the `token` is not defined");return i.headers.Authorization=`Bearer ${t.token}`,i}}const kTe=n=>function(t){return xM(t)&&t.expiration.getTime()-Date.now()<n},ITe=3e5,uj=kTe(ITe),xM=n=>n.expiration!==void 0,dj=(n,e,t)=>{if(n===void 0)return;const r=typeof n!="function"?async()=>Promise.resolve(n):n;let i,a,s,o=!1;const l=async c=>{a||(a=r(c));try{i=await a,s=!0,o=!1}finally{a=void 0}return i};return e===void 0?async c=>((!s||c?.forceRefresh)&&(i=await l(c)),i):async c=>((!s||c?.forceRefresh)&&(i=await l(c)),o?i:t(i)?(e(i)&&await l(c),i):(o=!0,i))},NTe=void 0;function DTe(n){return n===void 0?!0:typeof n=="string"&&n.length<=50}function OTe(n){const e=gg(n.userAgentAppId??NTe),{customUserAgent:t}=n;return Object.assign(n,{customUserAgent:typeof t=="string"?[[t]]:t,userAgentAppId:async()=>{const r=await e();if(!DTe(r)){const i=n.logger?.constructor?.name==="NoOpLogger"||!n.logger?console:n.logger;typeof r!="string"?i?.warn("userAgentAppId must be a string or undefined."):r.length>50&&i?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return r}})}class PTe{capacity;data=new Map;parameters=[];constructor({size:e,params:t}){this.capacity=e??50,t&&(this.parameters=t)}get(e,t){const r=this.hash(e);if(r===!1)return t();if(!this.data.has(r)){if(this.data.size>this.capacity+10){const i=this.data.keys();let a=0;for(;;){const{value:s,done:o}=i.next();if(this.data.delete(s),o||++a>10)break}}this.data.set(r,t())}return this.data.get(r)}size(){return this.data.size}hash(e){let t="";const{parameters:r}=this;if(r.length===0)return!1;for(const i of r){const a=String(e[i]??"");if(a.includes("|;"))return!1;t+=a+"|;"}return t}}const MTe=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),pj=n=>MTe.test(n)||n.startsWith("[")&&n.endsWith("]"),LTe=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),cw=(n,e=!1)=>{if(!e)return LTe.test(n);const t=n.split(".");for(const r of t)if(!cw(r))return!1;return!0},KS={},o_="endpoints";function Ku(n){return typeof n!="object"||n==null?n:"ref"in n?`$${Ku(n.ref)}`:"fn"in n?`${n.fn}(${(n.argv||[]).map(Ku).join(", ")})`:JSON.stringify(n,null,2)}class Vs extends Error{constructor(e){super(e),this.name="EndpointError"}}const FTe=(n,e)=>n===e,UTe=n=>{const e=n.split("."),t=[];for(const r of e){const i=r.indexOf("[");if(i!==-1){if(r.indexOf("]")!==r.length-1)throw new Vs(`Path: '${n}' does not end with ']'`);const a=r.slice(i+1,-1);if(Number.isNaN(parseInt(a)))throw new Vs(`Invalid array index: '${a}' in path: '${n}'`);i!==0&&t.push(r.slice(0,i)),t.push(a)}else t.push(r)}return t},hj=(n,e)=>UTe(e).reduce((t,r)=>{if(typeof t!="object")throw new Vs(`Index '${r}' in '${e}' not found in '${JSON.stringify(n)}'`);return Array.isArray(t)?t[parseInt(r)]:t[r]},n),BTe=n=>n!=null,$Te=n=>!n,lC={[n_.HTTP]:80,[n_.HTTPS]:443},GTe=n=>{const e=(()=>{try{if(n instanceof URL)return n;if(typeof n=="object"&&"hostname"in n){const{hostname:p,port:h,protocol:f="",path:m="",query:g={}}=n,_=new URL(`${f}//${p}${h?`:${h}`:""}${m}`);return _.search=Object.entries(g).map(([v,b])=>`${v}=${b}`).join("&"),_}return new URL(n)}catch{return null}})();if(!e)return console.error(`Unable to parse ${JSON.stringify(n)} as a whatwg URL.`),null;const t=e.href,{host:r,hostname:i,pathname:a,protocol:s,search:o}=e;if(o)return null;const l=s.slice(0,-1);if(!Object.values(n_).includes(l))return null;const c=pj(i),u=t.includes(`${r}:${lC[l]}`)||typeof n=="string"&&n.includes(`${r}:${lC[l]}`),d=`${r}${u?`:${lC[l]}`:""}`;return{scheme:l,authority:d,path:a,normalizedPath:a.endsWith("/")?a:`${a}/`,isIp:c}},WTe=(n,e)=>n===e,zTe=(n,e,t,r)=>e>=t||n.length<t||/[^\u0000-\u007f]/.test(n)?null:r?n.substring(n.length-t,n.length-e):n.substring(e,t),qTe=n=>encodeURIComponent(n).replace(/[!*'()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),HTe={booleanEquals:FTe,getAttr:hj,isSet:BTe,isValidHostLabel:cw,not:$Te,parseURL:GTe,stringEquals:WTe,substring:zTe,uriEncode:qTe},fj=(n,e)=>{const t=[],r={...e.endpointParams,...e.referenceRecord};let i=0;for(;i<n.length;){const a=n.indexOf("{",i);if(a===-1){t.push(n.slice(i));break}t.push(n.slice(i,a));const s=n.indexOf("}",a);if(s===-1){t.push(n.slice(a));break}n[a+1]==="{"&&n[s+1]==="}"&&(t.push(n.slice(a+1,s)),i=s+2);const o=n.substring(a+1,s);if(o.includes("#")){const[l,c]=o.split("#");t.push(hj(r[l],c))}else t.push(r[o]);i=s+1}return t.join("")},VTe=({ref:n},e)=>({...e.endpointParams,...e.referenceRecord})[n],uw=(n,e,t)=>{if(typeof n=="string")return fj(n,t);if(n.fn)return gj.callFunction(n,t);if(n.ref)return VTe(n,t);throw new Vs(`'${e}': ${String(n)} is not a string, function or reference.`)},mj=({fn:n,argv:e},t)=>{const r=e.map(a=>["boolean","number"].includes(typeof a)?a:gj.evaluateExpression(a,"arg",t)),i=n.split(".");return i[0]in KS&&i[1]!=null?KS[i[0]][i[1]](...r):HTe[n](...r)},gj={evaluateExpression:uw,callFunction:mj},YTe=({assign:n,...e},t)=>{if(n&&n in t.referenceRecord)throw new Vs(`'${n}' is already defined in Reference Record.`);const r=mj(e,t);return t.logger?.debug?.(`${o_} evaluateCondition: ${Ku(e)} = ${Ku(r)}`),{result:r===""?!0:!!r,...n!=null&&{toAssign:{name:n,value:r}}}},CM=(n=[],e)=>{const t={};for(const r of n){const{result:i,toAssign:a}=YTe(r,{...e,referenceRecord:{...e.referenceRecord,...t}});if(!i)return{result:i};a&&(t[a.name]=a.value,e.logger?.debug?.(`${o_} assign: ${a.name} := ${Ku(a.value)}`))}return{result:!0,referenceRecord:t}},KTe=(n,e)=>Object.entries(n).reduce((t,[r,i])=>({...t,[r]:i.map(a=>{const s=uw(a,"Header value entry",e);if(typeof s!="string")throw new Vs(`Header '${r}' value '${s}' is not a string`);return s})}),{}),_j=(n,e)=>Object.entries(n).reduce((t,[r,i])=>({...t,[r]:bj.getEndpointProperty(i,e)}),{}),vj=(n,e)=>{if(Array.isArray(n))return n.map(t=>vj(t,e));switch(typeof n){case"string":return fj(n,e);case"object":if(n===null)throw new Vs(`Unexpected endpoint property: ${n}`);return bj.getEndpointProperties(n,e);case"boolean":return n;default:throw new Vs(`Unexpected endpoint property type: ${typeof n}`)}},bj={getEndpointProperty:vj,getEndpointProperties:_j},QTe=(n,e)=>{const t=uw(n,"Endpoint URL",e);if(typeof t=="string")try{return new URL(t)}catch(r){throw console.error(`Failed to construct URL with ${t}`,r),r}throw new Vs(`Endpoint URL must be a string, got ${typeof t}`)},jTe=(n,e)=>{const{conditions:t,endpoint:r}=n,{result:i,referenceRecord:a}=CM(t,e);if(!i)return;const s={...e,referenceRecord:{...e.referenceRecord,...a}},{url:o,properties:l,headers:c}=r;return e.logger?.debug?.(`${o_} Resolving endpoint from template: ${Ku(r)}`),{...c!=null&&{headers:KTe(c,s)},...l!=null&&{properties:_j(l,s)},url:QTe(o,s)}},XTe=(n,e)=>{const{conditions:t,error:r}=n,{result:i,referenceRecord:a}=CM(t,e);if(i)throw new Vs(uw(r,"Error",{...e,referenceRecord:{...e.referenceRecord,...a}}))},yj=(n,e)=>{for(const t of n)if(t.type==="endpoint"){const r=jTe(t,e);if(r)return r}else if(t.type==="error")XTe(t,e);else if(t.type==="tree"){const r=Ej.evaluateTreeRule(t,e);if(r)return r}else throw new Vs(`Unknown endpoint rule: ${t}`);throw new Vs("Rules evaluation failed")},ZTe=(n,e)=>{const{conditions:t,rules:r}=n,{result:i,referenceRecord:a}=CM(t,e);if(i)return Ej.evaluateRules(r,{...e,referenceRecord:{...e.referenceRecord,...a}})},Ej={evaluateRules:yj,evaluateTreeRule:ZTe},JTe=(n,e)=>{const{endpointParams:t,logger:r}=e,{parameters:i,rules:a}=n;e.logger?.debug?.(`${o_} Initial EndpointParams: ${Ku(t)}`);const s=Object.entries(i).filter(([,c])=>c.default!=null).map(([c,u])=>[c,u.default]);if(s.length>0)for(const[c,u]of s)t[c]=t[c]??u;const o=Object.entries(i).filter(([,c])=>c.required).map(([c])=>c);for(const c of o)if(t[c]==null)throw new Vs(`Missing required parameter: '${c}'`);const l=yj(a,{endpointParams:t,logger:r,referenceRecord:{}});return e.logger?.debug?.(`${o_} Resolved endpoint: ${Ku(l)}`),l},Sj=(n,e=!1)=>{if(e){for(const t of n.split("."))if(!Sj(t))return!1;return!0}return!(!cw(n)||n.length<3||n.length>63||n!==n.toLowerCase()||pj(n))},b9=":",ewe="/",twe=n=>{const e=n.split(b9);if(e.length<6)return null;const[t,r,i,a,s,...o]=e;if(t!=="arn"||r===""||i===""||o.join(b9)==="")return null;const l=o.map(c=>c.split(ewe)).flat();return{partition:r,service:i,region:a,accountId:s,resourceId:l}},nwe=[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",regions:{"af-south-1":{description:"Africa (Cape Town)"},"ap-east-1":{description:"Asia Pacific (Hong Kong)"},"ap-east-2":{description:"Asia Pacific (Taipei)"},"ap-northeast-1":{description:"Asia Pacific (Tokyo)"},"ap-northeast-2":{description:"Asia Pacific (Seoul)"},"ap-northeast-3":{description:"Asia Pacific (Osaka)"},"ap-south-1":{description:"Asia Pacific (Mumbai)"},"ap-south-2":{description:"Asia Pacific (Hyderabad)"},"ap-southeast-1":{description:"Asia Pacific (Singapore)"},"ap-southeast-2":{description:"Asia Pacific (Sydney)"},"ap-southeast-3":{description:"Asia Pacific (Jakarta)"},"ap-southeast-4":{description:"Asia Pacific (Melbourne)"},"ap-southeast-5":{description:"Asia Pacific (Malaysia)"},"ap-southeast-6":{description:"Asia Pacific (New Zealand)"},"ap-southeast-7":{description:"Asia Pacific (Thailand)"},"aws-global":{description:"aws global region"},"ca-central-1":{description:"Canada (Central)"},"ca-west-1":{description:"Canada West (Calgary)"},"eu-central-1":{description:"Europe (Frankfurt)"},"eu-central-2":{description:"Europe (Zurich)"},"eu-north-1":{description:"Europe (Stockholm)"},"eu-south-1":{description:"Europe (Milan)"},"eu-south-2":{description:"Europe (Spain)"},"eu-west-1":{description:"Europe (Ireland)"},"eu-west-2":{description:"Europe (London)"},"eu-west-3":{description:"Europe (Paris)"},"il-central-1":{description:"Israel (Tel Aviv)"},"me-central-1":{description:"Middle East (UAE)"},"me-south-1":{description:"Middle East (Bahrain)"},"mx-central-1":{description:"Mexico (Central)"},"sa-east-1":{description:"South America (Sao Paulo)"},"us-east-1":{description:"US East (N. Virginia)"},"us-east-2":{description:"US East (Ohio)"},"us-west-1":{description:"US West (N. California)"},"us-west-2":{description:"US West (Oregon)"}}},{id:"aws-cn",outputs:{dnsSuffix:"amazonaws.com.cn",dualStackDnsSuffix:"api.amazonwebservices.com.cn",implicitGlobalRegion:"cn-northwest-1",name:"aws-cn",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^cn\\-\\w+\\-\\d+$",regions:{"aws-cn-global":{description:"aws-cn global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-eusc",outputs:{dnsSuffix:"amazonaws.eu",dualStackDnsSuffix:"api.amazonwebservices.eu",implicitGlobalRegion:"eusc-de-east-1",name:"aws-eusc",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eusc\\-(de)\\-\\w+\\-\\d+$",regions:{"eusc-de-east-1":{description:"AWS European Sovereign Cloud (Germany)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"api.aws.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"aws-iso global region"},"us-iso-east-1":{description:"US ISO East"},"us-iso-west-1":{description:"US ISO WEST"}}},{id:"aws-iso-b",outputs:{dnsSuffix:"sc2s.sgov.gov",dualStackDnsSuffix:"api.aws.scloud",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"aws-iso-b global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"},"us-isob-west-1":{description:"US ISOB West"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"api.cloud-aws.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"aws-iso-e-global":{description:"aws-iso-e global region"},"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"api.aws.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{"aws-iso-f-global":{description:"aws-iso-f global region"},"us-isof-east-1":{description:"US ISOF EAST"},"us-isof-south-1":{description:"US ISOF SOUTH"}}},{id:"aws-us-gov",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-gov-west-1",name:"aws-us-gov",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-gov\\-\\w+\\-\\d+$",regions:{"aws-us-gov-global":{description:"aws-us-gov global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}}],rwe={partitions:nwe};let iwe=rwe;const awe=n=>{const{partitions:e}=iwe;for(const r of e){const{regions:i,outputs:a}=r;for(const[s,o]of Object.entries(i))if(s===n)return{...a,...o}}for(const r of e){const{regionRegex:i,outputs:a}=r;if(new RegExp(i).test(n))return{...a}}const t=e.find(r=>r.id==="aws");if(!t)throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...t.outputs}},Tj={isVirtualHostableS3Bucket:Sj,parseArn:twe,partition:awe};KS.aws=Tj;function swe(n){const e={};if(n=n.replace(/^\?/,""),n)for(const t of n.split("&")){let[r,i=null]=t.split("=");r=decodeURIComponent(r),i&&(i=decodeURIComponent(i)),r in e?Array.isArray(e[r])?e[r].push(i):e[r]=[e[r],i]:e[r]=i}return e}const QS=n=>{if(typeof n=="string")return QS(new URL(n));const{hostname:e,pathname:t,port:r,protocol:i,search:a}=n;let s;return a&&(s=swe(a)),{hostname:e,port:r?parseInt(r):void 0,protocol:i,path:t,query:s}};function owe(n,e,t){return n.$source||(n.$source={}),n.$source[e]=t,n}function xl(n,e,t){n.__aws_sdk_context?n.__aws_sdk_context.features||(n.__aws_sdk_context.features={}):n.__aws_sdk_context={features:{}},n.__aws_sdk_context.features[e]=t}const y9=n=>Cp.isInstance(n)?n.headers?.date??n.headers?.Date:void 0,wj=n=>new Date(Date.now()+n),lwe=(n,e)=>Math.abs(wj(e).getTime()-n)>=3e5,E9=(n,e)=>{const t=Date.parse(n);return lwe(t,e)?t-Date.now():e},vg=(n,e)=>{if(!e)throw new Error(`Property \`${n}\` is not resolved for AWS SDK SigV4Auth`);return e},cwe=async n=>{const e=vg("context",n.context),t=vg("config",n.config),r=e.endpointV2?.properties?.authSchemes?.[0],a=await vg("signer",t.signer)(r),s=n?.signingRegion,o=n?.signingRegionSet,l=n?.signingName;return{config:t,signer:a,signingRegion:s,signingRegionSet:o,signingName:l}};class uwe{async sign(e,t,r){if(!Ka.isInstance(e))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const i=await cwe(r),{config:a,signer:s}=i;let{signingRegion:o,signingName:l}=i;const c=r.context;if(c?.authSchemes?.length??!1){const[d,p]=c.authSchemes;d?.name==="sigv4a"&&p?.name==="sigv4"&&(o=p?.signingRegion??o,l=p?.signingName??l)}return await s.sign(e,{signingDate:wj(a.systemClockOffset),signingRegion:o,signingService:l})}errorHandler(e){return t=>{const r=t.ServerTime??y9(t.$response);if(r){const i=vg("config",e.config),a=i.systemClockOffset;i.systemClockOffset=E9(r,i.systemClockOffset),i.systemClockOffset!==a&&t.$metadata&&(t.$metadata.clockSkewCorrected=!0)}throw t}}successHandler(e,t){const r=y9(e);if(r){const i=vg("config",t.config);i.systemClockOffset=E9(r,i.systemClockOffset)}}}const dwe=(n,e,t)=>{let r,i,a,s=!1;const o=async()=>{i||(i=n());try{r=await i,a=!0,s=!1}finally{i=void 0}return r};return async l=>((!a||l?.forceRefresh)&&(r=await o()),r)},pwe="X-Amz-Algorithm",hwe="X-Amz-Credential",xj="X-Amz-Date",fwe="X-Amz-SignedHeaders",mwe="X-Amz-Expires",Cj="X-Amz-Signature",Aj="X-Amz-Security-Token",Rj="authorization",kj=xj.toLowerCase(),gwe="date",_we=[Rj,kj,gwe],vwe=Cj.toLowerCase(),HN="x-amz-content-sha256",bwe=Aj.toLowerCase(),ywe={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},Ewe=/^proxy-/,Swe=/^sec-/,cC="AWS4-HMAC-SHA256",Twe="AWS4-HMAC-SHA256-PAYLOAD",wwe="UNSIGNED-PAYLOAD",xwe=50,Ij="aws4_request",Cwe=3600*24*7,Gb={},uC=[],dC=(n,e,t)=>`${n}/${e}/${t}/${Ij}`,Awe=async(n,e,t,r,i)=>{const a=await S9(n,e.secretAccessKey,e.accessKeyId),s=`${t}:${r}:${i}:${ps(a)}:${e.sessionToken}`;if(s in Gb)return Gb[s];for(uC.push(s);uC.length>xwe;)delete Gb[uC.shift()];let o=`AWS4${e.secretAccessKey}`;for(const l of[t,r,i,Ij])o=await S9(n,o,l);return Gb[s]=o},S9=(n,e,t)=>{const r=new n(e);return r.update(i_(t)),r.digest()},T9=({headers:n},e,t)=>{const r={};for(const i of Object.keys(n).sort()){if(n[i]==null)continue;const a=i.toLowerCase();(a in ywe||e?.has(a)||Ewe.test(a)||Swe.test(a))&&(!t||t&&!t.has(a))||(r[a]=n[i].trim().replace(/\s+/g," "))}return r},Rwe=n=>typeof ArrayBuffer=="function"&&n instanceof ArrayBuffer||Object.prototype.toString.call(n)==="[object ArrayBuffer]",pC=async({headers:n,body:e},t)=>{for(const r of Object.keys(n))if(r.toLowerCase()===HN)return n[r];if(e==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if(typeof e=="string"||ArrayBuffer.isView(e)||Rwe(e)){const r=new t;return r.update(i_(e)),ps(await r.digest())}return wwe};class kwe{format(e){const t=[];for(const a of Object.keys(e)){const s=Rp(a);t.push(Uint8Array.from([s.byteLength]),s,this.formatHeaderValue(e[a]))}const r=new Uint8Array(t.reduce((a,s)=>a+s.byteLength,0));let i=0;for(const a of t)r.set(a,i),i+=a.byteLength;return r}formatHeaderValue(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":const t=new DataView(new ArrayBuffer(3));return t.setUint8(0,3),t.setInt16(1,e.value,!1),new Uint8Array(t.buffer);case"integer":const r=new DataView(new ArrayBuffer(5));return r.setUint8(0,4),r.setInt32(1,e.value,!1),new Uint8Array(r.buffer);case"long":const i=new Uint8Array(9);return i[0]=5,i.set(e.value.bytes,1),i;case"binary":const a=new DataView(new ArrayBuffer(3+e.value.byteLength));a.setUint8(0,6),a.setUint16(1,e.value.byteLength,!1);const s=new Uint8Array(a.buffer);return s.set(e.value,3),s;case"string":const o=Rp(e.value),l=new DataView(new ArrayBuffer(3+o.byteLength));l.setUint8(0,7),l.setUint16(1,o.byteLength,!1);const c=new Uint8Array(l.buffer);return c.set(o,3),c;case"timestamp":const u=new Uint8Array(9);return u[0]=8,u.set(Nwe.fromNumber(e.value.valueOf()).bytes,1),u;case"uuid":if(!Iwe.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(bM(e.value.replace(/\-/g,"")),1),d}}}var w9;(function(n){n[n.boolTrue=0]="boolTrue",n[n.boolFalse=1]="boolFalse",n[n.byte=2]="byte",n[n.short=3]="short",n[n.integer=4]="integer",n[n.long=5]="long",n[n.byteArray=6]="byteArray",n[n.string=7]="string",n[n.timestamp=8]="timestamp",n[n.uuid=9]="uuid"})(w9||(w9={}));const Iwe=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;let Nwe=class Nj{bytes;constructor(e){if(this.bytes=e,e.byteLength!==8)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>9223372036854776e3||e<-9223372036854776e3)throw new Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);const t=new Uint8Array(8);for(let r=7,i=Math.abs(Math.round(e));r>-1&&i>0;r--,i/=256)t[r]=i;return e<0&&x9(t),new Nj(t)}valueOf(){const e=this.bytes.slice(0),t=e[0]&128;return t&&x9(e),parseInt(ps(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}};function x9(n){for(let e=0;e<8;e++)n[e]^=255;for(let e=7;e>-1&&(n[e]++,n[e]===0);e--);}const Dwe=(n,e)=>{n=n.toLowerCase();for(const t of Object.keys(e))if(n===t.toLowerCase())return!0;return!1},Owe=(n,e={})=>{const{headers:t,query:r={}}=Ka.clone(n);for(const i of Object.keys(t)){const a=i.toLowerCase();(a.slice(0,6)==="x-amz-"&&!e.unhoistableHeaders?.has(a)||e.hoistableHeaders?.has(a))&&(r[i]=t[i],delete t[i])}return{...n,headers:t,query:r}},C9=n=>{n=Ka.clone(n);for(const e of Object.keys(n.headers))_we.indexOf(e.toLowerCase())>-1&&delete n.headers[e];return n},Pwe=({query:n={}})=>{const e=[],t={};for(const r of Object.keys(n)){if(r.toLowerCase()===vwe)continue;const i=fp(r);e.push(i);const a=n[r];typeof a=="string"?t[i]=`${i}=${fp(a)}`:Array.isArray(a)&&(t[i]=a.slice(0).reduce((s,o)=>s.concat([`${i}=${fp(o)}`]),[]).sort().join("&"))}return e.sort().map(r=>t[r]).filter(r=>r).join("&")},Mwe=n=>Lwe(n).toISOString().replace(/\.\d{3}Z$/,"Z"),Lwe=n=>typeof n=="number"?new Date(n*1e3):typeof n=="string"?Number(n)?new Date(Number(n)*1e3):new Date(n):n;class Fwe{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:e,credentials:t,region:r,service:i,sha256:a,uriEscapePath:s=!0}){this.service=i,this.sha256=a,this.uriEscapePath=s,this.applyChecksum=typeof e=="boolean"?e:!0,this.regionProvider=Uc(r),this.credentialProvider=Uc(t)}createCanonicalRequest(e,t,r){const i=Object.keys(t).sort();return`${e.method}
|
|
130
130
|
${this.getCanonicalPath(e)}
|
|
131
131
|
${Pwe(e)}
|
|
132
132
|
${i.map(a=>`${a}:${t[a]}`).join(`
|
|
@@ -137,13 +137,13 @@ ${r}`}async createStringToSign(e,t,r,i){const a=new this.sha256;a.update(i_(r));
|
|
|
137
137
|
${e}
|
|
138
138
|
${t}
|
|
139
139
|
${ps(s)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){const t=[];for(const a of e.split("/"))a?.length!==0&&a!=="."&&(a===".."?t.pop():t.push(a));const r=`${e?.startsWith("/")?"/":""}${t.join("/")}${t.length>0&&e?.endsWith("/")?"/":""}`;return fp(r).replace(/%2F/g,"/")}return e}validateResolvedCredentials(e){if(typeof e!="object"||typeof e.accessKeyId!="string"||typeof e.secretAccessKey!="string")throw new Error("Resolved credential object is not valid")}formatDate(e){const t=Mwe(e).replace(/[\-:]/g,"");return{longDate:t,shortDate:t.slice(0,8)}}getCanonicalHeaderList(e){return Object.keys(e).sort().join(";")}}class A9 extends Fwe{headerFormatter=new kwe;constructor({applyChecksum:e,credentials:t,region:r,service:i,sha256:a,uriEscapePath:s=!0}){super({applyChecksum:e,credentials:t,region:r,service:i,sha256:a,uriEscapePath:s})}async presign(e,t={}){const{signingDate:r=new Date,expiresIn:i=3600,unsignableHeaders:a,unhoistableHeaders:s,signableHeaders:o,hoistableHeaders:l,signingRegion:c,signingService:u}=t,d=await this.credentialProvider();this.validateResolvedCredentials(d);const p=c??await this.regionProvider(),{longDate:h,shortDate:f}=this.formatDate(r);if(i>Cwe)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");const m=dC(f,p,u??this.service),g=Owe(C9(e),{unhoistableHeaders:s,hoistableHeaders:l});d.sessionToken&&(g.query[Aj]=d.sessionToken),g.query[pwe]=cC,g.query[hwe]=`${d.accessKeyId}/${m}`,g.query[xj]=h,g.query[mwe]=i.toString(10);const _=T9(g,a,o);return g.query[fwe]=this.getCanonicalHeaderList(_),g.query[Cj]=await this.getSignature(h,m,this.getSigningKey(d,p,f,u),this.createCanonicalRequest(g,_,await pC(e,this.sha256))),g}async sign(e,t){return typeof e=="string"?this.signString(e,t):e.headers&&e.payload?this.signEvent(e,t):e.message?this.signMessage(e,t):this.signRequest(e,t)}async signEvent({headers:e,payload:t},{signingDate:r=new Date,priorSignature:i,signingRegion:a,signingService:s}){const o=a??await this.regionProvider(),{shortDate:l,longDate:c}=this.formatDate(r),u=dC(l,o,s??this.service),d=await pC({headers:{},body:t},this.sha256),p=new this.sha256;p.update(e);const h=ps(await p.digest()),f=[Twe,c,u,i,h,d].join(`
|
|
140
|
-
`);return this.signString(f,{signingDate:r,signingRegion:o,signingService:s})}async signMessage(e,{signingDate:t=new Date,signingRegion:r,signingService:i}){return this.signEvent({headers:this.headerFormatter.format(e.message.headers),payload:e.message.body},{signingDate:t,signingRegion:r,signingService:i,priorSignature:e.priorSignature}).then(s=>({message:e.message,signature:s}))}async signString(e,{signingDate:t=new Date,signingRegion:r,signingService:i}={}){const a=await this.credentialProvider();this.validateResolvedCredentials(a);const s=r??await this.regionProvider(),{shortDate:o}=this.formatDate(t),l=new this.sha256(await this.getSigningKey(a,s,o,i));return l.update(i_(e)),ps(await l.digest())}async signRequest(e,{signingDate:t=new Date,signableHeaders:r,unsignableHeaders:i,signingRegion:a,signingService:s}={}){const o=await this.credentialProvider();this.validateResolvedCredentials(o);const l=a??await this.regionProvider(),c=C9(e),{longDate:u,shortDate:d}=this.formatDate(t),p=dC(d,l,s??this.service);c.headers[kj]=u,o.sessionToken&&(c.headers[bwe]=o.sessionToken);const h=await pC(c,this.sha256);!Dwe(HN,c.headers)&&this.applyChecksum&&(c.headers[HN]=h);const f=T9(c,i,r),m=await this.getSignature(u,p,this.getSigningKey(o,l,d,s),this.createCanonicalRequest(c,f,h));return c.headers[Rj]=`${cC} Credential=${o.accessKeyId}/${p}, SignedHeaders=${this.getCanonicalHeaderList(f)}, Signature=${m}`,c}async getSignature(e,t,r,i){const a=await this.createStringToSign(e,t,i,cC),s=new this.sha256(await r);return s.update(i_(a)),ps(await s.digest())}getSigningKey(e,t,r,i){return Awe(this.sha256,e,r,t,i||this.service)}}const Uwe=n=>{let e=n.credentials,t=!!n.credentials,r;Object.defineProperty(n,"credentials",{set(c){c&&c!==e&&c!==r&&(t=!0),e=c;const u=Bwe(n,{credentials:e,credentialDefaultProvider:n.credentialDefaultProvider}),d=$we(n,u);if(t&&!d.attributed){const p=typeof e=="object"&&e!==null;r=async h=>{const m=await d(h);return p&&(!m.$source||Object.keys(m.$source).length===0)?owe(m,"CREDENTIALS_CODE","e"):m},r.memoized=d.memoized,r.configBound=d.configBound,r.attributed=!0}else r=d},get(){return r},enumerable:!0,configurable:!0}),n.credentials=e;const{signingEscapePath:i=!0,systemClockOffset:a=n.systemClockOffset||0,sha256:s}=n;let o;return n.signer?o=gg(n.signer):n.regionInfoProvider?o=()=>gg(n.region)().then(async c=>[await n.regionInfoProvider(c,{useFipsEndpoint:await n.useFipsEndpoint(),useDualstackEndpoint:await n.useDualstackEndpoint()})||{},c]).then(([c,u])=>{const{signingRegion:d,signingService:p}=c;n.signingRegion=n.signingRegion||d||u,n.signingName=n.signingName||p||n.serviceId;const h={...n,credentials:n.credentials,region:n.signingRegion,service:n.signingName,sha256:s,uriEscapePath:i},f=n.signerConstructor||A9;return new f(h)}):o=async c=>{c=Object.assign({},{name:"sigv4",signingName:n.signingName||n.defaultSigningName,signingRegion:await gg(n.region)(),properties:{}},c);const u=c.signingRegion,d=c.signingName;n.signingRegion=n.signingRegion||u,n.signingName=n.signingName||d||n.serviceId;const p={...n,credentials:n.credentials,region:n.signingRegion,service:n.signingName,sha256:s,uriEscapePath:i},h=n.signerConstructor||A9;return new h(p)},Object.assign(n,{systemClockOffset:a,signingEscapePath:i,signer:o})};function Bwe(n,{credentials:e,credentialDefaultProvider:t}){let r;return e?e?.memoized?r=e:r=dj(e,uj,xM):t?r=gg(t(Object.assign({},n,{parentClientConfig:n}))):r=async()=>{throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")},r.memoized=!0,r}function $we(n,e){if(e.configBound)return e;const t=async r=>e({...r,callerClientConfig:n});return t.memoized=e.memoized,t.configBound=!0,t}const R9=typeof TextEncoder=="function"?new TextEncoder:null,Gwe=n=>{if(typeof n=="string"){if(R9)return R9.encode(n).byteLength;let e=n.length;for(let t=e-1;t>=0;t--){const r=n.charCodeAt(t);r>127&&r<=2047?e++:r>2047&&r<=65535&&(e+=2),r>=56320&&r<=57343&&t--}return e}else{if(typeof n.byteLength=="number")return n.byteLength;if(typeof n.size=="number")return n.size}throw new Error(`Body Length computation failed for ${n}`)},Dd=(n,e)=>{const t=[];if(n&&t.push(n),e)for(const r of e)t.push(r);return t},Su=(n,e)=>`${n||"anonymous"}${e&&e.length>0?` (a.k.a. ${e.join(",")})`:""}`,jS=()=>{let n=[],e=[],t=!1;const r=new Set,i=d=>d.sort((p,h)=>k9[h.step]-k9[p.step]||I9[h.priority||"normal"]-I9[p.priority||"normal"]),a=d=>{let p=!1;const h=f=>{const m=Dd(f.name,f.aliases);if(m.includes(d)){p=!0;for(const g of m)r.delete(g);return!1}return!0};return n=n.filter(h),e=e.filter(h),p},s=d=>{let p=!1;const h=f=>{if(f.middleware===d){p=!0;for(const m of Dd(f.name,f.aliases))r.delete(m);return!1}return!0};return n=n.filter(h),e=e.filter(h),p},o=d=>(n.forEach(p=>{d.add(p.middleware,{...p})}),e.forEach(p=>{d.addRelativeTo(p.middleware,{...p})}),d.identifyOnResolve?.(u.identifyOnResolve()),d),l=d=>{const p=[];return d.before.forEach(h=>{h.before.length===0&&h.after.length===0?p.push(h):p.push(...l(h))}),p.push(d),d.after.reverse().forEach(h=>{h.before.length===0&&h.after.length===0?p.push(h):p.push(...l(h))}),p},c=(d=!1)=>{const p=[],h=[],f={};return n.forEach(g=>{const _={...g,before:[],after:[]};for(const v of Dd(_.name,_.aliases))f[v]=_;p.push(_)}),e.forEach(g=>{const _={...g,before:[],after:[]};for(const v of Dd(_.name,_.aliases))f[v]=_;h.push(_)}),h.forEach(g=>{if(g.toMiddleware){const _=f[g.toMiddleware];if(_===void 0){if(d)return;throw new Error(`${g.toMiddleware} is not found when adding ${Su(g.name,g.aliases)} middleware ${g.relation} ${g.toMiddleware}`)}g.relation==="after"&&_.after.push(g),g.relation==="before"&&_.before.push(g)}}),i(p).map(l).reduce((g,_)=>(g.push(..._),g),[])},u={add:(d,p={})=>{const{name:h,override:f,aliases:m}=p,g={step:"initialize",priority:"normal",middleware:d,...p},_=Dd(h,m);if(_.length>0){if(_.some(v=>r.has(v))){if(!f)throw new Error(`Duplicate middleware name '${Su(h,m)}'`);for(const v of _){const b=n.findIndex(S=>S.name===v||S.aliases?.some(w=>w===v));if(b===-1)continue;const E=n[b];if(E.step!==g.step||g.priority!==E.priority)throw new Error(`"${Su(E.name,E.aliases)}" middleware with ${E.priority} priority in ${E.step} step cannot be overridden by "${Su(h,m)}" middleware with ${g.priority} priority in ${g.step} step.`);n.splice(b,1)}}for(const v of _)r.add(v)}n.push(g)},addRelativeTo:(d,p)=>{const{name:h,override:f,aliases:m}=p,g={middleware:d,...p},_=Dd(h,m);if(_.length>0){if(_.some(v=>r.has(v))){if(!f)throw new Error(`Duplicate middleware name '${Su(h,m)}'`);for(const v of _){const b=e.findIndex(S=>S.name===v||S.aliases?.some(w=>w===v));if(b===-1)continue;const E=e[b];if(E.toMiddleware!==g.toMiddleware||E.relation!==g.relation)throw new Error(`"${Su(E.name,E.aliases)}" middleware ${E.relation} "${E.toMiddleware}" middleware cannot be overridden by "${Su(h,m)}" middleware ${g.relation} "${g.toMiddleware}" middleware.`);e.splice(b,1)}}for(const v of _)r.add(v)}e.push(g)},clone:()=>o(jS()),use:d=>{d.applyToStack(u)},remove:d=>typeof d=="string"?a(d):s(d),removeByTag:d=>{let p=!1;const h=f=>{const{tags:m,name:g,aliases:_}=f;if(m&&m.includes(d)){const v=Dd(g,_);for(const b of v)r.delete(b);return p=!0,!1}return!0};return n=n.filter(h),e=e.filter(h),p},concat:d=>{const p=o(jS());return p.use(d),p.identifyOnResolve(t||p.identifyOnResolve()||(d.identifyOnResolve?.()??!1)),p},applyToStack:o,identify:()=>c(!0).map(d=>{const p=d.step??d.relation+" "+d.toMiddleware;return Su(d.name,d.aliases)+" - "+p}),identifyOnResolve(d){return typeof d=="boolean"&&(t=d),t},resolve:(d,p)=>{for(const h of c().map(f=>f.middleware).reverse())d=h(d,p);return t&&console.log(u.identify()),d}};return u},k9={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},I9={high:3,normal:2,low:1};class Wwe{config;middlewareStack=jS();initConfig;handlers;constructor(e){this.config=e;const{protocol:t,protocolSettings:r}=e;r&&typeof t=="function"&&(e.protocol=new t(r))}send(e,t,r){const i=typeof t!="function"?t:void 0,a=typeof t=="function"?t:r,s=i===void 0&&this.config.cacheMiddleware===!0;let o;if(s){this.handlers||(this.handlers=new WeakMap);const l=this.handlers;l.has(e.constructor)?o=l.get(e.constructor):(o=e.resolveMiddleware(this.middlewareStack,this.config,i),l.set(e.constructor,o))}else delete this.handlers,o=e.resolveMiddleware(this.middlewareStack,this.config,i);if(a)o(e).then(l=>a(null,l.output),l=>a(l)).catch(()=>{});else return o(e).then(l=>l.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}const hC="***SensitiveInformation***";function VN(n,e){if(e==null)return e;const t=yr.of(n);if(t.getMergedTraits().sensitive)return hC;if(t.isListSchema()){if(!!t.getValueSchema().getMergedTraits().sensitive)return hC}else if(t.isMapSchema()){if(!!t.getKeySchema().getMergedTraits().sensitive||!!t.getValueSchema().getMergedTraits().sensitive)return hC}else if(t.isStructSchema()&&typeof e=="object"){const r=e,i={};for(const[a,s]of t.structIterator())r[a]!=null&&(i[a]=VN(s,r[a]));return i}return e}class Dj{middlewareStack=jS();schema;static classBuilder(){return new zwe}resolveMiddlewareWithContext(e,t,r,{middlewareFn:i,clientName:a,commandName:s,inputFilterSensitiveLog:o,outputFilterSensitiveLog:l,smithyContext:c,additionalContext:u,CommandCtor:d}){for(const g of i.bind(this)(d,e,t,r))this.middlewareStack.use(g);const p=e.concat(this.middlewareStack),{logger:h}=t,f={logger:h,clientName:a,commandName:s,inputFilterSensitiveLog:o,outputFilterSensitiveLog:l,[WN]:{commandInstance:this,...c},...u},{requestHandler:m}=t;return p.resolve(g=>m.handle(g.request,r||{}),f)}}class zwe{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(e){this._init=e}ep(e){return this._ep=e,this}m(e){return this._middlewareFn=e,this}s(e,t,r={}){return this._smithyContext={service:e,operation:t,...r},this}c(e={}){return this._additionalContext=e,this}n(e,t){return this._clientName=e,this._commandName=t,this}f(e=r=>r,t=r=>r){return this._inputFilterSensitiveLog=e,this._outputFilterSensitiveLog=t,this}ser(e){return this._serializer=e,this}de(e){return this._deserializer=e,this}sc(e){return this._operationSchema=e,this._smithyContext.operationSchema=e,this}build(){const e=this;let t;return t=class extends Dj{input;static getEndpointParameterInstructions(){return e._ep}constructor(...[r]){super(),this.input=r??{},e._init(this),this.schema=e._operationSchema}resolveMiddleware(r,i,a){const s=e._operationSchema,o=s?.[4]??s?.input,l=s?.[5]??s?.output;return this.resolveMiddlewareWithContext(r,i,a,{CommandCtor:t,middlewareFn:e._middlewareFn,clientName:e._clientName,commandName:e._commandName,inputFilterSensitiveLog:e._inputFilterSensitiveLog??(s?VN.bind(null,o):c=>c),outputFilterSensitiveLog:e._outputFilterSensitiveLog??(s?VN.bind(null,l):c=>c),smithyContext:e._smithyContext,additionalContext:e._additionalContext})}serialize=e._serializer;deserialize=e._deserializer}}}class of extends Error{$fault;$response;$retryable;$metadata;constructor(e){super(e.message),Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=e.name,this.$fault=e.$fault,this.$metadata=e.$metadata}static isInstance(e){if(!e)return!1;const t=e;return of.prototype.isPrototypeOf(t)||!!t.$fault&&!!t.$metadata&&(t.$fault==="client"||t.$fault==="server")}static[Symbol.hasInstance](e){if(!e)return!1;const t=e;return this===of?of.isInstance(e):of.isInstance(e)?t.name&&this.name?this.prototype.isPrototypeOf(e)||t.name===this.name:this.prototype.isPrototypeOf(e):!1}}const N9=(n,e={})=>{Object.entries(e).filter(([,r])=>r!==void 0).forEach(([r,i])=>{(n[r]==null||n[r]==="")&&(n[r]=i)});const t=n.message||n.Message||"UnknownError";return n.message=t,delete n.Message,n},qwe=n=>{switch(n){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}},Oj=Object.values(r_),Hwe=n=>{const e=[];for(const t in r_){const r=r_[t];n[r]!==void 0&&e.push({algorithmId:()=>r,checksumConstructor:()=>n[r]})}for(const[t,r]of Object.entries(n.checksumAlgorithms??{}))e.push({algorithmId:()=>t,checksumConstructor:()=>r});return{addChecksumAlgorithm(t){n.checksumAlgorithms=n.checksumAlgorithms??{};const r=t.algorithmId(),i=t.checksumConstructor();Oj.includes(r)?n.checksumAlgorithms[r.toUpperCase()]=i:n.checksumAlgorithms[r]=i,e.push(t)},checksumAlgorithms(){return e}}},Vwe=n=>{const e={};return n.checksumAlgorithms().forEach(t=>{const r=t.algorithmId();Oj.includes(r)&&(e[r]=t.checksumConstructor())}),e},Ywe=n=>({setRetryStrategy(e){n.retryStrategy=e},retryStrategy(){return n.retryStrategy}}),Kwe=n=>{const e={};return e.retryStrategy=n.retryStrategy(),e},Qwe=n=>Object.assign(Hwe(n),Ywe(n)),jwe=n=>Object.assign(Vwe(n),Kwe(n));class Pj{trace(){}debug(){}info(){}warn(){}error(){}}class Xwe{queryCompat;constructor(e=!1){this.queryCompat=e}resolveRestContentType(e,t){const r=t.getMemberSchemas(),i=Object.values(r).find(a=>!!a.getMergedTraits().httpPayload);if(i){const a=i.getMergedTraits().mediaType;return a||(i.isStringSchema()?"text/plain":i.isBlobSchema()?"application/octet-stream":e)}else if(!t.isUnitSchema()&&Object.values(r).find(s=>{const{httpQuery:o,httpQueryParams:l,httpHeader:c,httpLabel:u,httpPrefixHeaders:d}=s.getMergedTraits();return!o&&!l&&!c&&!u&&d===void 0}))return e}async getErrorSchemaOrThrowBaseException(e,t,r,i,a,s){let o=t,l=e;e.includes("#")&&([o,l]=e.split("#"));const c={$metadata:a,$fault:r.statusCode<500?"client":"server"},u=cs.for(o);try{return{errorSchema:s?.(u,l)??u.getSchema(e),errorMetadata:c}}catch{i.message=i.message??i.Message??"UnknownError";const p=cs.for("smithy.ts.sdk.synthetic."+o),h=p.getBaseException();if(h){const f=p.getErrorCtor(h)??Error;throw this.decorateServiceException(Object.assign(new f({name:l}),c),i)}throw this.decorateServiceException(Object.assign(new Error(l),c),i)}}decorateServiceException(e,t={}){if(this.queryCompat){const r=e.Message??t.Message,i=N9(e,t);r&&(i.message=r),i.Error={...i.Error,Type:i.Error?.Type,Code:i.Error?.Code,Message:i.Error?.message??i.Error?.Message??r};const a=i.$metadata.requestId;return a&&(i.RequestId=a),i}return N9(e,t)}setQueryCompatError(e,t){const r=t.headers?.["x-amzn-query-error"];if(e!==void 0&&r!=null){const[i,a]=r.split(";"),s=Object.entries(e),o={Code:i,Type:a};Object.assign(e,o);for(const[l,c]of s)o[l==="message"?"Message":l]=c;delete o.__type,e.Error=o}}queryCompatOutput(e,t){e.Error&&(t.Error=e.Error),e.Type&&(t.Type=e.Type),e.Code&&(t.Code=e.Code)}findQueryCompatibleError(e,t){try{return e.getSchema(t)}catch{return e.find(i=>yr.of(i).getMergedTraits().awsQueryError?.[0]===t)}}}class AM{serdeContext;setSerdeContext(e){this.serdeContext=e}}class Zwe{from;to;keys;constructor(e,t){this.from=e,this.to=t,this.keys=new Set(Object.keys(this.from).filter(r=>r!=="__type"))}mark(e){this.keys.delete(e)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){const e=this.keys.values().next().value,t=this.from[e];this.to.$unknown=[e,t]}}}function Jwe(n,e,t){if(t?.source){const r=t.source;if(typeof e=="number"&&(e>Number.MAX_SAFE_INTEGER||e<Number.MIN_SAFE_INTEGER||r!==String(e)))return r.includes(".")?new tl(r,"bigDecimal"):BigInt(r)}return e}const exe=(n,e)=>V0(n,e).then(t=>(e?.utf8Encoder??vm)(t)),txe=(n,e)=>exe(n,e).then(t=>{if(t.length)try{return JSON.parse(t)}catch(r){throw r?.name==="SyntaxError"&&Object.defineProperty(r,"$responseBodyText",{value:t}),r}return{}}),nxe=(n,e)=>{const t=(a,s)=>Object.keys(a).find(o=>o.toLowerCase()===s.toLowerCase()),r=a=>{let s=a;return typeof s=="number"&&(s=s.toString()),s.indexOf(",")>=0&&(s=s.split(",")[0]),s.indexOf(":")>=0&&(s=s.split(":")[0]),s.indexOf("#")>=0&&(s=s.split("#")[1]),s},i=t(n.headers,"x-amzn-errortype");if(i!==void 0)return r(n.headers[i]);if(e&&typeof e=="object"){const a=t(e,"code");if(a&&e[a]!==void 0)return r(e[a]);if(e.__type!==void 0)return r(e.__type)}};class rxe extends AM{settings;constructor(e){super(),this.settings=e}async read(e,t){return this._read(e,typeof t=="string"?JSON.parse(t,Jwe):await txe(t,this.serdeContext))}readObject(e,t){return this._read(e,t)}_read(e,t){const r=t!==null&&typeof t=="object",i=yr.of(e);if(r){if(i.isStructSchema()){const s=t,o=i.isUnionSchema(),l={};let c;const{jsonName:u}=this.settings;u&&(c={});let d;o&&(d=new Zwe(s,l));for(const[p,h]of i.structIterator()){let f=p;u&&(f=h.getMergedTraits().jsonName??f,c[f]=p),o&&d.mark(f),s[f]!=null&&(l[p]=this._read(h,s[f]))}if(o)d.writeUnknown();else if(typeof s.__type=="string")for(const[p,h]of Object.entries(s)){const f=u?c[p]??p:p;f in l||(l[f]=h)}return l}if(Array.isArray(t)&&i.isListSchema()){const s=i.getValueSchema(),o=[],l=!!i.getMergedTraits().sparse;for(const c of t)(l||c!=null)&&o.push(this._read(s,c));return o}if(i.isMapSchema()){const s=i.getValueSchema(),o={},l=!!i.getMergedTraits().sparse;for(const[c,u]of Object.entries(t))(l||u!=null)&&(o[c]=this._read(s,u));return o}}if(i.isBlobSchema()&&typeof t=="string")return Ap(t);const a=i.getMergedTraits().mediaType;if(i.isStringSchema()&&typeof t=="string"&&a)return a==="application/json"||a.endsWith("+json")?Vl.from(t):t;if(i.isTimestampSchema()&&t!=null)switch(lw(i,this.settings)){case 5:return j1e(t);case 6:return eTe(t);case 7:return tTe(t);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",t),new Date(t)}if(i.isBigIntegerSchema()&&(typeof t=="number"||typeof t=="string"))return BigInt(t);if(i.isBigDecimalSchema()&&t!=null){if(t instanceof tl)return t;const s=t;return s.type==="bigDecimal"&&"string"in s?new tl(s.string,s.type):new tl(String(t),"bigDecimal")}if(i.isNumericSchema()&&typeof t=="string"){switch(t){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return t}if(i.isDocumentSchema())if(r){const s=Array.isArray(t)?[]:{};for(const[o,l]of Object.entries(t))l instanceof tl?s[o]=l:s[o]=this._read(i,l);return s}else return structuredClone(t);return t}}const D9="Ν";class ixe{values=new Map;counter=0;stage=0;createReplacer(){if(this.stage===1)throw new Error("@aws-sdk/core/protocols - JsonReplacer already created.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");return this.stage=1,(e,t)=>{if(t instanceof tl){const r=`${D9+"nv"+this.counter++}_`+t.string;return this.values.set(`"${r}"`,t.string),r}if(typeof t=="bigint"){const r=t.toString(),i=`${D9+"b"+this.counter++}_`+r;return this.values.set(`"${i}"`,r),i}return t}}replaceInJson(e){if(this.stage===0)throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");if(this.stage=2,this.counter===0)return e;for(const[t,r]of this.values)e=e.replace(t,r);return e}}class axe extends AM{settings;buffer;useReplacer=!1;rootSchema;constructor(e){super(),this.settings=e}write(e,t){this.rootSchema=yr.of(e),this.buffer=this._write(this.rootSchema,t)}writeDiscriminatedDocument(e,t){this.write(e,t),typeof this.buffer=="object"&&(this.buffer.__type=yr.of(e).getName(!0))}flush(){const{rootSchema:e,useReplacer:t}=this;if(this.rootSchema=void 0,this.useReplacer=!1,e?.isStructSchema()||e?.isDocumentSchema()){if(!t)return JSON.stringify(this.buffer);const r=new ixe;return r.replaceInJson(JSON.stringify(this.buffer,r.createReplacer(),0))}return this.buffer}_write(e,t,r){const i=t!==null&&typeof t=="object",a=yr.of(e);if(i){if(a.isStructSchema()){const s=t,o={},{jsonName:l}=this.settings;let c;l&&(c={});for(const[u,d]of a.structIterator()){const p=this._write(d,s[u],a);if(p!==void 0){let h=u;l&&(h=d.getMergedTraits().jsonName??u,c[u]=h),o[h]=p}}if(a.isUnionSchema()&&Object.keys(o).length===0){const{$unknown:u}=s;if(Array.isArray(u)){const[d,p]=u;o[d]=this._write(15,p)}}else if(typeof s.__type=="string")for(const[u,d]of Object.entries(s)){const p=l?c[u]??u:u;p in o||(o[p]=this._write(15,d))}return o}if(Array.isArray(t)&&a.isListSchema()){const s=a.getValueSchema(),o=[],l=!!a.getMergedTraits().sparse;for(const c of t)(l||c!=null)&&o.push(this._write(s,c));return o}if(a.isMapSchema()){const s=a.getValueSchema(),o={},l=!!a.getMergedTraits().sparse;for(const[c,u]of Object.entries(t))(l||u!=null)&&(o[c]=this._write(s,u));return o}if(t instanceof Uint8Array&&(a.isBlobSchema()||a.isDocumentSchema()))return a===this.rootSchema?t:(this.serdeContext?.base64Encoder??kp)(t);if(t instanceof Date&&(a.isTimestampSchema()||a.isDocumentSchema()))switch(lw(a,this.settings)){case 5:return t.toISOString().replace(".000Z","Z");case 6:return sj(t);case 7:return t.getTime()/1e3;default:return console.warn("Missing timestamp format, using epoch seconds",t),t.getTime()/1e3}t instanceof tl&&(this.useReplacer=!0)}if(!(t===null&&r?.isStructSchema())){if(a.isStringSchema()){if(typeof t>"u"&&a.isIdempotencyToken())return EM();const s=a.getMergedTraits().mediaType;return t!=null&&s&&(s==="application/json"||s.endsWith("+json"))?Vl.from(t):t}if(typeof t=="number"&&a.isNumericSchema())return Math.abs(t)===1/0||isNaN(t)?String(t):t;if(typeof t=="string"&&a.isBlobSchema())return a===this.rootSchema?t:(this.serdeContext?.base64Encoder??kp)(t);if(typeof t=="bigint"&&(this.useReplacer=!0),a.isDocumentSchema())if(i){const s=Array.isArray(t)?[]:{};for(const[o,l]of Object.entries(t))l instanceof tl?(this.useReplacer=!0,s[o]=l):s[o]=this._write(a,l);return s}else return structuredClone(t);return t}}}class sxe extends AM{settings;constructor(e){super(),this.settings=e}createSerializer(){const e=new axe(this.settings);return e.setSerdeContext(this.serdeContext),e}createDeserializer(){const e=new rxe(this.settings);return e.setSerdeContext(this.serdeContext),e}}class oxe extends ETe{serializer;deserializer;codec;mixin=new Xwe;constructor({defaultNamespace:e}){super({defaultNamespace:e});const t={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=new sxe(t),this.serializer=new xTe(this.codec.createSerializer(),t),this.deserializer=new TTe(this.codec.createDeserializer(),t)}getShapeId(){return"aws.protocols#restJson1"}getPayloadCodec(){return this.codec}setSerdeContext(e){this.codec.setSerdeContext(e),super.setSerdeContext(e)}async serializeRequest(e,t,r){const i=await super.serializeRequest(e,t,r),a=yr.of(e.input);if(!i.headers["content-type"]){const s=this.mixin.resolveRestContentType(this.getDefaultContentType(),a);s&&(i.headers["content-type"]=s)}return i.body==null&&i.headers["content-type"]===this.getDefaultContentType()&&(i.body="{}"),i}async deserializeResponse(e,t,r){const i=await super.deserializeResponse(e,t,r),a=yr.of(e.output);for(const[s,o]of a.structIterator())o.getMemberTraits().httpPayload&&!(s in i)&&(i[s]=null);return i}async handleError(e,t,r,i,a){const s=nxe(r,i)??"Unknown",{errorSchema:o,errorMetadata:l}=await this.mixin.getErrorSchemaOrThrowBaseException(s,this.options.defaultNamespace,r,i,a),c=yr.of(o),u=i.message??i.Message??"Unknown",d=cs.for(o[1]).getErrorCtor(o)??Error,p=new d(u);await this.deserializeHttpMessage(o,t,r,i);const h={};for(const[f,m]of c.structIterator()){const g=m.getMergedTraits().jsonName??f;h[f]=this.codec.createDeserializer().readObject(m,i[g])}throw this.mixin.decorateServiceException(Object.assign(p,l,{$fault:c.getMergedTraits().error,message:u},h),i)}getDefaultContentType(){return"application/json"}}const lxe=/\d{12}\.ddb/;async function cxe(n,e,t){if(t.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor"&&xl(n,"PROTOCOL_RPC_V2_CBOR","M"),typeof e.retryStrategy=="function"){const a=await e.retryStrategy();typeof a.acquireInitialRetryToken=="function"?a.constructor?.name?.includes("Adaptive")?xl(n,"RETRY_MODE_ADAPTIVE","F"):xl(n,"RETRY_MODE_STANDARD","E"):xl(n,"RETRY_MODE_LEGACY","D")}if(typeof e.accountIdEndpointMode=="function"){const a=n.endpointV2;switch(String(a?.url?.hostname).match(lxe)&&xl(n,"ACCOUNT_ID_ENDPOINT","O"),await e.accountIdEndpointMode?.()){case"disabled":xl(n,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":xl(n,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":xl(n,"ACCOUNT_ID_MODE_REQUIRED","R");break}}const i=n.__smithy_context?.selectedHttpAuthScheme?.identity;if(i?.$source){const a=i;a.accountId&&xl(n,"RESOLVED_ACCOUNT_ID","T");for(const[s,o]of Object.entries(a.$source??{}))xl(n,s,o)}}const O9="user-agent",fC="x-amz-user-agent",P9=" ",mC="/",uxe=/[^!$%&'*+\-.^_`|~\w]/g,dxe=/[^!$%&'*+\-.^_`|~\w#]/g,M9="-",pxe=1024;function hxe(n){let e="";for(const t in n){const r=n[t];if(e.length+r.length+1<=pxe){e.length?e+=","+r:e+=r;continue}break}return e}const fxe=n=>(e,t)=>async r=>{const{request:i}=r;if(!Ka.isInstance(i))return e(r);const{headers:a}=i,s=t?.userAgent?.map(Wb)||[],o=(await n.defaultUserAgentProvider()).map(Wb);await cxe(t,n,r);const l=t;o.push(`m/${hxe(Object.assign({},t.__smithy_context?.features,l.__aws_sdk_context?.features))}`);const c=n?.customUserAgent?.map(Wb)||[],u=await n.userAgentAppId();u&&o.push(Wb(["app",`${u}`]));const d=[].concat([...o,...s,...c]).join(P9),p=[...o.filter(h=>h.startsWith("aws-sdk-")),...c].join(P9);return n.runtime!=="browser"?(p&&(a[fC]=a[fC]?`${a[O9]} ${p}`:p),a[O9]=d):a[fC]=d,e({...r,request:i})},Wb=n=>{const e=n[0].split(mC).map(s=>s.replace(uxe,M9)).join(mC),t=n[1]?.replace(dxe,M9),r=e.indexOf(mC),i=e.substring(0,r);let a=e.substring(r+1);return i==="api"&&(a=a.toLowerCase()),[i,a,t].filter(s=>s&&s.length>0).reduce((s,o,l)=>{switch(l){case 0:return o;case 1:return`${s}/${o}`;default:return`${s}#${o}`}},"")},mxe={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},gxe=n=>({applyToStack:e=>{e.add(fxe(n),mxe)}});function _xe(n){const{port:e,query:t}=n;let{protocol:r,path:i,hostname:a}=n;r&&r.slice(-1)!==":"&&(r+=":"),e&&(a+=`:${e}`),i&&i.charAt(0)!=="/"&&(i=`/${i}`);let s=t?tj(t):"";s&&s[0]!=="?"&&(s=`?${s}`);let o="";if(n.username!=null||n.password!=null){const c=n.username??"",u=n.password??"";o=`${c}:${u}@`}let l="";return n.fragment&&(l=`#${n.fragment}`),`${r}//${o}${a}${i}${s}${l}`}var YN=function(n,e){return YN=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i])},YN(n,e)};function Mj(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");YN(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var XS=function(){return XS=Object.assign||function(e){for(var t,r=1,i=arguments.length;r<i;r++){t=arguments[r];for(var a in t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a])}return e},XS.apply(this,arguments)};function Lj(n,e){var t={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(n);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(n,r[i])&&(t[r[i]]=n[r[i]]);return t}function Fj(n,e,t,r){var i=arguments.length,a=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(n,e,t,r);else for(var o=n.length-1;o>=0;o--)(s=n[o])&&(a=(i<3?s(a):i>3?s(e,t,a):s(e,t))||a);return i>3&&a&&Object.defineProperty(e,t,a),a}function Uj(n,e){return function(t,r){e(t,r,n)}}function Bj(n,e,t,r,i,a){function s(_){if(_!==void 0&&typeof _!="function")throw new TypeError("Function expected");return _}for(var o=r.kind,l=o==="getter"?"get":o==="setter"?"set":"value",c=!e&&n?r.static?n:n.prototype:null,u=e||(c?Object.getOwnPropertyDescriptor(c,r.name):{}),d,p=!1,h=t.length-1;h>=0;h--){var f={};for(var m in r)f[m]=m==="access"?{}:r[m];for(var m in r.access)f.access[m]=r.access[m];f.addInitializer=function(_){if(p)throw new TypeError("Cannot add initializers after decoration has completed");a.push(s(_||null))};var g=(0,t[h])(o==="accessor"?{get:u.get,set:u.set}:u[l],f);if(o==="accessor"){if(g===void 0)continue;if(g===null||typeof g!="object")throw new TypeError("Object expected");(d=s(g.get))&&(u.get=d),(d=s(g.set))&&(u.set=d),(d=s(g.init))&&i.unshift(d)}else(d=s(g))&&(o==="field"?i.unshift(d):u[l]=d)}c&&Object.defineProperty(c,r.name,u),p=!0}function $j(n,e,t){for(var r=arguments.length>2,i=0;i<e.length;i++)t=r?e[i].call(n,t):e[i].call(n);return r?t:void 0}function Gj(n){return typeof n=="symbol"?n:"".concat(n)}function Wj(n,e,t){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(n,"name",{configurable:!0,value:t?"".concat(t," ",e):e})}function zj(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)}function RM(n,e,t,r){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(u){try{c(r.next(u))}catch(d){s(d)}}function l(u){try{c(r.throw(u))}catch(d){s(d)}}function c(u){u.done?a(u.value):i(u.value).then(o,l)}c((r=r.apply(n,e||[])).next())})}function kM(n,e){var t={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,s=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return s.next=o(0),s.throw=o(1),s.return=o(2),typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function o(c){return function(u){return l([c,u])}}function l(c){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,c[0]&&(t=0)),t;)try{if(r=1,i&&(a=c[0]&2?i.return:c[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,c[1])).done)return a;switch(i=0,a&&(c=[c[0]&2,a.value]),c[0]){case 0:case 1:a=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,i=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(a=t.trys,!(a=a.length>0&&a[a.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!a||c[1]>a[0]&&c[1]<a[3])){t.label=c[1];break}if(c[0]===6&&t.label<a[1]){t.label=a[1],a=c;break}if(a&&t.label<a[2]){t.label=a[2],t.ops.push(c);break}a[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(n,t)}catch(u){c=[6,u],i=0}finally{r=a=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}var dw=Object.create?(function(n,e,t,r){r===void 0&&(r=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,r,i)}):(function(n,e,t,r){r===void 0&&(r=t),n[r]=e[t]});function qj(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&dw(e,n,t)}function l_(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function IM(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),i,a=[],s;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)a.push(i.value)}catch(o){s={error:o}}finally{try{i&&!i.done&&(t=r.return)&&t.call(r)}finally{if(s)throw s.error}}return a}function Hj(){for(var n=[],e=0;e<arguments.length;e++)n=n.concat(IM(arguments[e]));return n}function Vj(){for(var n=0,e=0,t=arguments.length;e<t;e++)n+=arguments[e].length;for(var r=Array(n),i=0,e=0;e<t;e++)for(var a=arguments[e],s=0,o=a.length;s<o;s++,i++)r[i]=a[s];return r}function Yj(n,e,t){if(t||arguments.length===2)for(var r=0,i=e.length,a;r<i;r++)(a||!(r in e))&&(a||(a=Array.prototype.slice.call(e,0,r)),a[r]=e[r]);return n.concat(a||Array.prototype.slice.call(e))}function Uf(n){return this instanceof Uf?(this.v=n,this):new Uf(n)}function Kj(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(n,e||[]),i,a=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",s),i[Symbol.asyncIterator]=function(){return this},i;function s(h){return function(f){return Promise.resolve(f).then(h,d)}}function o(h,f){r[h]&&(i[h]=function(m){return new Promise(function(g,_){a.push([h,m,g,_])>1||l(h,m)})},f&&(i[h]=f(i[h])))}function l(h,f){try{c(r[h](f))}catch(m){p(a[0][3],m)}}function c(h){h.value instanceof Uf?Promise.resolve(h.value.v).then(u,d):p(a[0][2],h)}function u(h){l("next",h)}function d(h){l("throw",h)}function p(h,f){h(f),a.shift(),a.length&&l(a[0][0],a[0][1])}}function Qj(n){var e,t;return e={},r("next"),r("throw",function(i){throw i}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(i,a){e[i]=n[i]?function(s){return(t=!t)?{value:Uf(n[i](s)),done:!1}:a?a(s):s}:a}}function jj(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof l_=="function"?l_(n):n[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(a){t[a]=n[a]&&function(s){return new Promise(function(o,l){s=n[a](s),i(o,l,s.done,s.value)})}}function i(a,s,o,l){Promise.resolve(l).then(function(c){a({value:c,done:o})},s)}}function Xj(n,e){return Object.defineProperty?Object.defineProperty(n,"raw",{value:e}):n.raw=e,n}var vxe=Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e},KN=function(n){return KN=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},KN(n)};function Zj(n){if(n&&n.__esModule)return n;var e={};if(n!=null)for(var t=KN(n),r=0;r<t.length;r++)t[r]!=="default"&&dw(e,n,t[r]);return vxe(e,n),e}function Jj(n){return n&&n.__esModule?n:{default:n}}function eX(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}function tX(n,e,t,r,i){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!i:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?i.call(n,t):i?i.value=t:e.set(n,t),t}function nX(n,e){if(e===null||typeof e!="object"&&typeof e!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof n=="function"?e===n:n.has(e)}function rX(n,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,i;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],t&&(i=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");i&&(r=function(){try{i.call(this)}catch(a){return Promise.reject(a)}}),n.stack.push({value:e,dispose:r,async:t})}else t&&n.stack.push({async:!0});return e}var bxe=typeof SuppressedError=="function"?SuppressedError:function(n,e,t){var r=new Error(t);return r.name="SuppressedError",r.error=n,r.suppressed=e,r};function iX(n){function e(a){n.error=n.hasError?new bxe(a,n.error,"An error was suppressed during disposal."):a,n.hasError=!0}var t,r=0;function i(){for(;t=n.stack.pop();)try{if(!t.async&&r===1)return r=0,n.stack.push(t),Promise.resolve().then(i);if(t.dispose){var a=t.dispose.call(t.value);if(t.async)return r|=2,Promise.resolve(a).then(i,function(s){return e(s),i()})}else r|=1}catch(s){e(s)}if(r===1)return n.hasError?Promise.reject(n.error):Promise.resolve();if(n.hasError)throw n.error}return i()}function aX(n,e){return typeof n=="string"&&/^\.\.?\//.test(n)?n.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(t,r,i,a,s){return r?e?".jsx":".js":i&&(!a||!s)?t:i+a+"."+s.toLowerCase()+"js"}):n}const yxe={__extends:Mj,__assign:XS,__rest:Lj,__decorate:Fj,__param:Uj,__esDecorate:Bj,__runInitializers:$j,__propKey:Gj,__setFunctionName:Wj,__metadata:zj,__awaiter:RM,__generator:kM,__createBinding:dw,__exportStar:qj,__values:l_,__read:IM,__spread:Hj,__spreadArrays:Vj,__spreadArray:Yj,__await:Uf,__asyncGenerator:Kj,__asyncDelegator:Qj,__asyncValues:jj,__makeTemplateObject:Xj,__importStar:Zj,__importDefault:Jj,__classPrivateFieldGet:eX,__classPrivateFieldSet:tX,__classPrivateFieldIn:nX,__addDisposableResource:rX,__disposeResources:iX,__rewriteRelativeImportExtension:aX},dlt=Object.freeze(Object.defineProperty({__proto__:null,__addDisposableResource:rX,get __assign(){return XS},__asyncDelegator:Qj,__asyncGenerator:Kj,__asyncValues:jj,__await:Uf,__awaiter:RM,__classPrivateFieldGet:eX,__classPrivateFieldIn:nX,__classPrivateFieldSet:tX,__createBinding:dw,__decorate:Fj,__disposeResources:iX,__esDecorate:Bj,__exportStar:qj,__extends:Mj,__generator:kM,__importDefault:Jj,__importStar:Zj,__makeTemplateObject:Xj,__metadata:zj,__param:Uj,__propKey:Gj,__read:IM,__rest:Lj,__rewriteRelativeImportExtension:aX,__runInitializers:$j,__setFunctionName:Wj,__spread:Hj,__spreadArray:Yj,__spreadArrays:Vj,__values:l_,default:yxe},Symbol.toStringTag,{value:"Module"})),Exe=n=>new TextEncoder().encode(n);var Sxe=typeof Buffer<"u"&&Buffer.from?function(n){return Buffer.from(n,"utf8")}:Exe;function c_(n){return n instanceof Uint8Array?n:typeof n=="string"?Sxe(n):ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(n)}function QN(n){return typeof n=="string"?n.length===0:n.byteLength===0}function Txe(n){if(!Uint32Array.from){for(var e=new Uint32Array(n.length),t=0;t<n.length;)e[t]=n[t],t+=1;return e}return Uint32Array.from(n)}var sX=(function(){function n(){this.checksum=4294967295}return n.prototype.update=function(e){var t,r;try{for(var i=l_(e),a=i.next();!a.done;a=i.next()){var s=a.value;this.checksum=this.checksum>>>8^xxe[(this.checksum^s)&255]}}catch(o){t={error:o}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return this},n.prototype.digest=function(){return(this.checksum^4294967295)>>>0},n})(),wxe=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117],xxe=Txe(wxe);class bg{bytes;constructor(e){if(this.bytes=e,e.byteLength!==8)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>9223372036854776e3||e<-9223372036854776e3)throw new Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);const t=new Uint8Array(8);for(let r=7,i=Math.abs(Math.round(e));r>-1&&i>0;r--,i/=256)t[r]=i;return e<0&&L9(t),new bg(t)}valueOf(){const e=this.bytes.slice(0),t=e[0]&128;return t&&L9(e),parseInt(ps(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function L9(n){for(let e=0;e<8;e++)n[e]^=255;for(let e=7;e>-1&&(n[e]++,n[e]===0);e--);}class Cxe{toUtf8;fromUtf8;constructor(e,t){this.toUtf8=e,this.fromUtf8=t}format(e){const t=[];for(const a of Object.keys(e)){const s=this.fromUtf8(a);t.push(Uint8Array.from([s.byteLength]),s,this.formatHeaderValue(e[a]))}const r=new Uint8Array(t.reduce((a,s)=>a+s.byteLength,0));let i=0;for(const a of t)r.set(a,i),i+=a.byteLength;return r}formatHeaderValue(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":const t=new DataView(new ArrayBuffer(3));return t.setUint8(0,3),t.setInt16(1,e.value,!1),new Uint8Array(t.buffer);case"integer":const r=new DataView(new ArrayBuffer(5));return r.setUint8(0,4),r.setInt32(1,e.value,!1),new Uint8Array(r.buffer);case"long":const i=new Uint8Array(9);return i[0]=5,i.set(e.value.bytes,1),i;case"binary":const a=new DataView(new ArrayBuffer(3+e.value.byteLength));a.setUint8(0,6),a.setUint16(1,e.value.byteLength,!1);const s=new Uint8Array(a.buffer);return s.set(e.value,3),s;case"string":const o=this.fromUtf8(e.value),l=new DataView(new ArrayBuffer(3+o.byteLength));l.setUint8(0,7),l.setUint16(1,o.byteLength,!1);const c=new Uint8Array(l.buffer);return c.set(o,3),c;case"timestamp":const u=new Uint8Array(9);return u[0]=8,u.set(bg.fromNumber(e.value.valueOf()).bytes,1),u;case"uuid":if(!Mxe.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(bM(e.value.replace(/\-/g,"")),1),d}}parse(e){const t={};let r=0;for(;r<e.byteLength;){const i=e.getUint8(r++),a=this.toUtf8(new Uint8Array(e.buffer,e.byteOffset+r,i));switch(r+=i,e.getUint8(r++)){case 0:t[a]={type:U9,value:!0};break;case 1:t[a]={type:U9,value:!1};break;case 2:t[a]={type:Axe,value:e.getInt8(r++)};break;case 3:t[a]={type:Rxe,value:e.getInt16(r,!1)},r+=2;break;case 4:t[a]={type:kxe,value:e.getInt32(r,!1)},r+=4;break;case 5:t[a]={type:Ixe,value:new bg(new Uint8Array(e.buffer,e.byteOffset+r,8))},r+=8;break;case 6:const s=e.getUint16(r,!1);r+=2,t[a]={type:Nxe,value:new Uint8Array(e.buffer,e.byteOffset+r,s)},r+=s;break;case 7:const o=e.getUint16(r,!1);r+=2,t[a]={type:Dxe,value:this.toUtf8(new Uint8Array(e.buffer,e.byteOffset+r,o))},r+=o;break;case 8:t[a]={type:Oxe,value:new Date(new bg(new Uint8Array(e.buffer,e.byteOffset+r,8)).valueOf())},r+=8;break;case 9:const l=new Uint8Array(e.buffer,e.byteOffset+r,16);r+=16,t[a]={type:Pxe,value:`${ps(l.subarray(0,4))}-${ps(l.subarray(4,6))}-${ps(l.subarray(6,8))}-${ps(l.subarray(8,10))}-${ps(l.subarray(10))}`};break;default:throw new Error("Unrecognized header type tag")}}return t}}var F9;(function(n){n[n.boolTrue=0]="boolTrue",n[n.boolFalse=1]="boolFalse",n[n.byte=2]="byte",n[n.short=3]="short",n[n.integer=4]="integer",n[n.long=5]="long",n[n.byteArray=6]="byteArray",n[n.string=7]="string",n[n.timestamp=8]="timestamp",n[n.uuid=9]="uuid"})(F9||(F9={}));const U9="boolean",Axe="byte",Rxe="short",kxe="integer",Ixe="long",Nxe="binary",Dxe="string",Oxe="timestamp",Pxe="uuid",Mxe=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,oX=4,Ru=oX*2,Hd=4,Lxe=Ru+Hd*2;function Fxe({byteLength:n,byteOffset:e,buffer:t}){if(n<Lxe)throw new Error("Provided message too short to accommodate event stream message overhead");const r=new DataView(t,e,n),i=r.getUint32(0,!1);if(n!==i)throw new Error("Reported message length does not match received message length");const a=r.getUint32(oX,!1),s=r.getUint32(Ru,!1),o=r.getUint32(n-Hd,!1),l=new sX().update(new Uint8Array(t,e,Ru));if(s!==l.digest())throw new Error(`The prelude checksum specified in the message (${s}) does not match the calculated CRC32 checksum (${l.digest()})`);if(l.update(new Uint8Array(t,e+Ru,n-(Ru+Hd))),o!==l.digest())throw new Error(`The message checksum (${l.digest()}) did not match the expected value of ${o}`);return{headers:new DataView(t,e+Ru+Hd,a),body:new Uint8Array(t,e+Ru+Hd+a,i-a-(Ru+Hd+Hd))}}class lX{headerMarshaller;messageBuffer;isEndOfStream;constructor(e,t){this.headerMarshaller=new Cxe(e,t),this.messageBuffer=[],this.isEndOfStream=!1}feed(e){this.messageBuffer.push(this.decode(e))}endOfStream(){this.isEndOfStream=!0}getMessage(){const e=this.messageBuffer.pop(),t=this.isEndOfStream;return{getMessage(){return e},isEndOfStream(){return t}}}getAvailableMessages(){const e=this.messageBuffer;this.messageBuffer=[];const t=this.isEndOfStream;return{getMessages(){return e},isEndOfStream(){return t}}}encode({headers:e,body:t}){const r=this.headerMarshaller.format(e),i=r.byteLength+t.byteLength+16,a=new Uint8Array(i),s=new DataView(a.buffer,a.byteOffset,a.byteLength),o=new sX;return s.setUint32(0,i,!1),s.setUint32(4,r.byteLength,!1),s.setUint32(8,o.update(a.subarray(0,8)).digest(),!1),a.set(r,12),a.set(t,r.byteLength+12),s.setUint32(i-4,o.update(a.subarray(8,i-4)).digest(),!1),a}decode(e){const{headers:t,body:r}=Fxe(e);return{headers:this.headerMarshaller.parse(t),body:r}}formatHeaders(e){return this.headerMarshaller.format(e)}}class Uxe{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const e of this.options.inputStream)yield this.options.decoder.decode(e)}}class Bxe{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const e of this.options.messageStream)yield this.options.encoder.encode(e);this.options.includeEndFrame&&(yield new Uint8Array(0))}}class $xe{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const e of this.options.messageStream){const t=await this.options.deserializer(e);t!==void 0&&(yield t)}}}class Gxe{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const e of this.options.inputStream)yield this.options.serializer(e)}}function Wxe(n){let e=0,t=0,r=null,i=null;const a=o=>{if(typeof o!="number")throw new Error("Attempted to allocate an event message where size was not a number: "+o);e=o,t=4,r=new Uint8Array(o),new DataView(r.buffer).setUint32(0,o,!1)},s=async function*(){const o=n[Symbol.asyncIterator]();for(;;){const{value:l,done:c}=await o.next();if(c){if(e)if(e===t)yield r;else throw new Error("Truncated event message received.");else return;return}const u=l.length;let d=0;for(;d<u;){if(!r){const h=u-d;i||(i=new Uint8Array(4));const f=Math.min(4-t,h);if(i.set(l.slice(d,d+f),t),t+=f,d+=f,t<4)break;a(new DataView(i.buffer).getUint32(0,!1)),i=null}const p=Math.min(e-t,u-d);r.set(l.slice(d,d+p),t),t+=p,d+=p,e&&e===t&&(yield r,r=null,e=0,t=0)}}};return{[Symbol.asyncIterator]:s}}function zxe(n,e){return async function(t){const{value:r}=t.headers[":message-type"];if(r==="error"){const i=new Error(t.headers[":error-message"].value||"UnknownError");throw i.name=t.headers[":error-code"].value,i}else if(r==="exception"){const i=t.headers[":exception-type"].value,a={[i]:t},s=await n(a);if(s.$unknown){const o=new Error(e(t.body));throw o.name=i,o}throw s[i]}else if(r==="event"){const i={[t.headers[":event-type"].value]:t},a=await n(i);return a.$unknown?void 0:a}else throw Error(`Unrecognizable event type: ${t.headers[":event-type"].value}`)}}let qxe=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:e,utf8Decoder:t}){this.eventStreamCodec=new lX(e,t),this.utfEncoder=e}deserialize(e,t){const r=Wxe(e);return new $xe({messageStream:new Uxe({inputStream:r,decoder:this.eventStreamCodec}),deserializer:zxe(t,this.utfEncoder)})}serialize(e,t){return new Bxe({messageStream:new Gxe({inputStream:e,serializer:t}),encoder:this.eventStreamCodec,includeEndFrame:!0})}};const cX=n=>({[Symbol.asyncIterator]:async function*(){const e=n.getReader();try{for(;;){const{done:t,value:r}=await e.read();if(t)return;yield r}}finally{e.releaseLock()}}}),uX=n=>{const e=n[Symbol.asyncIterator]();return new ReadableStream({async pull(t){const{done:r,value:i}=await e.next();if(r)return t.close();t.enqueue(i)}})};class Hxe{universalMarshaller;constructor({utf8Encoder:e,utf8Decoder:t}){this.universalMarshaller=new qxe({utf8Decoder:t,utf8Encoder:e})}deserialize(e,t){const r=Vxe(e)?cX(e):e;return this.universalMarshaller.deserialize(r,t)}serialize(e,t){const r=this.universalMarshaller.serialize(e,t);return typeof ReadableStream=="function"?uX(r):r}}const Vxe=n=>typeof ReadableStream=="function"&&n instanceof ReadableStream,Yxe=n=>new Hxe(n),dX=n=>n.protocol==="ws:"||n.protocol==="wss:",Kxe=3e3;class NM{metadata={handlerProtocol:"websocket/h1.1"};config={};configPromise;httpHandler;sockets={};static create(e,t=new a_){return typeof e?.handle=="function"?e:new NM(e,t)}constructor(e,t=new a_){this.httpHandler=t;const r=i=>(this.config={...i??{}},this.config);typeof e=="function"?(this.config={},this.configPromise=e().then(i=>r(i))):this.configPromise=Promise.resolve(r(e))}destroy(){for(const[e,t]of Object.entries(this.sockets)){for(const r of t)r.close(1e3,"Socket closed through destroy() call");delete this.sockets[e]}}async handle(e){this.config=await this.configPromise;const{logger:t}=this.config;if(!dX(e))return t?.debug?.(`@aws-sdk - ws fetching ${e.protocol}${e.hostname}${e.path}`),this.httpHandler.handle(e);const r=_xe(e);t?.debug?.(`@aws-sdk - ws connecting ${r.split("?")[0]}`);const i=new WebSocket(r);this.sockets[r]||(this.sockets[r]=[]),this.sockets[r].push(i),i.binaryType="arraybuffer";const{connectionTimeout:a=Kxe}=this.config;await this.waitForReady(i,a);const{body:s}=e,o=Qxe(s),l=this.connect(i,o),c=jxe(l);return{response:new Cp({statusCode:200,body:c})}}updateHttpClientConfig(e,t){this.configPromise=this.configPromise.then(r=>(r[e]=t,r))}httpHandlerConfigs(){return this.config??{}}removeNotUsableSockets(e){this.sockets[e]=(this.sockets[e]??[]).filter(t=>![WebSocket.CLOSING,WebSocket.CLOSED].includes(t.readyState))}waitForReady(e,t){return new Promise((r,i)=>{const a=setTimeout(()=>{this.removeNotUsableSockets(e.url),i({$metadata:{httpStatusCode:500,websocketSynthetic500Error:!0}})},t);e.onopen=()=>{clearTimeout(a),r()}})}connect(e,t){const r=[];let i=null,a=null;const s=c=>{i?(c.error?a(c.error):i({done:c.done,value:c.value}),i=null,a=null):r.push(c)};e.onmessage=c=>{const{data:u}=c;s(typeof u=="string"?{done:!1,value:Ap(u)}:{done:!1,value:new Uint8Array(u)})},e.onerror=c=>{e.close(),s({done:!0,error:c})},e.onclose=()=>{this.removeNotUsableSockets(e.url),s({done:!0})};const o={[Symbol.asyncIterator]:()=>({async next(){if(r.length>0){const c=r.shift();if(c.error)throw c.error;return{done:c.done,value:c.value}}return new Promise((c,u)=>{i=c,a=u})}})};return(async()=>{try{for await(const c of t){if(e.readyState>=WebSocket.CLOSING)break;e.send(c)}}catch(c){s({done:!0,error:c})}finally{e.close(1e3)}})(),o}}const Qxe=n=>n[Symbol.asyncIterator]?n:Xxe(n)?cX(n):{[Symbol.asyncIterator]:async function*(){yield n}},jxe=n=>typeof ReadableStream=="function"?uX(n):n,Xxe=n=>typeof ReadableStream=="function"&&n instanceof ReadableStream;class Zxe{signer;constructor(e){this.signer=e.signer}presign(e,t={}){return this.signer.presign(e,t)}async sign(e,t){return Ka.isInstance(e)&&dX(e)?{...await this.signer.presign({...e,body:""},{...t,expiresIn:60,unsignableHeaders:new Set(Object.keys(e.headers).filter(i=>i!=="host"))}),body:e.body}:this.signer.sign(e,t)}signMessage(e,t){return this.signer.signMessage(e,t)}}const Jxe=n=>{const{signer:e}=n;return Object.assign(n,{signer:async t=>{const r=await e(t);if(eCe(r))return new Zxe({signer:r});throw new Error("Expected WebsocketSignatureV4 signer, please check the client constructor.")}})},eCe=n=>!!n;class tCe extends TransformStream{constructor(e,t,r,i){let a=e;super({start(){},async transform(s,o){try{const l=new Date(Date.now()+await i()),c={":date":{type:"timestamp",value:l}},u=await t.sign({message:{body:s,headers:c},priorSignature:a},{signingDate:l});a=u.signature;const d=r.encode({headers:{...c,":chunk-signature":{type:"binary",value:bM(u.signature)}},body:s});o.enqueue(d)}catch(l){o.error(l)}}})}}class nCe{messageSigner;eventStreamCodec;systemClockOffsetProvider;constructor(e){this.messageSigner=e.messageSigner,this.eventStreamCodec=new lX(e.utf8Encoder,e.utf8Decoder),this.systemClockOffsetProvider=async()=>e.systemClockOffset??0}async handle(e,t,r={}){const i=t.request,{body:a,headers:s,query:o}=i;if(!(a instanceof ReadableStream))throw new Error("Eventstream payload must be a ReadableStream.");const l=new TransformStream;i.body=l.readable;let u=((s?.authorization??"").match(/Signature=(\w+)$/)??[])[1]??(o&&o["X-Amz-Signature"])??"";r.__staticSignature&&(u="");const d=new tCe(u,await this.messageSigner(),this.eventStreamCodec,this.systemClockOffsetProvider);a.pipeThrough(d).pipeThrough(l);let p;try{p=await e(t)}catch(h){const f=a.cancel?.();throw f instanceof Promise&&f.catch(()=>{}),h}return p}}const rCe=n=>new nCe(n),iCe=!1,aCe=!1,B9=new Set,sCe=(n,e=cw)=>{if(!B9.has(n)&&!e(n))if(n==="*")console.warn('@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.');else throw new Error(`Region not accepted: region="${n}" is not a valid hostname component.`);else B9.add(n)},pX=n=>typeof n=="string"&&(n.startsWith("fips-")||n.endsWith("-fips")),oCe=n=>pX(n)?["fips-aws-global","aws-fips"].includes(n)?"us-east-1":n.replace(/fips-(dkr-|prod-)?|-fips/,""):n,lCe=n=>{const{region:e,useFipsEndpoint:t}=n;if(!e)throw new Error("Region is missing");return Object.assign(n,{region:async()=>{const r=typeof e=="function"?await e():e,i=oCe(r);return sCe(i),i},useFipsEndpoint:async()=>{const r=typeof e=="string"?e:await e();return pX(r)?!0:typeof t!="function"?Promise.resolve(!!t):t()}})},cCe=n=>Object.assign(n,{eventStreamMarshaller:n.eventStreamSerdeProvider(n)}),$9="content-length";function uCe(n){return e=>async t=>{const r=t.request;if(Ka.isInstance(r)){const{body:i,headers:a}=r;if(i&&Object.keys(a).map(s=>s.toLowerCase()).indexOf($9)===-1)try{const s=n(i);r.headers={...r.headers,[$9]:String(s)}}catch{}}return e({...t,request:r})}}const dCe={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},pCe=n=>({applyToStack:e=>{e.add(uCe(n.bodyLengthChecker),dCe)}}),hCe=async n=>{const e=n?.Bucket||"";if(typeof n.Bucket=="string"&&(n.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),vCe(e)){if(n.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!_Ce(e)||e.indexOf(".")!==-1&&!String(n.Endpoint).startsWith("http:")||e.toLowerCase()!==e||e.length<3)&&(n.ForcePathStyle=!0);return n.DisableMultiRegionAccessPoints&&(n.disableMultiRegionAccessPoints=!0,n.DisableMRAP=!0),n},fCe=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,mCe=/(\d+\.){3}\d+/,gCe=/\.\./,_Ce=n=>fCe.test(n)&&!mCe.test(n)&&!gCe.test(n),vCe=n=>{const[e,t,r,,,i]=n.split(":"),a=e==="arn"&&n.split(":").length>=6,s=!!(a&&t&&r&&i);if(a&&!s)throw new Error(`Invalid ARN: ${n} was an invalid ARN.`);return s},bCe=(n,e,t,r=!1)=>{const i=async()=>{let a;return r?a=t.clientContextParams?.[n]??t[n]??t[e]:a=t[n]??t[e],typeof a=="function"?a():a};return n==="credentialScope"||e==="CredentialScope"?async()=>{const a=typeof t.credentials=="function"?await t.credentials():t.credentials;return a?.credentialScope??a?.CredentialScope}:n==="accountId"||e==="AccountId"?async()=>{const a=typeof t.credentials=="function"?await t.credentials():t.credentials;return a?.accountId??a?.AccountId}:n==="endpoint"||e==="endpoint"?async()=>{if(t.isCustomEndpoint===!1)return;const a=await i();if(a&&typeof a=="object"){if("url"in a)return a.url.href;if("hostname"in a){const{protocol:s,hostname:o,port:l,path:c}=a;return`${s}//${o}${l?":"+l:""}${c}`}}return a}:i},hX=async n=>{},fX=n=>typeof n=="object"?"url"in n?QS(n.url):n:QS(n),yCe=async(n,e,t,r)=>{if(!t.isCustomEndpoint){let s;t.serviceConfiguredEndpoint?s=await t.serviceConfiguredEndpoint():s=await hX(t.serviceId),s&&(t.endpoint=()=>Promise.resolve(fX(s)),t.isCustomEndpoint=!0)}const i=await ECe(n,e,t);if(typeof t.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");return t.endpointProvider(i,r)},ECe=async(n,e,t)=>{const r={},i=e?.getEndpointParameterInstructions?.()||{};for(const[a,s]of Object.entries(i))switch(s.type){case"staticContextParams":r[a]=s.value;break;case"contextParams":r[a]=n[s.name];break;case"clientContextParams":case"builtInParams":r[a]=await bCe(s.name,a,t,s.type!=="builtInParams")();break;case"operationContextParams":r[a]=s.get(n);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(s))}return Object.keys(i).length===0&&Object.assign(r,t),String(t.serviceId).toLowerCase()==="s3"&&await hCe(r),r},SCe=({config:n,instructions:e})=>(t,r)=>async i=>{n.isCustomEndpoint&&CTe(r,"ENDPOINT_OVERRIDE","N");const a=await yCe(i.input,{getEndpointParameterInstructions(){return e}},{...n},r);r.endpointV2=a,r.authSchemes=a.properties?.authSchemes;const s=r.authSchemes?.[0];if(s){r.signing_region=s.signingRegion,r.signing_service=s.signingName;const l=_m(r)?.selectedHttpAuthScheme?.httpAuthOption;l&&(l.signingProperties=Object.assign(l.signingProperties||{},{signing_region:s.signingRegion,signingRegion:s.signingRegion,signing_service:s.signingName,signingName:s.signingName,signingRegionSet:s.signingRegionSet},s.properties))}return t({...i})},TCe={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:b1e.name},wCe=(n,e)=>({applyToStack:t=>{t.addRelativeTo(SCe({config:n,instructions:e}),TCe)}}),xCe=n=>{const e=n.tls??!0,{endpoint:t,useDualstackEndpoint:r,useFipsEndpoint:i}=n,a=t!=null?async()=>fX(await Uc(t)()):void 0,o=Object.assign(n,{endpoint:a,tls:e,isCustomEndpoint:!!t,useDualstackEndpoint:Uc(r??!1),useFipsEndpoint:Uc(i??!1)});let l;return o.serviceConfiguredEndpoint=async()=>(n.serviceId&&!l&&(l=hX(n.serviceId)),l),o};var Bf;(function(n){n.STANDARD="standard",n.ADAPTIVE="adaptive"})(Bf||(Bf={}));const ZS=3,CCe=Bf.STANDARD,ACe=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],RCe=["TimeoutError","RequestTimeout","RequestTimeoutException"],kCe=[500,502,503,504],ICe=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],NCe=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND"],DCe=n=>n?.$retryable!==void 0,OCe=n=>n.$metadata?.clockSkewCorrected,PCe=n=>{const e=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);return n&&n instanceof TypeError?e.has(n.message):!1},mX=n=>n.$metadata?.httpStatusCode===429||ACe.includes(n.name)||n.$retryable?.throttling==!0,DM=(n,e=0)=>DCe(n)||OCe(n)||RCe.includes(n.name)||ICe.includes(n?.code||"")||NCe.includes(n?.code||"")||kCe.includes(n.$metadata?.httpStatusCode||0)||PCe(n)||n.cause!==void 0&&e<=10&&DM(n.cause,e+1),MCe=n=>{if(n.$metadata?.httpStatusCode!==void 0){const e=n.$metadata.httpStatusCode;return 500<=e&&e<=599&&!DM(n)}return!1};class OM{static setTimeoutFn=setTimeout;beta;minCapacity;minFillRate;scaleConstant;smooth;currentCapacity=0;enabled=!1;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(e){this.beta=e?.beta??.7,this.minCapacity=e?.minCapacity??1,this.minFillRate=e?.minFillRate??.5,this.scaleConstant=e?.scaleConstant??.4,this.smooth=e?.smooth??.8;const t=this.getCurrentTimeInSeconds();this.lastThrottleTime=t,this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}getCurrentTimeInSeconds(){return Date.now()/1e3}async getSendToken(){return this.acquireTokenBucket(1)}async acquireTokenBucket(e){if(this.enabled){if(this.refillTokenBucket(),e>this.currentCapacity){const t=(e-this.currentCapacity)/this.fillRate*1e3;await new Promise(r=>OM.setTimeoutFn(r,t))}this.currentCapacity=this.currentCapacity-e}}refillTokenBucket(){const e=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=e;return}const t=(e-this.lastTimestamp)*this.fillRate;this.currentCapacity=Math.min(this.maxCapacity,this.currentCapacity+t),this.lastTimestamp=e}updateClientSendingRate(e){let t;if(this.updateMeasuredRate(),mX(e)){const i=this.enabled?Math.min(this.measuredTxRate,this.fillRate):this.measuredTxRate;this.lastMaxRate=i,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),t=this.cubicThrottle(i),this.enableTokenBucket()}else this.calculateTimeWindow(),t=this.cubicSuccess(this.getCurrentTimeInSeconds());const r=Math.min(t,2*this.measuredTxRate);this.updateTokenBucketRate(r)}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(e){return this.getPrecise(e*this.beta)}cubicSuccess(e){return this.getPrecise(this.scaleConstant*Math.pow(e-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(e){this.refillTokenBucket(),this.fillRate=Math.max(e,this.minFillRate),this.maxCapacity=Math.max(e,this.minCapacity),this.currentCapacity=Math.min(this.currentCapacity,this.maxCapacity)}updateMeasuredRate(){const e=this.getCurrentTimeInSeconds(),t=Math.floor(e*2)/2;if(this.requestCount++,t>this.lastTxRateBucket){const r=this.requestCount/(t-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(r*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=t}}getPrecise(e){return parseFloat(e.toFixed(8))}}const jN=100,gX=20*1e3,LCe=500,G9=500,FCe=5,UCe=10,BCe=1,$Ce="amz-sdk-invocation-id",GCe="amz-sdk-request",WCe=()=>{let n=jN;return{computeNextBackoffDelay:r=>Math.floor(Math.min(gX,Math.random()*2**r*n)),setDelayBase:r=>{n=r}}},W9=({retryDelay:n,retryCount:e,retryCost:t})=>({getRetryCount:()=>e,getRetryDelay:()=>Math.min(gX,n),getRetryCost:()=>t});class _X{maxAttempts;mode=Bf.STANDARD;capacity=G9;retryBackoffStrategy=WCe();maxAttemptsProvider;constructor(e){this.maxAttempts=e,this.maxAttemptsProvider=typeof e=="function"?e:async()=>e}async acquireInitialRetryToken(e){return W9({retryDelay:jN,retryCount:0})}async refreshRetryTokenForRetry(e,t){const r=await this.getMaxAttempts();if(this.shouldRetry(e,t,r)){const i=t.errorType;this.retryBackoffStrategy.setDelayBase(i==="THROTTLING"?LCe:jN);const a=this.retryBackoffStrategy.computeNextBackoffDelay(e.getRetryCount()),s=t.retryAfterHint?Math.max(t.retryAfterHint.getTime()-Date.now()||0,a):a,o=this.getCapacityCost(i);return this.capacity-=o,W9({retryDelay:s,retryCount:e.getRetryCount()+1,retryCost:o})}throw new Error("No retry token available")}recordSuccess(e){this.capacity=Math.max(G9,this.capacity+(e.getRetryCost()??BCe))}getCapacity(){return this.capacity}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch{return console.warn(`Max attempts provider could not resolve. Using default of ${ZS}`),ZS}}shouldRetry(e,t,r){return e.getRetryCount()+1<r&&this.capacity>=this.getCapacityCost(t.errorType)&&this.isRetryableError(t.errorType)}getCapacityCost(e){return e==="TRANSIENT"?UCe:FCe}isRetryableError(e){return e==="THROTTLING"||e==="TRANSIENT"}}class zCe{maxAttemptsProvider;rateLimiter;standardRetryStrategy;mode=Bf.ADAPTIVE;constructor(e,t){this.maxAttemptsProvider=e;const{rateLimiter:r}=t??{};this.rateLimiter=r??new OM,this.standardRetryStrategy=new _X(e)}async acquireInitialRetryToken(e){return await this.rateLimiter.getSendToken(),this.standardRetryStrategy.acquireInitialRetryToken(e)}async refreshRetryTokenForRetry(e,t){return this.rateLimiter.updateClientSendingRate(t),this.standardRetryStrategy.refreshRetryTokenForRetry(e,t)}recordSuccess(e){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(e)}}const qCe=n=>n instanceof Error?n:n instanceof Object?Object.assign(new Error,n):typeof n=="string"?new Error(n):new Error(`AWS SDK error wrapper for ${n}`),HCe=n=>{const{retryStrategy:e,retryMode:t,maxAttempts:r}=n,i=Uc(r??ZS);return Object.assign(n,{maxAttempts:i,retryStrategy:async()=>e||(await Uc(t)()===Bf.ADAPTIVE?new zCe(i):new _X(i))})},VCe=n=>n?.body instanceof ReadableStream,YCe=n=>(e,t)=>async r=>{let i=await n.retryStrategy();const a=await n.maxAttempts();if(KCe(i)){i=i;let s=await i.acquireInitialRetryToken(t.partition_id),o=new Error,l=0,c=0;const{request:u}=r,d=Ka.isInstance(u);for(d&&(u.headers[$Ce]=EM());;)try{d&&(u.headers[GCe]=`attempt=${l+1}; max=${a}`);const{response:p,output:h}=await e(r);return i.recordSuccess(s),h.$metadata.attempts=l+1,h.$metadata.totalRetryDelay=c,{response:p,output:h}}catch(p){const h=QCe(p);if(o=qCe(p),d&&VCe(u))throw(t.logger instanceof Pj?console:t.logger)?.warn("An error was encountered in a non-retryable streaming request."),o;try{s=await i.refreshRetryTokenForRetry(s,h)}catch{throw o.$metadata||(o.$metadata={}),o.$metadata.attempts=l+1,o.$metadata.totalRetryDelay=c,o}l=s.getRetryCount();const f=s.getRetryDelay();c+=f,await new Promise(m=>setTimeout(m,f))}}else return i=i,i?.mode&&(t.userAgent=[...t.userAgent||[],["cfg/retry-mode",i.mode]]),i.retry(e,r)},KCe=n=>typeof n.acquireInitialRetryToken<"u"&&typeof n.refreshRetryTokenForRetry<"u"&&typeof n.recordSuccess<"u",QCe=n=>{const e={error:n,errorType:jCe(n)},t=JCe(n.$response);return t&&(e.retryAfterHint=t),e},jCe=n=>mX(n)?"THROTTLING":DM(n)?"TRANSIENT":MCe(n)?"SERVER_ERROR":"CLIENT_ERROR",XCe={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0},ZCe=n=>({applyToStack:e=>{e.add(YCe(n),XCe)}}),JCe=n=>{if(!Cp.isInstance(n))return;const e=Object.keys(n.headers).find(a=>a.toLowerCase()==="retry-after");if(!e)return;const t=n.headers[e],r=Number(t);return Number.isNaN(r)?new Date(t):new Date(r*1e3)},eAe=async(n,e,t)=>({operation:_m(e).operation,region:await Uc(n.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});function tAe(n){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"bedrock",region:n.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}}function nAe(n){return{schemeId:"smithy.api#httpBearerAuth",propertiesExtractor:({profile:e,filepath:t,configFilepath:r,ignoreCache:i},a)=>({identityProperties:{profile:e,filepath:t,configFilepath:r,ignoreCache:i}})}}const rAe=n=>{const e=[];switch(n.operation){default:e.push(tAe(n)),e.push(nAe())}return e},iAe=n=>{const e=dj(n.token,uj,xM),t=Uwe(n);return Object.assign(t,{authSchemePreference:Uc(n.authSchemePreference??[]),token:e})},aAe=n=>Object.assign(n,{useDualstackEndpoint:n.useDualstackEndpoint??!1,useFipsEndpoint:n.useFipsEndpoint??!1,defaultSigningName:"bedrock"}),sAe={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},oAe="3.1000.0",lAe={version:oAe};var vX={name:"SHA-256"},z9={name:"HMAC",hash:vX},cAe=new Uint8Array([227,176,196,66,152,252,28,20,154,251,244,200,153,111,185,36,39,174,65,228,100,155,147,76,164,149,153,27,120,82,184,85]);const uAe={};function JE(){return typeof window<"u"?window:typeof self<"u"?self:uAe}var dAe=(function(){function n(e){this.toHash=new Uint8Array(0),this.secret=e,this.reset()}return n.prototype.update=function(e){if(!QN(e)){var t=c_(e),r=new Uint8Array(this.toHash.byteLength+t.byteLength);r.set(this.toHash,0),r.set(t,this.toHash.byteLength),this.toHash=r}},n.prototype.digest=function(){var e=this;return this.key?this.key.then(function(t){return JE().crypto.subtle.sign(z9,t,e.toHash).then(function(r){return new Uint8Array(r)})}):QN(this.toHash)?Promise.resolve(cAe):Promise.resolve().then(function(){return JE().crypto.subtle.digest(vX,e.toHash)}).then(function(t){return Promise.resolve(new Uint8Array(t))})},n.prototype.reset=function(){var e=this;this.toHash=new Uint8Array(0),this.secret&&this.secret!==void 0&&(this.key=new Promise(function(t,r){JE().crypto.subtle.importKey("raw",c_(e.secret),z9,!1,["sign"]).then(t,r)}),this.key.catch(function(){}))},n})(),vo=64,pAe=32,hAe=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),fAe=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],mAe=Math.pow(2,53)-1,eS=(function(){function n(){this.state=Int32Array.from(fAe),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}return n.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");var t=0,r=e.byteLength;if(this.bytesHashed+=r,this.bytesHashed*8>mAe)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;r>0;)this.buffer[this.bufferLength++]=e[t++],r--,this.bufferLength===vo&&(this.hashBuffer(),this.bufferLength=0)},n.prototype.digest=function(){if(!this.finished){var e=this.bytesHashed*8,t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),r=this.bufferLength;if(t.setUint8(this.bufferLength++,128),r%vo>=vo-8){for(var i=this.bufferLength;i<vo;i++)t.setUint8(i,0);this.hashBuffer(),this.bufferLength=0}for(var i=this.bufferLength;i<vo-8;i++)t.setUint8(i,0);t.setUint32(vo-8,Math.floor(e/4294967296),!0),t.setUint32(vo-4,e),this.hashBuffer(),this.finished=!0}for(var a=new Uint8Array(pAe),i=0;i<8;i++)a[i*4]=this.state[i]>>>24&255,a[i*4+1]=this.state[i]>>>16&255,a[i*4+2]=this.state[i]>>>8&255,a[i*4+3]=this.state[i]>>>0&255;return a},n.prototype.hashBuffer=function(){for(var e=this,t=e.buffer,r=e.state,i=r[0],a=r[1],s=r[2],o=r[3],l=r[4],c=r[5],u=r[6],d=r[7],p=0;p<vo;p++){if(p<16)this.temp[p]=(t[p*4]&255)<<24|(t[p*4+1]&255)<<16|(t[p*4+2]&255)<<8|t[p*4+3]&255;else{var h=this.temp[p-2],f=(h>>>17|h<<15)^(h>>>19|h<<13)^h>>>10;h=this.temp[p-15];var m=(h>>>7|h<<25)^(h>>>18|h<<14)^h>>>3;this.temp[p]=(f+this.temp[p-7]|0)+(m+this.temp[p-16]|0)}var g=(((l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7))+(l&c^~l&u)|0)+(d+(hAe[p]+this.temp[p]|0)|0)|0,_=((i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10))+(i&a^i&s^a&s)|0;d=u,u=c,c=l,l=o+g|0,o=s,s=a,a=i,i=g+_|0}r[0]+=i,r[1]+=a,r[2]+=s,r[3]+=o,r[4]+=l,r[5]+=c,r[6]+=u,r[7]+=d},n})(),gAe=(function(){function n(e){this.secret=e,this.hash=new eS,this.reset()}return n.prototype.update=function(e){if(!(QN(e)||this.error))try{this.hash.update(c_(e))}catch(t){this.error=t}},n.prototype.digestSync=function(){if(this.error)throw this.error;return this.outer?(this.outer.finished||this.outer.update(this.hash.digest()),this.outer.digest()):this.hash.digest()},n.prototype.digest=function(){return RM(this,void 0,void 0,function(){return kM(this,function(e){return[2,this.digestSync()]})})},n.prototype.reset=function(){if(this.hash=new eS,this.secret){this.outer=new eS;var e=_Ae(this.secret),t=new Uint8Array(vo);t.set(e);for(var r=0;r<vo;r++)e[r]^=54,t[r]^=92;this.hash.update(e),this.outer.update(t);for(var r=0;r<e.byteLength;r++)e[r]=0}},n})();function _Ae(n){var e=c_(n);if(e.byteLength>vo){var t=new eS;t.update(e),e=t.digest()}var r=new Uint8Array(vo);return r.set(e),r}var vAe=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function bAe(n){if(yAe(n)&&typeof n.crypto.subtle=="object"){var e=n.crypto.subtle;return EAe(e)}return!1}function yAe(n){if(typeof n=="object"&&typeof n.crypto=="object"){var e=n.crypto.getRandomValues;return typeof e=="function"}return!1}function EAe(n){return n&&vAe.every(function(e){return typeof n[e]=="function"})}var SAe=(function(){function n(e){bAe(JE())?this.hash=new dAe(e):this.hash=new gAe(e)}return n.prototype.update=function(e,t){this.hash.update(c_(e))},n.prototype.digest=function(){return this.hash.digest()},n.prototype.reset=function(){this.hash.reset()},n})();const TAe=({serviceId:n,clientVersion:e})=>async t=>{const r=typeof window<"u"?window.navigator:void 0,i=r?.userAgent??"",a=r?.userAgentData?.platform??q9.os(i)??"other",s=void 0,o=r?.userAgentData?.brands??[],l=o[o.length-1],c=l?.brand??q9.browser(i)??"unknown",u=l?.version??"unknown",d=[["aws-sdk-js",e],["ua","2.1"],[`os/${a}`,s],["lang/js"],["md/browser",`${c}_${u}`]];n&&d.push([`api/${n}`,e]);const p=await t?.userAgentAppId?.();return p&&d.push([`app/${p}`]),d},q9={os(n){if(/iPhone|iPad|iPod/.test(n))return"iOS";if(/Macintosh|Mac OS X/.test(n))return"macOS";if(/Windows NT/.test(n))return"Windows";if(/Android/.test(n))return"Android";if(/Linux/.test(n))return"Linux"},browser(n){if(/EdgiOS|EdgA|Edg\//.test(n))return"Microsoft Edge";if(/Firefox\//.test(n))return"Firefox";if(/Chrome\//.test(n))return"Chrome";if(/Safari\//.test(n))return"Safari"}},wAe=n=>()=>Promise.reject(n),xAe=["in-region","cross-region","mobile","standard","legacy"],CAe=({defaultsMode:n}={})=>dwe(async()=>{const e=typeof n=="function"?await n():n;switch(e?.toLowerCase()){case"auto":return Promise.resolve(AAe()?"mobile":"standard");case"mobile":case"in-region":case"cross-region":case"standard":case"legacy":return Promise.resolve(e?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${xAe.join(", ")}, got ${e}`)}}),AAe=()=>{const n=window?.navigator;if(n?.connection){const{effectiveType:e,rtt:t,downlink:r}=n?.connection;if(typeof e=="string"&&e!=="4g"||Number(t)>100||Number(r)<10)return!0}return n?.userAgentData?.mobile||typeof n?.maxTouchPoints=="number"&&n?.maxTouchPoints>1},bX="required",Wl="fn",zl="argv",bm="ref",H9=!0,V9="isSet",u_="booleanEquals",Rh="error",h0="endpoint",Aa="tree",PM="PartitionResult",Y9={[bX]:!1,type:"string"},K9={[bX]:!0,default:!1,type:"boolean"},Q9={[bm]:"Endpoint"},yX={[Wl]:u_,[zl]:[{[bm]:"UseFIPS"},!0]},EX={[Wl]:u_,[zl]:[{[bm]:"UseDualStack"},!0]},Cl={},j9={[Wl]:"getAttr",[zl]:[{[bm]:PM},"supportsFIPS"]},X9={[Wl]:u_,[zl]:[!0,{[Wl]:"getAttr",[zl]:[{[bm]:PM},"supportsDualStack"]}]},Z9=[yX],J9=[EX],e8=[{[bm]:"Region"}],RAe={parameters:{Region:Y9,UseDualStack:K9,UseFIPS:K9,Endpoint:Y9},rules:[{conditions:[{[Wl]:V9,[zl]:[Q9]}],rules:[{conditions:Z9,error:"Invalid Configuration: FIPS and custom endpoint are not supported",type:Rh},{rules:[{conditions:J9,error:"Invalid Configuration: Dualstack and custom endpoint are not supported",type:Rh},{endpoint:{url:Q9,properties:Cl,headers:Cl},type:h0}],type:Aa}],type:Aa},{rules:[{conditions:[{[Wl]:V9,[zl]:e8}],rules:[{conditions:[{[Wl]:"aws.partition",[zl]:e8,assign:PM}],rules:[{conditions:[yX,EX],rules:[{conditions:[{[Wl]:u_,[zl]:[H9,j9]},X9],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:Cl,headers:Cl},type:h0}],type:Aa}],type:Aa},{error:"FIPS and DualStack are enabled, but this partition does not support one or both",type:Rh}],type:Aa},{conditions:Z9,rules:[{conditions:[{[Wl]:u_,[zl]:[j9,H9]}],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime-fips.{Region}.{PartitionResult#dnsSuffix}",properties:Cl,headers:Cl},type:h0}],type:Aa}],type:Aa},{error:"FIPS is enabled but this partition does not support FIPS",type:Rh}],type:Aa},{conditions:J9,rules:[{conditions:[X9],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:Cl,headers:Cl},type:h0}],type:Aa}],type:Aa},{error:"DualStack is enabled but this partition does not support DualStack",type:Rh}],type:Aa},{rules:[{endpoint:{url:"https://bedrock-runtime.{Region}.{PartitionResult#dnsSuffix}",properties:Cl,headers:Cl},type:h0}],type:Aa}],type:Aa}],type:Aa},{error:"Invalid Configuration: Missing Region",type:Rh}],type:Aa}]},kAe=RAe,IAe=new PTe({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),NAe=(n,e={})=>IAe.get(n,()=>JTe(kAe,{endpointParams:n,logger:e.logger}));KS.aws=Tj;class Xa extends of{constructor(e){super(e),Object.setPrototypeOf(this,Xa.prototype)}}class MM extends Xa{name="AccessDeniedException";$fault="client";constructor(e){super({name:"AccessDeniedException",$fault:"client",...e}),Object.setPrototypeOf(this,MM.prototype)}}class LM extends Xa{name="InternalServerException";$fault="server";constructor(e){super({name:"InternalServerException",$fault:"server",...e}),Object.setPrototypeOf(this,LM.prototype)}}class FM extends Xa{name="ThrottlingException";$fault="client";constructor(e){super({name:"ThrottlingException",$fault:"client",...e}),Object.setPrototypeOf(this,FM.prototype)}}class UM extends Xa{name="ValidationException";$fault="client";constructor(e){super({name:"ValidationException",$fault:"client",...e}),Object.setPrototypeOf(this,UM.prototype)}}class BM extends Xa{name="ConflictException";$fault="client";constructor(e){super({name:"ConflictException",$fault:"client",...e}),Object.setPrototypeOf(this,BM.prototype)}}class $M extends Xa{name="ResourceNotFoundException";$fault="client";constructor(e){super({name:"ResourceNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,$M.prototype)}}class GM extends Xa{name="ServiceQuotaExceededException";$fault="client";constructor(e){super({name:"ServiceQuotaExceededException",$fault:"client",...e}),Object.setPrototypeOf(this,GM.prototype)}}class WM extends Xa{name="ServiceUnavailableException";$fault="server";constructor(e){super({name:"ServiceUnavailableException",$fault:"server",...e}),Object.setPrototypeOf(this,WM.prototype)}}class zM extends Xa{name="ModelErrorException";$fault="client";originalStatusCode;resourceName;constructor(e){super({name:"ModelErrorException",$fault:"client",...e}),Object.setPrototypeOf(this,zM.prototype),this.originalStatusCode=e.originalStatusCode,this.resourceName=e.resourceName}}class qM extends Xa{name="ModelNotReadyException";$fault="client";$retryable={};constructor(e){super({name:"ModelNotReadyException",$fault:"client",...e}),Object.setPrototypeOf(this,qM.prototype)}}class HM extends Xa{name="ModelTimeoutException";$fault="client";constructor(e){super({name:"ModelTimeoutException",$fault:"client",...e}),Object.setPrototypeOf(this,HM.prototype)}}class VM extends Xa{name="ModelStreamErrorException";$fault="client";originalStatusCode;originalMessage;constructor(e){super({name:"ModelStreamErrorException",$fault:"client",...e}),Object.setPrototypeOf(this,VM.prototype),this.originalStatusCode=e.originalStatusCode,this.originalMessage=e.originalMessage}}const DAe="AudioBlock",OAe="AccessDeniedException",PAe="AppliedGuardrailDetails",MAe="AudioSource",LAe="AnyToolChoice",FAe="AutoToolChoice",UAe="Citation",BAe="ContentBlocks",$Ae="ContentBlockDelta",GAe="ContentBlockDeltaEvent",WAe="ContentBlockStart",zAe="ContentBlockStartEvent",qAe="ContentBlockStopEvent",HAe="ContentBlock",VAe="CitationsConfig",YAe="CitationsContentBlock",KAe="CacheDetail",QAe="CacheDetailsList",jAe="CitationsDelta",XAe="ConflictException",ZAe="CitationGeneratedContent",JAe="CitationGeneratedContentList",eRe="CitationLocation",tRe="CachePointBlock",nRe="ConverseStream",rRe="CitationSourceContent",iRe="CitationSourceContentDelta",aRe="CitationSourceContentList",sRe="CitationSourceContentListDelta",oRe="ConverseStreamMetrics",lRe="ConverseStreamMetadataEvent",cRe="ConverseStreamOutput",uRe="ConverseStreamRequest",dRe="ConverseStreamResponse",pRe="ConverseStreamTrace",hRe="Citations",fRe="DocumentBlock",mRe="DocumentContentBlocks",gRe="DocumentContentBlock",_Re="DocumentCharLocation",vRe="DocumentChunkLocation",bRe="DocumentPageLocation",yRe="DocumentSource",ERe="ErrorBlock",SRe="GuardrailAssessment",TRe="GuardrailAssessmentList",wRe="GuardrailAssessmentListMap",xRe="GuardrailAssessmentMap",CRe="GuardrailAutomatedReasoningDifferenceScenarioList",ARe="GuardrailAutomatedReasoningFinding",RRe="GuardrailAutomatedReasoningFindingList",kRe="GuardrailAutomatedReasoningImpossibleFinding",IRe="GuardrailAutomatedReasoningInvalidFinding",NRe="GuardrailAutomatedReasoningInputTextReference",DRe="GuardrailAutomatedReasoningInputTextReferenceList",ORe="GuardrailAutomatedReasoningLogicWarning",PRe="GuardrailAutomatedReasoningNoTranslationsFinding",MRe="GuardrailAutomatedReasoningPolicyAssessment",LRe="GuardrailAutomatedReasoningRule",FRe="GuardrailAutomatedReasoningRuleList",URe="GuardrailAutomatedReasoningScenario",BRe="GuardrailAutomatedReasoningSatisfiableFinding",$Re="GuardrailAutomatedReasoningStatementList",GRe="GuardrailAutomatedReasoningStatementLogicContent",WRe="GuardrailAutomatedReasoningStatementNaturalLanguageContent",zRe="GuardrailAutomatedReasoningStatement",qRe="GuardrailAutomatedReasoningTranslation",HRe="GuardrailAutomatedReasoningTranslationAmbiguousFinding",VRe="GuardrailAutomatedReasoningTooComplexFinding",YRe="GuardrailAutomatedReasoningTranslationList",KRe="GuardrailAutomatedReasoningTranslationOption",QRe="GuardrailAutomatedReasoningTranslationOptionList",jRe="GuardrailAutomatedReasoningValidFinding",XRe="GuardrailConverseContentBlock",ZRe="GuardrailContentFilter",JRe="GuardrailContentFilterList",e2e="GuardrailContextualGroundingFilter",t2e="GuardrailContextualGroundingFilters",n2e="GuardrailContextualGroundingPolicyAssessment",r2e="GuardrailConverseImageBlock",i2e="GuardrailConverseImageSource",a2e="GuardrailContentPolicyAssessment",s2e="GuardrailConverseTextBlock",o2e="GuardrailCustomWord",l2e="GuardrailCustomWordList",c2e="GuardrailCoverage",u2e="GuardrailImageCoverage",d2e="GuardrailInvocationMetrics",p2e="GuardrailManagedWord",h2e="GuardrailManagedWordList",f2e="GuardrailPiiEntityFilter",m2e="GuardrailPiiEntityFilterList",g2e="GuardrailRegexFilter",_2e="GuardrailRegexFilterList",v2e="GuardrailStreamConfiguration",b2e="GuardrailSensitiveInformationPolicyAssessment",y2e="GuardrailTopic",E2e="GuardrailTraceAssessment",S2e="GuardrailTextCharactersCoverage",T2e="GuardrailTopicList",w2e="GuardrailTopicPolicyAssessment",x2e="GuardrailUsage",C2e="GuardrailWordPolicyAssessment",A2e="ImageBlock",R2e="ImageBlockDelta",k2e="ImageBlockStart",I2e="InferenceConfiguration",N2e="ImageSource",D2e="InternalServerException",O2e="JsonSchemaDefinition",P2e="Message",M2e="ModelErrorException",L2e="ModelNotReadyException",F2e="MessageStartEvent",U2e="ModelStreamErrorException",B2e="MessageStopEvent",$2e="ModelTimeoutException",G2e="Messages",W2e="OutputConfig",z2e="OutputFormat",q2e="OutputFormatStructure",H2e="PerformanceConfiguration",V2e="PromptRouterTrace",Y2e="PromptVariableMap",K2e="PromptVariableValues",Q2e="ReasoningContentBlock",j2e="ReasoningContentBlockDelta",X2e="RequestMetadata",Z2e="ResourceNotFoundException",J2e="ReasoningTextBlock",eke="SystemContentBlocks",tke="SystemContentBlock",nke="S3Location",rke="ServiceQuotaExceededException",ike="SearchResultBlock",ake="SearchResultContentBlock",ske="SearchResultContentBlocks",oke="SearchResultLocation",lke="ServiceTier",cke="SpecificToolChoice",uke="SystemTool",dke="ServiceUnavailableException",pke="ToolConfiguration",hke="ToolChoice",fke="ThrottlingException",mke="ToolInputSchema",gke="ToolResultBlock",_ke="ToolResultBlocksDelta",vke="ToolResultBlockDelta",bke="ToolResultBlockStart",yke="ToolResultContentBlocks",Eke="ToolResultContentBlock",Ske="ToolSpecification",Tke="TokenUsage",wke="ToolUseBlock",xke="ToolUseBlockDelta",Cke="ToolUseBlockStart",Ake="Tools",Rke="Tool",kke="VideoBlock",Ike="ValidationException",Nke="VideoSource",Dke="WebLocation",oh="action",Oke="appliedGuardrailDetails",Pke="additionalModelRequestFields",Mke="additionalModelResponseFieldPaths",Lke="additionalModelResponseFields",Fke="actionReason",Uke="automatedReasoningPolicy",Bke="automatedReasoningPolicyUnits",$ke="automatedReasoningPolicies",Gke="any",Wke="audio",zke="auto",Av="bytes",qke="bucketOwner",ac="client",Hke="contentBlockDelta",YM="contentBlockIndex",Vke="contentBlockStart",Yke="contentBlockStop",Kke="citationsContent",Qke="cacheDetails",jke="claimsFalseScenario",Xke="contextualGroundingPolicy",Zke="contextualGroundingPolicyUnits",Jke="contentPolicy",eIe="contentPolicyImageUnits",tIe="contentPolicyUnits",KM="cachePoint",SX="contradictingRules",nIe="cacheReadInputTokens",TX="claimsTrueScenario",rIe="customWords",iIe="cacheWriteInputTokens",QM="citations",aIe="citation",wX="claims",Rv="content",sIe="context",xX="confidence",oIe="delta",lIe="documentChar",cIe="documentChunk",jM="documentIndex",uIe="documentPage",dIe="differenceScenarios",lh="detected",CX="description",pIe="domain",AX="document",Za="error",hIe="enabled",pw="end",ym="format",fIe="filterStrength",mIe="findings",RX="filters",gIe="guardrail",_Ie="guardrailArn",vIe="guardrailCoverage",bIe="guardrailConfig",kX="guardContent",yIe="guardrailId",EIe="guardrailIdentifier",SIe="guardrailOrigin",TIe="guardrailOwnership",wIe="guardrailProcessingLatency",IX="guardrailVersion",NX="guarded",xIe="http",Lo="httpError",DX="input",CIe="inputAssessment",AIe="inferenceConfig",RIe="invocationMetrics",kIe="invokedModelId",IIe="inputSchema",NIe="internalServerException",OX="inputTokens",DIe="identifier",OIe="images",kv="image",PIe="impossible",MIe="invalid",XM="json",LIe="jsonSchema",PX="location",FIe="latencyMs",hw="logicWarning",UIe="latency",BIe="logic",Zs="message",$Ie="modelId",GIe="modelOutput",WIe="messageStart",zIe="modelStreamErrorException",qIe="messageStop",HIe="maxTokens",VIe="managedWordLists",fw="match",YIe="messages",KIe="metrics",QIe="metadata",ou="name",jIe="naturalLanguage",XIe="noTranslations",ZIe="outputAssessments",JIe="outputConfig",eNe="originalMessage",MX="originalStatusCode",tNe="outputTokens",nNe="options",LX="premises",FX="performanceConfig",rNe="piiEntities",iNe="promptRouter",aNe="promptVariables",sNe="policyVersionArn",oNe="qualifiers",lNe="regex",UX="reasoningContent",BX="redactedContent",cNe="requestMetadata",uNe="resourceName",dNe="reasoningText",pNe="regexes",$X="role",GX="smithy.ts.sdk.synthetic.com.amazonaws.bedrockruntime",WX="sourceContent",hNe="sensitiveInformationPolicy",fNe="sensitiveInformationPolicyFreeUnits",mNe="sensitiveInformationPolicyUnits",mw="s3Location",gNe="streamProcessingMode",_Ne="stopReason",vNe="searchResultIndex",bNe="searchResultLocation",zX="searchResult",yNe="supportingRules",ENe="stopSequences",qX="serviceTier",SNe="systemTool",TNe="serviceUnavailableException",wNe="satisfiable",xNe="score",CNe="schema",HX="server",VX="signature",lu="source",YX="status",Iv="start",ANe="statements",RNe="stream",kNe="streaming",INe="strict",NNe="structure",DNe="system",KX="ttl",ONe="translationAmbiguous",PNe="toolConfig",MNe="textCharacters",LNe="toolChoice",FNe="tooComplex",UNe="throttlingException",BNe="textFormat",$Ne="topicPolicy",GNe="topicPolicyUnits",WNe="topP",ZM="toolResult",zNe="toolSpec",qNe="totalTokens",JM="toolUse",gw="toolUseId",ha="text",HNe="temperature",VNe="threshold",e4="title",QX="total",YNe="tools",KNe="tool",QNe="topics",jX="trace",_w="translation",jNe="translations",Js="type",XX="usage",XNe="untranslatedClaims",ZNe="untranslatedPremises",JNe="uri",eDe="url",tDe="validationException",nDe="valid",ZX="video",rDe="web",iDe="wordPolicy",aDe="wordPolicyUnits",Ie="com.amazonaws.bedrockruntime",JX=cs.for(GX);var sDe=[-3,GX,"BedrockRuntimeServiceException",0,[],[]];JX.registerError(sDe,Xa);const eo=cs.for(Ie);var oDe=[-3,Ie,OAe,{[Za]:ac,[Lo]:403},[Zs],[0]];eo.registerError(oDe,MM);var lDe=[-3,Ie,XAe,{[Za]:ac,[Lo]:400},[Zs],[0]];eo.registerError(lDe,BM);var eZ=[-3,Ie,D2e,{[Za]:HX,[Lo]:500},[Zs],[0]];eo.registerError(eZ,LM);var cDe=[-3,Ie,M2e,{[Za]:ac,[Lo]:424},[Zs,MX,uNe],[0,1,0]];eo.registerError(cDe,zM);var uDe=[-3,Ie,L2e,{[Za]:ac,[Lo]:429},[Zs],[0]];eo.registerError(uDe,qM);var tZ=[-3,Ie,U2e,{[Za]:ac,[Lo]:424},[Zs,MX,eNe],[0,1,0]];eo.registerError(tZ,VM);var dDe=[-3,Ie,$2e,{[Za]:ac,[Lo]:408},[Zs],[0]];eo.registerError(dDe,HM);var pDe=[-3,Ie,Z2e,{[Za]:ac,[Lo]:404},[Zs],[0]];eo.registerError(pDe,$M);var hDe=[-3,Ie,rke,{[Za]:ac,[Lo]:400},[Zs],[0]];eo.registerError(hDe,GM);var nZ=[-3,Ie,dke,{[Za]:HX,[Lo]:503},[Zs],[0]];eo.registerError(nZ,WM);var rZ=[-3,Ie,fke,{[Za]:ac,[Lo]:429},[Zs],[0]];eo.registerError(rZ,FM);var iZ=[-3,Ie,Ike,{[Za]:ac,[Lo]:400},[Zs],[0]];eo.registerError(iZ,UM);const fDe=[JX,eo];var mDe=[0,Ie,GRe,8,0],aZ=[0,Ie,WRe,8,0],gDe=[3,Ie,LAe,0,[],[]],_De=[3,Ie,PAe,0,[yIe,IX,_Ie,SIe,TIe],[0,0,0,64,0]],vDe=[3,Ie,DAe,0,[ym,lu,Za],[0,[()=>fPe,0],[()=>n4,0]],2],bDe=[3,Ie,FAe,0,[],[]],yDe=[3,Ie,KAe,0,[KX,OX],[0,1],2],t4=[3,Ie,tRe,0,[Js,KX],[0,0],1],EDe=[3,Ie,UAe,0,[e4,lu,WX,PX],[0,0,()=>WOe,()=>fZ]],sZ=[3,Ie,VAe,0,[hIe],[2],1],SDe=[3,Ie,YAe,0,[Rv,QM],[()=>$Oe,()=>GOe]],TDe=[3,Ie,jAe,0,[e4,lu,WX,PX],[0,0,()=>zOe,()=>fZ]],wDe=[3,Ie,iRe,0,[ha],[0]],xDe=[3,Ie,GAe,0,[oIe,YM],[[()=>vPe,0],1],2],CDe=[3,Ie,zAe,0,[Iv,YM],[()=>bPe,1],2],ADe=[3,Ie,qAe,0,[YM],[1],1],RDe=[3,Ie,lRe,0,[XX,KIe,jX,FX,qX],[()=>IOe,()=>kDe,[()=>DDe,0],()=>uZ,()=>pZ],2],kDe=[3,Ie,oRe,0,[FIe],[1],1],IDe=[3,Ie,uRe,0,[$Ie,YIe,DNe,AIe,PNe,bIe,Pke,aNe,Mke,cNe,FX,qX,JIe],[[0,1],[()=>iPe,0],[()=>sPe,0],()=>_Oe,()=>NOe,()=>lOe,15,[()=>pPe,0],64,[()=>hPe,0],()=>uZ,()=>pZ,[()=>SOe,0]],1],NDe=[3,Ie,dRe,0,[RNe],[[()=>yPe,16]]],DDe=[3,Ie,pRe,0,[gIe,iNe],[[()=>pOe,0],()=>wOe]],oZ=[3,Ie,fRe,0,[ou,lu,ym,sIe,QM],[0,()=>SPe,0,0,()=>sZ],2],ODe=[3,Ie,_Re,0,[jM,Iv,pw],[1,1,1]],PDe=[3,Ie,vRe,0,[jM,Iv,pw],[1,1,1]],MDe=[3,Ie,bRe,0,[jM,Iv,pw],[1,1,1]],n4=[3,Ie,ERe,8,[Zs],[0]],lZ=[3,Ie,SRe,0,[$Ne,Jke,iDe,hNe,Xke,Uke,RIe,Oke],[()=>dOe,()=>QDe,()=>fOe,()=>oOe,()=>XDe,[()=>$De,0],()=>rOe,()=>_De]],LDe=[3,Ie,kRe,0,[_w,SX,hw],[[()=>Nv,0],()=>r4,[()=>vw,0]]],FDe=[3,Ie,NRe,0,[ha],[[()=>aZ,0]]],UDe=[3,Ie,IRe,0,[_w,SX,hw],[[()=>Nv,0],()=>r4,[()=>vw,0]]],vw=[3,Ie,ORe,0,[Js,LX,wX],[0,[()=>d_,0],[()=>d_,0]]],BDe=[3,Ie,PRe,0,[],[]],$De=[3,Ie,MRe,0,[mIe],[[()=>KOe,0]]],GDe=[3,Ie,LRe,0,[DIe,sNe],[0,0]],WDe=[3,Ie,BRe,0,[_w,TX,jke,hw],[[()=>Nv,0],[()=>JS,0],[()=>JS,0],[()=>vw,0]]],JS=[3,Ie,URe,0,[ANe],[[()=>d_,0]]],zDe=[3,Ie,zRe,0,[BIe,jIe],[[()=>mDe,0],[()=>aZ,0]]],qDe=[3,Ie,VRe,0,[],[]],Nv=[3,Ie,qRe,0,[LX,wX,ZNe,XNe,xX],[[()=>d_,0],[()=>d_,0],[()=>t8,0],[()=>t8,0],1]],HDe=[3,Ie,HRe,0,[nNe,dIe],[[()=>jOe,0],[()=>YOe,0]]],VDe=[3,Ie,KRe,0,[jNe],[[()=>QOe,0]]],YDe=[3,Ie,jRe,0,[_w,TX,yNe,hw],[[()=>Nv,0],[()=>JS,0],()=>r4,[()=>vw,0]]],KDe=[3,Ie,ZRe,0,[Js,xX,oh,fIe,lh],[0,0,0,0,2],3],QDe=[3,Ie,a2e,0,[RX],[()=>XOe],1],jDe=[3,Ie,e2e,0,[Js,VNe,xNe,oh,lh],[0,1,1,0,2],4],XDe=[3,Ie,n2e,0,[RX],[()=>ZOe]],ZDe=[3,Ie,r2e,8,[ym,lu],[0,[()=>wPe,0]],2],JDe=[3,Ie,s2e,0,[ha,oNe],[0,64],1],eOe=[3,Ie,c2e,0,[MNe,OIe],[()=>cOe,()=>nOe]],tOe=[3,Ie,o2e,0,[fw,oh,lh],[0,0,2],2],nOe=[3,Ie,u2e,0,[NX,QX],[1,1]],rOe=[3,Ie,d2e,0,[wIe,XX,vIe],[1,()=>hOe,()=>eOe]],iOe=[3,Ie,p2e,0,[fw,Js,oh,lh],[0,0,0,2],3],aOe=[3,Ie,f2e,0,[fw,Js,oh,lh],[0,0,0,2],3],sOe=[3,Ie,g2e,0,[oh,ou,fw,lNe,lh],[0,0,0,0,2],1],oOe=[3,Ie,b2e,0,[rNe,pNe],[()=>tPe,()=>nPe],2],lOe=[3,Ie,v2e,0,[EIe,IX,jX,gNe],[0,0,0,0]],cOe=[3,Ie,S2e,0,[NX,QX],[1,1]],uOe=[3,Ie,y2e,0,[ou,Js,oh,lh],[0,0,0,2],3],dOe=[3,Ie,w2e,0,[QNe],[()=>rPe],1],pOe=[3,Ie,E2e,0,[GIe,CIe,ZIe,Fke],[64,[()=>dPe,0],[()=>uPe,0],0]],hOe=[3,Ie,x2e,0,[GNe,tIe,aDe,mNe,fNe,Zke,eIe,Bke,$ke],[1,1,1,1,1,1,1,1,1],6],fOe=[3,Ie,C2e,0,[rIe,VIe],[()=>JOe,()=>ePe],2],cZ=[3,Ie,A2e,0,[ym,lu,Za],[0,[()=>gZ,0],[()=>n4,0]],2],mOe=[3,Ie,R2e,0,[lu,Za],[[()=>gZ,0],[()=>n4,0]]],gOe=[3,Ie,k2e,0,[ym],[0],1],_Oe=[3,Ie,I2e,0,[HIe,HNe,WNe,ENe],[1,1,1,64]],vOe=[3,Ie,O2e,0,[CNe,ou,CX],[0,0,0],1],bOe=[3,Ie,P2e,0,[$X,Rv],[0,[()=>qOe,0]],2],yOe=[3,Ie,F2e,0,[$X],[0],1],EOe=[3,Ie,B2e,0,[_Ne,Lke],[0,15],1],SOe=[3,Ie,W2e,0,[BNe],[[()=>TOe,0]]],TOe=[3,Ie,z2e,0,[Js,NNe],[0,[()=>xPe,0]],2],uZ=[3,Ie,H2e,0,[UIe],[0]],wOe=[3,Ie,V2e,0,[kIe],[0]],xOe=[3,Ie,J2e,8,[ha,VX],[0,0],1],bw=[3,Ie,nke,0,[JNe,qke],[0,0],1],dZ=[3,Ie,ike,0,[lu,e4,Rv,QM],[0,0,()=>aPe,()=>sZ],3],COe=[3,Ie,ake,0,[ha],[0],1],AOe=[3,Ie,oke,0,[vNe,Iv,pw],[1,1,1]],pZ=[3,Ie,lke,0,[Js],[0],1],ROe=[3,Ie,cke,0,[ou],[0],1],kOe=[3,Ie,uke,0,[ou],[0],1],IOe=[3,Ie,Tke,0,[OX,tNe,qNe,nIe,iIe,Qke],[1,1,1,1,1,()=>BOe],3],NOe=[3,Ie,pke,0,[YNe,LNe],[()=>cPe,()=>NPe],1],DOe=[3,Ie,gke,0,[gw,Rv,YX,Js],[0,[()=>lPe,0],0,0],2],OOe=[3,Ie,bke,0,[gw,Js,YX],[0,0,0],1],POe=[3,Ie,Ske,0,[ou,IIe,CX,INe],[0,()=>DPe,0,2],2],MOe=[3,Ie,wke,0,[gw,ou,DX,Js],[0,0,15,0],3],LOe=[3,Ie,xke,0,[DX],[0],1],FOe=[3,Ie,Cke,0,[gw,ou,Js],[0,0,0],2],hZ=[3,Ie,kke,0,[ym,lu],[0,()=>MPe],2],UOe=[3,Ie,Dke,0,[eDe,pIe],[0,0]],BOe=[1,Ie,QAe,0,()=>yDe],$Oe=[1,Ie,JAe,0,()=>mPe],GOe=[1,Ie,hRe,0,()=>EDe],WOe=[1,Ie,aRe,0,()=>gPe],zOe=[1,Ie,sRe,0,()=>wDe],qOe=[1,Ie,BAe,0,[()=>_Pe,0]],HOe=[1,Ie,mRe,0,()=>EPe],VOe=[1,Ie,TRe,0,[()=>lZ,0]],YOe=[1,Ie,CRe,0,[()=>JS,0]],KOe=[1,Ie,RRe,0,[()=>TPe,0]],t8=[1,Ie,DRe,0,[()=>FDe,0]],r4=[1,Ie,FRe,0,()=>GDe],d_=[1,Ie,$Re,0,[()=>zDe,0]],QOe=[1,Ie,YRe,0,[()=>Nv,0]],jOe=[1,Ie,QRe,0,[()=>VDe,0]],XOe=[1,Ie,JRe,0,()=>KDe],ZOe=[1,Ie,t2e,0,()=>jDe],JOe=[1,Ie,l2e,0,()=>tOe],ePe=[1,Ie,h2e,0,()=>iOe],tPe=[1,Ie,m2e,0,()=>aOe],nPe=[1,Ie,_2e,0,()=>sOe],rPe=[1,Ie,T2e,0,()=>uOe],iPe=[1,Ie,G2e,0,[()=>bOe,0]],aPe=[1,Ie,ske,0,()=>COe],sPe=[1,Ie,eke,0,[()=>kPe,0]],oPe=[1,Ie,_ke,0,()=>OPe],lPe=[1,Ie,yke,0,[()=>PPe,0]],cPe=[1,Ie,Ake,0,()=>IPe],uPe=[2,Ie,wRe,0,[0,0],[()=>VOe,0]],dPe=[2,Ie,xRe,0,[0,0],[()=>lZ,0]],pPe=[2,Ie,Y2e,8,0,()=>CPe],hPe=[2,Ie,X2e,8,0,0],fPe=[4,Ie,MAe,8,[Av,mw],[21,()=>bw]],mPe=[4,Ie,ZAe,0,[ha],[0]],fZ=[4,Ie,eRe,0,[rDe,lIe,uIe,cIe,bNe],[()=>UOe,()=>ODe,()=>MDe,()=>PDe,()=>AOe]],gPe=[4,Ie,rRe,0,[ha],[0]],_Pe=[4,Ie,HAe,0,[ha,kv,AX,ZX,Wke,JM,ZM,kX,KM,UX,Kke,zX],[0,[()=>cZ,0],()=>oZ,()=>hZ,[()=>vDe,0],()=>MOe,[()=>DOe,0],[()=>mZ,0],()=>t4,[()=>APe,0],()=>SDe,()=>dZ]],vPe=[4,Ie,$Ae,0,[ha,JM,ZM,UX,aIe,kv],[0,()=>LOe,()=>oPe,[()=>RPe,0],()=>TDe,[()=>mOe,0]]],bPe=[4,Ie,WAe,0,[JM,ZM,kv],[()=>FOe,()=>OOe,()=>gOe]],yPe=[4,Ie,cRe,{[kNe]:1},[WIe,Vke,Hke,Yke,qIe,QIe,NIe,zIe,tDe,UNe,TNe],[()=>yOe,()=>CDe,[()=>xDe,0],()=>ADe,()=>EOe,[()=>RDe,0],[()=>eZ,0],[()=>tZ,0],[()=>iZ,0],[()=>rZ,0],[()=>nZ,0]]],EPe=[4,Ie,gRe,0,[ha],[0]],SPe=[4,Ie,yRe,0,[Av,mw,ha,Rv],[21,()=>bw,0,()=>HOe]],TPe=[4,Ie,ARe,0,[nDe,MIe,wNe,PIe,ONe,FNe,XIe],[[()=>YDe,0],[()=>UDe,0],[()=>WDe,0],[()=>LDe,0],[()=>HDe,0],()=>qDe,()=>BDe]],mZ=[4,Ie,XRe,0,[ha,kv],[()=>JDe,[()=>ZDe,0]]],wPe=[4,Ie,i2e,8,[Av],[21]],gZ=[4,Ie,N2e,8,[Av,mw],[21,()=>bw]],xPe=[4,Ie,q2e,8,[LIe],[()=>vOe]],CPe=[4,Ie,K2e,0,[ha],[0]],APe=[4,Ie,Q2e,8,[dNe,BX],[[()=>xOe,0],21]],RPe=[4,Ie,j2e,8,[ha,BX,VX],[0,21,0]],kPe=[4,Ie,tke,0,[ha,kX,KM],[0,[()=>mZ,0],()=>t4]],IPe=[4,Ie,Rke,0,[zNe,SNe,KM],[()=>POe,()=>kOe,()=>t4]],NPe=[4,Ie,hke,0,[zke,Gke,KNe],[()=>bDe,()=>gDe,()=>ROe]],DPe=[4,Ie,mke,0,[XM],[15]],OPe=[4,Ie,vke,0,[ha,XM],[0,15]],PPe=[4,Ie,Eke,0,[XM,ha,kv,AX,ZX,zX],[15,0,[()=>cZ,0],()=>oZ,()=>hZ,()=>dZ]],MPe=[4,Ie,Nke,0,[Av,mw],[21,()=>bw]],LPe=[9,Ie,nRe,{[xIe]:["POST","/model/{modelId}/converse-stream",200]},()=>IDe,()=>NDe];const FPe=n=>({apiVersion:"2023-09-30",base64Decoder:n?.base64Decoder??Ap,base64Encoder:n?.base64Encoder??kp,disableHostPrefix:n?.disableHostPrefix??!1,endpointProvider:n?.endpointProvider??NAe,extensions:n?.extensions??[],httpAuthSchemeProvider:n?.httpAuthSchemeProvider??rAe,httpAuthSchemes:n?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new uwe},{schemeId:"smithy.api#httpBearerAuth",identityProvider:e=>e.getIdentityProvider("smithy.api#httpBearerAuth"),signer:new RTe}],logger:n?.logger??new Pj,protocol:n?.protocol??oxe,protocolSettings:n?.protocolSettings??{defaultNamespace:"com.amazonaws.bedrockruntime",errorTypeRegistries:fDe,version:"2023-09-30",serviceTarget:"AmazonBedrockFrontendService"},serviceId:n?.serviceId??"Bedrock Runtime",urlParser:n?.urlParser??QS,utf8Decoder:n?.utf8Decoder??Rp,utf8Encoder:n?.utf8Encoder??vm}),UPe=n=>{const e=CAe(n),t=()=>e().then(qwe),r=FPe(n);return{...r,...n,runtime:"browser",defaultsMode:e,bodyLengthChecker:n?.bodyLengthChecker??Gwe,credentialDefaultProvider:n?.credentialDefaultProvider??(i=>()=>Promise.reject(new Error("Credential is missing"))),defaultUserAgentProvider:n?.defaultUserAgentProvider??TAe({serviceId:r.serviceId,clientVersion:lAe.version}),eventStreamPayloadHandlerProvider:n?.eventStreamPayloadHandlerProvider??rCe,eventStreamSerdeProvider:n?.eventStreamSerdeProvider??Yxe,maxAttempts:n?.maxAttempts??ZS,region:n?.region??wAe("Region is missing"),requestHandler:NM.create(n?.requestHandler??t,a_.create(t)),retryMode:n?.retryMode??(async()=>(await t()).retryMode||CCe),sha256:n?.sha256??SAe,streamCollector:n?.streamCollector??nj,useDualstackEndpoint:n?.useDualstackEndpoint??(()=>Promise.resolve(iCe)),useFipsEndpoint:n?.useFipsEndpoint??(()=>Promise.resolve(aCe))}},BPe=n=>({setRegion(e){n.region=e},region(){return n.region}}),$Pe=n=>({region:n.region()}),GPe=n=>{const e=n.httpAuthSchemes;let t=n.httpAuthSchemeProvider,r=n.credentials,i=n.token;return{setHttpAuthScheme(a){const s=e.findIndex(o=>o.schemeId===a.schemeId);s===-1?e.push(a):e.splice(s,1,a)},httpAuthSchemes(){return e},setHttpAuthSchemeProvider(a){t=a},httpAuthSchemeProvider(){return t},setCredentials(a){r=a},credentials(){return r},setToken(a){i=a},token(){return i}}},WPe=n=>({httpAuthSchemes:n.httpAuthSchemes(),httpAuthSchemeProvider:n.httpAuthSchemeProvider(),credentials:n.credentials(),token:n.token()}),zPe=(n,e)=>{const t=Object.assign(BPe(n),Qwe(n),n1e(n),GPe(n));return e.forEach(r=>r.configure(t)),Object.assign(n,$Pe(t),jwe(t),r1e(t),WPe(t))};class qPe extends Wwe{config;constructor(...[e]){const t=UPe(e||{});super(t),this.initConfig=t;const r=aAe(t),i=OTe(r),a=HCe(i),s=lCe(a),o=s,l=xCe(o),c=cCe(l),u=iAe(c),d=t1e(u),p=Jxe(d),h=zPe(p,e?.extensions||[]);this.config=h,this.middlewareStack.use(F1e(this.config)),this.middlewareStack.use(gxe(this.config)),this.middlewareStack.use(ZCe(this.config)),this.middlewareStack.use(pCe(this.config)),this.middlewareStack.use(o1e(this.config)),this.middlewareStack.use(u1e(this.config)),this.middlewareStack.use(h1e(this.config)),this.middlewareStack.use(v1e(this.config,{httpAuthSchemeParametersProvider:eAe,identityProviderConfigProvider:async f=>new ATe({"aws.auth#sigv4":f.credentials,"smithy.api#httpBearerAuth":f.token})})),this.middlewareStack.use(w1e(this.config))}destroy(){super.destroy()}}class HPe extends Dj.classBuilder().ep(sAe).m(function(e,t,r,i){return[wCe(r,e.getEndpointParameterInstructions())]}).s("AmazonBedrockFrontendService","ConverseStream",{eventStream:{output:!0}}).n("BedrockRuntimeClient","ConverseStreamCommand").sc(LPe).build(){}const _Z={ONE_HOUR:"1h"},vZ={DEFAULT:"default"},zb={GIF:"gif",JPEG:"jpeg",PNG:"png",WEBP:"webp"},qb={ERROR:"error",SUCCESS:"success"},Y0={ASSISTANT:"assistant",USER:"user"},f0={END_TURN:"end_turn",MAX_TOKENS:"max_tokens",MODEL_CONTEXT_WINDOW_EXCEEDED:"model_context_window_exceeded",STOP_SEQUENCE:"stop_sequence",TOOL_USE:"tool_use"};var Ho={};const K0=(n,e,t={})=>{const r=new nu;return(async()=>{const i={role:"assistant",content:[],api:"bedrock-converse-stream",provider:n.provider,model:n.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()},a=i.content,s={region:t.region,profile:t.profile};if(typeof process<"u"&&(process.versions?.node||process.versions?.bun)){if(s.region=s.region||Ho.AWS_REGION||Ho.AWS_DEFAULT_REGION,Ho.AWS_BEDROCK_SKIP_AUTH==="1"&&(s.credentials={accessKeyId:"dummy-access-key",secretAccessKey:"dummy-secret-key"}),Ho.HTTP_PROXY||Ho.HTTPS_PROXY||Ho.NO_PROXY||Ho.http_proxy||Ho.https_proxy||Ho.no_proxy){const o=await _s(()=>import("./index-Bf_69wyB.js"),__vite__mapDeps([0,1])),l=await _s(()=>import("./index-D14II7Hd.js").then(u=>u.i),__vite__mapDeps([2,1])),c=new l.ProxyAgent;s.requestHandler=new o.NodeHttpHandler({httpAgent:c,httpsAgent:c})}else if(Ho.AWS_BEDROCK_FORCE_HTTP1==="1"){const o=await _s(()=>import("./index-Bf_69wyB.js"),__vite__mapDeps([0,1]));s.requestHandler=new o.NodeHttpHandler}}s.region=s.region||"us-east-1";try{const o=new qPe(s),l=ZPe(t.cacheRetention),c={modelId:n.id,messages:nMe(e,n,l),system:eMe(e.systemPrompt,n,l),inferenceConfig:{maxTokens:t.maxTokens,temperature:t.temperature},toolConfig:rMe(e.tools,t.toolChoice),additionalModelRequestFields:aMe(n,t)};t?.onPayload?.(c);const u=new HPe(c),d=await o.send(u,{abortSignal:t.signal});for await(const p of d.stream)if(p.messageStart){if(p.messageStart.role!==Y0.ASSISTANT)throw new Error("Unexpected assistant message start but got user message start instead");r.push({type:"start",partial:i})}else if(p.contentBlockStart)YPe(p.contentBlockStart,a,i,r);else if(p.contentBlockDelta)KPe(p.contentBlockDelta,a,i,r);else if(p.contentBlockStop)jPe(p.contentBlockStop,a,i,r);else if(p.messageStop)i.stopReason=iMe(p.messageStop.stopReason);else if(p.metadata)QPe(p.metadata,n,i);else{if(p.internalServerException)throw new Error(`Internal server error: ${p.internalServerException.message}`);if(p.modelStreamErrorException)throw new Error(`Model stream error: ${p.modelStreamErrorException.message}`);if(p.validationException)throw new Error(`Validation error: ${p.validationException.message}`);if(p.throttlingException)throw new Error(`Throttling error: ${p.throttlingException.message}`);if(p.serviceUnavailableException)throw new Error(`Service unavailable: ${p.serviceUnavailableException.message}`)}if(t.signal?.aborted)throw new Error("Request was aborted");if(i.stopReason==="error"||i.stopReason==="aborted")throw new Error("An unknown error occurred");r.push({type:"done",reason:i.stopReason,message:i}),r.end()}catch(o){for(const l of i.content)delete l.index,delete l.partialJson;i.stopReason=t.signal?.aborted?"aborted":"error",i.errorMessage=o instanceof Error?o.message:JSON.stringify(o),r.push({type:"error",reason:i.stopReason,error:i}),r.end()}})(),r},VPe=(n,e,t)=>{const r=ru(n,t,void 0);if(!t?.reasoning)return K0(n,e,{...r,reasoning:void 0});if(n.id.includes("anthropic.claude")||n.id.includes("anthropic/claude")){if(XN(n.id))return K0(n,e,{...r,reasoning:t.reasoning,thinkingBudgets:t.thinkingBudgets});const i=_Y(r.maxTokens||0,n.maxTokens,t.reasoning,t.thinkingBudgets);return K0(n,e,{...r,maxTokens:i.maxTokens,reasoning:t.reasoning,thinkingBudgets:{...t.thinkingBudgets||{},[iu(t.reasoning)]:i.thinkingBudget}})}return K0(n,e,{...r,reasoning:t.reasoning,thinkingBudgets:t.thinkingBudgets})};function YPe(n,e,t,r){const i=n.contentBlockIndex,a=n.start;if(a?.toolUse){const s={type:"toolCall",id:a.toolUse.toolUseId||"",name:a.toolUse.name||"",arguments:{},partialJson:"",index:i};t.content.push(s),r.push({type:"toolcall_start",contentIndex:e.length-1,partial:t})}}function KPe(n,e,t,r){const i=n.contentBlockIndex,a=n.delta;let s=e.findIndex(l=>l.index===i),o=e[s];if(a?.text!==void 0){if(!o){const l={type:"text",text:"",index:i};t.content.push(l),s=e.length-1,o=e[s],r.push({type:"text_start",contentIndex:s,partial:t})}o.type==="text"&&(o.text+=a.text,r.push({type:"text_delta",contentIndex:s,delta:a.text,partial:t}))}else if(a?.toolUse&&o?.type==="toolCall")o.partialJson=(o.partialJson||"")+(a.toolUse.input||""),o.arguments=Hl(o.partialJson),r.push({type:"toolcall_delta",contentIndex:s,delta:a.toolUse.input||"",partial:t});else if(a?.reasoningContent){let l=o,c=s;if(!l){const u={type:"thinking",thinking:"",thinkingSignature:"",index:i};t.content.push(u),c=e.length-1,l=e[c],r.push({type:"thinking_start",contentIndex:c,partial:t})}l?.type==="thinking"&&(a.reasoningContent.text&&(l.thinking+=a.reasoningContent.text,r.push({type:"thinking_delta",contentIndex:c,delta:a.reasoningContent.text,partial:t})),a.reasoningContent.signature&&(l.thinkingSignature=(l.thinkingSignature||"")+a.reasoningContent.signature))}}function QPe(n,e,t){n.usage&&(t.usage.input=n.usage.inputTokens||0,t.usage.output=n.usage.outputTokens||0,t.usage.cacheRead=n.usage.cacheReadInputTokens||0,t.usage.cacheWrite=n.usage.cacheWriteInputTokens||0,t.usage.totalTokens=n.usage.totalTokens||t.usage.input+t.usage.output,Yu(e,t.usage))}function jPe(n,e,t,r){const i=e.findIndex(s=>s.index===n.contentBlockIndex),a=e[i];if(a)switch(delete a.index,a.type){case"text":r.push({type:"text_end",contentIndex:i,content:a.text,partial:t});break;case"thinking":r.push({type:"thinking_end",contentIndex:i,content:a.thinking,partial:t});break;case"toolCall":a.arguments=Hl(a.partialJson),delete a.partialJson,r.push({type:"toolcall_end",contentIndex:i,toolCall:a,partial:t});break}}function XN(n){return n.includes("opus-4-6")||n.includes("opus-4.6")||n.includes("sonnet-4-6")||n.includes("sonnet-4.6")}function XPe(n,e){switch(n){case"minimal":case"low":return"low";case"medium":return"medium";case"high":return"high";case"xhigh":return e.includes("opus-4-6")||e.includes("opus-4.6")?"max":"high";default:return"high"}}function ZPe(n){return n||(typeof process<"u"&&Ho.PI_CACHE_RETENTION==="long"?"long":"short")}function bZ(n){if(n.cost.cacheRead||n.cost.cacheWrite)return!0;const e=n.id.toLowerCase();return!!(e.includes("claude")&&(e.includes("-4-")||e.includes("-4."))||e.includes("claude-3-7-sonnet")||e.includes("claude-3-5-haiku"))}function JPe(n){const e=n.id.toLowerCase();return e.includes("anthropic.claude")||e.includes("anthropic/claude")}function eMe(n,e,t){if(!n)return;const r=[{text:_n(n)}];return t!=="none"&&bZ(e)&&r.push({cachePoint:{type:vZ.DEFAULT,...t==="long"?{ttl:_Z.ONE_HOUR}:{}}}),r}function tMe(n){const e=n.replace(/[^a-zA-Z0-9_-]/g,"_");return e.length>64?e.slice(0,64):e}function nMe(n,e,t){const r=[],i=Sv(n.messages,e,tMe);for(let a=0;a<i.length;a++){const s=i[a];switch(s.role){case"user":r.push({role:Y0.USER,content:typeof s.content=="string"?[{text:_n(s.content)}]:s.content.map(o=>{switch(o.type){case"text":return{text:_n(o.text)};case"image":return{image:gC(o.mimeType,o.data)};default:throw new Error("Unknown user content type")}})});break;case"assistant":{if(s.content.length===0)continue;const o=[];for(const l of s.content)switch(l.type){case"text":if(l.text.trim().length===0)continue;o.push({text:_n(l.text)});break;case"toolCall":o.push({toolUse:{toolUseId:l.id,name:l.name,input:l.arguments}});break;case"thinking":if(l.thinking.trim().length===0)continue;JPe(e)?o.push({reasoningContent:{reasoningText:{text:_n(l.thinking),signature:l.thinkingSignature}}}):o.push({reasoningContent:{reasoningText:{text:_n(l.thinking)}}});break;default:throw new Error("Unknown assistant content type")}if(o.length===0)continue;r.push({role:Y0.ASSISTANT,content:o});break}case"toolResult":{const o=[];o.push({toolResult:{toolUseId:s.toolCallId,content:s.content.map(c=>c.type==="image"?{image:gC(c.mimeType,c.data)}:{text:_n(c.text)}),status:s.isError?qb.ERROR:qb.SUCCESS}});let l=a+1;for(;l<i.length&&i[l].role==="toolResult";){const c=i[l];o.push({toolResult:{toolUseId:c.toolCallId,content:c.content.map(u=>u.type==="image"?{image:gC(u.mimeType,u.data)}:{text:_n(u.text)}),status:c.isError?qb.ERROR:qb.SUCCESS}}),l++}a=l-1,r.push({role:Y0.USER,content:o});break}default:throw new Error("Unknown message role")}}if(t!=="none"&&bZ(e)&&r.length>0){const a=r[r.length-1];a.role===Y0.USER&&a.content&&a.content.push({cachePoint:{type:vZ.DEFAULT,...t==="long"?{ttl:_Z.ONE_HOUR}:{}}})}return r}function rMe(n,e){if(!n?.length||e==="none")return;const t=n.map(i=>({toolSpec:{name:i.name,description:i.description,inputSchema:{json:i.parameters}}}));let r;switch(e){case"auto":r={auto:{}};break;case"any":r={any:{}};break;default:e?.type==="tool"&&(r={tool:{name:e.name}})}return{tools:t,toolChoice:r}}function iMe(n){switch(n){case f0.END_TURN:case f0.STOP_SEQUENCE:return"stop";case f0.MAX_TOKENS:case f0.MODEL_CONTEXT_WINDOW_EXCEEDED:return"length";case f0.TOOL_USE:return"toolUse";default:return"error"}}function aMe(n,e){if(!(!e.reasoning||!n.reasoning)&&(n.id.includes("anthropic.claude")||n.id.includes("anthropic/claude"))){const t=XN(n.id)?{thinking:{type:"adaptive"},output_config:{effort:XPe(e.reasoning,n.id)}}:(()=>{const r={minimal:1024,low:2048,medium:8192,high:16384,xhigh:16384},i=e.reasoning==="xhigh"?"high":e.reasoning;return{thinking:{type:"enabled",budget_tokens:e.thinkingBudgets?.[i]??r[e.reasoning]}}})();return!XN(n.id)&&(e.interleavedThinking??!0)&&(t.anthropic_beta=["interleaved-thinking-2025-05-14"]),t}}function gC(n,e){let t;switch(n){case"image/jpeg":case"image/jpg":t=zb.JPEG;break;case"image/png":t=zb.PNG;break;case"image/gif":t=zb.GIF;break;case"image/webp":t=zb.WEBP;break;default:throw new Error(`Unknown image type: ${n}`)}const r=atob(e),i=new Uint8Array(r.length);for(let a=0;a<r.length;a++)i[a]=r.charCodeAt(a);return{source:{bytes:i},format:t}}let Q0=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&_s(()=>import("./_node-stub_node_os-TTKJha15.js").then(n=>n._),[]).then(n=>{Q0=n});const sMe="https://chatgpt.com/backend-api",oMe="https://api.openai.com/auth",_C=3,n8=1e3,lMe=new Set(["openai","openai-codex","opencode"]),cMe=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function uMe(n,e){return n===429||n===500||n===502||n===503||n===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(e)}function r8(n,e){return new Promise((t,r)=>{if(e?.aborted){r(new Error("Request was aborted"));return}const i=setTimeout(t,n);e?.addEventListener("abort",()=>{clearTimeout(i),r(new Error("Request was aborted"))})})}const yZ=(n,e,t)=>{const r=new nu;return(async()=>{const i={role:"assistant",content:[],api:"openai-codex-responses",provider:n.provider,model:n.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{const a=t?.apiKey||Mo(n.provider)||"";if(!a)throw new Error(`No API key for provider: ${n.provider}`);const s=RMe(a),o=pMe(n,e,t);t?.onPayload?.(o);const l=kMe(n.headers,t?.headers,s,a,t?.sessionId),c=JSON.stringify(o),u=t?.transport||"sse";if(u!=="sse"){let h=!1;try{if(await CMe(fMe(n.baseUrl),o,l,i,r,n,()=>{h=!0},t),t?.signal?.aborted)throw new Error("Request was aborted");r.push({type:"done",reason:i.stopReason,message:i}),r.end();return}catch(f){if(u==="websocket"||h)throw f}}let d,p;for(let h=0;h<=_C;h++){if(t?.signal?.aborted)throw new Error("Request was aborted");try{if(d=await fetch(EZ(n.baseUrl),{method:"POST",headers:l,body:c,signal:t?.signal}),d.ok)break;const f=await d.text();if(h<_C&&uMe(d.status,f)){const _=n8*2**h;await r8(_,t?.signal);continue}const m=new Response(f,{status:d.status,statusText:d.statusText}),g=await AMe(m);throw new Error(g.friendlyMessage||g.message)}catch(f){if(f instanceof Error&&(f.name==="AbortError"||f.message==="Request was aborted"))throw new Error("Request was aborted");if(p=f instanceof Error?f:new Error(String(f)),h<_C&&!p.message.includes("usage limit")){const m=n8*2**h;await r8(m,t?.signal);continue}throw p}}if(!d?.ok)throw p??new Error("Failed after retries");if(!d.body)throw new Error("No response body");if(r.push({type:"start",partial:i}),await mMe(d,i,r,n),t?.signal?.aborted)throw new Error("Request was aborted");r.push({type:"done",reason:i.stopReason,message:i}),r.end()}catch(a){i.stopReason=t?.signal?.aborted?"aborted":"error",i.errorMessage=a instanceof Error?a.message:String(a),r.push({type:"error",reason:i.stopReason,error:i}),r.end()}})(),r},dMe=(n,e,t)=>{const r=t?.apiKey||Mo(n.provider);if(!r)throw new Error(`No API key for provider: ${n.provider}`);const i=ru(n,t,r),a=WT(n)?t?.reasoning:iu(t?.reasoning);return yZ(n,e,{...i,reasoningEffort:a})};function pMe(n,e,t){const r=rM(n,e,lMe,{includeSystemPrompt:!1}),i={model:n.id,store:!1,stream:!0,instructions:e.systemPrompt,input:r,text:{verbosity:t?.textVerbosity||"medium"},include:["reasoning.encrypted_content"],prompt_cache_key:t?.sessionId,tool_choice:"auto",parallel_tool_calls:!0};return t?.temperature!==void 0&&(i.temperature=t.temperature),e.tools&&(i.tools=iM(e.tools,{strict:null})),t?.reasoningEffort!==void 0&&(i.reasoning={effort:hMe(n.id,t.reasoningEffort),summary:t.reasoningSummary??"auto"}),i}function hMe(n,e){const t=n.includes("/")?n.split("/").pop():n;return(t.startsWith("gpt-5.2")||t.startsWith("gpt-5.3"))&&e==="minimal"?"low":t==="gpt-5.1"&&e==="xhigh"?"high":t==="gpt-5.1-codex-mini"?e==="high"||e==="xhigh"?"high":"medium":e}function EZ(n){const t=(n&&n.trim().length>0?n:sMe).replace(/\/+$/,"");return t.endsWith("/codex/responses")?t:t.endsWith("/codex")?`${t}/responses`:`${t}/codex/responses`}function fMe(n){const e=new URL(EZ(n));return e.protocol==="https:"&&(e.protocol="wss:"),e.protocol==="http:"&&(e.protocol="ws:"),e.toString()}async function mMe(n,e,t,r){await ew(SZ(_Me(n)),e,t,r)}async function*SZ(n){for await(const e of n){const t=typeof e.type=="string"?e.type:void 0;if(t){if(t==="error"){const r=e.code||"",i=e.message||"";throw new Error(`Codex error: ${i||r||JSON.stringify(e)}`)}if(t==="response.failed"){const r=e.response?.error?.message;throw new Error(r||"Codex response failed")}if(t==="response.done"||t==="response.completed"){const r=e.response,i=r&&{...r,status:gMe(r.status)};yield{...e,type:"response.completed",response:i};continue}yield e}}}function gMe(n){if(typeof n=="string")return cMe.has(n)?n:void 0}async function*_Me(n){if(!n.body)return;const e=n.body.getReader(),t=new TextDecoder;let r="";for(;;){const{done:i,value:a}=await e.read();if(i)break;r+=t.decode(a,{stream:!0});let s=r.indexOf(`
|
|
140
|
+
`);return this.signString(f,{signingDate:r,signingRegion:o,signingService:s})}async signMessage(e,{signingDate:t=new Date,signingRegion:r,signingService:i}){return this.signEvent({headers:this.headerFormatter.format(e.message.headers),payload:e.message.body},{signingDate:t,signingRegion:r,signingService:i,priorSignature:e.priorSignature}).then(s=>({message:e.message,signature:s}))}async signString(e,{signingDate:t=new Date,signingRegion:r,signingService:i}={}){const a=await this.credentialProvider();this.validateResolvedCredentials(a);const s=r??await this.regionProvider(),{shortDate:o}=this.formatDate(t),l=new this.sha256(await this.getSigningKey(a,s,o,i));return l.update(i_(e)),ps(await l.digest())}async signRequest(e,{signingDate:t=new Date,signableHeaders:r,unsignableHeaders:i,signingRegion:a,signingService:s}={}){const o=await this.credentialProvider();this.validateResolvedCredentials(o);const l=a??await this.regionProvider(),c=C9(e),{longDate:u,shortDate:d}=this.formatDate(t),p=dC(d,l,s??this.service);c.headers[kj]=u,o.sessionToken&&(c.headers[bwe]=o.sessionToken);const h=await pC(c,this.sha256);!Dwe(HN,c.headers)&&this.applyChecksum&&(c.headers[HN]=h);const f=T9(c,i,r),m=await this.getSignature(u,p,this.getSigningKey(o,l,d,s),this.createCanonicalRequest(c,f,h));return c.headers[Rj]=`${cC} Credential=${o.accessKeyId}/${p}, SignedHeaders=${this.getCanonicalHeaderList(f)}, Signature=${m}`,c}async getSignature(e,t,r,i){const a=await this.createStringToSign(e,t,i,cC),s=new this.sha256(await r);return s.update(i_(a)),ps(await s.digest())}getSigningKey(e,t,r,i){return Awe(this.sha256,e,r,t,i||this.service)}}const Uwe=n=>{let e=n.credentials,t=!!n.credentials,r;Object.defineProperty(n,"credentials",{set(c){c&&c!==e&&c!==r&&(t=!0),e=c;const u=Bwe(n,{credentials:e,credentialDefaultProvider:n.credentialDefaultProvider}),d=$we(n,u);if(t&&!d.attributed){const p=typeof e=="object"&&e!==null;r=async h=>{const m=await d(h);return p&&(!m.$source||Object.keys(m.$source).length===0)?owe(m,"CREDENTIALS_CODE","e"):m},r.memoized=d.memoized,r.configBound=d.configBound,r.attributed=!0}else r=d},get(){return r},enumerable:!0,configurable:!0}),n.credentials=e;const{signingEscapePath:i=!0,systemClockOffset:a=n.systemClockOffset||0,sha256:s}=n;let o;return n.signer?o=gg(n.signer):n.regionInfoProvider?o=()=>gg(n.region)().then(async c=>[await n.regionInfoProvider(c,{useFipsEndpoint:await n.useFipsEndpoint(),useDualstackEndpoint:await n.useDualstackEndpoint()})||{},c]).then(([c,u])=>{const{signingRegion:d,signingService:p}=c;n.signingRegion=n.signingRegion||d||u,n.signingName=n.signingName||p||n.serviceId;const h={...n,credentials:n.credentials,region:n.signingRegion,service:n.signingName,sha256:s,uriEscapePath:i},f=n.signerConstructor||A9;return new f(h)}):o=async c=>{c=Object.assign({},{name:"sigv4",signingName:n.signingName||n.defaultSigningName,signingRegion:await gg(n.region)(),properties:{}},c);const u=c.signingRegion,d=c.signingName;n.signingRegion=n.signingRegion||u,n.signingName=n.signingName||d||n.serviceId;const p={...n,credentials:n.credentials,region:n.signingRegion,service:n.signingName,sha256:s,uriEscapePath:i},h=n.signerConstructor||A9;return new h(p)},Object.assign(n,{systemClockOffset:a,signingEscapePath:i,signer:o})};function Bwe(n,{credentials:e,credentialDefaultProvider:t}){let r;return e?e?.memoized?r=e:r=dj(e,uj,xM):t?r=gg(t(Object.assign({},n,{parentClientConfig:n}))):r=async()=>{throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")},r.memoized=!0,r}function $we(n,e){if(e.configBound)return e;const t=async r=>e({...r,callerClientConfig:n});return t.memoized=e.memoized,t.configBound=!0,t}const R9=typeof TextEncoder=="function"?new TextEncoder:null,Gwe=n=>{if(typeof n=="string"){if(R9)return R9.encode(n).byteLength;let e=n.length;for(let t=e-1;t>=0;t--){const r=n.charCodeAt(t);r>127&&r<=2047?e++:r>2047&&r<=65535&&(e+=2),r>=56320&&r<=57343&&t--}return e}else{if(typeof n.byteLength=="number")return n.byteLength;if(typeof n.size=="number")return n.size}throw new Error(`Body Length computation failed for ${n}`)},Dd=(n,e)=>{const t=[];if(n&&t.push(n),e)for(const r of e)t.push(r);return t},Su=(n,e)=>`${n||"anonymous"}${e&&e.length>0?` (a.k.a. ${e.join(",")})`:""}`,jS=()=>{let n=[],e=[],t=!1;const r=new Set,i=d=>d.sort((p,h)=>k9[h.step]-k9[p.step]||I9[h.priority||"normal"]-I9[p.priority||"normal"]),a=d=>{let p=!1;const h=f=>{const m=Dd(f.name,f.aliases);if(m.includes(d)){p=!0;for(const g of m)r.delete(g);return!1}return!0};return n=n.filter(h),e=e.filter(h),p},s=d=>{let p=!1;const h=f=>{if(f.middleware===d){p=!0;for(const m of Dd(f.name,f.aliases))r.delete(m);return!1}return!0};return n=n.filter(h),e=e.filter(h),p},o=d=>(n.forEach(p=>{d.add(p.middleware,{...p})}),e.forEach(p=>{d.addRelativeTo(p.middleware,{...p})}),d.identifyOnResolve?.(u.identifyOnResolve()),d),l=d=>{const p=[];return d.before.forEach(h=>{h.before.length===0&&h.after.length===0?p.push(h):p.push(...l(h))}),p.push(d),d.after.reverse().forEach(h=>{h.before.length===0&&h.after.length===0?p.push(h):p.push(...l(h))}),p},c=(d=!1)=>{const p=[],h=[],f={};return n.forEach(g=>{const _={...g,before:[],after:[]};for(const v of Dd(_.name,_.aliases))f[v]=_;p.push(_)}),e.forEach(g=>{const _={...g,before:[],after:[]};for(const v of Dd(_.name,_.aliases))f[v]=_;h.push(_)}),h.forEach(g=>{if(g.toMiddleware){const _=f[g.toMiddleware];if(_===void 0){if(d)return;throw new Error(`${g.toMiddleware} is not found when adding ${Su(g.name,g.aliases)} middleware ${g.relation} ${g.toMiddleware}`)}g.relation==="after"&&_.after.push(g),g.relation==="before"&&_.before.push(g)}}),i(p).map(l).reduce((g,_)=>(g.push(..._),g),[])},u={add:(d,p={})=>{const{name:h,override:f,aliases:m}=p,g={step:"initialize",priority:"normal",middleware:d,...p},_=Dd(h,m);if(_.length>0){if(_.some(v=>r.has(v))){if(!f)throw new Error(`Duplicate middleware name '${Su(h,m)}'`);for(const v of _){const b=n.findIndex(S=>S.name===v||S.aliases?.some(w=>w===v));if(b===-1)continue;const E=n[b];if(E.step!==g.step||g.priority!==E.priority)throw new Error(`"${Su(E.name,E.aliases)}" middleware with ${E.priority} priority in ${E.step} step cannot be overridden by "${Su(h,m)}" middleware with ${g.priority} priority in ${g.step} step.`);n.splice(b,1)}}for(const v of _)r.add(v)}n.push(g)},addRelativeTo:(d,p)=>{const{name:h,override:f,aliases:m}=p,g={middleware:d,...p},_=Dd(h,m);if(_.length>0){if(_.some(v=>r.has(v))){if(!f)throw new Error(`Duplicate middleware name '${Su(h,m)}'`);for(const v of _){const b=e.findIndex(S=>S.name===v||S.aliases?.some(w=>w===v));if(b===-1)continue;const E=e[b];if(E.toMiddleware!==g.toMiddleware||E.relation!==g.relation)throw new Error(`"${Su(E.name,E.aliases)}" middleware ${E.relation} "${E.toMiddleware}" middleware cannot be overridden by "${Su(h,m)}" middleware ${g.relation} "${g.toMiddleware}" middleware.`);e.splice(b,1)}}for(const v of _)r.add(v)}e.push(g)},clone:()=>o(jS()),use:d=>{d.applyToStack(u)},remove:d=>typeof d=="string"?a(d):s(d),removeByTag:d=>{let p=!1;const h=f=>{const{tags:m,name:g,aliases:_}=f;if(m&&m.includes(d)){const v=Dd(g,_);for(const b of v)r.delete(b);return p=!0,!1}return!0};return n=n.filter(h),e=e.filter(h),p},concat:d=>{const p=o(jS());return p.use(d),p.identifyOnResolve(t||p.identifyOnResolve()||(d.identifyOnResolve?.()??!1)),p},applyToStack:o,identify:()=>c(!0).map(d=>{const p=d.step??d.relation+" "+d.toMiddleware;return Su(d.name,d.aliases)+" - "+p}),identifyOnResolve(d){return typeof d=="boolean"&&(t=d),t},resolve:(d,p)=>{for(const h of c().map(f=>f.middleware).reverse())d=h(d,p);return t&&console.log(u.identify()),d}};return u},k9={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},I9={high:3,normal:2,low:1};class Wwe{config;middlewareStack=jS();initConfig;handlers;constructor(e){this.config=e;const{protocol:t,protocolSettings:r}=e;r&&typeof t=="function"&&(e.protocol=new t(r))}send(e,t,r){const i=typeof t!="function"?t:void 0,a=typeof t=="function"?t:r,s=i===void 0&&this.config.cacheMiddleware===!0;let o;if(s){this.handlers||(this.handlers=new WeakMap);const l=this.handlers;l.has(e.constructor)?o=l.get(e.constructor):(o=e.resolveMiddleware(this.middlewareStack,this.config,i),l.set(e.constructor,o))}else delete this.handlers,o=e.resolveMiddleware(this.middlewareStack,this.config,i);if(a)o(e).then(l=>a(null,l.output),l=>a(l)).catch(()=>{});else return o(e).then(l=>l.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}const hC="***SensitiveInformation***";function VN(n,e){if(e==null)return e;const t=yr.of(n);if(t.getMergedTraits().sensitive)return hC;if(t.isListSchema()){if(!!t.getValueSchema().getMergedTraits().sensitive)return hC}else if(t.isMapSchema()){if(!!t.getKeySchema().getMergedTraits().sensitive||!!t.getValueSchema().getMergedTraits().sensitive)return hC}else if(t.isStructSchema()&&typeof e=="object"){const r=e,i={};for(const[a,s]of t.structIterator())r[a]!=null&&(i[a]=VN(s,r[a]));return i}return e}class Dj{middlewareStack=jS();schema;static classBuilder(){return new zwe}resolveMiddlewareWithContext(e,t,r,{middlewareFn:i,clientName:a,commandName:s,inputFilterSensitiveLog:o,outputFilterSensitiveLog:l,smithyContext:c,additionalContext:u,CommandCtor:d}){for(const g of i.bind(this)(d,e,t,r))this.middlewareStack.use(g);const p=e.concat(this.middlewareStack),{logger:h}=t,f={logger:h,clientName:a,commandName:s,inputFilterSensitiveLog:o,outputFilterSensitiveLog:l,[WN]:{commandInstance:this,...c},...u},{requestHandler:m}=t;return p.resolve(g=>m.handle(g.request,r||{}),f)}}class zwe{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(e){this._init=e}ep(e){return this._ep=e,this}m(e){return this._middlewareFn=e,this}s(e,t,r={}){return this._smithyContext={service:e,operation:t,...r},this}c(e={}){return this._additionalContext=e,this}n(e,t){return this._clientName=e,this._commandName=t,this}f(e=r=>r,t=r=>r){return this._inputFilterSensitiveLog=e,this._outputFilterSensitiveLog=t,this}ser(e){return this._serializer=e,this}de(e){return this._deserializer=e,this}sc(e){return this._operationSchema=e,this._smithyContext.operationSchema=e,this}build(){const e=this;let t;return t=class extends Dj{input;static getEndpointParameterInstructions(){return e._ep}constructor(...[r]){super(),this.input=r??{},e._init(this),this.schema=e._operationSchema}resolveMiddleware(r,i,a){const s=e._operationSchema,o=s?.[4]??s?.input,l=s?.[5]??s?.output;return this.resolveMiddlewareWithContext(r,i,a,{CommandCtor:t,middlewareFn:e._middlewareFn,clientName:e._clientName,commandName:e._commandName,inputFilterSensitiveLog:e._inputFilterSensitiveLog??(s?VN.bind(null,o):c=>c),outputFilterSensitiveLog:e._outputFilterSensitiveLog??(s?VN.bind(null,l):c=>c),smithyContext:e._smithyContext,additionalContext:e._additionalContext})}serialize=e._serializer;deserialize=e._deserializer}}}class of extends Error{$fault;$response;$retryable;$metadata;constructor(e){super(e.message),Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=e.name,this.$fault=e.$fault,this.$metadata=e.$metadata}static isInstance(e){if(!e)return!1;const t=e;return of.prototype.isPrototypeOf(t)||!!t.$fault&&!!t.$metadata&&(t.$fault==="client"||t.$fault==="server")}static[Symbol.hasInstance](e){if(!e)return!1;const t=e;return this===of?of.isInstance(e):of.isInstance(e)?t.name&&this.name?this.prototype.isPrototypeOf(e)||t.name===this.name:this.prototype.isPrototypeOf(e):!1}}const N9=(n,e={})=>{Object.entries(e).filter(([,r])=>r!==void 0).forEach(([r,i])=>{(n[r]==null||n[r]==="")&&(n[r]=i)});const t=n.message||n.Message||"UnknownError";return n.message=t,delete n.Message,n},qwe=n=>{switch(n){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}},Oj=Object.values(r_),Hwe=n=>{const e=[];for(const t in r_){const r=r_[t];n[r]!==void 0&&e.push({algorithmId:()=>r,checksumConstructor:()=>n[r]})}for(const[t,r]of Object.entries(n.checksumAlgorithms??{}))e.push({algorithmId:()=>t,checksumConstructor:()=>r});return{addChecksumAlgorithm(t){n.checksumAlgorithms=n.checksumAlgorithms??{};const r=t.algorithmId(),i=t.checksumConstructor();Oj.includes(r)?n.checksumAlgorithms[r.toUpperCase()]=i:n.checksumAlgorithms[r]=i,e.push(t)},checksumAlgorithms(){return e}}},Vwe=n=>{const e={};return n.checksumAlgorithms().forEach(t=>{const r=t.algorithmId();Oj.includes(r)&&(e[r]=t.checksumConstructor())}),e},Ywe=n=>({setRetryStrategy(e){n.retryStrategy=e},retryStrategy(){return n.retryStrategy}}),Kwe=n=>{const e={};return e.retryStrategy=n.retryStrategy(),e},Qwe=n=>Object.assign(Hwe(n),Ywe(n)),jwe=n=>Object.assign(Vwe(n),Kwe(n));class Pj{trace(){}debug(){}info(){}warn(){}error(){}}class Xwe{queryCompat;constructor(e=!1){this.queryCompat=e}resolveRestContentType(e,t){const r=t.getMemberSchemas(),i=Object.values(r).find(a=>!!a.getMergedTraits().httpPayload);if(i){const a=i.getMergedTraits().mediaType;return a||(i.isStringSchema()?"text/plain":i.isBlobSchema()?"application/octet-stream":e)}else if(!t.isUnitSchema()&&Object.values(r).find(s=>{const{httpQuery:o,httpQueryParams:l,httpHeader:c,httpLabel:u,httpPrefixHeaders:d}=s.getMergedTraits();return!o&&!l&&!c&&!u&&d===void 0}))return e}async getErrorSchemaOrThrowBaseException(e,t,r,i,a,s){let o=t,l=e;e.includes("#")&&([o,l]=e.split("#"));const c={$metadata:a,$fault:r.statusCode<500?"client":"server"},u=cs.for(o);try{return{errorSchema:s?.(u,l)??u.getSchema(e),errorMetadata:c}}catch{i.message=i.message??i.Message??"UnknownError";const p=cs.for("smithy.ts.sdk.synthetic."+o),h=p.getBaseException();if(h){const f=p.getErrorCtor(h)??Error;throw this.decorateServiceException(Object.assign(new f({name:l}),c),i)}throw this.decorateServiceException(Object.assign(new Error(l),c),i)}}decorateServiceException(e,t={}){if(this.queryCompat){const r=e.Message??t.Message,i=N9(e,t);r&&(i.message=r),i.Error={...i.Error,Type:i.Error?.Type,Code:i.Error?.Code,Message:i.Error?.message??i.Error?.Message??r};const a=i.$metadata.requestId;return a&&(i.RequestId=a),i}return N9(e,t)}setQueryCompatError(e,t){const r=t.headers?.["x-amzn-query-error"];if(e!==void 0&&r!=null){const[i,a]=r.split(";"),s=Object.entries(e),o={Code:i,Type:a};Object.assign(e,o);for(const[l,c]of s)o[l==="message"?"Message":l]=c;delete o.__type,e.Error=o}}queryCompatOutput(e,t){e.Error&&(t.Error=e.Error),e.Type&&(t.Type=e.Type),e.Code&&(t.Code=e.Code)}findQueryCompatibleError(e,t){try{return e.getSchema(t)}catch{return e.find(i=>yr.of(i).getMergedTraits().awsQueryError?.[0]===t)}}}class AM{serdeContext;setSerdeContext(e){this.serdeContext=e}}class Zwe{from;to;keys;constructor(e,t){this.from=e,this.to=t,this.keys=new Set(Object.keys(this.from).filter(r=>r!=="__type"))}mark(e){this.keys.delete(e)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){const e=this.keys.values().next().value,t=this.from[e];this.to.$unknown=[e,t]}}}function Jwe(n,e,t){if(t?.source){const r=t.source;if(typeof e=="number"&&(e>Number.MAX_SAFE_INTEGER||e<Number.MIN_SAFE_INTEGER||r!==String(e)))return r.includes(".")?new tl(r,"bigDecimal"):BigInt(r)}return e}const exe=(n,e)=>V0(n,e).then(t=>(e?.utf8Encoder??vm)(t)),txe=(n,e)=>exe(n,e).then(t=>{if(t.length)try{return JSON.parse(t)}catch(r){throw r?.name==="SyntaxError"&&Object.defineProperty(r,"$responseBodyText",{value:t}),r}return{}}),nxe=(n,e)=>{const t=(a,s)=>Object.keys(a).find(o=>o.toLowerCase()===s.toLowerCase()),r=a=>{let s=a;return typeof s=="number"&&(s=s.toString()),s.indexOf(",")>=0&&(s=s.split(",")[0]),s.indexOf(":")>=0&&(s=s.split(":")[0]),s.indexOf("#")>=0&&(s=s.split("#")[1]),s},i=t(n.headers,"x-amzn-errortype");if(i!==void 0)return r(n.headers[i]);if(e&&typeof e=="object"){const a=t(e,"code");if(a&&e[a]!==void 0)return r(e[a]);if(e.__type!==void 0)return r(e.__type)}};class rxe extends AM{settings;constructor(e){super(),this.settings=e}async read(e,t){return this._read(e,typeof t=="string"?JSON.parse(t,Jwe):await txe(t,this.serdeContext))}readObject(e,t){return this._read(e,t)}_read(e,t){const r=t!==null&&typeof t=="object",i=yr.of(e);if(r){if(i.isStructSchema()){const s=t,o=i.isUnionSchema(),l={};let c;const{jsonName:u}=this.settings;u&&(c={});let d;o&&(d=new Zwe(s,l));for(const[p,h]of i.structIterator()){let f=p;u&&(f=h.getMergedTraits().jsonName??f,c[f]=p),o&&d.mark(f),s[f]!=null&&(l[p]=this._read(h,s[f]))}if(o)d.writeUnknown();else if(typeof s.__type=="string")for(const[p,h]of Object.entries(s)){const f=u?c[p]??p:p;f in l||(l[f]=h)}return l}if(Array.isArray(t)&&i.isListSchema()){const s=i.getValueSchema(),o=[],l=!!i.getMergedTraits().sparse;for(const c of t)(l||c!=null)&&o.push(this._read(s,c));return o}if(i.isMapSchema()){const s=i.getValueSchema(),o={},l=!!i.getMergedTraits().sparse;for(const[c,u]of Object.entries(t))(l||u!=null)&&(o[c]=this._read(s,u));return o}}if(i.isBlobSchema()&&typeof t=="string")return Ap(t);const a=i.getMergedTraits().mediaType;if(i.isStringSchema()&&typeof t=="string"&&a)return a==="application/json"||a.endsWith("+json")?Vl.from(t):t;if(i.isTimestampSchema()&&t!=null)switch(lw(i,this.settings)){case 5:return j1e(t);case 6:return eTe(t);case 7:return tTe(t);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",t),new Date(t)}if(i.isBigIntegerSchema()&&(typeof t=="number"||typeof t=="string"))return BigInt(t);if(i.isBigDecimalSchema()&&t!=null){if(t instanceof tl)return t;const s=t;return s.type==="bigDecimal"&&"string"in s?new tl(s.string,s.type):new tl(String(t),"bigDecimal")}if(i.isNumericSchema()&&typeof t=="string"){switch(t){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return t}if(i.isDocumentSchema())if(r){const s=Array.isArray(t)?[]:{};for(const[o,l]of Object.entries(t))l instanceof tl?s[o]=l:s[o]=this._read(i,l);return s}else return structuredClone(t);return t}}const D9="Ν";class ixe{values=new Map;counter=0;stage=0;createReplacer(){if(this.stage===1)throw new Error("@aws-sdk/core/protocols - JsonReplacer already created.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");return this.stage=1,(e,t)=>{if(t instanceof tl){const r=`${D9+"nv"+this.counter++}_`+t.string;return this.values.set(`"${r}"`,t.string),r}if(typeof t=="bigint"){const r=t.toString(),i=`${D9+"b"+this.counter++}_`+r;return this.values.set(`"${i}"`,r),i}return t}}replaceInJson(e){if(this.stage===0)throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");if(this.stage=2,this.counter===0)return e;for(const[t,r]of this.values)e=e.replace(t,r);return e}}class axe extends AM{settings;buffer;useReplacer=!1;rootSchema;constructor(e){super(),this.settings=e}write(e,t){this.rootSchema=yr.of(e),this.buffer=this._write(this.rootSchema,t)}writeDiscriminatedDocument(e,t){this.write(e,t),typeof this.buffer=="object"&&(this.buffer.__type=yr.of(e).getName(!0))}flush(){const{rootSchema:e,useReplacer:t}=this;if(this.rootSchema=void 0,this.useReplacer=!1,e?.isStructSchema()||e?.isDocumentSchema()){if(!t)return JSON.stringify(this.buffer);const r=new ixe;return r.replaceInJson(JSON.stringify(this.buffer,r.createReplacer(),0))}return this.buffer}_write(e,t,r){const i=t!==null&&typeof t=="object",a=yr.of(e);if(i){if(a.isStructSchema()){const s=t,o={},{jsonName:l}=this.settings;let c;l&&(c={});for(const[u,d]of a.structIterator()){const p=this._write(d,s[u],a);if(p!==void 0){let h=u;l&&(h=d.getMergedTraits().jsonName??u,c[u]=h),o[h]=p}}if(a.isUnionSchema()&&Object.keys(o).length===0){const{$unknown:u}=s;if(Array.isArray(u)){const[d,p]=u;o[d]=this._write(15,p)}}else if(typeof s.__type=="string")for(const[u,d]of Object.entries(s)){const p=l?c[u]??u:u;p in o||(o[p]=this._write(15,d))}return o}if(Array.isArray(t)&&a.isListSchema()){const s=a.getValueSchema(),o=[],l=!!a.getMergedTraits().sparse;for(const c of t)(l||c!=null)&&o.push(this._write(s,c));return o}if(a.isMapSchema()){const s=a.getValueSchema(),o={},l=!!a.getMergedTraits().sparse;for(const[c,u]of Object.entries(t))(l||u!=null)&&(o[c]=this._write(s,u));return o}if(t instanceof Uint8Array&&(a.isBlobSchema()||a.isDocumentSchema()))return a===this.rootSchema?t:(this.serdeContext?.base64Encoder??kp)(t);if(t instanceof Date&&(a.isTimestampSchema()||a.isDocumentSchema()))switch(lw(a,this.settings)){case 5:return t.toISOString().replace(".000Z","Z");case 6:return sj(t);case 7:return t.getTime()/1e3;default:return console.warn("Missing timestamp format, using epoch seconds",t),t.getTime()/1e3}t instanceof tl&&(this.useReplacer=!0)}if(!(t===null&&r?.isStructSchema())){if(a.isStringSchema()){if(typeof t>"u"&&a.isIdempotencyToken())return EM();const s=a.getMergedTraits().mediaType;return t!=null&&s&&(s==="application/json"||s.endsWith("+json"))?Vl.from(t):t}if(typeof t=="number"&&a.isNumericSchema())return Math.abs(t)===1/0||isNaN(t)?String(t):t;if(typeof t=="string"&&a.isBlobSchema())return a===this.rootSchema?t:(this.serdeContext?.base64Encoder??kp)(t);if(typeof t=="bigint"&&(this.useReplacer=!0),a.isDocumentSchema())if(i){const s=Array.isArray(t)?[]:{};for(const[o,l]of Object.entries(t))l instanceof tl?(this.useReplacer=!0,s[o]=l):s[o]=this._write(a,l);return s}else return structuredClone(t);return t}}}class sxe extends AM{settings;constructor(e){super(),this.settings=e}createSerializer(){const e=new axe(this.settings);return e.setSerdeContext(this.serdeContext),e}createDeserializer(){const e=new rxe(this.settings);return e.setSerdeContext(this.serdeContext),e}}class oxe extends ETe{serializer;deserializer;codec;mixin=new Xwe;constructor({defaultNamespace:e}){super({defaultNamespace:e});const t={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=new sxe(t),this.serializer=new xTe(this.codec.createSerializer(),t),this.deserializer=new TTe(this.codec.createDeserializer(),t)}getShapeId(){return"aws.protocols#restJson1"}getPayloadCodec(){return this.codec}setSerdeContext(e){this.codec.setSerdeContext(e),super.setSerdeContext(e)}async serializeRequest(e,t,r){const i=await super.serializeRequest(e,t,r),a=yr.of(e.input);if(!i.headers["content-type"]){const s=this.mixin.resolveRestContentType(this.getDefaultContentType(),a);s&&(i.headers["content-type"]=s)}return i.body==null&&i.headers["content-type"]===this.getDefaultContentType()&&(i.body="{}"),i}async deserializeResponse(e,t,r){const i=await super.deserializeResponse(e,t,r),a=yr.of(e.output);for(const[s,o]of a.structIterator())o.getMemberTraits().httpPayload&&!(s in i)&&(i[s]=null);return i}async handleError(e,t,r,i,a){const s=nxe(r,i)??"Unknown",{errorSchema:o,errorMetadata:l}=await this.mixin.getErrorSchemaOrThrowBaseException(s,this.options.defaultNamespace,r,i,a),c=yr.of(o),u=i.message??i.Message??"Unknown",d=cs.for(o[1]).getErrorCtor(o)??Error,p=new d(u);await this.deserializeHttpMessage(o,t,r,i);const h={};for(const[f,m]of c.structIterator()){const g=m.getMergedTraits().jsonName??f;h[f]=this.codec.createDeserializer().readObject(m,i[g])}throw this.mixin.decorateServiceException(Object.assign(p,l,{$fault:c.getMergedTraits().error,message:u},h),i)}getDefaultContentType(){return"application/json"}}const lxe=/\d{12}\.ddb/;async function cxe(n,e,t){if(t.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor"&&xl(n,"PROTOCOL_RPC_V2_CBOR","M"),typeof e.retryStrategy=="function"){const a=await e.retryStrategy();typeof a.acquireInitialRetryToken=="function"?a.constructor?.name?.includes("Adaptive")?xl(n,"RETRY_MODE_ADAPTIVE","F"):xl(n,"RETRY_MODE_STANDARD","E"):xl(n,"RETRY_MODE_LEGACY","D")}if(typeof e.accountIdEndpointMode=="function"){const a=n.endpointV2;switch(String(a?.url?.hostname).match(lxe)&&xl(n,"ACCOUNT_ID_ENDPOINT","O"),await e.accountIdEndpointMode?.()){case"disabled":xl(n,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":xl(n,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":xl(n,"ACCOUNT_ID_MODE_REQUIRED","R");break}}const i=n.__smithy_context?.selectedHttpAuthScheme?.identity;if(i?.$source){const a=i;a.accountId&&xl(n,"RESOLVED_ACCOUNT_ID","T");for(const[s,o]of Object.entries(a.$source??{}))xl(n,s,o)}}const O9="user-agent",fC="x-amz-user-agent",P9=" ",mC="/",uxe=/[^!$%&'*+\-.^_`|~\w]/g,dxe=/[^!$%&'*+\-.^_`|~\w#]/g,M9="-",pxe=1024;function hxe(n){let e="";for(const t in n){const r=n[t];if(e.length+r.length+1<=pxe){e.length?e+=","+r:e+=r;continue}break}return e}const fxe=n=>(e,t)=>async r=>{const{request:i}=r;if(!Ka.isInstance(i))return e(r);const{headers:a}=i,s=t?.userAgent?.map(Wb)||[],o=(await n.defaultUserAgentProvider()).map(Wb);await cxe(t,n,r);const l=t;o.push(`m/${hxe(Object.assign({},t.__smithy_context?.features,l.__aws_sdk_context?.features))}`);const c=n?.customUserAgent?.map(Wb)||[],u=await n.userAgentAppId();u&&o.push(Wb(["app",`${u}`]));const d=[].concat([...o,...s,...c]).join(P9),p=[...o.filter(h=>h.startsWith("aws-sdk-")),...c].join(P9);return n.runtime!=="browser"?(p&&(a[fC]=a[fC]?`${a[O9]} ${p}`:p),a[O9]=d):a[fC]=d,e({...r,request:i})},Wb=n=>{const e=n[0].split(mC).map(s=>s.replace(uxe,M9)).join(mC),t=n[1]?.replace(dxe,M9),r=e.indexOf(mC),i=e.substring(0,r);let a=e.substring(r+1);return i==="api"&&(a=a.toLowerCase()),[i,a,t].filter(s=>s&&s.length>0).reduce((s,o,l)=>{switch(l){case 0:return o;case 1:return`${s}/${o}`;default:return`${s}#${o}`}},"")},mxe={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},gxe=n=>({applyToStack:e=>{e.add(fxe(n),mxe)}});function _xe(n){const{port:e,query:t}=n;let{protocol:r,path:i,hostname:a}=n;r&&r.slice(-1)!==":"&&(r+=":"),e&&(a+=`:${e}`),i&&i.charAt(0)!=="/"&&(i=`/${i}`);let s=t?tj(t):"";s&&s[0]!=="?"&&(s=`?${s}`);let o="";if(n.username!=null||n.password!=null){const c=n.username??"",u=n.password??"";o=`${c}:${u}@`}let l="";return n.fragment&&(l=`#${n.fragment}`),`${r}//${o}${a}${i}${s}${l}`}var YN=function(n,e){return YN=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i])},YN(n,e)};function Mj(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");YN(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var XS=function(){return XS=Object.assign||function(e){for(var t,r=1,i=arguments.length;r<i;r++){t=arguments[r];for(var a in t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a])}return e},XS.apply(this,arguments)};function Lj(n,e){var t={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(n);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(n,r[i])&&(t[r[i]]=n[r[i]]);return t}function Fj(n,e,t,r){var i=arguments.length,a=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(n,e,t,r);else for(var o=n.length-1;o>=0;o--)(s=n[o])&&(a=(i<3?s(a):i>3?s(e,t,a):s(e,t))||a);return i>3&&a&&Object.defineProperty(e,t,a),a}function Uj(n,e){return function(t,r){e(t,r,n)}}function Bj(n,e,t,r,i,a){function s(_){if(_!==void 0&&typeof _!="function")throw new TypeError("Function expected");return _}for(var o=r.kind,l=o==="getter"?"get":o==="setter"?"set":"value",c=!e&&n?r.static?n:n.prototype:null,u=e||(c?Object.getOwnPropertyDescriptor(c,r.name):{}),d,p=!1,h=t.length-1;h>=0;h--){var f={};for(var m in r)f[m]=m==="access"?{}:r[m];for(var m in r.access)f.access[m]=r.access[m];f.addInitializer=function(_){if(p)throw new TypeError("Cannot add initializers after decoration has completed");a.push(s(_||null))};var g=(0,t[h])(o==="accessor"?{get:u.get,set:u.set}:u[l],f);if(o==="accessor"){if(g===void 0)continue;if(g===null||typeof g!="object")throw new TypeError("Object expected");(d=s(g.get))&&(u.get=d),(d=s(g.set))&&(u.set=d),(d=s(g.init))&&i.unshift(d)}else(d=s(g))&&(o==="field"?i.unshift(d):u[l]=d)}c&&Object.defineProperty(c,r.name,u),p=!0}function $j(n,e,t){for(var r=arguments.length>2,i=0;i<e.length;i++)t=r?e[i].call(n,t):e[i].call(n);return r?t:void 0}function Gj(n){return typeof n=="symbol"?n:"".concat(n)}function Wj(n,e,t){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(n,"name",{configurable:!0,value:t?"".concat(t," ",e):e})}function zj(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)}function RM(n,e,t,r){function i(a){return a instanceof t?a:new t(function(s){s(a)})}return new(t||(t=Promise))(function(a,s){function o(u){try{c(r.next(u))}catch(d){s(d)}}function l(u){try{c(r.throw(u))}catch(d){s(d)}}function c(u){u.done?a(u.value):i(u.value).then(o,l)}c((r=r.apply(n,e||[])).next())})}function kM(n,e){var t={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,s=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return s.next=o(0),s.throw=o(1),s.return=o(2),typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function o(c){return function(u){return l([c,u])}}function l(c){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,c[0]&&(t=0)),t;)try{if(r=1,i&&(a=c[0]&2?i.return:c[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,c[1])).done)return a;switch(i=0,a&&(c=[c[0]&2,a.value]),c[0]){case 0:case 1:a=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,i=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(a=t.trys,!(a=a.length>0&&a[a.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!a||c[1]>a[0]&&c[1]<a[3])){t.label=c[1];break}if(c[0]===6&&t.label<a[1]){t.label=a[1],a=c;break}if(a&&t.label<a[2]){t.label=a[2],t.ops.push(c);break}a[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(n,t)}catch(u){c=[6,u],i=0}finally{r=a=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}var dw=Object.create?(function(n,e,t,r){r===void 0&&(r=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,r,i)}):(function(n,e,t,r){r===void 0&&(r=t),n[r]=e[t]});function qj(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&dw(e,n,t)}function l_(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function IM(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),i,a=[],s;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)a.push(i.value)}catch(o){s={error:o}}finally{try{i&&!i.done&&(t=r.return)&&t.call(r)}finally{if(s)throw s.error}}return a}function Hj(){for(var n=[],e=0;e<arguments.length;e++)n=n.concat(IM(arguments[e]));return n}function Vj(){for(var n=0,e=0,t=arguments.length;e<t;e++)n+=arguments[e].length;for(var r=Array(n),i=0,e=0;e<t;e++)for(var a=arguments[e],s=0,o=a.length;s<o;s++,i++)r[i]=a[s];return r}function Yj(n,e,t){if(t||arguments.length===2)for(var r=0,i=e.length,a;r<i;r++)(a||!(r in e))&&(a||(a=Array.prototype.slice.call(e,0,r)),a[r]=e[r]);return n.concat(a||Array.prototype.slice.call(e))}function Uf(n){return this instanceof Uf?(this.v=n,this):new Uf(n)}function Kj(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(n,e||[]),i,a=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",s),i[Symbol.asyncIterator]=function(){return this},i;function s(h){return function(f){return Promise.resolve(f).then(h,d)}}function o(h,f){r[h]&&(i[h]=function(m){return new Promise(function(g,_){a.push([h,m,g,_])>1||l(h,m)})},f&&(i[h]=f(i[h])))}function l(h,f){try{c(r[h](f))}catch(m){p(a[0][3],m)}}function c(h){h.value instanceof Uf?Promise.resolve(h.value.v).then(u,d):p(a[0][2],h)}function u(h){l("next",h)}function d(h){l("throw",h)}function p(h,f){h(f),a.shift(),a.length&&l(a[0][0],a[0][1])}}function Qj(n){var e,t;return e={},r("next"),r("throw",function(i){throw i}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(i,a){e[i]=n[i]?function(s){return(t=!t)?{value:Uf(n[i](s)),done:!1}:a?a(s):s}:a}}function jj(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof l_=="function"?l_(n):n[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(a){t[a]=n[a]&&function(s){return new Promise(function(o,l){s=n[a](s),i(o,l,s.done,s.value)})}}function i(a,s,o,l){Promise.resolve(l).then(function(c){a({value:c,done:o})},s)}}function Xj(n,e){return Object.defineProperty?Object.defineProperty(n,"raw",{value:e}):n.raw=e,n}var vxe=Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e},KN=function(n){return KN=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},KN(n)};function Zj(n){if(n&&n.__esModule)return n;var e={};if(n!=null)for(var t=KN(n),r=0;r<t.length;r++)t[r]!=="default"&&dw(e,n,t[r]);return vxe(e,n),e}function Jj(n){return n&&n.__esModule?n:{default:n}}function eX(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}function tX(n,e,t,r,i){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!i:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?i.call(n,t):i?i.value=t:e.set(n,t),t}function nX(n,e){if(e===null||typeof e!="object"&&typeof e!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof n=="function"?e===n:n.has(e)}function rX(n,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,i;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],t&&(i=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");i&&(r=function(){try{i.call(this)}catch(a){return Promise.reject(a)}}),n.stack.push({value:e,dispose:r,async:t})}else t&&n.stack.push({async:!0});return e}var bxe=typeof SuppressedError=="function"?SuppressedError:function(n,e,t){var r=new Error(t);return r.name="SuppressedError",r.error=n,r.suppressed=e,r};function iX(n){function e(a){n.error=n.hasError?new bxe(a,n.error,"An error was suppressed during disposal."):a,n.hasError=!0}var t,r=0;function i(){for(;t=n.stack.pop();)try{if(!t.async&&r===1)return r=0,n.stack.push(t),Promise.resolve().then(i);if(t.dispose){var a=t.dispose.call(t.value);if(t.async)return r|=2,Promise.resolve(a).then(i,function(s){return e(s),i()})}else r|=1}catch(s){e(s)}if(r===1)return n.hasError?Promise.reject(n.error):Promise.resolve();if(n.hasError)throw n.error}return i()}function aX(n,e){return typeof n=="string"&&/^\.\.?\//.test(n)?n.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(t,r,i,a,s){return r?e?".jsx":".js":i&&(!a||!s)?t:i+a+"."+s.toLowerCase()+"js"}):n}const yxe={__extends:Mj,__assign:XS,__rest:Lj,__decorate:Fj,__param:Uj,__esDecorate:Bj,__runInitializers:$j,__propKey:Gj,__setFunctionName:Wj,__metadata:zj,__awaiter:RM,__generator:kM,__createBinding:dw,__exportStar:qj,__values:l_,__read:IM,__spread:Hj,__spreadArrays:Vj,__spreadArray:Yj,__await:Uf,__asyncGenerator:Kj,__asyncDelegator:Qj,__asyncValues:jj,__makeTemplateObject:Xj,__importStar:Zj,__importDefault:Jj,__classPrivateFieldGet:eX,__classPrivateFieldSet:tX,__classPrivateFieldIn:nX,__addDisposableResource:rX,__disposeResources:iX,__rewriteRelativeImportExtension:aX},plt=Object.freeze(Object.defineProperty({__proto__:null,__addDisposableResource:rX,get __assign(){return XS},__asyncDelegator:Qj,__asyncGenerator:Kj,__asyncValues:jj,__await:Uf,__awaiter:RM,__classPrivateFieldGet:eX,__classPrivateFieldIn:nX,__classPrivateFieldSet:tX,__createBinding:dw,__decorate:Fj,__disposeResources:iX,__esDecorate:Bj,__exportStar:qj,__extends:Mj,__generator:kM,__importDefault:Jj,__importStar:Zj,__makeTemplateObject:Xj,__metadata:zj,__param:Uj,__propKey:Gj,__read:IM,__rest:Lj,__rewriteRelativeImportExtension:aX,__runInitializers:$j,__setFunctionName:Wj,__spread:Hj,__spreadArray:Yj,__spreadArrays:Vj,__values:l_,default:yxe},Symbol.toStringTag,{value:"Module"})),Exe=n=>new TextEncoder().encode(n);var Sxe=typeof Buffer<"u"&&Buffer.from?function(n){return Buffer.from(n,"utf8")}:Exe;function c_(n){return n instanceof Uint8Array?n:typeof n=="string"?Sxe(n):ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(n)}function QN(n){return typeof n=="string"?n.length===0:n.byteLength===0}function Txe(n){if(!Uint32Array.from){for(var e=new Uint32Array(n.length),t=0;t<n.length;)e[t]=n[t],t+=1;return e}return Uint32Array.from(n)}var sX=(function(){function n(){this.checksum=4294967295}return n.prototype.update=function(e){var t,r;try{for(var i=l_(e),a=i.next();!a.done;a=i.next()){var s=a.value;this.checksum=this.checksum>>>8^xxe[(this.checksum^s)&255]}}catch(o){t={error:o}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return this},n.prototype.digest=function(){return(this.checksum^4294967295)>>>0},n})(),wxe=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117],xxe=Txe(wxe);class bg{bytes;constructor(e){if(this.bytes=e,e.byteLength!==8)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>9223372036854776e3||e<-9223372036854776e3)throw new Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);const t=new Uint8Array(8);for(let r=7,i=Math.abs(Math.round(e));r>-1&&i>0;r--,i/=256)t[r]=i;return e<0&&L9(t),new bg(t)}valueOf(){const e=this.bytes.slice(0),t=e[0]&128;return t&&L9(e),parseInt(ps(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function L9(n){for(let e=0;e<8;e++)n[e]^=255;for(let e=7;e>-1&&(n[e]++,n[e]===0);e--);}class Cxe{toUtf8;fromUtf8;constructor(e,t){this.toUtf8=e,this.fromUtf8=t}format(e){const t=[];for(const a of Object.keys(e)){const s=this.fromUtf8(a);t.push(Uint8Array.from([s.byteLength]),s,this.formatHeaderValue(e[a]))}const r=new Uint8Array(t.reduce((a,s)=>a+s.byteLength,0));let i=0;for(const a of t)r.set(a,i),i+=a.byteLength;return r}formatHeaderValue(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":const t=new DataView(new ArrayBuffer(3));return t.setUint8(0,3),t.setInt16(1,e.value,!1),new Uint8Array(t.buffer);case"integer":const r=new DataView(new ArrayBuffer(5));return r.setUint8(0,4),r.setInt32(1,e.value,!1),new Uint8Array(r.buffer);case"long":const i=new Uint8Array(9);return i[0]=5,i.set(e.value.bytes,1),i;case"binary":const a=new DataView(new ArrayBuffer(3+e.value.byteLength));a.setUint8(0,6),a.setUint16(1,e.value.byteLength,!1);const s=new Uint8Array(a.buffer);return s.set(e.value,3),s;case"string":const o=this.fromUtf8(e.value),l=new DataView(new ArrayBuffer(3+o.byteLength));l.setUint8(0,7),l.setUint16(1,o.byteLength,!1);const c=new Uint8Array(l.buffer);return c.set(o,3),c;case"timestamp":const u=new Uint8Array(9);return u[0]=8,u.set(bg.fromNumber(e.value.valueOf()).bytes,1),u;case"uuid":if(!Mxe.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const d=new Uint8Array(17);return d[0]=9,d.set(bM(e.value.replace(/\-/g,"")),1),d}}parse(e){const t={};let r=0;for(;r<e.byteLength;){const i=e.getUint8(r++),a=this.toUtf8(new Uint8Array(e.buffer,e.byteOffset+r,i));switch(r+=i,e.getUint8(r++)){case 0:t[a]={type:U9,value:!0};break;case 1:t[a]={type:U9,value:!1};break;case 2:t[a]={type:Axe,value:e.getInt8(r++)};break;case 3:t[a]={type:Rxe,value:e.getInt16(r,!1)},r+=2;break;case 4:t[a]={type:kxe,value:e.getInt32(r,!1)},r+=4;break;case 5:t[a]={type:Ixe,value:new bg(new Uint8Array(e.buffer,e.byteOffset+r,8))},r+=8;break;case 6:const s=e.getUint16(r,!1);r+=2,t[a]={type:Nxe,value:new Uint8Array(e.buffer,e.byteOffset+r,s)},r+=s;break;case 7:const o=e.getUint16(r,!1);r+=2,t[a]={type:Dxe,value:this.toUtf8(new Uint8Array(e.buffer,e.byteOffset+r,o))},r+=o;break;case 8:t[a]={type:Oxe,value:new Date(new bg(new Uint8Array(e.buffer,e.byteOffset+r,8)).valueOf())},r+=8;break;case 9:const l=new Uint8Array(e.buffer,e.byteOffset+r,16);r+=16,t[a]={type:Pxe,value:`${ps(l.subarray(0,4))}-${ps(l.subarray(4,6))}-${ps(l.subarray(6,8))}-${ps(l.subarray(8,10))}-${ps(l.subarray(10))}`};break;default:throw new Error("Unrecognized header type tag")}}return t}}var F9;(function(n){n[n.boolTrue=0]="boolTrue",n[n.boolFalse=1]="boolFalse",n[n.byte=2]="byte",n[n.short=3]="short",n[n.integer=4]="integer",n[n.long=5]="long",n[n.byteArray=6]="byteArray",n[n.string=7]="string",n[n.timestamp=8]="timestamp",n[n.uuid=9]="uuid"})(F9||(F9={}));const U9="boolean",Axe="byte",Rxe="short",kxe="integer",Ixe="long",Nxe="binary",Dxe="string",Oxe="timestamp",Pxe="uuid",Mxe=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,oX=4,Ru=oX*2,Hd=4,Lxe=Ru+Hd*2;function Fxe({byteLength:n,byteOffset:e,buffer:t}){if(n<Lxe)throw new Error("Provided message too short to accommodate event stream message overhead");const r=new DataView(t,e,n),i=r.getUint32(0,!1);if(n!==i)throw new Error("Reported message length does not match received message length");const a=r.getUint32(oX,!1),s=r.getUint32(Ru,!1),o=r.getUint32(n-Hd,!1),l=new sX().update(new Uint8Array(t,e,Ru));if(s!==l.digest())throw new Error(`The prelude checksum specified in the message (${s}) does not match the calculated CRC32 checksum (${l.digest()})`);if(l.update(new Uint8Array(t,e+Ru,n-(Ru+Hd))),o!==l.digest())throw new Error(`The message checksum (${l.digest()}) did not match the expected value of ${o}`);return{headers:new DataView(t,e+Ru+Hd,a),body:new Uint8Array(t,e+Ru+Hd+a,i-a-(Ru+Hd+Hd))}}class lX{headerMarshaller;messageBuffer;isEndOfStream;constructor(e,t){this.headerMarshaller=new Cxe(e,t),this.messageBuffer=[],this.isEndOfStream=!1}feed(e){this.messageBuffer.push(this.decode(e))}endOfStream(){this.isEndOfStream=!0}getMessage(){const e=this.messageBuffer.pop(),t=this.isEndOfStream;return{getMessage(){return e},isEndOfStream(){return t}}}getAvailableMessages(){const e=this.messageBuffer;this.messageBuffer=[];const t=this.isEndOfStream;return{getMessages(){return e},isEndOfStream(){return t}}}encode({headers:e,body:t}){const r=this.headerMarshaller.format(e),i=r.byteLength+t.byteLength+16,a=new Uint8Array(i),s=new DataView(a.buffer,a.byteOffset,a.byteLength),o=new sX;return s.setUint32(0,i,!1),s.setUint32(4,r.byteLength,!1),s.setUint32(8,o.update(a.subarray(0,8)).digest(),!1),a.set(r,12),a.set(t,r.byteLength+12),s.setUint32(i-4,o.update(a.subarray(8,i-4)).digest(),!1),a}decode(e){const{headers:t,body:r}=Fxe(e);return{headers:this.headerMarshaller.parse(t),body:r}}formatHeaders(e){return this.headerMarshaller.format(e)}}class Uxe{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const e of this.options.inputStream)yield this.options.decoder.decode(e)}}class Bxe{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const e of this.options.messageStream)yield this.options.encoder.encode(e);this.options.includeEndFrame&&(yield new Uint8Array(0))}}class $xe{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const e of this.options.messageStream){const t=await this.options.deserializer(e);t!==void 0&&(yield t)}}}class Gxe{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const e of this.options.inputStream)yield this.options.serializer(e)}}function Wxe(n){let e=0,t=0,r=null,i=null;const a=o=>{if(typeof o!="number")throw new Error("Attempted to allocate an event message where size was not a number: "+o);e=o,t=4,r=new Uint8Array(o),new DataView(r.buffer).setUint32(0,o,!1)},s=async function*(){const o=n[Symbol.asyncIterator]();for(;;){const{value:l,done:c}=await o.next();if(c){if(e)if(e===t)yield r;else throw new Error("Truncated event message received.");else return;return}const u=l.length;let d=0;for(;d<u;){if(!r){const h=u-d;i||(i=new Uint8Array(4));const f=Math.min(4-t,h);if(i.set(l.slice(d,d+f),t),t+=f,d+=f,t<4)break;a(new DataView(i.buffer).getUint32(0,!1)),i=null}const p=Math.min(e-t,u-d);r.set(l.slice(d,d+p),t),t+=p,d+=p,e&&e===t&&(yield r,r=null,e=0,t=0)}}};return{[Symbol.asyncIterator]:s}}function zxe(n,e){return async function(t){const{value:r}=t.headers[":message-type"];if(r==="error"){const i=new Error(t.headers[":error-message"].value||"UnknownError");throw i.name=t.headers[":error-code"].value,i}else if(r==="exception"){const i=t.headers[":exception-type"].value,a={[i]:t},s=await n(a);if(s.$unknown){const o=new Error(e(t.body));throw o.name=i,o}throw s[i]}else if(r==="event"){const i={[t.headers[":event-type"].value]:t},a=await n(i);return a.$unknown?void 0:a}else throw Error(`Unrecognizable event type: ${t.headers[":event-type"].value}`)}}let qxe=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:e,utf8Decoder:t}){this.eventStreamCodec=new lX(e,t),this.utfEncoder=e}deserialize(e,t){const r=Wxe(e);return new $xe({messageStream:new Uxe({inputStream:r,decoder:this.eventStreamCodec}),deserializer:zxe(t,this.utfEncoder)})}serialize(e,t){return new Bxe({messageStream:new Gxe({inputStream:e,serializer:t}),encoder:this.eventStreamCodec,includeEndFrame:!0})}};const cX=n=>({[Symbol.asyncIterator]:async function*(){const e=n.getReader();try{for(;;){const{done:t,value:r}=await e.read();if(t)return;yield r}}finally{e.releaseLock()}}}),uX=n=>{const e=n[Symbol.asyncIterator]();return new ReadableStream({async pull(t){const{done:r,value:i}=await e.next();if(r)return t.close();t.enqueue(i)}})};class Hxe{universalMarshaller;constructor({utf8Encoder:e,utf8Decoder:t}){this.universalMarshaller=new qxe({utf8Decoder:t,utf8Encoder:e})}deserialize(e,t){const r=Vxe(e)?cX(e):e;return this.universalMarshaller.deserialize(r,t)}serialize(e,t){const r=this.universalMarshaller.serialize(e,t);return typeof ReadableStream=="function"?uX(r):r}}const Vxe=n=>typeof ReadableStream=="function"&&n instanceof ReadableStream,Yxe=n=>new Hxe(n),dX=n=>n.protocol==="ws:"||n.protocol==="wss:",Kxe=3e3;class NM{metadata={handlerProtocol:"websocket/h1.1"};config={};configPromise;httpHandler;sockets={};static create(e,t=new a_){return typeof e?.handle=="function"?e:new NM(e,t)}constructor(e,t=new a_){this.httpHandler=t;const r=i=>(this.config={...i??{}},this.config);typeof e=="function"?(this.config={},this.configPromise=e().then(i=>r(i))):this.configPromise=Promise.resolve(r(e))}destroy(){for(const[e,t]of Object.entries(this.sockets)){for(const r of t)r.close(1e3,"Socket closed through destroy() call");delete this.sockets[e]}}async handle(e){this.config=await this.configPromise;const{logger:t}=this.config;if(!dX(e))return t?.debug?.(`@aws-sdk - ws fetching ${e.protocol}${e.hostname}${e.path}`),this.httpHandler.handle(e);const r=_xe(e);t?.debug?.(`@aws-sdk - ws connecting ${r.split("?")[0]}`);const i=new WebSocket(r);this.sockets[r]||(this.sockets[r]=[]),this.sockets[r].push(i),i.binaryType="arraybuffer";const{connectionTimeout:a=Kxe}=this.config;await this.waitForReady(i,a);const{body:s}=e,o=Qxe(s),l=this.connect(i,o),c=jxe(l);return{response:new Cp({statusCode:200,body:c})}}updateHttpClientConfig(e,t){this.configPromise=this.configPromise.then(r=>(r[e]=t,r))}httpHandlerConfigs(){return this.config??{}}removeNotUsableSockets(e){this.sockets[e]=(this.sockets[e]??[]).filter(t=>![WebSocket.CLOSING,WebSocket.CLOSED].includes(t.readyState))}waitForReady(e,t){return new Promise((r,i)=>{const a=setTimeout(()=>{this.removeNotUsableSockets(e.url),i({$metadata:{httpStatusCode:500,websocketSynthetic500Error:!0}})},t);e.onopen=()=>{clearTimeout(a),r()}})}connect(e,t){const r=[];let i=null,a=null;const s=c=>{i?(c.error?a(c.error):i({done:c.done,value:c.value}),i=null,a=null):r.push(c)};e.onmessage=c=>{const{data:u}=c;s(typeof u=="string"?{done:!1,value:Ap(u)}:{done:!1,value:new Uint8Array(u)})},e.onerror=c=>{e.close(),s({done:!0,error:c})},e.onclose=()=>{this.removeNotUsableSockets(e.url),s({done:!0})};const o={[Symbol.asyncIterator]:()=>({async next(){if(r.length>0){const c=r.shift();if(c.error)throw c.error;return{done:c.done,value:c.value}}return new Promise((c,u)=>{i=c,a=u})}})};return(async()=>{try{for await(const c of t){if(e.readyState>=WebSocket.CLOSING)break;e.send(c)}}catch(c){s({done:!0,error:c})}finally{e.close(1e3)}})(),o}}const Qxe=n=>n[Symbol.asyncIterator]?n:Xxe(n)?cX(n):{[Symbol.asyncIterator]:async function*(){yield n}},jxe=n=>typeof ReadableStream=="function"?uX(n):n,Xxe=n=>typeof ReadableStream=="function"&&n instanceof ReadableStream;class Zxe{signer;constructor(e){this.signer=e.signer}presign(e,t={}){return this.signer.presign(e,t)}async sign(e,t){return Ka.isInstance(e)&&dX(e)?{...await this.signer.presign({...e,body:""},{...t,expiresIn:60,unsignableHeaders:new Set(Object.keys(e.headers).filter(i=>i!=="host"))}),body:e.body}:this.signer.sign(e,t)}signMessage(e,t){return this.signer.signMessage(e,t)}}const Jxe=n=>{const{signer:e}=n;return Object.assign(n,{signer:async t=>{const r=await e(t);if(eCe(r))return new Zxe({signer:r});throw new Error("Expected WebsocketSignatureV4 signer, please check the client constructor.")}})},eCe=n=>!!n;class tCe extends TransformStream{constructor(e,t,r,i){let a=e;super({start(){},async transform(s,o){try{const l=new Date(Date.now()+await i()),c={":date":{type:"timestamp",value:l}},u=await t.sign({message:{body:s,headers:c},priorSignature:a},{signingDate:l});a=u.signature;const d=r.encode({headers:{...c,":chunk-signature":{type:"binary",value:bM(u.signature)}},body:s});o.enqueue(d)}catch(l){o.error(l)}}})}}class nCe{messageSigner;eventStreamCodec;systemClockOffsetProvider;constructor(e){this.messageSigner=e.messageSigner,this.eventStreamCodec=new lX(e.utf8Encoder,e.utf8Decoder),this.systemClockOffsetProvider=async()=>e.systemClockOffset??0}async handle(e,t,r={}){const i=t.request,{body:a,headers:s,query:o}=i;if(!(a instanceof ReadableStream))throw new Error("Eventstream payload must be a ReadableStream.");const l=new TransformStream;i.body=l.readable;let u=((s?.authorization??"").match(/Signature=(\w+)$/)??[])[1]??(o&&o["X-Amz-Signature"])??"";r.__staticSignature&&(u="");const d=new tCe(u,await this.messageSigner(),this.eventStreamCodec,this.systemClockOffsetProvider);a.pipeThrough(d).pipeThrough(l);let p;try{p=await e(t)}catch(h){const f=a.cancel?.();throw f instanceof Promise&&f.catch(()=>{}),h}return p}}const rCe=n=>new nCe(n),iCe=!1,aCe=!1,B9=new Set,sCe=(n,e=cw)=>{if(!B9.has(n)&&!e(n))if(n==="*")console.warn('@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.');else throw new Error(`Region not accepted: region="${n}" is not a valid hostname component.`);else B9.add(n)},pX=n=>typeof n=="string"&&(n.startsWith("fips-")||n.endsWith("-fips")),oCe=n=>pX(n)?["fips-aws-global","aws-fips"].includes(n)?"us-east-1":n.replace(/fips-(dkr-|prod-)?|-fips/,""):n,lCe=n=>{const{region:e,useFipsEndpoint:t}=n;if(!e)throw new Error("Region is missing");return Object.assign(n,{region:async()=>{const r=typeof e=="function"?await e():e,i=oCe(r);return sCe(i),i},useFipsEndpoint:async()=>{const r=typeof e=="string"?e:await e();return pX(r)?!0:typeof t!="function"?Promise.resolve(!!t):t()}})},cCe=n=>Object.assign(n,{eventStreamMarshaller:n.eventStreamSerdeProvider(n)}),$9="content-length";function uCe(n){return e=>async t=>{const r=t.request;if(Ka.isInstance(r)){const{body:i,headers:a}=r;if(i&&Object.keys(a).map(s=>s.toLowerCase()).indexOf($9)===-1)try{const s=n(i);r.headers={...r.headers,[$9]:String(s)}}catch{}}return e({...t,request:r})}}const dCe={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},pCe=n=>({applyToStack:e=>{e.add(uCe(n.bodyLengthChecker),dCe)}}),hCe=async n=>{const e=n?.Bucket||"";if(typeof n.Bucket=="string"&&(n.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),vCe(e)){if(n.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!_Ce(e)||e.indexOf(".")!==-1&&!String(n.Endpoint).startsWith("http:")||e.toLowerCase()!==e||e.length<3)&&(n.ForcePathStyle=!0);return n.DisableMultiRegionAccessPoints&&(n.disableMultiRegionAccessPoints=!0,n.DisableMRAP=!0),n},fCe=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,mCe=/(\d+\.){3}\d+/,gCe=/\.\./,_Ce=n=>fCe.test(n)&&!mCe.test(n)&&!gCe.test(n),vCe=n=>{const[e,t,r,,,i]=n.split(":"),a=e==="arn"&&n.split(":").length>=6,s=!!(a&&t&&r&&i);if(a&&!s)throw new Error(`Invalid ARN: ${n} was an invalid ARN.`);return s},bCe=(n,e,t,r=!1)=>{const i=async()=>{let a;return r?a=t.clientContextParams?.[n]??t[n]??t[e]:a=t[n]??t[e],typeof a=="function"?a():a};return n==="credentialScope"||e==="CredentialScope"?async()=>{const a=typeof t.credentials=="function"?await t.credentials():t.credentials;return a?.credentialScope??a?.CredentialScope}:n==="accountId"||e==="AccountId"?async()=>{const a=typeof t.credentials=="function"?await t.credentials():t.credentials;return a?.accountId??a?.AccountId}:n==="endpoint"||e==="endpoint"?async()=>{if(t.isCustomEndpoint===!1)return;const a=await i();if(a&&typeof a=="object"){if("url"in a)return a.url.href;if("hostname"in a){const{protocol:s,hostname:o,port:l,path:c}=a;return`${s}//${o}${l?":"+l:""}${c}`}}return a}:i},hX=async n=>{},fX=n=>typeof n=="object"?"url"in n?QS(n.url):n:QS(n),yCe=async(n,e,t,r)=>{if(!t.isCustomEndpoint){let s;t.serviceConfiguredEndpoint?s=await t.serviceConfiguredEndpoint():s=await hX(t.serviceId),s&&(t.endpoint=()=>Promise.resolve(fX(s)),t.isCustomEndpoint=!0)}const i=await ECe(n,e,t);if(typeof t.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");return t.endpointProvider(i,r)},ECe=async(n,e,t)=>{const r={},i=e?.getEndpointParameterInstructions?.()||{};for(const[a,s]of Object.entries(i))switch(s.type){case"staticContextParams":r[a]=s.value;break;case"contextParams":r[a]=n[s.name];break;case"clientContextParams":case"builtInParams":r[a]=await bCe(s.name,a,t,s.type!=="builtInParams")();break;case"operationContextParams":r[a]=s.get(n);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(s))}return Object.keys(i).length===0&&Object.assign(r,t),String(t.serviceId).toLowerCase()==="s3"&&await hCe(r),r},SCe=({config:n,instructions:e})=>(t,r)=>async i=>{n.isCustomEndpoint&&CTe(r,"ENDPOINT_OVERRIDE","N");const a=await yCe(i.input,{getEndpointParameterInstructions(){return e}},{...n},r);r.endpointV2=a,r.authSchemes=a.properties?.authSchemes;const s=r.authSchemes?.[0];if(s){r.signing_region=s.signingRegion,r.signing_service=s.signingName;const l=_m(r)?.selectedHttpAuthScheme?.httpAuthOption;l&&(l.signingProperties=Object.assign(l.signingProperties||{},{signing_region:s.signingRegion,signingRegion:s.signingRegion,signing_service:s.signingName,signingName:s.signingName,signingRegionSet:s.signingRegionSet},s.properties))}return t({...i})},TCe={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:b1e.name},wCe=(n,e)=>({applyToStack:t=>{t.addRelativeTo(SCe({config:n,instructions:e}),TCe)}}),xCe=n=>{const e=n.tls??!0,{endpoint:t,useDualstackEndpoint:r,useFipsEndpoint:i}=n,a=t!=null?async()=>fX(await Uc(t)()):void 0,o=Object.assign(n,{endpoint:a,tls:e,isCustomEndpoint:!!t,useDualstackEndpoint:Uc(r??!1),useFipsEndpoint:Uc(i??!1)});let l;return o.serviceConfiguredEndpoint=async()=>(n.serviceId&&!l&&(l=hX(n.serviceId)),l),o};var Bf;(function(n){n.STANDARD="standard",n.ADAPTIVE="adaptive"})(Bf||(Bf={}));const ZS=3,CCe=Bf.STANDARD,ACe=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],RCe=["TimeoutError","RequestTimeout","RequestTimeoutException"],kCe=[500,502,503,504],ICe=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],NCe=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND"],DCe=n=>n?.$retryable!==void 0,OCe=n=>n.$metadata?.clockSkewCorrected,PCe=n=>{const e=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);return n&&n instanceof TypeError?e.has(n.message):!1},mX=n=>n.$metadata?.httpStatusCode===429||ACe.includes(n.name)||n.$retryable?.throttling==!0,DM=(n,e=0)=>DCe(n)||OCe(n)||RCe.includes(n.name)||ICe.includes(n?.code||"")||NCe.includes(n?.code||"")||kCe.includes(n.$metadata?.httpStatusCode||0)||PCe(n)||n.cause!==void 0&&e<=10&&DM(n.cause,e+1),MCe=n=>{if(n.$metadata?.httpStatusCode!==void 0){const e=n.$metadata.httpStatusCode;return 500<=e&&e<=599&&!DM(n)}return!1};class OM{static setTimeoutFn=setTimeout;beta;minCapacity;minFillRate;scaleConstant;smooth;currentCapacity=0;enabled=!1;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(e){this.beta=e?.beta??.7,this.minCapacity=e?.minCapacity??1,this.minFillRate=e?.minFillRate??.5,this.scaleConstant=e?.scaleConstant??.4,this.smooth=e?.smooth??.8;const t=this.getCurrentTimeInSeconds();this.lastThrottleTime=t,this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}getCurrentTimeInSeconds(){return Date.now()/1e3}async getSendToken(){return this.acquireTokenBucket(1)}async acquireTokenBucket(e){if(this.enabled){if(this.refillTokenBucket(),e>this.currentCapacity){const t=(e-this.currentCapacity)/this.fillRate*1e3;await new Promise(r=>OM.setTimeoutFn(r,t))}this.currentCapacity=this.currentCapacity-e}}refillTokenBucket(){const e=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=e;return}const t=(e-this.lastTimestamp)*this.fillRate;this.currentCapacity=Math.min(this.maxCapacity,this.currentCapacity+t),this.lastTimestamp=e}updateClientSendingRate(e){let t;if(this.updateMeasuredRate(),mX(e)){const i=this.enabled?Math.min(this.measuredTxRate,this.fillRate):this.measuredTxRate;this.lastMaxRate=i,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),t=this.cubicThrottle(i),this.enableTokenBucket()}else this.calculateTimeWindow(),t=this.cubicSuccess(this.getCurrentTimeInSeconds());const r=Math.min(t,2*this.measuredTxRate);this.updateTokenBucketRate(r)}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(e){return this.getPrecise(e*this.beta)}cubicSuccess(e){return this.getPrecise(this.scaleConstant*Math.pow(e-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(e){this.refillTokenBucket(),this.fillRate=Math.max(e,this.minFillRate),this.maxCapacity=Math.max(e,this.minCapacity),this.currentCapacity=Math.min(this.currentCapacity,this.maxCapacity)}updateMeasuredRate(){const e=this.getCurrentTimeInSeconds(),t=Math.floor(e*2)/2;if(this.requestCount++,t>this.lastTxRateBucket){const r=this.requestCount/(t-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(r*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=t}}getPrecise(e){return parseFloat(e.toFixed(8))}}const jN=100,gX=20*1e3,LCe=500,G9=500,FCe=5,UCe=10,BCe=1,$Ce="amz-sdk-invocation-id",GCe="amz-sdk-request",WCe=()=>{let n=jN;return{computeNextBackoffDelay:r=>Math.floor(Math.min(gX,Math.random()*2**r*n)),setDelayBase:r=>{n=r}}},W9=({retryDelay:n,retryCount:e,retryCost:t})=>({getRetryCount:()=>e,getRetryDelay:()=>Math.min(gX,n),getRetryCost:()=>t});class _X{maxAttempts;mode=Bf.STANDARD;capacity=G9;retryBackoffStrategy=WCe();maxAttemptsProvider;constructor(e){this.maxAttempts=e,this.maxAttemptsProvider=typeof e=="function"?e:async()=>e}async acquireInitialRetryToken(e){return W9({retryDelay:jN,retryCount:0})}async refreshRetryTokenForRetry(e,t){const r=await this.getMaxAttempts();if(this.shouldRetry(e,t,r)){const i=t.errorType;this.retryBackoffStrategy.setDelayBase(i==="THROTTLING"?LCe:jN);const a=this.retryBackoffStrategy.computeNextBackoffDelay(e.getRetryCount()),s=t.retryAfterHint?Math.max(t.retryAfterHint.getTime()-Date.now()||0,a):a,o=this.getCapacityCost(i);return this.capacity-=o,W9({retryDelay:s,retryCount:e.getRetryCount()+1,retryCost:o})}throw new Error("No retry token available")}recordSuccess(e){this.capacity=Math.max(G9,this.capacity+(e.getRetryCost()??BCe))}getCapacity(){return this.capacity}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch{return console.warn(`Max attempts provider could not resolve. Using default of ${ZS}`),ZS}}shouldRetry(e,t,r){return e.getRetryCount()+1<r&&this.capacity>=this.getCapacityCost(t.errorType)&&this.isRetryableError(t.errorType)}getCapacityCost(e){return e==="TRANSIENT"?UCe:FCe}isRetryableError(e){return e==="THROTTLING"||e==="TRANSIENT"}}class zCe{maxAttemptsProvider;rateLimiter;standardRetryStrategy;mode=Bf.ADAPTIVE;constructor(e,t){this.maxAttemptsProvider=e;const{rateLimiter:r}=t??{};this.rateLimiter=r??new OM,this.standardRetryStrategy=new _X(e)}async acquireInitialRetryToken(e){return await this.rateLimiter.getSendToken(),this.standardRetryStrategy.acquireInitialRetryToken(e)}async refreshRetryTokenForRetry(e,t){return this.rateLimiter.updateClientSendingRate(t),this.standardRetryStrategy.refreshRetryTokenForRetry(e,t)}recordSuccess(e){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(e)}}const qCe=n=>n instanceof Error?n:n instanceof Object?Object.assign(new Error,n):typeof n=="string"?new Error(n):new Error(`AWS SDK error wrapper for ${n}`),HCe=n=>{const{retryStrategy:e,retryMode:t,maxAttempts:r}=n,i=Uc(r??ZS);return Object.assign(n,{maxAttempts:i,retryStrategy:async()=>e||(await Uc(t)()===Bf.ADAPTIVE?new zCe(i):new _X(i))})},VCe=n=>n?.body instanceof ReadableStream,YCe=n=>(e,t)=>async r=>{let i=await n.retryStrategy();const a=await n.maxAttempts();if(KCe(i)){i=i;let s=await i.acquireInitialRetryToken(t.partition_id),o=new Error,l=0,c=0;const{request:u}=r,d=Ka.isInstance(u);for(d&&(u.headers[$Ce]=EM());;)try{d&&(u.headers[GCe]=`attempt=${l+1}; max=${a}`);const{response:p,output:h}=await e(r);return i.recordSuccess(s),h.$metadata.attempts=l+1,h.$metadata.totalRetryDelay=c,{response:p,output:h}}catch(p){const h=QCe(p);if(o=qCe(p),d&&VCe(u))throw(t.logger instanceof Pj?console:t.logger)?.warn("An error was encountered in a non-retryable streaming request."),o;try{s=await i.refreshRetryTokenForRetry(s,h)}catch{throw o.$metadata||(o.$metadata={}),o.$metadata.attempts=l+1,o.$metadata.totalRetryDelay=c,o}l=s.getRetryCount();const f=s.getRetryDelay();c+=f,await new Promise(m=>setTimeout(m,f))}}else return i=i,i?.mode&&(t.userAgent=[...t.userAgent||[],["cfg/retry-mode",i.mode]]),i.retry(e,r)},KCe=n=>typeof n.acquireInitialRetryToken<"u"&&typeof n.refreshRetryTokenForRetry<"u"&&typeof n.recordSuccess<"u",QCe=n=>{const e={error:n,errorType:jCe(n)},t=JCe(n.$response);return t&&(e.retryAfterHint=t),e},jCe=n=>mX(n)?"THROTTLING":DM(n)?"TRANSIENT":MCe(n)?"SERVER_ERROR":"CLIENT_ERROR",XCe={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0},ZCe=n=>({applyToStack:e=>{e.add(YCe(n),XCe)}}),JCe=n=>{if(!Cp.isInstance(n))return;const e=Object.keys(n.headers).find(a=>a.toLowerCase()==="retry-after");if(!e)return;const t=n.headers[e],r=Number(t);return Number.isNaN(r)?new Date(t):new Date(r*1e3)},eAe=async(n,e,t)=>({operation:_m(e).operation,region:await Uc(n.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});function tAe(n){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"bedrock",region:n.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}}function nAe(n){return{schemeId:"smithy.api#httpBearerAuth",propertiesExtractor:({profile:e,filepath:t,configFilepath:r,ignoreCache:i},a)=>({identityProperties:{profile:e,filepath:t,configFilepath:r,ignoreCache:i}})}}const rAe=n=>{const e=[];switch(n.operation){default:e.push(tAe(n)),e.push(nAe())}return e},iAe=n=>{const e=dj(n.token,uj,xM),t=Uwe(n);return Object.assign(t,{authSchemePreference:Uc(n.authSchemePreference??[]),token:e})},aAe=n=>Object.assign(n,{useDualstackEndpoint:n.useDualstackEndpoint??!1,useFipsEndpoint:n.useFipsEndpoint??!1,defaultSigningName:"bedrock"}),sAe={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},oAe="3.1000.0",lAe={version:oAe};var vX={name:"SHA-256"},z9={name:"HMAC",hash:vX},cAe=new Uint8Array([227,176,196,66,152,252,28,20,154,251,244,200,153,111,185,36,39,174,65,228,100,155,147,76,164,149,153,27,120,82,184,85]);const uAe={};function JE(){return typeof window<"u"?window:typeof self<"u"?self:uAe}var dAe=(function(){function n(e){this.toHash=new Uint8Array(0),this.secret=e,this.reset()}return n.prototype.update=function(e){if(!QN(e)){var t=c_(e),r=new Uint8Array(this.toHash.byteLength+t.byteLength);r.set(this.toHash,0),r.set(t,this.toHash.byteLength),this.toHash=r}},n.prototype.digest=function(){var e=this;return this.key?this.key.then(function(t){return JE().crypto.subtle.sign(z9,t,e.toHash).then(function(r){return new Uint8Array(r)})}):QN(this.toHash)?Promise.resolve(cAe):Promise.resolve().then(function(){return JE().crypto.subtle.digest(vX,e.toHash)}).then(function(t){return Promise.resolve(new Uint8Array(t))})},n.prototype.reset=function(){var e=this;this.toHash=new Uint8Array(0),this.secret&&this.secret!==void 0&&(this.key=new Promise(function(t,r){JE().crypto.subtle.importKey("raw",c_(e.secret),z9,!1,["sign"]).then(t,r)}),this.key.catch(function(){}))},n})(),vo=64,pAe=32,hAe=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),fAe=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],mAe=Math.pow(2,53)-1,eS=(function(){function n(){this.state=Int32Array.from(fAe),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}return n.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");var t=0,r=e.byteLength;if(this.bytesHashed+=r,this.bytesHashed*8>mAe)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;r>0;)this.buffer[this.bufferLength++]=e[t++],r--,this.bufferLength===vo&&(this.hashBuffer(),this.bufferLength=0)},n.prototype.digest=function(){if(!this.finished){var e=this.bytesHashed*8,t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),r=this.bufferLength;if(t.setUint8(this.bufferLength++,128),r%vo>=vo-8){for(var i=this.bufferLength;i<vo;i++)t.setUint8(i,0);this.hashBuffer(),this.bufferLength=0}for(var i=this.bufferLength;i<vo-8;i++)t.setUint8(i,0);t.setUint32(vo-8,Math.floor(e/4294967296),!0),t.setUint32(vo-4,e),this.hashBuffer(),this.finished=!0}for(var a=new Uint8Array(pAe),i=0;i<8;i++)a[i*4]=this.state[i]>>>24&255,a[i*4+1]=this.state[i]>>>16&255,a[i*4+2]=this.state[i]>>>8&255,a[i*4+3]=this.state[i]>>>0&255;return a},n.prototype.hashBuffer=function(){for(var e=this,t=e.buffer,r=e.state,i=r[0],a=r[1],s=r[2],o=r[3],l=r[4],c=r[5],u=r[6],d=r[7],p=0;p<vo;p++){if(p<16)this.temp[p]=(t[p*4]&255)<<24|(t[p*4+1]&255)<<16|(t[p*4+2]&255)<<8|t[p*4+3]&255;else{var h=this.temp[p-2],f=(h>>>17|h<<15)^(h>>>19|h<<13)^h>>>10;h=this.temp[p-15];var m=(h>>>7|h<<25)^(h>>>18|h<<14)^h>>>3;this.temp[p]=(f+this.temp[p-7]|0)+(m+this.temp[p-16]|0)}var g=(((l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7))+(l&c^~l&u)|0)+(d+(hAe[p]+this.temp[p]|0)|0)|0,_=((i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10))+(i&a^i&s^a&s)|0;d=u,u=c,c=l,l=o+g|0,o=s,s=a,a=i,i=g+_|0}r[0]+=i,r[1]+=a,r[2]+=s,r[3]+=o,r[4]+=l,r[5]+=c,r[6]+=u,r[7]+=d},n})(),gAe=(function(){function n(e){this.secret=e,this.hash=new eS,this.reset()}return n.prototype.update=function(e){if(!(QN(e)||this.error))try{this.hash.update(c_(e))}catch(t){this.error=t}},n.prototype.digestSync=function(){if(this.error)throw this.error;return this.outer?(this.outer.finished||this.outer.update(this.hash.digest()),this.outer.digest()):this.hash.digest()},n.prototype.digest=function(){return RM(this,void 0,void 0,function(){return kM(this,function(e){return[2,this.digestSync()]})})},n.prototype.reset=function(){if(this.hash=new eS,this.secret){this.outer=new eS;var e=_Ae(this.secret),t=new Uint8Array(vo);t.set(e);for(var r=0;r<vo;r++)e[r]^=54,t[r]^=92;this.hash.update(e),this.outer.update(t);for(var r=0;r<e.byteLength;r++)e[r]=0}},n})();function _Ae(n){var e=c_(n);if(e.byteLength>vo){var t=new eS;t.update(e),e=t.digest()}var r=new Uint8Array(vo);return r.set(e),r}var vAe=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function bAe(n){if(yAe(n)&&typeof n.crypto.subtle=="object"){var e=n.crypto.subtle;return EAe(e)}return!1}function yAe(n){if(typeof n=="object"&&typeof n.crypto=="object"){var e=n.crypto.getRandomValues;return typeof e=="function"}return!1}function EAe(n){return n&&vAe.every(function(e){return typeof n[e]=="function"})}var SAe=(function(){function n(e){bAe(JE())?this.hash=new dAe(e):this.hash=new gAe(e)}return n.prototype.update=function(e,t){this.hash.update(c_(e))},n.prototype.digest=function(){return this.hash.digest()},n.prototype.reset=function(){this.hash.reset()},n})();const TAe=({serviceId:n,clientVersion:e})=>async t=>{const r=typeof window<"u"?window.navigator:void 0,i=r?.userAgent??"",a=r?.userAgentData?.platform??q9.os(i)??"other",s=void 0,o=r?.userAgentData?.brands??[],l=o[o.length-1],c=l?.brand??q9.browser(i)??"unknown",u=l?.version??"unknown",d=[["aws-sdk-js",e],["ua","2.1"],[`os/${a}`,s],["lang/js"],["md/browser",`${c}_${u}`]];n&&d.push([`api/${n}`,e]);const p=await t?.userAgentAppId?.();return p&&d.push([`app/${p}`]),d},q9={os(n){if(/iPhone|iPad|iPod/.test(n))return"iOS";if(/Macintosh|Mac OS X/.test(n))return"macOS";if(/Windows NT/.test(n))return"Windows";if(/Android/.test(n))return"Android";if(/Linux/.test(n))return"Linux"},browser(n){if(/EdgiOS|EdgA|Edg\//.test(n))return"Microsoft Edge";if(/Firefox\//.test(n))return"Firefox";if(/Chrome\//.test(n))return"Chrome";if(/Safari\//.test(n))return"Safari"}},wAe=n=>()=>Promise.reject(n),xAe=["in-region","cross-region","mobile","standard","legacy"],CAe=({defaultsMode:n}={})=>dwe(async()=>{const e=typeof n=="function"?await n():n;switch(e?.toLowerCase()){case"auto":return Promise.resolve(AAe()?"mobile":"standard");case"mobile":case"in-region":case"cross-region":case"standard":case"legacy":return Promise.resolve(e?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${xAe.join(", ")}, got ${e}`)}}),AAe=()=>{const n=window?.navigator;if(n?.connection){const{effectiveType:e,rtt:t,downlink:r}=n?.connection;if(typeof e=="string"&&e!=="4g"||Number(t)>100||Number(r)<10)return!0}return n?.userAgentData?.mobile||typeof n?.maxTouchPoints=="number"&&n?.maxTouchPoints>1},bX="required",Wl="fn",zl="argv",bm="ref",H9=!0,V9="isSet",u_="booleanEquals",Rh="error",h0="endpoint",Aa="tree",PM="PartitionResult",Y9={[bX]:!1,type:"string"},K9={[bX]:!0,default:!1,type:"boolean"},Q9={[bm]:"Endpoint"},yX={[Wl]:u_,[zl]:[{[bm]:"UseFIPS"},!0]},EX={[Wl]:u_,[zl]:[{[bm]:"UseDualStack"},!0]},Cl={},j9={[Wl]:"getAttr",[zl]:[{[bm]:PM},"supportsFIPS"]},X9={[Wl]:u_,[zl]:[!0,{[Wl]:"getAttr",[zl]:[{[bm]:PM},"supportsDualStack"]}]},Z9=[yX],J9=[EX],e8=[{[bm]:"Region"}],RAe={parameters:{Region:Y9,UseDualStack:K9,UseFIPS:K9,Endpoint:Y9},rules:[{conditions:[{[Wl]:V9,[zl]:[Q9]}],rules:[{conditions:Z9,error:"Invalid Configuration: FIPS and custom endpoint are not supported",type:Rh},{rules:[{conditions:J9,error:"Invalid Configuration: Dualstack and custom endpoint are not supported",type:Rh},{endpoint:{url:Q9,properties:Cl,headers:Cl},type:h0}],type:Aa}],type:Aa},{rules:[{conditions:[{[Wl]:V9,[zl]:e8}],rules:[{conditions:[{[Wl]:"aws.partition",[zl]:e8,assign:PM}],rules:[{conditions:[yX,EX],rules:[{conditions:[{[Wl]:u_,[zl]:[H9,j9]},X9],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:Cl,headers:Cl},type:h0}],type:Aa}],type:Aa},{error:"FIPS and DualStack are enabled, but this partition does not support one or both",type:Rh}],type:Aa},{conditions:Z9,rules:[{conditions:[{[Wl]:u_,[zl]:[j9,H9]}],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime-fips.{Region}.{PartitionResult#dnsSuffix}",properties:Cl,headers:Cl},type:h0}],type:Aa}],type:Aa},{error:"FIPS is enabled but this partition does not support FIPS",type:Rh}],type:Aa},{conditions:J9,rules:[{conditions:[X9],rules:[{rules:[{endpoint:{url:"https://bedrock-runtime.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:Cl,headers:Cl},type:h0}],type:Aa}],type:Aa},{error:"DualStack is enabled but this partition does not support DualStack",type:Rh}],type:Aa},{rules:[{endpoint:{url:"https://bedrock-runtime.{Region}.{PartitionResult#dnsSuffix}",properties:Cl,headers:Cl},type:h0}],type:Aa}],type:Aa}],type:Aa},{error:"Invalid Configuration: Missing Region",type:Rh}],type:Aa}]},kAe=RAe,IAe=new PTe({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),NAe=(n,e={})=>IAe.get(n,()=>JTe(kAe,{endpointParams:n,logger:e.logger}));KS.aws=Tj;class Xa extends of{constructor(e){super(e),Object.setPrototypeOf(this,Xa.prototype)}}class MM extends Xa{name="AccessDeniedException";$fault="client";constructor(e){super({name:"AccessDeniedException",$fault:"client",...e}),Object.setPrototypeOf(this,MM.prototype)}}class LM extends Xa{name="InternalServerException";$fault="server";constructor(e){super({name:"InternalServerException",$fault:"server",...e}),Object.setPrototypeOf(this,LM.prototype)}}class FM extends Xa{name="ThrottlingException";$fault="client";constructor(e){super({name:"ThrottlingException",$fault:"client",...e}),Object.setPrototypeOf(this,FM.prototype)}}class UM extends Xa{name="ValidationException";$fault="client";constructor(e){super({name:"ValidationException",$fault:"client",...e}),Object.setPrototypeOf(this,UM.prototype)}}class BM extends Xa{name="ConflictException";$fault="client";constructor(e){super({name:"ConflictException",$fault:"client",...e}),Object.setPrototypeOf(this,BM.prototype)}}class $M extends Xa{name="ResourceNotFoundException";$fault="client";constructor(e){super({name:"ResourceNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,$M.prototype)}}class GM extends Xa{name="ServiceQuotaExceededException";$fault="client";constructor(e){super({name:"ServiceQuotaExceededException",$fault:"client",...e}),Object.setPrototypeOf(this,GM.prototype)}}class WM extends Xa{name="ServiceUnavailableException";$fault="server";constructor(e){super({name:"ServiceUnavailableException",$fault:"server",...e}),Object.setPrototypeOf(this,WM.prototype)}}class zM extends Xa{name="ModelErrorException";$fault="client";originalStatusCode;resourceName;constructor(e){super({name:"ModelErrorException",$fault:"client",...e}),Object.setPrototypeOf(this,zM.prototype),this.originalStatusCode=e.originalStatusCode,this.resourceName=e.resourceName}}class qM extends Xa{name="ModelNotReadyException";$fault="client";$retryable={};constructor(e){super({name:"ModelNotReadyException",$fault:"client",...e}),Object.setPrototypeOf(this,qM.prototype)}}class HM extends Xa{name="ModelTimeoutException";$fault="client";constructor(e){super({name:"ModelTimeoutException",$fault:"client",...e}),Object.setPrototypeOf(this,HM.prototype)}}class VM extends Xa{name="ModelStreamErrorException";$fault="client";originalStatusCode;originalMessage;constructor(e){super({name:"ModelStreamErrorException",$fault:"client",...e}),Object.setPrototypeOf(this,VM.prototype),this.originalStatusCode=e.originalStatusCode,this.originalMessage=e.originalMessage}}const DAe="AudioBlock",OAe="AccessDeniedException",PAe="AppliedGuardrailDetails",MAe="AudioSource",LAe="AnyToolChoice",FAe="AutoToolChoice",UAe="Citation",BAe="ContentBlocks",$Ae="ContentBlockDelta",GAe="ContentBlockDeltaEvent",WAe="ContentBlockStart",zAe="ContentBlockStartEvent",qAe="ContentBlockStopEvent",HAe="ContentBlock",VAe="CitationsConfig",YAe="CitationsContentBlock",KAe="CacheDetail",QAe="CacheDetailsList",jAe="CitationsDelta",XAe="ConflictException",ZAe="CitationGeneratedContent",JAe="CitationGeneratedContentList",eRe="CitationLocation",tRe="CachePointBlock",nRe="ConverseStream",rRe="CitationSourceContent",iRe="CitationSourceContentDelta",aRe="CitationSourceContentList",sRe="CitationSourceContentListDelta",oRe="ConverseStreamMetrics",lRe="ConverseStreamMetadataEvent",cRe="ConverseStreamOutput",uRe="ConverseStreamRequest",dRe="ConverseStreamResponse",pRe="ConverseStreamTrace",hRe="Citations",fRe="DocumentBlock",mRe="DocumentContentBlocks",gRe="DocumentContentBlock",_Re="DocumentCharLocation",vRe="DocumentChunkLocation",bRe="DocumentPageLocation",yRe="DocumentSource",ERe="ErrorBlock",SRe="GuardrailAssessment",TRe="GuardrailAssessmentList",wRe="GuardrailAssessmentListMap",xRe="GuardrailAssessmentMap",CRe="GuardrailAutomatedReasoningDifferenceScenarioList",ARe="GuardrailAutomatedReasoningFinding",RRe="GuardrailAutomatedReasoningFindingList",kRe="GuardrailAutomatedReasoningImpossibleFinding",IRe="GuardrailAutomatedReasoningInvalidFinding",NRe="GuardrailAutomatedReasoningInputTextReference",DRe="GuardrailAutomatedReasoningInputTextReferenceList",ORe="GuardrailAutomatedReasoningLogicWarning",PRe="GuardrailAutomatedReasoningNoTranslationsFinding",MRe="GuardrailAutomatedReasoningPolicyAssessment",LRe="GuardrailAutomatedReasoningRule",FRe="GuardrailAutomatedReasoningRuleList",URe="GuardrailAutomatedReasoningScenario",BRe="GuardrailAutomatedReasoningSatisfiableFinding",$Re="GuardrailAutomatedReasoningStatementList",GRe="GuardrailAutomatedReasoningStatementLogicContent",WRe="GuardrailAutomatedReasoningStatementNaturalLanguageContent",zRe="GuardrailAutomatedReasoningStatement",qRe="GuardrailAutomatedReasoningTranslation",HRe="GuardrailAutomatedReasoningTranslationAmbiguousFinding",VRe="GuardrailAutomatedReasoningTooComplexFinding",YRe="GuardrailAutomatedReasoningTranslationList",KRe="GuardrailAutomatedReasoningTranslationOption",QRe="GuardrailAutomatedReasoningTranslationOptionList",jRe="GuardrailAutomatedReasoningValidFinding",XRe="GuardrailConverseContentBlock",ZRe="GuardrailContentFilter",JRe="GuardrailContentFilterList",e2e="GuardrailContextualGroundingFilter",t2e="GuardrailContextualGroundingFilters",n2e="GuardrailContextualGroundingPolicyAssessment",r2e="GuardrailConverseImageBlock",i2e="GuardrailConverseImageSource",a2e="GuardrailContentPolicyAssessment",s2e="GuardrailConverseTextBlock",o2e="GuardrailCustomWord",l2e="GuardrailCustomWordList",c2e="GuardrailCoverage",u2e="GuardrailImageCoverage",d2e="GuardrailInvocationMetrics",p2e="GuardrailManagedWord",h2e="GuardrailManagedWordList",f2e="GuardrailPiiEntityFilter",m2e="GuardrailPiiEntityFilterList",g2e="GuardrailRegexFilter",_2e="GuardrailRegexFilterList",v2e="GuardrailStreamConfiguration",b2e="GuardrailSensitiveInformationPolicyAssessment",y2e="GuardrailTopic",E2e="GuardrailTraceAssessment",S2e="GuardrailTextCharactersCoverage",T2e="GuardrailTopicList",w2e="GuardrailTopicPolicyAssessment",x2e="GuardrailUsage",C2e="GuardrailWordPolicyAssessment",A2e="ImageBlock",R2e="ImageBlockDelta",k2e="ImageBlockStart",I2e="InferenceConfiguration",N2e="ImageSource",D2e="InternalServerException",O2e="JsonSchemaDefinition",P2e="Message",M2e="ModelErrorException",L2e="ModelNotReadyException",F2e="MessageStartEvent",U2e="ModelStreamErrorException",B2e="MessageStopEvent",$2e="ModelTimeoutException",G2e="Messages",W2e="OutputConfig",z2e="OutputFormat",q2e="OutputFormatStructure",H2e="PerformanceConfiguration",V2e="PromptRouterTrace",Y2e="PromptVariableMap",K2e="PromptVariableValues",Q2e="ReasoningContentBlock",j2e="ReasoningContentBlockDelta",X2e="RequestMetadata",Z2e="ResourceNotFoundException",J2e="ReasoningTextBlock",eke="SystemContentBlocks",tke="SystemContentBlock",nke="S3Location",rke="ServiceQuotaExceededException",ike="SearchResultBlock",ake="SearchResultContentBlock",ske="SearchResultContentBlocks",oke="SearchResultLocation",lke="ServiceTier",cke="SpecificToolChoice",uke="SystemTool",dke="ServiceUnavailableException",pke="ToolConfiguration",hke="ToolChoice",fke="ThrottlingException",mke="ToolInputSchema",gke="ToolResultBlock",_ke="ToolResultBlocksDelta",vke="ToolResultBlockDelta",bke="ToolResultBlockStart",yke="ToolResultContentBlocks",Eke="ToolResultContentBlock",Ske="ToolSpecification",Tke="TokenUsage",wke="ToolUseBlock",xke="ToolUseBlockDelta",Cke="ToolUseBlockStart",Ake="Tools",Rke="Tool",kke="VideoBlock",Ike="ValidationException",Nke="VideoSource",Dke="WebLocation",oh="action",Oke="appliedGuardrailDetails",Pke="additionalModelRequestFields",Mke="additionalModelResponseFieldPaths",Lke="additionalModelResponseFields",Fke="actionReason",Uke="automatedReasoningPolicy",Bke="automatedReasoningPolicyUnits",$ke="automatedReasoningPolicies",Gke="any",Wke="audio",zke="auto",Av="bytes",qke="bucketOwner",ac="client",Hke="contentBlockDelta",YM="contentBlockIndex",Vke="contentBlockStart",Yke="contentBlockStop",Kke="citationsContent",Qke="cacheDetails",jke="claimsFalseScenario",Xke="contextualGroundingPolicy",Zke="contextualGroundingPolicyUnits",Jke="contentPolicy",eIe="contentPolicyImageUnits",tIe="contentPolicyUnits",KM="cachePoint",SX="contradictingRules",nIe="cacheReadInputTokens",TX="claimsTrueScenario",rIe="customWords",iIe="cacheWriteInputTokens",QM="citations",aIe="citation",wX="claims",Rv="content",sIe="context",xX="confidence",oIe="delta",lIe="documentChar",cIe="documentChunk",jM="documentIndex",uIe="documentPage",dIe="differenceScenarios",lh="detected",CX="description",pIe="domain",AX="document",Za="error",hIe="enabled",pw="end",ym="format",fIe="filterStrength",mIe="findings",RX="filters",gIe="guardrail",_Ie="guardrailArn",vIe="guardrailCoverage",bIe="guardrailConfig",kX="guardContent",yIe="guardrailId",EIe="guardrailIdentifier",SIe="guardrailOrigin",TIe="guardrailOwnership",wIe="guardrailProcessingLatency",IX="guardrailVersion",NX="guarded",xIe="http",Lo="httpError",DX="input",CIe="inputAssessment",AIe="inferenceConfig",RIe="invocationMetrics",kIe="invokedModelId",IIe="inputSchema",NIe="internalServerException",OX="inputTokens",DIe="identifier",OIe="images",kv="image",PIe="impossible",MIe="invalid",XM="json",LIe="jsonSchema",PX="location",FIe="latencyMs",hw="logicWarning",UIe="latency",BIe="logic",Zs="message",$Ie="modelId",GIe="modelOutput",WIe="messageStart",zIe="modelStreamErrorException",qIe="messageStop",HIe="maxTokens",VIe="managedWordLists",fw="match",YIe="messages",KIe="metrics",QIe="metadata",ou="name",jIe="naturalLanguage",XIe="noTranslations",ZIe="outputAssessments",JIe="outputConfig",eNe="originalMessage",MX="originalStatusCode",tNe="outputTokens",nNe="options",LX="premises",FX="performanceConfig",rNe="piiEntities",iNe="promptRouter",aNe="promptVariables",sNe="policyVersionArn",oNe="qualifiers",lNe="regex",UX="reasoningContent",BX="redactedContent",cNe="requestMetadata",uNe="resourceName",dNe="reasoningText",pNe="regexes",$X="role",GX="smithy.ts.sdk.synthetic.com.amazonaws.bedrockruntime",WX="sourceContent",hNe="sensitiveInformationPolicy",fNe="sensitiveInformationPolicyFreeUnits",mNe="sensitiveInformationPolicyUnits",mw="s3Location",gNe="streamProcessingMode",_Ne="stopReason",vNe="searchResultIndex",bNe="searchResultLocation",zX="searchResult",yNe="supportingRules",ENe="stopSequences",qX="serviceTier",SNe="systemTool",TNe="serviceUnavailableException",wNe="satisfiable",xNe="score",CNe="schema",HX="server",VX="signature",lu="source",YX="status",Iv="start",ANe="statements",RNe="stream",kNe="streaming",INe="strict",NNe="structure",DNe="system",KX="ttl",ONe="translationAmbiguous",PNe="toolConfig",MNe="textCharacters",LNe="toolChoice",FNe="tooComplex",UNe="throttlingException",BNe="textFormat",$Ne="topicPolicy",GNe="topicPolicyUnits",WNe="topP",ZM="toolResult",zNe="toolSpec",qNe="totalTokens",JM="toolUse",gw="toolUseId",ha="text",HNe="temperature",VNe="threshold",e4="title",QX="total",YNe="tools",KNe="tool",QNe="topics",jX="trace",_w="translation",jNe="translations",Js="type",XX="usage",XNe="untranslatedClaims",ZNe="untranslatedPremises",JNe="uri",eDe="url",tDe="validationException",nDe="valid",ZX="video",rDe="web",iDe="wordPolicy",aDe="wordPolicyUnits",Ie="com.amazonaws.bedrockruntime",JX=cs.for(GX);var sDe=[-3,GX,"BedrockRuntimeServiceException",0,[],[]];JX.registerError(sDe,Xa);const eo=cs.for(Ie);var oDe=[-3,Ie,OAe,{[Za]:ac,[Lo]:403},[Zs],[0]];eo.registerError(oDe,MM);var lDe=[-3,Ie,XAe,{[Za]:ac,[Lo]:400},[Zs],[0]];eo.registerError(lDe,BM);var eZ=[-3,Ie,D2e,{[Za]:HX,[Lo]:500},[Zs],[0]];eo.registerError(eZ,LM);var cDe=[-3,Ie,M2e,{[Za]:ac,[Lo]:424},[Zs,MX,uNe],[0,1,0]];eo.registerError(cDe,zM);var uDe=[-3,Ie,L2e,{[Za]:ac,[Lo]:429},[Zs],[0]];eo.registerError(uDe,qM);var tZ=[-3,Ie,U2e,{[Za]:ac,[Lo]:424},[Zs,MX,eNe],[0,1,0]];eo.registerError(tZ,VM);var dDe=[-3,Ie,$2e,{[Za]:ac,[Lo]:408},[Zs],[0]];eo.registerError(dDe,HM);var pDe=[-3,Ie,Z2e,{[Za]:ac,[Lo]:404},[Zs],[0]];eo.registerError(pDe,$M);var hDe=[-3,Ie,rke,{[Za]:ac,[Lo]:400},[Zs],[0]];eo.registerError(hDe,GM);var nZ=[-3,Ie,dke,{[Za]:HX,[Lo]:503},[Zs],[0]];eo.registerError(nZ,WM);var rZ=[-3,Ie,fke,{[Za]:ac,[Lo]:429},[Zs],[0]];eo.registerError(rZ,FM);var iZ=[-3,Ie,Ike,{[Za]:ac,[Lo]:400},[Zs],[0]];eo.registerError(iZ,UM);const fDe=[JX,eo];var mDe=[0,Ie,GRe,8,0],aZ=[0,Ie,WRe,8,0],gDe=[3,Ie,LAe,0,[],[]],_De=[3,Ie,PAe,0,[yIe,IX,_Ie,SIe,TIe],[0,0,0,64,0]],vDe=[3,Ie,DAe,0,[ym,lu,Za],[0,[()=>fPe,0],[()=>n4,0]],2],bDe=[3,Ie,FAe,0,[],[]],yDe=[3,Ie,KAe,0,[KX,OX],[0,1],2],t4=[3,Ie,tRe,0,[Js,KX],[0,0],1],EDe=[3,Ie,UAe,0,[e4,lu,WX,PX],[0,0,()=>WOe,()=>fZ]],sZ=[3,Ie,VAe,0,[hIe],[2],1],SDe=[3,Ie,YAe,0,[Rv,QM],[()=>$Oe,()=>GOe]],TDe=[3,Ie,jAe,0,[e4,lu,WX,PX],[0,0,()=>zOe,()=>fZ]],wDe=[3,Ie,iRe,0,[ha],[0]],xDe=[3,Ie,GAe,0,[oIe,YM],[[()=>vPe,0],1],2],CDe=[3,Ie,zAe,0,[Iv,YM],[()=>bPe,1],2],ADe=[3,Ie,qAe,0,[YM],[1],1],RDe=[3,Ie,lRe,0,[XX,KIe,jX,FX,qX],[()=>IOe,()=>kDe,[()=>DDe,0],()=>uZ,()=>pZ],2],kDe=[3,Ie,oRe,0,[FIe],[1],1],IDe=[3,Ie,uRe,0,[$Ie,YIe,DNe,AIe,PNe,bIe,Pke,aNe,Mke,cNe,FX,qX,JIe],[[0,1],[()=>iPe,0],[()=>sPe,0],()=>_Oe,()=>NOe,()=>lOe,15,[()=>pPe,0],64,[()=>hPe,0],()=>uZ,()=>pZ,[()=>SOe,0]],1],NDe=[3,Ie,dRe,0,[RNe],[[()=>yPe,16]]],DDe=[3,Ie,pRe,0,[gIe,iNe],[[()=>pOe,0],()=>wOe]],oZ=[3,Ie,fRe,0,[ou,lu,ym,sIe,QM],[0,()=>SPe,0,0,()=>sZ],2],ODe=[3,Ie,_Re,0,[jM,Iv,pw],[1,1,1]],PDe=[3,Ie,vRe,0,[jM,Iv,pw],[1,1,1]],MDe=[3,Ie,bRe,0,[jM,Iv,pw],[1,1,1]],n4=[3,Ie,ERe,8,[Zs],[0]],lZ=[3,Ie,SRe,0,[$Ne,Jke,iDe,hNe,Xke,Uke,RIe,Oke],[()=>dOe,()=>QDe,()=>fOe,()=>oOe,()=>XDe,[()=>$De,0],()=>rOe,()=>_De]],LDe=[3,Ie,kRe,0,[_w,SX,hw],[[()=>Nv,0],()=>r4,[()=>vw,0]]],FDe=[3,Ie,NRe,0,[ha],[[()=>aZ,0]]],UDe=[3,Ie,IRe,0,[_w,SX,hw],[[()=>Nv,0],()=>r4,[()=>vw,0]]],vw=[3,Ie,ORe,0,[Js,LX,wX],[0,[()=>d_,0],[()=>d_,0]]],BDe=[3,Ie,PRe,0,[],[]],$De=[3,Ie,MRe,0,[mIe],[[()=>KOe,0]]],GDe=[3,Ie,LRe,0,[DIe,sNe],[0,0]],WDe=[3,Ie,BRe,0,[_w,TX,jke,hw],[[()=>Nv,0],[()=>JS,0],[()=>JS,0],[()=>vw,0]]],JS=[3,Ie,URe,0,[ANe],[[()=>d_,0]]],zDe=[3,Ie,zRe,0,[BIe,jIe],[[()=>mDe,0],[()=>aZ,0]]],qDe=[3,Ie,VRe,0,[],[]],Nv=[3,Ie,qRe,0,[LX,wX,ZNe,XNe,xX],[[()=>d_,0],[()=>d_,0],[()=>t8,0],[()=>t8,0],1]],HDe=[3,Ie,HRe,0,[nNe,dIe],[[()=>jOe,0],[()=>YOe,0]]],VDe=[3,Ie,KRe,0,[jNe],[[()=>QOe,0]]],YDe=[3,Ie,jRe,0,[_w,TX,yNe,hw],[[()=>Nv,0],[()=>JS,0],()=>r4,[()=>vw,0]]],KDe=[3,Ie,ZRe,0,[Js,xX,oh,fIe,lh],[0,0,0,0,2],3],QDe=[3,Ie,a2e,0,[RX],[()=>XOe],1],jDe=[3,Ie,e2e,0,[Js,VNe,xNe,oh,lh],[0,1,1,0,2],4],XDe=[3,Ie,n2e,0,[RX],[()=>ZOe]],ZDe=[3,Ie,r2e,8,[ym,lu],[0,[()=>wPe,0]],2],JDe=[3,Ie,s2e,0,[ha,oNe],[0,64],1],eOe=[3,Ie,c2e,0,[MNe,OIe],[()=>cOe,()=>nOe]],tOe=[3,Ie,o2e,0,[fw,oh,lh],[0,0,2],2],nOe=[3,Ie,u2e,0,[NX,QX],[1,1]],rOe=[3,Ie,d2e,0,[wIe,XX,vIe],[1,()=>hOe,()=>eOe]],iOe=[3,Ie,p2e,0,[fw,Js,oh,lh],[0,0,0,2],3],aOe=[3,Ie,f2e,0,[fw,Js,oh,lh],[0,0,0,2],3],sOe=[3,Ie,g2e,0,[oh,ou,fw,lNe,lh],[0,0,0,0,2],1],oOe=[3,Ie,b2e,0,[rNe,pNe],[()=>tPe,()=>nPe],2],lOe=[3,Ie,v2e,0,[EIe,IX,jX,gNe],[0,0,0,0]],cOe=[3,Ie,S2e,0,[NX,QX],[1,1]],uOe=[3,Ie,y2e,0,[ou,Js,oh,lh],[0,0,0,2],3],dOe=[3,Ie,w2e,0,[QNe],[()=>rPe],1],pOe=[3,Ie,E2e,0,[GIe,CIe,ZIe,Fke],[64,[()=>dPe,0],[()=>uPe,0],0]],hOe=[3,Ie,x2e,0,[GNe,tIe,aDe,mNe,fNe,Zke,eIe,Bke,$ke],[1,1,1,1,1,1,1,1,1],6],fOe=[3,Ie,C2e,0,[rIe,VIe],[()=>JOe,()=>ePe],2],cZ=[3,Ie,A2e,0,[ym,lu,Za],[0,[()=>gZ,0],[()=>n4,0]],2],mOe=[3,Ie,R2e,0,[lu,Za],[[()=>gZ,0],[()=>n4,0]]],gOe=[3,Ie,k2e,0,[ym],[0],1],_Oe=[3,Ie,I2e,0,[HIe,HNe,WNe,ENe],[1,1,1,64]],vOe=[3,Ie,O2e,0,[CNe,ou,CX],[0,0,0],1],bOe=[3,Ie,P2e,0,[$X,Rv],[0,[()=>qOe,0]],2],yOe=[3,Ie,F2e,0,[$X],[0],1],EOe=[3,Ie,B2e,0,[_Ne,Lke],[0,15],1],SOe=[3,Ie,W2e,0,[BNe],[[()=>TOe,0]]],TOe=[3,Ie,z2e,0,[Js,NNe],[0,[()=>xPe,0]],2],uZ=[3,Ie,H2e,0,[UIe],[0]],wOe=[3,Ie,V2e,0,[kIe],[0]],xOe=[3,Ie,J2e,8,[ha,VX],[0,0],1],bw=[3,Ie,nke,0,[JNe,qke],[0,0],1],dZ=[3,Ie,ike,0,[lu,e4,Rv,QM],[0,0,()=>aPe,()=>sZ],3],COe=[3,Ie,ake,0,[ha],[0],1],AOe=[3,Ie,oke,0,[vNe,Iv,pw],[1,1,1]],pZ=[3,Ie,lke,0,[Js],[0],1],ROe=[3,Ie,cke,0,[ou],[0],1],kOe=[3,Ie,uke,0,[ou],[0],1],IOe=[3,Ie,Tke,0,[OX,tNe,qNe,nIe,iIe,Qke],[1,1,1,1,1,()=>BOe],3],NOe=[3,Ie,pke,0,[YNe,LNe],[()=>cPe,()=>NPe],1],DOe=[3,Ie,gke,0,[gw,Rv,YX,Js],[0,[()=>lPe,0],0,0],2],OOe=[3,Ie,bke,0,[gw,Js,YX],[0,0,0],1],POe=[3,Ie,Ske,0,[ou,IIe,CX,INe],[0,()=>DPe,0,2],2],MOe=[3,Ie,wke,0,[gw,ou,DX,Js],[0,0,15,0],3],LOe=[3,Ie,xke,0,[DX],[0],1],FOe=[3,Ie,Cke,0,[gw,ou,Js],[0,0,0],2],hZ=[3,Ie,kke,0,[ym,lu],[0,()=>MPe],2],UOe=[3,Ie,Dke,0,[eDe,pIe],[0,0]],BOe=[1,Ie,QAe,0,()=>yDe],$Oe=[1,Ie,JAe,0,()=>mPe],GOe=[1,Ie,hRe,0,()=>EDe],WOe=[1,Ie,aRe,0,()=>gPe],zOe=[1,Ie,sRe,0,()=>wDe],qOe=[1,Ie,BAe,0,[()=>_Pe,0]],HOe=[1,Ie,mRe,0,()=>EPe],VOe=[1,Ie,TRe,0,[()=>lZ,0]],YOe=[1,Ie,CRe,0,[()=>JS,0]],KOe=[1,Ie,RRe,0,[()=>TPe,0]],t8=[1,Ie,DRe,0,[()=>FDe,0]],r4=[1,Ie,FRe,0,()=>GDe],d_=[1,Ie,$Re,0,[()=>zDe,0]],QOe=[1,Ie,YRe,0,[()=>Nv,0]],jOe=[1,Ie,QRe,0,[()=>VDe,0]],XOe=[1,Ie,JRe,0,()=>KDe],ZOe=[1,Ie,t2e,0,()=>jDe],JOe=[1,Ie,l2e,0,()=>tOe],ePe=[1,Ie,h2e,0,()=>iOe],tPe=[1,Ie,m2e,0,()=>aOe],nPe=[1,Ie,_2e,0,()=>sOe],rPe=[1,Ie,T2e,0,()=>uOe],iPe=[1,Ie,G2e,0,[()=>bOe,0]],aPe=[1,Ie,ske,0,()=>COe],sPe=[1,Ie,eke,0,[()=>kPe,0]],oPe=[1,Ie,_ke,0,()=>OPe],lPe=[1,Ie,yke,0,[()=>PPe,0]],cPe=[1,Ie,Ake,0,()=>IPe],uPe=[2,Ie,wRe,0,[0,0],[()=>VOe,0]],dPe=[2,Ie,xRe,0,[0,0],[()=>lZ,0]],pPe=[2,Ie,Y2e,8,0,()=>CPe],hPe=[2,Ie,X2e,8,0,0],fPe=[4,Ie,MAe,8,[Av,mw],[21,()=>bw]],mPe=[4,Ie,ZAe,0,[ha],[0]],fZ=[4,Ie,eRe,0,[rDe,lIe,uIe,cIe,bNe],[()=>UOe,()=>ODe,()=>MDe,()=>PDe,()=>AOe]],gPe=[4,Ie,rRe,0,[ha],[0]],_Pe=[4,Ie,HAe,0,[ha,kv,AX,ZX,Wke,JM,ZM,kX,KM,UX,Kke,zX],[0,[()=>cZ,0],()=>oZ,()=>hZ,[()=>vDe,0],()=>MOe,[()=>DOe,0],[()=>mZ,0],()=>t4,[()=>APe,0],()=>SDe,()=>dZ]],vPe=[4,Ie,$Ae,0,[ha,JM,ZM,UX,aIe,kv],[0,()=>LOe,()=>oPe,[()=>RPe,0],()=>TDe,[()=>mOe,0]]],bPe=[4,Ie,WAe,0,[JM,ZM,kv],[()=>FOe,()=>OOe,()=>gOe]],yPe=[4,Ie,cRe,{[kNe]:1},[WIe,Vke,Hke,Yke,qIe,QIe,NIe,zIe,tDe,UNe,TNe],[()=>yOe,()=>CDe,[()=>xDe,0],()=>ADe,()=>EOe,[()=>RDe,0],[()=>eZ,0],[()=>tZ,0],[()=>iZ,0],[()=>rZ,0],[()=>nZ,0]]],EPe=[4,Ie,gRe,0,[ha],[0]],SPe=[4,Ie,yRe,0,[Av,mw,ha,Rv],[21,()=>bw,0,()=>HOe]],TPe=[4,Ie,ARe,0,[nDe,MIe,wNe,PIe,ONe,FNe,XIe],[[()=>YDe,0],[()=>UDe,0],[()=>WDe,0],[()=>LDe,0],[()=>HDe,0],()=>qDe,()=>BDe]],mZ=[4,Ie,XRe,0,[ha,kv],[()=>JDe,[()=>ZDe,0]]],wPe=[4,Ie,i2e,8,[Av],[21]],gZ=[4,Ie,N2e,8,[Av,mw],[21,()=>bw]],xPe=[4,Ie,q2e,8,[LIe],[()=>vOe]],CPe=[4,Ie,K2e,0,[ha],[0]],APe=[4,Ie,Q2e,8,[dNe,BX],[[()=>xOe,0],21]],RPe=[4,Ie,j2e,8,[ha,BX,VX],[0,21,0]],kPe=[4,Ie,tke,0,[ha,kX,KM],[0,[()=>mZ,0],()=>t4]],IPe=[4,Ie,Rke,0,[zNe,SNe,KM],[()=>POe,()=>kOe,()=>t4]],NPe=[4,Ie,hke,0,[zke,Gke,KNe],[()=>bDe,()=>gDe,()=>ROe]],DPe=[4,Ie,mke,0,[XM],[15]],OPe=[4,Ie,vke,0,[ha,XM],[0,15]],PPe=[4,Ie,Eke,0,[XM,ha,kv,AX,ZX,zX],[15,0,[()=>cZ,0],()=>oZ,()=>hZ,()=>dZ]],MPe=[4,Ie,Nke,0,[Av,mw],[21,()=>bw]],LPe=[9,Ie,nRe,{[xIe]:["POST","/model/{modelId}/converse-stream",200]},()=>IDe,()=>NDe];const FPe=n=>({apiVersion:"2023-09-30",base64Decoder:n?.base64Decoder??Ap,base64Encoder:n?.base64Encoder??kp,disableHostPrefix:n?.disableHostPrefix??!1,endpointProvider:n?.endpointProvider??NAe,extensions:n?.extensions??[],httpAuthSchemeProvider:n?.httpAuthSchemeProvider??rAe,httpAuthSchemes:n?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new uwe},{schemeId:"smithy.api#httpBearerAuth",identityProvider:e=>e.getIdentityProvider("smithy.api#httpBearerAuth"),signer:new RTe}],logger:n?.logger??new Pj,protocol:n?.protocol??oxe,protocolSettings:n?.protocolSettings??{defaultNamespace:"com.amazonaws.bedrockruntime",errorTypeRegistries:fDe,version:"2023-09-30",serviceTarget:"AmazonBedrockFrontendService"},serviceId:n?.serviceId??"Bedrock Runtime",urlParser:n?.urlParser??QS,utf8Decoder:n?.utf8Decoder??Rp,utf8Encoder:n?.utf8Encoder??vm}),UPe=n=>{const e=CAe(n),t=()=>e().then(qwe),r=FPe(n);return{...r,...n,runtime:"browser",defaultsMode:e,bodyLengthChecker:n?.bodyLengthChecker??Gwe,credentialDefaultProvider:n?.credentialDefaultProvider??(i=>()=>Promise.reject(new Error("Credential is missing"))),defaultUserAgentProvider:n?.defaultUserAgentProvider??TAe({serviceId:r.serviceId,clientVersion:lAe.version}),eventStreamPayloadHandlerProvider:n?.eventStreamPayloadHandlerProvider??rCe,eventStreamSerdeProvider:n?.eventStreamSerdeProvider??Yxe,maxAttempts:n?.maxAttempts??ZS,region:n?.region??wAe("Region is missing"),requestHandler:NM.create(n?.requestHandler??t,a_.create(t)),retryMode:n?.retryMode??(async()=>(await t()).retryMode||CCe),sha256:n?.sha256??SAe,streamCollector:n?.streamCollector??nj,useDualstackEndpoint:n?.useDualstackEndpoint??(()=>Promise.resolve(iCe)),useFipsEndpoint:n?.useFipsEndpoint??(()=>Promise.resolve(aCe))}},BPe=n=>({setRegion(e){n.region=e},region(){return n.region}}),$Pe=n=>({region:n.region()}),GPe=n=>{const e=n.httpAuthSchemes;let t=n.httpAuthSchemeProvider,r=n.credentials,i=n.token;return{setHttpAuthScheme(a){const s=e.findIndex(o=>o.schemeId===a.schemeId);s===-1?e.push(a):e.splice(s,1,a)},httpAuthSchemes(){return e},setHttpAuthSchemeProvider(a){t=a},httpAuthSchemeProvider(){return t},setCredentials(a){r=a},credentials(){return r},setToken(a){i=a},token(){return i}}},WPe=n=>({httpAuthSchemes:n.httpAuthSchemes(),httpAuthSchemeProvider:n.httpAuthSchemeProvider(),credentials:n.credentials(),token:n.token()}),zPe=(n,e)=>{const t=Object.assign(BPe(n),Qwe(n),n1e(n),GPe(n));return e.forEach(r=>r.configure(t)),Object.assign(n,$Pe(t),jwe(t),r1e(t),WPe(t))};class qPe extends Wwe{config;constructor(...[e]){const t=UPe(e||{});super(t),this.initConfig=t;const r=aAe(t),i=OTe(r),a=HCe(i),s=lCe(a),o=s,l=xCe(o),c=cCe(l),u=iAe(c),d=t1e(u),p=Jxe(d),h=zPe(p,e?.extensions||[]);this.config=h,this.middlewareStack.use(F1e(this.config)),this.middlewareStack.use(gxe(this.config)),this.middlewareStack.use(ZCe(this.config)),this.middlewareStack.use(pCe(this.config)),this.middlewareStack.use(o1e(this.config)),this.middlewareStack.use(u1e(this.config)),this.middlewareStack.use(h1e(this.config)),this.middlewareStack.use(v1e(this.config,{httpAuthSchemeParametersProvider:eAe,identityProviderConfigProvider:async f=>new ATe({"aws.auth#sigv4":f.credentials,"smithy.api#httpBearerAuth":f.token})})),this.middlewareStack.use(w1e(this.config))}destroy(){super.destroy()}}class HPe extends Dj.classBuilder().ep(sAe).m(function(e,t,r,i){return[wCe(r,e.getEndpointParameterInstructions())]}).s("AmazonBedrockFrontendService","ConverseStream",{eventStream:{output:!0}}).n("BedrockRuntimeClient","ConverseStreamCommand").sc(LPe).build(){}const _Z={ONE_HOUR:"1h"},vZ={DEFAULT:"default"},zb={GIF:"gif",JPEG:"jpeg",PNG:"png",WEBP:"webp"},qb={ERROR:"error",SUCCESS:"success"},Y0={ASSISTANT:"assistant",USER:"user"},f0={END_TURN:"end_turn",MAX_TOKENS:"max_tokens",MODEL_CONTEXT_WINDOW_EXCEEDED:"model_context_window_exceeded",STOP_SEQUENCE:"stop_sequence",TOOL_USE:"tool_use"};var Ho={};const K0=(n,e,t={})=>{const r=new nu;return(async()=>{const i={role:"assistant",content:[],api:"bedrock-converse-stream",provider:n.provider,model:n.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()},a=i.content,s={region:t.region,profile:t.profile};if(typeof process<"u"&&(process.versions?.node||process.versions?.bun)){if(s.region=s.region||Ho.AWS_REGION||Ho.AWS_DEFAULT_REGION,Ho.AWS_BEDROCK_SKIP_AUTH==="1"&&(s.credentials={accessKeyId:"dummy-access-key",secretAccessKey:"dummy-secret-key"}),Ho.HTTP_PROXY||Ho.HTTPS_PROXY||Ho.NO_PROXY||Ho.http_proxy||Ho.https_proxy||Ho.no_proxy){const o=await _s(()=>import("./index-CJEeBmBj.js"),__vite__mapDeps([0,1])),l=await _s(()=>import("./index-woI4agCy.js").then(u=>u.i),__vite__mapDeps([2,1])),c=new l.ProxyAgent;s.requestHandler=new o.NodeHttpHandler({httpAgent:c,httpsAgent:c})}else if(Ho.AWS_BEDROCK_FORCE_HTTP1==="1"){const o=await _s(()=>import("./index-CJEeBmBj.js"),__vite__mapDeps([0,1]));s.requestHandler=new o.NodeHttpHandler}}s.region=s.region||"us-east-1";try{const o=new qPe(s),l=ZPe(t.cacheRetention),c={modelId:n.id,messages:nMe(e,n,l),system:eMe(e.systemPrompt,n,l),inferenceConfig:{maxTokens:t.maxTokens,temperature:t.temperature},toolConfig:rMe(e.tools,t.toolChoice),additionalModelRequestFields:aMe(n,t)};t?.onPayload?.(c);const u=new HPe(c),d=await o.send(u,{abortSignal:t.signal});for await(const p of d.stream)if(p.messageStart){if(p.messageStart.role!==Y0.ASSISTANT)throw new Error("Unexpected assistant message start but got user message start instead");r.push({type:"start",partial:i})}else if(p.contentBlockStart)YPe(p.contentBlockStart,a,i,r);else if(p.contentBlockDelta)KPe(p.contentBlockDelta,a,i,r);else if(p.contentBlockStop)jPe(p.contentBlockStop,a,i,r);else if(p.messageStop)i.stopReason=iMe(p.messageStop.stopReason);else if(p.metadata)QPe(p.metadata,n,i);else{if(p.internalServerException)throw new Error(`Internal server error: ${p.internalServerException.message}`);if(p.modelStreamErrorException)throw new Error(`Model stream error: ${p.modelStreamErrorException.message}`);if(p.validationException)throw new Error(`Validation error: ${p.validationException.message}`);if(p.throttlingException)throw new Error(`Throttling error: ${p.throttlingException.message}`);if(p.serviceUnavailableException)throw new Error(`Service unavailable: ${p.serviceUnavailableException.message}`)}if(t.signal?.aborted)throw new Error("Request was aborted");if(i.stopReason==="error"||i.stopReason==="aborted")throw new Error("An unknown error occurred");r.push({type:"done",reason:i.stopReason,message:i}),r.end()}catch(o){for(const l of i.content)delete l.index,delete l.partialJson;i.stopReason=t.signal?.aborted?"aborted":"error",i.errorMessage=o instanceof Error?o.message:JSON.stringify(o),r.push({type:"error",reason:i.stopReason,error:i}),r.end()}})(),r},VPe=(n,e,t)=>{const r=ru(n,t,void 0);if(!t?.reasoning)return K0(n,e,{...r,reasoning:void 0});if(n.id.includes("anthropic.claude")||n.id.includes("anthropic/claude")){if(XN(n.id))return K0(n,e,{...r,reasoning:t.reasoning,thinkingBudgets:t.thinkingBudgets});const i=_Y(r.maxTokens||0,n.maxTokens,t.reasoning,t.thinkingBudgets);return K0(n,e,{...r,maxTokens:i.maxTokens,reasoning:t.reasoning,thinkingBudgets:{...t.thinkingBudgets||{},[iu(t.reasoning)]:i.thinkingBudget}})}return K0(n,e,{...r,reasoning:t.reasoning,thinkingBudgets:t.thinkingBudgets})};function YPe(n,e,t,r){const i=n.contentBlockIndex,a=n.start;if(a?.toolUse){const s={type:"toolCall",id:a.toolUse.toolUseId||"",name:a.toolUse.name||"",arguments:{},partialJson:"",index:i};t.content.push(s),r.push({type:"toolcall_start",contentIndex:e.length-1,partial:t})}}function KPe(n,e,t,r){const i=n.contentBlockIndex,a=n.delta;let s=e.findIndex(l=>l.index===i),o=e[s];if(a?.text!==void 0){if(!o){const l={type:"text",text:"",index:i};t.content.push(l),s=e.length-1,o=e[s],r.push({type:"text_start",contentIndex:s,partial:t})}o.type==="text"&&(o.text+=a.text,r.push({type:"text_delta",contentIndex:s,delta:a.text,partial:t}))}else if(a?.toolUse&&o?.type==="toolCall")o.partialJson=(o.partialJson||"")+(a.toolUse.input||""),o.arguments=Hl(o.partialJson),r.push({type:"toolcall_delta",contentIndex:s,delta:a.toolUse.input||"",partial:t});else if(a?.reasoningContent){let l=o,c=s;if(!l){const u={type:"thinking",thinking:"",thinkingSignature:"",index:i};t.content.push(u),c=e.length-1,l=e[c],r.push({type:"thinking_start",contentIndex:c,partial:t})}l?.type==="thinking"&&(a.reasoningContent.text&&(l.thinking+=a.reasoningContent.text,r.push({type:"thinking_delta",contentIndex:c,delta:a.reasoningContent.text,partial:t})),a.reasoningContent.signature&&(l.thinkingSignature=(l.thinkingSignature||"")+a.reasoningContent.signature))}}function QPe(n,e,t){n.usage&&(t.usage.input=n.usage.inputTokens||0,t.usage.output=n.usage.outputTokens||0,t.usage.cacheRead=n.usage.cacheReadInputTokens||0,t.usage.cacheWrite=n.usage.cacheWriteInputTokens||0,t.usage.totalTokens=n.usage.totalTokens||t.usage.input+t.usage.output,Yu(e,t.usage))}function jPe(n,e,t,r){const i=e.findIndex(s=>s.index===n.contentBlockIndex),a=e[i];if(a)switch(delete a.index,a.type){case"text":r.push({type:"text_end",contentIndex:i,content:a.text,partial:t});break;case"thinking":r.push({type:"thinking_end",contentIndex:i,content:a.thinking,partial:t});break;case"toolCall":a.arguments=Hl(a.partialJson),delete a.partialJson,r.push({type:"toolcall_end",contentIndex:i,toolCall:a,partial:t});break}}function XN(n){return n.includes("opus-4-6")||n.includes("opus-4.6")||n.includes("sonnet-4-6")||n.includes("sonnet-4.6")}function XPe(n,e){switch(n){case"minimal":case"low":return"low";case"medium":return"medium";case"high":return"high";case"xhigh":return e.includes("opus-4-6")||e.includes("opus-4.6")?"max":"high";default:return"high"}}function ZPe(n){return n||(typeof process<"u"&&Ho.PI_CACHE_RETENTION==="long"?"long":"short")}function bZ(n){if(n.cost.cacheRead||n.cost.cacheWrite)return!0;const e=n.id.toLowerCase();return!!(e.includes("claude")&&(e.includes("-4-")||e.includes("-4."))||e.includes("claude-3-7-sonnet")||e.includes("claude-3-5-haiku"))}function JPe(n){const e=n.id.toLowerCase();return e.includes("anthropic.claude")||e.includes("anthropic/claude")}function eMe(n,e,t){if(!n)return;const r=[{text:_n(n)}];return t!=="none"&&bZ(e)&&r.push({cachePoint:{type:vZ.DEFAULT,...t==="long"?{ttl:_Z.ONE_HOUR}:{}}}),r}function tMe(n){const e=n.replace(/[^a-zA-Z0-9_-]/g,"_");return e.length>64?e.slice(0,64):e}function nMe(n,e,t){const r=[],i=Sv(n.messages,e,tMe);for(let a=0;a<i.length;a++){const s=i[a];switch(s.role){case"user":r.push({role:Y0.USER,content:typeof s.content=="string"?[{text:_n(s.content)}]:s.content.map(o=>{switch(o.type){case"text":return{text:_n(o.text)};case"image":return{image:gC(o.mimeType,o.data)};default:throw new Error("Unknown user content type")}})});break;case"assistant":{if(s.content.length===0)continue;const o=[];for(const l of s.content)switch(l.type){case"text":if(l.text.trim().length===0)continue;o.push({text:_n(l.text)});break;case"toolCall":o.push({toolUse:{toolUseId:l.id,name:l.name,input:l.arguments}});break;case"thinking":if(l.thinking.trim().length===0)continue;JPe(e)?o.push({reasoningContent:{reasoningText:{text:_n(l.thinking),signature:l.thinkingSignature}}}):o.push({reasoningContent:{reasoningText:{text:_n(l.thinking)}}});break;default:throw new Error("Unknown assistant content type")}if(o.length===0)continue;r.push({role:Y0.ASSISTANT,content:o});break}case"toolResult":{const o=[];o.push({toolResult:{toolUseId:s.toolCallId,content:s.content.map(c=>c.type==="image"?{image:gC(c.mimeType,c.data)}:{text:_n(c.text)}),status:s.isError?qb.ERROR:qb.SUCCESS}});let l=a+1;for(;l<i.length&&i[l].role==="toolResult";){const c=i[l];o.push({toolResult:{toolUseId:c.toolCallId,content:c.content.map(u=>u.type==="image"?{image:gC(u.mimeType,u.data)}:{text:_n(u.text)}),status:c.isError?qb.ERROR:qb.SUCCESS}}),l++}a=l-1,r.push({role:Y0.USER,content:o});break}default:throw new Error("Unknown message role")}}if(t!=="none"&&bZ(e)&&r.length>0){const a=r[r.length-1];a.role===Y0.USER&&a.content&&a.content.push({cachePoint:{type:vZ.DEFAULT,...t==="long"?{ttl:_Z.ONE_HOUR}:{}}})}return r}function rMe(n,e){if(!n?.length||e==="none")return;const t=n.map(i=>({toolSpec:{name:i.name,description:i.description,inputSchema:{json:i.parameters}}}));let r;switch(e){case"auto":r={auto:{}};break;case"any":r={any:{}};break;default:e?.type==="tool"&&(r={tool:{name:e.name}})}return{tools:t,toolChoice:r}}function iMe(n){switch(n){case f0.END_TURN:case f0.STOP_SEQUENCE:return"stop";case f0.MAX_TOKENS:case f0.MODEL_CONTEXT_WINDOW_EXCEEDED:return"length";case f0.TOOL_USE:return"toolUse";default:return"error"}}function aMe(n,e){if(!(!e.reasoning||!n.reasoning)&&(n.id.includes("anthropic.claude")||n.id.includes("anthropic/claude"))){const t=XN(n.id)?{thinking:{type:"adaptive"},output_config:{effort:XPe(e.reasoning,n.id)}}:(()=>{const r={minimal:1024,low:2048,medium:8192,high:16384,xhigh:16384},i=e.reasoning==="xhigh"?"high":e.reasoning;return{thinking:{type:"enabled",budget_tokens:e.thinkingBudgets?.[i]??r[e.reasoning]}}})();return!XN(n.id)&&(e.interleavedThinking??!0)&&(t.anthropic_beta=["interleaved-thinking-2025-05-14"]),t}}function gC(n,e){let t;switch(n){case"image/jpeg":case"image/jpg":t=zb.JPEG;break;case"image/png":t=zb.PNG;break;case"image/gif":t=zb.GIF;break;case"image/webp":t=zb.WEBP;break;default:throw new Error(`Unknown image type: ${n}`)}const r=atob(e),i=new Uint8Array(r.length);for(let a=0;a<r.length;a++)i[a]=r.charCodeAt(a);return{source:{bytes:i},format:t}}let Q0=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&_s(()=>import("./_node-stub_node_os-TTKJha15.js").then(n=>n._),[]).then(n=>{Q0=n});const sMe="https://chatgpt.com/backend-api",oMe="https://api.openai.com/auth",_C=3,n8=1e3,lMe=new Set(["openai","openai-codex","opencode"]),cMe=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function uMe(n,e){return n===429||n===500||n===502||n===503||n===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(e)}function r8(n,e){return new Promise((t,r)=>{if(e?.aborted){r(new Error("Request was aborted"));return}const i=setTimeout(t,n);e?.addEventListener("abort",()=>{clearTimeout(i),r(new Error("Request was aborted"))})})}const yZ=(n,e,t)=>{const r=new nu;return(async()=>{const i={role:"assistant",content:[],api:"openai-codex-responses",provider:n.provider,model:n.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{const a=t?.apiKey||Mo(n.provider)||"";if(!a)throw new Error(`No API key for provider: ${n.provider}`);const s=RMe(a),o=pMe(n,e,t);t?.onPayload?.(o);const l=kMe(n.headers,t?.headers,s,a,t?.sessionId),c=JSON.stringify(o),u=t?.transport||"sse";if(u!=="sse"){let h=!1;try{if(await CMe(fMe(n.baseUrl),o,l,i,r,n,()=>{h=!0},t),t?.signal?.aborted)throw new Error("Request was aborted");r.push({type:"done",reason:i.stopReason,message:i}),r.end();return}catch(f){if(u==="websocket"||h)throw f}}let d,p;for(let h=0;h<=_C;h++){if(t?.signal?.aborted)throw new Error("Request was aborted");try{if(d=await fetch(EZ(n.baseUrl),{method:"POST",headers:l,body:c,signal:t?.signal}),d.ok)break;const f=await d.text();if(h<_C&&uMe(d.status,f)){const _=n8*2**h;await r8(_,t?.signal);continue}const m=new Response(f,{status:d.status,statusText:d.statusText}),g=await AMe(m);throw new Error(g.friendlyMessage||g.message)}catch(f){if(f instanceof Error&&(f.name==="AbortError"||f.message==="Request was aborted"))throw new Error("Request was aborted");if(p=f instanceof Error?f:new Error(String(f)),h<_C&&!p.message.includes("usage limit")){const m=n8*2**h;await r8(m,t?.signal);continue}throw p}}if(!d?.ok)throw p??new Error("Failed after retries");if(!d.body)throw new Error("No response body");if(r.push({type:"start",partial:i}),await mMe(d,i,r,n),t?.signal?.aborted)throw new Error("Request was aborted");r.push({type:"done",reason:i.stopReason,message:i}),r.end()}catch(a){i.stopReason=t?.signal?.aborted?"aborted":"error",i.errorMessage=a instanceof Error?a.message:String(a),r.push({type:"error",reason:i.stopReason,error:i}),r.end()}})(),r},dMe=(n,e,t)=>{const r=t?.apiKey||Mo(n.provider);if(!r)throw new Error(`No API key for provider: ${n.provider}`);const i=ru(n,t,r),a=WT(n)?t?.reasoning:iu(t?.reasoning);return yZ(n,e,{...i,reasoningEffort:a})};function pMe(n,e,t){const r=rM(n,e,lMe,{includeSystemPrompt:!1}),i={model:n.id,store:!1,stream:!0,instructions:e.systemPrompt,input:r,text:{verbosity:t?.textVerbosity||"medium"},include:["reasoning.encrypted_content"],prompt_cache_key:t?.sessionId,tool_choice:"auto",parallel_tool_calls:!0};return t?.temperature!==void 0&&(i.temperature=t.temperature),e.tools&&(i.tools=iM(e.tools,{strict:null})),t?.reasoningEffort!==void 0&&(i.reasoning={effort:hMe(n.id,t.reasoningEffort),summary:t.reasoningSummary??"auto"}),i}function hMe(n,e){const t=n.includes("/")?n.split("/").pop():n;return(t.startsWith("gpt-5.2")||t.startsWith("gpt-5.3"))&&e==="minimal"?"low":t==="gpt-5.1"&&e==="xhigh"?"high":t==="gpt-5.1-codex-mini"?e==="high"||e==="xhigh"?"high":"medium":e}function EZ(n){const t=(n&&n.trim().length>0?n:sMe).replace(/\/+$/,"");return t.endsWith("/codex/responses")?t:t.endsWith("/codex")?`${t}/responses`:`${t}/codex/responses`}function fMe(n){const e=new URL(EZ(n));return e.protocol==="https:"&&(e.protocol="wss:"),e.protocol==="http:"&&(e.protocol="ws:"),e.toString()}async function mMe(n,e,t,r){await ew(SZ(_Me(n)),e,t,r)}async function*SZ(n){for await(const e of n){const t=typeof e.type=="string"?e.type:void 0;if(t){if(t==="error"){const r=e.code||"",i=e.message||"";throw new Error(`Codex error: ${i||r||JSON.stringify(e)}`)}if(t==="response.failed"){const r=e.response?.error?.message;throw new Error(r||"Codex response failed")}if(t==="response.done"||t==="response.completed"){const r=e.response,i=r&&{...r,status:gMe(r.status)};yield{...e,type:"response.completed",response:i};continue}yield e}}}function gMe(n){if(typeof n=="string")return cMe.has(n)?n:void 0}async function*_Me(n){if(!n.body)return;const e=n.body.getReader(),t=new TextDecoder;let r="";for(;;){const{done:i,value:a}=await e.read();if(i)break;r+=t.decode(a,{stream:!0});let s=r.indexOf(`
|
|
141
141
|
|
|
142
142
|
`);for(;s!==-1;){const o=r.slice(0,s);r=r.slice(s+2);const l=o.split(`
|
|
143
143
|
`).filter(c=>c.startsWith("data:")).map(c=>c.slice(5).trim());if(l.length>0){const c=l.join(`
|
|
144
144
|
`).trim();if(c&&c!=="[DONE]")try{yield JSON.parse(c)}catch{}}s=r.indexOf(`
|
|
145
145
|
|
|
146
|
-
`)}}}const vMe="responses_websockets=2026-02-06",bMe=300*1e3,Vd=new Map;function yMe(){const n=globalThis.WebSocket;return typeof n!="function"?null:n}function EMe(n){const e={};for(const[t,r]of n.entries())e[t]=r;return e}function SMe(n){const e=n.readyState;return typeof e=="number"?e:void 0}function Hb(n){const e=SMe(n);return e===void 0||e===1}function Yd(n,e=1e3,t="done"){try{n.close(e,t)}catch{}}function i8(n,e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{e.busy||(Yd(e.socket,1e3,"idle_timeout"),Vd.delete(n))},bMe)}async function vC(n,e,t){const r=yMe();if(!r)throw new Error("WebSocket transport is not available in this runtime");const i=EMe(e);return i["OpenAI-Beta"]=vMe,new Promise((a,s)=>{let o=!1,l;try{l=new r(n,{headers:i})}catch(f){s(f instanceof Error?f:new Error(String(f)));return}const c=()=>{o||(o=!0,h(),a(l))},u=f=>{o||(o=!0,h(),s(TZ(f)))},d=f=>{o||(o=!0,h(),s(wZ(f)))},p=()=>{o||(o=!0,h(),l.close(1e3,"aborted"),s(new Error("Request was aborted")))},h=()=>{l.removeEventListener("open",c),l.removeEventListener("error",u),l.removeEventListener("close",d),t?.removeEventListener("abort",p)};l.addEventListener("open",c),l.addEventListener("error",u),l.addEventListener("close",d),t?.addEventListener("abort",p)})}async function TMe(n,e,t,r){if(!t){const o=await vC(n,e,r);return{socket:o,release:({keep:l}={})=>{if(l===!1){Yd(o);return}Yd(o)}}}const i=Vd.get(t);if(i){if(i.idleTimer&&(clearTimeout(i.idleTimer),i.idleTimer=void 0),!i.busy&&Hb(i.socket))return i.busy=!0,{socket:i.socket,release:({keep:o}={})=>{if(!o||!Hb(i.socket)){Yd(i.socket),Vd.delete(t);return}i.busy=!1,i8(t,i)}};if(i.busy){const o=await vC(n,e,r);return{socket:o,release:()=>{Yd(o)}}}Hb(i.socket)||(Yd(i.socket),Vd.delete(t))}const a=await vC(n,e,r),s={socket:a,busy:!0};return Vd.set(t,s),{socket:a,release:({keep:o}={})=>{if(!o||!Hb(s.socket)){Yd(s.socket),s.idleTimer&&clearTimeout(s.idleTimer),Vd.get(t)===s&&Vd.delete(t);return}s.busy=!1,i8(t,s)}}}function TZ(n){if(n&&typeof n=="object"&&"message"in n){const e=n.message;if(typeof e=="string"&&e.length>0)return new Error(e)}return new Error("WebSocket error")}function wZ(n){if(n&&typeof n=="object"){const e="code"in n?n.code:void 0,t="reason"in n?n.reason:void 0,r=typeof e=="number"?` ${e}`:"",i=typeof t=="string"&&t.length>0?` ${t}`:"";return new Error(`WebSocket closed${r}${i}`.trim())}return new Error("WebSocket closed")}async function wMe(n){if(typeof n=="string")return n;if(n instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(n));if(ArrayBuffer.isView(n)){const e=n;return new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}if(n&&typeof n=="object"&&"arrayBuffer"in n){const t=await n.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}async function*xMe(n,e){const t=[];let r=null,i=!1,a=null,s=!1;const o=()=>{if(!r)return;const p=r;r=null,p()},l=p=>{(async()=>{if(!p||typeof p!="object"||!("data"in p))return;const h=await wMe(p.data);if(h)try{const f=JSON.parse(h),m=typeof f.type=="string"?f.type:"";(m==="response.completed"||m==="response.done")&&(s=!0,i=!0),t.push(f),o()}catch{}})()},c=p=>{a=TZ(p),i=!0,o()},u=p=>{if(s){i=!0,o();return}a||(a=wZ(p)),i=!0,o()},d=()=>{a=new Error("Request was aborted"),i=!0,o()};n.addEventListener("message",l),n.addEventListener("error",c),n.addEventListener("close",u),e?.addEventListener("abort",d);try{for(;;){if(e?.aborted)throw new Error("Request was aborted");if(t.length>0){yield t.shift();continue}if(i)break;await new Promise(p=>{r=p})}if(a)throw a;if(!s)throw new Error("WebSocket stream closed before response.completed")}finally{n.removeEventListener("message",l),n.removeEventListener("error",c),n.removeEventListener("close",u),e?.removeEventListener("abort",d)}}async function CMe(n,e,t,r,i,a,s,o){const{socket:l,release:c}=await TMe(n,t,o?.sessionId,o?.signal);let u=!0;try{l.send(JSON.stringify({type:"response.create",...e})),s(),i.push({type:"start",partial:r}),await ew(SZ(xMe(l,o?.signal)),r,i,a),o?.signal?.aborted&&(u=!1)}catch(d){throw u=!1,d}finally{c({keep:u})}}async function AMe(n){const e=await n.text();let t=e||n.statusText||"Request failed",r;try{const a=JSON.parse(e)?.error;if(a){const s=a.code||a.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(s)||n.status===429){const o=a.plan_type?` (${a.plan_type.toLowerCase()} plan)`:"",l=a.resets_at?Math.max(0,Math.round((a.resets_at*1e3-Date.now())/6e4)):void 0,c=l!==void 0?` Try again in ~${l} min.`:"";r=`You have hit your ChatGPT usage limit${o}.${c}`.trim()}t=a.message||r||t}}catch{}return{message:t,friendlyMessage:r}}function RMe(n){try{const e=n.split(".");if(e.length!==3)throw new Error("Invalid token");const r=JSON.parse(atob(e[1]))?.[oMe]?.chatgpt_account_id;if(!r)throw new Error("No account ID in token");return r}catch{throw new Error("Failed to extract accountId from token")}}function kMe(n,e,t,r,i){const a=new Headers(n);a.set("Authorization",`Bearer ${r}`),a.set("chatgpt-account-id",t),a.set("OpenAI-Beta","responses=experimental"),a.set("originator","pi");const s=Q0?`pi (${Q0.platform()} ${Q0.release()}; ${Q0.arch()})`:"pi (browser)";a.set("User-Agent",s),a.set("accept","text/event-stream"),a.set("content-type","application/json");for(const[o,l]of Object.entries(e||{}))a.set(o,l);return i&&a.set("session_id",i),a}function IMe(){dc({api:"anthropic-messages",stream:LE,streamSimple:rfe}),dc({api:"openai-completions",stream:ZQ,streamSimple:USe}),dc({api:"openai-responses",stream:JQ,streamSimple:jSe}),dc({api:"azure-openai-responses",stream:JK,streamSimple:Cme}),dc({api:"openai-codex-responses",stream:yZ,streamSimple:dMe}),dc({api:"google-generative-ai",stream:QE,streamSimple:iSe}),dc({api:"google-gemini-cli",stream:jE,streamSimple:SSe}),dc({api:"google-vertex",stream:XE,streamSimple:RSe}),dc({api:"bedrock-converse-stream",stream:K0,streamSimple:VPe})}IMe();typeof process<"u"&&process.versions?.node&&_s(()=>import("./index-D16nGmo3.js").then(n=>n.i),__vite__mapDeps([3,4,5,6])).then(n=>{const{EnvHttpProxyAgent:e,setGlobalDispatcher:t}=n;t(new e)});function xZ(n){const e=Ype(n);if(!e)throw new Error(`No API provider registered for api: ${n}`);return e}function NMe(n,e,t){return xZ(n.api).stream(n,e,t)}async function DMe(n,e,t){return NMe(n,e,t).result()}function ZN(n,e,t){return xZ(n.api).streamSimple(n,e,t)}function a8(n){let e="";for(const t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function yw(){const n=new Uint8Array(32);crypto.getRandomValues(n);const e=a8(n),r=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",r),a=a8(new Uint8Array(i));return{verifier:e,challenge:a}}const OMe=n=>atob(n),JN=OMe("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl"),PMe="https://claude.ai/oauth/authorize",CZ="https://console.anthropic.com/v1/oauth/token",s8="https://console.anthropic.com/oauth/code/callback",MMe="org:create_api_key user:profile user:inference";async function LMe(n,e){const{verifier:t,challenge:r}=await yw(),i=new URLSearchParams({code:"true",client_id:JN,response_type:"code",redirect_uri:s8,scope:MMe,code_challenge:r,code_challenge_method:"S256",state:t}),a=`${PMe}?${i.toString()}`;n(a);const o=(await e()).split("#"),l=o[0],c=o[1],u=await fetch(CZ,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:JN,code:l,state:c,redirect_uri:s8,code_verifier:t})});if(!u.ok){const h=await u.text();throw new Error(`Token exchange failed: ${h}`)}const d=await u.json(),p=Date.now()+d.expires_in*1e3-300*1e3;return{refresh:d.refresh_token,access:d.access_token,expires:p}}async function FMe(n){const e=await fetch(CZ,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:JN,refresh_token:n})});if(!e.ok){const r=await e.text();throw new Error(`Anthropic token refresh failed: ${r}`)}const t=await e.json();return{refresh:t.refresh_token,access:t.access_token,expires:Date.now()+t.expires_in*1e3-300*1e3}}const UMe={id:"anthropic",name:"Anthropic (Claude Pro/Max)",async login(n){return LMe(e=>n.onAuth({url:e}),()=>n.onPrompt({message:"Paste the authorization code:"}))},async refreshToken(n){return FMe(n.refresh)},getApiKey(n){return n.access}},BMe=n=>atob(n),AZ=BMe("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),RZ={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"};function kZ(n){const e=n.trim();if(!e)return null;try{return(e.includes("://")?new URL(e):new URL(`https://${e}`)).hostname}catch{return null}}function i4(n){return{deviceCodeUrl:`https://${n}/login/device/code`,accessTokenUrl:`https://${n}/login/oauth/access_token`,copilotTokenUrl:`https://api.${n}/copilot_internal/v2/token`}}function $Me(n){const e=n.match(/proxy-ep=([^;]+)/);return e?`https://${e[1].replace(/^proxy\./,"api.")}`:null}function IZ(n,e){if(n){const t=$Me(n);if(t)return t}return e?`https://copilot-api.${e}`:"https://api.individual.githubcopilot.com"}async function a4(n,e){const t=await fetch(n,e);if(!t.ok){const r=await t.text();throw new Error(`${t.status} ${t.statusText}: ${r}`)}return t.json()}async function GMe(n){const e=i4(n),t=await a4(e.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"GitHubCopilotChat/0.35.0"},body:JSON.stringify({client_id:AZ,scope:"read:user"})});if(!t||typeof t!="object")throw new Error("Invalid device code response");const r=t.device_code,i=t.user_code,a=t.verification_uri,s=t.interval,o=t.expires_in;if(typeof r!="string"||typeof i!="string"||typeof a!="string"||typeof s!="number"||typeof o!="number")throw new Error("Invalid device code response fields");return{device_code:r,user_code:i,verification_uri:a,interval:s,expires_in:o}}function bC(n,e){return new Promise((t,r)=>{if(e?.aborted){r(new Error("Login cancelled"));return}const i=setTimeout(t,n);e?.addEventListener("abort",()=>{clearTimeout(i),r(new Error("Login cancelled"))},{once:!0})})}async function WMe(n,e,t,r,i){const a=i4(n),s=Date.now()+r*1e3;let o=Math.max(1e3,Math.floor(t*1e3));for(;Date.now()<s;){if(i?.aborted)throw new Error("Login cancelled");const l=await a4(a.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"GitHubCopilotChat/0.35.0"},body:JSON.stringify({client_id:AZ,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(l&&typeof l=="object"&&typeof l.access_token=="string")return l.access_token;if(l&&typeof l=="object"&&typeof l.error=="string"){const c=l.error;if(c==="authorization_pending"){await bC(o,i);continue}if(c==="slow_down"){o+=5e3,await bC(o,i);continue}throw new Error(`Device flow failed: ${c}`)}await bC(o,i)}throw new Error("Device flow timed out")}async function NZ(n,e){const r=i4(e||"github.com"),i=await a4(r.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${n}`,...RZ}});if(!i||typeof i!="object")throw new Error("Invalid Copilot token response");const a=i.token,s=i.expires_at;if(typeof a!="string"||typeof s!="number")throw new Error("Invalid Copilot token response fields");return{refresh:n,access:a,expires:s*1e3-300*1e3,enterpriseUrl:e}}async function zMe(n,e,t){const i=`${IZ(n,t)}/models/${e}/policy`;try{return(await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,...RZ,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})})).ok}catch{return!1}}async function qMe(n,e,t){const r=RV("github-copilot");await Promise.all(r.map(async i=>{await zMe(n,i.id,e)}))}async function HMe(n){const e=await n.onPrompt({message:"GitHub Enterprise URL/domain (blank for github.com)",placeholder:"company.ghe.com",allowEmpty:!0});if(n.signal?.aborted)throw new Error("Login cancelled");const t=e.trim(),r=kZ(e);if(t&&!r)throw new Error("Invalid GitHub Enterprise URL/domain");const i=r||"github.com",a=await GMe(i);n.onAuth(a.verification_uri,`Enter code: ${a.user_code}`);const s=await WMe(i,a.device_code,a.interval,a.expires_in,n.signal),o=await NZ(s,r??void 0);return n.onProgress?.("Enabling models..."),await qMe(o.access,r??void 0),o}const VMe={id:"github-copilot",name:"GitHub Copilot",async login(n){return HMe({onAuth:(e,t)=>n.onAuth({url:e,instructions:t}),onPrompt:n.onPrompt,onProgress:n.onProgress,signal:n.signal})},async refreshToken(n){const e=n;return NZ(e.refresh,e.enterpriseUrl)},getApiKey(n){return n.access},modifyModels(n,e){const t=e,r=t.enterpriseUrl?kZ(t.enterpriseUrl)??void 0:void 0,i=IZ(t.access,r);return n.map(a=>a.provider==="github-copilot"?{...a,baseUrl:i}:a)}};let j0=null,eD=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(eD=_s(()=>import("./_node-stub_node_http-CROXaVGJ.js").then(n=>n._),[]).then(n=>{j0=n.createServer}));const DZ=n=>atob(n),tD=DZ("MTA3MTAwNjA2MDU5MS10bWhzc2luMmgyMWxjcmUyMzV2dG9sb2poNGc0MDNlcC5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbQ=="),OZ=DZ("R09DU1BYLUs1OEZXUjQ4NkxkTEoxbUxCOHNYQzR6NnFEQWY="),o8="http://localhost:51121/oauth-callback",YMe=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/cclog","https://www.googleapis.com/auth/experimentsandconfigs"],KMe="https://accounts.google.com/o/oauth2/v2/auth",PZ="https://oauth2.googleapis.com/token",QMe="rising-fact-p41fc";async function jMe(){if(j0||(eD&&await eD,j0))return j0;throw new Error("Antigravity OAuth is only available in Node.js environments")}async function XMe(){const n=await jMe();return new Promise((e,t)=>{let r=null,i=!1;const a=n((s,o)=>{const l=new URL(s.url||"","http://localhost:51121");if(l.pathname==="/oauth-callback"){const c=l.searchParams.get("code"),u=l.searchParams.get("state"),d=l.searchParams.get("error");if(d){o.writeHead(400,{"Content-Type":"text/html"}),o.end(`<html><body><h1>Authentication Failed</h1><p>Error: ${d}</p><p>You can close this window.</p></body></html>`);return}c&&u?(o.writeHead(200,{"Content-Type":"text/html"}),o.end("<html><body><h1>Authentication Successful</h1><p>You can close this window and return to the terminal.</p></body></html>"),r={code:c,state:u}):(o.writeHead(400,{"Content-Type":"text/html"}),o.end("<html><body><h1>Authentication Failed</h1><p>Missing code or state parameter.</p></body></html>"))}else o.writeHead(404),o.end()});a.on("error",s=>{t(s)}),a.listen(51121,"127.0.0.1",()=>{e({server:a,cancelWait:()=>{i=!0},waitForCode:async()=>{const s=()=>new Promise(o=>setTimeout(o,100));for(;!r&&!i;)await s();return r}})})})}function l8(n){const e=n.trim();if(!e)return{};try{const t=new URL(e);return{code:t.searchParams.get("code")??void 0,state:t.searchParams.get("state")??void 0}}catch{return{}}}async function ZMe(n,e){const t={Authorization:`Bearer ${n}`,"Content-Type":"application/json","User-Agent":"google-api-nodejs-client/9.15.1","X-Goog-Api-Client":"google-cloud-sdk vscode_cloudshelleditor/0.1","Client-Metadata":JSON.stringify({ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"})},r=["https://cloudcode-pa.googleapis.com","https://daily-cloudcode-pa.sandbox.googleapis.com"];e?.("Checking for existing project...");for(const i of r)try{const a=await fetch(`${i}/v1internal:loadCodeAssist`,{method:"POST",headers:t,body:JSON.stringify({metadata:{ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}})});if(a.ok){const s=await a.json();if(typeof s.cloudaicompanionProject=="string"&&s.cloudaicompanionProject)return s.cloudaicompanionProject;if(s.cloudaicompanionProject&&typeof s.cloudaicompanionProject=="object"&&s.cloudaicompanionProject.id)return s.cloudaicompanionProject.id}}catch{}return e?.("Using default project..."),QMe}async function JMe(n){try{const e=await fetch("https://www.googleapis.com/oauth2/v1/userinfo?alt=json",{headers:{Authorization:`Bearer ${n}`}});if(e.ok)return(await e.json()).email}catch{}}async function e4e(n,e){const t=await fetch(PZ,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:tD,client_secret:OZ,refresh_token:n,grant_type:"refresh_token"})});if(!t.ok){const i=await t.text();throw new Error(`Antigravity token refresh failed: ${i}`)}const r=await t.json();return{refresh:r.refresh_token||n,access:r.access_token,expires:Date.now()+r.expires_in*1e3-300*1e3,projectId:e}}async function t4e(n,e,t){const{verifier:r,challenge:i}=await yw();e?.("Starting local server for OAuth callback...");const a=await XMe();let s;try{const o=new URLSearchParams({client_id:tD,response_type:"code",redirect_uri:o8,scope:YMe.join(" "),code_challenge:i,code_challenge_method:"S256",state:r,access_type:"offline",prompt:"consent"}),l=`${KMe}?${o.toString()}`;if(n({url:l,instructions:"Complete the sign-in in your browser."}),e?.("Waiting for OAuth callback..."),t){let m,g;const _=t().then(b=>{m=b,a.cancelWait()}).catch(b=>{g=b instanceof Error?b:new Error(String(b)),a.cancelWait()}),v=await a.waitForCode();if(g)throw g;if(v?.code){if(v.state!==r)throw new Error("OAuth state mismatch - possible CSRF attack");s=v.code}else if(m){const b=l8(m);if(b.state&&b.state!==r)throw new Error("OAuth state mismatch - possible CSRF attack");s=b.code}if(!s){if(await _,g)throw g;if(m){const b=l8(m);if(b.state&&b.state!==r)throw new Error("OAuth state mismatch - possible CSRF attack");s=b.code}}}else{const m=await a.waitForCode();if(m?.code){if(m.state!==r)throw new Error("OAuth state mismatch - possible CSRF attack");s=m.code}}if(!s)throw new Error("No authorization code received");e?.("Exchanging authorization code for tokens...");const c=await fetch(PZ,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:tD,client_secret:OZ,code:s,grant_type:"authorization_code",redirect_uri:o8,code_verifier:r})});if(!c.ok){const m=await c.text();throw new Error(`Token exchange failed: ${m}`)}const u=await c.json();if(!u.refresh_token)throw new Error("No refresh token received. Please try again.");e?.("Getting user info...");const d=await JMe(u.access_token),p=await ZMe(u.access_token,e),h=Date.now()+u.expires_in*1e3-300*1e3;return{refresh:u.refresh_token,access:u.access_token,expires:h,projectId:p,email:d}}finally{a.server.close()}}const n4e={id:"google-antigravity",name:"Antigravity (Gemini 3, Claude, GPT-OSS)",usesCallbackServer:!0,async login(n){return t4e(n.onAuth,n.onProgress,n.onManualCodeInput)},async refreshToken(n){const e=n;if(!e.projectId)throw new Error("Antigravity credentials missing projectId");return e4e(e.refresh,e.projectId)},getApiKey(n){const e=n;return JSON.stringify({token:e.access,projectId:e.projectId})}};var c8={};let X0=null,nD=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(nD=_s(()=>import("./_node-stub_node_http-CROXaVGJ.js").then(n=>n._),[]).then(n=>{X0=n.createServer}));const MZ=n=>atob(n),rD=MZ("NjgxMjU1ODA5Mzk1LW9vOGZ0Mm9wcmRybnA5ZTNhcWY2YXYzaG1kaWIxMzVqLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29t"),LZ=MZ("R09DU1BYLTR1SGdNUG0tMW83U2stZ2VWNkN1NWNsWEZzeGw="),u8="http://localhost:8085/oauth2callback",r4e=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile"],i4e="https://accounts.google.com/o/oauth2/v2/auth",FZ="https://oauth2.googleapis.com/token",iD="https://cloudcode-pa.googleapis.com";async function a4e(){if(X0||(nD&&await nD,X0))return X0;throw new Error("Gemini CLI OAuth is only available in Node.js environments")}async function s4e(){const n=await a4e();return new Promise((e,t)=>{let r=null,i=!1;const a=n((s,o)=>{const l=new URL(s.url||"","http://localhost:8085");if(l.pathname==="/oauth2callback"){const c=l.searchParams.get("code"),u=l.searchParams.get("state"),d=l.searchParams.get("error");if(d){o.writeHead(400,{"Content-Type":"text/html"}),o.end(`<html><body><h1>Authentication Failed</h1><p>Error: ${d}</p><p>You can close this window.</p></body></html>`);return}c&&u?(o.writeHead(200,{"Content-Type":"text/html"}),o.end("<html><body><h1>Authentication Successful</h1><p>You can close this window and return to the terminal.</p></body></html>"),r={code:c,state:u}):(o.writeHead(400,{"Content-Type":"text/html"}),o.end("<html><body><h1>Authentication Failed</h1><p>Missing code or state parameter.</p></body></html>"))}else o.writeHead(404),o.end()});a.on("error",s=>{t(s)}),a.listen(8085,"127.0.0.1",()=>{e({server:a,cancelWait:()=>{i=!0},waitForCode:async()=>{const s=()=>new Promise(o=>setTimeout(o,100));for(;!r&&!i;)await s();return r}})})})}function d8(n){const e=n.trim();if(!e)return{};try{const t=new URL(e);return{code:t.searchParams.get("code")??void 0,state:t.searchParams.get("state")??void 0}}catch{return{}}}const yC="free-tier",p8="legacy-tier",o4e="standard-tier";function l4e(n){return new Promise(e=>setTimeout(e,n))}function c4e(n){return!n||n.length===0?{id:p8}:n.find(t=>t.isDefault)??{id:p8}}function u4e(n){if(!n||typeof n!="object"||!("error"in n))return!1;const e=n.error;return!e?.details||!Array.isArray(e.details)?!1:e.details.some(t=>t.reason==="SECURITY_POLICY_VIOLATED")}async function d4e(n,e,t){let r=0;for(;;){r>0&&(t?.(`Waiting for project provisioning (attempt ${r+1})...`),await l4e(5e3));const i=await fetch(`${iD}/v1internal/${n}`,{method:"GET",headers:e});if(!i.ok)throw new Error(`Failed to poll operation: ${i.status} ${i.statusText}`);const a=await i.json();if(a.done)return a;r+=1}}async function p4e(n,e){const t=c8.GOOGLE_CLOUD_PROJECT||c8.GOOGLE_CLOUD_PROJECT_ID,r={Authorization:`Bearer ${n}`,"Content-Type":"application/json","User-Agent":"google-api-nodejs-client/9.15.1","X-Goog-Api-Client":"gl-node/22.17.0"};e?.("Checking for existing Cloud Code Assist project...");const i=await fetch(`${iD}/v1internal:loadCodeAssist`,{method:"POST",headers:r,body:JSON.stringify({cloudaicompanionProject:t,metadata:{ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI",duetProject:t}})});let a;if(i.ok)a=await i.json();else{let p;try{p=await i.clone().json()}catch{p=void 0}if(u4e(p))a={currentTier:{id:o4e}};else{const h=await i.text();throw new Error(`loadCodeAssist failed: ${i.status} ${i.statusText}: ${h}`)}}if(a.currentTier){if(a.cloudaicompanionProject)return a.cloudaicompanionProject;if(t)return t;throw new Error("This account requires setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID environment variable. See https://goo.gle/gemini-cli-auth-docs#workspace-gca")}const o=c4e(a.allowedTiers)?.id??yC;if(o!==yC&&!t)throw new Error("This account requires setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID environment variable. See https://goo.gle/gemini-cli-auth-docs#workspace-gca");e?.("Provisioning Cloud Code Assist project (this may take a moment)...");const l={tierId:o,metadata:{ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}};o!==yC&&t&&(l.cloudaicompanionProject=t,l.metadata.duetProject=t);const c=await fetch(`${iD}/v1internal:onboardUser`,{method:"POST",headers:r,body:JSON.stringify(l)});if(!c.ok){const p=await c.text();throw new Error(`onboardUser failed: ${c.status} ${c.statusText}: ${p}`)}let u=await c.json();!u.done&&u.name&&(u=await d4e(u.name,r,e));const d=u.response?.cloudaicompanionProject?.id;if(d)return d;if(t)return t;throw new Error("Could not discover or provision a Google Cloud project. Try setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID environment variable. See https://goo.gle/gemini-cli-auth-docs#workspace-gca")}async function h4e(n){try{const e=await fetch("https://www.googleapis.com/oauth2/v1/userinfo?alt=json",{headers:{Authorization:`Bearer ${n}`}});if(e.ok)return(await e.json()).email}catch{}}async function f4e(n,e){const t=await fetch(FZ,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:rD,client_secret:LZ,refresh_token:n,grant_type:"refresh_token"})});if(!t.ok){const i=await t.text();throw new Error(`Google Cloud token refresh failed: ${i}`)}const r=await t.json();return{refresh:r.refresh_token||n,access:r.access_token,expires:Date.now()+r.expires_in*1e3-300*1e3,projectId:e}}async function m4e(n,e,t){const{verifier:r,challenge:i}=await yw();e?.("Starting local server for OAuth callback...");const a=await s4e();let s;try{const o=new URLSearchParams({client_id:rD,response_type:"code",redirect_uri:u8,scope:r4e.join(" "),code_challenge:i,code_challenge_method:"S256",state:r,access_type:"offline",prompt:"consent"}),l=`${i4e}?${o.toString()}`;if(n({url:l,instructions:"Complete the sign-in in your browser."}),e?.("Waiting for OAuth callback..."),t){let m,g;const _=t().then(b=>{m=b,a.cancelWait()}).catch(b=>{g=b instanceof Error?b:new Error(String(b)),a.cancelWait()}),v=await a.waitForCode();if(g)throw g;if(v?.code){if(v.state!==r)throw new Error("OAuth state mismatch - possible CSRF attack");s=v.code}else if(m){const b=d8(m);if(b.state&&b.state!==r)throw new Error("OAuth state mismatch - possible CSRF attack");s=b.code}if(!s){if(await _,g)throw g;if(m){const b=d8(m);if(b.state&&b.state!==r)throw new Error("OAuth state mismatch - possible CSRF attack");s=b.code}}}else{const m=await a.waitForCode();if(m?.code){if(m.state!==r)throw new Error("OAuth state mismatch - possible CSRF attack");s=m.code}}if(!s)throw new Error("No authorization code received");e?.("Exchanging authorization code for tokens...");const c=await fetch(FZ,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:rD,client_secret:LZ,code:s,grant_type:"authorization_code",redirect_uri:u8,code_verifier:r})});if(!c.ok){const m=await c.text();throw new Error(`Token exchange failed: ${m}`)}const u=await c.json();if(!u.refresh_token)throw new Error("No refresh token received. Please try again.");e?.("Getting user info...");const d=await h4e(u.access_token),p=await p4e(u.access_token,e),h=Date.now()+u.expires_in*1e3-300*1e3;return{refresh:u.refresh_token,access:u.access_token,expires:h,projectId:p,email:d}}finally{a.server.close()}}const g4e={id:"google-gemini-cli",name:"Google Cloud Code Assist (Gemini CLI)",usesCallbackServer:!0,async login(n){return m4e(n.onAuth,n.onProgress,n.onManualCodeInput)},async refreshToken(n){const e=n;if(!e.projectId)throw new Error("Google Cloud credentials missing projectId");return f4e(e.refresh,e.projectId)},getApiKey(n){const e=n;return JSON.stringify({token:e.access,projectId:e.projectId})}};let aD=null,sD=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(_s(()=>import("./_node-stub_node_crypto-C_7epg3G.js").then(n=>n._),[]).then(n=>{aD=n.randomBytes}),_s(()=>import("./_node-stub_node_http-CROXaVGJ.js").then(n=>n._),[]).then(n=>{sD=n}));const s4="app_EMoamEEZ73f0CkXaXp7hrann",_4e="https://auth.openai.com/oauth/authorize",UZ="https://auth.openai.com/oauth/token",BZ="http://localhost:1455/auth/callback",v4e="openid profile email offline_access",b4e="https://api.openai.com/auth",y4e=`<!doctype html>
|
|
146
|
+
`)}}}const vMe="responses_websockets=2026-02-06",bMe=300*1e3,Vd=new Map;function yMe(){const n=globalThis.WebSocket;return typeof n!="function"?null:n}function EMe(n){const e={};for(const[t,r]of n.entries())e[t]=r;return e}function SMe(n){const e=n.readyState;return typeof e=="number"?e:void 0}function Hb(n){const e=SMe(n);return e===void 0||e===1}function Yd(n,e=1e3,t="done"){try{n.close(e,t)}catch{}}function i8(n,e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{e.busy||(Yd(e.socket,1e3,"idle_timeout"),Vd.delete(n))},bMe)}async function vC(n,e,t){const r=yMe();if(!r)throw new Error("WebSocket transport is not available in this runtime");const i=EMe(e);return i["OpenAI-Beta"]=vMe,new Promise((a,s)=>{let o=!1,l;try{l=new r(n,{headers:i})}catch(f){s(f instanceof Error?f:new Error(String(f)));return}const c=()=>{o||(o=!0,h(),a(l))},u=f=>{o||(o=!0,h(),s(TZ(f)))},d=f=>{o||(o=!0,h(),s(wZ(f)))},p=()=>{o||(o=!0,h(),l.close(1e3,"aborted"),s(new Error("Request was aborted")))},h=()=>{l.removeEventListener("open",c),l.removeEventListener("error",u),l.removeEventListener("close",d),t?.removeEventListener("abort",p)};l.addEventListener("open",c),l.addEventListener("error",u),l.addEventListener("close",d),t?.addEventListener("abort",p)})}async function TMe(n,e,t,r){if(!t){const o=await vC(n,e,r);return{socket:o,release:({keep:l}={})=>{if(l===!1){Yd(o);return}Yd(o)}}}const i=Vd.get(t);if(i){if(i.idleTimer&&(clearTimeout(i.idleTimer),i.idleTimer=void 0),!i.busy&&Hb(i.socket))return i.busy=!0,{socket:i.socket,release:({keep:o}={})=>{if(!o||!Hb(i.socket)){Yd(i.socket),Vd.delete(t);return}i.busy=!1,i8(t,i)}};if(i.busy){const o=await vC(n,e,r);return{socket:o,release:()=>{Yd(o)}}}Hb(i.socket)||(Yd(i.socket),Vd.delete(t))}const a=await vC(n,e,r),s={socket:a,busy:!0};return Vd.set(t,s),{socket:a,release:({keep:o}={})=>{if(!o||!Hb(s.socket)){Yd(s.socket),s.idleTimer&&clearTimeout(s.idleTimer),Vd.get(t)===s&&Vd.delete(t);return}s.busy=!1,i8(t,s)}}}function TZ(n){if(n&&typeof n=="object"&&"message"in n){const e=n.message;if(typeof e=="string"&&e.length>0)return new Error(e)}return new Error("WebSocket error")}function wZ(n){if(n&&typeof n=="object"){const e="code"in n?n.code:void 0,t="reason"in n?n.reason:void 0,r=typeof e=="number"?` ${e}`:"",i=typeof t=="string"&&t.length>0?` ${t}`:"";return new Error(`WebSocket closed${r}${i}`.trim())}return new Error("WebSocket closed")}async function wMe(n){if(typeof n=="string")return n;if(n instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(n));if(ArrayBuffer.isView(n)){const e=n;return new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}if(n&&typeof n=="object"&&"arrayBuffer"in n){const t=await n.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}async function*xMe(n,e){const t=[];let r=null,i=!1,a=null,s=!1;const o=()=>{if(!r)return;const p=r;r=null,p()},l=p=>{(async()=>{if(!p||typeof p!="object"||!("data"in p))return;const h=await wMe(p.data);if(h)try{const f=JSON.parse(h),m=typeof f.type=="string"?f.type:"";(m==="response.completed"||m==="response.done")&&(s=!0,i=!0),t.push(f),o()}catch{}})()},c=p=>{a=TZ(p),i=!0,o()},u=p=>{if(s){i=!0,o();return}a||(a=wZ(p)),i=!0,o()},d=()=>{a=new Error("Request was aborted"),i=!0,o()};n.addEventListener("message",l),n.addEventListener("error",c),n.addEventListener("close",u),e?.addEventListener("abort",d);try{for(;;){if(e?.aborted)throw new Error("Request was aborted");if(t.length>0){yield t.shift();continue}if(i)break;await new Promise(p=>{r=p})}if(a)throw a;if(!s)throw new Error("WebSocket stream closed before response.completed")}finally{n.removeEventListener("message",l),n.removeEventListener("error",c),n.removeEventListener("close",u),e?.removeEventListener("abort",d)}}async function CMe(n,e,t,r,i,a,s,o){const{socket:l,release:c}=await TMe(n,t,o?.sessionId,o?.signal);let u=!0;try{l.send(JSON.stringify({type:"response.create",...e})),s(),i.push({type:"start",partial:r}),await ew(SZ(xMe(l,o?.signal)),r,i,a),o?.signal?.aborted&&(u=!1)}catch(d){throw u=!1,d}finally{c({keep:u})}}async function AMe(n){const e=await n.text();let t=e||n.statusText||"Request failed",r;try{const a=JSON.parse(e)?.error;if(a){const s=a.code||a.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(s)||n.status===429){const o=a.plan_type?` (${a.plan_type.toLowerCase()} plan)`:"",l=a.resets_at?Math.max(0,Math.round((a.resets_at*1e3-Date.now())/6e4)):void 0,c=l!==void 0?` Try again in ~${l} min.`:"";r=`You have hit your ChatGPT usage limit${o}.${c}`.trim()}t=a.message||r||t}}catch{}return{message:t,friendlyMessage:r}}function RMe(n){try{const e=n.split(".");if(e.length!==3)throw new Error("Invalid token");const r=JSON.parse(atob(e[1]))?.[oMe]?.chatgpt_account_id;if(!r)throw new Error("No account ID in token");return r}catch{throw new Error("Failed to extract accountId from token")}}function kMe(n,e,t,r,i){const a=new Headers(n);a.set("Authorization",`Bearer ${r}`),a.set("chatgpt-account-id",t),a.set("OpenAI-Beta","responses=experimental"),a.set("originator","pi");const s=Q0?`pi (${Q0.platform()} ${Q0.release()}; ${Q0.arch()})`:"pi (browser)";a.set("User-Agent",s),a.set("accept","text/event-stream"),a.set("content-type","application/json");for(const[o,l]of Object.entries(e||{}))a.set(o,l);return i&&a.set("session_id",i),a}function IMe(){dc({api:"anthropic-messages",stream:LE,streamSimple:rfe}),dc({api:"openai-completions",stream:ZQ,streamSimple:USe}),dc({api:"openai-responses",stream:JQ,streamSimple:jSe}),dc({api:"azure-openai-responses",stream:JK,streamSimple:Cme}),dc({api:"openai-codex-responses",stream:yZ,streamSimple:dMe}),dc({api:"google-generative-ai",stream:QE,streamSimple:iSe}),dc({api:"google-gemini-cli",stream:jE,streamSimple:SSe}),dc({api:"google-vertex",stream:XE,streamSimple:RSe}),dc({api:"bedrock-converse-stream",stream:K0,streamSimple:VPe})}IMe();typeof process<"u"&&process.versions?.node&&_s(()=>import("./index-CAQqlK61.js").then(n=>n.i),__vite__mapDeps([3,4,5,6])).then(n=>{const{EnvHttpProxyAgent:e,setGlobalDispatcher:t}=n;t(new e)});function xZ(n){const e=Ype(n);if(!e)throw new Error(`No API provider registered for api: ${n}`);return e}function NMe(n,e,t){return xZ(n.api).stream(n,e,t)}async function DMe(n,e,t){return NMe(n,e,t).result()}function ZN(n,e,t){return xZ(n.api).streamSimple(n,e,t)}function a8(n){let e="";for(const t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function yw(){const n=new Uint8Array(32);crypto.getRandomValues(n);const e=a8(n),r=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",r),a=a8(new Uint8Array(i));return{verifier:e,challenge:a}}const OMe=n=>atob(n),JN=OMe("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl"),PMe="https://claude.ai/oauth/authorize",CZ="https://console.anthropic.com/v1/oauth/token",s8="https://console.anthropic.com/oauth/code/callback",MMe="org:create_api_key user:profile user:inference";async function LMe(n,e){const{verifier:t,challenge:r}=await yw(),i=new URLSearchParams({code:"true",client_id:JN,response_type:"code",redirect_uri:s8,scope:MMe,code_challenge:r,code_challenge_method:"S256",state:t}),a=`${PMe}?${i.toString()}`;n(a);const o=(await e()).split("#"),l=o[0],c=o[1],u=await fetch(CZ,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:JN,code:l,state:c,redirect_uri:s8,code_verifier:t})});if(!u.ok){const h=await u.text();throw new Error(`Token exchange failed: ${h}`)}const d=await u.json(),p=Date.now()+d.expires_in*1e3-300*1e3;return{refresh:d.refresh_token,access:d.access_token,expires:p}}async function FMe(n){const e=await fetch(CZ,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:JN,refresh_token:n})});if(!e.ok){const r=await e.text();throw new Error(`Anthropic token refresh failed: ${r}`)}const t=await e.json();return{refresh:t.refresh_token,access:t.access_token,expires:Date.now()+t.expires_in*1e3-300*1e3}}const UMe={id:"anthropic",name:"Anthropic (Claude Pro/Max)",async login(n){return LMe(e=>n.onAuth({url:e}),()=>n.onPrompt({message:"Paste the authorization code:"}))},async refreshToken(n){return FMe(n.refresh)},getApiKey(n){return n.access}},BMe=n=>atob(n),AZ=BMe("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),RZ={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"};function kZ(n){const e=n.trim();if(!e)return null;try{return(e.includes("://")?new URL(e):new URL(`https://${e}`)).hostname}catch{return null}}function i4(n){return{deviceCodeUrl:`https://${n}/login/device/code`,accessTokenUrl:`https://${n}/login/oauth/access_token`,copilotTokenUrl:`https://api.${n}/copilot_internal/v2/token`}}function $Me(n){const e=n.match(/proxy-ep=([^;]+)/);return e?`https://${e[1].replace(/^proxy\./,"api.")}`:null}function IZ(n,e){if(n){const t=$Me(n);if(t)return t}return e?`https://copilot-api.${e}`:"https://api.individual.githubcopilot.com"}async function a4(n,e){const t=await fetch(n,e);if(!t.ok){const r=await t.text();throw new Error(`${t.status} ${t.statusText}: ${r}`)}return t.json()}async function GMe(n){const e=i4(n),t=await a4(e.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"GitHubCopilotChat/0.35.0"},body:JSON.stringify({client_id:AZ,scope:"read:user"})});if(!t||typeof t!="object")throw new Error("Invalid device code response");const r=t.device_code,i=t.user_code,a=t.verification_uri,s=t.interval,o=t.expires_in;if(typeof r!="string"||typeof i!="string"||typeof a!="string"||typeof s!="number"||typeof o!="number")throw new Error("Invalid device code response fields");return{device_code:r,user_code:i,verification_uri:a,interval:s,expires_in:o}}function bC(n,e){return new Promise((t,r)=>{if(e?.aborted){r(new Error("Login cancelled"));return}const i=setTimeout(t,n);e?.addEventListener("abort",()=>{clearTimeout(i),r(new Error("Login cancelled"))},{once:!0})})}async function WMe(n,e,t,r,i){const a=i4(n),s=Date.now()+r*1e3;let o=Math.max(1e3,Math.floor(t*1e3));for(;Date.now()<s;){if(i?.aborted)throw new Error("Login cancelled");const l=await a4(a.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":"GitHubCopilotChat/0.35.0"},body:JSON.stringify({client_id:AZ,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(l&&typeof l=="object"&&typeof l.access_token=="string")return l.access_token;if(l&&typeof l=="object"&&typeof l.error=="string"){const c=l.error;if(c==="authorization_pending"){await bC(o,i);continue}if(c==="slow_down"){o+=5e3,await bC(o,i);continue}throw new Error(`Device flow failed: ${c}`)}await bC(o,i)}throw new Error("Device flow timed out")}async function NZ(n,e){const r=i4(e||"github.com"),i=await a4(r.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${n}`,...RZ}});if(!i||typeof i!="object")throw new Error("Invalid Copilot token response");const a=i.token,s=i.expires_at;if(typeof a!="string"||typeof s!="number")throw new Error("Invalid Copilot token response fields");return{refresh:n,access:a,expires:s*1e3-300*1e3,enterpriseUrl:e}}async function zMe(n,e,t){const i=`${IZ(n,t)}/models/${e}/policy`;try{return(await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,...RZ,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})})).ok}catch{return!1}}async function qMe(n,e,t){const r=RV("github-copilot");await Promise.all(r.map(async i=>{await zMe(n,i.id,e)}))}async function HMe(n){const e=await n.onPrompt({message:"GitHub Enterprise URL/domain (blank for github.com)",placeholder:"company.ghe.com",allowEmpty:!0});if(n.signal?.aborted)throw new Error("Login cancelled");const t=e.trim(),r=kZ(e);if(t&&!r)throw new Error("Invalid GitHub Enterprise URL/domain");const i=r||"github.com",a=await GMe(i);n.onAuth(a.verification_uri,`Enter code: ${a.user_code}`);const s=await WMe(i,a.device_code,a.interval,a.expires_in,n.signal),o=await NZ(s,r??void 0);return n.onProgress?.("Enabling models..."),await qMe(o.access,r??void 0),o}const VMe={id:"github-copilot",name:"GitHub Copilot",async login(n){return HMe({onAuth:(e,t)=>n.onAuth({url:e,instructions:t}),onPrompt:n.onPrompt,onProgress:n.onProgress,signal:n.signal})},async refreshToken(n){const e=n;return NZ(e.refresh,e.enterpriseUrl)},getApiKey(n){return n.access},modifyModels(n,e){const t=e,r=t.enterpriseUrl?kZ(t.enterpriseUrl)??void 0:void 0,i=IZ(t.access,r);return n.map(a=>a.provider==="github-copilot"?{...a,baseUrl:i}:a)}};let j0=null,eD=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(eD=_s(()=>import("./_node-stub_node_http-CROXaVGJ.js").then(n=>n._),[]).then(n=>{j0=n.createServer}));const DZ=n=>atob(n),tD=DZ("MTA3MTAwNjA2MDU5MS10bWhzc2luMmgyMWxjcmUyMzV2dG9sb2poNGc0MDNlcC5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbQ=="),OZ=DZ("R09DU1BYLUs1OEZXUjQ4NkxkTEoxbUxCOHNYQzR6NnFEQWY="),o8="http://localhost:51121/oauth-callback",YMe=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/cclog","https://www.googleapis.com/auth/experimentsandconfigs"],KMe="https://accounts.google.com/o/oauth2/v2/auth",PZ="https://oauth2.googleapis.com/token",QMe="rising-fact-p41fc";async function jMe(){if(j0||(eD&&await eD,j0))return j0;throw new Error("Antigravity OAuth is only available in Node.js environments")}async function XMe(){const n=await jMe();return new Promise((e,t)=>{let r=null,i=!1;const a=n((s,o)=>{const l=new URL(s.url||"","http://localhost:51121");if(l.pathname==="/oauth-callback"){const c=l.searchParams.get("code"),u=l.searchParams.get("state"),d=l.searchParams.get("error");if(d){o.writeHead(400,{"Content-Type":"text/html"}),o.end(`<html><body><h1>Authentication Failed</h1><p>Error: ${d}</p><p>You can close this window.</p></body></html>`);return}c&&u?(o.writeHead(200,{"Content-Type":"text/html"}),o.end("<html><body><h1>Authentication Successful</h1><p>You can close this window and return to the terminal.</p></body></html>"),r={code:c,state:u}):(o.writeHead(400,{"Content-Type":"text/html"}),o.end("<html><body><h1>Authentication Failed</h1><p>Missing code or state parameter.</p></body></html>"))}else o.writeHead(404),o.end()});a.on("error",s=>{t(s)}),a.listen(51121,"127.0.0.1",()=>{e({server:a,cancelWait:()=>{i=!0},waitForCode:async()=>{const s=()=>new Promise(o=>setTimeout(o,100));for(;!r&&!i;)await s();return r}})})})}function l8(n){const e=n.trim();if(!e)return{};try{const t=new URL(e);return{code:t.searchParams.get("code")??void 0,state:t.searchParams.get("state")??void 0}}catch{return{}}}async function ZMe(n,e){const t={Authorization:`Bearer ${n}`,"Content-Type":"application/json","User-Agent":"google-api-nodejs-client/9.15.1","X-Goog-Api-Client":"google-cloud-sdk vscode_cloudshelleditor/0.1","Client-Metadata":JSON.stringify({ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"})},r=["https://cloudcode-pa.googleapis.com","https://daily-cloudcode-pa.sandbox.googleapis.com"];e?.("Checking for existing project...");for(const i of r)try{const a=await fetch(`${i}/v1internal:loadCodeAssist`,{method:"POST",headers:t,body:JSON.stringify({metadata:{ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}})});if(a.ok){const s=await a.json();if(typeof s.cloudaicompanionProject=="string"&&s.cloudaicompanionProject)return s.cloudaicompanionProject;if(s.cloudaicompanionProject&&typeof s.cloudaicompanionProject=="object"&&s.cloudaicompanionProject.id)return s.cloudaicompanionProject.id}}catch{}return e?.("Using default project..."),QMe}async function JMe(n){try{const e=await fetch("https://www.googleapis.com/oauth2/v1/userinfo?alt=json",{headers:{Authorization:`Bearer ${n}`}});if(e.ok)return(await e.json()).email}catch{}}async function e4e(n,e){const t=await fetch(PZ,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:tD,client_secret:OZ,refresh_token:n,grant_type:"refresh_token"})});if(!t.ok){const i=await t.text();throw new Error(`Antigravity token refresh failed: ${i}`)}const r=await t.json();return{refresh:r.refresh_token||n,access:r.access_token,expires:Date.now()+r.expires_in*1e3-300*1e3,projectId:e}}async function t4e(n,e,t){const{verifier:r,challenge:i}=await yw();e?.("Starting local server for OAuth callback...");const a=await XMe();let s;try{const o=new URLSearchParams({client_id:tD,response_type:"code",redirect_uri:o8,scope:YMe.join(" "),code_challenge:i,code_challenge_method:"S256",state:r,access_type:"offline",prompt:"consent"}),l=`${KMe}?${o.toString()}`;if(n({url:l,instructions:"Complete the sign-in in your browser."}),e?.("Waiting for OAuth callback..."),t){let m,g;const _=t().then(b=>{m=b,a.cancelWait()}).catch(b=>{g=b instanceof Error?b:new Error(String(b)),a.cancelWait()}),v=await a.waitForCode();if(g)throw g;if(v?.code){if(v.state!==r)throw new Error("OAuth state mismatch - possible CSRF attack");s=v.code}else if(m){const b=l8(m);if(b.state&&b.state!==r)throw new Error("OAuth state mismatch - possible CSRF attack");s=b.code}if(!s){if(await _,g)throw g;if(m){const b=l8(m);if(b.state&&b.state!==r)throw new Error("OAuth state mismatch - possible CSRF attack");s=b.code}}}else{const m=await a.waitForCode();if(m?.code){if(m.state!==r)throw new Error("OAuth state mismatch - possible CSRF attack");s=m.code}}if(!s)throw new Error("No authorization code received");e?.("Exchanging authorization code for tokens...");const c=await fetch(PZ,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:tD,client_secret:OZ,code:s,grant_type:"authorization_code",redirect_uri:o8,code_verifier:r})});if(!c.ok){const m=await c.text();throw new Error(`Token exchange failed: ${m}`)}const u=await c.json();if(!u.refresh_token)throw new Error("No refresh token received. Please try again.");e?.("Getting user info...");const d=await JMe(u.access_token),p=await ZMe(u.access_token,e),h=Date.now()+u.expires_in*1e3-300*1e3;return{refresh:u.refresh_token,access:u.access_token,expires:h,projectId:p,email:d}}finally{a.server.close()}}const n4e={id:"google-antigravity",name:"Antigravity (Gemini 3, Claude, GPT-OSS)",usesCallbackServer:!0,async login(n){return t4e(n.onAuth,n.onProgress,n.onManualCodeInput)},async refreshToken(n){const e=n;if(!e.projectId)throw new Error("Antigravity credentials missing projectId");return e4e(e.refresh,e.projectId)},getApiKey(n){const e=n;return JSON.stringify({token:e.access,projectId:e.projectId})}};var c8={};let X0=null,nD=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(nD=_s(()=>import("./_node-stub_node_http-CROXaVGJ.js").then(n=>n._),[]).then(n=>{X0=n.createServer}));const MZ=n=>atob(n),rD=MZ("NjgxMjU1ODA5Mzk1LW9vOGZ0Mm9wcmRybnA5ZTNhcWY2YXYzaG1kaWIxMzVqLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29t"),LZ=MZ("R09DU1BYLTR1SGdNUG0tMW83U2stZ2VWNkN1NWNsWEZzeGw="),u8="http://localhost:8085/oauth2callback",r4e=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile"],i4e="https://accounts.google.com/o/oauth2/v2/auth",FZ="https://oauth2.googleapis.com/token",iD="https://cloudcode-pa.googleapis.com";async function a4e(){if(X0||(nD&&await nD,X0))return X0;throw new Error("Gemini CLI OAuth is only available in Node.js environments")}async function s4e(){const n=await a4e();return new Promise((e,t)=>{let r=null,i=!1;const a=n((s,o)=>{const l=new URL(s.url||"","http://localhost:8085");if(l.pathname==="/oauth2callback"){const c=l.searchParams.get("code"),u=l.searchParams.get("state"),d=l.searchParams.get("error");if(d){o.writeHead(400,{"Content-Type":"text/html"}),o.end(`<html><body><h1>Authentication Failed</h1><p>Error: ${d}</p><p>You can close this window.</p></body></html>`);return}c&&u?(o.writeHead(200,{"Content-Type":"text/html"}),o.end("<html><body><h1>Authentication Successful</h1><p>You can close this window and return to the terminal.</p></body></html>"),r={code:c,state:u}):(o.writeHead(400,{"Content-Type":"text/html"}),o.end("<html><body><h1>Authentication Failed</h1><p>Missing code or state parameter.</p></body></html>"))}else o.writeHead(404),o.end()});a.on("error",s=>{t(s)}),a.listen(8085,"127.0.0.1",()=>{e({server:a,cancelWait:()=>{i=!0},waitForCode:async()=>{const s=()=>new Promise(o=>setTimeout(o,100));for(;!r&&!i;)await s();return r}})})})}function d8(n){const e=n.trim();if(!e)return{};try{const t=new URL(e);return{code:t.searchParams.get("code")??void 0,state:t.searchParams.get("state")??void 0}}catch{return{}}}const yC="free-tier",p8="legacy-tier",o4e="standard-tier";function l4e(n){return new Promise(e=>setTimeout(e,n))}function c4e(n){return!n||n.length===0?{id:p8}:n.find(t=>t.isDefault)??{id:p8}}function u4e(n){if(!n||typeof n!="object"||!("error"in n))return!1;const e=n.error;return!e?.details||!Array.isArray(e.details)?!1:e.details.some(t=>t.reason==="SECURITY_POLICY_VIOLATED")}async function d4e(n,e,t){let r=0;for(;;){r>0&&(t?.(`Waiting for project provisioning (attempt ${r+1})...`),await l4e(5e3));const i=await fetch(`${iD}/v1internal/${n}`,{method:"GET",headers:e});if(!i.ok)throw new Error(`Failed to poll operation: ${i.status} ${i.statusText}`);const a=await i.json();if(a.done)return a;r+=1}}async function p4e(n,e){const t=c8.GOOGLE_CLOUD_PROJECT||c8.GOOGLE_CLOUD_PROJECT_ID,r={Authorization:`Bearer ${n}`,"Content-Type":"application/json","User-Agent":"google-api-nodejs-client/9.15.1","X-Goog-Api-Client":"gl-node/22.17.0"};e?.("Checking for existing Cloud Code Assist project...");const i=await fetch(`${iD}/v1internal:loadCodeAssist`,{method:"POST",headers:r,body:JSON.stringify({cloudaicompanionProject:t,metadata:{ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI",duetProject:t}})});let a;if(i.ok)a=await i.json();else{let p;try{p=await i.clone().json()}catch{p=void 0}if(u4e(p))a={currentTier:{id:o4e}};else{const h=await i.text();throw new Error(`loadCodeAssist failed: ${i.status} ${i.statusText}: ${h}`)}}if(a.currentTier){if(a.cloudaicompanionProject)return a.cloudaicompanionProject;if(t)return t;throw new Error("This account requires setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID environment variable. See https://goo.gle/gemini-cli-auth-docs#workspace-gca")}const o=c4e(a.allowedTiers)?.id??yC;if(o!==yC&&!t)throw new Error("This account requires setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID environment variable. See https://goo.gle/gemini-cli-auth-docs#workspace-gca");e?.("Provisioning Cloud Code Assist project (this may take a moment)...");const l={tierId:o,metadata:{ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}};o!==yC&&t&&(l.cloudaicompanionProject=t,l.metadata.duetProject=t);const c=await fetch(`${iD}/v1internal:onboardUser`,{method:"POST",headers:r,body:JSON.stringify(l)});if(!c.ok){const p=await c.text();throw new Error(`onboardUser failed: ${c.status} ${c.statusText}: ${p}`)}let u=await c.json();!u.done&&u.name&&(u=await d4e(u.name,r,e));const d=u.response?.cloudaicompanionProject?.id;if(d)return d;if(t)return t;throw new Error("Could not discover or provision a Google Cloud project. Try setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID environment variable. See https://goo.gle/gemini-cli-auth-docs#workspace-gca")}async function h4e(n){try{const e=await fetch("https://www.googleapis.com/oauth2/v1/userinfo?alt=json",{headers:{Authorization:`Bearer ${n}`}});if(e.ok)return(await e.json()).email}catch{}}async function f4e(n,e){const t=await fetch(FZ,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:rD,client_secret:LZ,refresh_token:n,grant_type:"refresh_token"})});if(!t.ok){const i=await t.text();throw new Error(`Google Cloud token refresh failed: ${i}`)}const r=await t.json();return{refresh:r.refresh_token||n,access:r.access_token,expires:Date.now()+r.expires_in*1e3-300*1e3,projectId:e}}async function m4e(n,e,t){const{verifier:r,challenge:i}=await yw();e?.("Starting local server for OAuth callback...");const a=await s4e();let s;try{const o=new URLSearchParams({client_id:rD,response_type:"code",redirect_uri:u8,scope:r4e.join(" "),code_challenge:i,code_challenge_method:"S256",state:r,access_type:"offline",prompt:"consent"}),l=`${i4e}?${o.toString()}`;if(n({url:l,instructions:"Complete the sign-in in your browser."}),e?.("Waiting for OAuth callback..."),t){let m,g;const _=t().then(b=>{m=b,a.cancelWait()}).catch(b=>{g=b instanceof Error?b:new Error(String(b)),a.cancelWait()}),v=await a.waitForCode();if(g)throw g;if(v?.code){if(v.state!==r)throw new Error("OAuth state mismatch - possible CSRF attack");s=v.code}else if(m){const b=d8(m);if(b.state&&b.state!==r)throw new Error("OAuth state mismatch - possible CSRF attack");s=b.code}if(!s){if(await _,g)throw g;if(m){const b=d8(m);if(b.state&&b.state!==r)throw new Error("OAuth state mismatch - possible CSRF attack");s=b.code}}}else{const m=await a.waitForCode();if(m?.code){if(m.state!==r)throw new Error("OAuth state mismatch - possible CSRF attack");s=m.code}}if(!s)throw new Error("No authorization code received");e?.("Exchanging authorization code for tokens...");const c=await fetch(FZ,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:rD,client_secret:LZ,code:s,grant_type:"authorization_code",redirect_uri:u8,code_verifier:r})});if(!c.ok){const m=await c.text();throw new Error(`Token exchange failed: ${m}`)}const u=await c.json();if(!u.refresh_token)throw new Error("No refresh token received. Please try again.");e?.("Getting user info...");const d=await h4e(u.access_token),p=await p4e(u.access_token,e),h=Date.now()+u.expires_in*1e3-300*1e3;return{refresh:u.refresh_token,access:u.access_token,expires:h,projectId:p,email:d}}finally{a.server.close()}}const g4e={id:"google-gemini-cli",name:"Google Cloud Code Assist (Gemini CLI)",usesCallbackServer:!0,async login(n){return m4e(n.onAuth,n.onProgress,n.onManualCodeInput)},async refreshToken(n){const e=n;if(!e.projectId)throw new Error("Google Cloud credentials missing projectId");return f4e(e.refresh,e.projectId)},getApiKey(n){const e=n;return JSON.stringify({token:e.access,projectId:e.projectId})}};let aD=null,sD=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(_s(()=>import("./_node-stub_node_crypto-C_7epg3G.js").then(n=>n._),[]).then(n=>{aD=n.randomBytes}),_s(()=>import("./_node-stub_node_http-CROXaVGJ.js").then(n=>n._),[]).then(n=>{sD=n}));const s4="app_EMoamEEZ73f0CkXaXp7hrann",_4e="https://auth.openai.com/oauth/authorize",UZ="https://auth.openai.com/oauth/token",BZ="http://localhost:1455/auth/callback",v4e="openid profile email offline_access",b4e="https://api.openai.com/auth",y4e=`<!doctype html>
|
|
147
147
|
<html lang="en">
|
|
148
148
|
<head>
|
|
149
149
|
<meta charset="utf-8" />
|
|
@@ -2959,10 +2959,10 @@ ${this.content||""}</pre
|
|
|
2959
2959
|
${br({variant:"outline",onClick:()=>this.handleCancel(),children:Te("Cancel")})}
|
|
2960
2960
|
${br({variant:"default",onClick:()=>this.handleConfirm(),children:Te("Confirm")})}
|
|
2961
2961
|
`})}
|
|
2962
|
-
`})}};Pm([Ge()],Kp.prototype,"headerTitle",void 0);Pm([Ge()],Kp.prototype,"message",void 0);Pm([Ge()],Kp.prototype,"defaultValue",void 0);Pm([Ge()],Kp.prototype,"isPassword",void 0);Pm([lt()],Kp.prototype,"inputValue",void 0);Kp=TO=Pm([sn("prompt-dialog")],Kp);function sat(n=16){const e=new Uint8Array(n);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}const sH="pipane-load-trace-id",sT=(()=>{const n=sessionStorage.getItem(sH);if(n)return n;const e=sat(16);return sessionStorage.setItem(sH,e),e})();function Tae(n,e,t){fetch("/api/debug/load-trace/event",{method:"POST",headers:{"Content-Type":"application/json","x-pi-trace-id":sT},body:JSON.stringify({traceId:sT,name:n,durationMs:e,attrs:t})}).catch(()=>{})}function wae(){return sT}function oT(n,e){Tae(n,void 0,e)}function $g(n,e){const t=performance.now();return()=>{const r=Number((performance.now()-t).toFixed(2));Tae(n,r,e)}}async function MI(n,e={},t){const r=$g(t||`fetch ${typeof n=="string"?n:n.toString()}`),i=new Headers(e.headers||void 0);i.set("x-pi-trace-id",sT);try{return await fetch(n,{...e,headers:i})}finally{r()}}function oat(){const n=performance.getEntriesByType("navigation")[0];n&&oT("navigation_timing",{domInteractive:Number(n.domInteractive.toFixed(2)),domContentLoadedEventEnd:Number(n.domContentLoadedEventEnd.toFixed(2)),loadEventEnd:Number(n.loadEventEnd.toFixed(2)),responseEnd:Number(n.responseEnd.toFixed(2))})}async function oH(n){if(typeof globalThis.crypto?.subtle?.digest=="function"){const t=new TextEncoder().encode(n),r=await globalThis.crypto.subtle.digest("SHA-256",t),i=new Uint8Array(r);return Array.from(i).map(a=>a.toString(16).padStart(2,"0")).join("")}const{createHash:e}=await _s(async()=>{const{createHash:t}=await import("./_node-stub_node_crypto-C_7epg3G.js").then(r=>r._);return{createHash:t}},[]);return e("sha256").update(n,"utf8").digest("hex")}function lat(n,e){let t=n;for(const r of e)t=t.slice(0,r.offset)+r.insert+t.slice(r.offset+r.deleteCount);return t}async function cat(n,e,t){if(t.op==="full"){const a=await oH(t.data);return a!==t.hash?(console.error("[jsonl-sync] Full sync hash mismatch",{expected:t.hash,actual:a}),null):{data:t.data,hash:t.hash}}if(t.baseHash!==e)return console.warn("[jsonl-sync] Base hash mismatch, need full sync",{expected:t.baseHash,actual:e}),null;const r=lat(n,t.patches),i=await oH(r);return i!==t.hash?(console.error("[jsonl-sync] Post-patch hash mismatch",{expected:t.hash,actual:i}),null):{data:r,hash:t.hash}}class uat{constructor(){this.ws=null,this.listeners=new Set,this.sessionsChangedListeners=new Set,this.piInstallRequiredListeners=new Set,this.pendingRequests=new Map,this.requestId=0,this._reconnecting=!1,this._reconnectAttempt=0,this._connectionListeners=new Set,this.streamFn=()=>{},this.getApiKey=void 0,this._state={systemPrompt:"",model:void 0,thinkingLevel:"off",tools:[],messages:[],isStreaming:!1,streamMessage:null,pendingToolCalls:new Set,error:void 0},this._pendingToolCallIds=new Set,this._steeringQueues=new Map,this._steeringQueueListeners=new Set,this._restoreModelFromServer=!1,this._availableModels=null,this._sessionId="",this._sessionStatus="virtual",this._optimisticSessions=new Map,this._globalSessionStatus=new Map,this._globalStatusListeners=new Set,this._sessionNonce=0,this._pendingNewPrompt=!1,this._syncJson="",this._syncHash="",this._pendingSessionSync=null,this._sessionSyncFlushScheduled=!1,this._sessionSyncFlushInProgress=!1,this._sessionListeners=new Set,this._contentListeners=new Set,this._statusListeners=new Set}get state(){return this._state}get sessionId(){return this._sessionId}get sessionFile(){return this._sessionPath}get sessionName(){return this._sessionName}get sessionStatus(){return this._sessionStatus}get isConnected(){return this.ws?.readyState===WebSocket.OPEN}get isReconnecting(){return this._reconnecting}onConnectionChange(e){return this._connectionListeners.add(e),()=>this._connectionListeners.delete(e)}emitConnectionChange(e){for(const t of this._connectionListeners)t(e)}get pendingToolCallIds(){return this._pendingToolCallIds}get steeringQueue(){return this._sessionPath?this._steeringQueues.get(this._sessionPath)??[]:[]}getSessionStatus(e){return this._globalSessionStatus.get(e)}onGlobalStatusChange(e){return this._globalStatusListeners.add(e),()=>this._globalStatusListeners.delete(e)}emitGlobalStatusChange(){for(const e of this._globalStatusListeners)e()}setGlobalSessionStatus(e,t){this._globalSessionStatus.set(e,t),this.emitGlobalStatusChange()}setAllSessionStatuses(e){this._globalSessionStatus.clear();for(const[t,r]of Object.entries(e))this._globalSessionStatus.set(t,r);this.emitGlobalStatusChange()}onSteeringQueueChange(e){return this._steeringQueueListeners.add(e),()=>this._steeringQueueListeners.delete(e)}emitSteeringQueueChange(){for(const e of this._steeringQueueListeners)e()}enqueueSteering(e,t){const r=this._steeringQueues.get(e)??[];this._steeringQueues.set(e,[...r,t]),this.emitSteeringQueueChange()}onSessionChange(e){return this._sessionListeners.add(e),()=>this._sessionListeners.delete(e)}emitSessionChange(){for(const e of this._sessionListeners)e()}onContentChange(e){return this._contentListeners.add(e),()=>this._contentListeners.delete(e)}emitContentChange(){for(const e of this._contentListeners)e()}onStatusChange(e){return this._statusListeners.add(e),()=>this._statusListeners.delete(e)}emitStatusChange(){for(const e of this._statusListeners)e()}onSessionsChanged(e){return this.sessionsChangedListeners.add(e),()=>this.sessionsChangedListeners.delete(e)}onPiInstallRequired(e){return this.piInstallRequiredListeners.add(e),()=>this.piInstallRequiredListeners.delete(e)}emitPiInstallRequired(e){for(const t of this.piInstallRequiredListeners)t(e)}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}emit(e){for(const t of this.listeners)t(e)}async connect(e){this._wsUrl=e,await this.connectWs(e,!1),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.syncStateOnFocus()})}connectWs(e,t){return new Promise((r,i)=>{const a=new WebSocket(e);a.onopen=()=>{this.ws=a,this._reconnecting=!1,this._reconnectAttempt=0,t||(this._sessionStatus="virtual"),console.log(`[ws-adapter] WebSocket ${t?"re":""}connected`),this.emitConnectionChange(!0),t&&this.onReconnected(),r()},a.onerror=()=>{t||i(new Error("WebSocket error"))},a.onclose=()=>{const s=this.ws===a;this.ws===a&&(this.ws=null);for(const[o,l]of this.pendingRequests)l.endSpan?.(),l.reject(new Error("WebSocket disconnected"));this.pendingRequests.clear(),s&&(console.log("[ws-adapter] WebSocket disconnected, will reconnect..."),this.emitConnectionChange(!1)),(t||s)&&this.scheduleReconnect()},a.onmessage=s=>this.handleMessage(s.data)})}scheduleReconnect(){if(this._reconnectTimer)return;this._reconnecting=!0,this._reconnectAttempt++;const e=Math.min(500*Math.pow(2,this._reconnectAttempt-1),1e4);console.log(`[ws-adapter] Reconnecting in ${e}ms (attempt ${this._reconnectAttempt})...`),this._reconnectTimer=setTimeout(async()=>{if(this._reconnectTimer=void 0,!!this._wsUrl)try{await this.connectWs(this._wsUrl,!0)}catch{}},e)}async onReconnected(){this._sessionPath&&this._sessionStatus!=="virtual"&&(this._syncJson="",this._syncHash="",this.subscribeToSession(this._sessionPath)),this.refreshSessionStatuses()}async syncStateOnFocus(){this.refreshSessionStatuses(),this._sessionPath&&this._sessionStatus!=="virtual"&&this.subscribeToSession(this._sessionPath),this._sessionStatus==="detached"&&this._state.isStreaming&&(console.log("[ws-adapter] Tab regained focus: clearing stale streaming state"),this._state.isStreaming=!1,this._state.streamMessage=null,this._state.pendingToolCalls=new Set,this._resolveRunning?.(),this._runningPromise=void 0,this._resolveRunning=void 0,this.emitStatusChange())}async refreshSessionStatuses(){try{const e=await this.send({type:"get_session_statuses"});e?.statuses&&this.setAllSessionStatuses(e.statuses)}catch(e){console.error("Failed to refresh session statuses:",e)}}async subscribeToSession(e){try{await this.send({type:"subscribe_session",sessionPath:e??""})}catch(t){console.error("Failed to subscribe to session:",t)}}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(t.type==="response"&&t.id&&this.pendingRequests.has(t.id)){const i=this.pendingRequests.get(t.id);this.pendingRequests.delete(t.id),i.endSpan?.(),t.success?i.resolve(t.data):i.reject(new Error(t.error||"Unknown error"));return}if(t.type==="pi_install_required"){this.emitPiInstallRequired({command:t.command||"pi",installable:!!t.installable,installing:!!t.installing,message:t.message||"pi is not available"});return}if(t.type==="init"){if(t.sessionStatuses&&this.setAllSessionStatuses(t.sessionStatuses),t.steeringQueues){this._steeringQueues.clear();for(const[i,a]of Object.entries(t.steeringQueues))a.length>0&&this._steeringQueues.set(i,[...a]);this.emitSteeringQueueChange()}return}if(t.type==="session_status_change"){t.sessionPath&&t.status&&this.setGlobalSessionStatus(t.sessionPath,t.status);return}if(t.type==="session_sync"){if(t.sessionPath!==this._sessionPath)return;this.enqueueSessionSync(t);return}if(t.type==="steering_queue_update"){const i=t.sessionPath;i&&(t.queue&&t.queue.length>0?this._steeringQueues.set(i,[...t.queue]):this._steeringQueues.delete(i),this.emitSteeringQueueChange());return}if(t.type==="session_messages"){t.sessionPath===this._sessionPath&&(this._state.messages=t.messages??[],this._restoreModelFromServer&&(t.model&&(this._state.model=this.findModelMatch(t.model)??this._state.model),t.thinkingLevel&&(this._state.thinkingLevel=t.thinkingLevel),this._restoreModelFromServer=!1),this.emitContentChange());return}if(t.type==="session_attached"){if(t.sessionPath&&this.setGlobalSessionStatus(t.sessionPath,"running"),t.sessionPath===this._sessionPath||this._sessionStatus==="virtual"&&this._pendingNewPrompt){if(this._sessionStatus==="virtual"&&t.sessionPath){this._sessionPath=t.sessionPath;const a=k0.basename(t.sessionPath,".jsonl"),s=a.split("_");this._sessionId=s.length>1?s.slice(1).join("_"):a}this._sessionStatus="attached",this._state.isStreaming=!0,t.sessionPath&&this.subscribeToSession(t.sessionPath),this.emitStatusChange()}if(t.sessionPath&&!this._optimisticSessions.has(t.sessionPath)){const a=new Date().toISOString(),s=k0.basename(t.sessionPath,".jsonl"),o=s.split("_"),l=o.length>1?o.slice(1).join("_"):s;this._optimisticSessions.set(t.sessionPath,{id:l,path:t.sessionPath,cwd:t.cwd||"",created:a,modified:a,lastUserPromptTime:a,messageCount:1,firstMessage:t.firstMessage||"(new session)"})}return}if(t.type==="session_detached"){t.sessionPath&&this.setGlobalSessionStatus(t.sessionPath,"done"),t.sessionPath===this._sessionPath&&(this._sessionStatus="detached",this._state.isStreaming=!1,this._state.streamMessage=null,this._state.pendingToolCalls=new Set,this._pendingToolCallIds.clear(),this._resolveRunning?.(),this._runningPromise=void 0,this._resolveRunning=void 0,this.emitStatusChange());return}if(t.type==="sessions_changed"){const i=t.file;for(const a of this.sessionsChangedListeners)a(i);return}if(t.type==="agent_event"){if(t.sessionPath&&t.sessionPath!==this._sessionPath)return;const i=t.event;this.emit(i);return}if(t.sessionPath&&t.sessionPath!==this._sessionPath)return;const r=t;this.updateState(r),this.emit(r)}enqueueSessionSync(e){const t=this._pendingSessionSync;t?e.op==="full"?this._pendingSessionSync=e:t.op!=="full"&&(this._pendingSessionSync=e):this._pendingSessionSync=e,!(this._sessionSyncFlushScheduled||this._sessionSyncFlushInProgress)&&(this._sessionSyncFlushScheduled=!0,requestAnimationFrame(()=>{this._sessionSyncFlushScheduled=!1,this.flushSessionSyncQueue()}))}clearSessionSyncQueue(){this._pendingSessionSync=null,this._sessionSyncFlushScheduled=!1}async flushSessionSyncQueue(){if(!this._sessionSyncFlushInProgress){this._sessionSyncFlushInProgress=!0;try{for(;this._pendingSessionSync;){const e=this._pendingSessionSync;this._pendingSessionSync=null,await this.applySessionSync(e)}}finally{this._sessionSyncFlushInProgress=!1,this._pendingSessionSync&&!this._sessionSyncFlushScheduled&&(this._sessionSyncFlushScheduled=!0,requestAnimationFrame(()=>{this._sessionSyncFlushScheduled=!1,this.flushSessionSyncQueue()}))}}}async applySessionSync(e){const t={op:e.op,...e.op==="full"?{data:e.data,hash:e.hash}:{patches:e.patches,hash:e.hash,baseHash:e.baseHash}};if(t.op==="delta"&&!this._syncHash){console.warn("[ws-adapter] Ignoring delta while awaiting full sync");return}const r=await cat(this._syncJson,this._syncHash,t);if(!r){console.error("[ws-adapter] Sync verification failed, re-subscribing"),this._sessionPath&&(this._syncJson="",this._syncHash="",this.subscribeToSession(this._sessionPath));return}this._syncJson=r.data,this._syncHash=r.hash;let i;try{i=JSON.parse(r.data)}catch{console.error("[ws-adapter] Failed to parse synced state");return}this._state.messages=i.messages??[],this._state.isStreaming=i.isStreaming??!1,this._sessionStatus!=="virtual"&&(this._sessionStatus=this._state.isStreaming?"attached":"detached"),this._pendingToolCallIds=new Set(i.pendingToolCalls??[]),this._state.pendingToolCalls=this._pendingToolCallIds,this._state.streamMessage=null,this._restoreModelFromServer&&(i.model&&(this._state.model=this.findModelMatch(i.model)??this._state.model),i.thinkingLevel&&(this._state.thinkingLevel=i.thinkingLevel),this._restoreModelFromServer=!1),Array.isArray(i.steeringQueue)&&this._sessionPath&&(i.steeringQueue.length>0?this._steeringQueues.set(this._sessionPath,[...i.steeringQueue]):this._steeringQueues.delete(this._sessionPath),this.emitSteeringQueueChange()),i.error?this._state.error=i.error:this._state.error=void 0,this.emitContentChange(),this.emitStatusChange()}updateState(e){switch(e.type){case"agent_start":this._state.isStreaming=!0,this._state.error=void 0,this._runningPromise=new Promise(t=>{this._resolveRunning=t}),this.emitStatusChange();break;case"agent_end":this._state.isStreaming=!1,this._state.streamMessage=null,this._state.pendingToolCalls=new Set,this._pendingToolCallIds.clear(),this._resolveRunning?.(),this._runningPromise=void 0,this._resolveRunning=void 0,this.emitStatusChange();break;case"turn_end":e.message.role==="assistant"&&e.message.errorMessage&&(this._state.error=e.message.errorMessage);break}}send(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return Promise.reject(new Error("WebSocket not connected"));const t=`req_${++this.requestId}`,r=$g(`frontend_ws_command ${e.type}`);return new Promise((i,a)=>{const s=setTimeout(()=>{this.pendingRequests.delete(t),r(),a(new Error(`Timeout waiting for response to ${e.type}`))},3e4);this.pendingRequests.set(t,{resolve:o=>{clearTimeout(s),i(o)},reject:o=>{clearTimeout(s),a(o)},endSpan:r}),this.ws.send(JSON.stringify({...e,id:t,__trace:{traceId:wae()}}))})}async fetchAvailableModels(){const t=(await this.send({type:"get_available_models"}))?.models??[];return this._availableModels=t,t}findModelMatch(e){if(this._availableModels)return this._availableModels.find(t=>t.provider===e.provider&&t.id===e.modelId)}modelSupportsThinking(e){if(!e)return!1;if(typeof e.reasoning=="boolean")return e.reasoning;const t=String(e.provider??"").toLowerCase(),r=String(e.id??"").toLowerCase();return!!(t==="openai-codex"||t==="openai"&&r.startsWith("gpt-5"))}async installPi(){await this.send({type:"install_pi"})}async loadDefaultModel(){if(this._state.model)return;const e=await this.send({type:"get_default_model"});e?.model&&(this._state.model=e.model),e?.thinkingLevel&&(this._state.thinkingLevel=e.thinkingLevel)}setCwd(e){this._pendingCwd=e}get cwd(){return this._pendingCwd}async prompt(e,t){let r;if(typeof e=="string"?r=e:Array.isArray(e)?r=e.map(l=>this.extractText(l)).join(`
|
|
2962
|
+
`})}};Pm([Ge()],Kp.prototype,"headerTitle",void 0);Pm([Ge()],Kp.prototype,"message",void 0);Pm([Ge()],Kp.prototype,"defaultValue",void 0);Pm([Ge()],Kp.prototype,"isPassword",void 0);Pm([lt()],Kp.prototype,"inputValue",void 0);Kp=TO=Pm([sn("prompt-dialog")],Kp);function sat(n=16){const e=new Uint8Array(n);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}const sH="pipane-load-trace-id",sT=(()=>{const n=sessionStorage.getItem(sH);if(n)return n;const e=sat(16);return sessionStorage.setItem(sH,e),e})();function Tae(n,e,t){fetch("/api/debug/load-trace/event",{method:"POST",headers:{"Content-Type":"application/json","x-pi-trace-id":sT},body:JSON.stringify({traceId:sT,name:n,durationMs:e,attrs:t})}).catch(()=>{})}function wae(){return sT}function oT(n,e){Tae(n,void 0,e)}function $g(n,e){const t=performance.now();return()=>{const r=Number((performance.now()-t).toFixed(2));Tae(n,r,e)}}async function MI(n,e={},t){const r=$g(t||`fetch ${typeof n=="string"?n:n.toString()}`),i=new Headers(e.headers||void 0);i.set("x-pi-trace-id",sT);try{return await fetch(n,{...e,headers:i})}finally{r()}}function oat(){const n=performance.getEntriesByType("navigation")[0];n&&oT("navigation_timing",{domInteractive:Number(n.domInteractive.toFixed(2)),domContentLoadedEventEnd:Number(n.domContentLoadedEventEnd.toFixed(2)),loadEventEnd:Number(n.loadEventEnd.toFixed(2)),responseEnd:Number(n.responseEnd.toFixed(2))})}function lat(n){const e=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],t=(g,_)=>g>>>_|g<<32-_,r=new TextEncoder().encode(n),i=r.length*8,a=new Uint8Array(Math.ceil((r.length+9)/64)*64);a.set(r),a[r.length]=128;const s=new DataView(a.buffer);s.setUint32(a.length-4,i,!1),i>4294967295&&s.setUint32(a.length-8,Math.floor(i/4294967296),!1);let[o,l,c,u,d,p,h,f]=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];const m=new Int32Array(64);for(let g=0;g<a.length;g+=64){for(let C=0;C<16;C++)m[C]=s.getInt32(g+C*4,!1);for(let C=16;C<64;C++){const D=t(m[C-15],7)^t(m[C-15],18)^m[C-15]>>>3,N=t(m[C-2],17)^t(m[C-2],19)^m[C-2]>>>10;m[C]=m[C-16]+D+m[C-7]+N|0}let[_,v,b,E,S,w,x,A]=[o,l,c,u,d,p,h,f];for(let C=0;C<64;C++){const D=t(S,6)^t(S,11)^t(S,25),N=S&w^~S&x,O=A+D+N+e[C]+m[C]|0,F=t(_,2)^t(_,13)^t(_,22),k=_&v^_&b^v&b,V=F+k|0;A=x,x=w,w=S,S=E+O|0,E=b,b=v,v=_,_=O+V|0}o=o+_|0,l=l+v|0,c=c+b|0,u=u+E|0,d=d+S|0,p=p+w|0,h=h+x|0,f=f+A|0}return[o,l,c,u,d,p,h,f].map(g=>(g>>>0).toString(16).padStart(8,"0")).join("")}async function oH(n){if(typeof globalThis.crypto?.subtle?.digest=="function"){const e=new TextEncoder().encode(n),t=await globalThis.crypto.subtle.digest("SHA-256",e),r=new Uint8Array(t);return Array.from(r).map(i=>i.toString(16).padStart(2,"0")).join("")}if(typeof globalThis.process<"u"){const{createHash:e}=await _s(async()=>{const{createHash:t}=await import("./_node-stub_node_crypto-C_7epg3G.js").then(r=>r._);return{createHash:t}},[]);return e("sha256").update(n,"utf8").digest("hex")}return lat(n)}function cat(n,e){let t=n;for(const r of e)t=t.slice(0,r.offset)+r.insert+t.slice(r.offset+r.deleteCount);return t}async function uat(n,e,t){if(t.op==="full"){const a=await oH(t.data);return a!==t.hash?(console.error("[jsonl-sync] Full sync hash mismatch",{expected:t.hash,actual:a}),null):{data:t.data,hash:t.hash}}if(t.baseHash!==e)return console.warn("[jsonl-sync] Base hash mismatch, need full sync",{expected:t.baseHash,actual:e}),null;const r=cat(n,t.patches),i=await oH(r);return i!==t.hash?(console.error("[jsonl-sync] Post-patch hash mismatch",{expected:t.hash,actual:i}),null):{data:r,hash:t.hash}}class dat{constructor(){this.ws=null,this.listeners=new Set,this.sessionsChangedListeners=new Set,this.piInstallRequiredListeners=new Set,this.pendingRequests=new Map,this.requestId=0,this._reconnecting=!1,this._reconnectAttempt=0,this._connectionListeners=new Set,this.streamFn=()=>{},this.getApiKey=void 0,this._state={systemPrompt:"",model:void 0,thinkingLevel:"off",tools:[],messages:[],isStreaming:!1,streamMessage:null,pendingToolCalls:new Set,error:void 0},this._pendingToolCallIds=new Set,this._steeringQueues=new Map,this._steeringQueueListeners=new Set,this._restoreModelFromServer=!1,this._availableModels=null,this._sessionId="",this._sessionStatus="virtual",this._optimisticSessions=new Map,this._globalSessionStatus=new Map,this._globalStatusListeners=new Set,this._sessionNonce=0,this._pendingNewPrompt=!1,this._syncJson="",this._syncHash="",this._pendingSessionSync=null,this._sessionSyncFlushScheduled=!1,this._sessionSyncFlushInProgress=!1,this._sessionListeners=new Set,this._contentListeners=new Set,this._statusListeners=new Set}get state(){return this._state}get sessionId(){return this._sessionId}get sessionFile(){return this._sessionPath}get sessionName(){return this._sessionName}get sessionStatus(){return this._sessionStatus}get isConnected(){return this.ws?.readyState===WebSocket.OPEN}get isReconnecting(){return this._reconnecting}onConnectionChange(e){return this._connectionListeners.add(e),()=>this._connectionListeners.delete(e)}emitConnectionChange(e){for(const t of this._connectionListeners)t(e)}get pendingToolCallIds(){return this._pendingToolCallIds}get steeringQueue(){return this._sessionPath?this._steeringQueues.get(this._sessionPath)??[]:[]}getSessionStatus(e){return this._globalSessionStatus.get(e)}onGlobalStatusChange(e){return this._globalStatusListeners.add(e),()=>this._globalStatusListeners.delete(e)}emitGlobalStatusChange(){for(const e of this._globalStatusListeners)e()}setGlobalSessionStatus(e,t){this._globalSessionStatus.set(e,t),this.emitGlobalStatusChange()}setAllSessionStatuses(e){this._globalSessionStatus.clear();for(const[t,r]of Object.entries(e))this._globalSessionStatus.set(t,r);this.emitGlobalStatusChange()}onSteeringQueueChange(e){return this._steeringQueueListeners.add(e),()=>this._steeringQueueListeners.delete(e)}emitSteeringQueueChange(){for(const e of this._steeringQueueListeners)e()}enqueueSteering(e,t){const r=this._steeringQueues.get(e)??[];this._steeringQueues.set(e,[...r,t]),this.emitSteeringQueueChange()}onSessionChange(e){return this._sessionListeners.add(e),()=>this._sessionListeners.delete(e)}emitSessionChange(){for(const e of this._sessionListeners)e()}onContentChange(e){return this._contentListeners.add(e),()=>this._contentListeners.delete(e)}emitContentChange(){for(const e of this._contentListeners)e()}onStatusChange(e){return this._statusListeners.add(e),()=>this._statusListeners.delete(e)}emitStatusChange(){for(const e of this._statusListeners)e()}onSessionsChanged(e){return this.sessionsChangedListeners.add(e),()=>this.sessionsChangedListeners.delete(e)}onPiInstallRequired(e){return this.piInstallRequiredListeners.add(e),()=>this.piInstallRequiredListeners.delete(e)}emitPiInstallRequired(e){for(const t of this.piInstallRequiredListeners)t(e)}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}emit(e){for(const t of this.listeners)t(e)}toErrorMessage(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}reportError(e,t="Request failed"){const r=this.toErrorMessage(e);this._state.error=r,this._state.messages=[...this._state.messages,{role:"assistant",content:[{type:"text",text:`⚠️ ${t}: ${r}`}],timestamp:Date.now()}],this.emitStatusChange(),this.emitContentChange()}async connect(e){this._wsUrl=e,await this.connectWs(e,!1),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.syncStateOnFocus()})}connectWs(e,t){return new Promise((r,i)=>{const a=new WebSocket(e);a.onopen=()=>{this.ws=a,this._reconnecting=!1,this._reconnectAttempt=0,t||(this._sessionStatus="virtual"),console.log(`[ws-adapter] WebSocket ${t?"re":""}connected`),this.emitConnectionChange(!0),t&&this.onReconnected(),r()},a.onerror=()=>{t||i(new Error("WebSocket error"))},a.onclose=()=>{const s=this.ws===a;this.ws===a&&(this.ws=null);for(const[o,l]of this.pendingRequests)l.endSpan?.(),l.reject(new Error("WebSocket disconnected"));this.pendingRequests.clear(),s&&(console.log("[ws-adapter] WebSocket disconnected, will reconnect..."),this.emitConnectionChange(!1)),(t||s)&&this.scheduleReconnect()},a.onmessage=s=>this.handleMessage(s.data)})}scheduleReconnect(){if(this._reconnectTimer)return;this._reconnecting=!0,this._reconnectAttempt++;const e=Math.min(500*Math.pow(2,this._reconnectAttempt-1),1e4);console.log(`[ws-adapter] Reconnecting in ${e}ms (attempt ${this._reconnectAttempt})...`),this._reconnectTimer=setTimeout(async()=>{if(this._reconnectTimer=void 0,!!this._wsUrl)try{await this.connectWs(this._wsUrl,!0)}catch{}},e)}async onReconnected(){this._sessionPath&&this._sessionStatus!=="virtual"&&(this._syncJson="",this._syncHash="",this.subscribeToSession(this._sessionPath)),this.refreshSessionStatuses()}async syncStateOnFocus(){this.refreshSessionStatuses(),this._sessionPath&&this._sessionStatus!=="virtual"&&this.subscribeToSession(this._sessionPath),this._sessionStatus==="detached"&&this._state.isStreaming&&(console.log("[ws-adapter] Tab regained focus: clearing stale streaming state"),this._state.isStreaming=!1,this._state.streamMessage=null,this._state.pendingToolCalls=new Set,this._resolveRunning?.(),this._runningPromise=void 0,this._resolveRunning=void 0,this.emitStatusChange())}async refreshSessionStatuses(){try{const e=await this.send({type:"get_session_statuses"});e?.statuses&&this.setAllSessionStatuses(e.statuses)}catch(e){console.error("Failed to refresh session statuses:",e)}}async subscribeToSession(e){try{await this.send({type:"subscribe_session",sessionPath:e??""})}catch(t){console.error("Failed to subscribe to session:",t)}}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(t.type==="response"&&t.id&&this.pendingRequests.has(t.id)){const i=this.pendingRequests.get(t.id);if(this.pendingRequests.delete(t.id),i.endSpan?.(),t.success)i.resolve(t.data);else{const a=t.error||"Unknown error";this._state.error=a,this.emitStatusChange(),i.reject(new Error(a))}return}if(t.type==="pi_install_required"){this.emitPiInstallRequired({command:t.command||"pi",installable:!!t.installable,installing:!!t.installing,message:t.message||"pi is not available"});return}if(t.type==="init"){if(t.sessionStatuses&&this.setAllSessionStatuses(t.sessionStatuses),t.steeringQueues){this._steeringQueues.clear();for(const[i,a]of Object.entries(t.steeringQueues))a.length>0&&this._steeringQueues.set(i,[...a]);this.emitSteeringQueueChange()}return}if(t.type==="session_status_change"){t.sessionPath&&t.status&&this.setGlobalSessionStatus(t.sessionPath,t.status);return}if(t.type==="session_sync"){if(t.sessionPath!==this._sessionPath)return;this.enqueueSessionSync(t);return}if(t.type==="steering_queue_update"){const i=t.sessionPath;i&&(t.queue&&t.queue.length>0?this._steeringQueues.set(i,[...t.queue]):this._steeringQueues.delete(i),this.emitSteeringQueueChange());return}if(t.type==="session_messages"){t.sessionPath===this._sessionPath&&(this._state.messages=t.messages??[],this._restoreModelFromServer&&(t.model&&(this._state.model=this.findModelMatch(t.model)??this._state.model),t.thinkingLevel&&(this._state.thinkingLevel=t.thinkingLevel),this._restoreModelFromServer=!1),this.emitContentChange());return}if(t.type==="session_attached"){if(t.sessionPath&&this.setGlobalSessionStatus(t.sessionPath,"running"),t.sessionPath===this._sessionPath||this._sessionStatus==="virtual"&&this._pendingNewPrompt){if(this._sessionStatus==="virtual"&&t.sessionPath){this._sessionPath=t.sessionPath;const a=k0.basename(t.sessionPath,".jsonl"),s=a.split("_");this._sessionId=s.length>1?s.slice(1).join("_"):a}this._sessionStatus="attached",this._state.isStreaming=!0,t.sessionPath&&this.subscribeToSession(t.sessionPath),this.emitStatusChange()}if(t.sessionPath&&!this._optimisticSessions.has(t.sessionPath)){const a=new Date().toISOString(),s=k0.basename(t.sessionPath,".jsonl"),o=s.split("_"),l=o.length>1?o.slice(1).join("_"):s;this._optimisticSessions.set(t.sessionPath,{id:l,path:t.sessionPath,cwd:t.cwd||"",created:a,modified:a,lastUserPromptTime:a,messageCount:1,firstMessage:t.firstMessage||"(new session)"})}return}if(t.type==="session_detached"){t.sessionPath&&this.setGlobalSessionStatus(t.sessionPath,"done"),t.sessionPath===this._sessionPath&&(this._sessionStatus="detached",this._state.isStreaming=!1,this._state.streamMessage=null,this._state.pendingToolCalls=new Set,this._pendingToolCallIds.clear(),this._resolveRunning?.(),this._runningPromise=void 0,this._resolveRunning=void 0,this.emitStatusChange());return}if(t.type==="sessions_changed"){const i=t.file;for(const a of this.sessionsChangedListeners)a(i);return}if(t.type==="agent_event"){if(t.sessionPath&&t.sessionPath!==this._sessionPath)return;const i=t.event;this.emit(i);return}if(t.sessionPath&&t.sessionPath!==this._sessionPath)return;const r=t;this.updateState(r),this.emit(r)}enqueueSessionSync(e){const t=this._pendingSessionSync;t?e.op==="full"?this._pendingSessionSync=e:t.op!=="full"&&(this._pendingSessionSync=e):this._pendingSessionSync=e,!(this._sessionSyncFlushScheduled||this._sessionSyncFlushInProgress)&&(this._sessionSyncFlushScheduled=!0,requestAnimationFrame(()=>{this._sessionSyncFlushScheduled=!1,this.flushSessionSyncQueue()}))}clearSessionSyncQueue(){this._pendingSessionSync=null,this._sessionSyncFlushScheduled=!1}async flushSessionSyncQueue(){if(!this._sessionSyncFlushInProgress){this._sessionSyncFlushInProgress=!0;try{for(;this._pendingSessionSync;){const e=this._pendingSessionSync;this._pendingSessionSync=null,await this.applySessionSync(e)}}finally{this._sessionSyncFlushInProgress=!1,this._pendingSessionSync&&!this._sessionSyncFlushScheduled&&(this._sessionSyncFlushScheduled=!0,requestAnimationFrame(()=>{this._sessionSyncFlushScheduled=!1,this.flushSessionSyncQueue()}))}}}async applySessionSync(e){const t={op:e.op,...e.op==="full"?{data:e.data,hash:e.hash}:{patches:e.patches,hash:e.hash,baseHash:e.baseHash}};if(t.op==="delta"&&!this._syncHash){console.warn("[ws-adapter] Ignoring delta while awaiting full sync");return}const r=await uat(this._syncJson,this._syncHash,t);if(!r){console.error("[ws-adapter] Sync verification failed, re-subscribing"),this._sessionPath&&(this._syncJson="",this._syncHash="",this.subscribeToSession(this._sessionPath));return}this._syncJson=r.data,this._syncHash=r.hash;let i;try{i=JSON.parse(r.data)}catch{console.error("[ws-adapter] Failed to parse synced state");return}this._state.messages=i.messages??[],this._state.isStreaming=i.isStreaming??!1,this._sessionStatus!=="virtual"&&(this._sessionStatus=this._state.isStreaming?"attached":"detached"),this._pendingToolCallIds=new Set(i.pendingToolCalls??[]),this._state.pendingToolCalls=this._pendingToolCallIds,this._state.streamMessage=null,this._restoreModelFromServer&&(i.model&&(this._state.model=this.findModelMatch(i.model)??this._state.model),i.thinkingLevel&&(this._state.thinkingLevel=i.thinkingLevel),this._restoreModelFromServer=!1),Array.isArray(i.steeringQueue)&&this._sessionPath&&(i.steeringQueue.length>0?this._steeringQueues.set(this._sessionPath,[...i.steeringQueue]):this._steeringQueues.delete(this._sessionPath),this.emitSteeringQueueChange()),i.error?this._state.error=i.error:this._state.error=void 0,this.emitContentChange(),this.emitStatusChange()}updateState(e){switch(e.type){case"agent_start":this._state.isStreaming=!0,this._state.error=void 0,this._runningPromise=new Promise(t=>{this._resolveRunning=t}),this.emitStatusChange();break;case"agent_end":this._state.isStreaming=!1,this._state.streamMessage=null,this._state.pendingToolCalls=new Set,this._pendingToolCallIds.clear(),this._resolveRunning?.(),this._runningPromise=void 0,this._resolveRunning=void 0,this.emitStatusChange();break;case"turn_end":e.message.role==="assistant"&&e.message.errorMessage&&(this._state.error=e.message.errorMessage);break}}send(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return Promise.reject(new Error("WebSocket not connected"));const t=`req_${++this.requestId}`,r=$g(`frontend_ws_command ${e.type}`);return new Promise((i,a)=>{const s=e.type==="prompt"||e.type==="fork_prompt"?9e4:3e4,o=setTimeout(()=>{this.pendingRequests.delete(t),r(),a(new Error(`Timeout waiting for response to ${e.type}`))},s);this.pendingRequests.set(t,{resolve:l=>{clearTimeout(o),i(l)},reject:l=>{clearTimeout(o),a(l)},endSpan:r}),this.ws.send(JSON.stringify({...e,id:t,__trace:{traceId:wae()}}))})}async fetchAvailableModels(){const t=(await this.send({type:"get_available_models"}))?.models??[];return this._availableModels=t,t}findModelMatch(e){if(this._availableModels)return this._availableModels.find(t=>t.provider===e.provider&&t.id===e.modelId)}modelSupportsThinking(e){if(!e)return!1;if(typeof e.reasoning=="boolean")return e.reasoning;const t=String(e.provider??"").toLowerCase(),r=String(e.id??"").toLowerCase();return!!(t==="openai-codex"||t==="openai"&&r.startsWith("gpt-5"))}async installPi(){await this.send({type:"install_pi"})}async loadDefaultModel(){if(this._state.model)return;const e=await this.send({type:"get_default_model"});e?.model&&(this._state.model=e.model),e?.thinkingLevel&&(this._state.thinkingLevel=e.thinkingLevel)}setCwd(e){this._pendingCwd=e}get cwd(){return this._pendingCwd}async prompt(e,t){let r;if(typeof e=="string"?r=e:Array.isArray(e)?r=e.map(l=>this.extractText(l)).join(`
|
|
2963
2963
|
`):r=this.extractText(e),await this.handleSlashCommand(r))return;if((this._sessionPath?this._globalSessionStatus.get(this._sessionPath)==="running":!1)&&this._sessionPath){this.enqueueSteering(this._sessionPath,r),await this.send({type:"steer",sessionPath:this._sessionPath,message:r});return}const s=this._nextPromptModelOverride??this._state.model;if(!s)throw new Error(`BUG: effective model is undefined when sending prompt. sessionStatus=${this._sessionStatus}, sessionPath=${this._sessionPath}`);const o={provider:s.provider,modelId:s.id};if(this._sessionStatus==="virtual"){this._nextPromptModelOverride=void 0;const l=this._sessionNonce;this._pendingNewPrompt=!0;try{const c=await this.send({type:"prompt",sessionPath:"__new__",cwd:this._pendingCwd,message:r,model:o,thinkingLevel:this._state.thinkingLevel,images:t});if(this._sessionNonce!==l){console.log("[ws-adapter] Discarding stale prompt response (session changed during await)");return}const u=c?.newSessionPath;if(u&&!this._sessionPath){this._sessionPath=u;const d=k0.basename(u,".jsonl"),p=d.split("_");this._sessionId=p.length>1?p.slice(1).join("_"):d,this._sessionStatus="attached",this.subscribeToSession(u),this.emitSessionChange(),this.emitStatusChange()}}finally{this._pendingNewPrompt=!1}return}if(!this._sessionPath)throw new Error("No session loaded");this._nextPromptModelOverride=void 0,await this.send({type:"prompt",sessionPath:this._sessionPath,message:r,model:o,thinkingLevel:this._state.thinkingLevel,images:t})}extractText(e){if("content"in e){if(typeof e.content=="string")return e.content;if(Array.isArray(e.content))return e.content.filter(t=>t.type==="text").map(t=>t.text).join(`
|
|
2964
2964
|
`)}return""}async fetchCommands(){try{return(await this.send({type:"get_commands"}))?.commands??[]}catch{return[]}}async showHelpMessage(){const e=["**Built-in commands:**","","| Command | Description |","|---------|-------------|","| `/help` | Show this help |","| `/new` | Start a new session |","| `/fork` | Fork session from a previous message |","| `/compact [instructions]` | Compact conversation history |","| `/name <name>` | Set session display name |","| `/reload` | Restart all pooled pi RPC processes |"],t=await this.fetchCommands(),r=t.filter(l=>l.source==="extension"),i=t.filter(l=>l.source==="prompt"),a=t.filter(l=>l.source==="skill");if(r.length>0){e.push("","**Extension commands:**","","| Command | Description |","|---------|-------------|");for(const l of r)e.push(`| \`/${l.name}\` | ${l.description||""} |`)}if(i.length>0){e.push("","**Prompt templates:**","","| Command | Description |","|---------|-------------|");for(const l of i){const c=l.location?` *(${l.location})*`:"";e.push(`| \`/${l.name}\` | ${l.description||""}${c} |`)}}if(a.length>0){e.push("","**Skills:**","","| Command | Description |","|---------|-------------|");for(const l of a){const c=l.location?` *(${l.location})*`:"";e.push(`| \`/${l.name}\` | ${l.description||""}${c} |`)}}e.push("","**Keyboard shortcuts:**","","| Shortcut | Action |","|----------|--------|","| `Enter` | Send message (also works during streaming to steer) |","| `Cmd+Enter` | Fork session and send message in the fork |","| `Shift+Enter` | New line |","| `Escape` | Abort current turn |");const o={role:"assistant",content:[{type:"text",text:e.join(`
|
|
2965
|
-
`)}]};this._state.messages=[...this._state.messages,o],this.emitContentChange()}async handleSlashCommand(e){const t=e.trim();if(!t.startsWith("/"))return!1;if(t==="/help")return await this.showHelpMessage(),!0;if(t==="/new")return await this.newSession(),!0;if(t==="/fork")return window.dispatchEvent(new CustomEvent("pi-fork-request")),!0;if(t==="/compact"||t.startsWith("/compact ")){if(!this._sessionPath)return!0;const r=t.startsWith("/compact ")?t.slice(9).trim():void 0;this._state.isStreaming=!0,this._state.messages=[...this._state.messages,{role:"compactionSummary",summary:"",tokensBefore:0,timestamp:Date.now(),_compacting:!0}],this.emitStatusChange(),this.emitContentChange();try{await this.send({type:"compact",sessionPath:this._sessionPath,customInstructions:r})}finally{this._state.isStreaming=!1,this.emitStatusChange()}return await this.subscribeToSession(this._sessionPath),!0}if(t.startsWith("/name ")){const r=t.slice(6).trim();if(!r)return!0;if(!this._sessionPath)return this._state.messages=[...this._state.messages,{role:"assistant",content:[{type:"text",text:"Cannot set name: no active session. Send a message first."}]}],this.emitContentChange(),!0;try{await this.send({type:"set_session_name",sessionPath:this._sessionPath,name:r}),this._sessionName=r,this._state.messages=[...this._state.messages,{role:"assistant",content:[{type:"text",text:`Session renamed to **${r}**`}]}],this.emitContentChange(),this.emitSessionChange()}catch(i){this._state.messages=[...this._state.messages,{role:"assistant",content:[{type:"text",text:`Failed to rename session: ${i?.message||"unknown error"}`}]}],this.emitContentChange()}return!0}if(t==="/reload"){try{const r=await this.send({type:"reload_processes"}),i=r?.killed??0,a=r?.draining??0;this._state.messages=[...this._state.messages,{role:"assistant",content:[{type:"text",text:`Reload requested: killed ${i} idle process(es), draining ${a} running process(es).`}]}],this.emitContentChange()}catch(r){this._state.messages=[...this._state.messages,{role:"assistant",content:[{type:"text",text:`Failed to reload pi processes: ${r?.message||"unknown error"}`}]}],this.emitContentChange()}return!0}return!1}abort(){this._sessionPath&&this.send({type:"abort",sessionPath:this._sessionPath}).catch(()=>{})}steer(e){const t=this.extractText(e);!t||!this._sessionPath||!(this._globalSessionStatus.get(this._sessionPath)==="running")||(this.enqueueSteering(this._sessionPath,t),this.send({type:"steer",sessionPath:this._sessionPath,message:t}).catch(console.error))}removeSteering(e){this._sessionPath&&this.send({type:"remove_steering",sessionPath:this._sessionPath,index:e}).catch(console.error)}setModel(e){this._nextPromptModelOverride=e,this._state.model=e,this._state.thinkingLevel=this.modelSupportsThinking(e)?"medium":"off",this.emitContentChange()}setThinkingLevel(e){this._state.thinkingLevel=e,this.emitContentChange()}setSystemPrompt(e){this._state.systemPrompt=e}setTools(e){this._state.tools=e}async getForkMessages(){if(!this._sessionPath)return[];const e=await MI(`/api/sessions/fork-messages?path=${encodeURIComponent(this._sessionPath)}`,{},"frontend_fetch_fork_messages");if(!e.ok)throw new Error(`Failed to get fork messages: ${e.statusText}`);return(await e.json()).messages??[]}async fork(e){if(!this._sessionPath)throw new Error("No session loaded");const t=await this.send({type:"fork",sessionPath:this._sessionPath,entryId:e});return{text:t?.text??"",cancelled:t?.cancelled??!1,newSessionPath:t?.newSessionPath??null}}async forkAndPrompt(e,t){if(!this._sessionPath||this._sessionStatus==="virtual"){await this.prompt(e,t);return}if(!this._state.model)throw new Error(`BUG: _state.model is undefined when sending fork_prompt. sessionPath=${this._sessionPath}`);const r={provider:this._state.model.provider,modelId:this._state.model.id},i=this._sessionNonce,a=await this.send({type:"fork_prompt",sessionPath:this._sessionPath,message:e,model:r,thinkingLevel:this._state.thinkingLevel,images:t});if(this._sessionNonce!==i){console.log("[ws-adapter] Discarding stale fork_prompt response (session changed during await)");return}if(a?.newSessionPath){this._sessionPath=a.newSessionPath;const s=k0.basename(a.newSessionPath,".jsonl"),o=s.split("_");this._sessionId=o.length>1?o.slice(1).join("_"):s,this.emitSessionChange()}}async listSessions(){const e=await MI("/api/sessions",{},"frontend_fetch_sessions");if(!e.ok)throw new Error(`Failed to list sessions: ${e.statusText}`);const t=await e.json(),r=new Set(t.map(a=>a.path));for(const[a,s]of this._optimisticSessions)if(r.has(a)){const o=t.find(l=>l.path===a);o&&!o.cwd&&s.cwd?o.cwd=s.cwd:this._optimisticSessions.delete(a)}else t.push(s);const i=this.virtualSessionInfo;return i&&!r.has(i.path)&&t.push(i),t}get optimisticSessions(){return Array.from(this._optimisticSessions.values())}async deleteSession(e){const t=await MI("/api/sessions",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!t.ok)throw new Error(`Failed to delete session: ${t.statusText}`)}async switchSession(e){this._sessionNonce++,this._pendingNewPrompt=!1,this._sessionPath=e;const t=k0.basename(e,".jsonl"),r=t.split("_");this._sessionId=r.length>1?r.slice(1).join("_"):t,this._sessionStatus="detached",this._restoreModelFromServer=!0,this._state.messages=[],this._state.isStreaming=!1,this._state.streamMessage=null,this._state.pendingToolCalls=new Set,this._pendingToolCallIds.clear(),this._syncJson="",this._syncHash="",this.clearSessionSyncQueue(),this._state.error=void 0,await this.subscribeToSession(e),this._globalSessionStatus.get(e)==="running"&&(this._sessionStatus="attached",this._state.isStreaming=!0),this.emitSessionChange(),this.emitStatusChange()}async newSession(e){this._sessionNonce++,this._pendingNewPrompt=!1,this._sessionId=crypto.randomUUID(),this._sessionPath=void 0,this._sessionName=void 0,this._sessionStatus="virtual",this._pendingCwd=e,this._state.messages=[],this._state.isStreaming=!1,this._state.streamMessage=null,this._state.pendingToolCalls=new Set,this._pendingToolCallIds.clear(),this._syncJson="",this._syncHash="",this.clearSessionSyncQueue(),this._state.error=void 0,this.subscribeToSession(void 0),this.emitSessionChange(),this.emitStatusChange()}get virtualSessionInfo(){if(this._sessionStatus!=="virtual"||!this._pendingCwd)return;const e=new Date().toISOString();return{id:this._sessionId,path:`__virtual__${this._sessionId}`,cwd:this._pendingCwd,created:e,modified:e,lastUserPromptTime:e,messageCount:0,firstMessage:"(new session)"}}}const k0={basename(n,e){const t=n.split("/").pop()||n;return e&&t.endsWith(e)?t.slice(0,-e.length):t}};class dat{constructor(){this.data=new Map}getStore(e){return this.data.has(e)||this.data.set(e,new Map),this.data.get(e)}async get(e,t){return e==="provider-keys"?"server-managed":this.getStore(e).get(t)??null}async set(e,t,r){this.getStore(e).set(t,r)}async delete(e,t){this.getStore(e).delete(t)}async keys(e,t){const r=this.getStore(e),i=Array.from(r.keys());return t?i.filter(a=>a.startsWith(t)):i}async getAllFromIndex(e,t,r){return[]}async clear(e){this.getStore(e).clear()}async has(e,t){return e==="provider-keys"?!0:this.getStore(e).has(t)}async transaction(e,t,r){const i=this;return r({get:(s,o)=>i.get(s,o),set:(s,o,l)=>i.set(s,o,l),delete:(s,o)=>i.delete(s,o)})}async getQuotaInfo(){return{usage:0,quota:1/0,percent:0}}async requestPersistence(){return!0}}var pat=Object.defineProperty,hat=Object.getOwnPropertyDescriptor,qi=(n,e,t,r)=>{for(var i=r>1?void 0:r?hat(e,t):e,a=n.length-1,s;a>=0;a--)(s=n[a])&&(i=(r?s(e,t,i):s(i))||i);return r&&i&&pat(e,t,i),i};const xae="pipane-pinned-sessions";function fat(){try{const n=localStorage.getItem(xae);if(n)return new Set(JSON.parse(n))}catch{}return new Set}function lH(n){try{localStorage.setItem(xae,JSON.stringify([...n]))}catch{}}let di=class extends vn{constructor(){super(...arguments),this.sessionsPerProject=5,this.sessions=[],this.loading=!0,this.showSkeleton=!1,this.searchQuery="",this.expandedGroups=new Set,this.pinnedSessions=fat(),this.burgerMenuOpen=!1,this.themeSubmenuOpen=!1,this.burgerMenuPos={top:0,left:0},this.showFolderPicker=!1,this.folderPath="~",this.folderDirs=[],this.folderLoading=!1,this._fetchInFlight=!1,this._fetchDirty=!1,this._sessionsChangedDebounceTimer=null,this._skeletonGraceTimer=null,this._burgerPortal=null}connectedCallback(){super.connectedCallback(),this.prefetchedSessions?(this.sessions=this.prefetchedSessions,this.loading=!1,this.prefetchedSessions=void 0):(this._skeletonGraceTimer=setTimeout(()=>{this.loading&&(this.showSkeleton=!0)},300),this.refreshSessions()),this.agent&&(this._lastObservedSessionStatus=this.agent.sessionStatus,this.unsubSessionChange=this.agent.onSessionChange(()=>{this.mergeOptimisticSessions(),this.requestUpdate(),this.refreshSessions()}),this.unsubSessionsChanged=this.agent.onSessionsChanged(()=>{this.mergeOptimisticSessions(),this.debouncedRefreshSessions()}),this.unsubGlobalStatus=this.agent.onGlobalStatusChange(()=>{this.requestUpdate()}),this.unsubStatusChange=this.agent.onStatusChange(()=>{const n=this._lastObservedSessionStatus,e=this.agent.sessionStatus;this._lastObservedSessionStatus=e,e==="attached"&&n!=="attached"&&this.clearSearchFilter()}))}disconnectedCallback(){super.disconnectedCallback(),this.unsubSessionChange?.(),this.unsubSessionsChanged?.(),this.unsubGlobalStatus?.(),this.unsubStatusChange?.(),this._removeBurgerPortal(),this._sessionsChangedDebounceTimer&&(clearTimeout(this._sessionsChangedDebounceTimer),this._sessionsChangedDebounceTimer=null),this._skeletonGraceTimer&&(clearTimeout(this._skeletonGraceTimer),this._skeletonGraceTimer=null)}mergeOptimisticSessions(){const n=this.agent.optimisticSessions,e=this.agent.virtualSessionInfo,t=[...n];if(e&&t.push(e),t.length===0)return;let r=this.sessions.filter(s=>!s.path.startsWith("__virtual__"));const i=new Set(r.map(s=>s.path));let a=r.length!==this.sessions.length;for(const s of t)if(i.has(s.path)){if(s.cwd){const o=r.find(l=>l.path===s.path);o&&!o.cwd&&(o.cwd=s.cwd,a=!0)}}else r=[...r,s],a=!0;a&&(this.sessions=r,this.requestUpdate())}debouncedRefreshSessions(){this._sessionsChangedDebounceTimer&&clearTimeout(this._sessionsChangedDebounceTimer),this._sessionsChangedDebounceTimer=setTimeout(()=>{this._sessionsChangedDebounceTimer=null,this.refreshSessions()},500)}async refreshSessions(){if(this._fetchInFlight){this._fetchDirty=!0;return}this._fetchInFlight=!0,this.sessions.length===0&&(this.loading=!0);try{this.sessions=await this.agent.listSessions()}catch(e){console.error("Failed to load sessions:",e),this.sessions=[]}this.loading=!1,this.showSkeleton=!1,this._skeletonGraceTimer&&(clearTimeout(this._skeletonGraceTimer),this._skeletonGraceTimer=null),this._fetchInFlight=!1,this._fetchDirty&&(this._fetchDirty=!1,this.refreshSessions())}get knownCwds(){const n=new Set;for(const e of this.sessions)e.cwd&&n.add(e.cwd);return Array.from(n).sort()}get filteredGroups(){const n=this.searchQuery.toLowerCase().trim();let e=this.sessions;n&&(e=e.filter(i=>i.name?.toLowerCase().includes(n)||i.firstMessage.toLowerCase().includes(n)||i.cwd.toLowerCase().includes(n)||(i.cwdDisplay?.toLowerCase().includes(n)??!1)));const t=new Map;for(const i of e){const a=i.cwd||"(unknown)";t.has(a)||t.set(a,[]),t.get(a).push(i)}const r=[];for(const[i,a]of t){const s=a[0]?.cwdDisplay||i;r.push({cwd:i,displayCwd:s,label:s,sessions:a})}for(const i of r)i.sessions.sort((a,s)=>{const o=this.agent.getSessionStatus(a.path)==="running",l=this.agent.getSessionStatus(s.path)==="running";if(o&&l){const h=this.getSessionDisplayName(a),f=this.getSessionDisplayName(s);return h.localeCompare(f,void 0,{sensitivity:"base"})}if(o)return-1;if(l)return 1;const c=this.pinnedSessions.has(a.path),u=this.pinnedSessions.has(s.path);if(c&&!u)return-1;if(!c&&u)return 1;const d=a.lastUserPromptTime?new Date(a.lastUserPromptTime).getTime():new Date(a.modified).getTime();return(s.lastUserPromptTime?new Date(s.lastUserPromptTime).getTime():new Date(s.modified).getTime())-d});return r.sort((i,a)=>{const s=l=>{let c=0;for(const u of l.sessions){if(this.agent.getSessionStatus(u.path)==="running")return 1/0;const d=u.lastUserPromptTime?new Date(u.lastUserPromptTime).getTime():new Date(u.modified).getTime();c=Math.max(c,d)}return c},o=s(a)-s(i);return o===0?i.label.localeCompare(a.label,void 0,{sensitivity:"base"}):o}),r}getSessionDisplayName(n){if(n.name)return n.name;const e=n.firstMessage;return!e||e==="(no messages)"?"New session":e.length>100?e.slice(0,100)+"…":e}formatTime(n){const e=new Date(n),r=new Date().getTime()-e.getTime(),i=Math.floor(r/6e4),a=Math.floor(r/36e5),s=Math.floor(r/864e5);return i<1?"just now":i<60?`${i}m ago`:a<24?`${a}h ago`:s<7?`${s}d ago`:e.toLocaleDateString()}async handleSessionClick(n){if(n.id!==this.agent?.sessionId&&!n.path.startsWith("__virtual__")){this.clearSearchFilter(),this.expandedGroups.size>0&&(this.expandedGroups=new Set);try{await this.agent.switchSession(n.path)}catch(e){console.error("Failed to switch session:",e)}}}async handleNewSessionInGroup(n){this.clearSearchFilter();try{await this.agent.newSession(n)}catch(e){console.error("Failed to create new session:",e)}}handleTogglePin(n,e){n.stopPropagation(),n.preventDefault();const t=new Set(this.pinnedSessions);t.has(e.path)?t.delete(e.path):t.add(e.path),this.pinnedSessions=t,lH(t)}async handleDeleteSession(n,e){if(n.stopPropagation(),n.preventDefault(),e.path.startsWith("__virtual__")){this.agent.newSession();return}const t=e.id===this.agent?.sessionId,r=e.name||e.firstMessage||"this session";if(confirm(`Delete "${r.slice(0,60)}"?`)){if(this.sessions=this.sessions.filter(i=>i.path!==e.path),this.pinnedSessions.has(e.path)){const i=new Set(this.pinnedSessions);i.delete(e.path),this.pinnedSessions=i,lH(i)}t&&this.agent.newSession();try{await this.agent.deleteSession(e.path)}catch(i){console.error("Failed to delete session:",i),await this.refreshSessions()}}}handleSearch(n){this.searchQuery=n.target.value}clearSearchFilter(){this.searchQuery&&(this.searchQuery="")}openFolderPicker(){this.showFolderPicker=!0,this.folderPath="~",this.browseTo("~")}closeFolderPicker(){this.showFolderPicker=!1}async browseTo(n){this.folderLoading=!0;try{const e=await fetch(`/api/browse?path=${encodeURIComponent(n)}`);if(!e.ok)throw new Error("Failed to browse");const t=await e.json();this.folderPath=t.path,this.folderDirs=t.dirs}catch(e){console.error("Failed to browse directory:",e),this.folderDirs=[]}this.folderLoading=!1}handleFolderInputChange(n){this.folderPath=n.target.value}handleFolderInputKeydown(n){n.key==="Enter"&&this.browseTo(this.folderPath)}handleFolderClick(n){this.folderPath=n.path,this.browseTo(n.path)}handleFolderSelect(){this.showFolderPicker=!1,this.clearSearchFilter(),this.agent.newSession(this.folderPath)}handleParentFolder(){const n=this.folderPath.replace(/\/[^/]+\/?$/,"")||"/";this.folderPath=n,this.browseTo(n)}closeBurgerMenu(){this.burgerMenuOpen=!1,this.themeSubmenuOpen=!1,this._removeBurgerPortal()}_removeBurgerPortal(){this._burgerPortal&&(this._burgerPortal.remove(),this._burgerPortal=null)}_ensureBurgerPortal(){return this._burgerPortal||(this._burgerPortal=document.createElement("div"),this._burgerPortal.id="burger-menu-portal",document.body.appendChild(this._burgerPortal)),this._burgerPortal}updated(n){super.updated(n),this.burgerMenuOpen&&this.burgerMenu?this._renderBurgerPortal():this._removeBurgerPortal()}_renderBurgerPortal(){if(!this.burgerMenuOpen||!this.burgerMenu)return;const n=this._ensureBurgerPortal(),e=this.burgerMenu,t=$O(),r=ES(),i=this.burgerMenuPos,a=[{id:"default",label:"Legacy"},{id:"gruvbox",label:"Gruvbox"}],s=[{id:"light",label:"Light",icon:"☀️"},{id:"dark",label:"Dark",icon:"🌙"},{id:"system",label:"System",icon:"💻"}],o=Q`
|
|
2965
|
+
`)}]};this._state.messages=[...this._state.messages,o],this.emitContentChange()}async handleSlashCommand(e){const t=e.trim();if(!t.startsWith("/"))return!1;if(t==="/help")return await this.showHelpMessage(),!0;if(t==="/new")return await this.newSession(),!0;if(t==="/fork")return window.dispatchEvent(new CustomEvent("pi-fork-request")),!0;if(t==="/compact"||t.startsWith("/compact ")){if(!this._sessionPath)return!0;const r=t.startsWith("/compact ")?t.slice(9).trim():void 0;this._state.isStreaming=!0,this._state.messages=[...this._state.messages,{role:"compactionSummary",summary:"",tokensBefore:0,timestamp:Date.now(),_compacting:!0}],this.emitStatusChange(),this.emitContentChange();try{await this.send({type:"compact",sessionPath:this._sessionPath,customInstructions:r})}finally{this._state.isStreaming=!1,this.emitStatusChange()}return await this.subscribeToSession(this._sessionPath),!0}if(t.startsWith("/name ")){const r=t.slice(6).trim();if(!r)return!0;if(!this._sessionPath)return this._state.messages=[...this._state.messages,{role:"assistant",content:[{type:"text",text:"Cannot set name: no active session. Send a message first."}]}],this.emitContentChange(),!0;try{await this.send({type:"set_session_name",sessionPath:this._sessionPath,name:r}),this._sessionName=r,this._state.messages=[...this._state.messages,{role:"assistant",content:[{type:"text",text:`Session renamed to **${r}**`}]}],this.emitContentChange(),this.emitSessionChange()}catch(i){this._state.messages=[...this._state.messages,{role:"assistant",content:[{type:"text",text:`Failed to rename session: ${i?.message||"unknown error"}`}]}],this.emitContentChange()}return!0}if(t==="/reload"){try{const r=await this.send({type:"reload_processes"}),i=r?.killed??0,a=r?.draining??0;this._state.messages=[...this._state.messages,{role:"assistant",content:[{type:"text",text:`Reload requested: killed ${i} idle process(es), draining ${a} running process(es).`}]}],this.emitContentChange()}catch(r){this._state.messages=[...this._state.messages,{role:"assistant",content:[{type:"text",text:`Failed to reload pi processes: ${r?.message||"unknown error"}`}]}],this.emitContentChange()}return!0}return!1}abort(){this._sessionPath&&this.send({type:"abort",sessionPath:this._sessionPath}).catch(()=>{})}steer(e){const t=this.extractText(e);!t||!this._sessionPath||!(this._globalSessionStatus.get(this._sessionPath)==="running")||(this.enqueueSteering(this._sessionPath,t),this.send({type:"steer",sessionPath:this._sessionPath,message:t}).catch(console.error))}removeSteering(e){this._sessionPath&&this.send({type:"remove_steering",sessionPath:this._sessionPath,index:e}).catch(console.error)}setModel(e){this._nextPromptModelOverride=e,this._state.model=e,this._state.thinkingLevel=this.modelSupportsThinking(e)?"medium":"off",this.emitContentChange()}setThinkingLevel(e){this._state.thinkingLevel=e,this.emitContentChange()}setSystemPrompt(e){this._state.systemPrompt=e}setTools(e){this._state.tools=e}async getForkMessages(){if(!this._sessionPath)return[];const e=await MI(`/api/sessions/fork-messages?path=${encodeURIComponent(this._sessionPath)}`,{},"frontend_fetch_fork_messages");if(!e.ok)throw new Error(`Failed to get fork messages: ${e.statusText}`);return(await e.json()).messages??[]}async fork(e){if(!this._sessionPath)throw new Error("No session loaded");const t=await this.send({type:"fork",sessionPath:this._sessionPath,entryId:e});return{text:t?.text??"",cancelled:t?.cancelled??!1,newSessionPath:t?.newSessionPath??null}}async forkAndPrompt(e,t){if(!this._sessionPath||this._sessionStatus==="virtual"){await this.prompt(e,t);return}if(!this._state.model)throw new Error(`BUG: _state.model is undefined when sending fork_prompt. sessionPath=${this._sessionPath}`);const r={provider:this._state.model.provider,modelId:this._state.model.id},i=this._sessionNonce,a=await this.send({type:"fork_prompt",sessionPath:this._sessionPath,message:e,model:r,thinkingLevel:this._state.thinkingLevel,images:t});if(this._sessionNonce!==i){console.log("[ws-adapter] Discarding stale fork_prompt response (session changed during await)");return}if(a?.newSessionPath){this._sessionPath=a.newSessionPath;const s=k0.basename(a.newSessionPath,".jsonl"),o=s.split("_");this._sessionId=o.length>1?o.slice(1).join("_"):s,this.emitSessionChange()}}async listSessions(){const e=await MI("/api/sessions",{},"frontend_fetch_sessions");if(!e.ok)throw new Error(`Failed to list sessions: ${e.statusText}`);const t=await e.json(),r=new Set(t.map(a=>a.path));for(const[a,s]of this._optimisticSessions)if(r.has(a)){const o=t.find(l=>l.path===a);o&&!o.cwd&&s.cwd?o.cwd=s.cwd:this._optimisticSessions.delete(a)}else t.push(s);const i=this.virtualSessionInfo;return i&&!r.has(i.path)&&t.push(i),t}get optimisticSessions(){return Array.from(this._optimisticSessions.values())}async deleteSession(e){const t=await MI("/api/sessions",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!t.ok)throw new Error(`Failed to delete session: ${t.statusText}`)}async switchSession(e){this._sessionNonce++,this._pendingNewPrompt=!1,this._sessionPath=e;const t=k0.basename(e,".jsonl"),r=t.split("_");this._sessionId=r.length>1?r.slice(1).join("_"):t,this._sessionStatus="detached",this._restoreModelFromServer=!0,this._state.messages=[],this._state.isStreaming=!1,this._state.streamMessage=null,this._state.pendingToolCalls=new Set,this._pendingToolCallIds.clear(),this._syncJson="",this._syncHash="",this.clearSessionSyncQueue(),this._state.error=void 0,await this.subscribeToSession(e),this._globalSessionStatus.get(e)==="running"&&(this._sessionStatus="attached",this._state.isStreaming=!0),this.emitSessionChange(),this.emitStatusChange()}async newSession(e){this._sessionNonce++,this._pendingNewPrompt=!1,this._sessionId=typeof crypto.randomUUID=="function"?crypto.randomUUID():Array.from(crypto.getRandomValues(new Uint8Array(16))).map(t=>t.toString(16).padStart(2,"0")).join("").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5"),this._sessionPath=void 0,this._sessionName=void 0,this._sessionStatus="virtual",this._pendingCwd=e,this._state.messages=[],this._state.isStreaming=!1,this._state.streamMessage=null,this._state.pendingToolCalls=new Set,this._pendingToolCallIds.clear(),this._syncJson="",this._syncHash="",this.clearSessionSyncQueue(),this._state.error=void 0,this.subscribeToSession(void 0),this.emitSessionChange(),this.emitStatusChange()}get virtualSessionInfo(){if(this._sessionStatus!=="virtual"||!this._pendingCwd)return;const e=new Date().toISOString();return{id:this._sessionId,path:`__virtual__${this._sessionId}`,cwd:this._pendingCwd,created:e,modified:e,lastUserPromptTime:e,messageCount:0,firstMessage:"(new session)"}}}const k0={basename(n,e){const t=n.split("/").pop()||n;return e&&t.endsWith(e)?t.slice(0,-e.length):t}};class pat{constructor(){this.data=new Map}getStore(e){return this.data.has(e)||this.data.set(e,new Map),this.data.get(e)}async get(e,t){return e==="provider-keys"?"server-managed":this.getStore(e).get(t)??null}async set(e,t,r){this.getStore(e).set(t,r)}async delete(e,t){this.getStore(e).delete(t)}async keys(e,t){const r=this.getStore(e),i=Array.from(r.keys());return t?i.filter(a=>a.startsWith(t)):i}async getAllFromIndex(e,t,r){return[]}async clear(e){this.getStore(e).clear()}async has(e,t){return e==="provider-keys"?!0:this.getStore(e).has(t)}async transaction(e,t,r){const i=this;return r({get:(s,o)=>i.get(s,o),set:(s,o,l)=>i.set(s,o,l),delete:(s,o)=>i.delete(s,o)})}async getQuotaInfo(){return{usage:0,quota:1/0,percent:0}}async requestPersistence(){return!0}}var hat=Object.defineProperty,fat=Object.getOwnPropertyDescriptor,qi=(n,e,t,r)=>{for(var i=r>1?void 0:r?fat(e,t):e,a=n.length-1,s;a>=0;a--)(s=n[a])&&(i=(r?s(e,t,i):s(i))||i);return r&&i&&hat(e,t,i),i};const xae="pipane-pinned-sessions";function mat(){try{const n=localStorage.getItem(xae);if(n)return new Set(JSON.parse(n))}catch{}return new Set}function lH(n){try{localStorage.setItem(xae,JSON.stringify([...n]))}catch{}}let di=class extends vn{constructor(){super(...arguments),this.sessionsPerProject=5,this.sessions=[],this.loading=!0,this.showSkeleton=!1,this.searchQuery="",this.expandedGroups=new Set,this.pinnedSessions=mat(),this.burgerMenuOpen=!1,this.themeSubmenuOpen=!1,this.burgerMenuPos={top:0,left:0},this.showFolderPicker=!1,this.folderPath="~",this.folderDirs=[],this.folderLoading=!1,this._fetchInFlight=!1,this._fetchDirty=!1,this._sessionsChangedDebounceTimer=null,this._skeletonGraceTimer=null,this._burgerPortal=null}connectedCallback(){super.connectedCallback(),this.prefetchedSessions?(this.sessions=this.prefetchedSessions,this.loading=!1,this.prefetchedSessions=void 0):(this._skeletonGraceTimer=setTimeout(()=>{this.loading&&(this.showSkeleton=!0)},300),this.refreshSessions()),this.agent&&(this._lastObservedSessionStatus=this.agent.sessionStatus,this.unsubSessionChange=this.agent.onSessionChange(()=>{this.mergeOptimisticSessions(),this.requestUpdate(),this.refreshSessions()}),this.unsubSessionsChanged=this.agent.onSessionsChanged(()=>{this.mergeOptimisticSessions(),this.debouncedRefreshSessions()}),this.unsubGlobalStatus=this.agent.onGlobalStatusChange(()=>{this.requestUpdate()}),this.unsubStatusChange=this.agent.onStatusChange(()=>{const n=this._lastObservedSessionStatus,e=this.agent.sessionStatus;this._lastObservedSessionStatus=e,e==="attached"&&n!=="attached"&&this.clearSearchFilter()}))}disconnectedCallback(){super.disconnectedCallback(),this.unsubSessionChange?.(),this.unsubSessionsChanged?.(),this.unsubGlobalStatus?.(),this.unsubStatusChange?.(),this._removeBurgerPortal(),this._sessionsChangedDebounceTimer&&(clearTimeout(this._sessionsChangedDebounceTimer),this._sessionsChangedDebounceTimer=null),this._skeletonGraceTimer&&(clearTimeout(this._skeletonGraceTimer),this._skeletonGraceTimer=null)}mergeOptimisticSessions(){const n=this.agent.optimisticSessions,e=this.agent.virtualSessionInfo,t=[...n];if(e&&t.push(e),t.length===0)return;let r=this.sessions.filter(s=>!s.path.startsWith("__virtual__"));const i=new Set(r.map(s=>s.path));let a=r.length!==this.sessions.length;for(const s of t)if(i.has(s.path)){if(s.cwd){const o=r.find(l=>l.path===s.path);o&&!o.cwd&&(o.cwd=s.cwd,a=!0)}}else r=[...r,s],a=!0;a&&(this.sessions=r,this.requestUpdate())}debouncedRefreshSessions(){this._sessionsChangedDebounceTimer&&clearTimeout(this._sessionsChangedDebounceTimer),this._sessionsChangedDebounceTimer=setTimeout(()=>{this._sessionsChangedDebounceTimer=null,this.refreshSessions()},500)}async refreshSessions(){if(this._fetchInFlight){this._fetchDirty=!0;return}this._fetchInFlight=!0,this.sessions.length===0&&(this.loading=!0);try{this.sessions=await this.agent.listSessions()}catch(e){console.error("Failed to load sessions:",e),this.sessions=[]}this.loading=!1,this.showSkeleton=!1,this._skeletonGraceTimer&&(clearTimeout(this._skeletonGraceTimer),this._skeletonGraceTimer=null),this._fetchInFlight=!1,this._fetchDirty&&(this._fetchDirty=!1,this.refreshSessions())}get knownCwds(){const n=new Set;for(const e of this.sessions)e.cwd&&n.add(e.cwd);return Array.from(n).sort()}get filteredGroups(){const n=this.searchQuery.toLowerCase().trim();let e=this.sessions;n&&(e=e.filter(i=>i.name?.toLowerCase().includes(n)||i.firstMessage.toLowerCase().includes(n)||i.cwd.toLowerCase().includes(n)||(i.cwdDisplay?.toLowerCase().includes(n)??!1)));const t=new Map;for(const i of e){const a=i.cwd||"(unknown)";t.has(a)||t.set(a,[]),t.get(a).push(i)}const r=[];for(const[i,a]of t){const s=a[0]?.cwdDisplay||i;r.push({cwd:i,displayCwd:s,label:s,sessions:a})}for(const i of r)i.sessions.sort((a,s)=>{const o=this.agent.getSessionStatus(a.path)==="running",l=this.agent.getSessionStatus(s.path)==="running";if(o&&l){const h=this.getSessionDisplayName(a),f=this.getSessionDisplayName(s);return h.localeCompare(f,void 0,{sensitivity:"base"})}if(o)return-1;if(l)return 1;const c=this.pinnedSessions.has(a.path),u=this.pinnedSessions.has(s.path);if(c&&!u)return-1;if(!c&&u)return 1;const d=a.lastUserPromptTime?new Date(a.lastUserPromptTime).getTime():new Date(a.modified).getTime();return(s.lastUserPromptTime?new Date(s.lastUserPromptTime).getTime():new Date(s.modified).getTime())-d});return r.sort((i,a)=>{const s=l=>{let c=0;for(const u of l.sessions){if(this.agent.getSessionStatus(u.path)==="running")return 1/0;const d=u.lastUserPromptTime?new Date(u.lastUserPromptTime).getTime():new Date(u.modified).getTime();c=Math.max(c,d)}return c},o=s(a)-s(i);return o===0?i.label.localeCompare(a.label,void 0,{sensitivity:"base"}):o}),r}getSessionDisplayName(n){if(n.name)return n.name;const e=n.firstMessage;return!e||e==="(no messages)"?"New session":e.length>100?e.slice(0,100)+"…":e}formatTime(n){const e=new Date(n),r=new Date().getTime()-e.getTime(),i=Math.floor(r/6e4),a=Math.floor(r/36e5),s=Math.floor(r/864e5);return i<1?"just now":i<60?`${i}m ago`:a<24?`${a}h ago`:s<7?`${s}d ago`:e.toLocaleDateString()}async handleSessionClick(n){if(n.id!==this.agent?.sessionId&&!n.path.startsWith("__virtual__")){this.clearSearchFilter(),this.expandedGroups.size>0&&(this.expandedGroups=new Set);try{await this.agent.switchSession(n.path)}catch(e){console.error("Failed to switch session:",e)}}}async handleNewSessionInGroup(n){this.clearSearchFilter();try{await this.agent.newSession(n)}catch(e){console.error("Failed to create new session:",e)}}handleTogglePin(n,e){n.stopPropagation(),n.preventDefault();const t=new Set(this.pinnedSessions);t.has(e.path)?t.delete(e.path):t.add(e.path),this.pinnedSessions=t,lH(t)}async handleDeleteSession(n,e){if(n.stopPropagation(),n.preventDefault(),e.path.startsWith("__virtual__")){this.agent.newSession();return}const t=e.id===this.agent?.sessionId,r=e.name||e.firstMessage||"this session";if(confirm(`Delete "${r.slice(0,60)}"?`)){if(this.sessions=this.sessions.filter(i=>i.path!==e.path),this.pinnedSessions.has(e.path)){const i=new Set(this.pinnedSessions);i.delete(e.path),this.pinnedSessions=i,lH(i)}t&&this.agent.newSession();try{await this.agent.deleteSession(e.path)}catch(i){console.error("Failed to delete session:",i),await this.refreshSessions()}}}handleSearch(n){this.searchQuery=n.target.value}clearSearchFilter(){this.searchQuery&&(this.searchQuery="")}openFolderPicker(){this.showFolderPicker=!0,this.folderPath="~",this.browseTo("~")}closeFolderPicker(){this.showFolderPicker=!1}async browseTo(n){this.folderLoading=!0;try{const e=await fetch(`/api/browse?path=${encodeURIComponent(n)}`);if(!e.ok)throw new Error("Failed to browse");const t=await e.json();this.folderPath=t.path,this.folderDirs=t.dirs}catch(e){console.error("Failed to browse directory:",e),this.folderDirs=[]}this.folderLoading=!1}handleFolderInputChange(n){this.folderPath=n.target.value}handleFolderInputKeydown(n){n.key==="Enter"&&this.browseTo(this.folderPath)}handleFolderClick(n){this.folderPath=n.path,this.browseTo(n.path)}handleFolderSelect(){this.showFolderPicker=!1,this.clearSearchFilter(),this.agent.newSession(this.folderPath)}handleParentFolder(){const n=this.folderPath.replace(/\/[^/]+\/?$/,"")||"/";this.folderPath=n,this.browseTo(n)}closeBurgerMenu(){this.burgerMenuOpen=!1,this.themeSubmenuOpen=!1,this._removeBurgerPortal()}_removeBurgerPortal(){this._burgerPortal&&(this._burgerPortal.remove(),this._burgerPortal=null)}_ensureBurgerPortal(){return this._burgerPortal||(this._burgerPortal=document.createElement("div"),this._burgerPortal.id="burger-menu-portal",document.body.appendChild(this._burgerPortal)),this._burgerPortal}updated(n){super.updated(n),this.burgerMenuOpen&&this.burgerMenu?this._renderBurgerPortal():this._removeBurgerPortal()}_renderBurgerPortal(){if(!this.burgerMenuOpen||!this.burgerMenu)return;const n=this._ensureBurgerPortal(),e=this.burgerMenu,t=$O(),r=ES(),i=this.burgerMenuPos,a=[{id:"default",label:"Legacy"},{id:"gruvbox",label:"Gruvbox"}],s=[{id:"light",label:"Light",icon:"☀️"},{id:"dark",label:"Dark",icon:"🌙"},{id:"system",label:"System",icon:"💻"}],o=Q`
|
|
2966
2966
|
<div class="burger-dropdown-backdrop" @click=${()=>this.closeBurgerMenu()}></div>
|
|
2967
2967
|
<div class="burger-dropdown" style="top: ${i.top}px; left: ${i.left}px;">
|
|
2968
2968
|
<button
|
|
@@ -3757,9 +3757,9 @@ ${this.content||""}</pre
|
|
|
3757
3757
|
.folder-picker-actions button:hover {
|
|
3758
3758
|
opacity: 0.9;
|
|
3759
3759
|
}
|
|
3760
|
-
`;qi([Ge({attribute:!1})],di.prototype,"agent",2);qi([Ge({attribute:!1})],di.prototype,"prefetchedSessions",2);qi([Ge({attribute:!1})],di.prototype,"burgerMenu",2);qi([Ge({type:Number,attribute:!1})],di.prototype,"sessionsPerProject",2);qi([lt()],di.prototype,"sessions",2);qi([lt()],di.prototype,"loading",2);qi([lt()],di.prototype,"showSkeleton",2);qi([lt()],di.prototype,"searchQuery",2);qi([lt()],di.prototype,"expandedGroups",2);qi([lt()],di.prototype,"pinnedSessions",2);qi([lt()],di.prototype,"burgerMenuOpen",2);qi([lt()],di.prototype,"themeSubmenuOpen",2);qi([lt()],di.prototype,"burgerMenuPos",2);qi([lt()],di.prototype,"showFolderPicker",2);qi([lt()],di.prototype,"folderPath",2);qi([lt()],di.prototype,"folderDirs",2);qi([lt()],di.prototype,"folderLoading",2);di=qi([sn("session-picker")],di);function mat(n){const e=n.regex,t={begin:/<\/?[A-Za-z_]/,end:">",subLanguage:"xml",relevance:0},r={begin:"^[-\\*]{3,}",end:"$"},i={className:"code",variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{begin:"(~{3,})[^~](.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))",contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},a={className:"bullet",begin:"^[ ]*([*+-]|(\\d+\\.))(?=\\s+)",end:"\\s+",excludeEnd:!0},s={begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:"symbol",begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:"link",begin:/:\s*/,end:/$/,excludeBegin:!0}]},o=/[A-Za-z][A-Za-z0-9+.-]*/,l={variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,relevance:2},{begin:e.concat(/\[.+?\]\(/,o,/:\/\/.*?\)/),relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/},{className:"string",relevance:0,begin:"\\[",end:"\\]",excludeBegin:!0,returnEnd:!0},{className:"link",relevance:0,begin:"\\]\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0},{className:"symbol",relevance:0,begin:"\\]\\[",end:"\\]",excludeBegin:!0,excludeEnd:!0}]},c={className:"strong",contains:[],variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}]},u={className:"emphasis",contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{begin:/_(?![_\s])/,end:/_/,relevance:0}]},d=n.inherit(c,{contains:[]}),p=n.inherit(u,{contains:[]});c.contains.push(p),u.contains.push(d);let h=[t,l];return[c,u,d,p].forEach(_=>{_.contains=_.contains.concat(h)}),h=h.concat(c,u),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:h},{begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n",contains:h}]}]},t,a,c,u,{className:"quote",begin:"^>\\s+",contains:h,end:"$"},i,r,l,s,{scope:"literal",match:/&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/}]}}function gat(n){const e="true false yes no null",t="[\\w#;/?:@&=+$,.~*'()[\\]]+",r={className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},i={className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]},a={className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:"char.escape",relevance:0}]},s={className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[n.BACKSLASH_ESCAPE,i]},o=n.inherit(s,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),p={className:"number",begin:"\\b"+"[0-9]{4}(-[0-9][0-9]){0,2}"+"([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?"+"(\\.[0-9]*)?"+"([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?"+"\\b"},h={end:",",endsWithParent:!0,excludeEnd:!0,keywords:e,relevance:0},f={begin:/\{/,end:/\}/,contains:[h],illegal:"\\n",relevance:0},m={begin:"\\[",end:"\\]",contains:[h],illegal:"\\n",relevance:0},g=[r,{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+t},{className:"type",begin:"!<"+t+">"},{className:"type",begin:"!"+t},{className:"type",begin:"!!"+t},{className:"meta",begin:"&"+n.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+n.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},n.HASH_COMMENT_MODE,{beginKeywords:e,keywords:{literal:e}},p,{className:"number",begin:n.C_NUMBER_RE+"\\b",relevance:0},f,m,a,s],_=[...g];return _.pop(),_.push(o),h.contains=_,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:g}}function _at(n){const a={keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"],literal:["true","false","iota","nil"],built_in:["append","cap","close","complex","copy","imag","len","make","new","panic","print","println","real","recover","delete"]};return{name:"Go",aliases:["golang"],keywords:a,illegal:"</",contains:[n.C_LINE_COMMENT_MODE,n.C_BLOCK_COMMENT_MODE,{className:"string",variants:[n.QUOTE_STRING_MODE,n.APOS_STRING_MODE,{begin:"`",end:"`"}]},{className:"number",variants:[{match:/-?\b0[xX]\.[a-fA-F0-9](_?[a-fA-F0-9])*[pP][+-]?\d(_?\d)*i?/,relevance:0},{match:/-?\b0[xX](_?[a-fA-F0-9])+((\.([a-fA-F0-9](_?[a-fA-F0-9])*)?)?[pP][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b0[oO](_?[0-7])*i?/,relevance:0},{match:/-?\.\d(_?\d)*([eE][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b\d(_?\d)*(\.(\d(_?\d)*)?)?([eE][+-]?\d(_?\d)*)?i?/,relevance:0}]},{begin:/:=/},{className:"function",beginKeywords:"func",end:"\\s*(\\{|$)",excludeEnd:!0,contains:[n.TITLE_MODE,{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:a,illegal:/["']/}]}]}}function vat(n){const e=n.regex,t=/(r#)?/,r=e.concat(t,n.UNDERSCORE_IDENT_RE),i=e.concat(t,n.IDENT_RE),a={className:"title.function.invoke",relevance:0,begin:e.concat(/\b/,/(?!let|for|while|if|else|match\b)/,i,e.lookahead(/\s*\(/))},s="([ui](8|16|32|64|128|size)|f(32|64))?",o=["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","ref","return","self","Self","static","struct","super","trait","true","try","type","typeof","union","unsafe","unsized","use","virtual","where","while","yield"],l=["true","false","Some","None","Ok","Err"],c=["drop ","Copy","Send","Sized","Sync","Drop","Fn","FnMut","FnOnce","ToOwned","Clone","Debug","PartialEq","PartialOrd","Eq","Ord","AsRef","AsMut","Into","From","Default","Iterator","Extend","IntoIterator","DoubleEndedIterator","ExactSizeIterator","SliceConcatExt","ToString","assert!","assert_eq!","bitflags!","bytes!","cfg!","col!","concat!","concat_idents!","debug_assert!","debug_assert_eq!","env!","eprintln!","panic!","file!","format!","format_args!","include_bytes!","include_str!","line!","local_data_key!","module_path!","option_env!","print!","println!","select!","stringify!","try!","unimplemented!","unreachable!","vec!","write!","writeln!","macro_rules!","assert_ne!","debug_assert_ne!"],u=["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f32","f64","str","char","bool","Box","Option","Result","String","Vec"];return{name:"Rust",aliases:["rs"],keywords:{$pattern:n.IDENT_RE+"!?",type:u,keyword:o,literal:l,built_in:c},illegal:"</",contains:[n.C_LINE_COMMENT_MODE,n.COMMENT("/\\*","\\*/",{contains:["self"]}),n.inherit(n.QUOTE_STRING_MODE,{begin:/b?"/,illegal:null}),{className:"symbol",begin:/'[a-zA-Z_][a-zA-Z0-9_]*(?!')/},{scope:"string",variants:[{begin:/b?r(#*)"(.|\n)*?"\1(?!#)/},{begin:/b?'/,end:/'/,contains:[{scope:"char.escape",match:/\\('|\w|x\w{2}|u\w{4}|U\w{8})/}]}]},{className:"number",variants:[{begin:"\\b0b([01_]+)"+s},{begin:"\\b0o([0-7_]+)"+s},{begin:"\\b0x([A-Fa-f0-9_]+)"+s},{begin:"\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)"+s}],relevance:0},{begin:[/fn/,/\s+/,r],className:{1:"keyword",3:"title.function"}},{className:"meta",begin:"#!?\\[",end:"\\]",contains:[{className:"string",begin:/"/,end:/"/,contains:[n.BACKSLASH_ESCAPE]}]},{begin:[/let/,/\s+/,/(?:mut\s+)?/,r],className:{1:"keyword",3:"keyword",4:"variable"}},{begin:[/for/,/\s+/,r,/\s+/,/in/],className:{1:"keyword",3:"variable",5:"keyword"}},{begin:[/type/,/\s+/,r],className:{1:"keyword",3:"title.class"}},{begin:[/(?:trait|enum|struct|union|impl|for)/,/\s+/,r],className:{1:"keyword",3:"title.class"}},{begin:n.IDENT_RE+"::",keywords:{keyword:"Self",built_in:c,type:u}},{className:"punctuation",begin:"->"},a]}}var Zh="[0-9](_*[0-9])*",wE=`\\.(${Zh})`,xE="[0-9a-fA-F](_*[0-9a-fA-F])*",cH={className:"number",variants:[{begin:`(\\b(${Zh})((${wE})|\\.)?|(${wE}))[eE][+-]?(${Zh})[fFdD]?\\b`},{begin:`\\b(${Zh})((${wE})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${wE})[fFdD]?\\b`},{begin:`\\b(${Zh})[fFdD]\\b`},{begin:`\\b0[xX]((${xE})\\.?|(${xE})?\\.(${xE}))[pP][+-]?(${Zh})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${xE})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function Cae(n,e,t){return t===-1?"":n.replace(e,r=>Cae(n,e,t-1))}function bat(n){const e=n.regex,t="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",r=t+Cae("(?:<"+t+"~~~(?:\\s*,\\s*"+t+"~~~)*>)?",/~~~/g,2),l={keyword:["synchronized","abstract","private","var","static","if","const ","for","while","strictfp","finally","protected","import","native","final","void","enum","else","break","transient","catch","instanceof","volatile","case","assert","package","default","public","try","switch","continue","throws","protected","public","private","module","requires","exports","do","sealed","yield","permits","goto","when"],literal:["false","true","null"],type:["char","boolean","long","float","int","byte","short","double"],built_in:["super","this"]},c={className:"meta",begin:"@"+t,contains:[{begin:/\(/,end:/\)/,contains:["self"]}]},u={className:"params",begin:/\(/,end:/\)/,keywords:l,relevance:0,contains:[n.C_BLOCK_COMMENT_MODE],endsParent:!0};return{name:"Java",aliases:["jsp"],keywords:l,illegal:/<\/|#/,contains:[n.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{begin:/\w+@/,relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]}),{begin:/import java\.[a-z]+\./,keywords:"import",relevance:2},n.C_LINE_COMMENT_MODE,n.C_BLOCK_COMMENT_MODE,{begin:/"""/,end:/"""/,className:"string",contains:[n.BACKSLASH_ESCAPE]},n.APOS_STRING_MODE,n.QUOTE_STRING_MODE,{match:[/\b(?:class|interface|enum|extends|implements|new)/,/\s+/,t],className:{1:"keyword",3:"title.class"}},{match:/non-sealed/,scope:"keyword"},{begin:[e.concat(/(?!else)/,t),/\s+/,t,/\s+/,/=(?!=)/],className:{1:"type",3:"variable",5:"operator"}},{begin:[/record/,/\s+/,t],className:{1:"keyword",3:"title.class"},contains:[u,n.C_LINE_COMMENT_MODE,n.C_BLOCK_COMMENT_MODE]},{beginKeywords:"new throw return else",relevance:0},{begin:["(?:"+r+"\\s+)",n.UNDERSCORE_IDENT_RE,/\s*(?=\()/],className:{2:"title.function"},keywords:l,contains:[{className:"params",begin:/\(/,end:/\)/,keywords:l,relevance:0,contains:[c,n.APOS_STRING_MODE,n.QUOTE_STRING_MODE,cH,n.C_BLOCK_COMMENT_MODE]},n.C_LINE_COMMENT_MODE,n.C_BLOCK_COMMENT_MODE]},cH,c]}}function yat(n){const e=n.regex,t=n.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),r="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",s="(?!struct)("+r+"|"+e.optional(i)+"[a-zA-Z_]\\w*"+e.optional("<[^<>]+>")+")",o={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},c={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[n.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},n.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},u={className:"number",variants:[{begin:"[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},d={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},n.inherit(c,{className:"string"}),{className:"string",begin:/<.*?>/},t,n.C_BLOCK_COMMENT_MODE]},p={className:"title",begin:e.optional(i)+n.IDENT_RE,relevance:0},h=e.optional(i)+n.IDENT_RE+"\\s*\\(",f=["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],m=["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"],g=["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"],_=["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"],E={type:m,keyword:f,literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:g},S={className:"function.dispatch",relevance:0,keywords:{_hint:_},begin:e.concat(/\b/,/(?!decltype)/,/(?!if)/,/(?!for)/,/(?!switch)/,/(?!while)/,n.IDENT_RE,e.lookahead(/(<[^<>]+>|)\s*\(/))},w=[S,d,o,t,n.C_BLOCK_COMMENT_MODE,u,c],x={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:E,contains:w.concat([{begin:/\(/,end:/\)/,keywords:E,contains:w.concat(["self"]),relevance:0}]),relevance:0},A={className:"function",begin:"("+s+"[\\*&\\s]+)+"+h,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:E,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:E,relevance:0},{begin:h,returnBegin:!0,contains:[p],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[c,u]},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:E,relevance:0,contains:[t,n.C_BLOCK_COMMENT_MODE,c,u,o,{begin:/\(/,end:/\)/,keywords:E,relevance:0,contains:["self",t,n.C_BLOCK_COMMENT_MODE,c,u,o]}]},o,t,n.C_BLOCK_COMMENT_MODE,d]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:E,illegal:"</",classNameAliases:{"function.dispatch":"built_in"},contains:[].concat(x,A,S,w,[d,{begin:"\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array|tuple|optional|variant|function|flat_map|flat_set)\\s*<(?!<)",end:">",keywords:E,contains:["self",o]},{begin:n.IDENT_RE+"::",keywords:E},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}}function Eat(n){const e=n.regex,t=n.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),r="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",s="("+r+"|"+e.optional(i)+"[a-zA-Z_]\\w*"+e.optional("<[^<>]+>")+")",o={className:"type",variants:[{begin:"\\b[a-z\\d_]*_t\\b"},{match:/\batomic_[a-z]{3,6}\b/}]},c={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[n.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},n.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},u={className:"number",variants:[{match:/\b(0b[01']+)/},{match:/(-?)\b([\d']+(\.[\d']*)?|\.[\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)/},{match:/(-?)\b(0[xX][a-fA-F0-9]+(?:'[a-fA-F0-9]+)*(?:\.[a-fA-F0-9]*(?:'[a-fA-F0-9]*)*)?(?:[pP][-+]?[0-9]+)?(l|L)?(u|U)?)/},{match:/(-?)\b\d+(?:'\d+)*(?:\.\d*(?:'\d*)*)?(?:[eE][-+]?\d+)?/}],relevance:0},d={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef elifdef elifndef include"},contains:[{begin:/\\\n/,relevance:0},n.inherit(c,{className:"string"}),{className:"string",begin:/<.*?>/},t,n.C_BLOCK_COMMENT_MODE]},p={className:"title",begin:e.optional(i)+n.IDENT_RE,relevance:0},h=e.optional(i)+n.IDENT_RE+"\\s*\\(",g={keyword:["asm","auto","break","case","continue","default","do","else","enum","extern","for","fortran","goto","if","inline","register","restrict","return","sizeof","typeof","typeof_unqual","struct","switch","typedef","union","volatile","while","_Alignas","_Alignof","_Atomic","_Generic","_Noreturn","_Static_assert","_Thread_local","alignas","alignof","noreturn","static_assert","thread_local","_Pragma"],type:["float","double","signed","unsigned","int","short","long","char","void","_Bool","_BitInt","_Complex","_Imaginary","_Decimal32","_Decimal64","_Decimal96","_Decimal128","_Decimal64x","_Decimal128x","_Float16","_Float32","_Float64","_Float128","_Float32x","_Float64x","_Float128x","const","static","constexpr","complex","bool","imaginary"],literal:"true false NULL",built_in:"std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr"},_=[d,o,t,n.C_BLOCK_COMMENT_MODE,u,c],v={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:g,contains:_.concat([{begin:/\(/,end:/\)/,keywords:g,contains:_.concat(["self"]),relevance:0}]),relevance:0},b={begin:"("+s+"[\\*&\\s]+)+"+h,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:g,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:g,relevance:0},{begin:h,returnBegin:!0,contains:[n.inherit(p,{className:"title.function"})],relevance:0},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:g,relevance:0,contains:[t,n.C_BLOCK_COMMENT_MODE,c,u,o,{begin:/\(/,end:/\)/,keywords:g,relevance:0,contains:["self",t,n.C_BLOCK_COMMENT_MODE,c,u,o]}]},o,t,n.C_BLOCK_COMMENT_MODE,d]};return{name:"C",aliases:["h"],keywords:g,disableAutodetect:!0,illegal:"</",contains:[].concat(v,b,_,[d,{begin:n.IDENT_RE+"::",keywords:g},{className:"class",beginKeywords:"enum class struct union",end:/[{;:<>=]/,contains:[{beginKeywords:"final class struct"},n.TITLE_MODE]}]),exports:{preprocessor:d,strings:c,keywords:g}}}function Sat(n){const e=n.regex,t="([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)",r=e.either(/\b([A-Z]+[a-z0-9]+)+/,/\b([A-Z]+[a-z0-9]+)+[A-Z]+/),i=e.concat(r,/(::\w+)*/),s={"variable.constant":["__FILE__","__LINE__","__ENCODING__"],"variable.language":["self","super"],keyword:["alias","and","begin","BEGIN","break","case","class","defined","do","else","elsif","end","END","ensure","for","if","in","module","next","not","or","redo","require","rescue","retry","return","then","undef","unless","until","when","while","yield",...["include","extend","prepend","public","private","protected","raise","throw"]],built_in:["proc","lambda","attr_accessor","attr_reader","attr_writer","define_method","private_constant","module_function"],literal:["true","false","nil"]},o={className:"doctag",begin:"@[A-Za-z]+"},l={begin:"#<",end:">"},c=[n.COMMENT("#","$",{contains:[o]}),n.COMMENT("^=begin","^=end",{contains:[o],relevance:10}),n.COMMENT("^__END__",n.MATCH_NOTHING_RE)],u={className:"subst",begin:/#\{/,end:/\}/,keywords:s},d={className:"string",contains:[n.BACKSLASH_ESCAPE,u],variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/`/,end:/`/},{begin:/%[qQwWx]?\(/,end:/\)/},{begin:/%[qQwWx]?\[/,end:/\]/},{begin:/%[qQwWx]?\{/,end:/\}/},{begin:/%[qQwWx]?</,end:/>/},{begin:/%[qQwWx]?\//,end:/\//},{begin:/%[qQwWx]?%/,end:/%/},{begin:/%[qQwWx]?-/,end:/-/},{begin:/%[qQwWx]?\|/,end:/\|/},{begin:/\B\?(\\\d{1,3})/},{begin:/\B\?(\\x[A-Fa-f0-9]{1,2})/},{begin:/\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/},{begin:/\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/},{begin:/\B\?\\(c|C-)[\x20-\x7e]/},{begin:/\B\?\\?\S/},{begin:e.concat(/<<[-~]?'?/,e.lookahead(/(\w+)(?=\W)[^\n]*\n(?:[^\n]*\n)*?\s*\1\b/)),contains:[n.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,contains:[n.BACKSLASH_ESCAPE,u]})]}]},p="[1-9](_?[0-9])*|0",h="[0-9](_?[0-9])*",f={className:"number",relevance:0,variants:[{begin:`\\b(${p})(\\.(${h}))?([eE][+-]?(${h})|r)?i?\\b`},{begin:"\\b0[dD][0-9](_?[0-9])*r?i?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*r?i?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*r?i?\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b"},{begin:"\\b0(_?[0-7])+r?i?\\b"}]},m={variants:[{match:/\(\)/},{className:"params",begin:/\(/,end:/(?=\))/,excludeBegin:!0,endsParent:!0,keywords:s}]},w=[d,{variants:[{match:[/class\s+/,i,/\s+<\s+/,i]},{match:[/\b(class|module)\s+/,i]}],scope:{2:"title.class",4:"title.class.inherited"},keywords:s},{match:[/(include|extend)\s+/,i],scope:{2:"title.class"},keywords:s},{relevance:0,match:[i,/\.new[. (]/],scope:{1:"title.class"}},{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},{relevance:0,match:r,scope:"title.class"},{match:[/def/,/\s+/,t],scope:{1:"keyword",3:"title.function"},contains:[m]},{begin:n.IDENT_RE+"::"},{className:"symbol",begin:n.UNDERSCORE_IDENT_RE+"(!|\\?)?:",relevance:0},{className:"symbol",begin:":(?!\\s)",contains:[d,{begin:t}],relevance:0},f,{className:"variable",begin:"(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])"},{className:"params",begin:/\|(?!=)/,end:/\|/,excludeBegin:!0,excludeEnd:!0,relevance:0,keywords:s},{begin:"("+n.RE_STARTERS_RE+"|unless)\\s*",keywords:"unless",contains:[{className:"regexp",contains:[n.BACKSLASH_ESCAPE,u],illegal:/\n/,variants:[{begin:"/",end:"/[a-z]*"},{begin:/%r\{/,end:/\}[a-z]*/},{begin:"%r\\(",end:"\\)[a-z]*"},{begin:"%r!",end:"![a-z]*"},{begin:"%r\\[",end:"\\][a-z]*"}]}].concat(l,c),relevance:0}].concat(l,c);u.contains=w,m.contains=w;const D=[{begin:/^\s*=>/,starts:{end:"$",contains:w}},{className:"meta.prompt",begin:"^("+"[>?]>"+"|"+"[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]"+"|"+"(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>"+")(?=[ ])",starts:{end:"$",keywords:s,contains:w}}];return c.unshift(l),{name:"Ruby",aliases:["rb","gemspec","podspec","thor","irb"],keywords:s,illegal:/\/\*/,contains:[n.SHEBANG({binary:"ruby"})].concat(D).concat(c).concat(w)}}function Tat(n){const e=n.regex,t=/(?![A-Za-z0-9])(?![$])/,r=e.concat(/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/,t),i=e.concat(/(\\?[A-Z][a-z0-9_\x7f-\xff]+|\\?[A-Z]+(?=[A-Z][a-z0-9_\x7f-\xff])){1,}/,t),a=e.concat(/[A-Z]+/,t),s={scope:"variable",match:"\\$+"+r},o={scope:"meta",variants:[{begin:/<\?php/,relevance:10},{begin:/<\?=/},{begin:/<\?/,relevance:.1},{begin:/\?>/}]},l={scope:"subst",variants:[{begin:/\$\w+/},{begin:/\{\$/,end:/\}/}]},c=n.inherit(n.APOS_STRING_MODE,{illegal:null}),u=n.inherit(n.QUOTE_STRING_MODE,{illegal:null,contains:n.QUOTE_STRING_MODE.contains.concat(l)}),d={begin:/<<<[ \t]*(?:(\w+)|"(\w+)")\n/,end:/[ \t]*(\w+)\b/,contains:n.QUOTE_STRING_MODE.contains.concat(l),"on:begin":(k,V)=>{V.data._beginMatch=k[1]||k[2]},"on:end":(k,V)=>{V.data._beginMatch!==k[1]&&V.ignoreMatch()}},p=n.END_SAME_AS_BEGIN({begin:/<<<[ \t]*'(\w+)'\n/,end:/[ \t]*(\w+)\b/}),h=`[
|
|
3761
|
-
]`,f={scope:"string",variants:[u,c,d,p]},m={scope:"number",variants:[{begin:"\\b0[bB][01]+(?:_[01]+)*\\b"},{begin:"\\b0[oO][0-7]+(?:_[0-7]+)*\\b"},{begin:"\\b0[xX][\\da-fA-F]+(?:_[\\da-fA-F]+)*\\b"},{begin:"(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:[eE][+-]?\\d+)?"}],relevance:0},g=["false","null","true"],_=["__CLASS__","__DIR__","__FILE__","__FUNCTION__","__COMPILER_HALT_OFFSET__","__LINE__","__METHOD__","__NAMESPACE__","__TRAIT__","die","echo","exit","include","include_once","print","require","require_once","array","abstract","and","as","binary","bool","boolean","break","callable","case","catch","class","clone","const","continue","declare","default","do","double","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","enum","eval","extends","final","finally","float","for","foreach","from","global","goto","if","implements","instanceof","insteadof","int","integer","interface","isset","iterable","list","match|0","mixed","new","never","object","or","private","protected","public","readonly","real","return","string","switch","throw","trait","try","unset","use","var","void","while","xor","yield"],v=["Error|0","AppendIterator","ArgumentCountError","ArithmeticError","ArrayIterator","ArrayObject","AssertionError","BadFunctionCallException","BadMethodCallException","CachingIterator","CallbackFilterIterator","CompileError","Countable","DirectoryIterator","DivisionByZeroError","DomainException","EmptyIterator","ErrorException","Exception","FilesystemIterator","FilterIterator","GlobIterator","InfiniteIterator","InvalidArgumentException","IteratorIterator","LengthException","LimitIterator","LogicException","MultipleIterator","NoRewindIterator","OutOfBoundsException","OutOfRangeException","OuterIterator","OverflowException","ParentIterator","ParseError","RangeException","RecursiveArrayIterator","RecursiveCachingIterator","RecursiveCallbackFilterIterator","RecursiveDirectoryIterator","RecursiveFilterIterator","RecursiveIterator","RecursiveIteratorIterator","RecursiveRegexIterator","RecursiveTreeIterator","RegexIterator","RuntimeException","SeekableIterator","SplDoublyLinkedList","SplFileInfo","SplFileObject","SplFixedArray","SplHeap","SplMaxHeap","SplMinHeap","SplObjectStorage","SplObserver","SplPriorityQueue","SplQueue","SplStack","SplSubject","SplTempFileObject","TypeError","UnderflowException","UnexpectedValueException","UnhandledMatchError","ArrayAccess","BackedEnum","Closure","Fiber","Generator","Iterator","IteratorAggregate","Serializable","Stringable","Throwable","Traversable","UnitEnum","WeakReference","WeakMap","Directory","__PHP_Incomplete_Class","parent","php_user_filter","self","static","stdClass"],E={keyword:_,literal:(k=>{const V=[];return k.forEach(de=>{V.push(de),de.toLowerCase()===de?V.push(de.toUpperCase()):V.push(de.toLowerCase())}),V})(g),built_in:v},S=k=>k.map(V=>V.replace(/\|\d+$/,"")),w={variants:[{match:[/new/,e.concat(h,"+"),e.concat("(?!",S(v).join("\\b|"),"\\b)"),i],scope:{1:"keyword",4:"title.class"}}]},x=e.concat(r,"\\b(?!\\()"),A={variants:[{match:[e.concat(/::/,e.lookahead(/(?!class\b)/)),x],scope:{2:"variable.constant"}},{match:[/::/,/class/],scope:{2:"variable.language"}},{match:[i,e.concat(/::/,e.lookahead(/(?!class\b)/)),x],scope:{1:"title.class",3:"variable.constant"}},{match:[i,e.concat("::",e.lookahead(/(?!class\b)/))],scope:{1:"title.class"}},{match:[i,/::/,/class/],scope:{1:"title.class",3:"variable.language"}}]},C={scope:"attr",match:e.concat(r,e.lookahead(":"),e.lookahead(/(?!::)/))},D={relevance:0,begin:/\(/,end:/\)/,keywords:E,contains:[C,s,A,n.C_BLOCK_COMMENT_MODE,f,m,w]},N={relevance:0,match:[/\b/,e.concat("(?!fn\\b|function\\b|",S(_).join("\\b|"),"|",S(v).join("\\b|"),"\\b)"),r,e.concat(h,"*"),e.lookahead(/(?=\()/)],scope:{3:"title.function.invoke"},contains:[D]};D.contains.push(N);const O=[C,A,n.C_BLOCK_COMMENT_MODE,f,m,w],F={begin:e.concat(/#\[\s*\\?/,e.either(i,a)),beginScope:"meta",end:/]/,endScope:"meta",keywords:{literal:g,keyword:["new","array"]},contains:[{begin:/\[/,end:/]/,keywords:{literal:g,keyword:["new","array"]},contains:["self",...O]},...O,{scope:"meta",variants:[{match:i},{match:a}]}]};return{case_insensitive:!1,keywords:E,contains:[F,n.HASH_COMMENT_MODE,n.COMMENT("//","$"),n.COMMENT("/\\*","\\*/",{contains:[{scope:"doctag",match:"@[A-Za-z]+"}]}),{match:/__halt_compiler\(\);/,keywords:"__halt_compiler",starts:{scope:"comment",end:n.MATCH_NOTHING_RE,contains:[{match:/\?>/,scope:"meta",endsParent:!0}]}},o,{scope:"variable.language",match:/\$this\b/},s,N,A,{match:[/const/,/\s/,r],scope:{1:"keyword",3:"variable.constant"}},w,{scope:"function",relevance:0,beginKeywords:"fn function",end:/[;{]/,excludeEnd:!0,illegal:"[$%\\[]",contains:[{beginKeywords:"use"},n.UNDERSCORE_TITLE_MODE,{begin:"=>",endsParent:!0},{scope:"params",begin:"\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0,keywords:E,contains:["self",F,s,A,n.C_BLOCK_COMMENT_MODE,f,m]}]},{scope:"class",variants:[{beginKeywords:"enum",illegal:/[($"]/},{beginKeywords:"class interface trait",illegal:/[:($"]/}],relevance:0,end:/\{/,excludeEnd:!0,contains:[{beginKeywords:"extends implements"},n.UNDERSCORE_TITLE_MODE]},{beginKeywords:"namespace",relevance:0,end:";",illegal:/[.']/,contains:[n.inherit(n.UNDERSCORE_TITLE_MODE,{scope:"title.class"})]},{beginKeywords:"use",relevance:0,end:";",contains:[{match:/\b(as|const|function)\b/,scope:"keyword"},n.UNDERSCORE_TITLE_MODE]},f,m]}}function Aae(n){return n?typeof n=="string"?n:n.source:null}function I0(n){return ur("(?=",n,")")}function ur(...n){return n.map(t=>Aae(t)).join("")}function wat(n){const e=n[n.length-1];return typeof e=="object"&&e.constructor===Object?(n.splice(n.length-1,1),e):{}}function Ua(...n){return"("+(wat(n).capture?"":"?:")+n.map(r=>Aae(r)).join("|")+")"}const RL=n=>ur(/\b/,n,/\w$/.test(n)?/\b/:/\B/),xat=["Protocol","Type"].map(RL),uH=["init","self"].map(RL),Cat=["Any","Self"],LI=["actor","any","associatedtype","async","await",/as\?/,/as!/,"as","borrowing","break","case","catch","class","consume","consuming","continue","convenience","copy","default","defer","deinit","didSet","distributed","do","dynamic","each","else","enum","extension","fallthrough",/fileprivate\(set\)/,"fileprivate","final","for","func","get","guard","if","import","indirect","infix",/init\?/,/init!/,"inout",/internal\(set\)/,"internal","in","is","isolated","nonisolated","lazy","let","macro","mutating","nonmutating",/open\(set\)/,"open","operator","optional","override","package","postfix","precedencegroup","prefix",/private\(set\)/,"private","protocol",/public\(set\)/,"public","repeat","required","rethrows","return","set","some","static","struct","subscript","super","switch","throws","throw",/try\?/,/try!/,"try","typealias",/unowned\(safe\)/,/unowned\(unsafe\)/,"unowned","var","weak","where","while","willSet"],dH=["false","nil","true"],Aat=["assignment","associativity","higherThan","left","lowerThan","none","right"],Rat=["#colorLiteral","#column","#dsohandle","#else","#elseif","#endif","#error","#file","#fileID","#fileLiteral","#filePath","#function","#if","#imageLiteral","#keyPath","#line","#selector","#sourceLocation","#warning"],pH=["abs","all","any","assert","assertionFailure","debugPrint","dump","fatalError","getVaList","isKnownUniquelyReferenced","max","min","numericCast","pointwiseMax","pointwiseMin","precondition","preconditionFailure","print","readLine","repeatElement","sequence","stride","swap","swift_unboxFromSwiftValueWithType","transcode","type","unsafeBitCast","unsafeDowncast","withExtendedLifetime","withUnsafeMutablePointer","withUnsafePointer","withVaList","withoutActuallyEscaping","zip"],Rae=Ua(/[/=\-+!*%<>&|^~?]/,/[\u00A1-\u00A7]/,/[\u00A9\u00AB]/,/[\u00AC\u00AE]/,/[\u00B0\u00B1]/,/[\u00B6\u00BB\u00BF\u00D7\u00F7]/,/[\u2016-\u2017]/,/[\u2020-\u2027]/,/[\u2030-\u203E]/,/[\u2041-\u2053]/,/[\u2055-\u205E]/,/[\u2190-\u23FF]/,/[\u2500-\u2775]/,/[\u2794-\u2BFF]/,/[\u2E00-\u2E7F]/,/[\u3001-\u3003]/,/[\u3008-\u3020]/,/[\u3030]/),kae=Ua(Rae,/[\u0300-\u036F]/,/[\u1DC0-\u1DFF]/,/[\u20D0-\u20FF]/,/[\uFE00-\uFE0F]/,/[\uFE20-\uFE2F]/),FI=ur(Rae,kae,"*"),Iae=Ua(/[a-zA-Z_]/,/[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,/[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,/[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,/[\u1E00-\u1FFF]/,/[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,/[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,/[\u2C00-\u2DFF\u2E80-\u2FFF]/,/[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,/[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,/[\uFE47-\uFEFE\uFF00-\uFFFD]/),lT=Ua(Iae,/\d/,/[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/),Ml=ur(Iae,lT,"*"),CE=ur(/[A-Z]/,lT,"*"),kat=["attached","autoclosure",ur(/convention\(/,Ua("swift","block","c"),/\)/),"discardableResult","dynamicCallable","dynamicMemberLookup","escaping","freestanding","frozen","GKInspectable","IBAction","IBDesignable","IBInspectable","IBOutlet","IBSegueAction","inlinable","main","nonobjc","NSApplicationMain","NSCopying","NSManaged",ur(/objc\(/,Ml,/\)/),"objc","objcMembers","propertyWrapper","requires_stored_property_inits","resultBuilder","Sendable","testable","UIApplicationMain","unchecked","unknown","usableFromInline","warn_unqualified_access"],Iat=["iOS","iOSApplicationExtension","macOS","macOSApplicationExtension","macCatalyst","macCatalystApplicationExtension","watchOS","watchOSApplicationExtension","tvOS","tvOSApplicationExtension","swift"];function Nat(n){const e={match:/\s+/,relevance:0},t=n.COMMENT("/\\*","\\*/",{contains:["self"]}),r=[n.C_LINE_COMMENT_MODE,t],i={match:[/\./,Ua(...xat,...uH)],className:{2:"keyword"}},a={match:ur(/\./,Ua(...LI)),relevance:0},s=LI.filter(ie=>typeof ie=="string").concat(["_|0"]),o=LI.filter(ie=>typeof ie!="string").concat(Cat).map(RL),l={variants:[{className:"keyword",match:Ua(...o,...uH)}]},c={$pattern:Ua(/\b\w+/,/#\w+/),keyword:s.concat(Rat),literal:dH},u=[i,a,l],d={match:ur(/\./,Ua(...pH)),relevance:0},p={className:"built_in",match:ur(/\b/,Ua(...pH),/(?=\()/)},h=[d,p],f={match:/->/,relevance:0},m={className:"operator",relevance:0,variants:[{match:FI},{match:`\\.(\\.|${kae})+`}]},g=[f,m],_="([0-9]_*)+",v="([0-9a-fA-F]_*)+",b={className:"number",relevance:0,variants:[{match:`\\b(${_})(\\.(${_}))?([eE][+-]?(${_}))?\\b`},{match:`\\b0x(${v})(\\.(${v}))?([pP][+-]?(${_}))?\\b`},{match:/\b0o([0-7]_*)+\b/},{match:/\b0b([01]_*)+\b/}]},E=(ie="")=>({className:"subst",variants:[{match:ur(/\\/,ie,/[0\\tnr"']/)},{match:ur(/\\/,ie,/u\{[0-9a-fA-F]{1,8}\}/)}]}),S=(ie="")=>({className:"subst",match:ur(/\\/,ie,/[\t ]*(?:[\r\n]|\r\n)/)}),w=(ie="")=>({className:"subst",label:"interpol",begin:ur(/\\/,ie,/\(/),end:/\)/}),x=(ie="")=>({begin:ur(ie,/"""/),end:ur(/"""/,ie),contains:[E(ie),S(ie),w(ie)]}),A=(ie="")=>({begin:ur(ie,/"/),end:ur(/"/,ie),contains:[E(ie),w(ie)]}),C={className:"string",variants:[x(),x("#"),x("##"),x("###"),A(),A("#"),A("##"),A("###")]},D=[n.BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0,contains:[n.BACKSLASH_ESCAPE]}],N={begin:/\/[^\s](?=[^/\n]*\/)/,end:/\//,contains:D},O=ie=>{const J=ur(ie,/\//),j=ur(/\//,ie);return{begin:J,end:j,contains:[...D,{scope:"comment",begin:`#(?!.*${j})`,end:/$/}]}},F={scope:"regexp",variants:[O("###"),O("##"),O("#"),N]},k={match:ur(/`/,Ml,/`/)},V={className:"variable",match:/\$\d+/},de={className:"variable",match:`\\$${lT}+`},te=[k,V,de],ue={match:/(@|#(un)?)available/,scope:"keyword",starts:{contains:[{begin:/\(/,end:/\)/,keywords:Iat,contains:[...g,b,C]}]}},be={scope:"keyword",match:ur(/@/,Ua(...kat),I0(Ua(/\(/,/\s+/)))},ee={scope:"meta",match:ur(/@/,Ml)},G=[ue,be,ee],U={match:I0(/\b[A-Z]/),relevance:0,contains:[{className:"type",match:ur(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/,lT,"+")},{className:"type",match:CE,relevance:0},{match:/[?!]+/,relevance:0},{match:/\.\.\./,relevance:0},{match:ur(/\s+&\s+/,I0(CE)),relevance:0}]},Z={begin:/</,end:/>/,keywords:c,contains:[...r,...u,...G,f,U]};U.contains.push(Z);const M={match:ur(Ml,/\s*:/),keywords:"_|0",relevance:0},z={begin:/\(/,end:/\)/,relevance:0,keywords:c,contains:["self",M,...r,F,...u,...h,...g,b,C,...te,...G,U]},_e={begin:/</,end:/>/,keywords:"repeat each",contains:[...r,U]},we={begin:Ua(I0(ur(Ml,/\s*:/)),I0(ur(Ml,/\s+/,Ml,/\s*:/))),end:/:/,relevance:0,contains:[{className:"keyword",match:/\b_\b/},{className:"params",match:Ml}]},q={begin:/\(/,end:/\)/,keywords:c,contains:[we,...r,...u,...g,b,C,...G,U,z],endsParent:!0,illegal:/["']/},oe={match:[/(func|macro)/,/\s+/,Ua(k.match,Ml,FI)],className:{1:"keyword",3:"title.function"},contains:[_e,q,e],illegal:[/\[/,/%/]},ae={match:[/\b(?:subscript|init[?!]?)/,/\s*(?=[<(])/],className:{1:"keyword"},contains:[_e,q,e],illegal:/\[|%/},L={match:[/operator/,/\s+/,FI],className:{1:"keyword",3:"title"}},ne={begin:[/precedencegroup/,/\s+/,CE],className:{1:"keyword",3:"title"},contains:[U],keywords:[...Aat,...dH],end:/}/},B={match:[/class\b/,/\s+/,/func\b/,/\s+/,/\b[A-Za-z_][A-Za-z0-9_]*\b/],scope:{1:"keyword",3:"keyword",5:"title.function"}},I={match:[/class\b/,/\s+/,/var\b/],scope:{1:"keyword",3:"keyword"}},he={begin:[/(struct|protocol|class|extension|enum|actor)/,/\s+/,Ml,/\s*/],beginScope:{1:"keyword",3:"title.class"},keywords:c,contains:[_e,...u,{begin:/:/,end:/\{/,keywords:c,contains:[{scope:"title.class.inherited",match:CE},...u],relevance:0}]};for(const ie of C.variants){const J=ie.contains.find(me=>me.label==="interpol");J.keywords=c;const j=[...u,...h,...g,b,C,...te];J.contains=[...j,{begin:/\(/,end:/\)/,contains:["self",...j]}]}return{name:"Swift",keywords:c,contains:[...r,oe,ae,B,I,he,L,ne,{beginKeywords:"import",end:/$/,contains:[...r],relevance:0},F,...u,...h,...g,b,C,...te,...G,U,z]}}var Jh="[0-9](_*[0-9])*",AE=`\\.(${Jh})`,RE="[0-9a-fA-F](_*[0-9a-fA-F])*",Dat={className:"number",variants:[{begin:`(\\b(${Jh})((${AE})|\\.)?|(${AE}))[eE][+-]?(${Jh})[fFdD]?\\b`},{begin:`\\b(${Jh})((${AE})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${AE})[fFdD]?\\b`},{begin:`\\b(${Jh})[fFdD]\\b`},{begin:`\\b0[xX]((${RE})\\.?|(${RE})?\\.(${RE}))[pP][+-]?(${Jh})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${RE})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function Oat(n){const e={keyword:"abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed internal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual",built_in:"Byte Short Char Int Long Boolean Float Double Void Unit Nothing",literal:"true false null"},t={className:"keyword",begin:/\b(break|continue|return|this)\b/,starts:{contains:[{className:"symbol",begin:/@\w+/}]}},r={className:"symbol",begin:n.UNDERSCORE_IDENT_RE+"@"},i={className:"subst",begin:/\$\{/,end:/\}/,contains:[n.C_NUMBER_MODE]},a={className:"variable",begin:"\\$"+n.UNDERSCORE_IDENT_RE},s={className:"string",variants:[{begin:'"""',end:'"""(?=[^"])',contains:[a,i]},{begin:"'",end:"'",illegal:/\n/,contains:[n.BACKSLASH_ESCAPE]},{begin:'"',end:'"',illegal:/\n/,contains:[n.BACKSLASH_ESCAPE,a,i]}]};i.contains.push(s);const o={className:"meta",begin:"@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*"+n.UNDERSCORE_IDENT_RE+")?"},l={className:"meta",begin:"@"+n.UNDERSCORE_IDENT_RE,contains:[{begin:/\(/,end:/\)/,contains:[n.inherit(s,{className:"string"}),"self"]}]},c=Dat,u=n.COMMENT("/\\*","\\*/",{contains:[n.C_BLOCK_COMMENT_MODE]}),d={variants:[{className:"type",begin:n.UNDERSCORE_IDENT_RE},{begin:/\(/,end:/\)/,contains:[]}]},p=d;return p.variants[1].contains=[d],d.variants[1].contains=[p],{name:"Kotlin",aliases:["kt","kts"],keywords:e,contains:[n.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"}]}),n.C_LINE_COMMENT_MODE,u,t,r,o,l,{className:"function",beginKeywords:"fun",end:"[(]|$",returnBegin:!0,excludeEnd:!0,keywords:e,relevance:5,contains:[{begin:n.UNDERSCORE_IDENT_RE+"\\s*\\(",returnBegin:!0,relevance:0,contains:[n.UNDERSCORE_TITLE_MODE]},{className:"type",begin:/</,end:/>/,keywords:"reified",relevance:0},{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:e,relevance:0,contains:[{begin:/:/,end:/[=,\/]/,endsWithParent:!0,contains:[d,n.C_LINE_COMMENT_MODE,u],relevance:0},n.C_LINE_COMMENT_MODE,u,o,l,s,n.C_NUMBER_MODE]},u]},{begin:[/class|interface|trait/,/\s+/,n.UNDERSCORE_IDENT_RE],beginScope:{3:"title.class"},keywords:"class interface trait",end:/[:\{(]|$/,excludeEnd:!0,illegal:"extends implements",contains:[{beginKeywords:"public protected internal private constructor"},n.UNDERSCORE_TITLE_MODE,{className:"type",begin:/</,end:/>/,excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:/[,:]\s*/,end:/[<\(,){\s]|$/,excludeBegin:!0,returnEnd:!0},o,l]},s,{className:"meta",begin:"^#!/usr/bin/env",end:"$",illegal:`
|
|
3762
|
-
`},c]}}const Pat=n=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:n.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[n.APOS_STRING_MODE,n.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:n.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),Mat=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],Lat=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],Fat=[...Mat,...Lat],Uat=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),Bat=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),$at=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),Gat=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();function Wat(n){const e=Pat(n),t=$at,r=Bat,i="@[a-z-]+",a="and or not only",o={className:"variable",begin:"(\\$"+"[a-zA-Z-][a-zA-Z0-9_-]*"+")\\b",relevance:0};return{name:"SCSS",case_insensitive:!0,illegal:"[=/|']",contains:[n.C_LINE_COMMENT_MODE,n.C_BLOCK_COMMENT_MODE,e.CSS_NUMBER_MODE,{className:"selector-id",begin:"#[A-Za-z0-9_-]+",relevance:0},{className:"selector-class",begin:"\\.[A-Za-z0-9_-]+",relevance:0},e.ATTRIBUTE_SELECTOR_MODE,{className:"selector-tag",begin:"\\b("+Fat.join("|")+")\\b",relevance:0},{className:"selector-pseudo",begin:":("+r.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+t.join("|")+")"},o,{begin:/\(/,end:/\)/,contains:[e.CSS_NUMBER_MODE]},e.CSS_VARIABLE,{className:"attribute",begin:"\\b("+Gat.join("|")+")\\b"},{begin:"\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b"},{begin:/:/,end:/[;}{]/,relevance:0,contains:[e.BLOCK_COMMENT,o,e.HEXCOLOR,e.CSS_NUMBER_MODE,n.QUOTE_STRING_MODE,n.APOS_STRING_MODE,e.IMPORTANT,e.FUNCTION_DISPATCH]},{begin:"@(page|font-face)",keywords:{$pattern:i,keyword:"@page @font-face"}},{begin:"@",end:"[{;]",returnBegin:!0,keywords:{$pattern:/[a-z-]+/,keyword:a,attribute:Uat.join(" ")},contains:[{begin:i,className:"keyword"},{begin:/[a-z-]+(?=:)/,className:"attribute"},o,n.QUOTE_STRING_MODE,n.APOS_STRING_MODE,e.HEXCOLOR,e.CSS_NUMBER_MODE]},e.FUNCTION_DISPATCH]}}let Nae="Canvas",Dae="",ib=!1,hS=null,kL=null;const Oae=new Set;function IL(n,e){Nae=n||"Canvas",Dae=e,ib=!0,NL(),kL?.()}function Pae(){ib=!1,NL(),kL?.()}function zat(){return ib}function qat(n,e){hS=n,kL=e,NL()}function Hat(n){if(n.role!=="toolResult"||n.toolName!=="canvas")return null;const e=n.details?.markdown;return e?{title:n.details?.title||"Canvas",markdown:e}:null}function Mae(n,e){return`${n.split("/").pop()||n}:${e}`}function Lae(n){Oae.add(n)}function Vat(n){return Oae.has(n)}function hH(n,e){let t=-1,r=null;for(let i=0;i<n.length;i++){const a=Hat(n[i]);a&&(r=a,t=i)}if(r&&t>=0){if(e){const i=Mae(e,t);if(Vat(i))return;Lae(i)}IL(r.title,r.markdown)}else ib&&Pae()}function NL(){if(!hS)return;if(!ib){ol(Q``,hS);return}const n=Q`
|
|
3760
|
+
`;qi([Ge({attribute:!1})],di.prototype,"agent",2);qi([Ge({attribute:!1})],di.prototype,"prefetchedSessions",2);qi([Ge({attribute:!1})],di.prototype,"burgerMenu",2);qi([Ge({type:Number,attribute:!1})],di.prototype,"sessionsPerProject",2);qi([lt()],di.prototype,"sessions",2);qi([lt()],di.prototype,"loading",2);qi([lt()],di.prototype,"showSkeleton",2);qi([lt()],di.prototype,"searchQuery",2);qi([lt()],di.prototype,"expandedGroups",2);qi([lt()],di.prototype,"pinnedSessions",2);qi([lt()],di.prototype,"burgerMenuOpen",2);qi([lt()],di.prototype,"themeSubmenuOpen",2);qi([lt()],di.prototype,"burgerMenuPos",2);qi([lt()],di.prototype,"showFolderPicker",2);qi([lt()],di.prototype,"folderPath",2);qi([lt()],di.prototype,"folderDirs",2);qi([lt()],di.prototype,"folderLoading",2);di=qi([sn("session-picker")],di);function gat(n){const e=n.regex,t={begin:/<\/?[A-Za-z_]/,end:">",subLanguage:"xml",relevance:0},r={begin:"^[-\\*]{3,}",end:"$"},i={className:"code",variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{begin:"(~{3,})[^~](.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))",contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},a={className:"bullet",begin:"^[ ]*([*+-]|(\\d+\\.))(?=\\s+)",end:"\\s+",excludeEnd:!0},s={begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:"symbol",begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:"link",begin:/:\s*/,end:/$/,excludeBegin:!0}]},o=/[A-Za-z][A-Za-z0-9+.-]*/,l={variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,relevance:2},{begin:e.concat(/\[.+?\]\(/,o,/:\/\/.*?\)/),relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/},{className:"string",relevance:0,begin:"\\[",end:"\\]",excludeBegin:!0,returnEnd:!0},{className:"link",relevance:0,begin:"\\]\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0},{className:"symbol",relevance:0,begin:"\\]\\[",end:"\\]",excludeBegin:!0,excludeEnd:!0}]},c={className:"strong",contains:[],variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}]},u={className:"emphasis",contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{begin:/_(?![_\s])/,end:/_/,relevance:0}]},d=n.inherit(c,{contains:[]}),p=n.inherit(u,{contains:[]});c.contains.push(p),u.contains.push(d);let h=[t,l];return[c,u,d,p].forEach(_=>{_.contains=_.contains.concat(h)}),h=h.concat(c,u),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:h},{begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n",contains:h}]}]},t,a,c,u,{className:"quote",begin:"^>\\s+",contains:h,end:"$"},i,r,l,s,{scope:"literal",match:/&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/}]}}function _at(n){const e="true false yes no null",t="[\\w#;/?:@&=+$,.~*'()[\\]]+",r={className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},i={className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]},a={className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:"char.escape",relevance:0}]},s={className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[n.BACKSLASH_ESCAPE,i]},o=n.inherit(s,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),p={className:"number",begin:"\\b"+"[0-9]{4}(-[0-9][0-9]){0,2}"+"([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?"+"(\\.[0-9]*)?"+"([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?"+"\\b"},h={end:",",endsWithParent:!0,excludeEnd:!0,keywords:e,relevance:0},f={begin:/\{/,end:/\}/,contains:[h],illegal:"\\n",relevance:0},m={begin:"\\[",end:"\\]",contains:[h],illegal:"\\n",relevance:0},g=[r,{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+t},{className:"type",begin:"!<"+t+">"},{className:"type",begin:"!"+t},{className:"type",begin:"!!"+t},{className:"meta",begin:"&"+n.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+n.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},n.HASH_COMMENT_MODE,{beginKeywords:e,keywords:{literal:e}},p,{className:"number",begin:n.C_NUMBER_RE+"\\b",relevance:0},f,m,a,s],_=[...g];return _.pop(),_.push(o),h.contains=_,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:g}}function vat(n){const a={keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"],literal:["true","false","iota","nil"],built_in:["append","cap","close","complex","copy","imag","len","make","new","panic","print","println","real","recover","delete"]};return{name:"Go",aliases:["golang"],keywords:a,illegal:"</",contains:[n.C_LINE_COMMENT_MODE,n.C_BLOCK_COMMENT_MODE,{className:"string",variants:[n.QUOTE_STRING_MODE,n.APOS_STRING_MODE,{begin:"`",end:"`"}]},{className:"number",variants:[{match:/-?\b0[xX]\.[a-fA-F0-9](_?[a-fA-F0-9])*[pP][+-]?\d(_?\d)*i?/,relevance:0},{match:/-?\b0[xX](_?[a-fA-F0-9])+((\.([a-fA-F0-9](_?[a-fA-F0-9])*)?)?[pP][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b0[oO](_?[0-7])*i?/,relevance:0},{match:/-?\.\d(_?\d)*([eE][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b\d(_?\d)*(\.(\d(_?\d)*)?)?([eE][+-]?\d(_?\d)*)?i?/,relevance:0}]},{begin:/:=/},{className:"function",beginKeywords:"func",end:"\\s*(\\{|$)",excludeEnd:!0,contains:[n.TITLE_MODE,{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:a,illegal:/["']/}]}]}}function bat(n){const e=n.regex,t=/(r#)?/,r=e.concat(t,n.UNDERSCORE_IDENT_RE),i=e.concat(t,n.IDENT_RE),a={className:"title.function.invoke",relevance:0,begin:e.concat(/\b/,/(?!let|for|while|if|else|match\b)/,i,e.lookahead(/\s*\(/))},s="([ui](8|16|32|64|128|size)|f(32|64))?",o=["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","ref","return","self","Self","static","struct","super","trait","true","try","type","typeof","union","unsafe","unsized","use","virtual","where","while","yield"],l=["true","false","Some","None","Ok","Err"],c=["drop ","Copy","Send","Sized","Sync","Drop","Fn","FnMut","FnOnce","ToOwned","Clone","Debug","PartialEq","PartialOrd","Eq","Ord","AsRef","AsMut","Into","From","Default","Iterator","Extend","IntoIterator","DoubleEndedIterator","ExactSizeIterator","SliceConcatExt","ToString","assert!","assert_eq!","bitflags!","bytes!","cfg!","col!","concat!","concat_idents!","debug_assert!","debug_assert_eq!","env!","eprintln!","panic!","file!","format!","format_args!","include_bytes!","include_str!","line!","local_data_key!","module_path!","option_env!","print!","println!","select!","stringify!","try!","unimplemented!","unreachable!","vec!","write!","writeln!","macro_rules!","assert_ne!","debug_assert_ne!"],u=["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f32","f64","str","char","bool","Box","Option","Result","String","Vec"];return{name:"Rust",aliases:["rs"],keywords:{$pattern:n.IDENT_RE+"!?",type:u,keyword:o,literal:l,built_in:c},illegal:"</",contains:[n.C_LINE_COMMENT_MODE,n.COMMENT("/\\*","\\*/",{contains:["self"]}),n.inherit(n.QUOTE_STRING_MODE,{begin:/b?"/,illegal:null}),{className:"symbol",begin:/'[a-zA-Z_][a-zA-Z0-9_]*(?!')/},{scope:"string",variants:[{begin:/b?r(#*)"(.|\n)*?"\1(?!#)/},{begin:/b?'/,end:/'/,contains:[{scope:"char.escape",match:/\\('|\w|x\w{2}|u\w{4}|U\w{8})/}]}]},{className:"number",variants:[{begin:"\\b0b([01_]+)"+s},{begin:"\\b0o([0-7_]+)"+s},{begin:"\\b0x([A-Fa-f0-9_]+)"+s},{begin:"\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)"+s}],relevance:0},{begin:[/fn/,/\s+/,r],className:{1:"keyword",3:"title.function"}},{className:"meta",begin:"#!?\\[",end:"\\]",contains:[{className:"string",begin:/"/,end:/"/,contains:[n.BACKSLASH_ESCAPE]}]},{begin:[/let/,/\s+/,/(?:mut\s+)?/,r],className:{1:"keyword",3:"keyword",4:"variable"}},{begin:[/for/,/\s+/,r,/\s+/,/in/],className:{1:"keyword",3:"variable",5:"keyword"}},{begin:[/type/,/\s+/,r],className:{1:"keyword",3:"title.class"}},{begin:[/(?:trait|enum|struct|union|impl|for)/,/\s+/,r],className:{1:"keyword",3:"title.class"}},{begin:n.IDENT_RE+"::",keywords:{keyword:"Self",built_in:c,type:u}},{className:"punctuation",begin:"->"},a]}}var Zh="[0-9](_*[0-9])*",wE=`\\.(${Zh})`,xE="[0-9a-fA-F](_*[0-9a-fA-F])*",cH={className:"number",variants:[{begin:`(\\b(${Zh})((${wE})|\\.)?|(${wE}))[eE][+-]?(${Zh})[fFdD]?\\b`},{begin:`\\b(${Zh})((${wE})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${wE})[fFdD]?\\b`},{begin:`\\b(${Zh})[fFdD]\\b`},{begin:`\\b0[xX]((${xE})\\.?|(${xE})?\\.(${xE}))[pP][+-]?(${Zh})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${xE})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function Cae(n,e,t){return t===-1?"":n.replace(e,r=>Cae(n,e,t-1))}function yat(n){const e=n.regex,t="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",r=t+Cae("(?:<"+t+"~~~(?:\\s*,\\s*"+t+"~~~)*>)?",/~~~/g,2),l={keyword:["synchronized","abstract","private","var","static","if","const ","for","while","strictfp","finally","protected","import","native","final","void","enum","else","break","transient","catch","instanceof","volatile","case","assert","package","default","public","try","switch","continue","throws","protected","public","private","module","requires","exports","do","sealed","yield","permits","goto","when"],literal:["false","true","null"],type:["char","boolean","long","float","int","byte","short","double"],built_in:["super","this"]},c={className:"meta",begin:"@"+t,contains:[{begin:/\(/,end:/\)/,contains:["self"]}]},u={className:"params",begin:/\(/,end:/\)/,keywords:l,relevance:0,contains:[n.C_BLOCK_COMMENT_MODE],endsParent:!0};return{name:"Java",aliases:["jsp"],keywords:l,illegal:/<\/|#/,contains:[n.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{begin:/\w+@/,relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]}),{begin:/import java\.[a-z]+\./,keywords:"import",relevance:2},n.C_LINE_COMMENT_MODE,n.C_BLOCK_COMMENT_MODE,{begin:/"""/,end:/"""/,className:"string",contains:[n.BACKSLASH_ESCAPE]},n.APOS_STRING_MODE,n.QUOTE_STRING_MODE,{match:[/\b(?:class|interface|enum|extends|implements|new)/,/\s+/,t],className:{1:"keyword",3:"title.class"}},{match:/non-sealed/,scope:"keyword"},{begin:[e.concat(/(?!else)/,t),/\s+/,t,/\s+/,/=(?!=)/],className:{1:"type",3:"variable",5:"operator"}},{begin:[/record/,/\s+/,t],className:{1:"keyword",3:"title.class"},contains:[u,n.C_LINE_COMMENT_MODE,n.C_BLOCK_COMMENT_MODE]},{beginKeywords:"new throw return else",relevance:0},{begin:["(?:"+r+"\\s+)",n.UNDERSCORE_IDENT_RE,/\s*(?=\()/],className:{2:"title.function"},keywords:l,contains:[{className:"params",begin:/\(/,end:/\)/,keywords:l,relevance:0,contains:[c,n.APOS_STRING_MODE,n.QUOTE_STRING_MODE,cH,n.C_BLOCK_COMMENT_MODE]},n.C_LINE_COMMENT_MODE,n.C_BLOCK_COMMENT_MODE]},cH,c]}}function Eat(n){const e=n.regex,t=n.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),r="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",s="(?!struct)("+r+"|"+e.optional(i)+"[a-zA-Z_]\\w*"+e.optional("<[^<>]+>")+")",o={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},c={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[n.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},n.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},u={className:"number",variants:[{begin:"[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},d={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},n.inherit(c,{className:"string"}),{className:"string",begin:/<.*?>/},t,n.C_BLOCK_COMMENT_MODE]},p={className:"title",begin:e.optional(i)+n.IDENT_RE,relevance:0},h=e.optional(i)+n.IDENT_RE+"\\s*\\(",f=["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],m=["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"],g=["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"],_=["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"],E={type:m,keyword:f,literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:g},S={className:"function.dispatch",relevance:0,keywords:{_hint:_},begin:e.concat(/\b/,/(?!decltype)/,/(?!if)/,/(?!for)/,/(?!switch)/,/(?!while)/,n.IDENT_RE,e.lookahead(/(<[^<>]+>|)\s*\(/))},w=[S,d,o,t,n.C_BLOCK_COMMENT_MODE,u,c],x={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:E,contains:w.concat([{begin:/\(/,end:/\)/,keywords:E,contains:w.concat(["self"]),relevance:0}]),relevance:0},A={className:"function",begin:"("+s+"[\\*&\\s]+)+"+h,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:E,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:E,relevance:0},{begin:h,returnBegin:!0,contains:[p],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[c,u]},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:E,relevance:0,contains:[t,n.C_BLOCK_COMMENT_MODE,c,u,o,{begin:/\(/,end:/\)/,keywords:E,relevance:0,contains:["self",t,n.C_BLOCK_COMMENT_MODE,c,u,o]}]},o,t,n.C_BLOCK_COMMENT_MODE,d]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:E,illegal:"</",classNameAliases:{"function.dispatch":"built_in"},contains:[].concat(x,A,S,w,[d,{begin:"\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array|tuple|optional|variant|function|flat_map|flat_set)\\s*<(?!<)",end:">",keywords:E,contains:["self",o]},{begin:n.IDENT_RE+"::",keywords:E},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}}function Sat(n){const e=n.regex,t=n.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),r="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",s="("+r+"|"+e.optional(i)+"[a-zA-Z_]\\w*"+e.optional("<[^<>]+>")+")",o={className:"type",variants:[{begin:"\\b[a-z\\d_]*_t\\b"},{match:/\batomic_[a-z]{3,6}\b/}]},c={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[n.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},n.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},u={className:"number",variants:[{match:/\b(0b[01']+)/},{match:/(-?)\b([\d']+(\.[\d']*)?|\.[\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)/},{match:/(-?)\b(0[xX][a-fA-F0-9]+(?:'[a-fA-F0-9]+)*(?:\.[a-fA-F0-9]*(?:'[a-fA-F0-9]*)*)?(?:[pP][-+]?[0-9]+)?(l|L)?(u|U)?)/},{match:/(-?)\b\d+(?:'\d+)*(?:\.\d*(?:'\d*)*)?(?:[eE][-+]?\d+)?/}],relevance:0},d={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef elifdef elifndef include"},contains:[{begin:/\\\n/,relevance:0},n.inherit(c,{className:"string"}),{className:"string",begin:/<.*?>/},t,n.C_BLOCK_COMMENT_MODE]},p={className:"title",begin:e.optional(i)+n.IDENT_RE,relevance:0},h=e.optional(i)+n.IDENT_RE+"\\s*\\(",g={keyword:["asm","auto","break","case","continue","default","do","else","enum","extern","for","fortran","goto","if","inline","register","restrict","return","sizeof","typeof","typeof_unqual","struct","switch","typedef","union","volatile","while","_Alignas","_Alignof","_Atomic","_Generic","_Noreturn","_Static_assert","_Thread_local","alignas","alignof","noreturn","static_assert","thread_local","_Pragma"],type:["float","double","signed","unsigned","int","short","long","char","void","_Bool","_BitInt","_Complex","_Imaginary","_Decimal32","_Decimal64","_Decimal96","_Decimal128","_Decimal64x","_Decimal128x","_Float16","_Float32","_Float64","_Float128","_Float32x","_Float64x","_Float128x","const","static","constexpr","complex","bool","imaginary"],literal:"true false NULL",built_in:"std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr"},_=[d,o,t,n.C_BLOCK_COMMENT_MODE,u,c],v={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:g,contains:_.concat([{begin:/\(/,end:/\)/,keywords:g,contains:_.concat(["self"]),relevance:0}]),relevance:0},b={begin:"("+s+"[\\*&\\s]+)+"+h,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:g,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:g,relevance:0},{begin:h,returnBegin:!0,contains:[n.inherit(p,{className:"title.function"})],relevance:0},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:g,relevance:0,contains:[t,n.C_BLOCK_COMMENT_MODE,c,u,o,{begin:/\(/,end:/\)/,keywords:g,relevance:0,contains:["self",t,n.C_BLOCK_COMMENT_MODE,c,u,o]}]},o,t,n.C_BLOCK_COMMENT_MODE,d]};return{name:"C",aliases:["h"],keywords:g,disableAutodetect:!0,illegal:"</",contains:[].concat(v,b,_,[d,{begin:n.IDENT_RE+"::",keywords:g},{className:"class",beginKeywords:"enum class struct union",end:/[{;:<>=]/,contains:[{beginKeywords:"final class struct"},n.TITLE_MODE]}]),exports:{preprocessor:d,strings:c,keywords:g}}}function Tat(n){const e=n.regex,t="([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)",r=e.either(/\b([A-Z]+[a-z0-9]+)+/,/\b([A-Z]+[a-z0-9]+)+[A-Z]+/),i=e.concat(r,/(::\w+)*/),s={"variable.constant":["__FILE__","__LINE__","__ENCODING__"],"variable.language":["self","super"],keyword:["alias","and","begin","BEGIN","break","case","class","defined","do","else","elsif","end","END","ensure","for","if","in","module","next","not","or","redo","require","rescue","retry","return","then","undef","unless","until","when","while","yield",...["include","extend","prepend","public","private","protected","raise","throw"]],built_in:["proc","lambda","attr_accessor","attr_reader","attr_writer","define_method","private_constant","module_function"],literal:["true","false","nil"]},o={className:"doctag",begin:"@[A-Za-z]+"},l={begin:"#<",end:">"},c=[n.COMMENT("#","$",{contains:[o]}),n.COMMENT("^=begin","^=end",{contains:[o],relevance:10}),n.COMMENT("^__END__",n.MATCH_NOTHING_RE)],u={className:"subst",begin:/#\{/,end:/\}/,keywords:s},d={className:"string",contains:[n.BACKSLASH_ESCAPE,u],variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/`/,end:/`/},{begin:/%[qQwWx]?\(/,end:/\)/},{begin:/%[qQwWx]?\[/,end:/\]/},{begin:/%[qQwWx]?\{/,end:/\}/},{begin:/%[qQwWx]?</,end:/>/},{begin:/%[qQwWx]?\//,end:/\//},{begin:/%[qQwWx]?%/,end:/%/},{begin:/%[qQwWx]?-/,end:/-/},{begin:/%[qQwWx]?\|/,end:/\|/},{begin:/\B\?(\\\d{1,3})/},{begin:/\B\?(\\x[A-Fa-f0-9]{1,2})/},{begin:/\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/},{begin:/\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/},{begin:/\B\?\\(c|C-)[\x20-\x7e]/},{begin:/\B\?\\?\S/},{begin:e.concat(/<<[-~]?'?/,e.lookahead(/(\w+)(?=\W)[^\n]*\n(?:[^\n]*\n)*?\s*\1\b/)),contains:[n.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,contains:[n.BACKSLASH_ESCAPE,u]})]}]},p="[1-9](_?[0-9])*|0",h="[0-9](_?[0-9])*",f={className:"number",relevance:0,variants:[{begin:`\\b(${p})(\\.(${h}))?([eE][+-]?(${h})|r)?i?\\b`},{begin:"\\b0[dD][0-9](_?[0-9])*r?i?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*r?i?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*r?i?\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b"},{begin:"\\b0(_?[0-7])+r?i?\\b"}]},m={variants:[{match:/\(\)/},{className:"params",begin:/\(/,end:/(?=\))/,excludeBegin:!0,endsParent:!0,keywords:s}]},w=[d,{variants:[{match:[/class\s+/,i,/\s+<\s+/,i]},{match:[/\b(class|module)\s+/,i]}],scope:{2:"title.class",4:"title.class.inherited"},keywords:s},{match:[/(include|extend)\s+/,i],scope:{2:"title.class"},keywords:s},{relevance:0,match:[i,/\.new[. (]/],scope:{1:"title.class"}},{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},{relevance:0,match:r,scope:"title.class"},{match:[/def/,/\s+/,t],scope:{1:"keyword",3:"title.function"},contains:[m]},{begin:n.IDENT_RE+"::"},{className:"symbol",begin:n.UNDERSCORE_IDENT_RE+"(!|\\?)?:",relevance:0},{className:"symbol",begin:":(?!\\s)",contains:[d,{begin:t}],relevance:0},f,{className:"variable",begin:"(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])"},{className:"params",begin:/\|(?!=)/,end:/\|/,excludeBegin:!0,excludeEnd:!0,relevance:0,keywords:s},{begin:"("+n.RE_STARTERS_RE+"|unless)\\s*",keywords:"unless",contains:[{className:"regexp",contains:[n.BACKSLASH_ESCAPE,u],illegal:/\n/,variants:[{begin:"/",end:"/[a-z]*"},{begin:/%r\{/,end:/\}[a-z]*/},{begin:"%r\\(",end:"\\)[a-z]*"},{begin:"%r!",end:"![a-z]*"},{begin:"%r\\[",end:"\\][a-z]*"}]}].concat(l,c),relevance:0}].concat(l,c);u.contains=w,m.contains=w;const D=[{begin:/^\s*=>/,starts:{end:"$",contains:w}},{className:"meta.prompt",begin:"^("+"[>?]>"+"|"+"[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]"+"|"+"(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>"+")(?=[ ])",starts:{end:"$",keywords:s,contains:w}}];return c.unshift(l),{name:"Ruby",aliases:["rb","gemspec","podspec","thor","irb"],keywords:s,illegal:/\/\*/,contains:[n.SHEBANG({binary:"ruby"})].concat(D).concat(c).concat(w)}}function wat(n){const e=n.regex,t=/(?![A-Za-z0-9])(?![$])/,r=e.concat(/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/,t),i=e.concat(/(\\?[A-Z][a-z0-9_\x7f-\xff]+|\\?[A-Z]+(?=[A-Z][a-z0-9_\x7f-\xff])){1,}/,t),a=e.concat(/[A-Z]+/,t),s={scope:"variable",match:"\\$+"+r},o={scope:"meta",variants:[{begin:/<\?php/,relevance:10},{begin:/<\?=/},{begin:/<\?/,relevance:.1},{begin:/\?>/}]},l={scope:"subst",variants:[{begin:/\$\w+/},{begin:/\{\$/,end:/\}/}]},c=n.inherit(n.APOS_STRING_MODE,{illegal:null}),u=n.inherit(n.QUOTE_STRING_MODE,{illegal:null,contains:n.QUOTE_STRING_MODE.contains.concat(l)}),d={begin:/<<<[ \t]*(?:(\w+)|"(\w+)")\n/,end:/[ \t]*(\w+)\b/,contains:n.QUOTE_STRING_MODE.contains.concat(l),"on:begin":(k,V)=>{V.data._beginMatch=k[1]||k[2]},"on:end":(k,V)=>{V.data._beginMatch!==k[1]&&V.ignoreMatch()}},p=n.END_SAME_AS_BEGIN({begin:/<<<[ \t]*'(\w+)'\n/,end:/[ \t]*(\w+)\b/}),h=`[
|
|
3761
|
+
]`,f={scope:"string",variants:[u,c,d,p]},m={scope:"number",variants:[{begin:"\\b0[bB][01]+(?:_[01]+)*\\b"},{begin:"\\b0[oO][0-7]+(?:_[0-7]+)*\\b"},{begin:"\\b0[xX][\\da-fA-F]+(?:_[\\da-fA-F]+)*\\b"},{begin:"(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:[eE][+-]?\\d+)?"}],relevance:0},g=["false","null","true"],_=["__CLASS__","__DIR__","__FILE__","__FUNCTION__","__COMPILER_HALT_OFFSET__","__LINE__","__METHOD__","__NAMESPACE__","__TRAIT__","die","echo","exit","include","include_once","print","require","require_once","array","abstract","and","as","binary","bool","boolean","break","callable","case","catch","class","clone","const","continue","declare","default","do","double","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","enum","eval","extends","final","finally","float","for","foreach","from","global","goto","if","implements","instanceof","insteadof","int","integer","interface","isset","iterable","list","match|0","mixed","new","never","object","or","private","protected","public","readonly","real","return","string","switch","throw","trait","try","unset","use","var","void","while","xor","yield"],v=["Error|0","AppendIterator","ArgumentCountError","ArithmeticError","ArrayIterator","ArrayObject","AssertionError","BadFunctionCallException","BadMethodCallException","CachingIterator","CallbackFilterIterator","CompileError","Countable","DirectoryIterator","DivisionByZeroError","DomainException","EmptyIterator","ErrorException","Exception","FilesystemIterator","FilterIterator","GlobIterator","InfiniteIterator","InvalidArgumentException","IteratorIterator","LengthException","LimitIterator","LogicException","MultipleIterator","NoRewindIterator","OutOfBoundsException","OutOfRangeException","OuterIterator","OverflowException","ParentIterator","ParseError","RangeException","RecursiveArrayIterator","RecursiveCachingIterator","RecursiveCallbackFilterIterator","RecursiveDirectoryIterator","RecursiveFilterIterator","RecursiveIterator","RecursiveIteratorIterator","RecursiveRegexIterator","RecursiveTreeIterator","RegexIterator","RuntimeException","SeekableIterator","SplDoublyLinkedList","SplFileInfo","SplFileObject","SplFixedArray","SplHeap","SplMaxHeap","SplMinHeap","SplObjectStorage","SplObserver","SplPriorityQueue","SplQueue","SplStack","SplSubject","SplTempFileObject","TypeError","UnderflowException","UnexpectedValueException","UnhandledMatchError","ArrayAccess","BackedEnum","Closure","Fiber","Generator","Iterator","IteratorAggregate","Serializable","Stringable","Throwable","Traversable","UnitEnum","WeakReference","WeakMap","Directory","__PHP_Incomplete_Class","parent","php_user_filter","self","static","stdClass"],E={keyword:_,literal:(k=>{const V=[];return k.forEach(de=>{V.push(de),de.toLowerCase()===de?V.push(de.toUpperCase()):V.push(de.toLowerCase())}),V})(g),built_in:v},S=k=>k.map(V=>V.replace(/\|\d+$/,"")),w={variants:[{match:[/new/,e.concat(h,"+"),e.concat("(?!",S(v).join("\\b|"),"\\b)"),i],scope:{1:"keyword",4:"title.class"}}]},x=e.concat(r,"\\b(?!\\()"),A={variants:[{match:[e.concat(/::/,e.lookahead(/(?!class\b)/)),x],scope:{2:"variable.constant"}},{match:[/::/,/class/],scope:{2:"variable.language"}},{match:[i,e.concat(/::/,e.lookahead(/(?!class\b)/)),x],scope:{1:"title.class",3:"variable.constant"}},{match:[i,e.concat("::",e.lookahead(/(?!class\b)/))],scope:{1:"title.class"}},{match:[i,/::/,/class/],scope:{1:"title.class",3:"variable.language"}}]},C={scope:"attr",match:e.concat(r,e.lookahead(":"),e.lookahead(/(?!::)/))},D={relevance:0,begin:/\(/,end:/\)/,keywords:E,contains:[C,s,A,n.C_BLOCK_COMMENT_MODE,f,m,w]},N={relevance:0,match:[/\b/,e.concat("(?!fn\\b|function\\b|",S(_).join("\\b|"),"|",S(v).join("\\b|"),"\\b)"),r,e.concat(h,"*"),e.lookahead(/(?=\()/)],scope:{3:"title.function.invoke"},contains:[D]};D.contains.push(N);const O=[C,A,n.C_BLOCK_COMMENT_MODE,f,m,w],F={begin:e.concat(/#\[\s*\\?/,e.either(i,a)),beginScope:"meta",end:/]/,endScope:"meta",keywords:{literal:g,keyword:["new","array"]},contains:[{begin:/\[/,end:/]/,keywords:{literal:g,keyword:["new","array"]},contains:["self",...O]},...O,{scope:"meta",variants:[{match:i},{match:a}]}]};return{case_insensitive:!1,keywords:E,contains:[F,n.HASH_COMMENT_MODE,n.COMMENT("//","$"),n.COMMENT("/\\*","\\*/",{contains:[{scope:"doctag",match:"@[A-Za-z]+"}]}),{match:/__halt_compiler\(\);/,keywords:"__halt_compiler",starts:{scope:"comment",end:n.MATCH_NOTHING_RE,contains:[{match:/\?>/,scope:"meta",endsParent:!0}]}},o,{scope:"variable.language",match:/\$this\b/},s,N,A,{match:[/const/,/\s/,r],scope:{1:"keyword",3:"variable.constant"}},w,{scope:"function",relevance:0,beginKeywords:"fn function",end:/[;{]/,excludeEnd:!0,illegal:"[$%\\[]",contains:[{beginKeywords:"use"},n.UNDERSCORE_TITLE_MODE,{begin:"=>",endsParent:!0},{scope:"params",begin:"\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0,keywords:E,contains:["self",F,s,A,n.C_BLOCK_COMMENT_MODE,f,m]}]},{scope:"class",variants:[{beginKeywords:"enum",illegal:/[($"]/},{beginKeywords:"class interface trait",illegal:/[:($"]/}],relevance:0,end:/\{/,excludeEnd:!0,contains:[{beginKeywords:"extends implements"},n.UNDERSCORE_TITLE_MODE]},{beginKeywords:"namespace",relevance:0,end:";",illegal:/[.']/,contains:[n.inherit(n.UNDERSCORE_TITLE_MODE,{scope:"title.class"})]},{beginKeywords:"use",relevance:0,end:";",contains:[{match:/\b(as|const|function)\b/,scope:"keyword"},n.UNDERSCORE_TITLE_MODE]},f,m]}}function Aae(n){return n?typeof n=="string"?n:n.source:null}function I0(n){return ur("(?=",n,")")}function ur(...n){return n.map(t=>Aae(t)).join("")}function xat(n){const e=n[n.length-1];return typeof e=="object"&&e.constructor===Object?(n.splice(n.length-1,1),e):{}}function Ua(...n){return"("+(xat(n).capture?"":"?:")+n.map(r=>Aae(r)).join("|")+")"}const RL=n=>ur(/\b/,n,/\w$/.test(n)?/\b/:/\B/),Cat=["Protocol","Type"].map(RL),uH=["init","self"].map(RL),Aat=["Any","Self"],LI=["actor","any","associatedtype","async","await",/as\?/,/as!/,"as","borrowing","break","case","catch","class","consume","consuming","continue","convenience","copy","default","defer","deinit","didSet","distributed","do","dynamic","each","else","enum","extension","fallthrough",/fileprivate\(set\)/,"fileprivate","final","for","func","get","guard","if","import","indirect","infix",/init\?/,/init!/,"inout",/internal\(set\)/,"internal","in","is","isolated","nonisolated","lazy","let","macro","mutating","nonmutating",/open\(set\)/,"open","operator","optional","override","package","postfix","precedencegroup","prefix",/private\(set\)/,"private","protocol",/public\(set\)/,"public","repeat","required","rethrows","return","set","some","static","struct","subscript","super","switch","throws","throw",/try\?/,/try!/,"try","typealias",/unowned\(safe\)/,/unowned\(unsafe\)/,"unowned","var","weak","where","while","willSet"],dH=["false","nil","true"],Rat=["assignment","associativity","higherThan","left","lowerThan","none","right"],kat=["#colorLiteral","#column","#dsohandle","#else","#elseif","#endif","#error","#file","#fileID","#fileLiteral","#filePath","#function","#if","#imageLiteral","#keyPath","#line","#selector","#sourceLocation","#warning"],pH=["abs","all","any","assert","assertionFailure","debugPrint","dump","fatalError","getVaList","isKnownUniquelyReferenced","max","min","numericCast","pointwiseMax","pointwiseMin","precondition","preconditionFailure","print","readLine","repeatElement","sequence","stride","swap","swift_unboxFromSwiftValueWithType","transcode","type","unsafeBitCast","unsafeDowncast","withExtendedLifetime","withUnsafeMutablePointer","withUnsafePointer","withVaList","withoutActuallyEscaping","zip"],Rae=Ua(/[/=\-+!*%<>&|^~?]/,/[\u00A1-\u00A7]/,/[\u00A9\u00AB]/,/[\u00AC\u00AE]/,/[\u00B0\u00B1]/,/[\u00B6\u00BB\u00BF\u00D7\u00F7]/,/[\u2016-\u2017]/,/[\u2020-\u2027]/,/[\u2030-\u203E]/,/[\u2041-\u2053]/,/[\u2055-\u205E]/,/[\u2190-\u23FF]/,/[\u2500-\u2775]/,/[\u2794-\u2BFF]/,/[\u2E00-\u2E7F]/,/[\u3001-\u3003]/,/[\u3008-\u3020]/,/[\u3030]/),kae=Ua(Rae,/[\u0300-\u036F]/,/[\u1DC0-\u1DFF]/,/[\u20D0-\u20FF]/,/[\uFE00-\uFE0F]/,/[\uFE20-\uFE2F]/),FI=ur(Rae,kae,"*"),Iae=Ua(/[a-zA-Z_]/,/[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,/[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,/[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,/[\u1E00-\u1FFF]/,/[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,/[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,/[\u2C00-\u2DFF\u2E80-\u2FFF]/,/[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,/[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,/[\uFE47-\uFEFE\uFF00-\uFFFD]/),lT=Ua(Iae,/\d/,/[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/),Ml=ur(Iae,lT,"*"),CE=ur(/[A-Z]/,lT,"*"),Iat=["attached","autoclosure",ur(/convention\(/,Ua("swift","block","c"),/\)/),"discardableResult","dynamicCallable","dynamicMemberLookup","escaping","freestanding","frozen","GKInspectable","IBAction","IBDesignable","IBInspectable","IBOutlet","IBSegueAction","inlinable","main","nonobjc","NSApplicationMain","NSCopying","NSManaged",ur(/objc\(/,Ml,/\)/),"objc","objcMembers","propertyWrapper","requires_stored_property_inits","resultBuilder","Sendable","testable","UIApplicationMain","unchecked","unknown","usableFromInline","warn_unqualified_access"],Nat=["iOS","iOSApplicationExtension","macOS","macOSApplicationExtension","macCatalyst","macCatalystApplicationExtension","watchOS","watchOSApplicationExtension","tvOS","tvOSApplicationExtension","swift"];function Dat(n){const e={match:/\s+/,relevance:0},t=n.COMMENT("/\\*","\\*/",{contains:["self"]}),r=[n.C_LINE_COMMENT_MODE,t],i={match:[/\./,Ua(...Cat,...uH)],className:{2:"keyword"}},a={match:ur(/\./,Ua(...LI)),relevance:0},s=LI.filter(ie=>typeof ie=="string").concat(["_|0"]),o=LI.filter(ie=>typeof ie!="string").concat(Aat).map(RL),l={variants:[{className:"keyword",match:Ua(...o,...uH)}]},c={$pattern:Ua(/\b\w+/,/#\w+/),keyword:s.concat(kat),literal:dH},u=[i,a,l],d={match:ur(/\./,Ua(...pH)),relevance:0},p={className:"built_in",match:ur(/\b/,Ua(...pH),/(?=\()/)},h=[d,p],f={match:/->/,relevance:0},m={className:"operator",relevance:0,variants:[{match:FI},{match:`\\.(\\.|${kae})+`}]},g=[f,m],_="([0-9]_*)+",v="([0-9a-fA-F]_*)+",b={className:"number",relevance:0,variants:[{match:`\\b(${_})(\\.(${_}))?([eE][+-]?(${_}))?\\b`},{match:`\\b0x(${v})(\\.(${v}))?([pP][+-]?(${_}))?\\b`},{match:/\b0o([0-7]_*)+\b/},{match:/\b0b([01]_*)+\b/}]},E=(ie="")=>({className:"subst",variants:[{match:ur(/\\/,ie,/[0\\tnr"']/)},{match:ur(/\\/,ie,/u\{[0-9a-fA-F]{1,8}\}/)}]}),S=(ie="")=>({className:"subst",match:ur(/\\/,ie,/[\t ]*(?:[\r\n]|\r\n)/)}),w=(ie="")=>({className:"subst",label:"interpol",begin:ur(/\\/,ie,/\(/),end:/\)/}),x=(ie="")=>({begin:ur(ie,/"""/),end:ur(/"""/,ie),contains:[E(ie),S(ie),w(ie)]}),A=(ie="")=>({begin:ur(ie,/"/),end:ur(/"/,ie),contains:[E(ie),w(ie)]}),C={className:"string",variants:[x(),x("#"),x("##"),x("###"),A(),A("#"),A("##"),A("###")]},D=[n.BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0,contains:[n.BACKSLASH_ESCAPE]}],N={begin:/\/[^\s](?=[^/\n]*\/)/,end:/\//,contains:D},O=ie=>{const J=ur(ie,/\//),j=ur(/\//,ie);return{begin:J,end:j,contains:[...D,{scope:"comment",begin:`#(?!.*${j})`,end:/$/}]}},F={scope:"regexp",variants:[O("###"),O("##"),O("#"),N]},k={match:ur(/`/,Ml,/`/)},V={className:"variable",match:/\$\d+/},de={className:"variable",match:`\\$${lT}+`},te=[k,V,de],ue={match:/(@|#(un)?)available/,scope:"keyword",starts:{contains:[{begin:/\(/,end:/\)/,keywords:Nat,contains:[...g,b,C]}]}},be={scope:"keyword",match:ur(/@/,Ua(...Iat),I0(Ua(/\(/,/\s+/)))},ee={scope:"meta",match:ur(/@/,Ml)},G=[ue,be,ee],U={match:I0(/\b[A-Z]/),relevance:0,contains:[{className:"type",match:ur(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/,lT,"+")},{className:"type",match:CE,relevance:0},{match:/[?!]+/,relevance:0},{match:/\.\.\./,relevance:0},{match:ur(/\s+&\s+/,I0(CE)),relevance:0}]},Z={begin:/</,end:/>/,keywords:c,contains:[...r,...u,...G,f,U]};U.contains.push(Z);const M={match:ur(Ml,/\s*:/),keywords:"_|0",relevance:0},z={begin:/\(/,end:/\)/,relevance:0,keywords:c,contains:["self",M,...r,F,...u,...h,...g,b,C,...te,...G,U]},_e={begin:/</,end:/>/,keywords:"repeat each",contains:[...r,U]},we={begin:Ua(I0(ur(Ml,/\s*:/)),I0(ur(Ml,/\s+/,Ml,/\s*:/))),end:/:/,relevance:0,contains:[{className:"keyword",match:/\b_\b/},{className:"params",match:Ml}]},q={begin:/\(/,end:/\)/,keywords:c,contains:[we,...r,...u,...g,b,C,...G,U,z],endsParent:!0,illegal:/["']/},oe={match:[/(func|macro)/,/\s+/,Ua(k.match,Ml,FI)],className:{1:"keyword",3:"title.function"},contains:[_e,q,e],illegal:[/\[/,/%/]},ae={match:[/\b(?:subscript|init[?!]?)/,/\s*(?=[<(])/],className:{1:"keyword"},contains:[_e,q,e],illegal:/\[|%/},L={match:[/operator/,/\s+/,FI],className:{1:"keyword",3:"title"}},ne={begin:[/precedencegroup/,/\s+/,CE],className:{1:"keyword",3:"title"},contains:[U],keywords:[...Rat,...dH],end:/}/},B={match:[/class\b/,/\s+/,/func\b/,/\s+/,/\b[A-Za-z_][A-Za-z0-9_]*\b/],scope:{1:"keyword",3:"keyword",5:"title.function"}},I={match:[/class\b/,/\s+/,/var\b/],scope:{1:"keyword",3:"keyword"}},he={begin:[/(struct|protocol|class|extension|enum|actor)/,/\s+/,Ml,/\s*/],beginScope:{1:"keyword",3:"title.class"},keywords:c,contains:[_e,...u,{begin:/:/,end:/\{/,keywords:c,contains:[{scope:"title.class.inherited",match:CE},...u],relevance:0}]};for(const ie of C.variants){const J=ie.contains.find(me=>me.label==="interpol");J.keywords=c;const j=[...u,...h,...g,b,C,...te];J.contains=[...j,{begin:/\(/,end:/\)/,contains:["self",...j]}]}return{name:"Swift",keywords:c,contains:[...r,oe,ae,B,I,he,L,ne,{beginKeywords:"import",end:/$/,contains:[...r],relevance:0},F,...u,...h,...g,b,C,...te,...G,U,z]}}var Jh="[0-9](_*[0-9])*",AE=`\\.(${Jh})`,RE="[0-9a-fA-F](_*[0-9a-fA-F])*",Oat={className:"number",variants:[{begin:`(\\b(${Jh})((${AE})|\\.)?|(${AE}))[eE][+-]?(${Jh})[fFdD]?\\b`},{begin:`\\b(${Jh})((${AE})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${AE})[fFdD]?\\b`},{begin:`\\b(${Jh})[fFdD]\\b`},{begin:`\\b0[xX]((${RE})\\.?|(${RE})?\\.(${RE}))[pP][+-]?(${Jh})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${RE})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function Pat(n){const e={keyword:"abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed internal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual",built_in:"Byte Short Char Int Long Boolean Float Double Void Unit Nothing",literal:"true false null"},t={className:"keyword",begin:/\b(break|continue|return|this)\b/,starts:{contains:[{className:"symbol",begin:/@\w+/}]}},r={className:"symbol",begin:n.UNDERSCORE_IDENT_RE+"@"},i={className:"subst",begin:/\$\{/,end:/\}/,contains:[n.C_NUMBER_MODE]},a={className:"variable",begin:"\\$"+n.UNDERSCORE_IDENT_RE},s={className:"string",variants:[{begin:'"""',end:'"""(?=[^"])',contains:[a,i]},{begin:"'",end:"'",illegal:/\n/,contains:[n.BACKSLASH_ESCAPE]},{begin:'"',end:'"',illegal:/\n/,contains:[n.BACKSLASH_ESCAPE,a,i]}]};i.contains.push(s);const o={className:"meta",begin:"@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*"+n.UNDERSCORE_IDENT_RE+")?"},l={className:"meta",begin:"@"+n.UNDERSCORE_IDENT_RE,contains:[{begin:/\(/,end:/\)/,contains:[n.inherit(s,{className:"string"}),"self"]}]},c=Oat,u=n.COMMENT("/\\*","\\*/",{contains:[n.C_BLOCK_COMMENT_MODE]}),d={variants:[{className:"type",begin:n.UNDERSCORE_IDENT_RE},{begin:/\(/,end:/\)/,contains:[]}]},p=d;return p.variants[1].contains=[d],d.variants[1].contains=[p],{name:"Kotlin",aliases:["kt","kts"],keywords:e,contains:[n.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"}]}),n.C_LINE_COMMENT_MODE,u,t,r,o,l,{className:"function",beginKeywords:"fun",end:"[(]|$",returnBegin:!0,excludeEnd:!0,keywords:e,relevance:5,contains:[{begin:n.UNDERSCORE_IDENT_RE+"\\s*\\(",returnBegin:!0,relevance:0,contains:[n.UNDERSCORE_TITLE_MODE]},{className:"type",begin:/</,end:/>/,keywords:"reified",relevance:0},{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:e,relevance:0,contains:[{begin:/:/,end:/[=,\/]/,endsWithParent:!0,contains:[d,n.C_LINE_COMMENT_MODE,u],relevance:0},n.C_LINE_COMMENT_MODE,u,o,l,s,n.C_NUMBER_MODE]},u]},{begin:[/class|interface|trait/,/\s+/,n.UNDERSCORE_IDENT_RE],beginScope:{3:"title.class"},keywords:"class interface trait",end:/[:\{(]|$/,excludeEnd:!0,illegal:"extends implements",contains:[{beginKeywords:"public protected internal private constructor"},n.UNDERSCORE_TITLE_MODE,{className:"type",begin:/</,end:/>/,excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:/[,:]\s*/,end:/[<\(,){\s]|$/,excludeBegin:!0,returnEnd:!0},o,l]},s,{className:"meta",begin:"^#!/usr/bin/env",end:"$",illegal:`
|
|
3762
|
+
`},c]}}const Mat=n=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:n.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[n.APOS_STRING_MODE,n.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:n.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),Lat=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],Fat=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],Uat=[...Lat,...Fat],Bat=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),$at=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),Gat=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),Wat=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();function zat(n){const e=Mat(n),t=Gat,r=$at,i="@[a-z-]+",a="and or not only",o={className:"variable",begin:"(\\$"+"[a-zA-Z-][a-zA-Z0-9_-]*"+")\\b",relevance:0};return{name:"SCSS",case_insensitive:!0,illegal:"[=/|']",contains:[n.C_LINE_COMMENT_MODE,n.C_BLOCK_COMMENT_MODE,e.CSS_NUMBER_MODE,{className:"selector-id",begin:"#[A-Za-z0-9_-]+",relevance:0},{className:"selector-class",begin:"\\.[A-Za-z0-9_-]+",relevance:0},e.ATTRIBUTE_SELECTOR_MODE,{className:"selector-tag",begin:"\\b("+Uat.join("|")+")\\b",relevance:0},{className:"selector-pseudo",begin:":("+r.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+t.join("|")+")"},o,{begin:/\(/,end:/\)/,contains:[e.CSS_NUMBER_MODE]},e.CSS_VARIABLE,{className:"attribute",begin:"\\b("+Wat.join("|")+")\\b"},{begin:"\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b"},{begin:/:/,end:/[;}{]/,relevance:0,contains:[e.BLOCK_COMMENT,o,e.HEXCOLOR,e.CSS_NUMBER_MODE,n.QUOTE_STRING_MODE,n.APOS_STRING_MODE,e.IMPORTANT,e.FUNCTION_DISPATCH]},{begin:"@(page|font-face)",keywords:{$pattern:i,keyword:"@page @font-face"}},{begin:"@",end:"[{;]",returnBegin:!0,keywords:{$pattern:/[a-z-]+/,keyword:a,attribute:Bat.join(" ")},contains:[{begin:i,className:"keyword"},{begin:/[a-z-]+(?=:)/,className:"attribute"},o,n.QUOTE_STRING_MODE,n.APOS_STRING_MODE,e.HEXCOLOR,e.CSS_NUMBER_MODE]},e.FUNCTION_DISPATCH]}}let Nae="Canvas",Dae="",ib=!1,hS=null,kL=null;const Oae=new Set;function IL(n,e){Nae=n||"Canvas",Dae=e,ib=!0,NL(),kL?.()}function Pae(){ib=!1,NL(),kL?.()}function qat(){return ib}function Hat(n,e){hS=n,kL=e,NL()}function Vat(n){if(n.role!=="toolResult"||n.toolName!=="canvas")return null;const e=n.details?.markdown;return e?{title:n.details?.title||"Canvas",markdown:e}:null}function Mae(n,e){return`${n.split("/").pop()||n}:${e}`}function Lae(n){Oae.add(n)}function Yat(n){return Oae.has(n)}function hH(n,e){let t=-1,r=null;for(let i=0;i<n.length;i++){const a=Vat(n[i]);a&&(r=a,t=i)}if(r&&t>=0){if(e){const i=Mae(e,t);if(Yat(i))return;Lae(i)}IL(r.title,r.markdown)}else ib&&Pae()}function NL(){if(!hS)return;if(!ib){ol(Q``,hS);return}const n=Q`
|
|
3763
3763
|
<div class="canvas-panel">
|
|
3764
3764
|
<div class="canvas-header">
|
|
3765
3765
|
<span class="canvas-title">${Nae}</span>
|
|
@@ -3773,9 +3773,9 @@ ${this.content||""}</pre
|
|
|
3773
3773
|
<markdown-block .content=${Dae}></markdown-block>
|
|
3774
3774
|
</div>
|
|
3775
3775
|
</div>
|
|
3776
|
-
`;ol(n,hS)}let wO=999999;const DL=new Set,Gg=new Set;let xO=0;function
|
|
3777
|
-
`)?n:""}const
|
|
3778
|
-
`)||""}function sb(n){return n==="complete"?"text-green-600 dark:text-green-500":n==="error"?"text-destructive":"text-foreground"}function ob(n){return n==="complete"?"bg-green-300 dark:bg-green-700":n==="error"?"bg-destructive/40":"bg-border"}function lb(n){const e=n.currentTarget,t=e.closest(".tool-gutter-wrap");if(!t)return;const r=t.querySelector(".tool-body-collapsible"),i=t.querySelector(".tool-thread-line"),a=e.querySelector(".tool-chevron");if(!r)return;const s=r.style.display==="none";r.style.display=s?"":"none",i&&(i.style.display=s?"":"none"),a&&(a.style.transform=s?"rotate(90deg)":""),s&&
|
|
3776
|
+
`;ol(n,hS)}let wO=999999;const DL=new Set,Gg=new Set;let xO=0;function Kat(){DL.clear(),Gg.clear(),xO=0}function Qat(n){const t=n.closest("tool-message")?.getAttribute("data-tool-call-id");if(!t)return;const r=n.querySelector(".tool-body-collapsible");r&&r.style.display!=="none"&&Gg.has(t)&&DL.add(t)}function jat(){if(wO>=999999)return;const n=document.querySelectorAll("tool-message[data-tool-call-id]");if(!n.length)return;const e=[];for(const i of n){const a=i.getAttribute("data-tool-call-id"),s=i.querySelector(".tool-gutter-wrap");if(!s)continue;s.querySelector(".animate-spin")||e.push({id:a,wrap:s})}if(e.length<=xO)return;xO=e.length;const t=e.filter(i=>!DL.has(i.id)),r=t.slice(0,Math.max(0,t.length-wO));for(const{id:i,wrap:a}of r){if(Gg.has(i))continue;const s=a.querySelector(".tool-body-collapsible");if(!s||s.style.display==="none"){Gg.add(i);continue}s.style.display="none";const o=a.querySelector(".tool-thread-line"),l=a.querySelector(".tool-chevron");o&&(o.style.display="none"),l&&(l.style.transform=""),Gg.add(i)}}async function Fae(){try{const n=await fetch("/api/settings/local");if(!n.ok)return;const t=(await n.json())?.settings?.toolCollapse?.keepOpen;typeof t=="number"&&Number.isFinite(t)&&t>=0&&(wO=t)}catch{}}Nn.registerLanguage("javascript",lae);Nn.registerLanguage("typescript",bae);Nn.registerLanguage("python",uae);Nn.registerLanguage("html",px);Nn.registerLanguage("xml",px);Nn.registerLanguage("css",iae);Nn.registerLanguage("json",cae);Nn.registerLanguage("bash",rae);Nn.registerLanguage("sql",dae);Nn.registerLanguage("markdown",gat);Nn.registerLanguage("yaml",_at);Nn.registerLanguage("go",vat);Nn.registerLanguage("rust",bat);Nn.registerLanguage("java",yat);Nn.registerLanguage("cpp",Eat);Nn.registerLanguage("c",Sat);Nn.registerLanguage("ruby",Tat);Nn.registerLanguage("php",wat);Nn.registerLanguage("swift",Dat);Nn.registerLanguage("kotlin",Pat);Nn.registerLanguage("scss",zat);function cT(n,e){return n}function ab(){let n=!1,e=!1,t=null,r=null,i=!1,a=!1;function s(){return t?t.scrollHeight-t.scrollTop-t.clientHeight<8:!0}function o(){t&&(t.scrollTop=t.scrollHeight)}function l(){!t||!e||(n=!s())}function c(){t&&e&&!n&&o()}function u(d){!d||!(d instanceof HTMLElement)||(d!==t&&(t=d,i=!1,r?.disconnect(),r=null,a=!1,n=!1),i||(t.addEventListener("scroll",l,{passive:!0}),i=!0),r||(r=new MutationObserver(c),r.observe(t,{childList:!0,subtree:!0,characterData:!0})),!e&&!a&&(a=!0,requestAnimationFrame(()=>o())))}return{ref:u,set streaming(d){e&&!d&&(a=!1),!e&&d&&(n=!1,a=!1),e=d}}}function Xat(n){if(!n)return n;const e=n.match(/^cd\s+\S+\s+&&\s+(.*)$/s);return e?e[1]:n}function Zat(n){return n?.trim()&&n.includes(`
|
|
3777
|
+
`)?n:""}const Jat={js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",ts:"typescript",tsx:"typescript",mts:"typescript",cts:"typescript",html:"html",htm:"html",svg:"xml",xml:"xml",css:"css",scss:"scss",json:"json",jsonl:"json",py:"python",pyw:"python",md:"markdown",mdx:"markdown",yaml:"yaml",yml:"yaml",sh:"bash",bash:"bash",zsh:"bash",sql:"sql",java:"java",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",go:"go",rs:"rust",php:"php",rb:"ruby",swift:"swift",kt:"kotlin",kts:"kotlin"};function Uae(n){if(!n)return"";const e=n.split(".").pop()?.toLowerCase()||"";return Jat[e]||""}function OL(n,e){return e&&Nn.getLanguage(e)?Nn.highlight(n,{language:e,ignoreIllegals:!0}).value:""}function Mm(n){return n&&n.content?.filter(e=>e.type==="text").map(e=>e.text).join(`
|
|
3778
|
+
`)||""}function sb(n){return n==="complete"?"text-green-600 dark:text-green-500":n==="error"?"text-destructive":"text-foreground"}function ob(n){return n==="complete"?"bg-green-300 dark:bg-green-700":n==="error"?"bg-destructive/40":"bg-border"}function lb(n){const e=n.currentTarget,t=e.closest(".tool-gutter-wrap");if(!t)return;const r=t.querySelector(".tool-body-collapsible"),i=t.querySelector(".tool-thread-line"),a=e.querySelector(".tool-chevron");if(!r)return;const s=r.style.display==="none";r.style.display=s?"":"none",i&&(i.style.display=s?"":"none"),a&&(a.style.transform=s?"rotate(90deg)":""),s&&Qat(t)}function est(n){if(!n||!(n instanceof HTMLElement))return;const e=n.offsetHeight;e>0&&(n.style.minHeight=`${e}px`,requestAnimationFrame(()=>{n.style.minHeight=""}))}class tst{constructor(){this.scrollPin=ab()}render(e,t,r){const i=t?t.isError?"error":"complete":r?"inprogress":"complete";this.scrollPin.streaming=i==="inprogress";let a={};try{a=typeof e=="string"?JSON.parse(e):e||{}}catch{}const s=a.path||"",o=s?s.split("/").pop():"",l=[];a.offset!=null&&l.push(`offset:${a.offset}`),a.limit!=null&&l.push(`limit:${a.limit}`);const c=[o,...l].filter(Boolean).join(", "),u=c?`read(${c})`:"read",d=Mm(t),p=t?.isError??!1,h=Q`<span class="inline-block ${sb(i)}">${Rt(ug,"sm")}</span>`,f=i==="inprogress"?Q`<span class="inline-block text-foreground animate-spin">${Rt(Jc,"sm")}</span>`:"",m=d?cT(d):"",g=Uae(s),_=m&&!p?OL(m,g):"",v=!!m;return{content:Q`
|
|
3779
3779
|
<div class="tool-gutter-wrap flex my-0">
|
|
3780
3780
|
<div class="tool-gutter flex flex-col items-center w-5 shrink-0 pt-0.5">
|
|
3781
3781
|
${h}
|
|
@@ -3794,7 +3794,7 @@ ${this.content||""}</pre
|
|
|
3794
3794
|
</div>`:""}
|
|
3795
3795
|
</div>
|
|
3796
3796
|
</div>
|
|
3797
|
-
`,isCustom:!0}}}class
|
|
3797
|
+
`,isCustom:!0}}}class nst{constructor(){this.scrollPin=ab()}render(e,t,r){const i=t?t.isError?"error":"complete":r?"inprogress":"complete";this.scrollPin.streaming=i==="inprogress";let a={};try{a=typeof e=="string"?JSON.parse(e):e||{}}catch{}const s=a.path||"",o=s?s.split("/").pop():"",l=a.content||"",c=l?new TextEncoder().encode(l).length:0,u=Mm(t),d=t?.isError??!1;let p=o?`write(${o})`:"write";i==="error"&&u?p+=` — ${cT(u)}`:i==="complete"&&c>0&&(p+=` — ${c.toLocaleString()} bytes`);const h=Q`<span class="inline-block ${sb(i)}">${Rt(Ese,"sm")}</span>`,f=i==="inprogress"?Q`<span class="inline-block text-foreground animate-spin">${Rt(Jc,"sm")}</span>`:"",m=Uae(s),g=l?cT(l):"",_=g&&!d?OL(g,m):"",v=!!g;return{content:Q`
|
|
3798
3798
|
<div class="tool-gutter-wrap flex my-0">
|
|
3799
3799
|
<div class="tool-gutter flex flex-col items-center w-5 shrink-0 pt-0.5">
|
|
3800
3800
|
${h}
|
|
@@ -3813,14 +3813,14 @@ ${this.content||""}</pre
|
|
|
3813
3813
|
</div>`:""}
|
|
3814
3814
|
</div>
|
|
3815
3815
|
</div>
|
|
3816
|
-
`,isCustom:!0}}}function
|
|
3816
|
+
`,isCustom:!0}}}function rst(n,e){const t=n.split(`
|
|
3817
3817
|
`),r=e.split(`
|
|
3818
|
-
`),i=[],a=t.length,s=r.length,o=Array.from({length:a+1},()=>new Array(s+1).fill(0));for(let p=1;p<=a;p++)for(let h=1;h<=s;h++)o[p][h]=t[p-1]===r[h-1]?o[p-1][h-1]+1:Math.max(o[p-1][h],o[p][h-1]);let l=a,c=s;const u=[],d=[];for(;l>0||c>0;)l>0&&c>0&&t[l-1]===r[c-1]?(u.push("ctx"),d.push(t[l-1]),l--,c--):c>0&&(l===0||o[l][c-1]>=o[l-1][c])?(u.push("add"),d.push(r[c-1]),c--):(u.push("del"),d.push(t[l-1]),l--);u.reverse(),d.reverse();for(let p=0;p<u.length;p++)i.push({type:u[p],text:d[p]});return{lines:i}}class
|
|
3818
|
+
`),i=[],a=t.length,s=r.length,o=Array.from({length:a+1},()=>new Array(s+1).fill(0));for(let p=1;p<=a;p++)for(let h=1;h<=s;h++)o[p][h]=t[p-1]===r[h-1]?o[p-1][h-1]+1:Math.max(o[p-1][h],o[p][h-1]);let l=a,c=s;const u=[],d=[];for(;l>0||c>0;)l>0&&c>0&&t[l-1]===r[c-1]?(u.push("ctx"),d.push(t[l-1]),l--,c--):c>0&&(l===0||o[l][c-1]>=o[l-1][c])?(u.push("add"),d.push(r[c-1]),c--):(u.push("del"),d.push(t[l-1]),l--);u.reverse(),d.reverse();for(let p=0;p<u.length;p++)i.push({type:u[p],text:d[p]});return{lines:i}}class ist{constructor(){this.scrollPin=ab()}render(e,t,r){const i=t?t.isError?"error":"complete":r?"inprogress":"complete";this.scrollPin.streaming=i==="inprogress";let a={};try{a=typeof e=="string"?JSON.parse(e):e||{}}catch{}const s=a.path||"",o=s?s.split("/").pop():"",l=o?`edit(${o})`:"edit",c=Mm(t),u=t?.isError??!1,d=Q`<span class="inline-block ${sb(i)}">${Rt(yse,"sm")}</span>`,p=i==="inprogress"?Q`<span class="inline-block text-foreground animate-spin">${Rt(Jc,"sm")}</span>`:"",h=a.oldText||"",f=a.newText||"",m=h||f;let g="";if(m){const v=rst(h,f);g=Q`<div ${ir(this.scrollPin.ref)} class="overflow-auto tool-body-scroll bg-muted rounded-md mt-0.5 px-2 py-1.5">
|
|
3819
3819
|
<pre class="m-0 tool-body-code font-mono whitespace-pre-wrap">${v.lines.map(b=>b.type==="del"?Q`<span class="text-red-500 dark:text-red-400">- ${b.text}\n</span>`:b.type==="add"?Q`<span class="text-green-500 dark:text-green-400">+ ${b.text}\n</span>`:Q`<span class="text-muted-foreground"> ${b.text}\n</span>`)}</pre>
|
|
3820
3820
|
</div>`}else c&&u&&(g=Q`<div class="overflow-auto tool-body-scroll bg-muted rounded-md mt-0.5 px-2 py-1.5">
|
|
3821
3821
|
<pre class="m-0 tool-body-code text-destructive font-mono whitespace-pre-wrap">${cT(c)}</pre>
|
|
3822
3822
|
</div>`);const _=!!(m||c&&u);return{content:Q`
|
|
3823
|
-
<div ${ir(
|
|
3823
|
+
<div ${ir(est)} class="tool-gutter-wrap flex my-0">
|
|
3824
3824
|
<div class="tool-gutter flex flex-col items-center w-5 shrink-0 pt-0.5">
|
|
3825
3825
|
${d}
|
|
3826
3826
|
${_?Q`<div class="tool-thread-line w-0.5 flex-1 mt-0.5 rounded-full ${ob(i)}"></div>`:""}
|
|
@@ -3834,7 +3834,7 @@ ${this.content||""}</pre
|
|
|
3834
3834
|
${_?Q`<div class="tool-body-collapsible">${g}</div>`:""}
|
|
3835
3835
|
</div>
|
|
3836
3836
|
</div>
|
|
3837
|
-
`,isCustom:!0}}}class
|
|
3837
|
+
`,isCustom:!0}}}class ast{constructor(){this.scrollPin=ab()}render(e,t,r){const i=t?t.isError?"error":r?"inprogress":"complete":"inprogress";this.scrollPin.streaming=i==="inprogress";let a={};try{a=typeof e=="string"?JSON.parse(e):e||{}}catch{}const s=Xat(a.command||""),o=Mm(t),l=Zat(s),c=o?l?`> ${l}
|
|
3838
3838
|
|
|
3839
3839
|
${o}`:o:l?`> ${l}`:"",u=t?.isError??!1,d=Q`<span class="inline-block ${sb(i)}">${Rt(IE,"sm")}</span>`,p=i==="inprogress"?Q`<span class="inline-block text-foreground animate-spin">${Rt(Jc,"sm")}</span>`:"";return{content:Q`
|
|
3840
3840
|
<div class="tool-gutter-wrap flex my-0">
|
|
@@ -3855,7 +3855,7 @@ ${o}`:o:l?`> ${l}`:"",u=t?.isError??!1,d=Q`<span class="inline-block ${sb(i)}">$
|
|
|
3855
3855
|
</div>
|
|
3856
3856
|
</div>
|
|
3857
3857
|
</div>
|
|
3858
|
-
`,isCustom:!0}}}class
|
|
3858
|
+
`,isCustom:!0}}}class sst{render(e,t,r){let i={};try{i=typeof e=="string"?JSON.parse(e):e||{}}catch{}const a=i.title||"Canvas",s=t?.isError??!1;if(!t&&r)return{content:Q`
|
|
3859
3859
|
<div class="flex items-center gap-2 px-3 py-1.5 text-xs text-muted-foreground">
|
|
3860
3860
|
<span class="inline-block animate-spin">${Rt(Jc,"sm")}</span>
|
|
3861
3861
|
<span>Preparing canvas…</span>
|
|
@@ -3871,7 +3871,7 @@ ${o}`:o:l?`> ${l}`:"",u=t?.isError??!1,d=Q`<span class="inline-block ${sb(i)}">$
|
|
|
3871
3871
|
<span class="inline-flex text-muted-foreground">${Rt(Ase,"sm")}</span>
|
|
3872
3872
|
<span>${a}</span>
|
|
3873
3873
|
</button>
|
|
3874
|
-
`,isCustom:!0}}}class
|
|
3874
|
+
`,isCustom:!0}}}class ost{constructor(){this.scrollPin=ab()}render(e,t,r,i){const a=r?r.isError?"error":"complete":i?"inprogress":"complete";this.scrollPin.streaming=a==="inprogress";let s={};try{s=typeof t=="string"?JSON.parse(t):t||{}}catch{}const o=Object.keys(s);let l="";if(o.length===1){const v=s[o[0]],b=typeof v=="string"?v:JSON.stringify(v);l=b.length>60?b.slice(0,57)+"…":b}else o.length>1&&(l=o.join(", "));const c=l?`${e}(${l})`:e,u=Mm(r),d=r?.isError??!1;let p="";if(t)try{p=JSON.stringify(s,null,2)}catch{p=String(t)}let h="";p&&p!=="{}"&&u?h=`> ${p}
|
|
3875
3875
|
|
|
3876
3876
|
${u}`:u?h=u:p&&p!=="{}"&&(h=p);const f=Q`<span class="inline-block ${sb(a)}">${Rt(kse,"sm")}</span>`,m=a==="inprogress"?Q`<span class="inline-block text-foreground animate-spin">${Rt(Jc,"sm")}</span>`:"",g=!!h||a==="inprogress",_=h?OL(h,"json"):"";return{content:Q`
|
|
3877
3877
|
<div class="tool-gutter-wrap flex my-0">
|
|
@@ -3892,7 +3892,7 @@ ${u}`:u?h=u:p&&p!=="{}"&&(h=p);const f=Q`<span class="inline-block ${sb(a)}">${R
|
|
|
3892
3892
|
</div>`:""}
|
|
3893
3893
|
</div>
|
|
3894
3894
|
</div>
|
|
3895
|
-
`,isCustom:!0}}}function
|
|
3895
|
+
`,isCustom:!0}}}function lst(){Oc("read",new tst),Oc("write",new nst),Oc("edit",new ist),Oc("bash",new ast),Oc("canvas",new sst),kXe(new ost)}function cst(n){const e=document.createElement("div");e.style.cssText="position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,0.85);display:flex;align-items:center;justify-content:center;cursor:zoom-out;";const t=document.createElement("img");t.src=n.src,t.style.cssText="max-width:90vw;max-height:90vh;object-fit:contain;border-radius:8px;",e.appendChild(t),e.addEventListener("click",()=>e.remove()),document.addEventListener("keydown",function r(i){i.key==="Escape"&&(e.remove(),document.removeEventListener("keydown",r))}),document.body.appendChild(e)}Fre("user",{render(n){const e=typeof n.content=="string"?n.content:n.content.find(r=>r.type==="text")?.text||"",t=typeof n.content=="string"?[]:n.content.filter(r=>r.type==="image");return Q`
|
|
3896
3896
|
<div class="flex justify-start mx-4">
|
|
3897
3897
|
<div class="user-message-container py-2 px-4 rounded-xl">
|
|
3898
3898
|
<markdown-block .content=${e}></markdown-block>
|
|
@@ -3902,20 +3902,20 @@ ${u}`:u?h=u:p&&p!=="{}"&&(h=p);const f=Q`<span class="inline-block ${sb(a)}">${R
|
|
|
3902
3902
|
src="data:${r.mimeType};base64,${r.data}"
|
|
3903
3903
|
alt="Attached image"
|
|
3904
3904
|
class="max-w-xs max-h-64 rounded-md border border-border object-contain cursor-pointer"
|
|
3905
|
-
@click=${i=>
|
|
3905
|
+
@click=${i=>cst(i.target)}
|
|
3906
3906
|
/>`)}
|
|
3907
3907
|
</div>
|
|
3908
3908
|
`:""}
|
|
3909
3909
|
</div>
|
|
3910
3910
|
</div>
|
|
3911
|
-
`}});function
|
|
3911
|
+
`}});function ust(n){return n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1e3?`${(n/1e3).toFixed(0)}k`:String(n)}function dst(n){const e=n.currentTarget,t=e.closest(".tool-gutter-wrap");if(!t)return;const r=t.querySelector(".tool-body-collapsible"),i=t.querySelector(".tool-thread-line"),a=e.querySelector(".tool-chevron");if(!r)return;const s=r.style.display==="none";r.style.display=s?"":"none",i&&(i.style.display=s?"":"none"),a&&(a.style.transform=s?"rotate(90deg)":"")}Fre("compactionSummary",{render(n){const e=n.summary||"",t=n.tokensBefore||0,r=!!n._compacting,i=r?"compacting…":t>0?`compacted — ${ust(t)} tokens summarized`:"compacted",a=r?"text-foreground":"text-green-600 dark:text-green-500",s=r?"bg-border":"bg-green-300 dark:bg-green-700",o=r?Q`<span class="inline-block text-foreground animate-spin">${Rt(Jc,"sm")}</span>`:"",l=!!e;return Q`
|
|
3912
3912
|
<div class="tool-gutter-wrap flex my-0 px-4">
|
|
3913
3913
|
<div class="tool-gutter flex flex-col items-center w-5 shrink-0 pt-0.5">
|
|
3914
3914
|
<span class="inline-block ${a}">${Rt(Nse,"sm")}</span>
|
|
3915
3915
|
${l?Q`<div class="tool-thread-line w-0.5 flex-1 mt-0.5 rounded-full ${s}" style="display: none"></div>`:""}
|
|
3916
3916
|
</div>
|
|
3917
3917
|
<div class="flex-1 min-w-0">
|
|
3918
|
-
<div class="tool-hdr flex items-center gap-1 cursor-pointer py-px hover:text-foreground" @click=${
|
|
3918
|
+
<div class="tool-hdr flex items-center gap-1 cursor-pointer py-px hover:text-foreground" @click=${dst}>
|
|
3919
3919
|
<span class="tool-chevron inline-block transition-transform text-muted-foreground">${Rt(ic,"xs")}</span>
|
|
3920
3920
|
<span class="tool-header-label text-muted-foreground font-mono">${i}</span>
|
|
3921
3921
|
${o}
|
|
@@ -3938,7 +3938,7 @@ ${u}`:u?h=u:p&&p!=="{}"&&(h=p);const f=Q`<span class="inline-block ${sb(a)}">${R
|
|
|
3938
3938
|
</div>
|
|
3939
3939
|
${t?Q`<markdown-block .content=${n} .isThinking=${!0}></markdown-block>`:""}
|
|
3940
3940
|
</div>
|
|
3941
|
-
`});var
|
|
3941
|
+
`});var pst=Object.defineProperty,hst=Object.getOwnPropertyDescriptor,gx=(n,e,t,r)=>{for(var i=r>1?void 0:r?hst(e,t):e,a=n.length-1,s;a>=0;a--)(s=n[a])&&(i=(r?s(e,t,i):s(i))||i);return r&&i&&pst(e,t,i),i};let iv=class extends vn{constructor(){super(...arguments),this.messages=[],this.isStreaming=!1,this.pendingToolCalls=new Set}createRenderRoot(){return this}connectedCallback(){super.connectedCallback(),this.style.display="block"}render(){const n=new Map;for(const t of this.messages)t.role==="toolResult"&&n.set(t.toolCallId,t);const e=this.buildRenderItems(n);return Q`<div class="flex flex-col gap-3">
|
|
3942
3942
|
${q_(e,t=>t.key,t=>Q`<div data-message-index=${String(t.messageIndex)} style="display: contents;">${t.template}</div>`)}
|
|
3943
3943
|
${this.isStreaming?Q`<span class="mx-4 inline-block w-2 h-4 bg-muted-foreground animate-pulse"></span>`:""}
|
|
3944
3944
|
</div>`}buildRenderItems(n){const e=[];let t=0;for(const r of this.messages){if(r.role==="artifact"||r.role==="toolResult")continue;const i=Ure(r);if(i){e.push({key:`msg:${t}`,template:i,messageIndex:t}),t++;continue}if(r.role==="user"||r.role==="user-with-attachments")e.push({key:`msg:${t}`,template:Q`<user-message .message=${r}></user-message>`,messageIndex:t}),t++;else if(r.role==="assistant"){const a=this.isStreaming&&this.isLastAssistantMessage(r);e.push({key:`msg:${t}`,template:Q`<assistant-message
|
|
@@ -3949,7 +3949,7 @@ ${u}`:u?h=u:p&&p!=="{}"&&(h=p);const f=Q`<span class="inline-block ${sb(a)}">${R
|
|
|
3949
3949
|
.toolResultsById=${n}
|
|
3950
3950
|
.hideToolCalls=${!1}
|
|
3951
3951
|
.hidePendingToolCalls=${!1}
|
|
3952
|
-
></assistant-message>`,messageIndex:t}),t++}}return e}isLastAssistantMessage(n){for(let e=this.messages.length-1;e>=0;e--)if(this.messages[e].role==="assistant")return this.messages[e]===n;return!1}};gx([Ge({type:Array})],iv.prototype,"messages",2);gx([Ge({type:Boolean})],iv.prototype,"isStreaming",2);gx([Ge({type:Object})],iv.prototype,"pendingToolCalls",2);iv=gx([sn("pi-message-list")],iv);var
|
|
3952
|
+
></assistant-message>`,messageIndex:t}),t++}}return e}isLastAssistantMessage(n){for(let e=this.messages.length-1;e>=0;e--)if(this.messages[e].role==="assistant")return this.messages[e]===n;return!1}};gx([Ge({type:Array})],iv.prototype,"messages",2);gx([Ge({type:Boolean})],iv.prototype,"isStreaming",2);gx([Ge({type:Object})],iv.prototype,"pendingToolCalls",2);iv=gx([sn("pi-message-list")],iv);var fst=Object.defineProperty,mst=Object.getOwnPropertyDescriptor,Sh=(n,e,t,r)=>{for(var i=r>1?void 0:r?mst(e,t):e,a=n.length-1,s;a>=0;a--)(s=n[a])&&(i=(r?s(e,t,i):s(i))||i);return r&&i&&fst(e,t,i),i};let Zc=class extends vn{constructor(){super(...arguments),this.messages=[],this.loading=!0,this.forking=!1,this.search="",this.selectedIndex=0}open(n){return this.agent=n,this.loading=!0,this.forking=!1,this.search="",this.selectedIndex=0,this.messages=[],this.loadMessages(),new Promise(e=>{this.onComplete=e})}async loadMessages(){try{this.messages=await this.agent.getForkMessages()}catch(n){console.error("Failed to load fork messages:",n),this.messages=[]}this.loading=!1}get filteredMessages(){if(!this.search.trim())return this.messages;const n=this.search.toLowerCase();return this.messages.filter(e=>e.text.toLowerCase().includes(n))}close(n=null){this.onComplete?.(n),this.onComplete=void 0,this.remove()}async selectMessage(n){this.forking=!0;try{const e=await this.agent.fork(n.entryId);if(e.cancelled){this.forking=!1;return}this.close({text:e.text,newSessionPath:e.newSessionPath})}catch(e){console.error("Fork failed:",e),this.forking=!1}}onKeyDown(n){const e=this.filteredMessages;n.key==="Escape"?(n.preventDefault(),this.close()):n.key==="ArrowDown"?(n.preventDefault(),this.selectedIndex=Math.min(this.selectedIndex+1,e.length-1),this.scrollSelectedIntoView()):n.key==="ArrowUp"?(n.preventDefault(),this.selectedIndex=Math.max(this.selectedIndex-1,0),this.scrollSelectedIntoView()):n.key==="Enter"&&(n.preventDefault(),e.length>0&&this.selectedIndex<e.length&&this.selectMessage(e[this.selectedIndex]))}scrollSelectedIntoView(){requestAnimationFrame(()=>{const e=this.shadowRoot?.querySelector(".messages-list")?.querySelectorAll(".message-item");e&&e[this.selectedIndex]&&e[this.selectedIndex].scrollIntoView({block:"nearest"})})}onSearchInput(n){this.search=n.target.value,this.selectedIndex=0}firstUpdated(){requestAnimationFrame(()=>{this.shadowRoot?.querySelector(".search-input")?.focus()})}render(){const n=this.filteredMessages;return Q`
|
|
3953
3953
|
<div class="backdrop" @click=${()=>this.close()}></div>
|
|
3954
3954
|
<div class="modal" @keydown=${e=>this.onKeyDown(e)}>
|
|
3955
3955
|
${this.forking?Q`<div class="forking-overlay"><span class="forking-text">Forking session…</span></div>`:sr}
|
|
@@ -4185,18 +4185,18 @@ ${u}`:u?h=u:p&&p!=="{}"&&(h=p);const f=Q`<span class="inline-block ${sb(a)}">${R
|
|
|
4185
4185
|
font-family: inherit;
|
|
4186
4186
|
color: var(--muted-foreground, #6b7280);
|
|
4187
4187
|
}
|
|
4188
|
-
`;Sh([Ge({attribute:!1})],Zc.prototype,"agent",2);Sh([lt()],Zc.prototype,"messages",2);Sh([lt()],Zc.prototype,"loading",2);Sh([lt()],Zc.prototype,"forking",2);Sh([lt()],Zc.prototype,"search",2);Sh([lt()],Zc.prototype,"selectedIndex",2);Zc=Sh([sn("fork-modal")],Zc);let jl=!1,lp=null,PL=null,em,fs=[],Xo=new Set,fS=null,_x=!1,mS=null,av=null,qc=null,kf=new Set,Bae=0;const gS=200,CO=3;function AO(){return jl}function
|
|
4189
|
-
`).filter(r=>r.trim());(t.length!==fs.length||t.some((r,i)=>r!==fs[i]))&&(fs=t,xo())}catch{}}function
|
|
4190
|
-
`);if(!(n.length>gS||i.length>CO))return`<span class="jsonl-str">"${BI(n)}"</span>`;if(r){const u=BI(n),d=n.length,p=i.length,h=p>1?`${d} chars, ${p} lines`:`${d} chars`;return`<span class="jsonl-str jsonl-str-long">"<span class="jsonl-str-content">${u}</span>"</span><button class="jsonl-str-toggle" data-str-id="${t}" onclick="this.dispatchEvent(new CustomEvent('toggle-string', {bubbles:true, detail:'${t}'}))" title="Collapse string">▲ collapse (${h})</button>`}const s=
|
|
4191
|
-
`)}function
|
|
4192
|
-
`);return t.length>gS?t.slice(0,gS):t}return n.slice(0,gS)}function RO(n,e,t){if(n===null)return'<span class="jsonl-null">null</span>';if(typeof n=="boolean")return`<span class="jsonl-bool">${n}</span>`;if(typeof n=="number")return`<span class="jsonl-num">${n}</span>`;if(typeof n=="string")return
|
|
4188
|
+
`;Sh([Ge({attribute:!1})],Zc.prototype,"agent",2);Sh([lt()],Zc.prototype,"messages",2);Sh([lt()],Zc.prototype,"loading",2);Sh([lt()],Zc.prototype,"forking",2);Sh([lt()],Zc.prototype,"search",2);Sh([lt()],Zc.prototype,"selectedIndex",2);Zc=Sh([sn("fork-modal")],Zc);let jl=!1,lp=null,PL=null,em,fs=[],Xo=new Set,fS=null,_x=!1,mS=null,av=null,qc=null,kf=new Set,Bae=0;const gS=200,CO=3;function AO(){return jl}function gst(){jl=!jl,jl?(vx(),yst()):ML(),PL?.()}function _st(){jl=!1,ML(),av=null,qc&&(clearTimeout(qc),qc=null),xo(),PL?.()}function vst(n,e){lp=n,PL=e,xo()}function mH(n){n!==em&&(em=n,fs=[],Xo.clear(),kf.clear(),av=null,qc&&(clearTimeout(qc),qc=null),_x=!1,jl&&vx())}function UI(){jl&&em&&vx()}function bst(n,e){if(!jl||!lp||fs.length===0)return!1;let t=(e?kst(e):null)??Ist(n);return t==null?!1:(av=t,Xo.delete(t),_x=!0,xo(),requestAnimationFrame(()=>{const r=lp?.querySelector(`.jsonl-entry[data-line-index="${t}"]`);r&&(r.scrollIntoView({block:"center",behavior:"smooth"}),r.classList.add("jsonl-jump-flash"),qc&&clearTimeout(qc),qc=setTimeout(()=>{r.classList.remove("jsonl-jump-flash"),av=null,xo()},1200))}),!0)}function yst(){ML(),mS=setInterval(()=>{jl&&em&&vx()},1500)}function ML(){mS&&(clearInterval(mS),mS=null)}async function vx(){if(!em){fs=[],xo();return}try{const n=await fetch(`/api/sessions/raw?path=${encodeURIComponent(em)}`);if(!n.ok){fs=[],xo();return}const t=(await n.text()).split(`
|
|
4189
|
+
`).filter(r=>r.trim());(t.length!==fs.length||t.some((r,i)=>r!==fs[i]))&&(fs=t,xo())}catch{}}function Est(n){Xo.has(n)?Xo.delete(n):Xo.add(n),xo()}function Sst(n){kf.has(n)?kf.delete(n):kf.add(n),xo()}function Tst(n){const e=n.target;if(!e)return;_x=!(e.scrollHeight-e.scrollTop-e.clientHeight<60)}function wst(){fS&&!_x&&(fS.scrollTop=fS.scrollHeight)}function xst(n,e){try{const t=JSON.parse(n);return Bae=0,RO(t,0,e)}catch{return uT(n)}}function uT(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Cst(n,e){const t=`s-${e}-${Bae++}`,r=kf.has(t),i=n.split(`
|
|
4190
|
+
`);if(!(n.length>gS||i.length>CO))return`<span class="jsonl-str">"${BI(n)}"</span>`;if(r){const u=BI(n),d=n.length,p=i.length,h=p>1?`${d} chars, ${p} lines`:`${d} chars`;return`<span class="jsonl-str jsonl-str-long">"<span class="jsonl-str-content">${u}</span>"</span><button class="jsonl-str-toggle" data-str-id="${t}" onclick="this.dispatchEvent(new CustomEvent('toggle-string', {bubbles:true, detail:'${t}'}))" title="Collapse string">▲ collapse (${h})</button>`}const s=Ast(n,i),o=n.length,l=i.length,c=l>1?`${o} chars, ${l} lines`:`${o} chars`;return`<span class="jsonl-str jsonl-str-long jsonl-str-truncated">"<span class="jsonl-str-content">${BI(s)}</span>…"</span><button class="jsonl-str-toggle" data-str-id="${t}" onclick="this.dispatchEvent(new CustomEvent('toggle-string', {bubbles:true, detail:'${t}'}))" title="Expand full string">▼ expand (${c})</button>`}function BI(n){return uT(n).replace(/\n/g,`<span class="jsonl-str-newline">↵</span>
|
|
4191
|
+
`)}function Ast(n,e){if(e.length>CO){const t=e.slice(0,CO).join(`
|
|
4192
|
+
`);return t.length>gS?t.slice(0,gS):t}return n.slice(0,gS)}function RO(n,e,t){if(n===null)return'<span class="jsonl-null">null</span>';if(typeof n=="boolean")return`<span class="jsonl-bool">${n}</span>`;if(typeof n=="number")return`<span class="jsonl-num">${n}</span>`;if(typeof n=="string")return Cst(n,t);if(Array.isArray(n)){if(n.length===0)return'<span class="jsonl-bracket">[]</span>';const r=" ".repeat(e+1),i=" ".repeat(e);return`<span class="jsonl-bracket">[</span>
|
|
4193
4193
|
${n.map(s=>`${r}${RO(s,e+1,t)}`).join(`,
|
|
4194
4194
|
`)}
|
|
4195
4195
|
${i}<span class="jsonl-bracket">]</span>`}if(typeof n=="object"){const r=Object.keys(n);if(r.length===0)return'<span class="jsonl-bracket">{}</span>';const i=" ".repeat(e+1),a=" ".repeat(e);return`<span class="jsonl-bracket">{</span>
|
|
4196
4196
|
${r.map(o=>{const l=`<span class="jsonl-key">"${uT(o)}"</span>`,c=RO(n[o],e+1,t);return`${i}${l}<span class="jsonl-colon">: </span>${c}`}).join(`,
|
|
4197
4197
|
`)}
|
|
4198
|
-
${a}<span class="jsonl-bracket">}</span>`}return uT(String(n))}function
|
|
4199
|
-
<div class="jsonl-panel" @toggle-string=${e=>
|
|
4198
|
+
${a}<span class="jsonl-bracket">}</span>`}return uT(String(n))}function Rst(n){try{const e=JSON.parse(n),t=e.type||"unknown";return t==="message"&&e.message?.role?`${t} (${e.message.role})`:t==="context"?"context":t==="config"?"config":t}catch{return"parse error"}}function $ae(n){try{return JSON.parse(n)}catch{return null}}function kst(n){if(!n)return null;for(let e=0;e<fs.length;e++){const t=$ae(fs[e]);if(!t||t.type!=="message")continue;const r=t.message;if(r?.role==="toolResult"&&r.toolCallId===n)return e}return null}function Ist(n){if(n<0)return null;let e=0;for(let t=0;t<fs.length;t++){const r=$ae(fs[t]);if(!r||r.type!=="message")continue;const i=r.message?.role;if(!(i==="toolResult"||i==="artifact")){if(e===n)return t;e++}}return null}function xo(){if(!lp)return;if(!jl){ol(Q``,lp);return}const n=Q`
|
|
4199
|
+
<div class="jsonl-panel" @toggle-string=${e=>Sst(e.detail)}>
|
|
4200
4200
|
<div class="jsonl-header">
|
|
4201
4201
|
<span class="jsonl-title">Raw JSONL</span>
|
|
4202
4202
|
<div class="jsonl-header-actions">
|
|
@@ -4236,30 +4236,30 @@ ${a}<span class="jsonl-bracket">}</span>`}return uT(String(n))}function Ast(n){t
|
|
|
4236
4236
|
</button>
|
|
4237
4237
|
<button
|
|
4238
4238
|
class="jsonl-close"
|
|
4239
|
-
@click=${()=>
|
|
4239
|
+
@click=${()=>_st()}
|
|
4240
4240
|
title="Close JSONL viewer"
|
|
4241
4241
|
>✕</button>
|
|
4242
4242
|
</div>
|
|
4243
4243
|
</div>
|
|
4244
|
-
<div class="jsonl-body" @scroll=${
|
|
4244
|
+
<div class="jsonl-body" @scroll=${Tst}>
|
|
4245
4245
|
${fs.length===0?Q`<div class="jsonl-empty">No session data</div>`:fs.map((e,t)=>Q`
|
|
4246
4246
|
<div
|
|
4247
4247
|
class="jsonl-entry ${Xo.has(t)?"collapsed":""} ${av===t?"jsonl-entry-focused":""}"
|
|
4248
4248
|
data-line-index="${t}"
|
|
4249
4249
|
>
|
|
4250
|
-
<div class="jsonl-entry-header" @click=${()=>
|
|
4250
|
+
<div class="jsonl-entry-header" @click=${()=>Est(t)}>
|
|
4251
4251
|
<span class="jsonl-chevron">${Xo.has(t)?"▶":"▼"}</span>
|
|
4252
4252
|
<span class="jsonl-line-num">${t+1}</span>
|
|
4253
|
-
<span class="jsonl-line-label">${
|
|
4253
|
+
<span class="jsonl-line-label">${Rst(e)}</span>
|
|
4254
4254
|
</div>
|
|
4255
|
-
${Xo.has(t)?"":Q`<pre class="jsonl-content"><code .innerHTML=${
|
|
4255
|
+
${Xo.has(t)?"":Q`<pre class="jsonl-content"><code .innerHTML=${xst(e,t)}></code></pre>`}
|
|
4256
4256
|
</div>
|
|
4257
4257
|
`)}
|
|
4258
4258
|
</div>
|
|
4259
4259
|
</div>
|
|
4260
|
-
`;ol(n,lp),fS=lp.querySelector(".jsonl-body"),requestAnimationFrame(()=>
|
|
4260
|
+
`;ol(n,lp),fS=lp.querySelector(".jsonl-body"),requestAnimationFrame(()=>wst())}function Nst(n,e){if(!n||n.length===0)return window.alert("No models available from pi. Check your provider login/API keys."),Promise.resolve(null);const t=[...n].sort((r,i)=>`${r.provider}/${r.id}`.localeCompare(`${i.provider}/${i.id}`));return new Promise(r=>{const i=document.createElement("div");i.className="model-picker-overlay";const a=document.createElement("div");a.className="model-picker-panel";const s=document.createElement("div");s.className="model-picker-header",s.textContent="Select model";const o=document.createElement("input");o.className="model-picker-search",o.type="text",o.placeholder="Search provider/model...";const l=document.createElement("div");l.className="model-picker-list";const c=document.createElement("div");c.className="model-picker-footer";const u=document.createElement("button");u.className="model-picker-cancel",u.type="button",u.textContent="Cancel";const d=f=>{document.removeEventListener("keydown",p),i.remove(),r(f)},p=f=>{f.key==="Escape"&&d(null)},h=()=>{const f=o.value.trim().toLowerCase(),m=f?t.filter(g=>`${g.provider}/${g.id} ${g.name||""}`.toLowerCase().includes(f)):t;if(l.innerHTML="",m.length===0){const g=document.createElement("div");g.className="model-picker-empty",g.textContent="No matching models",l.appendChild(g);return}for(const g of m){const _=document.createElement("button");_.type="button",_.className="model-picker-item";const v=!!e&&e.provider===g.provider&&e.id===g.id;v&&_.classList.add("is-current");const b=document.createElement("div");b.className="model-picker-item-label",b.textContent=`${g.provider}/${g.id}`;const E=document.createElement("div");E.className="model-picker-item-meta",E.textContent=v?"current":g.name||"",_.appendChild(b),_.appendChild(E),_.addEventListener("click",()=>d(g)),l.appendChild(_)}};o.addEventListener("input",h),i.addEventListener("click",f=>{f.target===i&&d(null)}),u.addEventListener("click",()=>d(null)),document.addEventListener("keydown",p),c.appendChild(u),a.appendChild(s),a.appendChild(o),a.appendChild(l),a.appendChild(c),i.appendChild(a),document.body.appendChild(i),h(),requestAnimationFrame(()=>o.focus())})}const Gae={version:1,sidebar:{cwdTitle:{filters:[]},sessionsPerProject:5}};function Dst(n){const e=JSON.parse(n);return`${JSON.stringify(e,null,2)}
|
|
4261
4261
|
`}function $I(){return`${JSON.stringify(Gae,null,2)}
|
|
4262
|
-
`}async function
|
|
4262
|
+
`}async function Ost(n){const e=document.createElement("div");e.className="local-settings-overlay";const t=document.createElement("div");t.className="local-settings-panel";const r=document.createElement("div");r.className="local-settings-header";const i=document.createElement("div");i.className="local-settings-title",i.textContent="Local settings";const a=document.createElement("button");a.type="button",a.className="local-settings-close",a.textContent="✕",a.title="Close",r.appendChild(i),r.appendChild(a);const s=document.createElement("div");s.className="local-settings-path",s.textContent="Loading…";const o=document.createElement("details");o.className="local-settings-hint",o.open=!1,o.innerHTML=`
|
|
4263
4263
|
<summary>Schema hint</summary>
|
|
4264
4264
|
<div class="local-settings-hint-body">
|
|
4265
4265
|
<p><strong>Path title pipeline:</strong> full cwd → replace HOME prefix with <code>~</code> → apply filters in order.</p>
|
|
@@ -4293,22 +4293,22 @@ ${a}<span class="jsonl-bracket">}</span>`}return uT(String(n))}function Ast(n){t
|
|
|
4293
4293
|
<p><strong>Appearance:</strong> <code>colorTheme</code>, <code>darkMode</code>, and <code>showTokenUsage</code> are also togglable from the sidebar menu.</p>
|
|
4294
4294
|
<p><strong>Tool collapse:</strong> <code>keepOpen</code> = number of recent tool calls to leave expanded. <code>0</code> = collapse all finished, <code>999999</code> = disable. Once you manually open a collapsed tool, it stays open.</p>
|
|
4295
4295
|
</div>
|
|
4296
|
-
`;const l=document.createElement("textarea");l.className="local-settings-editor",l.spellcheck=!1,l.placeholder="{}";const c=document.createElement("div");c.className="local-settings-status";const u=document.createElement("div");u.className="local-settings-footer";const d=document.createElement("div");d.className="local-settings-footer-left";const p=document.createElement("button");p.type="button",p.className="local-settings-btn",p.textContent="Reset defaults";const h=document.createElement("button");h.type="button",h.className="local-settings-btn",h.textContent="Format",d.appendChild(p),d.appendChild(h);const f=document.createElement("div");f.className="local-settings-footer-right";const m=document.createElement("button");m.type="button",m.className="local-settings-btn",m.textContent="Validate";const g=document.createElement("button");g.type="button",g.className="local-settings-btn local-settings-btn-primary",g.textContent="Save";const _=document.createElement("button");_.type="button",_.className="local-settings-btn",_.textContent="Cancel",f.appendChild(m),f.appendChild(g),f.appendChild(_),u.appendChild(d),u.appendChild(f),t.appendChild(r),t.appendChild(s),t.appendChild(o),t.appendChild(l),t.appendChild(c),t.appendChild(u),e.appendChild(t),document.body.appendChild(e);let v=!1,b=!1;const E=C=>{b=C,l.disabled=C,p.disabled=C,h.disabled=C,m.disabled=C,g.disabled=C,_.disabled=C,a.disabled=C},S=(C,D="info")=>{c.className=`local-settings-status ${D}`,c.textContent=C},w=()=>{v||(v=!0,document.removeEventListener("keydown",x),e.remove())},x=C=>{C.key==="Escape"&&!b&&(C.preventDefault(),w())};document.addEventListener("keydown",x),e.addEventListener("click",C=>{C.target===e&&!b&&w()}),a.addEventListener("click",w),_.addEventListener("click",w),h.addEventListener("click",()=>{try{l.value=
|
|
4296
|
+
`;const l=document.createElement("textarea");l.className="local-settings-editor",l.spellcheck=!1,l.placeholder="{}";const c=document.createElement("div");c.className="local-settings-status";const u=document.createElement("div");u.className="local-settings-footer";const d=document.createElement("div");d.className="local-settings-footer-left";const p=document.createElement("button");p.type="button",p.className="local-settings-btn",p.textContent="Reset defaults";const h=document.createElement("button");h.type="button",h.className="local-settings-btn",h.textContent="Format",d.appendChild(p),d.appendChild(h);const f=document.createElement("div");f.className="local-settings-footer-right";const m=document.createElement("button");m.type="button",m.className="local-settings-btn",m.textContent="Validate";const g=document.createElement("button");g.type="button",g.className="local-settings-btn local-settings-btn-primary",g.textContent="Save";const _=document.createElement("button");_.type="button",_.className="local-settings-btn",_.textContent="Cancel",f.appendChild(m),f.appendChild(g),f.appendChild(_),u.appendChild(d),u.appendChild(f),t.appendChild(r),t.appendChild(s),t.appendChild(o),t.appendChild(l),t.appendChild(c),t.appendChild(u),e.appendChild(t),document.body.appendChild(e);let v=!1,b=!1;const E=C=>{b=C,l.disabled=C,p.disabled=C,h.disabled=C,m.disabled=C,g.disabled=C,_.disabled=C,a.disabled=C},S=(C,D="info")=>{c.className=`local-settings-status ${D}`,c.textContent=C},w=()=>{v||(v=!0,document.removeEventListener("keydown",x),e.remove())},x=C=>{C.key==="Escape"&&!b&&(C.preventDefault(),w())};document.addEventListener("keydown",x),e.addEventListener("click",C=>{C.target===e&&!b&&w()}),a.addEventListener("click",w),_.addEventListener("click",w),h.addEventListener("click",()=>{try{l.value=Dst(l.value),S("Formatted JSON in editor.","ok")}catch(C){S(`Cannot format: ${C instanceof Error?C.message:String(C)}`,"error")}}),p.addEventListener("click",()=>{l.value=$I(),S("Reset editor to default settings. Click Save to persist.","info")});const A=async()=>{E(!0);try{const C=await fetch("/api/settings/local/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:l.value})}),D=await C.json();return C.ok?(D.valid?(typeof D.formatted=="string"&&(l.value=D.formatted),S("Config is valid.","ok")):S(D.errors?.join(`
|
|
4297
4297
|
`)||"Invalid config","error"),D):(S(D?.error||"Validation failed","error"),null)}catch(C){return S(C instanceof Error?C.message:String(C),"error"),null}finally{E(!1)}};m.addEventListener("click",()=>{A()}),g.addEventListener("click",async()=>{E(!0);try{const C=await fetch("/api/settings/local",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:l.value})}),D=await C.json();if(!C.ok){const N=Array.isArray(D?.errors)?D.errors.join(`
|
|
4298
4298
|
`):D?.error||"Save failed";S(N,"error");return}typeof D.formatted=="string"&&(l.value=D.formatted),S("Saved. JSON was auto-formatted.","ok"),n?.onSaved?.(),w();return}catch(C){S(C instanceof Error?C.message:String(C),"error")}finally{E(!1)}}),E(!0);try{const C=await fetch("/api/settings/local"),D=await C.json();if(!C.ok){S(D?.error||"Failed to load settings","error"),s.textContent="~/.piweb/settings.json",l.value=$I();return}const N=D;s.textContent=`${N.path}${N.exists?"":" (will be created on save)"}`,l.value=N.formatted||JSON.stringify(N.settings??Gae,null,2),N.errors?.length?S(N.errors.join(`
|
|
4299
|
-
`),"error"):S("Edit JSON, validate, then save.","info")}catch(C){S(C instanceof Error?C.message:String(C),"error"),s.textContent="~/.piweb/settings.json",l.value=$I()}finally{E(!1),requestAnimationFrame(()=>l.focus())}}"serviceWorker"in navigator&&navigator.serviceWorker.getRegistrations().then(n=>{for(const e of n)e.unregister()});
|
|
4299
|
+
`),"error"):S("Edit JSON, validate, then save.","info")}catch(C){S(C instanceof Error?C.message:String(C),"error"),s.textContent="~/.piweb/settings.json",l.value=$I()}finally{E(!1),requestAnimationFrame(()=>l.focus())}}"serviceWorker"in navigator&&navigator.serviceWorker.getRegistrations().then(n=>{for(const e of n)e.unregister()});lst();jse();let Pt;const If=()=>window.innerWidth<=768;let gH=If(),Wg=!1,dT=[];window.addEventListener("resize",()=>{const n=If();n!==gH&&(gH=n,n||(Wg=!1),Ga())});let GI=!1,WI=!1,_H=!1,tp,sv=!0,pT=0,hT=!1,ef=!1,fT=5;const Pst=!1;oT("frontend_bootstrap_loaded",{url:window.location.pathname});function Mst(){return!bT()}function Lst(){Qse(!bT())}function Fst(){const n=document.querySelector("message-editor");if(!n)return;n.allowSendDuringStreaming=!0,n.onKeyDown=t=>{if(t.key==="Enter"&&(t.metaKey||t.ctrlKey)&&!t.shiftKey){if(t.preventDefault(),!n.processingFiles&&(n.value.trim()||n.attachments.length>0)){const r=n.value,i=n.attachments;n.value="",n.attachments=[],Yst(r,i)}return!0}return!1},n.onModelSelect=async()=>{try{const t=await Pt.fetchAvailableModels(),r=await Nst(t,Pt.state.model);r&&Pt.setModel(r)}catch(t){console.error("Failed to open model picker:",t)}};const e=n.updated?.bind(n);n.updated=t=>{e?.(t)}}function Ust(n,e){const t=[],r=[];if(e&&e.length>0)for(const s of e)s.type==="image"?t.push({type:"image",data:s.content,mimeType:s.mimeType}):s.extractedText&&r.push(s.extractedText);const i=r.length>0?n?n+`
|
|
4300
4300
|
|
|
4301
4301
|
`+r.join(`
|
|
4302
4302
|
|
|
4303
4303
|
`):r.join(`
|
|
4304
4304
|
|
|
4305
|
-
`):n,a=document.querySelector("message-editor");a&&(a.value="",a.attachments=[]),sv=!0,
|
|
4305
|
+
`):n,a=document.querySelector("message-editor");a&&(a.value="",a.attachments=[]),sv=!0,Pt.prompt(i,t.length>0?t:void 0).catch(s=>{Pt.reportError(s,"Prompt failed"),console.error("Prompt failed:",s)})}function Bst(){_H||(_H=!0,document.addEventListener("click",n=>{if(!AO())return;const e=n.target;if(!e)return;const t=document.querySelector("pi-message-list");if(!t||!t.contains(e))return;let r=NaN;const a=e.closest("[data-message-index]")?.getAttribute("data-message-index");if(a!=null&&(r=Number(a)),!Number.isFinite(r)||r<0)return;const s=e.closest("tool-message"),o=s?.getAttribute?.("data-tool-call-id")??s?.toolCall?.id;bst(r,o||void 0)}))}function $st(){return dT.length===0?"":Q`
|
|
4306
4306
|
<div class="steering-queue">
|
|
4307
4307
|
${dT.map((n,e)=>Q`
|
|
4308
4308
|
<div class="steering-chip">
|
|
4309
4309
|
<span class="steering-chip-num">${e+1}</span>
|
|
4310
4310
|
<span class="steering-chip-text">${n.length>80?n.slice(0,80)+"…":n}</span>
|
|
4311
|
-
<button class="steering-chip-remove" @click=${()=>{
|
|
4311
|
+
<button class="steering-chip-remove" @click=${()=>{Pt.removeSteering(e)}} title="Remove from queue">
|
|
4312
4312
|
<svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
|
|
4313
4313
|
<line x1="18" y1="6" x2="6" y2="18"></line>
|
|
4314
4314
|
<line x1="6" y1="6" x2="18" y2="18"></line>
|
|
@@ -4317,10 +4317,10 @@ ${a}<span class="jsonl-bracket">}</span>`}return uT(String(n))}function Ast(n){t
|
|
|
4317
4317
|
</div>
|
|
4318
4318
|
`)}
|
|
4319
4319
|
</div>
|
|
4320
|
-
`}const zI=["off","minimal","low","medium","high"];function
|
|
4320
|
+
`}const zI=["off","minimal","low","medium","high"];function Gst(n){if(!n)return!1;if(typeof n.reasoning=="boolean")return n.reasoning;const e=String(n.provider??"").toLowerCase(),t=String(n.id??"").toLowerCase();return!!(e==="openai-codex"||e==="openai"&&t.startsWith("gpt-5"))}function Wst(){if(!Pt)return"";const n=Pt.state?.model;if(!Gst(n))return"";const e=Pt.state?.thinkingLevel??"off",t=zI.indexOf(e),r=zI[(t+1)%zI.length],i=t,a=`Thinking: ${e} (click to switch to ${r})`;return Q`
|
|
4321
4321
|
<button
|
|
4322
4322
|
class="thinking-icon-btn"
|
|
4323
|
-
@click=${()=>
|
|
4323
|
+
@click=${()=>Pt?.setThinkingLevel(r)}
|
|
4324
4324
|
title=${a}
|
|
4325
4325
|
>
|
|
4326
4326
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
@@ -4331,13 +4331,13 @@ ${a}<span class="jsonl-bracket">}</span>`}return uT(String(n))}function Ast(n){t
|
|
|
4331
4331
|
${[0,1,2,3].map(s=>Q`<span class="thinking-bar ${s<i?"filled":""}"></span>`)}
|
|
4332
4332
|
</span>
|
|
4333
4333
|
</button>
|
|
4334
|
-
`}function
|
|
4334
|
+
`}function zst(){return Q`${Wst()}${Hst()}`}async function qst(){if(!WI){WI=!0;try{await Ost({onSaved:()=>{Fae(),Ga(),document.querySelector("session-picker")?.refreshSessions?.()}})}finally{WI=!1}}}function qI(n){return n<1e3?String(n):n<1e4?`${(n/1e3).toFixed(1)}k`:`${Math.round(n/1e3)}k`}let N0="";function Hst(){if(!Pt)return"";const n=Pt.state,e=n.messages.filter(s=>s.role==="assistant").reduce((s,o)=>{const l=o.usage;return l&&(s.input+=l.input??l.inputTokens??0,s.output+=l.output??l.outputTokens??0,s.cacheRead+=l.cacheRead??0,s.cacheWrite+=l.cacheWrite??0,s.cost.total+=l.cost?.total??l.totalCost??0),s},{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}});if(!(e.input||e.output||e.cacheRead||e.cacheWrite))return n.messages.length===0?N0:(N0="","");const r=n.messages.filter(s=>s.role==="assistant"&&s.usage),a=(r.length?r[r.length-1].usage:null)?.totalTokens??0;try{const s=[],o=n.model?.contextWindow;if(a&&o){const l=Math.round(a/o*100);s.push(`↑${l}%/${qI(o)}`)}else e.input&&s.push(`↑${qI(e.input)}`);return e.output&&s.push(`↓${qI(e.output)}`),e.cost?.total&&s.push(`$${e.cost.total<.01?e.cost.total.toFixed(4):e.cost.total<1?e.cost.total.toFixed(3):e.cost.total.toFixed(2)}`),s.length?(N0=Q`<span class="input-token-usage">${s.join(" ")}</span>`,N0):(N0="","")}catch{return""}}function Vst(n){const e=n.target;if(!e||hT)return;const t=e.scrollTop,r=e.scrollHeight-t-e.clientHeight;t!==0&&t<pT&&r>50?sv=!1:r<10&&(sv=!0),pT=t}function Wae(){sv&&(hT=!0,requestAnimationFrame(()=>{const n=document.getElementById("chat-scroll-area");n&&(n.scrollTop=n.scrollHeight,pT=n.scrollTop),requestAnimationFrame(()=>{hT=!1})}))}const Ga=()=>{const n=document.getElementById("app");if(!n)return;const e=document.getElementById("skeleton-shell");e&&e.remove();const t=Pt?.state,r=t?.messages??[],i=t?.isStreaming??!1,a={onToggleTokenUsage:()=>{Lst(),Ga()},onOpenSettings:()=>{qst()},onToggleJsonl:()=>{gst(),Ga()},isTokenUsageHidden:Mst(),isJsonlVisible:AO(),isDevMode:Pst},s=Q`
|
|
4335
4335
|
<div class="w-full h-screen flex flex-col bg-background text-foreground overflow-hidden">
|
|
4336
4336
|
<!-- Main content: sidebar + chat -->
|
|
4337
4337
|
<div class="flex flex-1 overflow-hidden">
|
|
4338
4338
|
${If()?"":Q`
|
|
4339
4339
|
<div class="shrink-0 border-r border-border bg-background overflow-hidden" style="width: 280px;">
|
|
4340
|
-
<session-picker .agent=${
|
|
4340
|
+
<session-picker .agent=${Pt} .prefetchedSessions=${tp} .burgerMenu=${a} .sessionsPerProject=${fT}></session-picker>
|
|
4341
4341
|
</div>
|
|
4342
4342
|
`}
|
|
4343
4343
|
<div class="flex-1 overflow-hidden flex flex-col">
|
|
@@ -4354,7 +4354,7 @@ ${a}<span class="jsonl-bracket">}</span>`}return uT(String(n))}function Ast(n){t
|
|
|
4354
4354
|
</svg>
|
|
4355
4355
|
</button>
|
|
4356
4356
|
`:""}
|
|
4357
|
-
${
|
|
4357
|
+
${Pt&&!Pt.isConnected?Q`
|
|
4358
4358
|
<div class="flex items-center justify-center gap-2 px-4 py-1.5 bg-yellow-500/15 border-b border-yellow-500/30 text-sm text-yellow-700 dark:text-yellow-400">
|
|
4359
4359
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0 animate-spin" style="animation-duration: 1.5s;">
|
|
4360
4360
|
<path d="M21 12a9 9 0 1 1-6.219-8.56"></path>
|
|
@@ -4362,28 +4362,38 @@ ${a}<span class="jsonl-bracket">}</span>`}return uT(String(n))}function Ast(n){t
|
|
|
4362
4362
|
<span>Reconnecting to server…</span>
|
|
4363
4363
|
</div>
|
|
4364
4364
|
`:""}
|
|
4365
|
-
${
|
|
4365
|
+
${t?.error?Q`
|
|
4366
|
+
<div class="flex items-center gap-2 px-4 py-1.5 bg-red-500/15 border-b border-red-500/30 text-sm text-red-700 dark:text-red-400" title=${t.error}>
|
|
4367
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0">
|
|
4368
|
+
<circle cx="12" cy="12" r="10"></circle>
|
|
4369
|
+
<line x1="12" y1="8" x2="12" y2="12"></line>
|
|
4370
|
+
<line x1="12" y1="16" x2="12.01" y2="16"></line>
|
|
4371
|
+
</svg>
|
|
4372
|
+
<span class="truncate">${t.error}</span>
|
|
4373
|
+
</div>
|
|
4374
|
+
`:""}
|
|
4375
|
+
${Pt?.sessionStatus==="virtual"&&Pt?.cwd&&r.length===0?Q`
|
|
4366
4376
|
<div class="flex items-center gap-2 px-4 py-2 border-b border-border bg-accent/50 text-sm text-muted-foreground">
|
|
4367
4377
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0">
|
|
4368
4378
|
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path>
|
|
4369
4379
|
</svg>
|
|
4370
|
-
<span>New conversation in <span class="font-medium text-foreground" title="${
|
|
4380
|
+
<span>New conversation in <span class="font-medium text-foreground" title="${Pt.cwd}">${Pt.cwd.split("/").filter(Boolean).pop()||Pt.cwd}</span></span>
|
|
4371
4381
|
</div>
|
|
4372
4382
|
`:""}
|
|
4373
4383
|
<div class="flex-1 overflow-hidden flex">
|
|
4374
4384
|
<div class="flex-1 overflow-hidden relative flex flex-col">
|
|
4375
4385
|
<!-- Messages area -->
|
|
4376
|
-
<div id="chat-scroll-area" class="flex-1 overflow-y-auto" @scroll=${
|
|
4386
|
+
<div id="chat-scroll-area" class="flex-1 overflow-y-auto" @scroll=${Vst}>
|
|
4377
4387
|
<div class="max-w-3xl mx-auto p-4 pb-4">
|
|
4378
4388
|
<pi-message-list
|
|
4379
4389
|
.messages=${r}
|
|
4380
4390
|
.isStreaming=${i}
|
|
4381
|
-
.pendingToolCalls=${
|
|
4391
|
+
.pendingToolCalls=${Pt?.pendingToolCallIds??new Set}
|
|
4382
4392
|
></pi-message-list>
|
|
4383
4393
|
</div>
|
|
4384
4394
|
</div>
|
|
4385
4395
|
<!-- Steering queue (between messages and input) -->
|
|
4386
|
-
${
|
|
4396
|
+
${$st()}
|
|
4387
4397
|
<!-- Input area -->
|
|
4388
4398
|
<div class="shrink-0 border-t border-border">
|
|
4389
4399
|
<div class="max-w-3xl mx-auto px-2">
|
|
@@ -4395,15 +4405,15 @@ ${a}<span class="jsonl-bracket">}</span>`}return uT(String(n))}function Ast(n){t
|
|
|
4395
4405
|
.showAttachmentButton=${!0}
|
|
4396
4406
|
.showModelSelector=${!0}
|
|
4397
4407
|
.showThinkingSelector=${!1}
|
|
4398
|
-
.onSend=${(o,l)=>
|
|
4399
|
-
.onAbort=${()=>
|
|
4400
|
-
.onThinkingChange=${o=>
|
|
4401
|
-
.extraToolbarButtons=${()=>
|
|
4408
|
+
.onSend=${(o,l)=>Ust(o,l)}
|
|
4409
|
+
.onAbort=${()=>Pt?.abort()}
|
|
4410
|
+
.onThinkingChange=${o=>Pt?.setThinkingLevel(o)}
|
|
4411
|
+
.extraToolbarButtons=${()=>zst()}
|
|
4402
4412
|
></message-editor>
|
|
4403
4413
|
</div>
|
|
4404
4414
|
</div>
|
|
4405
4415
|
</div>
|
|
4406
|
-
${ef&&
|
|
4416
|
+
${ef&&qat()?Q`<div id="canvas-container" class="canvas-container border-l border-border"></div>`:""}
|
|
4407
4417
|
${AO()?Q`<div id="jsonl-container" class="jsonl-container border-l border-border"></div>`:""}
|
|
4408
4418
|
</div>
|
|
4409
4419
|
</div>
|
|
@@ -4412,22 +4422,22 @@ ${a}<span class="jsonl-bracket">}</span>`}return uT(String(n))}function Ast(n){t
|
|
|
4412
4422
|
`;if(Wg&&If()){const o=Q`
|
|
4413
4423
|
<div class="sidebar-mobile-overlay">
|
|
4414
4424
|
<div class="sidebar-panel shrink-0 border-r border-border bg-background overflow-hidden">
|
|
4415
|
-
<session-picker .agent=${
|
|
4425
|
+
<session-picker .agent=${Pt} .prefetchedSessions=${tp} .burgerMenu=${a} .sessionsPerProject=${fT}></session-picker>
|
|
4416
4426
|
</div>
|
|
4417
4427
|
<div class="sidebar-mobile-backdrop" @click=${()=>{Wg=!1,Ga()}}></div>
|
|
4418
4428
|
</div>
|
|
4419
|
-
`;ol(Q`${s}${o}`,n)}else ol(s,n);requestAnimationFrame(()=>{
|
|
4429
|
+
`;ol(Q`${s}${o}`,n)}else ol(s,n);requestAnimationFrame(()=>{Fst(),Wae(),jat();const o=document.getElementById("canvas-container");o&&Hat(o,Ga);const l=document.getElementById("jsonl-container");l&&vst(l,Ga)})};async function Yst(n,e){const t=[],r=[];if(e&&e.length>0)for(const a of e)a.type==="image"?t.push({type:"image",data:a.content,mimeType:a.mimeType}):a.extractedText&&r.push(a.extractedText);const i=r.length>0?n?n+`
|
|
4420
4430
|
|
|
4421
4431
|
`+r.join(`
|
|
4422
4432
|
|
|
4423
4433
|
`):r.join(`
|
|
4424
4434
|
|
|
4425
|
-
`):n;await
|
|
4435
|
+
`):n;try{await Pt.forkAndPrompt(i,t.length>0?t:void 0)}catch(a){Pt.reportError(a,"Fork prompt failed"),console.error("Fork prompt failed:",a)}}async function Kst(){oT("init_app_start"),oat();const n=document.getElementById("app");if(!n)throw new Error("App container not found");let e;const t=document.getElementById("skeleton-shell");e=setTimeout(()=>{if(t?.parentElement===n){const g=document.createElement("div");g.id="connecting-overlay",g.style.cssText="position:absolute;bottom:2rem;left:50%;transform:translateX(-50%);color:var(--muted-foreground,#6b7280);font-size:0.8rem;z-index:10;",g.textContent="Connecting…",t.style.position="relative",t.appendChild(g)}},300);const r=new aat,i=new rat,a=new iat,s=new nat,o=new pat;r.setBackend(o),i.setBackend(o),a.setBackend(o),s.setBackend(o);const l=new K3e(r,i,a,s,o);Q3e(l);try{const g=await fetch("/api/settings/local");if(g.ok){const _=await g.json();ef=_.settings?.canvas?.enabled===!0,typeof _.settings?.sidebar?.sessionsPerProject=="number"&&(fT=_.settings.sidebar.sessionsPerProject)}}catch{}Pt=new dat;const u=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?traceId=${encodeURIComponent(wae())}`,d=$g("frontend_ws_connect");try{await Pt.connect(u),d()}catch{d(),clearTimeout(e),ol(Q`
|
|
4426
4436
|
<div class="w-full h-screen flex items-center justify-center bg-background text-foreground">
|
|
4427
4437
|
<div class="text-destructive">Failed to connect to server. Is the backend running?</div>
|
|
4428
4438
|
</div>
|
|
4429
|
-
`,n);return}clearTimeout(e);const p=
|
|
4439
|
+
`,n);return}clearTimeout(e);const p=Pt.listSessions().catch(g=>{console.error("Failed to prefetch sessions:",g)});Bst(),Pt.subscribe(g=>{if((g.type==="agent_start"||g.type==="agent_end")&&(mH(Pt.sessionFile),UI()),g.type==="message_end"&&UI(),ef&&g.type==="tool_execution_end"&&g.toolName==="canvas"){const _=g.result?.details;if(_?.markdown&&(IL(_.title||"Canvas",_.markdown),Pt.sessionFile)){const v=Pt.state.messages;for(let b=v.length-1;b>=0;b--){const E=v[b];if(E.role==="toolResult"&&E.toolName==="canvas"){Lae(Mae(Pt.sessionFile,b));break}}}}}),Pt.onSessionsChanged(async g=>{if(g==="__local_settings__"){try{const _=await fetch("/api/settings/local");if(_.ok){const v=await _.json();ef=v.settings?.canvas?.enabled===!0,typeof v.settings?.sidebar?.sessionsPerProject=="number"&&(fT=v.settings.sidebar.sessionsPerProject)}}catch{}await Xse(),Ga()}}),Pt.onSessionChange(async()=>{dT=Pt.steeringQueue,Kat(),ef&&hH(Pt.state.messages,Pt.sessionFile),mH(Pt.sessionFile),sv=!0,pT=0,hT=!1,If()&&(Wg=!1),Ga(),requestAnimationFrame(()=>{const g=document.querySelector("message-editor");(g?.shadowRoot?.querySelector("textarea")??g?.textareaRef?.value)?.focus()})}),Pt.onContentChange(()=>{ef&&hH(Pt.state.messages,Pt.sessionFile),UI(),Ga(),Wae()}),Pt.onStatusChange(()=>{Ga()}),Pt.onConnectionChange(g=>{Ga()}),Pt.onSteeringQueueChange(()=>{dT=Pt.steeringQueue,Ga()}),Pt.onPiInstallRequired(async g=>{if(!GI){GI=!0;try{if(!g.installable){alert(`${g.message}
|
|
4430
4440
|
|
|
4431
4441
|
Please install pi manually or set PI_CLI.`);return}if(g.installing||!window.confirm(`${g.message}
|
|
4432
4442
|
|
|
4433
|
-
Install pi now? (npm install -g @mariozechner/pi-coding-agent)`))return;await
|
|
4443
|
+
Install pi now? (npm install -g @mariozechner/pi-coding-agent)`))return;await Pt.installPi(),alert("pi installed. You can retry your action now.")}catch(_){alert(_ instanceof Error?_.message:String(_))}finally{GI=!1}}});const h=async()=>{if(!Pt.sessionFile||Pt.sessionStatus==="virtual")return;const g=document.createElement("fork-modal");document.body.appendChild(g);const _=await g.open(Pt);if(_&&(_.newSessionPath&&await Pt.switchSession(_.newSessionPath),_.text)){const v=document.querySelector("message-editor");v&&(v.value=_.text,v.requestUpdate(),requestAnimationFrame(()=>{(v.shadowRoot?.querySelector("textarea")??v.textareaRef?.value)?.focus()}))}};window.addEventListener("pi-fork-request",h),Fae();const f=$g("frontend_load_default_model");await Pt.loadDefaultModel(),f(),tp=await p??void 0;const m=$g("frontend_new_session");if(tp&&tp.length>0){const g=tp.reduce((_,v)=>{const b=_.lastUserPromptTime?new Date(_.lastUserPromptTime).getTime():new Date(_.modified).getTime();return(v.lastUserPromptTime?new Date(v.lastUserPromptTime).getTime():new Date(v.modified).getTime())>b?v:_});await Pt.switchSession(g.path)}else await Pt.newSession();m(),Ga(),tp=void 0,oT("frontend_first_render_complete",{sessionStatus:Pt.sessionStatus})}Kst();export{Cp as H,ah as a,tj as b,Rb as c,vm as d,Rp as f,Pot as g,plt as t};
|