@sunerpy/kiro-provider 0.4.0 → 0.5.0-rc.1
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/README.md +188 -37
- package/dist/cli.js +134 -88
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,60 +1,60 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
GFS4: `),console.error(n)};if(!ln[$n]){if(oh=global[$n]||[],F0(ln,oh),ln.close=function(n){function t(i,s){return n.call(ln,i,function(r){if(!r)W0();if(typeof s==="function")s.apply(this,arguments)})}return Object.defineProperty(t,We,{value:n}),t}(ln.close),ln.closeSync=function(n){function t(i){n.apply(ln,arguments),W0()}return Object.defineProperty(t,We,{value:n}),t}(ln.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){Oi(ln[$n]),p("assert").equal(ln[$n].length,0)})}var oh;if(!global[$n])F0(global,ln[$n]);uh.exports=fh(b2(ln));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!ln.__patched)uh.exports=fh(ln),ln.__patched=!0;function fh(n){I2(n),n.gracefulify=fh,n.createReadStream=I,n.createWriteStream=F;var t=n.readFile;n.readFile=i;function i(b,$,N){if(typeof $==="function")N=$,$=null;return B(b,$,N);function B(g,X,Z,tn){return t(g,X,function(en){if(en&&(en.code==="EMFILE"||en.code==="ENFILE"))ys([B,[g,X,Z],en,tn||Date.now(),Date.now()]);else if(typeof Z==="function")Z.apply(this,arguments)})}}var s=n.writeFile;n.writeFile=r;function r(b,$,N,B){if(typeof N==="function")B=N,N=null;return g(b,$,N,B);function g(X,Z,tn,en,H){return s(X,Z,tn,function(W){if(W&&(W.code==="EMFILE"||W.code==="ENFILE"))ys([g,[X,Z,tn,en],W,H||Date.now(),Date.now()]);else if(typeof en==="function")en.apply(this,arguments)})}}var e=n.appendFile;if(e)n.appendFile=f;function f(b,$,N,B){if(typeof N==="function")B=N,N=null;return g(b,$,N,B);function g(X,Z,tn,en,H){return e(X,Z,tn,function(W){if(W&&(W.code==="EMFILE"||W.code==="ENFILE"))ys([g,[X,Z,tn,en],W,H||Date.now(),Date.now()]);else if(typeof en==="function")en.apply(this,arguments)})}}var o=n.copyFile;if(o)n.copyFile=h;function h(b,$,N,B){if(typeof N==="function")B=N,N=0;return g(b,$,N,B);function g(X,Z,tn,en,H){return o(X,Z,tn,function(W){if(W&&(W.code==="EMFILE"||W.code==="ENFILE"))ys([g,[X,Z,tn,en],W,H||Date.now(),Date.now()]);else if(typeof en==="function")en.apply(this,arguments)})}}var u=n.readdir;n.readdir=_;var c=/^v[0-5]\./;function _(b,$,N){if(typeof $==="function")N=$,$=null;var B=c.test(process.version)?function(Z,tn,en,H){return u(Z,g(Z,tn,en,H))}:function(Z,tn,en,H){return u(Z,tn,g(Z,tn,en,H))};return B(b,$,N);function g(X,Z,tn,en){return function(H,W){if(H&&(H.code==="EMFILE"||H.code==="ENFILE"))ys([B,[X,Z,tn],H,en||Date.now(),Date.now()]);else{if(W&&W.sort)W.sort();if(typeof tn==="function")tn.call(this,H,W)}}}}if(process.version.substr(0,4)==="v0.8"){var w=U2(n);R=w.ReadStream,T=w.WriteStream}var l=n.ReadStream;if(l)R.prototype=Object.create(l.prototype),R.prototype.open=y;var A=n.WriteStream;if(A)T.prototype=Object.create(A.prototype),T.prototype.open=S;Object.defineProperty(n,"ReadStream",{get:function(){return R},set:function(b){R=b},enumerable:!0,configurable:!0}),Object.defineProperty(n,"WriteStream",{get:function(){return T},set:function(b){T=b},enumerable:!0,configurable:!0});var d=R;Object.defineProperty(n,"FileReadStream",{get:function(){return d},set:function(b){d=b},enumerable:!0,configurable:!0});var E=T;Object.defineProperty(n,"FileWriteStream",{get:function(){return E},set:function(b){E=b},enumerable:!0,configurable:!0});function R(b,$){if(this instanceof R)return l.apply(this,arguments),this;else return R.apply(Object.create(R.prototype),arguments)}function y(){var b=this;sn(b.path,b.flags,b.mode,function($,N){if($){if(b.autoClose)b.destroy();b.emit("error",$)}else b.fd=N,b.emit("open",N),b.read()})}function T(b,$){if(this instanceof T)return A.apply(this,arguments),this;else return T.apply(Object.create(T.prototype),arguments)}function S(){var b=this;sn(b.path,b.flags,b.mode,function($,N){if($)b.destroy(),b.emit("error",$);else b.fd=N,b.emit("open",N)})}function I(b,$){return new n.ReadStream(b,$)}function F(b,$){return new n.WriteStream(b,$)}var C=n.open;n.open=sn;function sn(b,$,N,B){if(typeof N==="function")B=N,N=null;return g(b,$,N,B);function g(X,Z,tn,en,H){return C(X,Z,tn,function(W,on){if(W&&(W.code==="EMFILE"||W.code==="ENFILE"))ys([g,[X,Z,tn,en],W,H||Date.now(),Date.now()]);else if(typeof en==="function")en.apply(this,arguments)})}}return n}function ys(n){Oi("ENQUEUE",n[0].name,n[1]),ln[$n].push(n),hh()}var He;function W0(){var n=Date.now();for(var t=0;t<ln[$n].length;++t)if(ln[$n][t].length>2)ln[$n][t][3]=n,ln[$n][t][4]=n;hh()}function hh(){if(clearTimeout(He),He=void 0,ln[$n].length===0)return;var n=ln[$n].shift(),t=n[0],i=n[1],s=n[2],r=n[3],e=n[4];if(r===void 0)Oi("RETRY",t.name,i),t.apply(null,i);else if(Date.now()-r>=60000){Oi("TIMEOUT",t.name,i);var f=i.pop();if(typeof f==="function")f.call(null,s)}else{var o=Date.now()-e,h=Math.max(e-r,1),u=Math.min(h*1.2,100);if(o>=u)Oi("RETRY",t.name,i),t.apply(null,i.concat([r]));else ln[$n].push(n)}if(He===void 0)He=setTimeout(hh,0)}});var D0=k((qC,P0)=>{function vn(n,t){if(typeof t==="boolean")t={forever:t};if(this._originalTimeouts=JSON.parse(JSON.stringify(n)),this._timeouts=n,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever)this._cachedTimeouts=this._timeouts.slice(0)}P0.exports=vn;vn.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};vn.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};vn.prototype.retry=function(n){if(this._timeout)clearTimeout(this._timeout);if(!n)return!1;var t=new Date().getTime();if(n&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(n);var i=this._timeouts.shift();if(i===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),i=this._timeouts.shift();else return!1;var s=this,r=setTimeout(function(){if(s._attempts++,s._operationTimeoutCb){if(s._timeout=setTimeout(function(){s._operationTimeoutCb(s._attempts)},s._operationTimeout),s._options.unref)s._timeout.unref()}s._fn(s._attempts)},i);if(this._options.unref)r.unref();return!0};vn.prototype.attempt=function(n,t){if(this._fn=n,t){if(t.timeout)this._operationTimeout=t.timeout;if(t.cb)this._operationTimeoutCb=t.cb}var i=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){i._operationTimeoutCb()},i._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};vn.prototype.try=function(n){console.log("Using RetryOperation.try() is deprecated"),this.attempt(n)};vn.prototype.start=function(n){console.log("Using RetryOperation.start() is deprecated"),this.attempt(n)};vn.prototype.start=vn.prototype.try;vn.prototype.errors=function(){return this._errors};vn.prototype.attempts=function(){return this._attempts};vn.prototype.mainError=function(){if(this._errors.length===0)return null;var n={},t=null,i=0;for(var s=0;s<this._errors.length;s++){var r=this._errors[s],e=r.message,f=(n[e]||0)+1;if(n[e]=f,f>=i)t=r,i=f}return t}});var m0=k((O2)=>{var L2=D0();O2.operation=function(n){var t=O2.timeouts(n);return new L2(t,{forever:n&&n.forever,unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})};O2.timeouts=function(n){if(n instanceof Array)return[].concat(n);var t={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var i in n)t[i]=n[i];if(t.minTimeout>t.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var s=[];for(var r=0;r<t.retries;r++)s.push(this.createTimeout(r,t));if(n&&n.forever&&!s.length)s.push(this.createTimeout(r,t));return s.sort(function(e,f){return e-f}),s};O2.createTimeout=function(n,t){var i=t.randomize?Math.random()+1:1,s=Math.round(i*t.minTimeout*Math.pow(t.factor,n));return s=Math.min(s,t.maxTimeout),s};O2.wrap=function(n,t,i){if(t instanceof Array)i=t,t=null;if(!i){i=[];for(var s in n)if(typeof n[s]==="function")i.push(s)}for(var r=0;r<i.length;r++){var e=i[r],f=n[e];n[e]=function(h){var u=O2.operation(t),c=Array.prototype.slice.call(arguments,1),_=c.pop();c.push(function(w){if(u.retry(w))return;if(w)arguments[0]=u.mainError();_.apply(this,arguments)}),u.attempt(function(){h.apply(n,c)})}.bind(n,f),n[e].options=t}}});var J0=k((jC,Fe)=>{Fe.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")Fe.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")Fe.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var X0=k((aC,gs)=>{var _n=global.process,Bi=function(n){return n&&typeof n==="object"&&typeof n.removeListener==="function"&&typeof n.emit==="function"&&typeof n.reallyExit==="function"&&typeof n.listeners==="function"&&typeof n.kill==="function"&&typeof n.pid==="number"&&typeof n.on==="function"};if(!Bi(_n))gs.exports=function(){return function(){}};else{if(_h=p("assert"),Ni=J0(),wh=/^win/i.test(_n.platform),Ts=p("events"),typeof Ts!=="function")Ts=Ts.EventEmitter;if(_n.__signal_exit_emitter__)Tn=_n.__signal_exit_emitter__;else Tn=_n.__signal_exit_emitter__=new Ts,Tn.count=0,Tn.emitted={};if(!Tn.infinite)Tn.setMaxListeners(1/0),Tn.infinite=!0;gs.exports=function(n,t){if(!Bi(global.process))return function(){};if(_h.equal(typeof n,"function","a callback must be provided for exit handler"),Gi===!1)Pe();var i="exit";if(t&&t.alwaysLast)i="afterexit";var s=function(){if(Tn.removeListener(i,n),Tn.listeners("exit").length===0&&Tn.listeners("afterexit").length===0)Er()};return Tn.on(i,n),s},Er=function(){if(!Gi||!Bi(global.process))return;Gi=!1,Ni.forEach(function(t){try{_n.removeListener(t,yr[t])}catch(i){}}),_n.emit=Tr,_n.reallyExit=De,Tn.count-=1},gs.exports.unload=Er,pt=function(t,i,s){if(Tn.emitted[t])return;Tn.emitted[t]=!0,Tn.emit(t,i,s)},yr={},Ni.forEach(function(n){yr[n]=function(){if(!Bi(global.process))return;var i=_n.listeners(n);if(i.length===Tn.count){if(Er(),pt("exit",null,n),pt("afterexit",null,n),wh&&n==="SIGHUP")n="SIGINT";_n.kill(_n.pid,n)}}}),gs.exports.signals=function(){return Ni},Gi=!1,Pe=function(){if(Gi||!Bi(global.process))return;Gi=!0,Tn.count+=1,Ni=Ni.filter(function(t){try{return _n.on(t,yr[t]),!0}catch(i){return!1}}),_n.emit=Ah,_n.reallyExit=lh},gs.exports.load=Pe,De=_n.reallyExit,lh=function(t){if(!Bi(global.process))return;_n.exitCode=t||0,pt("exit",_n.exitCode,null),pt("afterexit",_n.exitCode,null),De.call(_n,_n.exitCode)},Tr=_n.emit,Ah=function(t,i){if(t==="exit"&&Bi(global.process)){if(i!==void 0)_n.exitCode=i;var s=Tr.apply(this,arguments);return pt("exit",_n.exitCode,null),pt("afterexit",_n.exitCode,null),s}else return Tr.apply(this,arguments)}}var _h,Ni,wh,Ts,Tn,Er,pt,yr,Gi,Pe,De,lh,Tr,Ah});var Q0=k((F2,Mh)=>{var z0=Symbol();function H2(n,t,i){let s=t[z0];if(s)return t.stat(n,(e,f)=>{if(e)return i(e);i(null,f.mtime,s)});let r=new Date(Math.ceil(Date.now()/1000)*1000+5);t.utimes(n,r,r,(e)=>{if(e)return i(e);t.stat(n,(f,o)=>{if(f)return i(f);let h=o.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty(t,z0,{value:h}),i(null,o.mtime,h)})})}function W2(n){let t=Date.now();if(n==="s")t=Math.ceil(t/1000)*1000;return new Date(t)}F2.probe=H2;F2.getMtime=W2});var q0=k((C2,Sr)=>{var Y2=p("path"),Eh=ch(),m2=m0(),J2=X0(),C0=Q0(),Yt={};function gr(n,t){return t.lockfilePath||`${n}.lock`}function yh(n,t,i){if(!t.realpath)return i(null,Y2.resolve(n));t.fs.realpath(n,i)}function Rh(n,t,i){let s=gr(n,t);t.fs.mkdir(s,(r)=>{if(!r)return C0.probe(s,t.fs,(e,f,o)=>{if(e)return t.fs.rmdir(s,()=>{}),i(e);i(null,f,o)});if(r.code!=="EEXIST")return i(r);if(t.stale<=0)return i(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:n}));t.fs.stat(s,(e,f)=>{if(e){if(e.code==="ENOENT")return Rh(n,{...t,stale:0},i);return i(e)}if(!x0(f,t))return i(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:n}));K0(n,t,(o)=>{if(o)return i(o);Rh(n,{...t,stale:0},i)})})})}function x0(n,t){return n.mtime.getTime()<Date.now()-t.stale}function K0(n,t,i){t.fs.rmdir(gr(n,t),(s)=>{if(s&&s.code!=="ENOENT")return i(s);i()})}function Ye(n,t){let i=Yt[n];if(i.updateTimeout)return;if(i.updateDelay=i.updateDelay||t.update,i.updateTimeout=setTimeout(()=>{i.updateTimeout=null,t.fs.stat(i.lockfilePath,(s,r)=>{let e=i.lastUpdate+t.stale<Date.now();if(s){if(s.code==="ENOENT"||e)return dh(n,i,Object.assign(s,{code:"ECOMPROMISED"}));return i.updateDelay=1000,Ye(n,t)}if(i.mtime.getTime()!==r.mtime.getTime())return dh(n,i,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let o=C0.getMtime(i.mtimePrecision);t.fs.utimes(i.lockfilePath,o,o,(h)=>{let u=i.lastUpdate+t.stale<Date.now();if(i.released)return;if(h){if(h.code==="ENOENT"||u)return dh(n,i,Object.assign(h,{code:"ECOMPROMISED"}));return i.updateDelay=1000,Ye(n,t)}i.mtime=o,i.lastUpdate=Date.now(),i.updateDelay=null,Ye(n,t)})})},i.updateDelay),i.updateTimeout.unref)i.updateTimeout.unref()}function dh(n,t,i){if(t.released=!0,t.updateTimeout)clearTimeout(t.updateTimeout);if(Yt[n]===t)delete Yt[n];t.options.onCompromised(i)}function X2(n,t,i){t={stale:1e4,update:null,realpath:!0,retries:0,fs:Eh,onCompromised:(s)=>{throw s},...t},t.retries=t.retries||0,t.retries=typeof t.retries==="number"?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2000),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1000),yh(n,t,(s,r)=>{if(s)return i(s);let e=m2.operation(t.retries);e.attempt(()=>{Rh(r,t,(f,o,h)=>{if(e.retry(f))return;if(f)return i(e.mainError());let u=Yt[r]={lockfilePath:gr(r,t),mtime:o,mtimePrecision:h,options:t,lastUpdate:Date.now()};Ye(r,t),i(null,(c)=>{if(u.released)return c&&c(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));k0(r,{...t,realpath:!1},c)})})})})}function k0(n,t,i){t={fs:Eh,realpath:!0,...t},yh(n,t,(s,r)=>{if(s)return i(s);let e=Yt[r];if(!e)return i(Object.assign(Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));e.updateTimeout&&clearTimeout(e.updateTimeout),e.released=!0,delete Yt[r],K0(r,t,i)})}function z2(n,t,i){t={stale:1e4,realpath:!0,fs:Eh,...t},t.stale=Math.max(t.stale||0,2000),yh(n,t,(s,r)=>{if(s)return i(s);t.fs.stat(gr(r,t),(e,f)=>{if(e)return e.code==="ENOENT"?i(null,!1):i(e);return i(null,!x0(f,t))})})}function Q2(){return Yt}J2(()=>{for(let n in Yt){let t=Yt[n].options;try{t.fs.rmdirSync(gr(n,t))}catch(i){}}});C2.lock=X2;C2.unlock=k0;C2.check=z2;C2.getLocks=Q2});var j0=k((vC,V0)=>{var V2=ch();function j2(n){let t=["mkdir","realpath","stat","rmdir","utimes"],i={...n};return t.forEach((s)=>{i[s]=(...r)=>{let e=r.pop(),f;try{f=n[`${s}Sync`](...r)}catch(o){return e(o)}e(null,f)}}),i}function a2(n){return(...t)=>new Promise((i,s)=>{t.push((r,e)=>{if(r)s(r);else i(e)}),n(...t)})}function v2(n){return(...t)=>{let i,s;if(t.push((r,e)=>{i=r,s=e}),n(...t),i)throw i;return s}}function Z2(n){if(n={...n},n.fs=j2(n.fs||V2),typeof n.retries==="number"&&n.retries>0||n.retries&&typeof n.retries.retries==="number"&&n.retries.retries>0)throw Object.assign(Error("Cannot use retries with the sync api"),{code:"ESYNC"});return n}V0.exports={toPromise:a2,toSync:v2,toSyncOptions:Z2}});var v0=k((ZC,ni)=>{var Ss=q0(),{toPromise:me,toSync:Je,toSyncOptions:Th}=j0();async function a0(n,t){let i=await me(Ss.lock)(n,t);return me(i)}function p2(n,t){let i=Je(Ss.lock)(n,Th(t));return Je(i)}function n6(n,t){return me(Ss.unlock)(n,t)}function t6(n,t){return Je(Ss.unlock)(n,Th(t))}function i6(n,t){return me(Ss.check)(n,t)}function s6(n,t){return Je(Ss.check)(n,Th(t))}ni.exports=a0;ni.exports.lock=a0;ni.exports.unlock=n6;ni.exports.lockSync=p2;ni.exports.unlockSync=t6;ni.exports.check=i6;ni.exports.checkSync=s6});var iw=k((ix,tw)=>{var Is=1000,Us=Is*60,bs=Us*60,Hi=bs*24,A6=Hi*7,M6=Hi*365.25;tw.exports=function(n,t){t=t||{};var i=typeof n;if(i==="string"&&n.length>0)return d6(n);else if(i==="number"&&isFinite(n))return t.long?E6(n):R6(n);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function d6(n){if(n=String(n),n.length>100)return;var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(n);if(!t)return;var i=parseFloat(t[1]),s=(t[2]||"ms").toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return i*M6;case"weeks":case"week":case"w":return i*A6;case"days":case"day":case"d":return i*Hi;case"hours":case"hour":case"hrs":case"hr":case"h":return i*bs;case"minutes":case"minute":case"mins":case"min":case"m":return i*Us;case"seconds":case"second":case"secs":case"sec":case"s":return i*Is;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:return}}function R6(n){var t=Math.abs(n);if(t>=Hi)return Math.round(n/Hi)+"d";if(t>=bs)return Math.round(n/bs)+"h";if(t>=Us)return Math.round(n/Us)+"m";if(t>=Is)return Math.round(n/Is)+"s";return n+"ms"}function E6(n){var t=Math.abs(n);if(t>=Hi)return Xe(n,t,Hi,"day");if(t>=bs)return Xe(n,t,bs,"hour");if(t>=Us)return Xe(n,t,Us,"minute");if(t>=Is)return Xe(n,t,Is,"second");return n+" ms"}function Xe(n,t,i,s){var r=t>=i*1.5;return Math.round(n/i)+" "+s+(r?"s":"")}});var Sh=k((sx,sw)=>{function y6(n){i.debug=i,i.default=i,i.coerce=h,i.disable=f,i.enable=r,i.enabled=o,i.humanize=iw(),i.destroy=u,Object.keys(n).forEach((c)=>{i[c]=n[c]}),i.names=[],i.skips=[],i.formatters={};function t(c){let _=0;for(let w=0;w<c.length;w++)_=(_<<5)-_+c.charCodeAt(w),_|=0;return i.colors[Math.abs(_)%i.colors.length]}i.selectColor=t;function i(c){let _,w=null,l,A;function d(...E){if(!d.enabled)return;let R=d,y=Number(new Date),T=y-(_||y);if(R.diff=T,R.prev=_,R.curr=y,_=y,E[0]=i.coerce(E[0]),typeof E[0]!=="string")E.unshift("%O");let S=0;E[0]=E[0].replace(/%([a-zA-Z%])/g,(F,C)=>{if(F==="%%")return"%";S++;let sn=i.formatters[C];if(typeof sn==="function"){let b=E[S];F=sn.call(R,b),E.splice(S,1),S--}return F}),i.formatArgs.call(R,E),(R.log||i.log).apply(R,E)}if(d.namespace=c,d.useColors=i.useColors(),d.color=i.selectColor(c),d.extend=s,d.destroy=i.destroy,Object.defineProperty(d,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(w!==null)return w;if(l!==i.namespaces)l=i.namespaces,A=i.enabled(c);return A},set:(E)=>{w=E}}),typeof i.init==="function")i.init(d);return d}function s(c,_){let w=i(this.namespace+(typeof _>"u"?":":_)+c);return w.log=this.log,w}function r(c){i.save(c),i.namespaces=c,i.names=[],i.skips=[];let _=(typeof c==="string"?c:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let w of _)if(w[0]==="-")i.skips.push(w.slice(1));else i.names.push(w)}function e(c,_){let w=0,l=0,A=-1,d=0;while(w<c.length)if(l<_.length&&(_[l]===c[w]||_[l]==="*"))if(_[l]==="*")A=l,d=w,l++;else w++,l++;else if(A!==-1)l=A+1,d++,w=d;else return!1;while(l<_.length&&_[l]==="*")l++;return l===_.length}function f(){let c=[...i.names,...i.skips.map((_)=>"-"+_)].join(",");return i.enable(""),c}function o(c){for(let _ of i.skips)if(e(c,_))return!1;for(let _ of i.names)if(e(c,_))return!0;return!1}function h(c){if(c instanceof Error)return c.stack||c.message;return c}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return i.enable(i.load()),i}sw.exports=y6});var ew=k((rw,ze)=>{rw.formatArgs=g6;rw.save=S6;rw.load=I6;rw.useColors=T6;rw.storage=U6();rw.destroy=(()=>{let n=!1;return()=>{if(!n)n=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();rw.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function T6(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let n;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(n=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(n[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function g6(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+ze.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;n.splice(1,0,t,"color: inherit");let i=0,s=0;n[0].replace(/%[a-zA-Z%]/g,(r)=>{if(r==="%%")return;if(i++,r==="%c")s=i}),n.splice(s,0,t)}rw.log=console.debug||console.log||(()=>{});function S6(n){try{if(n)rw.storage.setItem("debug",n);else rw.storage.removeItem("debug")}catch(t){}}function I6(){let n;try{n=rw.storage.getItem("debug")||rw.storage.getItem("DEBUG")}catch(t){}if(!n&&typeof process<"u"&&"env"in process)n=process.env.DEBUG;return n}function U6(){try{return localStorage}catch(n){}}ze.exports=Sh()(rw);var{formatters:b6}=ze.exports;b6.j=function(n){try{return JSON.stringify(n)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var uw=k((fw,Ce)=>{var W6=p("tty"),Qe=p("util");fw.init=X6;fw.log=Y6;fw.formatArgs=P6;fw.save=m6;fw.load=J6;fw.useColors=F6;fw.destroy=Qe.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");fw.colors=[6,2,3,4,5,1];try{let n=(()=>{throw new Error("Cannot require module "+"supports-color");})();if(n&&(n.stderr||n).level>=2)fw.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch(n){}fw.inspectOpts=Object.keys(process.env).filter((n)=>{return/^debug_/i.test(n)}).reduce((n,t)=>{let i=t.substring(6).toLowerCase().replace(/_([a-z])/g,(r,e)=>{return e.toUpperCase()}),s=process.env[t];if(/^(yes|on|true|enabled)$/i.test(s))s=!0;else if(/^(no|off|false|disabled)$/i.test(s))s=!1;else if(s==="null")s=null;else s=Number(s);return n[i]=s,n},{});function F6(){return"colors"in fw.inspectOpts?Boolean(fw.inspectOpts.colors):W6.isatty(process.stderr.fd)}function P6(n){let{namespace:t,useColors:i}=this;if(i){let s=this.color,r="\x1B[3"+(s<8?s:"8;5;"+s),e=` ${r};1m${t} \x1B[0m`;n[0]=e+n[0].split(`
|
|
3
|
+
var O2=Object.create;var{getPrototypeOf:U2,defineProperty:w0,getOwnPropertyNames:b2}=Object;var N2=Object.prototype.hasOwnProperty;function B2(n){return this[n]}var I2,H2,k=(n,t,i)=>{var r=n!=null&&typeof n==="object";if(r){var s=t?I2??=new WeakMap:H2??=new WeakMap,f=s.get(n);if(f)return f}i=n!=null?O2(U2(n)):{};let h=t||!n||!n.__esModule?w0(i,"default",{value:n,enumerable:!0}):i;for(let _ of b2(n))if(!N2.call(h,_))w0(h,_,{get:B2.bind(n,_),enumerable:!0});if(r)s.set(n,h);return h};var nn=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var G2=(n)=>n;function W2(n,t){this[n]=G2.bind(null,t)}var D2=(n,t)=>{for(var i in t)w0(n,i,{get:t[i],enumerable:!0,configurable:!0,set:W2.bind(t,i)})};var cn=import.meta.require;var ve=nn((Ox,ae)=>{var ui=cn("constants"),ug=process.cwd,Kf=null,yg=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){if(!Kf)Kf=ug.call(process);return Kf};try{process.cwd()}catch(n){}if(typeof process.chdir==="function"){if(xf=process.chdir,process.chdir=function(n){Kf=null,xf.call(process,n)},Object.setPrototypeOf)Object.setPrototypeOf(process.chdir,xf)}var xf;ae.exports=dg;function dg(n){if(ui.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./))t(n);if(!n.lutimes)i(n);if(n.chown=f(n.chown),n.fchown=f(n.fchown),n.lchown=f(n.lchown),n.chmod=r(n.chmod),n.fchmod=r(n.fchmod),n.lchmod=r(n.lchmod),n.chownSync=h(n.chownSync),n.fchownSync=h(n.fchownSync),n.lchownSync=h(n.lchownSync),n.chmodSync=s(n.chmodSync),n.fchmodSync=s(n.fchmodSync),n.lchmodSync=s(n.lchmodSync),n.stat=_(n.stat),n.fstat=_(n.fstat),n.lstat=_(n.lstat),n.statSync=c(n.statSync),n.fstatSync=c(n.fstatSync),n.lstatSync=c(n.lstatSync),n.chmod&&!n.lchmod)n.lchmod=function(w,e,u){if(u)process.nextTick(u)},n.lchmodSync=function(){};if(n.chown&&!n.lchown)n.lchown=function(w,e,u,y){if(y)process.nextTick(y)},n.lchownSync=function(){};if(yg==="win32")n.rename=typeof n.rename!=="function"?n.rename:function(w){function e(u,y,A){var R=Date.now(),M=0;w(u,y,function E(g){if(g&&(g.code==="EACCES"||g.code==="EPERM"||g.code==="EBUSY")&&Date.now()-R<60000){if(setTimeout(function(){n.stat(y,function(T,S){if(T&&T.code==="ENOENT")w(u,y,E);else A(g)})},M),M<100)M+=10;return}if(A)A(g)})}if(Object.setPrototypeOf)Object.setPrototypeOf(e,w);return e}(n.rename);n.read=typeof n.read!=="function"?n.read:function(w){function e(u,y,A,R,M,E){var g;if(E&&typeof E==="function"){var T=0;g=function(S,L,b){if(S&&S.code==="EAGAIN"&&T<10)return T++,w.call(n,u,y,A,R,M,g);E.apply(this,arguments)}}return w.call(n,u,y,A,R,M,g)}if(Object.setPrototypeOf)Object.setPrototypeOf(e,w);return e}(n.read),n.readSync=typeof n.readSync!=="function"?n.readSync:function(w){return function(e,u,y,A,R){var M=0;while(!0)try{return w.call(n,e,u,y,A,R)}catch(E){if(E.code==="EAGAIN"&&M<10){M++;continue}throw E}}}(n.readSync);function t(w){w.lchmod=function(e,u,y){w.open(e,ui.O_WRONLY|ui.O_SYMLINK,u,function(A,R){if(A){if(y)y(A);return}w.fchmod(R,u,function(M){w.close(R,function(E){if(y)y(M||E)})})})},w.lchmodSync=function(e,u){var y=w.openSync(e,ui.O_WRONLY|ui.O_SYMLINK,u),A=!0,R;try{R=w.fchmodSync(y,u),A=!1}finally{if(A)try{w.closeSync(y)}catch(M){}else w.closeSync(y)}return R}}function i(w){if(ui.hasOwnProperty("O_SYMLINK")&&w.futimes)w.lutimes=function(e,u,y,A){w.open(e,ui.O_SYMLINK,function(R,M){if(R){if(A)A(R);return}w.futimes(M,u,y,function(E){w.close(M,function(g){if(A)A(E||g)})})})},w.lutimesSync=function(e,u,y){var A=w.openSync(e,ui.O_SYMLINK),R,M=!0;try{R=w.futimesSync(A,u,y),M=!1}finally{if(M)try{w.closeSync(A)}catch(E){}else w.closeSync(A)}return R};else if(w.futimes)w.lutimes=function(e,u,y,A){if(A)process.nextTick(A)},w.lutimesSync=function(){}}function r(w){if(!w)return w;return function(e,u,y){return w.call(n,e,u,function(A){if(o(A))A=null;if(y)y.apply(this,arguments)})}}function s(w){if(!w)return w;return function(e,u){try{return w.call(n,e,u)}catch(y){if(!o(y))throw y}}}function f(w){if(!w)return w;return function(e,u,y,A){return w.call(n,e,u,y,function(R){if(o(R))R=null;if(A)A.apply(this,arguments)})}}function h(w){if(!w)return w;return function(e,u,y){try{return w.call(n,e,u,y)}catch(A){if(!o(A))throw A}}}function _(w){if(!w)return w;return function(e,u,y){if(typeof u==="function")y=u,u=null;function A(R,M){if(M){if(M.uid<0)M.uid+=4294967296;if(M.gid<0)M.gid+=4294967296}if(y)y.apply(this,arguments)}return u?w.call(n,e,u,A):w.call(n,e,A)}}function c(w){if(!w)return w;return function(e,u){var y=u?w.call(n,e,u):w.call(n,e);if(y){if(y.uid<0)y.uid+=4294967296;if(y.gid<0)y.gid+=4294967296}return y}}function o(w){if(!w)return!0;if(w.code==="ENOSYS")return!0;var e=!process.getuid||process.getuid()!==0;if(e){if(w.code==="EINVAL"||w.code==="EPERM")return!0}return!1}}});var tu=nn((Ux,nu)=>{var pe=cn("stream").Stream;nu.exports=Ag;function Ag(n){return{ReadStream:t,WriteStream:i};function t(r,s){if(!(this instanceof t))return new t(r,s);pe.call(this);var f=this;this.path=r,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=65536,s=s||{};var h=Object.keys(s);for(var _=0,c=h.length;_<c;_++){var o=h[_];this[o]=s[o]}if(this.encoding)this.setEncoding(this.encoding);if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!=="number")throw TypeError("end must be a Number");if(this.start>this.end)throw Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){f._read()});return}n.open(this.path,this.flags,this.mode,function(w,e){if(w){f.emit("error",w),f.readable=!1;return}f.fd=e,f.emit("open",e),f._read()})}function i(r,s){if(!(this instanceof i))return new i(r,s);pe.call(this),this.path=r,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,s=s||{};var f=Object.keys(s);for(var h=0,_=f.length;h<_;h++){var c=f[h];this[c]=s[c]}if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.start<0)throw Error("start must be >= zero");this.pos=this.start}if(this.busy=!1,this._queue=[],this.fd===null)this._open=n.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush()}}});var ru=nn((bx,iu)=>{iu.exports=Mg;var Rg=Object.getPrototypeOf||function(n){return n.__proto__};function Mg(n){if(n===null||typeof n!=="object")return n;if(n instanceof Object)var t={__proto__:Rg(n)};else var t=Object.create(null);return Object.getOwnPropertyNames(n).forEach(function(i){Object.defineProperty(t,i,Object.getOwnPropertyDescriptor(n,i))}),t}});var L0=nn((Nx,S0)=>{var gn=cn("fs"),Eg=ve(),Tg=tu(),gg=ru(),jf=cn("util"),Dn,qf;if(typeof Symbol==="function"&&typeof Symbol.for==="function")Dn=Symbol.for("graceful-fs.queue"),qf=Symbol.for("graceful-fs.previous");else Dn="___graceful-fs.queue",qf="___graceful-fs.previous";function Sg(){}function fu(n,t){Object.defineProperty(n,Dn,{get:function(){return t}})}var zi=Sg;if(jf.debuglog)zi=jf.debuglog("gfs4");else if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))zi=function(){var n=jf.format.apply(jf,arguments);n="GFS4: "+n.split(/\n/).join(`
|
|
4
|
+
GFS4: `),console.error(n)};if(!gn[Dn]){if(E0=global[Dn]||[],fu(gn,E0),gn.close=function(n){function t(i,r){return n.call(gn,i,function(s){if(!s)su();if(typeof r==="function")r.apply(this,arguments)})}return Object.defineProperty(t,qf,{value:n}),t}(gn.close),gn.closeSync=function(n){function t(i){n.apply(gn,arguments),su()}return Object.defineProperty(t,qf,{value:n}),t}(gn.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){zi(gn[Dn]),cn("assert").equal(gn[Dn].length,0)})}var E0;if(!global[Dn])fu(global,gn[Dn]);S0.exports=T0(gg(gn));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!gn.__patched)S0.exports=T0(gn),gn.__patched=!0;function T0(n){Eg(n),n.gracefulify=T0,n.createReadStream=L,n.createWriteStream=b;var t=n.readFile;n.readFile=i;function i($,U,X){if(typeof U==="function")X=U,U=null;return H($,U,X);function H(W,K,P,z){return t(W,K,function(x){if(x&&(x.code==="EMFILE"||x.code==="ENFILE"))Dr([H,[W,K,P],x,z||Date.now(),Date.now()]);else if(typeof P==="function")P.apply(this,arguments)})}}var r=n.writeFile;n.writeFile=s;function s($,U,X,H){if(typeof X==="function")H=X,X=null;return W($,U,X,H);function W(K,P,z,x,q){return r(K,P,z,function(v){if(v&&(v.code==="EMFILE"||v.code==="ENFILE"))Dr([W,[K,P,z,x],v,q||Date.now(),Date.now()]);else if(typeof x==="function")x.apply(this,arguments)})}}var f=n.appendFile;if(f)n.appendFile=h;function h($,U,X,H){if(typeof X==="function")H=X,X=null;return W($,U,X,H);function W(K,P,z,x,q){return f(K,P,z,function(v){if(v&&(v.code==="EMFILE"||v.code==="ENFILE"))Dr([W,[K,P,z,x],v,q||Date.now(),Date.now()]);else if(typeof x==="function")x.apply(this,arguments)})}}var _=n.copyFile;if(_)n.copyFile=c;function c($,U,X,H){if(typeof X==="function")H=X,X=0;return W($,U,X,H);function W(K,P,z,x,q){return _(K,P,z,function(v){if(v&&(v.code==="EMFILE"||v.code==="ENFILE"))Dr([W,[K,P,z,x],v,q||Date.now(),Date.now()]);else if(typeof x==="function")x.apply(this,arguments)})}}var o=n.readdir;n.readdir=e;var w=/^v[0-5]\./;function e($,U,X){if(typeof U==="function")X=U,U=null;var H=w.test(process.version)?function(P,z,x,q){return o(P,W(P,z,x,q))}:function(P,z,x,q){return o(P,z,W(P,z,x,q))};return H($,U,X);function W(K,P,z,x){return function(q,v){if(q&&(q.code==="EMFILE"||q.code==="ENFILE"))Dr([H,[K,P,z],q,x||Date.now(),Date.now()]);else{if(v&&v.sort)v.sort();if(typeof z==="function")z.call(this,q,v)}}}}if(process.version.substr(0,4)==="v0.8"){var u=Tg(n);E=u.ReadStream,T=u.WriteStream}var y=n.ReadStream;if(y)E.prototype=Object.create(y.prototype),E.prototype.open=g;var A=n.WriteStream;if(A)T.prototype=Object.create(A.prototype),T.prototype.open=S;Object.defineProperty(n,"ReadStream",{get:function(){return E},set:function($){E=$},enumerable:!0,configurable:!0}),Object.defineProperty(n,"WriteStream",{get:function(){return T},set:function($){T=$},enumerable:!0,configurable:!0});var R=E;Object.defineProperty(n,"FileReadStream",{get:function(){return R},set:function($){R=$},enumerable:!0,configurable:!0});var M=T;Object.defineProperty(n,"FileWriteStream",{get:function(){return M},set:function($){M=$},enumerable:!0,configurable:!0});function E($,U){if(this instanceof E)return y.apply(this,arguments),this;else return E.apply(Object.create(E.prototype),arguments)}function g(){var $=this;Z($.path,$.flags,$.mode,function(U,X){if(U){if($.autoClose)$.destroy();$.emit("error",U)}else $.fd=X,$.emit("open",X),$.read()})}function T($,U){if(this instanceof T)return A.apply(this,arguments),this;else return T.apply(Object.create(T.prototype),arguments)}function S(){var $=this;Z($.path,$.flags,$.mode,function(U,X){if(U)$.destroy(),$.emit("error",U);else $.fd=X,$.emit("open",X)})}function L($,U){return new n.ReadStream($,U)}function b($,U){return new n.WriteStream($,U)}var I=n.open;n.open=Z;function Z($,U,X,H){if(typeof X==="function")H=X,X=null;return W($,U,X,H);function W(K,P,z,x,q){return I(K,P,z,function(v,Di){if(v&&(v.code==="EMFILE"||v.code==="ENFILE"))Dr([W,[K,P,z,x],v,q||Date.now(),Date.now()]);else if(typeof x==="function")x.apply(this,arguments)})}}return n}function Dr(n){zi("ENQUEUE",n[0].name,n[1]),gn[Dn].push(n),g0()}var kf;function su(){var n=Date.now();for(var t=0;t<gn[Dn].length;++t)if(gn[Dn][t].length>2)gn[Dn][t][3]=n,gn[Dn][t][4]=n;g0()}function g0(){if(clearTimeout(kf),kf=void 0,gn[Dn].length===0)return;var n=gn[Dn].shift(),t=n[0],i=n[1],r=n[2],s=n[3],f=n[4];if(s===void 0)zi("RETRY",t.name,i),t.apply(null,i);else if(Date.now()-s>=60000){zi("TIMEOUT",t.name,i);var h=i.pop();if(typeof h==="function")h.call(null,r)}else{var _=Date.now()-f,c=Math.max(f-s,1),o=Math.min(c*1.2,100);if(_>=o)zi("RETRY",t.name,i),t.apply(null,i.concat([s]));else gn[Dn].push(n)}if(kf===void 0)kf=setTimeout(g0,0)}});var hu=nn((Bx,_u)=>{function _t(n,t){if(typeof t==="boolean")t={forever:t};if(this._originalTimeouts=JSON.parse(JSON.stringify(n)),this._timeouts=n,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever)this._cachedTimeouts=this._timeouts.slice(0)}_u.exports=_t;_t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};_t.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};_t.prototype.retry=function(n){if(this._timeout)clearTimeout(this._timeout);if(!n)return!1;var t=new Date().getTime();if(n&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(n);var i=this._timeouts.shift();if(i===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),i=this._timeouts.shift();else return!1;var r=this,s=setTimeout(function(){if(r._attempts++,r._operationTimeoutCb){if(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref)r._timeout.unref()}r._fn(r._attempts)},i);if(this._options.unref)s.unref();return!0};_t.prototype.attempt=function(n,t){if(this._fn=n,t){if(t.timeout)this._operationTimeout=t.timeout;if(t.cb)this._operationTimeoutCb=t.cb}var i=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){i._operationTimeoutCb()},i._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};_t.prototype.try=function(n){console.log("Using RetryOperation.try() is deprecated"),this.attempt(n)};_t.prototype.start=function(n){console.log("Using RetryOperation.start() is deprecated"),this.attempt(n)};_t.prototype.start=_t.prototype.try;_t.prototype.errors=function(){return this._errors};_t.prototype.attempts=function(){return this._attempts};_t.prototype.mainError=function(){if(this._errors.length===0)return null;var n={},t=null,i=0;for(var r=0;r<this._errors.length;r++){var s=this._errors[r],f=s.message,h=(n[f]||0)+1;if(n[f]=h,h>=i)t=s,i=h}return t}});var ou=nn(($g)=>{var Lg=hu();$g.operation=function(n){var t=$g.timeouts(n);return new Lg(t,{forever:n&&n.forever,unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})};$g.timeouts=function(n){if(n instanceof Array)return[].concat(n);var t={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var i in n)t[i]=n[i];if(t.minTimeout>t.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var r=[];for(var s=0;s<t.retries;s++)r.push(this.createTimeout(s,t));if(n&&n.forever&&!r.length)r.push(this.createTimeout(s,t));return r.sort(function(f,h){return f-h}),r};$g.createTimeout=function(n,t){var i=t.randomize?Math.random()+1:1,r=Math.round(i*t.minTimeout*Math.pow(t.factor,n));return r=Math.min(r,t.maxTimeout),r};$g.wrap=function(n,t,i){if(t instanceof Array)i=t,t=null;if(!i){i=[];for(var r in n)if(typeof n[r]==="function")i.push(r)}for(var s=0;s<i.length;s++){var f=i[s],h=n[f];n[f]=function(c){var o=$g.operation(t),w=Array.prototype.slice.call(arguments,1),e=w.pop();w.push(function(u){if(o.retry(u))return;if(u)arguments[0]=o.mainError();e.apply(this,arguments)}),o.attempt(function(){c.apply(n,w)})}.bind(n,h),n[f].options=t}}});var wu=nn((Hx,mf)=>{mf.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")mf.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")mf.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var eu=nn((Gx,Yr)=>{var Rn=global.process,Ci=function(n){return n&&typeof n==="object"&&typeof n.removeListener==="function"&&typeof n.emit==="function"&&typeof n.reallyExit==="function"&&typeof n.listeners==="function"&&typeof n.kill==="function"&&typeof n.pid==="number"&&typeof n.on==="function"};if(!Ci(Rn))Yr.exports=function(){return function(){}};else{if($0=cn("assert"),Vi=wu(),O0=/^win/i.test(Rn.platform),Pr=cn("events"),typeof Pr!=="function")Pr=Pr.EventEmitter;if(Rn.__signal_exit_emitter__)Nn=Rn.__signal_exit_emitter__;else Nn=Rn.__signal_exit_emitter__=new Pr,Nn.count=0,Nn.emitted={};if(!Nn.infinite)Nn.setMaxListeners(1/0),Nn.infinite=!0;Yr.exports=function(n,t){if(!Ci(global.process))return function(){};if($0.equal(typeof n,"function","a callback must be provided for exit handler"),Ki===!1)Zf();var i="exit";if(t&&t.alwaysLast)i="afterexit";var r=function(){if(Nn.removeListener(i,n),Nn.listeners("exit").length===0&&Nn.listeners("afterexit").length===0)Ps()};return Nn.on(i,n),r},Ps=function(){if(!Ki||!Ci(global.process))return;Ki=!1,Vi.forEach(function(t){try{Rn.removeListener(t,Ys[t])}catch(i){}}),Rn.emit=Fs,Rn.reallyExit=af,Nn.count-=1},Yr.exports.unload=Ps,yi=function(t,i,r){if(Nn.emitted[t])return;Nn.emitted[t]=!0,Nn.emit(t,i,r)},Ys={},Vi.forEach(function(n){Ys[n]=function(){if(!Ci(global.process))return;var i=Rn.listeners(n);if(i.length===Nn.count){if(Ps(),yi("exit",null,n),yi("afterexit",null,n),O0&&n==="SIGHUP")n="SIGINT";Rn.kill(Rn.pid,n)}}}),Yr.exports.signals=function(){return Vi},Ki=!1,Zf=function(){if(Ki||!Ci(global.process))return;Ki=!0,Nn.count+=1,Vi=Vi.filter(function(t){try{return Rn.on(t,Ys[t]),!0}catch(i){return!1}}),Rn.emit=b0,Rn.reallyExit=U0},Yr.exports.load=Zf,af=Rn.reallyExit,U0=function(t){if(!Ci(global.process))return;Rn.exitCode=t||0,yi("exit",Rn.exitCode,null),yi("afterexit",Rn.exitCode,null),af.call(Rn,Rn.exitCode)},Fs=Rn.emit,b0=function(t,i){if(t==="exit"&&Ci(global.process)){if(i!==void 0)Rn.exitCode=i;var r=Fs.apply(this,arguments);return yi("exit",Rn.exitCode,null),yi("afterexit",Rn.exitCode,null),r}else return Fs.apply(this,arguments)}}var $0,Vi,O0,Pr,Nn,Ps,yi,Ys,Ki,Zf,af,U0,Fs,b0});var yu=nn((Ig,N0)=>{var uu=Symbol();function Ng(n,t,i){let r=t[uu];if(r)return t.stat(n,(f,h)=>{if(f)return i(f);i(null,h.mtime,r)});let s=new Date(Math.ceil(Date.now()/1000)*1000+5);t.utimes(n,s,s,(f)=>{if(f)return i(f);t.stat(n,(h,_)=>{if(h)return i(h);let c=_.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty(t,uu,{value:c}),i(null,_.mtime,c)})})}function Bg(n){let t=Date.now();if(n==="s")t=Math.ceil(t/1000)*1000;return new Date(t)}Ig.probe=Ng;Ig.getMtime=Bg});var Eu=nn((lg,ls)=>{var Wg=cn("path"),H0=L0(),Dg=ou(),Pg=eu(),du=yu(),qt={};function Xs(n,t){return t.lockfilePath||`${n}.lock`}function G0(n,t,i){if(!t.realpath)return i(null,Wg.resolve(n));t.fs.realpath(n,i)}function I0(n,t,i){let r=Xs(n,t);t.fs.mkdir(r,(s)=>{if(!s)return du.probe(r,t.fs,(f,h,_)=>{if(f)return t.fs.rmdir(r,()=>{}),i(f);i(null,h,_)});if(s.code!=="EEXIST")return i(s);if(t.stale<=0)return i(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:n}));t.fs.stat(r,(f,h)=>{if(f){if(f.code==="ENOENT")return I0(n,{...t,stale:0},i);return i(f)}if(!Au(h,t))return i(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:n}));Ru(n,t,(_)=>{if(_)return i(_);I0(n,{...t,stale:0},i)})})})}function Au(n,t){return n.mtime.getTime()<Date.now()-t.stale}function Ru(n,t,i){t.fs.rmdir(Xs(n,t),(r)=>{if(r&&r.code!=="ENOENT")return i(r);i()})}function vf(n,t){let i=qt[n];if(i.updateTimeout)return;if(i.updateDelay=i.updateDelay||t.update,i.updateTimeout=setTimeout(()=>{i.updateTimeout=null,t.fs.stat(i.lockfilePath,(r,s)=>{let f=i.lastUpdate+t.stale<Date.now();if(r){if(r.code==="ENOENT"||f)return B0(n,i,Object.assign(r,{code:"ECOMPROMISED"}));return i.updateDelay=1000,vf(n,t)}if(i.mtime.getTime()!==s.mtime.getTime())return B0(n,i,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let _=du.getMtime(i.mtimePrecision);t.fs.utimes(i.lockfilePath,_,_,(c)=>{let o=i.lastUpdate+t.stale<Date.now();if(i.released)return;if(c){if(c.code==="ENOENT"||o)return B0(n,i,Object.assign(c,{code:"ECOMPROMISED"}));return i.updateDelay=1000,vf(n,t)}i.mtime=_,i.lastUpdate=Date.now(),i.updateDelay=null,vf(n,t)})})},i.updateDelay),i.updateTimeout.unref)i.updateTimeout.unref()}function B0(n,t,i){if(t.released=!0,t.updateTimeout)clearTimeout(t.updateTimeout);if(qt[n]===t)delete qt[n];t.options.onCompromised(i)}function Yg(n,t,i){t={stale:1e4,update:null,realpath:!0,retries:0,fs:H0,onCompromised:(r)=>{throw r},...t},t.retries=t.retries||0,t.retries=typeof t.retries==="number"?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2000),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1000),G0(n,t,(r,s)=>{if(r)return i(r);let f=Dg.operation(t.retries);f.attempt(()=>{I0(s,t,(h,_,c)=>{if(f.retry(h))return;if(h)return i(f.mainError());let o=qt[s]={lockfilePath:Xs(s,t),mtime:_,mtimePrecision:c,options:t,lastUpdate:Date.now()};vf(s,t),i(null,(w)=>{if(o.released)return w&&w(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));Mu(s,{...t,realpath:!1},w)})})})})}function Mu(n,t,i){t={fs:H0,realpath:!0,...t},G0(n,t,(r,s)=>{if(r)return i(r);let f=qt[s];if(!f)return i(Object.assign(Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));f.updateTimeout&&clearTimeout(f.updateTimeout),f.released=!0,delete qt[s],Ru(s,t,i)})}function Fg(n,t,i){t={stale:1e4,realpath:!0,fs:H0,...t},t.stale=Math.max(t.stale||0,2000),G0(n,t,(r,s)=>{if(r)return i(r);t.fs.stat(Xs(s,t),(f,h)=>{if(f)return f.code==="ENOENT"?i(null,!1):i(f);return i(null,!Au(h,t))})})}function Xg(){return qt}Pg(()=>{for(let n in qt){let t=qt[n].options;try{t.fs.rmdirSync(Xs(n,t))}catch(i){}}});lg.lock=Yg;lg.unlock=Mu;lg.check=Fg;lg.getLocks=Xg});var gu=nn((Wx,Tu)=>{var Vg=L0();function Kg(n){let t=["mkdir","realpath","stat","rmdir","utimes"],i={...n};return t.forEach((r)=>{i[r]=(...s)=>{let f=s.pop(),h;try{h=n[`${r}Sync`](...s)}catch(_){return f(_)}f(null,h)}}),i}function xg(n){return(...t)=>new Promise((i,r)=>{t.push((s,f)=>{if(s)r(s);else i(f)}),n(...t)})}function jg(n){return(...t)=>{let i,r;if(t.push((s,f)=>{i=s,r=f}),n(...t),i)throw i;return r}}function kg(n){if(n={...n},n.fs=Kg(n.fs||Vg),typeof n.retries==="number"&&n.retries>0||n.retries&&typeof n.retries.retries==="number"&&n.retries.retries>0)throw Object.assign(Error("Cannot use retries with the sync api"),{code:"ESYNC"});return n}Tu.exports={toPromise:xg,toSync:jg,toSyncOptions:kg}});var Lu=nn((Dx,di)=>{var Fr=Eu(),{toPromise:pf,toSync:n_,toSyncOptions:W0}=gu();async function Su(n,t){let i=await pf(Fr.lock)(n,t);return pf(i)}function qg(n,t){let i=n_(Fr.lock)(n,W0(t));return n_(i)}function mg(n,t){return pf(Fr.unlock)(n,t)}function Zg(n,t){return n_(Fr.unlock)(n,W0(t))}function ag(n,t){return pf(Fr.check)(n,t)}function vg(n,t){return n_(Fr.check)(n,W0(t))}di.exports=Su;di.exports.lock=Su;di.exports.unlock=mg;di.exports.lockSync=qg;di.exports.unlockSync=Zg;di.exports.check=ag;di.exports.checkSync=vg});var Nu=nn((Xx,bu)=>{var Xr=1000,lr=Xr*60,Jr=lr*60,xi=Jr*24,o8=xi*7,w8=xi*365.25;bu.exports=function(n,t){t=t||{};var i=typeof n;if(i==="string"&&n.length>0)return e8(n);else if(i==="number"&&isFinite(n))return t.long?y8(n):u8(n);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function e8(n){if(n=String(n),n.length>100)return;var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(n);if(!t)return;var i=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return i*w8;case"weeks":case"week":case"w":return i*o8;case"days":case"day":case"d":return i*xi;case"hours":case"hour":case"hrs":case"hr":case"h":return i*Jr;case"minutes":case"minute":case"mins":case"min":case"m":return i*lr;case"seconds":case"second":case"secs":case"sec":case"s":return i*Xr;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:return}}function u8(n){var t=Math.abs(n);if(t>=xi)return Math.round(n/xi)+"d";if(t>=Jr)return Math.round(n/Jr)+"h";if(t>=lr)return Math.round(n/lr)+"m";if(t>=Xr)return Math.round(n/Xr)+"s";return n+"ms"}function y8(n){var t=Math.abs(n);if(t>=xi)return t_(n,t,xi,"day");if(t>=Jr)return t_(n,t,Jr,"hour");if(t>=lr)return t_(n,t,lr,"minute");if(t>=Xr)return t_(n,t,Xr,"second");return n+" ms"}function t_(n,t,i,r){var s=t>=i*1.5;return Math.round(n/i)+" "+r+(s?"s":"")}});var P0=nn((lx,Bu)=>{function d8(n){i.debug=i,i.default=i,i.coerce=c,i.disable=h,i.enable=s,i.enabled=_,i.humanize=Nu(),i.destroy=o,Object.keys(n).forEach((w)=>{i[w]=n[w]}),i.names=[],i.skips=[],i.formatters={};function t(w){let e=0;for(let u=0;u<w.length;u++)e=(e<<5)-e+w.charCodeAt(u),e|=0;return i.colors[Math.abs(e)%i.colors.length]}i.selectColor=t;function i(w){let e,u=null,y,A;function R(...M){if(!R.enabled)return;let E=R,g=Number(new Date),T=g-(e||g);if(E.diff=T,E.prev=e,E.curr=g,e=g,M[0]=i.coerce(M[0]),typeof M[0]!=="string")M.unshift("%O");let S=0;M[0]=M[0].replace(/%([a-zA-Z%])/g,(b,I)=>{if(b==="%%")return"%";S++;let Z=i.formatters[I];if(typeof Z==="function"){let $=M[S];b=Z.call(E,$),M.splice(S,1),S--}return b}),i.formatArgs.call(E,M),(E.log||i.log).apply(E,M)}if(R.namespace=w,R.useColors=i.useColors(),R.color=i.selectColor(w),R.extend=r,R.destroy=i.destroy,Object.defineProperty(R,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(u!==null)return u;if(y!==i.namespaces)y=i.namespaces,A=i.enabled(w);return A},set:(M)=>{u=M}}),typeof i.init==="function")i.init(R);return R}function r(w,e){let u=i(this.namespace+(typeof e>"u"?":":e)+w);return u.log=this.log,u}function s(w){i.save(w),i.namespaces=w,i.names=[],i.skips=[];let e=(typeof w==="string"?w:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let u of e)if(u[0]==="-")i.skips.push(u.slice(1));else i.names.push(u)}function f(w,e){let u=0,y=0,A=-1,R=0;while(u<w.length)if(y<e.length&&(e[y]===w[u]||e[y]==="*"))if(e[y]==="*")A=y,R=u,y++;else u++,y++;else if(A!==-1)y=A+1,R++,u=R;else return!1;while(y<e.length&&e[y]==="*")y++;return y===e.length}function h(){let w=[...i.names,...i.skips.map((e)=>"-"+e)].join(",");return i.enable(""),w}function _(w){for(let e of i.skips)if(f(w,e))return!1;for(let e of i.names)if(f(w,e))return!0;return!1}function c(w){if(w instanceof Error)return w.stack||w.message;return w}function o(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return i.enable(i.load()),i}Bu.exports=d8});var Hu=nn((Iu,i_)=>{Iu.formatArgs=R8;Iu.save=M8;Iu.load=E8;Iu.useColors=A8;Iu.storage=T8();Iu.destroy=(()=>{let n=!1;return()=>{if(!n)n=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();Iu.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function A8(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let n;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(n=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(n[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function R8(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+i_.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;n.splice(1,0,t,"color: inherit");let i=0,r=0;n[0].replace(/%[a-zA-Z%]/g,(s)=>{if(s==="%%")return;if(i++,s==="%c")r=i}),n.splice(r,0,t)}Iu.log=console.debug||console.log||(()=>{});function M8(n){try{if(n)Iu.storage.setItem("debug",n);else Iu.storage.removeItem("debug")}catch(t){}}function E8(){let n;try{n=Iu.storage.getItem("debug")||Iu.storage.getItem("DEBUG")}catch(t){}if(!n&&typeof process<"u"&&"env"in process)n=process.env.DEBUG;return n}function T8(){try{return localStorage}catch(n){}}i_.exports=P0()(Iu);var{formatters:g8}=i_.exports;g8.j=function(n){try{return JSON.stringify(n)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var Pu=nn((Wu,s_)=>{var B8=cn("tty"),r_=cn("util");Wu.init=Y8;Wu.log=W8;Wu.formatArgs=H8;Wu.save=D8;Wu.load=P8;Wu.useColors=I8;Wu.destroy=r_.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Wu.colors=[6,2,3,4,5,1];try{let n=(()=>{throw new Error("Cannot require module "+"supports-color");})();if(n&&(n.stderr||n).level>=2)Wu.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch(n){}Wu.inspectOpts=Object.keys(process.env).filter((n)=>{return/^debug_/i.test(n)}).reduce((n,t)=>{let i=t.substring(6).toLowerCase().replace(/_([a-z])/g,(s,f)=>{return f.toUpperCase()}),r=process.env[t];if(/^(yes|on|true|enabled)$/i.test(r))r=!0;else if(/^(no|off|false|disabled)$/i.test(r))r=!1;else if(r==="null")r=null;else r=Number(r);return n[i]=r,n},{});function I8(){return"colors"in Wu.inspectOpts?Boolean(Wu.inspectOpts.colors):B8.isatty(process.stderr.fd)}function H8(n){let{namespace:t,useColors:i}=this;if(i){let r=this.color,s="\x1B[3"+(r<8?r:"8;5;"+r),f=` ${s};1m${t} \x1B[0m`;n[0]=f+n[0].split(`
|
|
5
5
|
`).join(`
|
|
6
|
-
`+
|
|
7
|
-
`)}function
|
|
8
|
-
`).map((t)=>t.trim()).join(" ")};
|
|
9
|
-
Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(l){if(!i.logger||i.logger?.constructor?.name==="NoOpLogger")console.warn("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.");else i.logger?.warn?.("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.")}if(typeof _.$responseBodyText<"u"){if(_.$response)_.$response.body=_.$responseBodyText}try{if(kg.isInstance(r)){let{headers:l={},statusCode:A}=r,d=Object.entries(l);_.$metadata={httpStatusCode:A,requestId:xh(/^x-[\w-]+-request-?id$/,d),extendedRequestId:xh(/^x-[\w-]+-id-2$/,d),cfId:xh(/^x-[\w-]+-cf-id$/,d)}}}catch(l){}}throw _}},xh=(n,t)=>{return(t.find(([i])=>{return i.match(n)})||[void 0,void 0])[1]},jg=(n)=>(t,i)=>async(s)=>{let{operationSchema:r}=Gw(i),[,e,f,o,h,u]=r??[],c=i.endpointV2?async()=>qg(i.endpointV2):n.endpoint,_=await n.protocol.serializeRequest(kh(e,f,o,h,u),s.input,{...n,...i,endpoint:c});return t({...s,request:_})},Hw={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},Ww={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function ag(n){return{applyToStack:(t)=>{t.add(jg(n),Ww),t.add(Vg(n),Hw),n.protocol.setSerdeContext(n)}}}class Dn{name;namespace;traits;static assign(n,t){return Object.assign(n,t)}static[Symbol.hasInstance](n){let t=this.prototype.isPrototypeOf(n);if(!t&&typeof n==="object"&&n!==null)return n.symbol===this.symbol;return t}getName(){return this.namespace+"#"+this.name}}class to extends Dn{static symbol=Symbol.for("@smithy/lis");name;traits;valueSchema;symbol=to.symbol}var vg=(n,t,i,s)=>Dn.assign(new to,{name:t,namespace:n,traits:i,valueSchema:s});class io extends Dn{static symbol=Symbol.for("@smithy/map");name;traits;keySchema;valueSchema;symbol=io.symbol}var Zg=(n,t,i,s,r)=>Dn.assign(new io,{name:t,namespace:n,traits:i,keySchema:s,valueSchema:r});class so extends Dn{static symbol=Symbol.for("@smithy/ope");name;traits;input;output;symbol=so.symbol}var pg=(n,t,i,s,r)=>Dn.assign(new so,{name:t,namespace:n,traits:i,input:s,output:r});class Wr extends Dn{static symbol=Symbol.for("@smithy/str");name;traits;memberNames;memberList;symbol=Wr.symbol}var nS=(n,t,i,s,r)=>Dn.assign(new Wr,{name:t,namespace:n,traits:i,memberNames:s,memberList:r});class ro extends Wr{static symbol=Symbol.for("@smithy/err");ctor;symbol=ro.symbol}var tS=(n,t,i,s,r,e)=>Dn.assign(new ro,{name:t,namespace:n,traits:i,memberNames:s,memberList:r,ctor:null}),Ze=[];function Hr(n){if(typeof n==="object")return n;if(n=n|0,Ze[n])return Ze[n];let t={},i=0;for(let s of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])if((n>>i++&1)===1)t[s]=1;return Ze[n]=t}var Nr={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},pe=[],no={};class Jt{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=Jt.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(n,t){this.ref=n,this.memberName=t;let i=[],s=n,r=n;this._isMemberSchema=!1;while(Kh(s))i.push(s[1]),s=s[0],r=ve(s),this._isMemberSchema=!0;if(i.length>0){this.memberTraits={};for(let e=i.length-1;e>=0;--e){let f=i[e];Object.assign(this.memberTraits,Hr(f))}}else this.memberTraits=0;if(r instanceof Jt){let e=this.memberTraits;Object.assign(this,r),this.memberTraits=Object.assign({},e,r.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=t??r.memberName;return}if(this.schema=ve(r),Fw(this.schema))this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3];else this.name=this.memberName??String(r),this.traits=0;if(this._isMemberSchema&&!t)throw Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](n){let t=this.prototype.isPrototypeOf(n);if(!t&&typeof n==="object"&&n!==null)return n.symbol===this.symbol;return t}static of(n){let t=typeof n==="function"||typeof n==="object"&&n!==null;if(typeof n==="number"){if(pe[n])return pe[n]}else if(typeof n==="string"){if(no[n])return no[n]}else if(t){if(n[Nr.ns])return n[Nr.ns]}let i=ve(n);if(i instanceof Jt)return i;if(Kh(i)){let[r,e]=i;if(r instanceof Jt)return Object.assign(r.getMergedTraits(),Hr(e)),r;throw Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(n,null,2)}.`)}let s=new Jt(i);if(t)return n[Nr.ns]=s;if(typeof i==="string")return no[i]=s;if(typeof i==="number")return pe[i]=s;return s}getSchema(){let n=this.schema;if(Array.isArray(n)&&n[0]===0)return n[4];return n}getName(n=!1){let{name:t}=this;return!n&&t&&t.includes("#")?t.split("#")[1]:t||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){let n=this.getSchema();return typeof n==="number"?n>=64&&n<128:n[0]===1}isMapSchema(){let n=this.getSchema();return typeof n==="number"?n>=128&&n<=255:n[0]===2}isStructSchema(){let n=this.getSchema();if(typeof n!=="object")return!1;let t=n[0];return t===3||t===-3||t===4}isUnionSchema(){let n=this.getSchema();if(typeof n!=="object")return!1;return n[0]===4}isBlobSchema(){let n=this.getSchema();return n===21||n===42}isTimestampSchema(){let n=this.getSchema();return typeof n==="number"&&n>=4&&n<=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(){let{streaming:n}=this.getMergedTraits();return!!n||this.getSchema()===42}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return Hr(this.memberTraits)}getOwnTraits(){return Hr(this.traits)}getKeySchema(){let[n,t]=[this.isDocumentSchema(),this.isMapSchema()];if(!n&&!t)throw Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);let i=this.getSchema(),s=n?15:i[4]??0;return Gr([s,0],"key")}getValueSchema(){let n=this.getSchema(),[t,i,s]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],r=typeof n==="number"?63&n:n&&typeof n==="object"&&(i||s)?n[3+n[0]]:t?15:void 0;if(r!=null)return Gr([r,0],i?"value":"member");throw Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(n){let t=this.getSchema();if(this.isStructSchema()&&t[4].includes(n)){let i=t[4].indexOf(n),s=t[5][i];return Gr(Kh(s)?s:[s,0],n)}if(this.isDocumentSchema())return Gr([15,0],n);throw Error(`@smithy/core/schema - ${this.getName(!0)} has no member=${n}.`)}getMemberSchemas(){let n={};try{for(let[t,i]of this.structIterator())n[t]=i}catch(t){}return n}getEventStreamMember(){if(this.isStructSchema()){for(let[n,t]of this.structIterator())if(t.isStreaming()&&t.isStructSchema())return n}return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw Error("@smithy/core/schema - cannot iterate non-struct schema.");let n=this.getSchema(),t=n[4].length,i=n[Nr.it];if(i&&t===i.length){yield*i;return}i=Array(t);for(let s=0;s<t;++s){let r=n[4][s],e=Gr([n[5][s],0],r);yield i[s]=[r,e]}n[Nr.it]=i}}function Gr(n,t){if(n instanceof Jt)return Object.assign(n,{memberName:t,_isMemberSchema:!0});return new Jt(n,t)}var Kh=(n)=>Array.isArray(n)&&n.length===2,Fw=(n)=>Array.isArray(n)&&n.length>=5;class Fr extends Dn{static symbol=Symbol.for("@smithy/sim");name;schemaRef;traits;symbol=Fr.symbol}var iS=(n,t,i,s)=>Dn.assign(new Fr,{name:t,namespace:n,traits:s,schemaRef:i}),sS=(n,t,i,s)=>Dn.assign(new Fr,{name:t,namespace:n,traits:i,schemaRef:s}),rS={BLOB:21,STREAMING_BLOB:42,BOOLEAN:2,STRING:0,NUMERIC:1,BIG_INTEGER:17,BIG_DECIMAL:19,DOCUMENT:15,TIMESTAMP_DEFAULT:4,TIMESTAMP_DATE_TIME:5,TIMESTAMP_HTTP_DATE:6,TIMESTAMP_EPOCH_SECONDS:7,LIST_MODIFIER:64,MAP_MODIFIER:128};class mt{namespace;schemas;exceptions;static registries=new Map;constructor(n,t=new Map,i=new Map){this.namespace=n,this.schemas=t,this.exceptions=i}static for(n){if(!mt.registries.has(n))mt.registries.set(n,new mt(n));return mt.registries.get(n)}copyFrom(n){let{schemas:t,exceptions:i}=this;for(let[s,r]of n.schemas)if(!t.has(s))t.set(s,r);for(let[s,r]of n.exceptions)if(!i.has(s))i.set(s,r)}register(n,t){let i=this.normalizeShapeId(n);for(let s of[this,mt.for(i.split("#")[0])])s.schemas.set(i,t)}getSchema(n){let t=this.normalizeShapeId(n);if(!this.schemas.has(t)){if(!n.includes("#")){let i="#"+n,s=[];for(let[r,e]of this.schemas.entries())if(r.endsWith(i))s.push(e);if(s.length===1)return s[0]}throw Error(`@smithy/core/schema - schema not found for ${t}`)}return this.schemas.get(t)}registerError(n,t){let i=n,s=i[1];for(let r of[this,mt.for(s)])r.schemas.set(s+"#"+i[2],i),r.exceptions.set(i,t)}getErrorCtor(n){let t=n;if(this.exceptions.has(t))return this.exceptions.get(t);return mt.for(t[1]).exceptions.get(t)}getBaseException(){for(let n of this.exceptions.keys())if(Array.isArray(n)){let[,t,i]=n,s=t+"#"+i;if(s.startsWith("smithy.ts.sdk.synthetic.")&&s.endsWith("ServiceException"))return n}return}find(n){for(let t of this.schemas.values())if(n(t))return t;return}clear(){this.schemas.clear(),this.exceptions.clear()}normalizeShapeId(n){if(n.includes("#"))return n;return this.namespace+"#"+n}}eS.ErrorSchema=ro;eS.ListSchema=to;eS.MapSchema=io;eS.NormalizedSchema=Jt;eS.OperationSchema=so;eS.SCHEMA=rS;eS.Schema=Dn;eS.SimpleSchema=Fr;eS.StructureSchema=Wr;eS.TypeRegistry=mt;eS.deref=ve;eS.deserializerMiddlewareOption=Hw;eS.error=tS;eS.getSchemaSerdePlugin=ag;eS.isStaticSchema=Fw;eS.list=vg;eS.map=Zg;eS.op=pg;eS.operation=kh;eS.serializerMiddlewareOption=Ww;eS.sim=iS;eS.simAdapter=sS;eS.simpleSchemaCacheN=pe;eS.simpleSchemaCacheS=no;eS.struct=nS;eS.traitsCache=Ze;eS.translateTraits=Hr});var Xt=k((wI)=>{var{getSmithyContext:WS,normalizeProvider:FS}=St();wI.getSmithyContext=WS;wI.normalizeProvider=FS;var{SMITHY_CONTEXT_KEY:PS,AlgorithmId:oo}=Di();wI.AlgorithmId=oo;var{NormalizedSchema:DS}=ri(),Yi=(n,t)=>{let i=[];if(n)i.push(n);if(t)for(let s of t)i.push(s);return i},ei=(n,t)=>{return`${n||"anonymous"}${t&&t.length>0?` (a.k.a. ${t.join(",")})`:""}`},Pr=()=>{let n=[],t=[],i=!1,s=new Set,r=(_)=>_.sort((w,l)=>Pw[l.step]-Pw[w.step]||Dw[l.priority||"normal"]-Dw[w.priority||"normal"]),e=(_)=>{let w=!1,l=(A)=>{let d=Yi(A.name,A.aliases);if(d.includes(_)){w=!0;for(let E of d)s.delete(E);return!1}return!0};return n=n.filter(l),t=t.filter(l),w},f=(_)=>{let w=!1,l=(A)=>{if(A.middleware===_){w=!0;for(let d of Yi(A.name,A.aliases))s.delete(d);return!1}return!0};return n=n.filter(l),t=t.filter(l),w},o=(_)=>{return n.forEach((w)=>{_.add(w.middleware,{...w})}),t.forEach((w)=>{_.addRelativeTo(w.middleware,{...w})}),_.identifyOnResolve?.(c.identifyOnResolve()),_},h=(_)=>{let w=[];return _.before.forEach((l)=>{if(l.before.length===0&&l.after.length===0)w.push(l);else w.push(...h(l))}),w.push(_),_.after.reverse().forEach((l)=>{if(l.before.length===0&&l.after.length===0)w.push(l);else w.push(...h(l))}),w},u=(_=!1)=>{let w=[],l=[],A={};return n.forEach((E)=>{let R={...E,before:[],after:[]};for(let y of Yi(R.name,R.aliases))A[y]=R;w.push(R)}),t.forEach((E)=>{let R={...E,before:[],after:[]};for(let y of Yi(R.name,R.aliases))A[y]=R;l.push(R)}),l.forEach((E)=>{if(E.toMiddleware){let R=A[E.toMiddleware];if(R===void 0){if(_)return;throw Error(`${E.toMiddleware} is not found when adding ${ei(E.name,E.aliases)} middleware ${E.relation} ${E.toMiddleware}`)}if(E.relation==="after")R.after.push(E);if(E.relation==="before")R.before.push(E)}}),r(w).map(h).reduce((E,R)=>{return E.push(...R),E},[])},c={add:(_,w={})=>{let{name:l,override:A,aliases:d}=w,E={step:"initialize",priority:"normal",middleware:_,...w},R=Yi(l,d);if(R.length>0){if(R.some((y)=>s.has(y))){if(!A)throw Error(`Duplicate middleware name '${ei(l,d)}'`);for(let y of R){let T=n.findIndex((I)=>I.name===y||I.aliases?.some((F)=>F===y));if(T===-1)continue;let S=n[T];if(S.step!==E.step||E.priority!==S.priority)throw Error(`"${ei(S.name,S.aliases)}" middleware with ${S.priority} priority in ${S.step} step cannot be overridden by "${ei(l,d)}" middleware with ${E.priority} priority in ${E.step} step.`);n.splice(T,1)}}for(let y of R)s.add(y)}n.push(E)},addRelativeTo:(_,w)=>{let{name:l,override:A,aliases:d}=w,E={middleware:_,...w},R=Yi(l,d);if(R.length>0){if(R.some((y)=>s.has(y))){if(!A)throw Error(`Duplicate middleware name '${ei(l,d)}'`);for(let y of R){let T=t.findIndex((I)=>I.name===y||I.aliases?.some((F)=>F===y));if(T===-1)continue;let S=t[T];if(S.toMiddleware!==E.toMiddleware||S.relation!==E.relation)throw Error(`"${ei(S.name,S.aliases)}" middleware ${S.relation} "${S.toMiddleware}" middleware cannot be overridden by "${ei(l,d)}" middleware ${E.relation} "${E.toMiddleware}" middleware.`);t.splice(T,1)}}for(let y of R)s.add(y)}t.push(E)},clone:()=>o(Pr()),use:(_)=>{_.applyToStack(c)},remove:(_)=>{if(typeof _==="string")return e(_);else return f(_)},removeByTag:(_)=>{let w=!1,l=(A)=>{let{tags:d,name:E,aliases:R}=A;if(d&&d.includes(_)){let y=Yi(E,R);for(let T of y)s.delete(T);return w=!0,!1}return!0};return n=n.filter(l),t=t.filter(l),w},concat:(_)=>{let w=o(Pr());return w.use(_),w.identifyOnResolve(i||w.identifyOnResolve()||(_.identifyOnResolve?.()??!1)),w},applyToStack:o,identify:()=>{return u(!0).map((_)=>{let w=_.step??_.relation+" "+_.toMiddleware;return ei(_.name,_.aliases)+" - "+w})},identifyOnResolve(_){if(typeof _==="boolean")i=_;return i},resolve:(_,w)=>{for(let l of u().map((A)=>A.middleware).reverse())_=l(_,w);if(i)console.log(c.identify());return _}};return c},Pw={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},Dw={high:3,normal:2,low:1},YS=(n)=>()=>{throw Error(n)},mS=(n)=>()=>Promise.reject(n),eo=()=>{let n=new WeakSet;return(t,i)=>{if(typeof i==="object"&&i!==null){if(n.has(i))return"[Circular]";n.add(i)}return i}},JS=(n)=>{return new Promise((t)=>setTimeout(t,n*1000))},Jw={minDelay:2,maxDelay:120},It;(function(n){n.ABORTED="ABORTED",n.FAILURE="FAILURE",n.SUCCESS="SUCCESS",n.RETRY="RETRY",n.TIMEOUT="TIMEOUT"})(It||(It={}));var XS=(n)=>{if(n.state===It.ABORTED){let t=Error(`${JSON.stringify({...n,reason:"Request was aborted"},eo())}`);throw t.name="AbortError",t}else if(n.state===It.TIMEOUT){let t=Error(`${JSON.stringify({...n,reason:"Waiter has timed out"},eo())}`);throw t.name="TimeoutError",t}else if(n.state!==It.SUCCESS)throw Error(`${JSON.stringify(n,eo())}`);return n},zS=async({minDelay:n,maxDelay:t,maxWaitTime:i,abortController:s,client:r,abortSignal:e},f,o)=>{let h={},[u,c]=[n*1000,t*1000],_=0,w=Date.now()+i*1000,l=Date.now()+60000,A=!1;while(!0){if(_>0){let R=xS(u,c,_,w);if(s?.signal?.aborted||e?.aborted)return h["AbortController signal aborted."]|=0,h["AbortController signal aborted."]+=1,{state:It.ABORTED,observedResponses:h};if(Date.now()+R>w)return{state:It.TIMEOUT,observedResponses:h};await JS(R/1000)}let{state:d,reason:E}=await o(r,f);if(E){let R=CS(E);h[R]|=0,h[R]+=1}if(d!==It.RETRY)return{state:d,reason:E,final:E,observedResponses:h};if(_+=1,!A&&Date.now()>=l)QS(h,r),A=!0}},QS=(n={},t)=>{let i=Object.keys(n),s=0;for(let f of i){let o=n[f]|0;if(f.startsWith("403:"))s+=o}let r=t?.config?.logger,e=typeof r?.warn==="function"&&!r.constructor?.name?.includes?.("NoOpLogger")?r:console;if(s>=3||i[i.length-1]?.startsWith("403:"))e.warn("@smithy/util-waiter WARN - 403 status code encountered during waiter polling.")},CS=(n)=>{let t=n?.$response?.statusCode??n?.$metadata?.httpStatusCode;if(n?.$responseBodyText)return`${t?t+": ":""}Deserialization error for body: ${n.$responseBodyText}`;if(t){if(n?.$response||n?.message)return`${t??"Unknown"}: ${n?.message}`;return`${t}: OK`}return String(n?.message??JSON.stringify(n,eo())??"Unknown")},xS=(n,t,i,s)=>{let r=Math.log(t/n)/Math.log(2)+1;if(i>r)return t;let e=n*2**(i-1),f=Math.min(e,t),o=KS(n,f);if(Date.now()+o>s){let h=s-Date.now();return Math.max(0,h-500)}return o},KS=(n,t)=>n+Math.random()*(t-n),kS=(n)=>{if(n.maxWaitTime<=0)throw Error("WaiterConfiguration.maxWaitTime must be greater than 0");else if(n.minDelay<=0)throw Error("WaiterConfiguration.minDelay must be greater than 0");else if(n.maxDelay<=0)throw Error("WaiterConfiguration.maxDelay must be greater than 0");else if(n.maxWaitTime<=n.minDelay)throw Error(`WaiterConfiguration.maxWaitTime [${n.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${n.minDelay}] for this waiter`);else if(n.maxDelay<n.minDelay)throw Error(`WaiterConfiguration.maxDelay [${n.maxDelay}] must be greater than WaiterConfiguration.minDelay [${n.minDelay}] for this waiter`)},Yw=(n)=>{let t,i=new Promise((s)=>{if(t=()=>s({state:It.ABORTED}),typeof n.addEventListener==="function")n.addEventListener("abort",t);else n.onabort=t});return{clearListener(){if(typeof n.removeEventListener==="function")n.removeEventListener("abort",t)},aborted:i}},qS=async(n,t,i)=>{let s={...Jw,...n};kS(s);let r=[zS(s,t,i)],e=[];if(n.abortSignal){let{aborted:f,clearListener:o}=Yw(n.abortSignal);e.push(o),r.push(f)}if(n.abortController?.signal){let{aborted:f,clearListener:o}=Yw(n.abortController.signal);e.push(o),r.push(f)}return Promise.race(r).then((f)=>{for(let o of e)o();return f})};class Xw{config;middlewareStack=Pr();initConfig;handlers;constructor(n){this.config=n;let{protocol:t,protocolSettings:i}=n;if(i){if(typeof t==="function")n.protocol=new t(i)}}send(n,t,i){let s=typeof t!=="function"?t:void 0,r=typeof t==="function"?t:i,e=s===void 0&&this.config.cacheMiddleware===!0,f;if(e){if(!this.handlers)this.handlers=new WeakMap;let o=this.handlers;if(o.has(n.constructor))f=o.get(n.constructor);else f=n.resolveMiddleware(this.middlewareStack,this.config,s),o.set(n.constructor,f)}else delete this.handlers,f=n.resolveMiddleware(this.middlewareStack,this.config,s);if(r)f(n).then((o)=>r(null,o.output),(o)=>r(o)).catch(()=>{});else return f(n).then((o)=>o.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}var qh="***SensitiveInformation***";function fo(n,t){if(t==null)return t;let i=DS.of(n);if(i.getMergedTraits().sensitive)return qh;if(i.isListSchema()){if(!!i.getValueSchema().getMergedTraits().sensitive)return qh}else if(i.isMapSchema()){if(!!i.getKeySchema().getMergedTraits().sensitive||!!i.getValueSchema().getMergedTraits().sensitive)return qh}else if(i.isStructSchema()&&typeof t==="object"){let s=t,r={};for(let[e,f]of i.structIterator())if(s[e]!=null)r[e]=fo(f,s[e]);return r}return t}class ho{middlewareStack=Pr();schema;static classBuilder(){return new zw}resolveMiddlewareWithContext(n,t,i,{middlewareFn:s,clientName:r,commandName:e,inputFilterSensitiveLog:f,outputFilterSensitiveLog:o,smithyContext:h,additionalContext:u,CommandCtor:c}){for(let E of s.bind(this)(c,n,t,i))this.middlewareStack.use(E);let _=n.concat(this.middlewareStack),{logger:w}=t,l={logger:w,clientName:r,commandName:e,inputFilterSensitiveLog:f,outputFilterSensitiveLog:o,[PS]:{commandInstance:this,...h},...u},{requestHandler:A}=t,d=i??{};if(h.eventStream)d={isEventStream:!0,...d};return _.resolve((E)=>A.handle(E.request,d),l)}}class zw{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(n){this._init=n}ep(n){return this._ep=n,this}m(n){return this._middlewareFn=n,this}s(n,t,i={}){return this._smithyContext={service:n,operation:t,...i},this}c(n={}){return this._additionalContext=n,this}n(n,t){return this._clientName=n,this._commandName=t,this}f(n=(i)=>i,t=(i)=>i){return this._inputFilterSensitiveLog=n,this._outputFilterSensitiveLog=t,this}ser(n){return this._serializer=n,this}de(n){return this._deserializer=n,this}sc(n){return this._operationSchema=n,this._smithyContext.operationSchema=n,this}build(){let n=this,t;return t=class extends ho{input;static getEndpointParameterInstructions(){return n._ep}constructor(...[i]){super();this.input=i??{},n._init(this),this.schema=n._operationSchema}resolveMiddleware(i,s,r){let e=n._operationSchema,f=e?.[4]??e?.input,o=e?.[5]??e?.output;return this.resolveMiddlewareWithContext(i,s,r,{CommandCtor:t,middlewareFn:n._middlewareFn,clientName:n._clientName,commandName:n._commandName,inputFilterSensitiveLog:n._inputFilterSensitiveLog??(e?fo.bind(null,f):(h)=>h),outputFilterSensitiveLog:n._outputFilterSensitiveLog??(e?fo.bind(null,o):(h)=>h),smithyContext:n._smithyContext,additionalContext:n._additionalContext})}serialize=n._serializer;deserialize=n._deserializer}}}var VS="***SensitiveInformation***",jS=(n,t,i)=>{for(let[e,f]of Object.entries(n)){let o=async function(u,c,_){let w=new f(u);if(typeof c==="function")this.send(w,c);else if(typeof _==="function"){if(typeof c!=="object")throw Error(`Expected http options but got ${typeof c}`);this.send(w,c||{},_)}else return this.send(w,c)},h=(e[0].toLowerCase()+e.slice(1)).replace(/Command$/,"");t.prototype[h]=o}let{paginators:s={},waiters:r={}}=i??{};for(let[e,f]of Object.entries(s))if(t.prototype[e]===void 0)t.prototype[e]=function(o={},h,...u){return f({...h,client:this},o,...u)};for(let[e,f]of Object.entries(r))if(t.prototype[e]===void 0)t.prototype[e]=async function(o={},h,...u){let c=h;if(typeof h==="number")c={maxWaitTime:h};return f({...c,client:this},o,...u)}};class Os extends Error{$fault;$response;$retryable;$metadata;constructor(n){super(n.message);Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=n.name,this.$fault=n.$fault,this.$metadata=n.$metadata}static isInstance(n){if(!n)return!1;let t=n;return Os.prototype.isPrototypeOf(t)||Boolean(t.$fault)&&Boolean(t.$metadata)&&(t.$fault==="client"||t.$fault==="server")}static[Symbol.hasInstance](n){if(!n)return!1;let t=n;if(this===Os)return Os.isInstance(n);if(Os.isInstance(n)){if(t.name&&this.name)return this.prototype.isPrototypeOf(n)||t.name===this.name;return this.prototype.isPrototypeOf(n)}return!1}}var Qw=(n,t={})=>{Object.entries(t).filter(([,s])=>s!==void 0).forEach(([s,r])=>{if(n[s]==null||n[s]==="")n[s]=r});let i=n.message||n.Message||"UnknownError";return n.message=i,delete n.Message,n},Cw=({output:n,parsedBody:t,exceptionCtor:i,errorCode:s})=>{let r=vS(n),e=r.httpStatusCode?r.httpStatusCode+"":void 0,f=new i({name:t?.code||t?.Code||s||e||"UnknownError",$fault:"client",$metadata:r});throw Qw(f,t)},aS=(n)=>{return({output:t,parsedBody:i,errorCode:s})=>{Cw({output:t,parsedBody:i,exceptionCtor:n,errorCode:s})}},vS=(n)=>({httpStatusCode:n.statusCode,requestId:n.headers["x-amzn-requestid"]??n.headers["x-amzn-request-id"]??n.headers["x-amz-request-id"],extendedRequestId:n.headers["x-amz-id-2"],cfId:n.headers["x-amz-cf-id"]}),ZS=(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:30000};default:return{}}},mw=!1,pS=(n)=>{if(n&&!mw&&parseInt(n.substring(1,n.indexOf(".")))<16)mw=!0},xw=Object.values(oo),Kw=(n)=>{let t=[];for(let i in oo){let s=oo[i];if(n[s]===void 0)continue;t.push({algorithmId:()=>s,checksumConstructor:()=>n[s]})}for(let[i,s]of Object.entries(n.checksumAlgorithms??{}))t.push({algorithmId:()=>i,checksumConstructor:()=>s});return{addChecksumAlgorithm(i){n.checksumAlgorithms=n.checksumAlgorithms??{};let s=i.algorithmId(),r=i.checksumConstructor();if(xw.includes(s))n.checksumAlgorithms[s.toUpperCase()]=r;else n.checksumAlgorithms[s]=r;t.push(i)},checksumAlgorithms(){return t}}},kw=(n)=>{let t={};return n.checksumAlgorithms().forEach((i)=>{let s=i.algorithmId();if(xw.includes(s))t[s]=i.checksumConstructor()}),t},qw=(n)=>{return{setRetryStrategy(t){n.retryStrategy=t},retryStrategy(){return n.retryStrategy}}},Vw=(n)=>{let t={};return t.retryStrategy=n.retryStrategy(),t},jw=(n)=>{return Object.assign(Kw(n),qw(n))},nI=jw,tI=(n)=>{return Object.assign(kw(n),Vw(n))},iI=(n)=>Array.isArray(n)?n:[n],aw=(n)=>{for(let i in n)if(Object.prototype.hasOwnProperty.call(n,i)&&n[i]["#text"]!==void 0)n[i]=n[i]["#text"];else if(typeof n[i]==="object"&&n[i]!==null)n[i]=aw(n[i]);return n},sI=(n)=>{return n!=null};class vw{trace(){}debug(){}info(){}warn(){}error(){}}function Zw(n,t,i){let s,r,e;if(typeof t>"u"&&typeof i>"u")s={},e=n;else if(s=n,typeof t==="function")return r=t,e=i,oI(s,r,e);else e=t;for(let f of Object.keys(e)){if(!Array.isArray(e[f])){s[f]=e[f];continue}pw(s,null,e,f)}return s}var rI=(n)=>{let t={};for(let[i,s]of Object.entries(n||{}))t[i]=[,s];return t},eI=(n,t)=>{let i={};for(let s in t)pw(i,n,t,s);return i},oI=(n,t,i)=>{return Zw(n,Object.entries(i).reduce((s,[r,e])=>{if(Array.isArray(e))s[r]=e;else if(typeof e==="function")s[r]=[t,e()];else s[r]=[t,e];return s},{}))},pw=(n,t,i,s)=>{if(t!==null){let f=i[s];if(typeof f==="function")f=[,f];let[o=fI,h=hI,u=s]=f;if(typeof o==="function"&&o(t[u])||typeof o!=="function"&&!!o)n[s]=h(t[u]);return}let[r,e]=i[s];if(typeof e==="function"){let f,o=r===void 0&&(f=e())!=null,h=typeof r==="function"&&!!r(void 0)||typeof r!=="function"&&!!r;if(o)n[s]=f;else if(h)n[s]=e()}else{let f=r===void 0&&e!=null,o=typeof r==="function"&&!!r(e)||typeof r!=="function"&&!!r;if(f||o)n[s]=e}},fI=(n)=>n!=null,hI=(n)=>n,uI=(n)=>{if(n!==n)return"NaN";switch(n){case 1/0:return"Infinity";case-1/0:return"-Infinity";default:return n}},cI=(n)=>n.toISOString().replace(".000Z","Z"),Vh=(n)=>{if(n==null)return{};if(Array.isArray(n))return n.filter((t)=>t!=null).map(Vh);if(typeof n==="object"){let t={};for(let i of Object.keys(n)){if(n[i]==null)continue;t[i]=Vh(n[i])}return t}return n};function _I(n,t,i,s){return function(e,f,o,h,u={}){let c=Object.assign({},n,e);return ho.classBuilder().ep(c).m(function(_,w,l,A){let d=f.call(this,_,w,l,A);return d.unshift(s(l,_.getEndpointParameterInstructions())),d}).s(t,o,u).n(i,o.charAt(0).toUpperCase()+o.slice(1)+"Command").sc(h).build()}}wI.Client=Xw;wI.Command=ho;wI.NoOpLogger=vw;wI.SENSITIVE_STRING=VS;wI.ServiceException=Os;wI.WaiterState=It;wI._json=Vh;wI.checkExceptions=XS;wI.constructStack=Pr;wI.convertMap=rI;wI.createAggregatedClient=jS;wI.createWaiter=qS;wI.decorateServiceException=Qw;wI.emitWarningIfUnsupportedVersion=pS;wI.getArrayIfSingleItem=iI;wI.getChecksumConfiguration=Kw;wI.getDefaultClientConfiguration=nI;wI.getDefaultExtensionConfiguration=jw;wI.getRetryConfiguration=qw;wI.getValueFromTextNode=aw;wI.invalidFunction=YS;wI.invalidProvider=mS;wI.isSerializableHeaderValue=sI;wI.loadConfigsForDefaultMode=ZS;wI.makeBuilder=_I;wI.map=Zw;wI.resolveChecksumRuntimeConfig=kw;wI.resolveDefaultRuntimeConfig=tI;wI.resolveRetryRuntimeConfig=Vw;wI.schemaLogFilter=fo;wI.serializeDateTime=cI;wI.serializeFloat=uI;wI.take=eI;wI.throwDefaultError=Cw;wI.waiterServiceDefaults=Jw;wI.withBaseException=aS});var Yn=k((Z5)=>{var{homedir:ZI}=p("os"),{sep:pI,join:Dr}=p("path"),{createHash:n5}=p("crypto"),{readFile:hl}=p("fs/promises"),{IniSectionType:uo}=Di(),{normalizeProvider:co}=Xt(),{isValidHostLabel:t5}=St();class Bs extends Error{name="ProviderError";tryNextLink;constructor(n,t=!0){let i,s=!0;if(typeof t==="boolean")i=void 0,s=t;else if(t!=null&&typeof t==="object")i=t.logger,s=t.tryNextLink??!0;super(n);this.tryNextLink=s,Object.setPrototypeOf(this,Bs.prototype),i?.debug?.(`@smithy/property-provider ${s?"->":"(!)"} ${n}`)}static from(n,t=!0){return Object.assign(new this(n.message,t),n)}}class Yr extends Bs{name="CredentialsProviderError";constructor(n,t=!0){super(n,t);Object.setPrototypeOf(this,Yr.prototype)}}class ph extends Bs{name="TokenProviderError";constructor(n,t=!0){super(n,t);Object.setPrototypeOf(this,ph.prototype)}}var ul=(...n)=>async()=>{if(n.length===0)throw new Bs("No providers in chain");let t;for(let i of n)try{return await i()}catch(s){if(t=s,s?.tryNextLink)continue;throw s}throw t},cl=(n)=>()=>Promise.resolve(n),nu=(n,t,i)=>{let s,r,e,f=!1,o=async()=>{if(!r)r=n();try{s=await r,e=!0,f=!1}finally{r=void 0}return s};if(t===void 0)return async(h)=>{if(!e||h?.forceRefresh)s=await o();return s};return async(h)=>{if(!e||h?.forceRefresh)s=await o();if(f)return s;if(i&&!i(s))return f=!0,s;if(t(s))return await o(),s;return s}},zt=(n,t,i)=>{if(!(t in n))return;if(n[t]==="true")return!0;if(n[t]==="false")return!1;throw Error(`Cannot load ${i} "${t}". Expected "true" or "false", got ${n[t]}.`)},i5=(n,t,i)=>{if(!(t in n))return;let s=parseInt(n[t],10);if(Number.isNaN(s))throw TypeError(`Cannot load ${i} '${t}'. Expected number, got '${n[t]}'.`);return s},ut;(function(n){n.ENV="env",n.CONFIG="shared config entry"})(ut||(ut={}));var jh={},s5=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},mr=()=>{let{HOME:n,USERPROFILE:t,HOMEPATH:i,HOMEDRIVE:s=`C:${pI}`}=process.env;if(n)return n;if(t)return t;if(i)return`${s}${i}`;let r=s5();if(!jh[r])jh[r]=ZI();return jh[r]},_l="AWS_PROFILE",wl="default",ll=(n)=>n.profile||process.env[_l]||wl,Al=(n)=>{let i=n5("sha1").update(n).digest("hex");return Dr(mr(),".aws","sso","cache",`${i}.json`)},_o={},r5=async(n)=>{if(_o[n])return _o[n];let t=Al(n),i=await hl(t,"utf8");return JSON.parse(i)},mi=".",e5=(n)=>Object.entries(n).filter(([t])=>{let i=t.indexOf(mi);if(i===-1)return!1;return Object.values(uo).includes(t.substring(0,i))}).reduce((t,[i,s])=>{let r=i.indexOf(mi),e=i.substring(0,r)===uo.PROFILE?i.substring(r+1):i;return t[e]=s,t},{...n.default&&{default:n.default}}),o5="AWS_CONFIG_FILE",Ml=()=>process.env[o5]||Dr(mr(),".aws","config"),f5="AWS_SHARED_CREDENTIALS_FILE",h5=()=>process.env[f5]||Dr(mr(),".aws","credentials"),u5=/^([\w-]+)\s(["'])?([\w-@+.%:/]+)\2$/,c5=["__proto__","profile __proto__"],vh=(n)=>{let t={},i,s;for(let r of n.split(/\r?\n/)){let e=r.split(/(^|\s)[;#]/)[0].trim();if(e[0]==="["&&e[e.length-1]==="]"){i=void 0,s=void 0;let o=e.substring(1,e.length-1),h=u5.exec(o);if(h){let[,u,,c]=h;if(Object.values(uo).includes(u))i=[u,c].join(mi)}else i=o;if(c5.includes(o))throw Error(`Found invalid profile name "${o}"`)}else if(i){let o=e.indexOf("=");if(![0,-1].includes(o)){let[h,u]=[e.substring(0,o).trim(),e.substring(o+1).trim()];if(u==="")s=h;else{if(s&&r.trimStart()===r)s=void 0;t[i]=t[i]||{};let c=s?[s,h].join(mi):h;t[i][c]=u}}}}return t},ah={},wo={},lo=(n,t)=>{if(wo[n]!==void 0)return wo[n];if(!ah[n]||t?.ignoreCache)ah[n]=hl(n,"utf8");return ah[n]},nl=()=>({}),tu=async(n={})=>{let{filepath:t=h5(),configFilepath:i=Ml()}=n,s=mr(),r="~/",e=t;if(t.startsWith("~/"))e=Dr(s,t.slice(2));let f=i;if(i.startsWith("~/"))f=Dr(s,i.slice(2));let o=await Promise.all([lo(f,{ignoreCache:n.ignoreCache}).then(vh).then(e5).catch(nl),lo(e,{ignoreCache:n.ignoreCache}).then(vh).catch(nl)]);return{configFile:o[0],credentialsFile:o[1]}},_5=(n)=>Object.entries(n).filter(([t])=>t.startsWith(uo.SSO_SESSION+mi)).reduce((t,[i,s])=>({...t,[i.substring(i.indexOf(mi)+1)]:s}),{}),w5=()=>({}),l5=async(n={})=>lo(n.configFilepath??Ml()).then(vh).then(_5).catch(w5),A5=(...n)=>{let t={};for(let i of n)for(let[s,r]of Object.entries(i))if(t[s]!==void 0)Object.assign(t[s],r);else t[s]=r;return t},M5=async(n)=>{let t=await tu(n);return A5(t.configFile,t.credentialsFile)},d5={getFileRecord(){return wo},interceptFile(n,t){wo[n]=Promise.resolve(t)},getTokenRecord(){return _o},interceptToken(n,t){_o[n]=t}};function dl(n){try{let t=new Set(Array.from(n.match(/([A-Z_]){3,}/g)??[]));return t.delete("CONFIG"),t.delete("CONFIG_PREFIX_SEPARATOR"),t.delete("ENV"),[...t].join(", ")}catch(t){return n}}var R5=(n,t)=>async()=>{try{let i=n(process.env,t);if(i===void 0)throw Error();return i}catch(i){throw new Yr(i.message||`Not found in ENV: ${dl(n.toString())}`,{logger:t?.logger})}},E5=(n,{preferredFile:t="config",...i}={})=>async()=>{let s=ll(i),{configFile:r,credentialsFile:e}=await tu(i),f=e[s]||{},o=r[s]||{},h=t==="config"?{...f,...o}:{...o,...f};try{let c=n(h,t==="config"?r:e);if(c===void 0)throw Error();return c}catch(u){throw new Yr(u.message||`Not found in config files w/ profile [${s}]: ${dl(n.toString())}`,{logger:i.logger})}},y5=(n)=>typeof n==="function",Rl=(n)=>y5(n)?async()=>await n():cl(n),Zh=({environmentVariableSelector:n,configFileSelector:t,default:i},s={})=>{let{signingName:r,logger:e}=s;return nu(ul(R5(n,{signingName:r,logger:e}),E5(t,s),Rl(i)))},iu="AWS_USE_DUALSTACK_ENDPOINT",su="use_dualstack_endpoint",T5=!1,g5={environmentVariableSelector:(n)=>zt(n,iu,ut.ENV),configFileSelector:(n)=>zt(n,su,ut.CONFIG),default:!1},S5={environmentVariableSelector:(n)=>zt(n,iu,ut.ENV),configFileSelector:(n)=>zt(n,su,ut.CONFIG),default:void 0},ru="AWS_USE_FIPS_ENDPOINT",eu="use_fips_endpoint",I5=!1,U5={environmentVariableSelector:(n)=>zt(n,ru,ut.ENV),configFileSelector:(n)=>zt(n,eu,ut.CONFIG),default:!1},b5={environmentVariableSelector:(n)=>zt(n,ru,ut.ENV),configFileSelector:(n)=>zt(n,eu,ut.CONFIG),default:void 0},$5=(n)=>{let{tls:t,endpoint:i,urlParser:s,useDualstackEndpoint:r}=n;return Object.assign(n,{tls:t??!0,endpoint:co(typeof i==="string"?s(i):i),isCustomEndpoint:!0,useDualstackEndpoint:co(r??!1)})},L5=async(n)=>{let{tls:t=!0}=n,i=await n.region();if(!new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/).test(i))throw Error("Invalid region in client config");let r=await n.useDualstackEndpoint(),e=await n.useFipsEndpoint(),{hostname:f}=await n.regionInfoProvider(i,{useDualstackEndpoint:r,useFipsEndpoint:e})??{};if(!f)throw Error("Cannot resolve hostname from client config");return n.urlParser(`${t?"https:":"http:"}//${f}`)},O5=(n)=>{let t=co(n.useDualstackEndpoint??!1),{endpoint:i,useFipsEndpoint:s,urlParser:r,tls:e}=n;return Object.assign(n,{tls:e??!0,endpoint:i?co(typeof i==="string"?r(i):i):()=>L5({...n,useDualstackEndpoint:t,useFipsEndpoint:s}),isCustomEndpoint:!!i,useDualstackEndpoint:t})},B5="AWS_EXECUTION_ENV",tl="AWS_REGION",il="AWS_DEFAULT_REGION",N5="AWS_EC2_METADATA_DISABLED",G5=["in-region","cross-region","mobile","standard","legacy"],H5="/latest/meta-data/placement/region",W5="/latest/api/token",F5="x-aws-ec2-metadata-token",P5="x-aws-ec2-metadata-token-ttl-seconds",sl=1000,D5=60000,El=0,yl=async()=>{if(process.env[N5])return;if(Date.now()<El)return;try{let n=Y5(),t=(await el({...n,path:W5,method:"PUT",headers:{[P5]:"21600"}})).toString();return(await el({...n,path:H5,method:"GET",headers:{[F5]:t}})).toString().trim()||rl()}catch{return rl()}},rl=()=>{El=Date.now()+D5;return},Y5=()=>{let n=process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT;if(n){let t=new URL(n);return{hostname:t.hostname.replace(/^\[(.+)]$/,"$1"),port:t.port?Number(t.port):void 0}}if(process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE==="IPv6")return{hostname:"fd00:ec2::254"};return{hostname:"169.254.169.254"}},el=async(n)=>{let{request:t}=p("http");return new Promise((i,s)=>{let r=t({hostname:n.hostname,port:n.port,path:n.path,method:n.method,headers:n.headers,timeout:sl,signal:AbortSignal.timeout(sl)});r.on("error",(e)=>{s(e),r.destroy()}),r.on("timeout",()=>{s(Error("TimeoutError from instance metadata service")),r.destroy()}),r.on("response",(e)=>{let{statusCode:f=400}=e;if(f<200||f>=300){s(Object.assign(Error("Error response received from instance metadata service"),{statusCode:f})),r.destroy();return}let o=[];e.on("data",(h)=>o.push(h)),e.on("end",()=>{i(Buffer.concat(o)),r.destroy()})}),r.end()})},Tl="AWS_REGION",gl="region",Sl={environmentVariableSelector:(n)=>n[Tl],configFileSelector:(n)=>n[gl],default:async()=>{let n=await yl();if(n)return n;throw Error("Region is missing")}},m5={preferredFile:"credentials"},ol=new Set,J5=(n,t=t5)=>{if(!ol.has(n)&&!t(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 Error(`Region not accepted: region="${n}" is not a valid hostname component.`);else ol.add(n)},Il=(n)=>typeof n==="string"&&(n.startsWith("fips-")||n.endsWith("-fips")),X5=(n)=>Il(n)?["fips-aws-global","aws-fips"].includes(n)?"us-east-1":n.replace(/fips-(dkr-|prod-)?|-fips/,""):n,z5=(n)=>{let{region:t,useFipsEndpoint:i}=n;if(!t)throw Error("Region is missing");return Object.assign(n,{region:async()=>{let s=typeof t==="function"?await t():t,r=X5(s);return J5(r),r},useFipsEndpoint:async()=>{let s=typeof t==="string"?t:await t();if(Il(s))return!0;return typeof i!=="function"?Promise.resolve(!!i):i()}})},fl=(n=[],{useFipsEndpoint:t,useDualstackEndpoint:i})=>n.find(({tags:s})=>t===s.includes("fips")&&i===s.includes("dualstack"))?.hostname,Q5=(n,{regionHostname:t,partitionHostname:i})=>t?t:i?i.replace("{region}",n):void 0,C5=(n,{partitionHash:t})=>Object.keys(t||{}).find((i)=>t[i].regions.includes(n))??"aws",x5=(n,{signingRegion:t,regionRegex:i,useFipsEndpoint:s})=>{if(t)return t;else if(s){let r=i.replace("\\\\","\\").replace(/^\^/g,"\\.").replace(/\$$/g,"\\."),e=n.match(r);if(e)return e[0].slice(1,-1)}},K5=(n,{useFipsEndpoint:t=!1,useDualstackEndpoint:i=!1,signingService:s,regionHash:r,partitionHash:e})=>{let f=C5(n,{partitionHash:e}),o=n in r?n:e[f]?.endpoint??n,h={useFipsEndpoint:t,useDualstackEndpoint:i},u=fl(r[o]?.variants,h),c=fl(e[f]?.variants,h),_=Q5(o,{regionHostname:u,partitionHostname:c});if(_===void 0)throw Error(`Endpoint resolution failed for: ${{resolvedRegion:o,useFipsEndpoint:t,useDualstackEndpoint:i}}`);let w=x5(_,{signingRegion:r[o]?.signingRegion,regionRegex:e[f].regionRegex,useFipsEndpoint:t});return{partition:f,signingService:s,hostname:_,...w&&{signingRegion:w},...r[o]?.signingService&&{signingService:r[o].signingService}}},k5="AWS_DEFAULTS_MODE",q5="defaults_mode",V5={environmentVariableSelector:(n)=>{return n[k5]},configFileSelector:(n)=>{return n[q5]},default:"legacy"},j5=({region:n=Zh(Sl),defaultsMode:t=Zh(V5)}={})=>nu(async()=>{let i=typeof t==="function"?await t():t;switch(i?.toLowerCase()){case"auto":return a5(n);case"in-region":case"cross-region":case"mobile":case"standard":case"legacy":return Promise.resolve(i?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw Error(`Invalid parameter for "defaultsMode", expect ${G5.join(", ")}, got ${i}`)}}),a5=async(n)=>{if(n){let t=typeof n==="function"?await n():n,i=await v5();if(!i)return"standard";if(t===i)return"in-region";else return"cross-region"}return"standard"},v5=async()=>{if(process.env[B5]&&(process.env[tl]||process.env[il]))return process.env[tl]??process.env[il];return yl()};Z5.CONFIG_PREFIX_SEPARATOR=mi;Z5.CONFIG_USE_DUALSTACK_ENDPOINT=su;Z5.CONFIG_USE_FIPS_ENDPOINT=eu;Z5.CredentialsProviderError=Yr;Z5.DEFAULT_PROFILE=wl;Z5.DEFAULT_USE_DUALSTACK_ENDPOINT=T5;Z5.DEFAULT_USE_FIPS_ENDPOINT=I5;Z5.ENV_PROFILE=_l;Z5.ENV_USE_DUALSTACK_ENDPOINT=iu;Z5.ENV_USE_FIPS_ENDPOINT=ru;Z5.NODE_REGION_CONFIG_FILE_OPTIONS=m5;Z5.NODE_REGION_CONFIG_OPTIONS=Sl;Z5.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS=g5;Z5.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS=U5;Z5.ProviderError=Bs;Z5.REGION_ENV_NAME=Tl;Z5.REGION_INI_NAME=gl;Z5.SelectorType=ut;Z5.TokenProviderError=ph;Z5.booleanSelector=zt;Z5.chain=ul;Z5.externalDataInterceptor=d5;Z5.fromStatic=Rl;Z5.fromValue=cl;Z5.getHomeDir=mr;Z5.getProfileName=ll;Z5.getRegionInfo=K5;Z5.getSSOTokenFilepath=Al;Z5.getSSOTokenFromFile=r5;Z5.loadConfig=Zh;Z5.loadSharedConfigFiles=tu;Z5.loadSsoSessionData=l5;Z5.memoize=nu;Z5.nodeDualstackConfigSelectors=S5;Z5.nodeFipsConfigSelectors=b5;Z5.numberSelector=i5;Z5.parseKnownFiles=M5;Z5.readFile=lo;Z5.resolveCustomEndpointsConfig=$5;Z5.resolveDefaultsModeConfig=j5;Z5.resolveEndpointsConfig=O5;Z5.resolveRegionConfig=z5});var Ji=k((bU)=>{var{CONFIG_PREFIX_SEPARATOR:Ul,loadConfig:z8}=Yn(),{toEndpointV1:Ao,getSmithyContext:Q8,normalizeProvider:ou,isValidHostLabel:Ll}=St();bU.isValidHostLabel=Ll;bU.middlewareEndpointToEndpointV1=Ao;bU.toEndpointV1=Ao;var{EndpointURLScheme:uu}=Di(),bl="AWS_ENDPOINT_URL",$l="endpoint_url",C8=(n)=>({environmentVariableSelector:(t)=>{let i=n.split(" ").map((e)=>e.toUpperCase()),s=t[[bl,...i].join("_")];if(s)return s;let r=t[bl];if(r)return r;return},configFileSelector:(t,i)=>{if(i&&t.services){let r=i[["services",t.services].join(Ul)];if(r){let e=n.split(" ").map((o)=>o.toLowerCase()),f=r[[e.join("_"),$l].join(Ul)];if(f)return f}}let s=t[$l];if(s)return s;return},default:void 0}),Mo=async(n)=>z8(C8(n??""))(),x8=async(n)=>{let t=n?.Bucket||"";if(typeof n.Bucket==="string")n.Bucket=t.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"));if(j8(t)){if(n.ForcePathStyle===!0)throw Error("Path-style addressing cannot be used with ARN buckets")}else if(!V8(t)||t.indexOf(".")!==-1&&!String(n.Endpoint).startsWith("http:")||t.toLowerCase()!==t||t.length<3)n.ForcePathStyle=!0;if(n.DisableMultiRegionAccessPoints)n.disableMultiRegionAccessPoints=!0,n.DisableMRAP=!0;return n},K8=/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/,k8=/(\d+\.){3}\d+/,q8=/\.\./,V8=(n)=>K8.test(n)&&!k8.test(n)&&!q8.test(n),j8=(n)=>{let[t,i,s,,,r]=n.split(":"),e=t==="arn"&&n.split(":").length>=6,f=Boolean(e&&i&&s&&r);if(e&&!f)throw Error(`Invalid ARN: ${n} was an invalid ARN.`);return f},a8=(n,t,i,s=!1)=>{let r=async()=>{let e;if(s)e=i.clientContextParams?.[n]??i[n]??i[t];else e=i[n]??i[t];if(typeof e==="function")return e();return e};if(n==="credentialScope"||t==="CredentialScope")return async()=>{let e=typeof i.credentials==="function"?await i.credentials():i.credentials;return e?.credentialScope??e?.CredentialScope};if(n==="accountId"||t==="AccountId")return async()=>{let e=typeof i.credentials==="function"?await i.credentials():i.credentials;return e?.accountId??e?.AccountId};if(n==="endpoint"||t==="endpoint")return async()=>{if(i.isCustomEndpoint===!1)return;let e=await r();if(e&&typeof e==="object"){if("url"in e)return e.url.href;if("hostname"in e){let{protocol:f,hostname:o,port:h,path:u}=e;return`${f}//${o}${h?":"+h:""}${u}`}}return e};return r};function Ol(n){return async(t,i,s,r)=>{if(!s.isCustomEndpoint){let o;if(s.serviceConfiguredEndpoint)o=await s.serviceConfiguredEndpoint();else o=await n(s.serviceId);if(o)s.endpoint=()=>Promise.resolve(Ao(o)),s.isCustomEndpoint=!0}let e=await Bl(t,i,s);if(typeof s.endpointProvider!=="function")throw Error("config.endpointProvider is not set.");let f=s.endpointProvider(e,r);if(s.isCustomEndpoint&&s.endpoint){let o=await s.endpoint();if(o?.headers){f.headers??={};for(let[h,u]of Object.entries(o.headers))f.headers[h]=Array.isArray(u)?u:[u]}}return f}}var Bl=async(n,t,i)=>{let s={},r=t?.getEndpointParameterInstructions?.()||{};for(let[e,f]of Object.entries(r))switch(f.type){case"staticContextParams":s[e]=f.value;break;case"contextParams":s[e]=n[f.name];break;case"clientContextParams":case"builtInParams":s[e]=await a8(f.name,e,i,f.type!=="builtInParams")();break;case"operationContextParams":s[e]=f.get(n);break;default:throw Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(f))}if(Object.keys(r).length===0)Object.assign(s,i);if(String(i.serviceId).toLowerCase()==="s3")await x8(s);return s};function v8(n,t,i){if(!n.__smithy_context)n.__smithy_context={features:{}};else if(!n.__smithy_context.features)n.__smithy_context.features={};n.__smithy_context.features[t]=i}function Nl(n){let t=Ol(n);return({config:i,instructions:s})=>{return(r,e)=>async(f)=>{if(i.isCustomEndpoint)v8(e,"ENDPOINT_OVERRIDE","N");let o=await t(f.input,{getEndpointParameterInstructions(){return s}},{...i},e);e.endpointV2=o,e.authSchemes=o.properties?.authSchemes;let h=e.authSchemes?.[0];if(h){e.signing_region=h.signingRegion,e.signing_service=h.signingName;let c=Q8(e)?.selectedHttpAuthScheme?.httpAuthOption;if(c)c.signingProperties=Object.assign(c.signingProperties||{},{signing_region:h.signingRegion,signingRegion:h.signingRegion,signing_service:h.signingName,signingName:h.signingName,signingRegionSet:h.signingRegionSet},h.properties)}return r({...f})}}}var Z8={name:"serializerMiddleware"},Gl={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:Z8.name};function p8(n){let t=Nl(n);return(i,s)=>({applyToStack:(r)=>{r.addRelativeTo(t({config:i,instructions:s}),Gl)}})}function nU(n){return(t)=>{let i=t.tls??!0,{endpoint:s,useDualstackEndpoint:r,useFipsEndpoint:e}=t,f=s!=null?async()=>Ao(await ou(s)()):void 0,h=Object.assign(t,{endpoint:f,tls:i,isCustomEndpoint:!!s,useDualstackEndpoint:ou(r??!1),useFipsEndpoint:ou(e??!1)}),u=void 0;return h.serviceConfiguredEndpoint=async()=>{if(t.serviceId&&!u)u=n(t.serviceId);return u},h}}class cu{nodes;root;conditions;results;constructor(n,t,i,s){this.nodes=n,this.root=t,this.conditions=i,this.results=s}static from(n,t,i,s){return new cu(n,t,i,s)}}class Hl{capacity;data=new Map;parameters=[];constructor({size:n,params:t}){if(this.capacity=n??50,t)this.parameters=t}get(n,t){let i=this.hash(n);if(i===!1)return t();if(!this.data.has(i)){if(this.data.size>this.capacity+10){let s=this.data.keys(),r=0;while(!0){let{value:e,done:f}=s.next();if(this.data.delete(e),f||++r>10)break}}this.data.set(i,t())}return this.data.get(i)}size(){return this.data.size}hash(n){let t="",{parameters:i}=this;if(i.length===0)return!1;for(let s of i){let r=String(n[s]??"");if(r.includes("|;"))return!1;t+=r+"|;"}return t}}class Ln extends Error{constructor(n){super(n);this.name="EndpointError"}}var Jr="endpoints";function oi(n){if(typeof n!=="object"||n==null)return n;if("ref"in n)return`$${oi(n.ref)}`;if("fn"in n)return`${n.fn}(${(n.argv||[]).map(oi).join(", ")})`;return JSON.stringify(n,null,2)}var Wl={},tU=(n,t)=>n===t;function iU(...n){for(let t of n)if(t!=null)return t;return}var sU=(n)=>{let t=n.split("."),i=[];for(let s of t){let r=s.indexOf("[");if(r!==-1){if(s.indexOf("]")!==s.length-1)throw new Ln(`Path: '${n}' does not end with ']'`);let e=s.slice(r+1,-1);if(Number.isNaN(parseInt(e)))throw new Ln(`Invalid array index: '${e}' in path: '${n}'`);if(r!==0)i.push(s.slice(0,r));i.push(e)}else i.push(s)}return i},Fl=(n,t)=>sU(t).reduce((i,s)=>{if(typeof i!=="object")throw new Ln(`Index '${s}' in '${t}' not found in '${JSON.stringify(n)}'`);else if(Array.isArray(i)){let r=parseInt(s);return i[r<0?i.length+r:r]}return i[s]},n),rU=(n)=>n!=null;function eU(n,t,i){return n?t:i}var oU=(n)=>!n,fU=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}$"),Pl=(n)=>fU.test(n)||n.startsWith("[")&&n.endsWith("]"),fu={[uu.HTTP]:80,[uu.HTTPS]:443},hU=(n)=>{let t=(()=>{try{if(n instanceof URL)return n;if(typeof n==="object"&&"hostname"in n){let{hostname:w,port:l,protocol:A="",path:d="",query:E={}}=n,R=new URL(`${A}//${w}${l?`:${l}`:""}${d}`);return R.search=Object.entries(E).map(([y,T])=>`${y}=${T}`).join("&"),R}return new URL(n)}catch(w){return null}})();if(!t)return console.error(`Unable to parse ${JSON.stringify(n)} as a whatwg URL.`),null;let i=t.href,{host:s,hostname:r,pathname:e,protocol:f,search:o}=t;if(o)return null;let h=f.slice(0,-1);if(!Object.values(uu).includes(h))return null;let u=Pl(r),c=i.includes(`${s}:${fu[h]}`)||typeof n==="string"&&n.includes(`${s}:${fu[h]}`),_=`${s}${c?`:${fu[h]}`:""}`;return{scheme:h,authority:_,path:e,normalizedPath:e.endsWith("/")?e:`${e}/`,isIp:u}};function uU(n,t,i){if(i===1)return[n];if(n==="")return[""];let s=n.split(t);if(i===0)return s;return s.slice(0,i-1).concat(s.slice(1).join(t))}var cU=(n,t)=>n===t,_U=(n,t,i,s)=>{if(n==null||t>=i||n.length<i||/[^\u0000-\u007f]/.test(n))return null;if(!s)return n.substring(t,i);return n.substring(n.length-i,n.length-t)},wU=(n)=>encodeURIComponent(n).replace(/[!*'()]/g,(t)=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),lU={booleanEquals:tU,coalesce:iU,getAttr:Fl,isSet:rU,isValidHostLabel:Ll,ite:eU,not:oU,parseURL:hU,split:uU,stringEquals:cU,substring:_U,uriEncode:wU},Dl=(n,t)=>{let i=[],{referenceRecord:s,endpointParams:r}=t,e=0;while(e<n.length){let f=n.indexOf("{",e);if(f===-1){i.push(n.slice(e));break}i.push(n.slice(e,f));let o=n.indexOf("}",f);if(o===-1){i.push(n.slice(f));break}if(n[f+1]==="{"&&n[o+1]==="}")i.push(n.slice(f+1,o)),e=o+2;let h=n.substring(f+1,o);if(h.includes("#")){let[u,c]=h.split("#");i.push(Fl(s[u]??r[u],c))}else i.push(s[h]??r[h]);e=o+1}return i.join("")},AU=({ref:n},t)=>{return t.referenceRecord[n]??t.endpointParams[n]},Xr=(n,t,i)=>{if(typeof n==="string")return Dl(n,i);else if(n.fn)return ml.callFunction(n,i);else if(n.ref)return AU(n,i);throw new Ln(`'${t}': ${String(n)} is not a string, function or reference.`)},Yl=({fn:n,argv:t},i)=>{let s=Array(t.length);for(let f=0;f<s.length;++f){let o=t[f];if(typeof o==="boolean"||typeof o==="number")s[f]=o;else s[f]=ml.evaluateExpression(o,"arg",i)}let r=n.indexOf(".");if(r!==-1){let o=Wl[n.slice(0,r)]?.[n.slice(r+1)];if(typeof o==="function")return o(...s)}let e=lU[n];if(typeof e==="function")return e(...s);throw Error(`function ${n} not loaded in endpointFunctions.`)},ml={evaluateExpression:Xr,callFunction:Yl},Jl=(n,t)=>{let{assign:i}=n;if(i&&i in t.referenceRecord)throw new Ln(`'${i}' is already defined in Reference Record.`);let s=Yl(n,t);t.logger?.debug?.(`${Jr} evaluateCondition: ${oi(n)} = ${oi(s)}`);let r=s===""?!0:!!s;if(i!=null)return{result:r,toAssign:{name:i,value:s}};return{result:r}},Xl=(n,t)=>Object.entries(n??{}).reduce((i,[s,r])=>{return i[s]=r.map((e)=>{let f=Xr(e,"Header value entry",t);if(typeof f!=="string")throw new Ln(`Header '${s}' value '${f}' is not a string`);return f}),i},{}),_u=(n,t)=>Object.entries(n).reduce((i,[s,r])=>{return i[s]=Ql.getEndpointProperty(r,t),i},{}),zl=(n,t)=>{if(Array.isArray(n))return n.map((i)=>zl(i,t));switch(typeof n){case"string":return Dl(n,t);case"object":if(n===null)throw new Ln(`Unexpected endpoint property: ${n}`);return Ql.getEndpointProperties(n,t);case"boolean":return n;default:throw new Ln(`Unexpected endpoint property type: ${typeof n}`)}},Ql={getEndpointProperty:zl,getEndpointProperties:_u},Cl=(n,t)=>{let i=Xr(n,"Endpoint URL",t);if(typeof i==="string")try{return new URL(i)}catch(s){throw console.error(`Failed to construct URL with ${i}`,s),s}throw new Ln(`Endpoint URL must be a string, got ${typeof i}`)},hu=1e8,MU=(n,t)=>{let{nodes:i,root:s,results:r,conditions:e}=n,f=s,o={},h={referenceRecord:o,endpointParams:t.endpointParams,logger:t.logger};while(f!==1&&f!==-1&&f<hu){let u=3*(Math.abs(f)-1),[c,_,w]=[i[u],i[u+1],i[u+2]],[l,A,d]=e[c],E=Jl({fn:l,assign:d,argv:A},h);if(E.toAssign){let{name:R,value:y}=E.toAssign;o[R]=y}f=f>=0===E.result?_:w}if(f>=hu){let u=r[f-hu];if(u[0]===-1){let[,l]=u;throw new Ln(Xr(l,"Error",h))}let[c,_,w]=u;return{url:Cl(c,h),properties:_u(_,h),headers:Xl(w??{},h)}}throw new Ln("No matching endpoint.")},wu=(n=[],t)=>{let i={},s={...t,referenceRecord:{...t.referenceRecord}},r=!1;for(let e of n){let{result:f,toAssign:o}=Jl(e,s);if(!f)return{result:f};if(o)r=!0,i[o.name]=o.value,s.referenceRecord[o.name]=o.value,t.logger?.debug?.(`${Jr} assign: ${o.name} := ${oi(o.value)}`)}if(r)return{result:!0,referenceRecord:i};return{result:!0}},dU=(n,t)=>{let{conditions:i,endpoint:s}=n,{result:r,referenceRecord:e}=wu(i,t);if(!r)return;let f=e?{...t,referenceRecord:{...t.referenceRecord,...e}}:t,{url:o,properties:h,headers:u}=s;t.logger?.debug?.(`${Jr} Resolving endpoint from template: ${oi(s)}`);let c={url:Cl(o,f)};if(u!=null)c.headers=Xl(u,f);if(h!=null)c.properties=_u(h,f);return c},RU=(n,t)=>{let{conditions:i,error:s}=n,{result:r,referenceRecord:e}=wu(i,t);if(!r)return;let f=e?{...t,referenceRecord:{...t.referenceRecord,...e}}:t;throw new Ln(Xr(s,"Error",f))},xl=(n,t)=>{for(let i of n)if(i.type==="endpoint"){let s=dU(i,t);if(s)return s}else if(i.type==="error")RU(i,t);else if(i.type==="tree"){let s=Kl.evaluateTreeRule(i,t);if(s)return s}else throw new Ln(`Unknown endpoint rule: ${i}`);throw new Ln("Rules evaluation failed")},EU=(n,t)=>{let{conditions:i,rules:s}=n,{result:r,referenceRecord:e}=wu(i,t);if(!r)return;let f=e?{...t,referenceRecord:{...t.referenceRecord,...e}}:t;return Kl.evaluateRules(s,f)},Kl={evaluateRules:xl,evaluateTreeRule:EU},yU=(n,t)=>{let{endpointParams:i,logger:s}=t,{parameters:r,rules:e}=n;t.logger?.debug?.(`${Jr} Initial EndpointParams: ${oi(i)}`);for(let o in r){let h=r[o],u=i[o];if(u==null&&h.default!=null){i[o]=h.default;continue}if(h.required&&u==null)throw new Ln(`Missing required parameter: '${o}'`)}let f=xl(e,{endpointParams:i,logger:s,referenceRecord:{}});return t.logger?.debug?.(`${Jr} Resolved endpoint: ${oi(f)}`),f},TU=(n)=>{let{endpoint:t}=n;if(t===void 0)n.endpoint=async()=>{throw Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint.")};return n},gU=Ol(Mo),SU=nU(Mo),IU=Nl(Mo),UU=p8(Mo);bU.BinaryDecisionDiagram=cu;bU.EndpointCache=Hl;bU.EndpointError=Ln;bU.customEndpointFunctions=Wl;bU.decideEndpoint=MU;bU.endpointMiddleware=IU;bU.endpointMiddlewareOptions=Gl;bU.getEndpointFromInstructions=gU;bU.getEndpointPlugin=UU;bU.isIpAddress=Pl;bU.resolveEndpoint=yU;bU.resolveEndpointConfig=SU;bU.resolveEndpointRequiredConfig=TU;bU.resolveParams=Bl});var mn=k((R$)=>{var{createHmac:CU,createHash:xU,getRandomValues:KU}=p("crypto"),{ReadStream:kU,lstatSync:qU,fstatSync:VU}=p("fs"),{HttpResponse:jU}=St(),{toEndpointV1:aU}=Ji(),{Readable:Ns,Writable:pl,PassThrough:kl}=p("stream"),nA=(n)=>typeof ArrayBuffer==="function"&&n instanceof ArrayBuffer||Object.prototype.toString.call(n)==="[object ArrayBuffer]",Hs=(n,t=0,i=n.byteLength-t)=>{if(!nA(n))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof n} (${n})`);return Buffer.from(n,t,i)},To=(n,t)=>{if(typeof n!=="string")throw TypeError(`The "input" argument must be of type string. Received type ${typeof n} (${n})`);return t?Buffer.from(n,t):Buffer.from(n)},vU=/^[A-Za-z0-9+/]*={0,2}$/,tA=(n)=>{if(n.length*3%4!==0)throw TypeError("Incorrect padding on base64 string.");if(!vU.exec(n))throw TypeError("Invalid base64 string.");let t=To(n,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)},go=(n)=>{let t=To(n,"utf8");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT)},Tu=(n)=>{let t;if(typeof n==="string")t=go(n);else t=n;if(typeof t!=="object"||typeof t.byteOffset!=="number"||typeof t.byteLength!=="number")throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");return Hs(t.buffer,t.byteOffset,t.byteLength).toString("base64")};function ZU(n,t,i,s){return class r extends Uint8Array{static fromString(e,f="utf-8"){if(typeof e==="string"){if(f==="base64")return r.mutate(s(e));return r.mutate(t(e))}throw Error(`Unsupported conversion from ${typeof e} to Uint8ArrayBlobAdapter.`)}static mutate(e){return Object.setPrototypeOf(e,r.prototype),e}transformToString(e="utf-8"){if(e==="base64")return i(this);return n(this)}}}var iA=(n)=>{if(typeof n==="string")return n;if(typeof n!=="object"||typeof n.byteOffset!=="number"||typeof n.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return Hs(n.buffer,n.byteOffset,n.byteLength).toString("utf8")},Gn=Array.from({length:256},(n,t)=>t.toString(16).padStart(2,"0"));function pU(n){if(typeof crypto<"u"&&typeof crypto.randomUUID==="function")return()=>crypto.randomUUID();return()=>{let t=new Uint8Array(16);return n(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128,Gn[t[0]]+Gn[t[1]]+Gn[t[2]]+Gn[t[3]]+"-"+Gn[t[4]]+Gn[t[5]]+"-"+Gn[t[6]]+Gn[t[7]]+"-"+Gn[t[8]]+Gn[t[9]]+"-"+Gn[t[10]]+Gn[t[11]]+Gn[t[12]]+Gn[t[13]]+Gn[t[14]]+Gn[t[15]]}}var nb=(n,t,i=(s)=>s)=>n,tb=(n)=>{switch(n){case"true":return!0;case"false":return!1;default:throw Error(`Unable to parse boolean value "${n}"`)}},ib=(n)=>{if(n===null||n===void 0)return;if(typeof n==="number"){if(n===0||n===1)xr.warn(Eo(`Expected boolean, got ${typeof n}: ${n}`));if(n===0)return!1;if(n===1)return!0}if(typeof n==="string"){let t=n.toLowerCase();if(t==="false"||t==="true")xr.warn(Eo(`Expected boolean, got ${typeof n}: ${n}`));if(t==="false")return!1;if(t==="true")return!0}if(typeof n==="boolean")return n;throw TypeError(`Expected boolean, got ${typeof n}: ${n}`)},Qr=(n)=>{if(n===null||n===void 0)return;if(typeof n==="string"){let t=parseFloat(n);if(!Number.isNaN(t)){if(String(t)!==String(n))xr.warn(Eo(`Expected number but observed string: ${n}`));return t}}if(typeof n==="number")return n;throw TypeError(`Expected number, got ${typeof n}: ${n}`)},sb=Math.ceil(340282346638528860000000000000000000000),Ro=(n)=>{let t=Qr(n);if(t!==void 0&&!Number.isNaN(t)&&t!==1/0&&t!==-1/0){if(Math.abs(t)>sb)throw TypeError(`Expected 32-bit float, got ${n}`)}return t},Cr=(n)=>{if(n===null||n===void 0)return;if(Number.isInteger(n)&&!Number.isNaN(n))return n;throw TypeError(`Expected integer, got ${typeof n}: ${n}`)},rb=Cr,du=(n)=>gu(n,32),Ru=(n)=>gu(n,16),Eu=(n)=>gu(n,8),gu=(n,t)=>{let i=Cr(n);if(i!==void 0&&eb(i,t)!==i)throw TypeError(`Expected ${t}-bit integer, got ${n}`);return i},eb=(n,t)=>{switch(t){case 32:return Int32Array.of(n)[0];case 16:return Int16Array.of(n)[0];case 8:return Int8Array.of(n)[0]}},ob=(n,t)=>{if(n===null||n===void 0){if(t)throw TypeError(`Expected a non-null value for ${t}`);throw TypeError("Expected a non-null value")}return n},sA=(n)=>{if(n===null||n===void 0)return;if(typeof n==="object"&&!Array.isArray(n))return n;let t=Array.isArray(n)?"array":typeof n;throw TypeError(`Expected object, got ${t}: ${n}`)},fb=(n)=>{if(n===null||n===void 0)return;if(typeof n==="string")return n;if(["boolean","number","bigint"].includes(typeof n))return xr.warn(Eo(`Expected string, got ${typeof n}: ${n}`)),String(n);throw TypeError(`Expected string, got ${typeof n}: ${n}`)},hb=(n)=>{if(n===null||n===void 0)return;let t=sA(n),i=[];for(let s in t)if(t[s]!=null)i.push(s);if(i.length===0)throw TypeError("Unions must have exactly one non-null member. None were found.");if(i.length>1)throw TypeError(`Unions must have exactly one non-null member. Keys ${i} were not null.`);return t},Su=(n)=>{if(typeof n=="string")return Qr(Ps(n));return Qr(n)},ub=Su,rA=(n)=>{if(typeof n=="string")return Ro(Ps(n));return Ro(n)},cb=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,Ps=(n)=>{let t=n.match(cb);if(t===null||t[0].length!==n.length)throw TypeError("Expected real number, got implicit NaN");return parseFloat(n)},Iu=(n)=>{if(typeof n=="string")return eA(n);return Qr(n)},_b=Iu,wb=Iu,lb=(n)=>{if(typeof n=="string")return eA(n);return Ro(n)},eA=(n)=>{switch(n){case"NaN":return NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;default:throw Error(`Unable to parse float value: ${n}`)}},oA=(n)=>{if(typeof n==="string")return Cr(Ps(n));return Cr(n)},Ab=oA,Mb=(n)=>{if(typeof n==="string")return du(Ps(n));return du(n)},Ws=(n)=>{if(typeof n==="string")return Ru(Ps(n));return Ru(n)},fA=(n)=>{if(typeof n==="string")return Eu(Ps(n));return Eu(n)},Eo=(n)=>{return String(TypeError(n).stack||n).split(`
|
|
6
|
+
`+f),n.push(s+"m+"+s_.exports.humanize(this.diff)+"\x1B[0m")}else n[0]=G8()+t+" "+n[0]}function G8(){if(Wu.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function W8(...n){return process.stderr.write(r_.formatWithOptions(Wu.inspectOpts,...n)+`
|
|
7
|
+
`)}function D8(n){if(n)process.env.DEBUG=n;else delete process.env.DEBUG}function P8(){return process.env.DEBUG}function Y8(n){n.inspectOpts={};let t=Object.keys(Wu.inspectOpts);for(let i=0;i<t.length;i++)n.inspectOpts[t[i]]=Wu.inspectOpts[t[i]]}s_.exports=P0()(Wu);var{formatters:Gu}=s_.exports;Gu.o=function(n){return this.inspectOpts.colors=this.useColors,r_.inspect(n,this.inspectOpts).split(`
|
|
8
|
+
`).map((t)=>t.trim()).join(" ")};Gu.O=function(n){return this.inspectOpts.colors=this.useColors,r_.inspect(n,this.inspectOpts)}});var F0=nn((zx,Y0)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)Y0.exports=Hu();else Y0.exports=Pu()});var mi=nn((D5)=>{var rc;(function(n){n.HEADER="header",n.QUERY="query"})(rc||(rc={}));var sc;(function(n){n.HEADER="header",n.QUERY="query"})(sc||(sc={}));var fc;(function(n){n.HTTP="http",n.HTTPS="https"})(fc||(fc={}));var xs;(function(n){n.MD5="md5",n.CRC32="crc32",n.CRC32C="crc32c",n.SHA1="sha1",n.SHA256="sha256"})(xs||(xs={}));var B5=(n)=>{let t=[];if(n.sha256!==void 0)t.push({algorithmId:()=>xs.SHA256,checksumConstructor:()=>n.sha256});if(n.md5!=null)t.push({algorithmId:()=>xs.MD5,checksumConstructor:()=>n.md5});return{addChecksumAlgorithm(i){t.push(i)},checksumAlgorithms(){return t}}},I5=(n)=>{let t={};return n.checksumAlgorithms().forEach((i)=>{t[i.algorithmId()]=i.checksumConstructor()}),t},H5=(n)=>{return B5(n)},G5=(n)=>{return I5(n)},_c;(function(n){n[n.HEADER=0]="HEADER",n[n.TRAILER=1]="TRAILER"})(_c||(_c={}));var W5="__smithy_context",hc;(function(n){n.PROFILE="profile",n.SSO_SESSION="sso-session",n.SERVICES="services"})(hc||(hc={}));var cc;(function(n){n.HTTP_0_9="http/0.9",n.HTTP_1_0="http/1.0",n.TDS_8_0="tds/8.0"})(cc||(cc={}));D5.AlgorithmId=xs;D5.EndpointURLScheme=fc;D5.FieldPosition=_c;D5.HttpApiKeyAuthLocation=sc;D5.HttpAuthLocation=rc;D5.IniSectionType=hc;D5.RequestHandlerProtocol=cc;D5.SMITHY_CONTEXT_KEY=W5;D5.getDefaultClientConfiguration=H5;D5.resolveDefaultRuntimeConfig=G5});var Dt=nn((Z5)=>{var{SMITHY_CONTEXT_KEY:ey}=mi(),K5=(n)=>n[ey]||(n[ey]={});class e_{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(n){this.method=n.method||"GET",this.hostname=n.hostname||"localhost",this.port=n.port,this.query=n.query||{},this.headers=n.headers||{},this.body=n.body,this.protocol=n.protocol?n.protocol.slice(-1)!==":"?`${n.protocol}:`:n.protocol:"https:",this.path=n.path?n.path.charAt(0)!=="/"?`/${n.path}`:n.path:"/",this.username=n.username,this.password=n.password,this.fragment=n.fragment}static clone(n){let t=new e_({...n,headers:{...n.headers}});if(t.query)t.query=x5(t.query);return t}static isInstance(n){if(!n)return!1;let t=n;return"method"in t&&"protocol"in t&&"hostname"in t&&"path"in t&&typeof t.query==="object"&&typeof t.headers==="object"}clone(){return e_.clone(this)}}function x5(n){return Object.keys(n).reduce((t,i)=>{let r=n[i];return{...t,[i]:Array.isArray(r)?[...r]:r}},{})}class uy{statusCode;reason;headers;body;constructor(n){this.statusCode=n.statusCode,this.reason=n.reason,this.headers=n.headers||{},this.body=n.body}static isInstance(n){if(!n)return!1;let t=n;return typeof t.statusCode==="number"&&typeof t.headers==="object"}}var j5=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),yy=(n,t=!1)=>{if(!t)return j5.test(n);let i=n.split(".");for(let r of i)if(!yy(r))return!1;return!0};function k5(n){return/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/.test(n)}var q5=(n)=>{if(typeof n==="function")return n;let t=Promise.resolve(n);return()=>t};function dy(n){let t={};if(n=n.replace(/^\?/,""),n)for(let i of n.split("&")){let[r,s=null]=i.split("=");if(r=decodeURIComponent(r),s)s=decodeURIComponent(s);if(!(r in t))t[r]=s;else if(Array.isArray(t[r]))t[r].push(s);else t[r]=[t[r],s]}return t}var u_=(n)=>{if(typeof n==="string")return u_(new URL(n));let{hostname:t,pathname:i,port:r,protocol:s,search:f}=n,h;if(f)h=dy(f);return{hostname:t,port:r?parseInt(r):void 0,protocol:s,path:i,query:h}},m5=(n)=>{if(typeof n==="object"){if("url"in n){let t=u_(n.url);if(n.headers){t.headers={};for(let i in n.headers)t.headers[i.toLowerCase()]=n.headers[i].join(", ")}return t}return n}return u_(n)};Z5.HttpRequest=e_;Z5.HttpResponse=uy;Z5.getSmithyContext=K5;Z5.isValidHostLabel=yy;Z5.isValidHostname=k5;Z5.normalizeProvider=q5;Z5.parseQueryString=dy;Z5.parseUrl=u_;Z5.toEndpointV1=m5});var Ei=nn((TS)=>{var{getSmithyContext:Ay,HttpResponse:_S,toEndpointV1:hS}=Dt(),y_=(n)=>{if(typeof n==="function")return n();return n},ec=(n,t,i,r,s)=>({name:t,namespace:n,traits:i,input:r,output:s}),cS=(n)=>(t,i)=>async(r)=>{let{response:s}=await t(r),{operationSchema:f}=Ay(i),[,h,_,c,o,w]=f??[];try{let e=await n.protocol.deserializeResponse(ec(h,_,c,o,w),{...n,...i},s);return{response:s,output:e}}catch(e){if(Object.defineProperty(e,"$response",{value:s,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in e)){try{e.message+=`
|
|
9
|
+
Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(y){if(!i.logger||i.logger?.constructor?.name==="NoOpLogger")console.warn("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.");else i.logger?.warn?.("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.")}if(typeof e.$responseBodyText<"u"){if(e.$response)e.$response.body=e.$responseBodyText}try{if(_S.isInstance(s)){let{headers:y={},statusCode:A}=s,R=Object.entries(y);e.$metadata={httpStatusCode:A,requestId:oc(/^x-[\w-]+-request-?id$/,R),extendedRequestId:oc(/^x-[\w-]+-id-2$/,R),cfId:oc(/^x-[\w-]+-cf-id$/,R)}}}catch(y){}}throw e}},oc=(n,t)=>{return(t.find(([i])=>{return i.match(n)})||[void 0,void 0])[1]},oS=(n)=>(t,i)=>async(r)=>{let{operationSchema:s}=Ay(i),[,f,h,_,c,o]=s??[],w=i.endpointV2?async()=>hS(i.endpointV2):n.endpoint,e=await n.protocol.serializeRequest(ec(f,h,_,c,o),r.input,{...n,...i,endpoint:w});return t({...r,request:e})},Ry={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},My={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function wS(n){return{applyToStack:(t)=>{t.add(oS(n),My),t.add(cS(n),Ry),n.protocol.setSerdeContext(n)}}}class Kn{name;namespace;traits;static assign(n,t){return Object.assign(n,t)}static[Symbol.hasInstance](n){let t=this.prototype.isPrototypeOf(n);if(!t&&typeof n==="object"&&n!==null)return n.symbol===this.symbol;return t}getName(){return this.namespace+"#"+this.name}}class M_ extends Kn{static symbol=Symbol.for("@smithy/lis");name;traits;valueSchema;symbol=M_.symbol}var eS=(n,t,i,r)=>Kn.assign(new M_,{name:t,namespace:n,traits:i,valueSchema:r});class E_ extends Kn{static symbol=Symbol.for("@smithy/map");name;traits;keySchema;valueSchema;symbol=E_.symbol}var uS=(n,t,i,r,s)=>Kn.assign(new E_,{name:t,namespace:n,traits:i,keySchema:r,valueSchema:s});class T_ extends Kn{static symbol=Symbol.for("@smithy/ope");name;traits;input;output;symbol=T_.symbol}var yS=(n,t,i,r,s)=>Kn.assign(new T_,{name:t,namespace:n,traits:i,input:r,output:s});class ms extends Kn{static symbol=Symbol.for("@smithy/str");name;traits;memberNames;memberList;symbol=ms.symbol}var dS=(n,t,i,r,s)=>Kn.assign(new ms,{name:t,namespace:n,traits:i,memberNames:r,memberList:s});class g_ extends ms{static symbol=Symbol.for("@smithy/err");ctor;symbol=g_.symbol}var AS=(n,t,i,r,s,f)=>Kn.assign(new g_,{name:t,namespace:n,traits:i,memberNames:r,memberList:s,ctor:null}),d_=[];function qs(n){if(typeof n==="object")return n;if(n=n|0,d_[n])return d_[n];let t={},i=0;for(let r of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])if((n>>i++&1)===1)t[r]=1;return d_[n]=t}var js={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},A_=[],R_={};class Zt{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=Zt.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(n,t){this.ref=n,this.memberName=t;let i=[],r=n,s=n;this._isMemberSchema=!1;while(wc(r))i.push(r[1]),r=r[0],s=y_(r),this._isMemberSchema=!0;if(i.length>0){this.memberTraits={};for(let f=i.length-1;f>=0;--f){let h=i[f];Object.assign(this.memberTraits,qs(h))}}else this.memberTraits=0;if(s instanceof Zt){let f=this.memberTraits;Object.assign(this,s),this.memberTraits=Object.assign({},f,s.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=t??s.memberName;return}if(this.schema=y_(s),Ey(this.schema))this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3];else this.name=this.memberName??String(s),this.traits=0;if(this._isMemberSchema&&!t)throw Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](n){let t=this.prototype.isPrototypeOf(n);if(!t&&typeof n==="object"&&n!==null)return n.symbol===this.symbol;return t}static of(n){let t=typeof n==="function"||typeof n==="object"&&n!==null;if(typeof n==="number"){if(A_[n])return A_[n]}else if(typeof n==="string"){if(R_[n])return R_[n]}else if(t){if(n[js.ns])return n[js.ns]}let i=y_(n);if(i instanceof Zt)return i;if(wc(i)){let[s,f]=i;if(s instanceof Zt)return Object.assign(s.getMergedTraits(),qs(f)),s;throw Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(n,null,2)}.`)}let r=new Zt(i);if(t)return n[js.ns]=r;if(typeof i==="string")return R_[i]=r;if(typeof i==="number")return A_[i]=r;return r}getSchema(){let n=this.schema;if(Array.isArray(n)&&n[0]===0)return n[4];return n}getName(n=!1){let{name:t}=this;return!n&&t&&t.includes("#")?t.split("#")[1]:t||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){let n=this.getSchema();return typeof n==="number"?n>=64&&n<128:n[0]===1}isMapSchema(){let n=this.getSchema();return typeof n==="number"?n>=128&&n<=255:n[0]===2}isStructSchema(){let n=this.getSchema();if(typeof n!=="object")return!1;let t=n[0];return t===3||t===-3||t===4}isUnionSchema(){let n=this.getSchema();if(typeof n!=="object")return!1;return n[0]===4}isBlobSchema(){let n=this.getSchema();return n===21||n===42}isTimestampSchema(){let n=this.getSchema();return typeof n==="number"&&n>=4&&n<=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(){let{streaming:n}=this.getMergedTraits();return!!n||this.getSchema()===42}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return qs(this.memberTraits)}getOwnTraits(){return qs(this.traits)}getKeySchema(){let[n,t]=[this.isDocumentSchema(),this.isMapSchema()];if(!n&&!t)throw Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);let i=this.getSchema(),r=n?15:i[4]??0;return ks([r,0],"key")}getValueSchema(){let n=this.getSchema(),[t,i,r]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],s=typeof n==="number"?63&n:n&&typeof n==="object"&&(i||r)?n[3+n[0]]:t?15:void 0;if(s!=null)return ks([s,0],i?"value":"member");throw Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(n){let t=this.getSchema();if(this.isStructSchema()&&t[4].includes(n)){let i=t[4].indexOf(n),r=t[5][i];return ks(wc(r)?r:[r,0],n)}if(this.isDocumentSchema())return ks([15,0],n);throw Error(`@smithy/core/schema - ${this.getName(!0)} has no member=${n}.`)}getMemberSchemas(){let n={};try{for(let[t,i]of this.structIterator())n[t]=i}catch(t){}return n}getEventStreamMember(){if(this.isStructSchema()){for(let[n,t]of this.structIterator())if(t.isStreaming()&&t.isStructSchema())return n}return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw Error("@smithy/core/schema - cannot iterate non-struct schema.");let n=this.getSchema(),t=n[4].length,i=n[js.it];if(i&&t===i.length){yield*i;return}i=Array(t);for(let r=0;r<t;++r){let s=n[4][r],f=ks([n[5][r],0],s);yield i[r]=[s,f]}n[js.it]=i}}function ks(n,t){if(n instanceof Zt)return Object.assign(n,{memberName:t,_isMemberSchema:!0});return new Zt(n,t)}var wc=(n)=>Array.isArray(n)&&n.length===2,Ey=(n)=>Array.isArray(n)&&n.length>=5;class Zs extends Kn{static symbol=Symbol.for("@smithy/sim");name;schemaRef;traits;symbol=Zs.symbol}var RS=(n,t,i,r)=>Kn.assign(new Zs,{name:t,namespace:n,traits:r,schemaRef:i}),MS=(n,t,i,r)=>Kn.assign(new Zs,{name:t,namespace:n,traits:i,schemaRef:r}),ES={BLOB:21,STREAMING_BLOB:42,BOOLEAN:2,STRING:0,NUMERIC:1,BIG_INTEGER:17,BIG_DECIMAL:19,DOCUMENT:15,TIMESTAMP_DEFAULT:4,TIMESTAMP_DATE_TIME:5,TIMESTAMP_HTTP_DATE:6,TIMESTAMP_EPOCH_SECONDS:7,LIST_MODIFIER:64,MAP_MODIFIER:128};class mt{namespace;schemas;exceptions;static registries=new Map;constructor(n,t=new Map,i=new Map){this.namespace=n,this.schemas=t,this.exceptions=i}static for(n){if(!mt.registries.has(n))mt.registries.set(n,new mt(n));return mt.registries.get(n)}copyFrom(n){let{schemas:t,exceptions:i}=this;for(let[r,s]of n.schemas)if(!t.has(r))t.set(r,s);for(let[r,s]of n.exceptions)if(!i.has(r))i.set(r,s)}register(n,t){let i=this.normalizeShapeId(n);for(let r of[this,mt.for(i.split("#")[0])])r.schemas.set(i,t)}getSchema(n){let t=this.normalizeShapeId(n);if(!this.schemas.has(t)){if(!n.includes("#")){let i="#"+n,r=[];for(let[s,f]of this.schemas.entries())if(s.endsWith(i))r.push(f);if(r.length===1)return r[0]}throw Error(`@smithy/core/schema - schema not found for ${t}`)}return this.schemas.get(t)}registerError(n,t){let i=n,r=i[1];for(let s of[this,mt.for(r)])s.schemas.set(r+"#"+i[2],i),s.exceptions.set(i,t)}getErrorCtor(n){let t=n;if(this.exceptions.has(t))return this.exceptions.get(t);return mt.for(t[1]).exceptions.get(t)}getBaseException(){for(let n of this.exceptions.keys())if(Array.isArray(n)){let[,t,i]=n,r=t+"#"+i;if(r.startsWith("smithy.ts.sdk.synthetic.")&&r.endsWith("ServiceException"))return n}return}find(n){for(let t of this.schemas.values())if(n(t))return t;return}clear(){this.schemas.clear(),this.exceptions.clear()}normalizeShapeId(n){if(n.includes("#"))return n;return this.namespace+"#"+n}}TS.ErrorSchema=g_;TS.ListSchema=M_;TS.MapSchema=E_;TS.NormalizedSchema=Zt;TS.OperationSchema=T_;TS.SCHEMA=ES;TS.Schema=Kn;TS.SimpleSchema=Zs;TS.StructureSchema=ms;TS.TypeRegistry=mt;TS.deref=y_;TS.deserializerMiddlewareOption=Ry;TS.error=AS;TS.getSchemaSerdePlugin=wS;TS.isStaticSchema=Ey;TS.list=eS;TS.map=uS;TS.op=yS;TS.operation=ec;TS.serializerMiddlewareOption=My;TS.sim=RS;TS.simAdapter=MS;TS.simpleSchemaCacheN=A_;TS.simpleSchemaCacheS=R_;TS.struct=dS;TS.traitsCache=d_;TS.translateTraits=qs});var at=nn((bL)=>{var{getSmithyContext:kS,normalizeProvider:qS}=Dt();bL.getSmithyContext=kS;bL.normalizeProvider=qS;var{SMITHY_CONTEXT_KEY:mS,AlgorithmId:L_}=mi();bL.AlgorithmId=L_;var{NormalizedSchema:ZS}=Ei(),Zi=(n,t)=>{let i=[];if(n)i.push(n);if(t)for(let r of t)i.push(r);return i},Ti=(n,t)=>{return`${n||"anonymous"}${t&&t.length>0?` (a.k.a. ${t.join(",")})`:""}`},as=()=>{let n=[],t=[],i=!1,r=new Set,s=(e)=>e.sort((u,y)=>Ty[y.step]-Ty[u.step]||gy[y.priority||"normal"]-gy[u.priority||"normal"]),f=(e)=>{let u=!1,y=(A)=>{let R=Zi(A.name,A.aliases);if(R.includes(e)){u=!0;for(let M of R)r.delete(M);return!1}return!0};return n=n.filter(y),t=t.filter(y),u},h=(e)=>{let u=!1,y=(A)=>{if(A.middleware===e){u=!0;for(let R of Zi(A.name,A.aliases))r.delete(R);return!1}return!0};return n=n.filter(y),t=t.filter(y),u},_=(e)=>{return n.forEach((u)=>{e.add(u.middleware,{...u})}),t.forEach((u)=>{e.addRelativeTo(u.middleware,{...u})}),e.identifyOnResolve?.(w.identifyOnResolve()),e},c=(e)=>{let u=[];return e.before.forEach((y)=>{if(y.before.length===0&&y.after.length===0)u.push(y);else u.push(...c(y))}),u.push(e),e.after.reverse().forEach((y)=>{if(y.before.length===0&&y.after.length===0)u.push(y);else u.push(...c(y))}),u},o=(e=!1)=>{let u=[],y=[],A={};return n.forEach((M)=>{let E={...M,before:[],after:[]};for(let g of Zi(E.name,E.aliases))A[g]=E;u.push(E)}),t.forEach((M)=>{let E={...M,before:[],after:[]};for(let g of Zi(E.name,E.aliases))A[g]=E;y.push(E)}),y.forEach((M)=>{if(M.toMiddleware){let E=A[M.toMiddleware];if(E===void 0){if(e)return;throw Error(`${M.toMiddleware} is not found when adding ${Ti(M.name,M.aliases)} middleware ${M.relation} ${M.toMiddleware}`)}if(M.relation==="after")E.after.push(M);if(M.relation==="before")E.before.push(M)}}),s(u).map(c).reduce((M,E)=>{return M.push(...E),M},[])},w={add:(e,u={})=>{let{name:y,override:A,aliases:R}=u,M={step:"initialize",priority:"normal",middleware:e,...u},E=Zi(y,R);if(E.length>0){if(E.some((g)=>r.has(g))){if(!A)throw Error(`Duplicate middleware name '${Ti(y,R)}'`);for(let g of E){let T=n.findIndex((L)=>L.name===g||L.aliases?.some((b)=>b===g));if(T===-1)continue;let S=n[T];if(S.step!==M.step||M.priority!==S.priority)throw Error(`"${Ti(S.name,S.aliases)}" middleware with ${S.priority} priority in ${S.step} step cannot be overridden by "${Ti(y,R)}" middleware with ${M.priority} priority in ${M.step} step.`);n.splice(T,1)}}for(let g of E)r.add(g)}n.push(M)},addRelativeTo:(e,u)=>{let{name:y,override:A,aliases:R}=u,M={middleware:e,...u},E=Zi(y,R);if(E.length>0){if(E.some((g)=>r.has(g))){if(!A)throw Error(`Duplicate middleware name '${Ti(y,R)}'`);for(let g of E){let T=t.findIndex((L)=>L.name===g||L.aliases?.some((b)=>b===g));if(T===-1)continue;let S=t[T];if(S.toMiddleware!==M.toMiddleware||S.relation!==M.relation)throw Error(`"${Ti(S.name,S.aliases)}" middleware ${S.relation} "${S.toMiddleware}" middleware cannot be overridden by "${Ti(y,R)}" middleware ${M.relation} "${M.toMiddleware}" middleware.`);t.splice(T,1)}}for(let g of E)r.add(g)}t.push(M)},clone:()=>_(as()),use:(e)=>{e.applyToStack(w)},remove:(e)=>{if(typeof e==="string")return f(e);else return h(e)},removeByTag:(e)=>{let u=!1,y=(A)=>{let{tags:R,name:M,aliases:E}=A;if(R&&R.includes(e)){let g=Zi(M,E);for(let T of g)r.delete(T);return u=!0,!1}return!0};return n=n.filter(y),t=t.filter(y),u},concat:(e)=>{let u=_(as());return u.use(e),u.identifyOnResolve(i||u.identifyOnResolve()||(e.identifyOnResolve?.()??!1)),u},applyToStack:_,identify:()=>{return o(!0).map((e)=>{let u=e.step??e.relation+" "+e.toMiddleware;return Ti(e.name,e.aliases)+" - "+u})},identifyOnResolve(e){if(typeof e==="boolean")i=e;return i},resolve:(e,u)=>{for(let y of o().map((A)=>A.middleware).reverse())e=y(e,u);if(i)console.log(w.identify());return e}};return w},Ty={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},gy={high:3,normal:2,low:1},aS=(n)=>()=>{throw Error(n)},vS=(n)=>()=>Promise.reject(n),S_=()=>{let n=new WeakSet;return(t,i)=>{if(typeof i==="object"&&i!==null){if(n.has(i))return"[Circular]";n.add(i)}return i}},pS=(n)=>{return new Promise((t)=>setTimeout(t,n*1000))},$y={minDelay:2,maxDelay:120},Pt;(function(n){n.ABORTED="ABORTED",n.FAILURE="FAILURE",n.SUCCESS="SUCCESS",n.RETRY="RETRY",n.TIMEOUT="TIMEOUT"})(Pt||(Pt={}));var nL=(n)=>{if(n.state===Pt.ABORTED){let t=Error(`${JSON.stringify({...n,reason:"Request was aborted"},S_())}`);throw t.name="AbortError",t}else if(n.state===Pt.TIMEOUT){let t=Error(`${JSON.stringify({...n,reason:"Waiter has timed out"},S_())}`);throw t.name="TimeoutError",t}else if(n.state!==Pt.SUCCESS)throw Error(`${JSON.stringify(n,S_())}`);return n},tL=async({minDelay:n,maxDelay:t,maxWaitTime:i,abortController:r,client:s,abortSignal:f},h,_)=>{let c={},[o,w]=[n*1000,t*1000],e=0,u=Date.now()+i*1000,y=Date.now()+60000,A=!1;while(!0){if(e>0){let E=sL(o,w,e,u);if(r?.signal?.aborted||f?.aborted)return c["AbortController signal aborted."]|=0,c["AbortController signal aborted."]+=1,{state:Pt.ABORTED,observedResponses:c};if(Date.now()+E>u)return{state:Pt.TIMEOUT,observedResponses:c};await pS(E/1000)}let{state:R,reason:M}=await _(s,h);if(M){let E=rL(M);c[E]|=0,c[E]+=1}if(R!==Pt.RETRY)return{state:R,reason:M,final:M,observedResponses:c};if(e+=1,!A&&Date.now()>=y)iL(c,s),A=!0}},iL=(n={},t)=>{let i=Object.keys(n),r=0;for(let h of i){let _=n[h]|0;if(h.startsWith("403:"))r+=_}let s=t?.config?.logger,f=typeof s?.warn==="function"&&!s.constructor?.name?.includes?.("NoOpLogger")?s:console;if(r>=3||i[i.length-1]?.startsWith("403:"))f.warn("@smithy/util-waiter WARN - 403 status code encountered during waiter polling.")},rL=(n)=>{let t=n?.$response?.statusCode??n?.$metadata?.httpStatusCode;if(n?.$responseBodyText)return`${t?t+": ":""}Deserialization error for body: ${n.$responseBodyText}`;if(t){if(n?.$response||n?.message)return`${t??"Unknown"}: ${n?.message}`;return`${t}: OK`}return String(n?.message??JSON.stringify(n,S_())??"Unknown")},sL=(n,t,i,r)=>{let s=Math.log(t/n)/Math.log(2)+1;if(i>s)return t;let f=n*2**(i-1),h=Math.min(f,t),_=fL(n,h);if(Date.now()+_>r){let c=r-Date.now();return Math.max(0,c-500)}return _},fL=(n,t)=>n+Math.random()*(t-n),_L=(n)=>{if(n.maxWaitTime<=0)throw Error("WaiterConfiguration.maxWaitTime must be greater than 0");else if(n.minDelay<=0)throw Error("WaiterConfiguration.minDelay must be greater than 0");else if(n.maxDelay<=0)throw Error("WaiterConfiguration.maxDelay must be greater than 0");else if(n.maxWaitTime<=n.minDelay)throw Error(`WaiterConfiguration.maxWaitTime [${n.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${n.minDelay}] for this waiter`);else if(n.maxDelay<n.minDelay)throw Error(`WaiterConfiguration.maxDelay [${n.maxDelay}] must be greater than WaiterConfiguration.minDelay [${n.minDelay}] for this waiter`)},Sy=(n)=>{let t,i=new Promise((r)=>{if(t=()=>r({state:Pt.ABORTED}),typeof n.addEventListener==="function")n.addEventListener("abort",t);else n.onabort=t});return{clearListener(){if(typeof n.removeEventListener==="function")n.removeEventListener("abort",t)},aborted:i}},hL=async(n,t,i)=>{let r={...$y,...n};_L(r);let s=[tL(r,t,i)],f=[];if(n.abortSignal){let{aborted:h,clearListener:_}=Sy(n.abortSignal);f.push(_),s.push(h)}if(n.abortController?.signal){let{aborted:h,clearListener:_}=Sy(n.abortController.signal);f.push(_),s.push(h)}return Promise.race(s).then((h)=>{for(let _ of f)_();return h})};class Oy{config;middlewareStack=as();initConfig;handlers;constructor(n){this.config=n;let{protocol:t,protocolSettings:i}=n;if(i){if(typeof t==="function")n.protocol=new t(i)}}send(n,t,i){let r=typeof t!=="function"?t:void 0,s=typeof t==="function"?t:i,f=r===void 0&&this.config.cacheMiddleware===!0,h;if(f){if(!this.handlers)this.handlers=new WeakMap;let _=this.handlers;if(_.has(n.constructor))h=_.get(n.constructor);else h=n.resolveMiddleware(this.middlewareStack,this.config,r),_.set(n.constructor,h)}else delete this.handlers,h=n.resolveMiddleware(this.middlewareStack,this.config,r);if(s)h(n).then((_)=>s(null,_.output),(_)=>s(_)).catch(()=>{});else return h(n).then((_)=>_.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}var uc="***SensitiveInformation***";function $_(n,t){if(t==null)return t;let i=ZS.of(n);if(i.getMergedTraits().sensitive)return uc;if(i.isListSchema()){if(!!i.getValueSchema().getMergedTraits().sensitive)return uc}else if(i.isMapSchema()){if(!!i.getKeySchema().getMergedTraits().sensitive||!!i.getValueSchema().getMergedTraits().sensitive)return uc}else if(i.isStructSchema()&&typeof t==="object"){let r=t,s={};for(let[f,h]of i.structIterator())if(r[f]!=null)s[f]=$_(h,r[f]);return s}return t}class O_{middlewareStack=as();schema;static classBuilder(){return new Uy}resolveMiddlewareWithContext(n,t,i,{middlewareFn:r,clientName:s,commandName:f,inputFilterSensitiveLog:h,outputFilterSensitiveLog:_,smithyContext:c,additionalContext:o,CommandCtor:w}){for(let M of r.bind(this)(w,n,t,i))this.middlewareStack.use(M);let e=n.concat(this.middlewareStack),{logger:u}=t,y={logger:u,clientName:s,commandName:f,inputFilterSensitiveLog:h,outputFilterSensitiveLog:_,[mS]:{commandInstance:this,...c},...o},{requestHandler:A}=t,R=i??{};if(c.eventStream)R={isEventStream:!0,...R};return e.resolve((M)=>A.handle(M.request,R),y)}}class Uy{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(n){this._init=n}ep(n){return this._ep=n,this}m(n){return this._middlewareFn=n,this}s(n,t,i={}){return this._smithyContext={service:n,operation:t,...i},this}c(n={}){return this._additionalContext=n,this}n(n,t){return this._clientName=n,this._commandName=t,this}f(n=(i)=>i,t=(i)=>i){return this._inputFilterSensitiveLog=n,this._outputFilterSensitiveLog=t,this}ser(n){return this._serializer=n,this}de(n){return this._deserializer=n,this}sc(n){return this._operationSchema=n,this._smithyContext.operationSchema=n,this}build(){let n=this,t;return t=class extends O_{input;static getEndpointParameterInstructions(){return n._ep}constructor(...[i]){super();this.input=i??{},n._init(this),this.schema=n._operationSchema}resolveMiddleware(i,r,s){let f=n._operationSchema,h=f?.[4]??f?.input,_=f?.[5]??f?.output;return this.resolveMiddlewareWithContext(i,r,s,{CommandCtor:t,middlewareFn:n._middlewareFn,clientName:n._clientName,commandName:n._commandName,inputFilterSensitiveLog:n._inputFilterSensitiveLog??(f?$_.bind(null,h):(c)=>c),outputFilterSensitiveLog:n._outputFilterSensitiveLog??(f?$_.bind(null,_):(c)=>c),smithyContext:n._smithyContext,additionalContext:n._additionalContext})}serialize=n._serializer;deserialize=n._deserializer}}}var cL="***SensitiveInformation***",oL=(n,t,i)=>{for(let[f,h]of Object.entries(n)){let _=async function(o,w,e){let u=new h(o);if(typeof w==="function")this.send(u,w);else if(typeof e==="function"){if(typeof w!=="object")throw Error(`Expected http options but got ${typeof w}`);this.send(u,w||{},e)}else return this.send(u,w)},c=(f[0].toLowerCase()+f.slice(1)).replace(/Command$/,"");t.prototype[c]=_}let{paginators:r={},waiters:s={}}=i??{};for(let[f,h]of Object.entries(r))if(t.prototype[f]===void 0)t.prototype[f]=function(_={},c,...o){return h({...c,client:this},_,...o)};for(let[f,h]of Object.entries(s))if(t.prototype[f]===void 0)t.prototype[f]=async function(_={},c,...o){let w=c;if(typeof c==="number")w={maxWaitTime:c};return h({...w,client:this},_,...o)}};class Cr extends Error{$fault;$response;$retryable;$metadata;constructor(n){super(n.message);Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=n.name,this.$fault=n.$fault,this.$metadata=n.$metadata}static isInstance(n){if(!n)return!1;let t=n;return Cr.prototype.isPrototypeOf(t)||Boolean(t.$fault)&&Boolean(t.$metadata)&&(t.$fault==="client"||t.$fault==="server")}static[Symbol.hasInstance](n){if(!n)return!1;let t=n;if(this===Cr)return Cr.isInstance(n);if(Cr.isInstance(n)){if(t.name&&this.name)return this.prototype.isPrototypeOf(n)||t.name===this.name;return this.prototype.isPrototypeOf(n)}return!1}}var by=(n,t={})=>{Object.entries(t).filter(([,r])=>r!==void 0).forEach(([r,s])=>{if(n[r]==null||n[r]==="")n[r]=s});let i=n.message||n.Message||"UnknownError";return n.message=i,delete n.Message,n},Ny=({output:n,parsedBody:t,exceptionCtor:i,errorCode:r})=>{let s=eL(n),f=s.httpStatusCode?s.httpStatusCode+"":void 0,h=new i({name:t?.code||t?.Code||r||f||"UnknownError",$fault:"client",$metadata:s});throw by(h,t)},wL=(n)=>{return({output:t,parsedBody:i,errorCode:r})=>{Ny({output:t,parsedBody:i,exceptionCtor:n,errorCode:r})}},eL=(n)=>({httpStatusCode:n.statusCode,requestId:n.headers["x-amzn-requestid"]??n.headers["x-amzn-request-id"]??n.headers["x-amz-request-id"],extendedRequestId:n.headers["x-amz-id-2"],cfId:n.headers["x-amz-cf-id"]}),uL=(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:30000};default:return{}}},Ly=!1,yL=(n)=>{if(n&&!Ly&&parseInt(n.substring(1,n.indexOf(".")))<16)Ly=!0},By=Object.values(L_),Iy=(n)=>{let t=[];for(let i in L_){let r=L_[i];if(n[r]===void 0)continue;t.push({algorithmId:()=>r,checksumConstructor:()=>n[r]})}for(let[i,r]of Object.entries(n.checksumAlgorithms??{}))t.push({algorithmId:()=>i,checksumConstructor:()=>r});return{addChecksumAlgorithm(i){n.checksumAlgorithms=n.checksumAlgorithms??{};let r=i.algorithmId(),s=i.checksumConstructor();if(By.includes(r))n.checksumAlgorithms[r.toUpperCase()]=s;else n.checksumAlgorithms[r]=s;t.push(i)},checksumAlgorithms(){return t}}},Hy=(n)=>{let t={};return n.checksumAlgorithms().forEach((i)=>{let r=i.algorithmId();if(By.includes(r))t[r]=i.checksumConstructor()}),t},Gy=(n)=>{return{setRetryStrategy(t){n.retryStrategy=t},retryStrategy(){return n.retryStrategy}}},Wy=(n)=>{let t={};return t.retryStrategy=n.retryStrategy(),t},Dy=(n)=>{return Object.assign(Iy(n),Gy(n))},dL=Dy,AL=(n)=>{return Object.assign(Hy(n),Wy(n))},RL=(n)=>Array.isArray(n)?n:[n],Py=(n)=>{for(let i in n)if(Object.prototype.hasOwnProperty.call(n,i)&&n[i]["#text"]!==void 0)n[i]=n[i]["#text"];else if(typeof n[i]==="object"&&n[i]!==null)n[i]=Py(n[i]);return n},ML=(n)=>{return n!=null};class Yy{trace(){}debug(){}info(){}warn(){}error(){}}function Fy(n,t,i){let r,s,f;if(typeof t>"u"&&typeof i>"u")r={},f=n;else if(r=n,typeof t==="function")return s=t,f=i,gL(r,s,f);else f=t;for(let h of Object.keys(f)){if(!Array.isArray(f[h])){r[h]=f[h];continue}Xy(r,null,f,h)}return r}var EL=(n)=>{let t={};for(let[i,r]of Object.entries(n||{}))t[i]=[,r];return t},TL=(n,t)=>{let i={};for(let r in t)Xy(i,n,t,r);return i},gL=(n,t,i)=>{return Fy(n,Object.entries(i).reduce((r,[s,f])=>{if(Array.isArray(f))r[s]=f;else if(typeof f==="function")r[s]=[t,f()];else r[s]=[t,f];return r},{}))},Xy=(n,t,i,r)=>{if(t!==null){let h=i[r];if(typeof h==="function")h=[,h];let[_=SL,c=LL,o=r]=h;if(typeof _==="function"&&_(t[o])||typeof _!=="function"&&!!_)n[r]=c(t[o]);return}let[s,f]=i[r];if(typeof f==="function"){let h,_=s===void 0&&(h=f())!=null,c=typeof s==="function"&&!!s(void 0)||typeof s!=="function"&&!!s;if(_)n[r]=h;else if(c)n[r]=f()}else{let h=s===void 0&&f!=null,_=typeof s==="function"&&!!s(f)||typeof s!=="function"&&!!s;if(h||_)n[r]=f}},SL=(n)=>n!=null,LL=(n)=>n,$L=(n)=>{if(n!==n)return"NaN";switch(n){case 1/0:return"Infinity";case-1/0:return"-Infinity";default:return n}},OL=(n)=>n.toISOString().replace(".000Z","Z"),yc=(n)=>{if(n==null)return{};if(Array.isArray(n))return n.filter((t)=>t!=null).map(yc);if(typeof n==="object"){let t={};for(let i of Object.keys(n)){if(n[i]==null)continue;t[i]=yc(n[i])}return t}return n};function UL(n,t,i,r){return function(f,h,_,c,o={}){let w=Object.assign({},n,f);return O_.classBuilder().ep(w).m(function(e,u,y,A){let R=h.call(this,e,u,y,A);return R.unshift(r(y,e.getEndpointParameterInstructions())),R}).s(t,_,o).n(i,_.charAt(0).toUpperCase()+_.slice(1)+"Command").sc(c).build()}}bL.Client=Oy;bL.Command=O_;bL.NoOpLogger=Yy;bL.SENSITIVE_STRING=cL;bL.ServiceException=Cr;bL.WaiterState=Pt;bL._json=yc;bL.checkExceptions=nL;bL.constructStack=as;bL.convertMap=EL;bL.createAggregatedClient=oL;bL.createWaiter=hL;bL.decorateServiceException=by;bL.emitWarningIfUnsupportedVersion=yL;bL.getArrayIfSingleItem=RL;bL.getChecksumConfiguration=Iy;bL.getDefaultClientConfiguration=dL;bL.getDefaultExtensionConfiguration=Dy;bL.getRetryConfiguration=Gy;bL.getValueFromTextNode=Py;bL.invalidFunction=aS;bL.invalidProvider=vS;bL.isSerializableHeaderValue=ML;bL.loadConfigsForDefaultMode=uL;bL.makeBuilder=UL;bL.map=Fy;bL.resolveChecksumRuntimeConfig=Hy;bL.resolveDefaultRuntimeConfig=AL;bL.resolveRetryRuntimeConfig=Wy;bL.schemaLogFilter=$_;bL.serializeDateTime=OL;bL.serializeFloat=$L;bL.take=TL;bL.throwDefaultError=Ny;bL.waiterServiceDefaults=$y;bL.withBaseException=wL});var xn=nn((uO)=>{var{homedir:u$}=cn("os"),{sep:y$,join:vs}=cn("path"),{createHash:d$}=cn("crypto"),{readFile:jy}=cn("fs/promises"),{IniSectionType:U_}=mi(),{normalizeProvider:b_}=at(),{isValidHostLabel:A$}=Dt();class Vr extends Error{name="ProviderError";tryNextLink;constructor(n,t=!0){let i,r=!0;if(typeof t==="boolean")i=void 0,r=t;else if(t!=null&&typeof t==="object")i=t.logger,r=t.tryNextLink??!0;super(n);this.tryNextLink=r,Object.setPrototypeOf(this,Vr.prototype),i?.debug?.(`@smithy/property-provider ${r?"->":"(!)"} ${n}`)}static from(n,t=!0){return Object.assign(new this(n.message,t),n)}}class ps extends Vr{name="CredentialsProviderError";constructor(n,t=!0){super(n,t);Object.setPrototypeOf(this,ps.prototype)}}class Ec extends Vr{name="TokenProviderError";constructor(n,t=!0){super(n,t);Object.setPrototypeOf(this,Ec.prototype)}}var ky=(...n)=>async()=>{if(n.length===0)throw new Vr("No providers in chain");let t;for(let i of n)try{return await i()}catch(r){if(t=r,r?.tryNextLink)continue;throw r}throw t},qy=(n)=>()=>Promise.resolve(n),Tc=(n,t,i)=>{let r,s,f,h=!1,_=async()=>{if(!s)s=n();try{r=await s,f=!0,h=!1}finally{s=void 0}return r};if(t===void 0)return async(c)=>{if(!f||c?.forceRefresh)r=await _();return r};return async(c)=>{if(!f||c?.forceRefresh)r=await _();if(h)return r;if(i&&!i(r))return h=!0,r;if(t(r))return await _(),r;return r}},vt=(n,t,i)=>{if(!(t in n))return;if(n[t]==="true")return!0;if(n[t]==="false")return!1;throw Error(`Cannot load ${i} "${t}". Expected "true" or "false", got ${n[t]}.`)},R$=(n,t,i)=>{if(!(t in n))return;let r=parseInt(n[t],10);if(Number.isNaN(r))throw TypeError(`Cannot load ${i} '${t}'. Expected number, got '${n[t]}'.`);return r},Tt;(function(n){n.ENV="env",n.CONFIG="shared config entry"})(Tt||(Tt={}));var dc={},M$=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},nf=()=>{let{HOME:n,USERPROFILE:t,HOMEPATH:i,HOMEDRIVE:r=`C:${y$}`}=process.env;if(n)return n;if(t)return t;if(i)return`${r}${i}`;let s=M$();if(!dc[s])dc[s]=u$();return dc[s]},my="AWS_PROFILE",Zy="default",ay=(n)=>n.profile||process.env[my]||Zy,vy=(n)=>{let i=d$("sha1").update(n).digest("hex");return vs(nf(),".aws","sso","cache",`${i}.json`)},N_={},E$=async(n)=>{if(N_[n])return N_[n];let t=vy(n),i=await jy(t,"utf8");return JSON.parse(i)},ai=".",T$=(n)=>Object.entries(n).filter(([t])=>{let i=t.indexOf(ai);if(i===-1)return!1;return Object.values(U_).includes(t.substring(0,i))}).reduce((t,[i,r])=>{let s=i.indexOf(ai),f=i.substring(0,s)===U_.PROFILE?i.substring(s+1):i;return t[f]=r,t},{...n.default&&{default:n.default}}),g$="AWS_CONFIG_FILE",py=()=>process.env[g$]||vs(nf(),".aws","config"),S$="AWS_SHARED_CREDENTIALS_FILE",L$=()=>process.env[S$]||vs(nf(),".aws","credentials"),$$=/^([\w-]+)\s(["'])?([\w-@+.%:/]+)\2$/,O$=["__proto__","profile __proto__"],Rc=(n)=>{let t={},i,r;for(let s of n.split(/\r?\n/)){let f=s.split(/(^|\s)[;#]/)[0].trim();if(f[0]==="["&&f[f.length-1]==="]"){i=void 0,r=void 0;let _=f.substring(1,f.length-1),c=$$.exec(_);if(c){let[,o,,w]=c;if(Object.values(U_).includes(o))i=[o,w].join(ai)}else i=_;if(O$.includes(_))throw Error(`Found invalid profile name "${_}"`)}else if(i){let _=f.indexOf("=");if(![0,-1].includes(_)){let[c,o]=[f.substring(0,_).trim(),f.substring(_+1).trim()];if(o==="")r=c;else{if(r&&s.trimStart()===s)r=void 0;t[i]=t[i]||{};let w=r?[r,c].join(ai):c;t[i][w]=o}}}}return t},Ac={},B_={},I_=(n,t)=>{if(B_[n]!==void 0)return B_[n];if(!Ac[n]||t?.ignoreCache)Ac[n]=jy(n,"utf8");return Ac[n]},ly=()=>({}),gc=async(n={})=>{let{filepath:t=L$(),configFilepath:i=py()}=n,r=nf(),s="~/",f=t;if(t.startsWith("~/"))f=vs(r,t.slice(2));let h=i;if(i.startsWith("~/"))h=vs(r,i.slice(2));let _=await Promise.all([I_(h,{ignoreCache:n.ignoreCache}).then(Rc).then(T$).catch(ly),I_(f,{ignoreCache:n.ignoreCache}).then(Rc).catch(ly)]);return{configFile:_[0],credentialsFile:_[1]}},U$=(n)=>Object.entries(n).filter(([t])=>t.startsWith(U_.SSO_SESSION+ai)).reduce((t,[i,r])=>({...t,[i.substring(i.indexOf(ai)+1)]:r}),{}),b$=()=>({}),N$=async(n={})=>I_(n.configFilepath??py()).then(Rc).then(U$).catch(b$),B$=(...n)=>{let t={};for(let i of n)for(let[r,s]of Object.entries(i))if(t[r]!==void 0)Object.assign(t[r],s);else t[r]=s;return t},I$=async(n)=>{let t=await gc(n);return B$(t.configFile,t.credentialsFile)},H$={getFileRecord(){return B_},interceptFile(n,t){B_[n]=Promise.resolve(t)},getTokenRecord(){return N_},interceptToken(n,t){N_[n]=t}};function nd(n){try{let t=new Set(Array.from(n.match(/([A-Z_]){3,}/g)??[]));return t.delete("CONFIG"),t.delete("CONFIG_PREFIX_SEPARATOR"),t.delete("ENV"),[...t].join(", ")}catch(t){return n}}var G$=(n,t)=>async()=>{try{let i=n(process.env,t);if(i===void 0)throw Error();return i}catch(i){throw new ps(i.message||`Not found in ENV: ${nd(n.toString())}`,{logger:t?.logger})}},W$=(n,{preferredFile:t="config",...i}={})=>async()=>{let r=ay(i),{configFile:s,credentialsFile:f}=await gc(i),h=f[r]||{},_=s[r]||{},c=t==="config"?{...h,..._}:{..._,...h};try{let w=n(c,t==="config"?s:f);if(w===void 0)throw Error();return w}catch(o){throw new ps(o.message||`Not found in config files w/ profile [${r}]: ${nd(n.toString())}`,{logger:i.logger})}},D$=(n)=>typeof n==="function",td=(n)=>D$(n)?async()=>await n():qy(n),Mc=({environmentVariableSelector:n,configFileSelector:t,default:i},r={})=>{let{signingName:s,logger:f}=r;return Tc(ky(G$(n,{signingName:s,logger:f}),W$(t,r),td(i)))},Sc="AWS_USE_DUALSTACK_ENDPOINT",Lc="use_dualstack_endpoint",P$=!1,Y$={environmentVariableSelector:(n)=>vt(n,Sc,Tt.ENV),configFileSelector:(n)=>vt(n,Lc,Tt.CONFIG),default:!1},F$={environmentVariableSelector:(n)=>vt(n,Sc,Tt.ENV),configFileSelector:(n)=>vt(n,Lc,Tt.CONFIG),default:void 0},$c="AWS_USE_FIPS_ENDPOINT",Oc="use_fips_endpoint",X$=!1,l$={environmentVariableSelector:(n)=>vt(n,$c,Tt.ENV),configFileSelector:(n)=>vt(n,Oc,Tt.CONFIG),default:!1},J$={environmentVariableSelector:(n)=>vt(n,$c,Tt.ENV),configFileSelector:(n)=>vt(n,Oc,Tt.CONFIG),default:void 0},Q$=(n)=>{let{tls:t,endpoint:i,urlParser:r,useDualstackEndpoint:s}=n;return Object.assign(n,{tls:t??!0,endpoint:b_(typeof i==="string"?r(i):i),isCustomEndpoint:!0,useDualstackEndpoint:b_(s??!1)})},z$=async(n)=>{let{tls:t=!0}=n,i=await n.region();if(!new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/).test(i))throw Error("Invalid region in client config");let s=await n.useDualstackEndpoint(),f=await n.useFipsEndpoint(),{hostname:h}=await n.regionInfoProvider(i,{useDualstackEndpoint:s,useFipsEndpoint:f})??{};if(!h)throw Error("Cannot resolve hostname from client config");return n.urlParser(`${t?"https:":"http:"}//${h}`)},C$=(n)=>{let t=b_(n.useDualstackEndpoint??!1),{endpoint:i,useFipsEndpoint:r,urlParser:s,tls:f}=n;return Object.assign(n,{tls:f??!0,endpoint:i?b_(typeof i==="string"?s(i):i):()=>z$({...n,useDualstackEndpoint:t,useFipsEndpoint:r}),isCustomEndpoint:!!i,useDualstackEndpoint:t})},V$="AWS_EXECUTION_ENV",Jy="AWS_REGION",Qy="AWS_DEFAULT_REGION",K$="AWS_EC2_METADATA_DISABLED",x$=["in-region","cross-region","mobile","standard","legacy"],j$="/latest/meta-data/placement/region",k$="/latest/api/token",q$="x-aws-ec2-metadata-token",m$="x-aws-ec2-metadata-token-ttl-seconds",zy=1000,Z$=60000,id=0,rd=async()=>{if(process.env[K$])return;if(Date.now()<id)return;try{let n=a$(),t=(await Vy({...n,path:k$,method:"PUT",headers:{[m$]:"21600"}})).toString();return(await Vy({...n,path:j$,method:"GET",headers:{[q$]:t}})).toString().trim()||Cy()}catch{return Cy()}},Cy=()=>{id=Date.now()+Z$;return},a$=()=>{let n=process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT;if(n){let t=new URL(n);return{hostname:t.hostname.replace(/^\[(.+)]$/,"$1"),port:t.port?Number(t.port):void 0}}if(process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE==="IPv6")return{hostname:"fd00:ec2::254"};return{hostname:"169.254.169.254"}},Vy=async(n)=>{let{request:t}=cn("http");return new Promise((i,r)=>{let s=t({hostname:n.hostname,port:n.port,path:n.path,method:n.method,headers:n.headers,timeout:zy,signal:AbortSignal.timeout(zy)});s.on("error",(f)=>{r(f),s.destroy()}),s.on("timeout",()=>{r(Error("TimeoutError from instance metadata service")),s.destroy()}),s.on("response",(f)=>{let{statusCode:h=400}=f;if(h<200||h>=300){r(Object.assign(Error("Error response received from instance metadata service"),{statusCode:h})),s.destroy();return}let _=[];f.on("data",(c)=>_.push(c)),f.on("end",()=>{i(Buffer.concat(_)),s.destroy()})}),s.end()})},sd="AWS_REGION",fd="region",_d={environmentVariableSelector:(n)=>n[sd],configFileSelector:(n)=>n[fd],default:async()=>{let n=await rd();if(n)return n;throw Error("Region is missing")}},v$={preferredFile:"credentials"},Ky=new Set,p$=(n,t=A$)=>{if(!Ky.has(n)&&!t(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 Error(`Region not accepted: region="${n}" is not a valid hostname component.`);else Ky.add(n)},hd=(n)=>typeof n==="string"&&(n.startsWith("fips-")||n.endsWith("-fips")),nO=(n)=>hd(n)?["fips-aws-global","aws-fips"].includes(n)?"us-east-1":n.replace(/fips-(dkr-|prod-)?|-fips/,""):n,tO=(n)=>{let{region:t,useFipsEndpoint:i}=n;if(!t)throw Error("Region is missing");return Object.assign(n,{region:async()=>{let r=typeof t==="function"?await t():t,s=nO(r);return p$(s),s},useFipsEndpoint:async()=>{let r=typeof t==="string"?t:await t();if(hd(r))return!0;return typeof i!=="function"?Promise.resolve(!!i):i()}})},xy=(n=[],{useFipsEndpoint:t,useDualstackEndpoint:i})=>n.find(({tags:r})=>t===r.includes("fips")&&i===r.includes("dualstack"))?.hostname,iO=(n,{regionHostname:t,partitionHostname:i})=>t?t:i?i.replace("{region}",n):void 0,rO=(n,{partitionHash:t})=>Object.keys(t||{}).find((i)=>t[i].regions.includes(n))??"aws",sO=(n,{signingRegion:t,regionRegex:i,useFipsEndpoint:r})=>{if(t)return t;else if(r){let s=i.replace("\\\\","\\").replace(/^\^/g,"\\.").replace(/\$$/g,"\\."),f=n.match(s);if(f)return f[0].slice(1,-1)}},fO=(n,{useFipsEndpoint:t=!1,useDualstackEndpoint:i=!1,signingService:r,regionHash:s,partitionHash:f})=>{let h=rO(n,{partitionHash:f}),_=n in s?n:f[h]?.endpoint??n,c={useFipsEndpoint:t,useDualstackEndpoint:i},o=xy(s[_]?.variants,c),w=xy(f[h]?.variants,c),e=iO(_,{regionHostname:o,partitionHostname:w});if(e===void 0)throw Error(`Endpoint resolution failed for: ${{resolvedRegion:_,useFipsEndpoint:t,useDualstackEndpoint:i}}`);let u=sO(e,{signingRegion:s[_]?.signingRegion,regionRegex:f[h].regionRegex,useFipsEndpoint:t});return{partition:h,signingService:r,hostname:e,...u&&{signingRegion:u},...s[_]?.signingService&&{signingService:s[_].signingService}}},_O="AWS_DEFAULTS_MODE",hO="defaults_mode",cO={environmentVariableSelector:(n)=>{return n[_O]},configFileSelector:(n)=>{return n[hO]},default:"legacy"},oO=({region:n=Mc(_d),defaultsMode:t=Mc(cO)}={})=>Tc(async()=>{let i=typeof t==="function"?await t():t;switch(i?.toLowerCase()){case"auto":return wO(n);case"in-region":case"cross-region":case"mobile":case"standard":case"legacy":return Promise.resolve(i?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw Error(`Invalid parameter for "defaultsMode", expect ${x$.join(", ")}, got ${i}`)}}),wO=async(n)=>{if(n){let t=typeof n==="function"?await n():n,i=await eO();if(!i)return"standard";if(t===i)return"in-region";else return"cross-region"}return"standard"},eO=async()=>{if(process.env[V$]&&(process.env[Jy]||process.env[Qy]))return process.env[Jy]??process.env[Qy];return rd()};uO.CONFIG_PREFIX_SEPARATOR=ai;uO.CONFIG_USE_DUALSTACK_ENDPOINT=Lc;uO.CONFIG_USE_FIPS_ENDPOINT=Oc;uO.CredentialsProviderError=ps;uO.DEFAULT_PROFILE=Zy;uO.DEFAULT_USE_DUALSTACK_ENDPOINT=P$;uO.DEFAULT_USE_FIPS_ENDPOINT=X$;uO.ENV_PROFILE=my;uO.ENV_USE_DUALSTACK_ENDPOINT=Sc;uO.ENV_USE_FIPS_ENDPOINT=$c;uO.NODE_REGION_CONFIG_FILE_OPTIONS=v$;uO.NODE_REGION_CONFIG_OPTIONS=_d;uO.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS=Y$;uO.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS=l$;uO.ProviderError=Vr;uO.REGION_ENV_NAME=sd;uO.REGION_INI_NAME=fd;uO.SelectorType=Tt;uO.TokenProviderError=Ec;uO.booleanSelector=vt;uO.chain=ky;uO.externalDataInterceptor=H$;uO.fromStatic=td;uO.fromValue=qy;uO.getHomeDir=nf;uO.getProfileName=ay;uO.getRegionInfo=fO;uO.getSSOTokenFilepath=vy;uO.getSSOTokenFromFile=E$;uO.loadConfig=Mc;uO.loadSharedConfigFiles=gc;uO.loadSsoSessionData=N$;uO.memoize=Tc;uO.nodeDualstackConfigSelectors=F$;uO.nodeFipsConfigSelectors=J$;uO.numberSelector=R$;uO.parseKnownFiles=I$;uO.readFile=I_;uO.resolveCustomEndpointsConfig=Q$;uO.resolveDefaultsModeConfig=oO;uO.resolveEndpointsConfig=C$;uO.resolveRegionConfig=tO});var vi=nn((JU)=>{var{CONFIG_PREFIX_SEPARATOR:cd,loadConfig:tU}=xn(),{toEndpointV1:H_,getSmithyContext:iU,normalizeProvider:Uc,isValidHostLabel:ed}=Dt();JU.isValidHostLabel=ed;JU.middlewareEndpointToEndpointV1=H_;JU.toEndpointV1=H_;var{EndpointURLScheme:Bc}=mi(),od="AWS_ENDPOINT_URL",wd="endpoint_url",rU=(n)=>({environmentVariableSelector:(t)=>{let i=n.split(" ").map((f)=>f.toUpperCase()),r=t[[od,...i].join("_")];if(r)return r;let s=t[od];if(s)return s;return},configFileSelector:(t,i)=>{if(i&&t.services){let s=i[["services",t.services].join(cd)];if(s){let f=n.split(" ").map((_)=>_.toLowerCase()),h=s[[f.join("_"),wd].join(cd)];if(h)return h}}let r=t[wd];if(r)return r;return},default:void 0}),G_=async(n)=>tU(rU(n??""))(),sU=async(n)=>{let t=n?.Bucket||"";if(typeof n.Bucket==="string")n.Bucket=t.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"));if(oU(t)){if(n.ForcePathStyle===!0)throw Error("Path-style addressing cannot be used with ARN buckets")}else if(!cU(t)||t.indexOf(".")!==-1&&!String(n.Endpoint).startsWith("http:")||t.toLowerCase()!==t||t.length<3)n.ForcePathStyle=!0;if(n.DisableMultiRegionAccessPoints)n.disableMultiRegionAccessPoints=!0,n.DisableMRAP=!0;return n},fU=/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/,_U=/(\d+\.){3}\d+/,hU=/\.\./,cU=(n)=>fU.test(n)&&!_U.test(n)&&!hU.test(n),oU=(n)=>{let[t,i,r,,,s]=n.split(":"),f=t==="arn"&&n.split(":").length>=6,h=Boolean(f&&i&&r&&s);if(f&&!h)throw Error(`Invalid ARN: ${n} was an invalid ARN.`);return h},wU=(n,t,i,r=!1)=>{let s=async()=>{let f;if(r)f=i.clientContextParams?.[n]??i[n]??i[t];else f=i[n]??i[t];if(typeof f==="function")return f();return f};if(n==="credentialScope"||t==="CredentialScope")return async()=>{let f=typeof i.credentials==="function"?await i.credentials():i.credentials;return f?.credentialScope??f?.CredentialScope};if(n==="accountId"||t==="AccountId")return async()=>{let f=typeof i.credentials==="function"?await i.credentials():i.credentials;return f?.accountId??f?.AccountId};if(n==="endpoint"||t==="endpoint")return async()=>{if(i.isCustomEndpoint===!1)return;let f=await s();if(f&&typeof f==="object"){if("url"in f)return f.url.href;if("hostname"in f){let{protocol:h,hostname:_,port:c,path:o}=f;return`${h}//${_}${c?":"+c:""}${o}`}}return f};return s};function ud(n){return async(t,i,r,s)=>{if(!r.isCustomEndpoint){let _;if(r.serviceConfiguredEndpoint)_=await r.serviceConfiguredEndpoint();else _=await n(r.serviceId);if(_)r.endpoint=()=>Promise.resolve(H_(_)),r.isCustomEndpoint=!0}let f=await yd(t,i,r);if(typeof r.endpointProvider!=="function")throw Error("config.endpointProvider is not set.");let h=r.endpointProvider(f,s);if(r.isCustomEndpoint&&r.endpoint){let _=await r.endpoint();if(_?.headers){h.headers??={};for(let[c,o]of Object.entries(_.headers))h.headers[c]=Array.isArray(o)?o:[o]}}return h}}var yd=async(n,t,i)=>{let r={},s=t?.getEndpointParameterInstructions?.()||{};for(let[f,h]of Object.entries(s))switch(h.type){case"staticContextParams":r[f]=h.value;break;case"contextParams":r[f]=n[h.name];break;case"clientContextParams":case"builtInParams":r[f]=await wU(h.name,f,i,h.type!=="builtInParams")();break;case"operationContextParams":r[f]=h.get(n);break;default:throw Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(h))}if(Object.keys(s).length===0)Object.assign(r,i);if(String(i.serviceId).toLowerCase()==="s3")await sU(r);return r};function eU(n,t,i){if(!n.__smithy_context)n.__smithy_context={features:{}};else if(!n.__smithy_context.features)n.__smithy_context.features={};n.__smithy_context.features[t]=i}function dd(n){let t=ud(n);return({config:i,instructions:r})=>{return(s,f)=>async(h)=>{if(i.isCustomEndpoint)eU(f,"ENDPOINT_OVERRIDE","N");let _=await t(h.input,{getEndpointParameterInstructions(){return r}},{...i},f);f.endpointV2=_,f.authSchemes=_.properties?.authSchemes;let c=f.authSchemes?.[0];if(c){f.signing_region=c.signingRegion,f.signing_service=c.signingName;let w=iU(f)?.selectedHttpAuthScheme?.httpAuthOption;if(w)w.signingProperties=Object.assign(w.signingProperties||{},{signing_region:c.signingRegion,signingRegion:c.signingRegion,signing_service:c.signingName,signingName:c.signingName,signingRegionSet:c.signingRegionSet},c.properties)}return s({...h})}}}var uU={name:"serializerMiddleware"},Ad={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:uU.name};function yU(n){let t=dd(n);return(i,r)=>({applyToStack:(s)=>{s.addRelativeTo(t({config:i,instructions:r}),Ad)}})}function dU(n){return(t)=>{let i=t.tls??!0,{endpoint:r,useDualstackEndpoint:s,useFipsEndpoint:f}=t,h=r!=null?async()=>H_(await Uc(r)()):void 0,c=Object.assign(t,{endpoint:h,tls:i,isCustomEndpoint:!!r,useDualstackEndpoint:Uc(s??!1),useFipsEndpoint:Uc(f??!1)}),o=void 0;return c.serviceConfiguredEndpoint=async()=>{if(t.serviceId&&!o)o=n(t.serviceId);return o},c}}class Ic{nodes;root;conditions;results;constructor(n,t,i,r){this.nodes=n,this.root=t,this.conditions=i,this.results=r}static from(n,t,i,r){return new Ic(n,t,i,r)}}class Rd{capacity;data=new Map;parameters=[];constructor({size:n,params:t}){if(this.capacity=n??50,t)this.parameters=t}get(n,t){let i=this.hash(n);if(i===!1)return t();if(!this.data.has(i)){if(this.data.size>this.capacity+10){let r=this.data.keys(),s=0;while(!0){let{value:f,done:h}=r.next();if(this.data.delete(f),h||++s>10)break}}this.data.set(i,t())}return this.data.get(i)}size(){return this.data.size}hash(n){let t="",{parameters:i}=this;if(i.length===0)return!1;for(let r of i){let s=String(n[r]??"");if(s.includes("|;"))return!1;t+=s+"|;"}return t}}class Yn extends Error{constructor(n){super(n);this.name="EndpointError"}}var tf="endpoints";function gi(n){if(typeof n!=="object"||n==null)return n;if("ref"in n)return`$${gi(n.ref)}`;if("fn"in n)return`${n.fn}(${(n.argv||[]).map(gi).join(", ")})`;return JSON.stringify(n,null,2)}var Md={},AU=(n,t)=>n===t;function RU(...n){for(let t of n)if(t!=null)return t;return}var MU=(n)=>{let t=n.split("."),i=[];for(let r of t){let s=r.indexOf("[");if(s!==-1){if(r.indexOf("]")!==r.length-1)throw new Yn(`Path: '${n}' does not end with ']'`);let f=r.slice(s+1,-1);if(Number.isNaN(parseInt(f)))throw new Yn(`Invalid array index: '${f}' in path: '${n}'`);if(s!==0)i.push(r.slice(0,s));i.push(f)}else i.push(r)}return i},Ed=(n,t)=>MU(t).reduce((i,r)=>{if(typeof i!=="object")throw new Yn(`Index '${r}' in '${t}' not found in '${JSON.stringify(n)}'`);else if(Array.isArray(i)){let s=parseInt(r);return i[s<0?i.length+s:s]}return i[r]},n),EU=(n)=>n!=null;function TU(n,t,i){return n?t:i}var gU=(n)=>!n,SU=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}$"),Td=(n)=>SU.test(n)||n.startsWith("[")&&n.endsWith("]"),bc={[Bc.HTTP]:80,[Bc.HTTPS]:443},LU=(n)=>{let t=(()=>{try{if(n instanceof URL)return n;if(typeof n==="object"&&"hostname"in n){let{hostname:u,port:y,protocol:A="",path:R="",query:M={}}=n,E=new URL(`${A}//${u}${y?`:${y}`:""}${R}`);return E.search=Object.entries(M).map(([g,T])=>`${g}=${T}`).join("&"),E}return new URL(n)}catch(u){return null}})();if(!t)return console.error(`Unable to parse ${JSON.stringify(n)} as a whatwg URL.`),null;let i=t.href,{host:r,hostname:s,pathname:f,protocol:h,search:_}=t;if(_)return null;let c=h.slice(0,-1);if(!Object.values(Bc).includes(c))return null;let o=Td(s),w=i.includes(`${r}:${bc[c]}`)||typeof n==="string"&&n.includes(`${r}:${bc[c]}`),e=`${r}${w?`:${bc[c]}`:""}`;return{scheme:c,authority:e,path:f,normalizedPath:f.endsWith("/")?f:`${f}/`,isIp:o}};function $U(n,t,i){if(i===1)return[n];if(n==="")return[""];let r=n.split(t);if(i===0)return r;return r.slice(0,i-1).concat(r.slice(1).join(t))}var OU=(n,t)=>n===t,UU=(n,t,i,r)=>{if(n==null||t>=i||n.length<i||/[^\u0000-\u007f]/.test(n))return null;if(!r)return n.substring(t,i);return n.substring(n.length-i,n.length-t)},bU=(n)=>encodeURIComponent(n).replace(/[!*'()]/g,(t)=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),NU={booleanEquals:AU,coalesce:RU,getAttr:Ed,isSet:EU,isValidHostLabel:ed,ite:TU,not:gU,parseURL:LU,split:$U,stringEquals:OU,substring:UU,uriEncode:bU},gd=(n,t)=>{let i=[],{referenceRecord:r,endpointParams:s}=t,f=0;while(f<n.length){let h=n.indexOf("{",f);if(h===-1){i.push(n.slice(f));break}i.push(n.slice(f,h));let _=n.indexOf("}",h);if(_===-1){i.push(n.slice(h));break}if(n[h+1]==="{"&&n[_+1]==="}")i.push(n.slice(h+1,_)),f=_+2;let c=n.substring(h+1,_);if(c.includes("#")){let[o,w]=c.split("#");i.push(Ed(r[o]??s[o],w))}else i.push(r[c]??s[c]);f=_+1}return i.join("")},BU=({ref:n},t)=>{return t.referenceRecord[n]??t.endpointParams[n]},rf=(n,t,i)=>{if(typeof n==="string")return gd(n,i);else if(n.fn)return Ld.callFunction(n,i);else if(n.ref)return BU(n,i);throw new Yn(`'${t}': ${String(n)} is not a string, function or reference.`)},Sd=({fn:n,argv:t},i)=>{let r=Array(t.length);for(let h=0;h<r.length;++h){let _=t[h];if(typeof _==="boolean"||typeof _==="number")r[h]=_;else r[h]=Ld.evaluateExpression(_,"arg",i)}let s=n.indexOf(".");if(s!==-1){let _=Md[n.slice(0,s)]?.[n.slice(s+1)];if(typeof _==="function")return _(...r)}let f=NU[n];if(typeof f==="function")return f(...r);throw Error(`function ${n} not loaded in endpointFunctions.`)},Ld={evaluateExpression:rf,callFunction:Sd},$d=(n,t)=>{let{assign:i}=n;if(i&&i in t.referenceRecord)throw new Yn(`'${i}' is already defined in Reference Record.`);let r=Sd(n,t);t.logger?.debug?.(`${tf} evaluateCondition: ${gi(n)} = ${gi(r)}`);let s=r===""?!0:!!r;if(i!=null)return{result:s,toAssign:{name:i,value:r}};return{result:s}},Od=(n,t)=>Object.entries(n??{}).reduce((i,[r,s])=>{return i[r]=s.map((f)=>{let h=rf(f,"Header value entry",t);if(typeof h!=="string")throw new Yn(`Header '${r}' value '${h}' is not a string`);return h}),i},{}),Hc=(n,t)=>Object.entries(n).reduce((i,[r,s])=>{return i[r]=bd.getEndpointProperty(s,t),i},{}),Ud=(n,t)=>{if(Array.isArray(n))return n.map((i)=>Ud(i,t));switch(typeof n){case"string":return gd(n,t);case"object":if(n===null)throw new Yn(`Unexpected endpoint property: ${n}`);return bd.getEndpointProperties(n,t);case"boolean":return n;default:throw new Yn(`Unexpected endpoint property type: ${typeof n}`)}},bd={getEndpointProperty:Ud,getEndpointProperties:Hc},Nd=(n,t)=>{let i=rf(n,"Endpoint URL",t);if(typeof i==="string")try{return new URL(i)}catch(r){throw console.error(`Failed to construct URL with ${i}`,r),r}throw new Yn(`Endpoint URL must be a string, got ${typeof i}`)},Nc=1e8,IU=(n,t)=>{let{nodes:i,root:r,results:s,conditions:f}=n,h=r,_={},c={referenceRecord:_,endpointParams:t.endpointParams,logger:t.logger};while(h!==1&&h!==-1&&h<Nc){let o=3*(Math.abs(h)-1),[w,e,u]=[i[o],i[o+1],i[o+2]],[y,A,R]=f[w],M=$d({fn:y,assign:R,argv:A},c);if(M.toAssign){let{name:E,value:g}=M.toAssign;_[E]=g}h=h>=0===M.result?e:u}if(h>=Nc){let o=s[h-Nc];if(o[0]===-1){let[,y]=o;throw new Yn(rf(y,"Error",c))}let[w,e,u]=o;return{url:Nd(w,c),properties:Hc(e,c),headers:Od(u??{},c)}}throw new Yn("No matching endpoint.")},Gc=(n=[],t)=>{let i={},r={...t,referenceRecord:{...t.referenceRecord}},s=!1;for(let f of n){let{result:h,toAssign:_}=$d(f,r);if(!h)return{result:h};if(_)s=!0,i[_.name]=_.value,r.referenceRecord[_.name]=_.value,t.logger?.debug?.(`${tf} assign: ${_.name} := ${gi(_.value)}`)}if(s)return{result:!0,referenceRecord:i};return{result:!0}},HU=(n,t)=>{let{conditions:i,endpoint:r}=n,{result:s,referenceRecord:f}=Gc(i,t);if(!s)return;let h=f?{...t,referenceRecord:{...t.referenceRecord,...f}}:t,{url:_,properties:c,headers:o}=r;t.logger?.debug?.(`${tf} Resolving endpoint from template: ${gi(r)}`);let w={url:Nd(_,h)};if(o!=null)w.headers=Od(o,h);if(c!=null)w.properties=Hc(c,h);return w},GU=(n,t)=>{let{conditions:i,error:r}=n,{result:s,referenceRecord:f}=Gc(i,t);if(!s)return;let h=f?{...t,referenceRecord:{...t.referenceRecord,...f}}:t;throw new Yn(rf(r,"Error",h))},Bd=(n,t)=>{for(let i of n)if(i.type==="endpoint"){let r=HU(i,t);if(r)return r}else if(i.type==="error")GU(i,t);else if(i.type==="tree"){let r=Id.evaluateTreeRule(i,t);if(r)return r}else throw new Yn(`Unknown endpoint rule: ${i}`);throw new Yn("Rules evaluation failed")},WU=(n,t)=>{let{conditions:i,rules:r}=n,{result:s,referenceRecord:f}=Gc(i,t);if(!s)return;let h=f?{...t,referenceRecord:{...t.referenceRecord,...f}}:t;return Id.evaluateRules(r,h)},Id={evaluateRules:Bd,evaluateTreeRule:WU},DU=(n,t)=>{let{endpointParams:i,logger:r}=t,{parameters:s,rules:f}=n;t.logger?.debug?.(`${tf} Initial EndpointParams: ${gi(i)}`);for(let _ in s){let c=s[_],o=i[_];if(o==null&&c.default!=null){i[_]=c.default;continue}if(c.required&&o==null)throw new Yn(`Missing required parameter: '${_}'`)}let h=Bd(f,{endpointParams:i,logger:r,referenceRecord:{}});return t.logger?.debug?.(`${tf} Resolved endpoint: ${gi(h)}`),h},PU=(n)=>{let{endpoint:t}=n;if(t===void 0)n.endpoint=async()=>{throw Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint.")};return n},YU=ud(G_),FU=dU(G_),XU=dd(G_),lU=yU(G_);JU.BinaryDecisionDiagram=Ic;JU.EndpointCache=Rd;JU.EndpointError=Yn;JU.customEndpointFunctions=Md;JU.decideEndpoint=IU;JU.endpointMiddleware=XU;JU.endpointMiddlewareOptions=Ad;JU.getEndpointFromInstructions=YU;JU.getEndpointPlugin=lU;JU.isIpAddress=Td;JU.resolveEndpoint=DU;JU.resolveEndpointConfig=FU;JU.resolveEndpointRequiredConfig=PU;JU.resolveParams=yd});var jn=nn((GN)=>{var{createHmac:rb,createHash:sb,getRandomValues:fb}=cn("crypto"),{ReadStream:_b,lstatSync:hb,fstatSync:cb}=cn("fs"),{HttpResponse:ob}=Dt(),{toEndpointV1:wb}=vi(),{Readable:Kr,Writable:Xd,PassThrough:Hd}=cn("stream"),ld=(n)=>typeof ArrayBuffer==="function"&&n instanceof ArrayBuffer||Object.prototype.toString.call(n)==="[object ArrayBuffer]",jr=(n,t=0,i=n.byteLength-t)=>{if(!ld(n))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof n} (${n})`);return Buffer.from(n,t,i)},Y_=(n,t)=>{if(typeof n!=="string")throw TypeError(`The "input" argument must be of type string. Received type ${typeof n} (${n})`);return t?Buffer.from(n,t):Buffer.from(n)},eb=/^[A-Za-z0-9+/]*={0,2}$/,Jd=(n)=>{if(n.length*3%4!==0)throw TypeError("Incorrect padding on base64 string.");if(!eb.exec(n))throw TypeError("Invalid base64 string.");let t=Y_(n,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)},F_=(n)=>{let t=Y_(n,"utf8");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT)},Jc=(n)=>{let t;if(typeof n==="string")t=F_(n);else t=n;if(typeof t!=="object"||typeof t.byteOffset!=="number"||typeof t.byteLength!=="number")throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");return jr(t.buffer,t.byteOffset,t.byteLength).toString("base64")};function ub(n,t,i,r){return class s extends Uint8Array{static fromString(f,h="utf-8"){if(typeof f==="string"){if(h==="base64")return s.mutate(r(f));return s.mutate(t(f))}throw Error(`Unsupported conversion from ${typeof f} to Uint8ArrayBlobAdapter.`)}static mutate(f){return Object.setPrototypeOf(f,s.prototype),f}transformToString(f="utf-8"){if(f==="base64")return i(this);return n(this)}}}var Qd=(n)=>{if(typeof n==="string")return n;if(typeof n!=="object"||typeof n.byteOffset!=="number"||typeof n.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return jr(n.buffer,n.byteOffset,n.byteLength).toString("utf8")},Jn=Array.from({length:256},(n,t)=>t.toString(16).padStart(2,"0"));function yb(n){if(typeof crypto<"u"&&typeof crypto.randomUUID==="function")return()=>crypto.randomUUID();return()=>{let t=new Uint8Array(16);return n(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128,Jn[t[0]]+Jn[t[1]]+Jn[t[2]]+Jn[t[3]]+"-"+Jn[t[4]]+Jn[t[5]]+"-"+Jn[t[6]]+Jn[t[7]]+"-"+Jn[t[8]]+Jn[t[9]]+"-"+Jn[t[10]]+Jn[t[11]]+Jn[t[12]]+Jn[t[13]]+Jn[t[14]]+Jn[t[15]]}}var db=(n,t,i=(r)=>r)=>n,Ab=(n)=>{switch(n){case"true":return!0;case"false":return!1;default:throw Error(`Unable to parse boolean value "${n}"`)}},Rb=(n)=>{if(n===null||n===void 0)return;if(typeof n==="number"){if(n===0||n===1)hf.warn(D_(`Expected boolean, got ${typeof n}: ${n}`));if(n===0)return!1;if(n===1)return!0}if(typeof n==="string"){let t=n.toLowerCase();if(t==="false"||t==="true")hf.warn(D_(`Expected boolean, got ${typeof n}: ${n}`));if(t==="false")return!1;if(t==="true")return!0}if(typeof n==="boolean")return n;throw TypeError(`Expected boolean, got ${typeof n}: ${n}`)},ff=(n)=>{if(n===null||n===void 0)return;if(typeof n==="string"){let t=parseFloat(n);if(!Number.isNaN(t)){if(String(t)!==String(n))hf.warn(D_(`Expected number but observed string: ${n}`));return t}}if(typeof n==="number")return n;throw TypeError(`Expected number, got ${typeof n}: ${n}`)},Mb=Math.ceil(340282346638528860000000000000000000000),W_=(n)=>{let t=ff(n);if(t!==void 0&&!Number.isNaN(t)&&t!==1/0&&t!==-1/0){if(Math.abs(t)>Mb)throw TypeError(`Expected 32-bit float, got ${n}`)}return t},_f=(n)=>{if(n===null||n===void 0)return;if(Number.isInteger(n)&&!Number.isNaN(n))return n;throw TypeError(`Expected integer, got ${typeof n}: ${n}`)},Eb=_f,Yc=(n)=>Qc(n,32),Fc=(n)=>Qc(n,16),Xc=(n)=>Qc(n,8),Qc=(n,t)=>{let i=_f(n);if(i!==void 0&&Tb(i,t)!==i)throw TypeError(`Expected ${t}-bit integer, got ${n}`);return i},Tb=(n,t)=>{switch(t){case 32:return Int32Array.of(n)[0];case 16:return Int16Array.of(n)[0];case 8:return Int8Array.of(n)[0]}},gb=(n,t)=>{if(n===null||n===void 0){if(t)throw TypeError(`Expected a non-null value for ${t}`);throw TypeError("Expected a non-null value")}return n},zd=(n)=>{if(n===null||n===void 0)return;if(typeof n==="object"&&!Array.isArray(n))return n;let t=Array.isArray(n)?"array":typeof n;throw TypeError(`Expected object, got ${t}: ${n}`)},Sb=(n)=>{if(n===null||n===void 0)return;if(typeof n==="string")return n;if(["boolean","number","bigint"].includes(typeof n))return hf.warn(D_(`Expected string, got ${typeof n}: ${n}`)),String(n);throw TypeError(`Expected string, got ${typeof n}: ${n}`)},Lb=(n)=>{if(n===null||n===void 0)return;let t=zd(n),i=[];for(let r in t)if(t[r]!=null)i.push(r);if(i.length===0)throw TypeError("Unions must have exactly one non-null member. None were found.");if(i.length>1)throw TypeError(`Unions must have exactly one non-null member. Keys ${i} were not null.`);return t},zc=(n)=>{if(typeof n=="string")return ff(mr(n));return ff(n)},$b=zc,Cd=(n)=>{if(typeof n=="string")return W_(mr(n));return W_(n)},Ob=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,mr=(n)=>{let t=n.match(Ob);if(t===null||t[0].length!==n.length)throw TypeError("Expected real number, got implicit NaN");return parseFloat(n)},Cc=(n)=>{if(typeof n=="string")return Vd(n);return ff(n)},Ub=Cc,bb=Cc,Nb=(n)=>{if(typeof n=="string")return Vd(n);return W_(n)},Vd=(n)=>{switch(n){case"NaN":return NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;default:throw Error(`Unable to parse float value: ${n}`)}},Kd=(n)=>{if(typeof n==="string")return _f(mr(n));return _f(n)},Bb=Kd,Ib=(n)=>{if(typeof n==="string")return Yc(mr(n));return Yc(n)},kr=(n)=>{if(typeof n==="string")return Fc(mr(n));return Fc(n)},xd=(n)=>{if(typeof n==="string")return Xc(mr(n));return Xc(n)},D_=(n)=>{return String(TypeError(n).stack||n).split(`
|
|
10
10
|
`).slice(0,5).filter((t)=>!t.includes("stackTraceWarning")).join(`
|
|
11
|
-
`)},
|
|
12
|
-
Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(
|
|
13
|
-
`),
|
|
14
|
-
`),
|
|
15
|
-
`)}
|
|
16
|
-
${
|
|
17
|
-
`)}})};function
|
|
18
|
-
`),
|
|
19
|
-
`)}),i.on("end",async()=>{if(
|
|
20
|
-
`),
|
|
21
|
-
`),
|
|
22
|
-
`)}
|
|
23
|
-
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 r.stream()};return Object.assign(n,{transformToByteArray:i,transformToString:async(r)=>{let e=await i();if(r==="base64")return TA(e);else if(r==="hex")return _A(e);else if(r===void 0||r==="utf8"||r==="utf-8")return u$(e);else if(typeof TextDecoder==="function")return new TextDecoder(r).decode(e);else throw Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(t)throw Error(al);if(t=!0,vl(n))return s(n);else if(bt(n))return n;else throw Error(`Cannot transform payload to web stream, got ${n}`)}})},vl=(n)=>typeof Blob==="function"&&n instanceof Blob,$A=(n)=>{if(Uo(n))return UA(n);if(bt(n))return bA(n);return new Promise((t,i)=>{let s=new LA,r=n;r.pipe(s),r.on("error",(e)=>{s.end(),i(e)}),s.on("error",i),s.on("finish",function(){let e=Io(this.bufferedBytes);t(e)})})};class LA extends pl{bufferedBytes=[];_write(n,t,i){this.bufferedBytes.push(n),i()}}var Zl="The stream has already been transformed.",w$=(n)=>{if(!(n instanceof Ns))try{return _$(n)}catch(s){let r=n?.__proto__?.constructor?.name||n;throw Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${r}`)}let t=!1,i=async()=>{if(t)throw Error(Zl);return t=!0,await $A(n)};return Object.assign(n,{transformToByteArray:i,transformToString:async(s)=>{let r=await i();if(s===void 0||Buffer.isEncoding(s))return Hs(r.buffer,r.byteOffset,r.byteLength).toString(s);else return new TextDecoder(s).decode(r)},transformToWebStream:()=>{if(t)throw Error(Zl);if(n.readableFlowing!==null)throw Error("The stream has been consumed by other callbacks.");if(typeof Ns.toWeb!=="function")throw Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");return t=!0,Ns.toWeb(n)}})};async function l$(n){if(typeof n.stream==="function")n=n.stream();return n.tee()}async function A$(n){if(bt(n)||Uo(n))return l$(n);let t=new kl,i=new kl;return n.pipe(t),n.pipe(i),[t,i]}class OA extends ZU(iA,go,Tu,tA){}var M$=KU,BA=pU(M$),d$=BA;R$.ChecksumStream=EA;R$.Hash=RA;R$.LazyJsonString=Xi;R$.NumericValue=So;R$.Uint8ArrayBlobAdapter=OA;R$._parseEpochTimestamp=zb;R$._parseRfc3339DateTimeWithOffset=Qb;R$._parseRfc7231DateTime=Cb;R$.calculateBodyLength=Vb;R$.concatBytes=Io;R$.copyDocumentWithTransform=nb;R$.createBufferedReadable=s$;R$.createChecksumStream=t$;R$.dateToUtcString=Rb;R$.deserializerMiddleware=lA;R$.deserializerMiddlewareOption=MA;R$.expectBoolean=ib;R$.expectByte=Eu;R$.expectFloat32=Ro;R$.expectInt=rb;R$.expectInt32=du;R$.expectLong=Cr;R$.expectNonNull=ob;R$.expectNumber=Qr;R$.expectObject=sA;R$.expectShort=Ru;R$.expectString=fb;R$.expectUnion=hb;R$.fromArrayBuffer=Hs;R$.fromBase64=tA;R$.fromHex=qb;R$.fromString=To;R$.fromUtf8=go;R$.generateIdempotencyToken=d$;R$.getAwsChunkedEncodingStream=e$;R$.getSerdePlugin=jb;R$.handleFloat=_b;R$.headStream=f$;R$.isArrayBuffer=nA;R$.isBlob=Uo;R$.isReadableStream=bt;R$.limitedParseDouble=Iu;R$.limitedParseFloat=wb;R$.limitedParseFloat32=lb;R$.logger=xr;R$.nv=kb;R$.parseBoolean=tb;R$.parseEpochTimestamp=$b;R$.parseRfc3339DateTime=yb;R$.parseRfc3339DateTimeWithOffset=gb;R$.parseRfc7231DateTime=bb;R$.quoteHeader=Pb;R$.sdkStreamMixin=w$;R$.serializerMiddleware=AA;R$.serializerMiddlewareOption=dA;R$.splitEvery=xb;R$.splitHeader=Kb;R$.splitStream=A$;R$.streamCollector=$A;R$.strictParseByte=fA;R$.strictParseDouble=Su;R$.strictParseFloat=ub;R$.strictParseFloat32=rA;R$.strictParseInt=Ab;R$.strictParseInt32=Mb;R$.strictParseLong=oA;R$.strictParseShort=Ws;R$.toBase64=Tu;R$.toHex=_A;R$.toUint8Array=wA;R$.toUtf8=iA;R$.v4=BA});var Wu=k((rO)=>{var{createReadStream:DL}=p("fs"),{Writable:YL}=p("stream"),{toUint8Array:Ds,concatBytes:mL}=mn(),{createHash:Kr,createHmac:JL}=p("crypto"),NA=p("zlib");async function PA(n,t,i=1048576){let s=n.size,r=0;while(r<s){let e=n.slice(r,Math.min(s,r+i));t(new Uint8Array(await e.arrayBuffer())),r+=e.size}}var XL=async function(t,i){let s=new t;return await PA(i,(r)=>{s.update(r)}),s.digest()};class Nu extends YL{hash;constructor(n,t){super(t);this.hash=n}_write(n,t,i){try{this.hash.update(Ds(n))}catch(s){return i(s)}i()}}var zL=(n,t)=>new Promise((i,s)=>{if(!QL(t)){s(Error("Unable to calculate hash for non-file streams."));return}let r=DL(t.path,{start:t.start,end:t.end}),e=new n,f=new Nu(e);r.pipe(f),r.on("error",(o)=>{f.end(),s(o)}),f.on("error",s),f.on("finish",function(){e.digest().then(i).catch(s)})}),QL=(n)=>typeof n.path==="string",CL=(n,t)=>{if(t.readableFlowing!==null)throw Error("Unable to calculate hash for flowing readable stream");let i=new n,s=new Nu(i);return t.pipe(s),new Promise((r,e)=>{t.on("error",(f)=>{s.end(),e(f)}),s.on("error",e),s.on("finish",()=>{i.digest().then(r).catch(e)})})};class Gu{digestLength=16;state=Uint32Array.from(GA);writeBuffer=new DataView(new ArrayBuffer(64));bufferLength=0;bytesHashed=0;update(n){let t=Ds(n),i=0,s=t.byteLength;this.bytesHashed+=s;while(s>0)if(this.writeBuffer.setUint8(this.bufferLength++,t[i++]),--s,this.bufferLength===64)Ou(this.state,this.writeBuffer),this.bufferLength=0}async digest(){let n=Uint32Array.from(this.state),t=new DataView(this.writeBuffer.buffer.slice(0)),i=this.bufferLength,s=this.bytesHashed*8;if(t.setUint8(i++,128),this.bufferLength%64>=56){for(let f=i;f<64;++f)t.setUint8(f,0);Ou(n,t),i=0}for(let f=i;f<56;++f)t.setUint8(f,0);t.setUint32(56,s>>>0,!0),t.setUint32(60,Math.floor(s/4294967296),!0),Ou(n,t);let r=new Uint8Array(16),e=new DataView(r.buffer);for(let f=0;f<4;++f)e.setUint32(f*4,n[f],!0);return r}reset(){this.state.set(GA),this.writeBuffer=new DataView(new ArrayBuffer(64)),this.bufferLength=0,this.bytesHashed=0}}var GA=[1732584193,4023233417,2562383102,271733878],hi=4294967295,xL=Uint8Array.of(7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21),KL=Array.from({length:64},(n,t)=>Math.abs(Math.sin(t+1))*4294967296>>>0);function Ou(n,t){let i=n[0],s=n[1],r=n[2],e=n[3];for(let f=0;f<64;++f){let o,h;if(f<16)o=s&r|~s&e,h=f;else if(f<32)o=e&s|r&~e,h=(5*f+1)%16;else if(f<48)o=s^r^e,h=(3*f+5)%16;else o=r^(s|~e),h=7*f%16;let u=t.getUint32(h*4,!0),c=e;e=r,r=s;let _=xL[(f>>4)*4+(f&3)],w=(i+o&hi)+(u+KL[f]&hi)&hi;s=s+((w<<_|w>>>32-_)>>>0)&hi,i=c}n[0]=n[0]+i&hi,n[1]=n[1]+s&hi,n[2]=n[2]+r&hi,n[3]=n[3]+e&hi}var kL=(()=>{try{return Kr("md5"),!0}catch{return!1}})(),DA=kL?qL():Gu;function qL(){return class{digestLength=16;hash=Kr("md5");update(t){this.hash.update(Ds(t))}async digest(){let t=this.hash.copy().digest();return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}reset(){this.hash=Kr("md5")}}}var YA=new Uint32Array(256);for(let n=0;n<256;++n){let t=n;for(let i=0;i<8;++i)t=t&1?3988292384^t>>>1:t>>>1;YA[n]=t>>>0}var Bu=4294967295;class Hu{digestLength=4;checksum=Bu;update(n){for(let t=0;t<n.length;++t)this.checksum=this.checksum>>>8^YA[(this.checksum^n[t])&255]}digestSync(){return(this.checksum^Bu)>>>0}async digest(){let n=this.digestSync(),t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n,!1),t}reset(){this.checksum=Bu}}var HA=typeof NA.crc32==="function"?NA.crc32:void 0,mA=HA?VL(HA):Hu;function VL(n){return class{digestLength=4;value=0;update(i){this.value=n(i,this.value)}digestSync(){return this.value>>>0}async digest(){let i=new Uint8Array(4);return new DataView(i.buffer).setUint32(0,this.digestSync(),!1),i}reset(){this.value=0}}}var On=64,WA=32,jL=9007199254740991;class Ct{digestLength=WA;state=Int32Array.from(FA);w;buffer=new Uint8Array(64);bufferLength=0;bytesHashed=0;finished=!1;inner;outer;constructor(n){if(n){let t=Ct.normalizeKey(n);this.inner=new Ct,this.outer=new Ct;let{inner:i,outer:s}=this,r=new Uint8Array(On*2);for(let e=0;e<On;++e)r[e]=54^t[e],r[e+On]=92^t[e];i.update(r.subarray(0,On)),s.update(r.subarray(On))}}update(n){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.inner){this.inner.update(n);return}let t=Ds(n),i=0,{byteLength:s}=t;if(this.bytesHashed+=s,this.bytesHashed*8>jL)throw Error("Cannot hash more than 2^53 - 1 bits");while(s>0)if(this.buffer[this.bufferLength++]=t[i++],s--,this.bufferLength===On)this.hashBuffer(),this.bufferLength=0}async digest(){let{inner:n,outer:t}=this;if(n&&t){if(this.finished)throw Error("Attempted to digest an already finished HMAC.");this.finished=!0;let i=n.digestSync();return t.update(i),t.digestSync()}return this.digestSync()}reset(){this.state=Int32Array.from(FA),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0}digestSync(){let n=this.state.slice(),t=this.buffer.slice(),i=this.bufferLength,s=this.bytesHashed*8,r=new DataView(t.buffer,t.byteOffset,t.byteLength);if(r.setUint8(i++,128),(i-1)%On>=On-8){for(let f=i;f<On;++f)r.setUint8(f,0);this.hashBufferWith(n,t),i=0}for(let f=i;f<On-8;++f)r.setUint8(f,0);r.setUint32(On-8,Math.floor(s/4294967296),!1),r.setUint32(On-4,s,!1),this.hashBufferWith(n,t);let e=new Uint8Array(WA);for(let f=0;f<8;++f)e[f*4]=n[f]>>>24&255,e[f*4+1]=n[f]>>>16&255,e[f*4+2]=n[f]>>>8&255,e[f*4+3]=n[f]>>>0&255;return e}static normalizeKey(n){let t=Ds(n);if(t.byteLength>On){let i=new Ct;i.update(t);let s=i.digestSync(),r=new Uint8Array(On);return r.set(s),r}if(t.byteLength<On){let i=new Uint8Array(On);return i.set(t),i}return t}hashBuffer(){this.hashBufferWith(this.state,this.buffer)}hashBufferWith(n,t){let i=this.w??=new Int32Array(64),s=n[0],r=n[1],e=n[2],f=n[3],o=n[4],h=n[5],u=n[6],c=n[7];for(let _=0;_<On;++_){if(_<16)i[_]=(t[_*4]&255)<<24|(t[_*4+1]&255)<<16|(t[_*4+2]&255)<<8|t[_*4+3]&255;else{let A=i[_-2],d=(A>>>17|A<<15)^(A>>>19|A<<13)^A>>>10;A=i[_-15];let E=(A>>>7|A<<25)^(A>>>18|A<<14)^A>>>3;i[_]=(d+i[_-7]|0)+(E+i[_-16]|0)}let w=(((o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7))+(o&h^~o&u)|0)+(c+(aL[_]+i[_]|0)|0)|0,l=((s>>>2|s<<30)^(s>>>13|s<<19)^(s>>>22|s<<10))+(s&r^s&e^r&e)|0;c=u,u=h,h=o,o=f+w|0,f=e,e=r,r=s,s=w+l|0}n[0]+=s,n[1]+=r,n[2]+=e,n[3]+=f,n[4]+=o,n[5]+=h,n[6]+=u,n[7]+=c}}var FA=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),aL=new Int32Array([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]),vL=(()=>{try{return Kr("sha256"),!0}catch{return!1}})(),JA=vL?ZL():Ct;function ZL(){return class{digestLength=32;secret;hash;isHmac;finished=!1;constructor(t){this.secret=t,this.isHmac=!!t,this.hash=this.createHash()}update(t){if(this.finished)throw Error("Attempted to update an already finished hash.");this.hash.update(t)}async digest(){let t;if(this.isHmac)this.finished=!0,t=this.hash.digest();else t=this.hash.copy().digest();return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}reset(){this.hash=this.createHash(),this.finished=!1}createHash(){return this.secret?JL("sha256",pL(this.secret)):Kr("sha256")}}}function pL(n){if(typeof n==="string")return n;if(ArrayBuffer.isView(n))return Buffer.from(n.buffer,n.byteOffset,n.byteLength);return Buffer.from(n)}var{digest:nO,sign:tO,importKey:iO}=globalThis?.crypto?.subtle??{},bo=typeof nO==="function"&&typeof tO==="function"&&typeof iO==="function"?globalThis.crypto.subtle:void 0,sO=8388608;class XA{digestLength=32;secret;pending=[];pendingBytes=0;fallback;finished=!1;constructor(n){if(n)this.secret=Ds(n)}update(n){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.fallback){this.fallback.update(n);return}if(this.pending.push(n.slice()),this.pendingBytes+=n.byteLength,this.pendingBytes>=sO)this.switchToFallback()}async digest(){if(this.fallback)return this.fallback.digest();if(this.secret&&this.finished)throw Error("Attempted to digest an already finished HMAC.");let n=mL(this.pending);if(bo){if(this.secret){this.finished=!0;let s=await bo.importKey("raw",this.secret,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await bo.sign("HMAC",s,n);return new Uint8Array(r)}let i=await bo.digest("SHA-256",n);return new Uint8Array(i)}let t=new Ct(this.secret);return t.update(n),t.digest()}reset(){this.pending=[],this.pendingBytes=0,this.fallback=void 0,this.finished=!1}switchToFallback(){let n=new Ct(this.secret);for(let t of this.pending)n.update(t);this.fallback=n,this.pending=[],this.pendingBytes=0}}rO.Crc32=mA;rO.Crc32Js=Hu;rO.Crc32Node=mA;rO.Md5=DA;rO.Md5Js=Gu;rO.Md5Node=DA;rO.Sha256=JA;rO.Sha256Js=Ct;rO.Sha256Node=JA;rO.Sha256WebCrypto=XA;rO.blobHasher=XL;rO.blobReader=PA;rO.fileStreamHasher=zL;rO.readableStreamHasher=CL});var $o=k((zO)=>{var{Crc32:CA}=Wu(),{toHex:Ys,fromHex:yO,toUtf8:TO,fromUtf8:gO}=mn(),{Readable:SO}=p("stream");class ms{bytes;constructor(n){if(this.bytes=n,n.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(n){if(n>9223372036854776000||n<-9223372036854776000)throw Error(`${n} is too large (or, if negative, too small) to represent as an Int64`);let t=new Uint8Array(8);for(let i=7,s=Math.abs(Math.round(n));i>-1&&s>0;i--,s/=256)t[i]=s;if(n<0)zA(t);return new ms(t)}valueOf(){let n=this.bytes.slice(0),t=n[0]&128;if(t)zA(n);return parseInt(Ys(n),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function zA(n){for(let t=0;t<8;t++)n[t]^=255;for(let t=7;t>-1;t--)if(n[t]++,n[t]!==0)break}class Fu{toUtf8;fromUtf8;constructor(n,t){this.toUtf8=n,this.fromUtf8=t}format(n){let t=[];for(let r of Object.keys(n)){let e=this.fromUtf8(r);t.push(Uint8Array.from([e.byteLength]),e,this.formatHeaderValue(n[r]))}let i=new Uint8Array(t.reduce((r,e)=>r+e.byteLength,0)),s=0;for(let r of t)i.set(r,s),s+=r.byteLength;return i}formatHeaderValue(n){switch(n.type){case"boolean":return Uint8Array.from([n.value?Mn.boolTrue:Mn.boolFalse]);case"byte":return Uint8Array.from([Mn.byte,n.value]);case"short":let t=new DataView(new ArrayBuffer(3));return t.setUint8(0,Mn.short),t.setInt16(1,n.value,!1),new Uint8Array(t.buffer);case"integer":let i=new DataView(new ArrayBuffer(5));return i.setUint8(0,Mn.integer),i.setInt32(1,n.value,!1),new Uint8Array(i.buffer);case"long":let s=new Uint8Array(9);return s[0]=Mn.long,s.set(n.value.bytes,1),s;case"binary":let r=new DataView(new ArrayBuffer(3+n.value.byteLength));r.setUint8(0,Mn.byteArray),r.setUint16(1,n.value.byteLength,!1);let e=new Uint8Array(r.buffer);return e.set(n.value,3),e;case"string":let f=this.fromUtf8(n.value),o=new DataView(new ArrayBuffer(3+f.byteLength));o.setUint8(0,Mn.string),o.setUint16(1,f.byteLength,!1);let h=new Uint8Array(o.buffer);return h.set(f,3),h;case"timestamp":let u=new Uint8Array(9);return u[0]=Mn.timestamp,u.set(ms.fromNumber(n.value.valueOf()).bytes,1),u;case"uuid":if(!GO.test(n.value))throw Error(`Invalid UUID received: ${n.value}`);let c=new Uint8Array(17);return c[0]=Mn.uuid,c.set(yO(n.value.replace(/-/g,"")),1),c}}parse(n){let t={},i=0;while(i<n.byteLength){let s=n.getUint8(i++),r=this.toUtf8(new Uint8Array(n.buffer,n.byteOffset+i,s));switch(i+=s,n.getUint8(i++)){case Mn.boolTrue:t[r]={type:QA,value:!0};break;case Mn.boolFalse:t[r]={type:QA,value:!1};break;case Mn.byte:t[r]={type:IO,value:n.getInt8(i++)};break;case Mn.short:t[r]={type:UO,value:n.getInt16(i,!1)},i+=2;break;case Mn.integer:t[r]={type:bO,value:n.getInt32(i,!1)},i+=4;break;case Mn.long:t[r]={type:$O,value:new ms(new Uint8Array(n.buffer,n.byteOffset+i,8))},i+=8;break;case Mn.byteArray:let e=n.getUint16(i,!1);i+=2,t[r]={type:LO,value:new Uint8Array(n.buffer,n.byteOffset+i,e)},i+=e;break;case Mn.string:let f=n.getUint16(i,!1);i+=2,t[r]={type:OO,value:this.toUtf8(new Uint8Array(n.buffer,n.byteOffset+i,f))},i+=f;break;case Mn.timestamp:t[r]={type:BO,value:new Date(new ms(new Uint8Array(n.buffer,n.byteOffset+i,8)).valueOf())},i+=8;break;case Mn.uuid:let o=new Uint8Array(n.buffer,n.byteOffset+i,16);i+=16,t[r]={type:NO,value:`${Ys(o.subarray(0,4))}-${Ys(o.subarray(4,6))}-${Ys(o.subarray(6,8))}-${Ys(o.subarray(8,10))}-${Ys(o.subarray(10))}`};break;default:throw Error("Unrecognized header type tag")}}return t}}var Mn;(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"})(Mn||(Mn={}));var QA="boolean",IO="byte",UO="short",bO="integer",$O="long",LO="binary",OO="string",BO="timestamp",NO="uuid",GO=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,xA=4,ui=xA*2,zi=4,HO=ui+zi*2;function WO({byteLength:n,byteOffset:t,buffer:i}){if(n<HO)throw Error("Provided message too short to accommodate event stream message overhead");let s=new DataView(i,t,n),r=s.getUint32(0,!1);if(n!==r)throw Error("Reported message length does not match received message length");let e=s.getUint32(xA,!1),f=s.getUint32(ui,!1),o=s.getUint32(n-zi,!1),h=new CA;if(h.update(new Uint8Array(i,t,ui)),f!==h.digestSync())throw Error(`The prelude checksum specified in the message (${f}) does not match the calculated CRC32 checksum (${h.digestSync()})`);if(h.update(new Uint8Array(i,t+ui,n-(ui+zi))),o!==h.digestSync())throw Error(`The message checksum (${h.digestSync()}) did not match the expected value of ${o}`);return{headers:new DataView(i,t+ui+zi,e),body:new Uint8Array(i,t+ui+zi+e,r-e-(ui+zi+zi))}}class Pu{headerMarshaller;messageBuffer;isEndOfStream;constructor(n,t){this.headerMarshaller=new Fu(n,t),this.messageBuffer=[],this.isEndOfStream=!1}feed(n){this.messageBuffer.push(this.decode(n))}endOfStream(){this.isEndOfStream=!0}getMessage(){let n=this.messageBuffer.pop(),t=this.isEndOfStream;return{getMessage(){return n},isEndOfStream(){return t}}}getAvailableMessages(){let n=this.messageBuffer;this.messageBuffer=[];let t=this.isEndOfStream;return{getMessages(){return n},isEndOfStream(){return t}}}encode({headers:n,body:t}){let i=this.headerMarshaller.format(n),s=i.byteLength+t.byteLength+16,r=new Uint8Array(s),e=new DataView(r.buffer,r.byteOffset,r.byteLength),f=new CA;return e.setUint32(0,s,!1),e.setUint32(4,i.byteLength,!1),f.update(r.subarray(0,8)),e.setUint32(8,f.digestSync(),!1),r.set(i,12),r.set(t,i.byteLength+12),f.update(r.subarray(8,s-4)),e.setUint32(s-4,f.digestSync(),!1),r}decode(n){let{headers:t,body:i}=WO(n);return{headers:this.headerMarshaller.parse(t),body:i}}formatHeaders(n){return this.headerMarshaller.format(n)}}class Du{options;constructor(n){this.options=n}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let n of this.options.inputStream)yield this.options.decoder.decode(n)}}class Yu{options;constructor(n){this.options=n}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let n of this.options.messageStream)yield this.options.encoder.encode(n);if(this.options.includeEndFrame)yield new Uint8Array(0)}}class mu{options;constructor(n){this.options=n}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let n of this.options.messageStream){let t=await this.options.deserializer(n);if(t===void 0)continue;yield t}}}class Ju{options;constructor(n){this.options=n}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let n of this.options.inputStream)yield this.options.serializer(n)}}function KA(n){let t=0,i=0,s=null,r=null,e=(o)=>{if(typeof o!=="number")throw Error("Attempted to allocate an event message where size was not a number: "+o);t=o,i=4,s=new Uint8Array(o),new DataView(s.buffer).setUint32(0,o,!1)},f=async function*(){let o=n[Symbol.asyncIterator]();while(!0){let{value:h,done:u}=await o.next();if(u){if(!t)return;else if(t===i)yield s;else throw Error("Truncated event message received.");return}let c=h.length,_=0;while(_<c){if(!s){let l=c-_;if(!r)r=new Uint8Array(4);let A=Math.min(4-i,l);if(r.set(h.slice(_,_+A),i),i+=A,_+=A,i<4)break;e(new DataView(r.buffer).getUint32(0,!1)),r=null}let w=Math.min(t-i,c-_);if(s.set(h.slice(_,_+w),i),i+=w,_+=w,t&&t===i)yield s,s=null,t=0,i=0}}};return{[Symbol.asyncIterator]:f}}function FO(n,t){let i=Xu(t.deserializer,t.toUtf8);return{[Symbol.asyncIterator]:async function*(){for await(let s of n){let r=t.eventStreamCodec.decode(s),e=await i(r);if(e===void 0)continue;yield e}}}}function Xu(n,t){return async function(i){let{value:s}=i.headers[":message-type"];if(s==="error"){let r=Error(i.headers[":error-message"].value||"UnknownError");throw r.name=i.headers[":error-code"].value,r}else if(s==="exception"){let r=i.headers[":exception-type"].value,e={[r]:i},f=await n(e);if(f.$unknown){let o=Error(t(i.body));throw o.name=r,o}throw f[r]}else if(s==="event"){let r={[i.headers[":event-type"].value]:i},e=await n(r);if(e.$unknown)return;return e}else throw Error(`Unrecognizable event type: ${i.headers[":event-type"].value}`)}}var zu=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:t,utf8Decoder:i}){this.eventStreamCodec=new Pu(t,i),this.utfEncoder=t}deserialize(t,i){let s=KA(t);return new mu({messageStream:new Du({inputStream:s,decoder:this.eventStreamCodec}),deserializer:Xu(i,this.utfEncoder)})}serialize(t,i){return new Yu({messageStream:new Ju({inputStream:t,serializer:i}),encoder:this.eventStreamCodec,includeEndFrame:!0})}},PO=(n)=>new zu(n);class Qu{universalMarshaller;constructor({utf8Encoder:n,utf8Decoder:t}){this.universalMarshaller=new zu({utf8Decoder:t,utf8Encoder:n})}deserialize(n,t){let i=typeof n[Symbol.asyncIterator]==="function"?n:YO(n);return this.universalMarshaller.deserialize(i,t)}serialize(n,t){return SO.from(this.universalMarshaller.serialize(n,t))}}var DO=(n)=>new Qu(n);async function*YO(n){let t=!1,i=!1,s=[];n.on("error",(r)=>{if(!t)t=!0;if(r)throw r}),n.on("data",(r)=>{s.push(r)}),n.on("end",()=>{t=!0});while(!i){let r=await new Promise((e)=>setTimeout(()=>e(s.shift()),0));if(r)yield r;i=t&&s.length===0}}var mO=(n)=>({[Symbol.asyncIterator]:async function*(){let t=n.getReader();try{while(!0){let{done:i,value:s}=await t.read();if(i)return;yield s}}finally{t.releaseLock()}}}),JO=(n)=>{let t=n[Symbol.asyncIterator]();return new ReadableStream({async pull(i){let{done:s,value:r}=await t.next();if(s)return i.close();i.enqueue(r)}})},XO=(n)=>Object.assign(n,{eventStreamMarshaller:n.eventStreamSerdeProvider(n)});class kA{marshaller;serializer;deserializer;serdeContext;defaultContentType;constructor({marshaller:n,serializer:t,deserializer:i,serdeContext:s,defaultContentType:r}){this.marshaller=n,this.serializer=t,this.deserializer=i,this.serdeContext=s,this.defaultContentType=r}async serializeEventStream({eventStream:n,requestSchema:t,initialRequest:i}){let s=this.marshaller,r=t.getEventStreamMember(),e=t.getMemberSchema(r),f=this.serializer,o=this.defaultContentType,h=Symbol("initialRequestMarker"),u={async*[Symbol.asyncIterator](){if(i){let c={":event-type":{type:"string",value:"initial-request"},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:o}};f.write(t,i);let _=f.flush();yield{[h]:!0,headers:c,body:_}}for await(let c of n)yield c}};return s.serialize(u,(c)=>{if(c[h])return{headers:c.headers,body:c.body};let _="";for(let R in c)if(R!=="__type"){_=R;break}let{additionalHeaders:w,body:l,eventType:A,explicitPayloadContentType:d}=this.writeEventBody(_,e,c);return{headers:{":event-type":{type:"string",value:A},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:d??o},...w},body:l}})}async deserializeEventStream({response:n,responseSchema:t,initialResponseContainer:i}){let s=this.marshaller,r=t.getEventStreamMember(),f=t.getMemberSchema(r).getMemberSchemas(),o=Symbol("initialResponseMarker"),h=s.deserialize(n.body,async(_)=>{let w="";for(let A in _)if(A!=="__type"){w=A;break}let l=_[w].body;if(w==="initial-response"){let A=await this.deserializer.read(t,l);return delete A[r],{[o]:!0,...A}}else if(w in f){let A=f[w];if(A.isStructSchema()){let d={},E=!1;for(let[R,y]of A.structIterator()){let{eventHeader:T,eventPayload:S}=y.getMergedTraits();if(E=E||Boolean(T||S),S){if(y.isBlobSchema())d[R]=l;else if(y.isStringSchema())d[R]=(this.serdeContext?.utf8Encoder??TO)(l);else if(y.isStructSchema())d[R]=await this.deserializer.read(y,l)}else if(T){let I=_[w].headers[R]?.value;if(I!=null)if(y.isNumericSchema())if(I&&typeof I==="object"&&"bytes"in I)d[R]=BigInt(I.toString());else d[R]=Number(I);else d[R]=I}}if(E)return{[w]:d};if(l.byteLength===0)return{[w]:{}}}return{[w]:await this.deserializer.read(A,l)}}else return{$unknown:_}}),u=h[Symbol.asyncIterator](),c=await u.next();if(c.done)return h;if(c.value?.[o]){if(!t)throw Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");for(let _ in c.value)i[_]=c.value[_]}return{async*[Symbol.asyncIterator](){if(!c?.value?.[o])yield c.value;while(!0){let{done:_,value:w}=await u.next();if(_)break;yield w}}}}writeEventBody(n,t,i){let s=this.serializer,r=n,e=null,f,o=(()=>{return t.getSchema()[4].includes(n)})(),h={};if(!o){let[_,w]=i[n];r=_,s.write(15,w)}else{let _=t.getMemberSchema(n);if(_.isStructSchema()){for(let[w,l]of _.structIterator()){let{eventHeader:A,eventPayload:d}=l.getMergedTraits();if(d)e=w;else if(A){let E=i[n][w],R="binary";if(l.isNumericSchema())if(-2147483648<=E&&E<=2147483647)R="integer";else R="long";else if(l.isTimestampSchema())R="timestamp";else if(l.isStringSchema())R="string";else if(l.isBooleanSchema())R="boolean";if(E!=null)h[w]={type:R,value:E},delete i[n][w]}}if(e!==null){let w=_.getMemberSchema(e);if(w.isBlobSchema())f="application/octet-stream";else if(w.isStringSchema())f="text/plain";s.write(w,i[n][e])}else s.write(_,i[n])}else if(_.isUnitSchema())s.write(_,{});else throw Error("@smithy/core/event-streams - non-struct member not supported in event stream union.")}let u=s.flush()??new Uint8Array;return{body:typeof u==="string"?(this.serdeContext?.utf8Decoder??gO)(u):u,eventType:r,explicitPayloadContentType:f,additionalHeaders:h}}}zO.EventStreamCodec=Pu;zO.EventStreamMarshaller=Qu;zO.EventStreamSerde=kA;zO.HeaderMarshaller=Fu;zO.Int64=ms;zO.MessageDecoderStream=Du;zO.MessageEncoderStream=Yu;zO.SmithyMessageDecoderStream=mu;zO.SmithyMessageEncoderStream=Ju;zO.UniversalEventStreamMarshaller=zu;zO.eventStreamSerdeProvider=DO;zO.getChunkedStream=KA;zO.getMessageUnmarshaller=Xu;zO.getUnmarshalledStream=FO;zO.iterableToReadableStream=JO;zO.readableStreamToIterable=mO;zO.resolveEventStreamSerdeConfig=XO;zO.universalEventStreamSerdeProvider=PO});var Jn=k((LB)=>{var{Uint8ArrayBlobAdapter:Cu,sdkStreamMixin:oB,splitEvery:fB,splitHeader:aA,fromBase64:qA,_parseEpochTimestamp:hB,_parseRfc7231DateTime:uB,_parseRfc3339DateTimeWithOffset:cB,LazyJsonString:vA,NumericValue:_B,toUtf8:ZA,fromUtf8:wB,generateIdempotencyToken:lB,toBase64:VA,dateToUtcString:AB,quoteHeader:MB}=mn(),{TypeRegistry:dB,NormalizedSchema:$t,translateTraits:pA}=ri(),{HttpRequest:Js,HttpResponse:nM,isValidHostname:tM}=St(),{parseQueryString:RB,parseUrl:EB}=St();LB.HttpRequest=Js;LB.HttpResponse=nM;LB.isValidHostname=tM;LB.parseQueryString=RB;LB.parseUrl=EB;var{FieldPosition:yB}=Di(),Qi=async(n=new Uint8Array,t)=>{if(n instanceof Uint8Array)return Cu.mutate(n);if(!n)return Cu.mutate(new Uint8Array);let i=t.streamCollector(n);return Cu.mutate(await i)};function qr(n){return encodeURIComponent(n).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}class Xs{serdeContext;setSerdeContext(n){this.serdeContext=n}}class Lo extends Xs{options;compositeErrorRegistry;constructor(n){super();this.options=n,this.compositeErrorRegistry=dB.for(n.defaultNamespace);for(let t of n.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(t)}getRequestType(){return Js}getResponseType(){return nM}setSerdeContext(n){if(this.serdeContext=n,this.serializer.setSerdeContext(n),this.deserializer.setSerdeContext(n),this.getPayloadCodec())this.getPayloadCodec().setSerdeContext(n)}updateServiceEndpoint(n,t){if("url"in t){if(n.protocol=t.url.protocol,n.hostname=t.url.hostname,n.port=t.url.port?Number(t.url.port):void 0,n.path=t.url.pathname,n.fragment=t.url.hash||void 0,n.username=t.url.username||void 0,n.password=t.url.password||void 0,!n.query)n.query={};for(let[i,s]of t.url.searchParams.entries())n.query[i]=s;if(t.headers)for(let i in t.headers)n.headers[i]=t.headers[i].join(", ");return n}else{if(n.protocol=t.protocol,n.hostname=t.hostname,n.port=t.port?Number(t.port):void 0,n.path=t.path,n.query={...t.query},t.headers)for(let i in t.headers)n.headers[i]=t.headers[i];return n}}setHostPrefix(n,t,i){if(this.serdeContext?.disableHostPrefix)return;let s=$t.of(t.input),r=pA(t.traits??{});if(r.endpoint){let e=r.endpoint?.[0];if(typeof e==="string"){for(let[f,o]of s.structIterator()){if(!o.getMergedTraits().hostLabel)continue;let h=i[f];if(typeof h!=="string")throw Error(`@smithy/core/schema - ${f} in input must be a string as hostLabel.`);e=e.replace(`{${f}}`,h)}if(n.hostname=e+n.hostname,!tM(n.hostname))throw Error(`[${n.hostname}] is not a valid hostname.`)}}}deserializeMetadata(n){return{httpStatusCode:n.statusCode,requestId:n.headers["x-amzn-requestid"]??n.headers["x-amzn-request-id"]??n.headers["x-amz-request-id"],extendedRequestId:n.headers["x-amz-id-2"],cfId:n.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream:n,requestSchema:t,initialRequest:i}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:n,requestSchema:t,initialRequest:i})}async deserializeEventStream({response:n,responseSchema:t,initialResponseContainer:i}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:n,responseSchema:t,initialResponseContainer:i})}async loadEventStreamCapability(){let{EventStreamSerde:n,eventStreamSerdeProvider:t}=$o(),i=this.resolveEventStreamMarshaller(t);return new n({marshaller:i,serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}resolveEventStreamMarshaller(n){let t=this.serdeContext;if(t.eventStreamMarshaller)return t.eventStreamMarshaller;return n(this.serdeContext)}getDefaultContentType(){throw Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(n,t,i,s,r){return[]}getEventStreamMarshaller(){let n=this.serdeContext;if(!n.eventStreamMarshaller)throw Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return n.eventStreamMarshaller}}class iM extends Lo{async serializeRequest(n,t,i){let s=t&&typeof t==="object"?t:{},r=this.serializer,e={},f={},o=await i.endpoint(),h=$t.of(n?.input),u=[],c=[],_=!1,w,l=new Js({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:e,headers:f,body:void 0});if(o){this.updateServiceEndpoint(l,o),this.setHostPrefix(l,n,s);let A=pA(n.traits);if(A.http){l.method=A.http[0];let[d,E]=A.http[1].split("?");if(l.path=="/")l.path=d;else l.path+=d;let R=new URLSearchParams(E??"");for(let[y,T]of R)e[y]=T}}for(let[A,d]of h.structIterator()){let E=d.getMergedTraits()??{},R=s[A];if(R==null&&!d.isIdempotencyToken()){if(E.httpLabel){if(l.path.includes(`{${A}+}`)||l.path.includes(`{${A}}`))throw Error(`No value provided for input HTTP label: ${A}.`)}continue}if(E.httpPayload)if(d.isStreaming())if(d.isStructSchema()){if(s[A])w=await this.serializeEventStream({eventStream:s[A],requestSchema:h})}else w=R;else r.write(d,R),w=r.flush();else if(E.httpLabel){r.write(d,R);let y=r.flush();if(l.path.includes(`{${A}+}`))l.path=l.path.replace(`{${A}+}`,y.split("/").map(qr).join("/"));else if(l.path.includes(`{${A}}`))l.path=l.path.replace(`{${A}}`,qr(y))}else if(E.httpHeader)r.write(d,R),f[E.httpHeader.toLowerCase()]=String(r.flush());else if(typeof E.httpPrefixHeaders==="string")for(let y in R){let T=R[y],S=E.httpPrefixHeaders+y;r.write([d.getValueSchema(),{httpHeader:S}],T),f[S.toLowerCase()]=r.flush()}else if(E.httpQuery||E.httpQueryParams)this.serializeQuery(d,R,e);else _=!0,u.push(A),c.push(d)}if(_&&s){let[A,d]=(h.getName(!0)??"#Unknown").split("#"),E=h.getSchema()[6],R=[3,A,d,h.getMergedTraits(),u,c,void 0];if(E)R[6]=E;else R.pop();r.write(R,s),w=r.flush()}return l.headers=f,l.query=e,l.body=w,l}serializeQuery(n,t,i){let s=this.serializer,r=n.getMergedTraits();if(r.httpQueryParams){for(let e in t)if(!(e in i)){let f=t[e],o=n.getValueSchema();Object.assign(o.getMergedTraits(),{...r,httpQuery:e,httpQueryParams:void 0}),this.serializeQuery(o,f,i)}return}if(n.isListSchema()){let e=!!n.getMergedTraits().sparse,f=[];for(let o of t){s.write([n.getValueSchema(),r],o);let h=s.flush();if(e||h!==void 0)f.push(h)}i[r.httpQuery]=f}else s.write([n,r],t),i[r.httpQuery]=s.flush()}async deserializeResponse(n,t,i){let s=this.deserializer,r=$t.of(n.output),e={};if(i.statusCode>=300){let o=await Qi(i.body,t);if(o.byteLength>0)Object.assign(e,await s.read(15,o));throw await this.handleError(n,t,i,e,this.deserializeMetadata(i)),Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(let o in i.headers){let h=i.headers[o];delete i.headers[o],i.headers[o.toLowerCase()]=h}let f=await this.deserializeHttpMessage(r,t,i,e);if(f.length){let o=await Qi(i.body,t);if(o.byteLength>0){let h=await s.read(r,o);for(let u of f)if(h[u]!=null)e[u]=h[u]}}else if(f.discardResponseBody)await Qi(i.body,t);return e.$metadata=this.deserializeMetadata(i),e}async deserializeHttpMessage(n,t,i,s,r){let e;if(s instanceof Set)e=r;else e=s;let f=!0,o=this.deserializer,h=$t.of(n),u=[];for(let[c,_]of h.structIterator()){let w=_.getMemberTraits();if(w.httpPayload){if(f=!1,_.isStreaming())if(_.isStructSchema())e[c]=await this.deserializeEventStream({response:i,responseSchema:h});else e[c]=oB(i.body);else if(i.body){let A=await Qi(i.body,t);if(A.byteLength>0)e[c]=await o.read(_,A)}}else if(w.httpHeader){let l=String(w.httpHeader).toLowerCase(),A=i.headers[l];if(A!=null)if(_.isListSchema()){let d=_.getValueSchema();d.getMergedTraits().httpHeader=l;let E;if(d.isTimestampSchema()&&d.getSchema()===4)E=fB(A,",",2);else E=aA(A);let R=[];for(let y of E)R.push(await o.read(d,y.trim()));e[c]=R}else e[c]=await o.read(_,A)}else if(w.httpPrefixHeaders!==void 0){e[c]={};for(let l in i.headers)if(l.startsWith(w.httpPrefixHeaders)){let A=i.headers[l],d=_.getValueSchema();d.getMergedTraits().httpHeader=l,e[c][l.slice(w.httpPrefixHeaders.length)]=await o.read(d,A)}}else if(w.httpResponseCode)e[c]=i.statusCode;else u.push(c)}return u.discardResponseBody=f,u}}class sM extends Lo{async serializeRequest(n,t,i){let s=this.serializer,r={},e={},f=await i.endpoint(),o=$t.of(n?.input),h=o.getSchema(),u,c=t&&typeof t==="object"?t:{},_=new Js({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:r,headers:e,body:void 0});if(f)this.updateServiceEndpoint(_,f),this.setHostPrefix(_,n,c);if(c){let w=o.getEventStreamMember();if(w){if(c[w]){let l={};for(let[A,d]of o.structIterator())if(A!==w&&c[A])s.write(d,c[A]),l[A]=s.flush();u=await this.serializeEventStream({eventStream:c[w],requestSchema:o,initialRequest:l})}}else s.write(h,c),u=s.flush()}return _.headers=Object.assign(_.headers,e),_.query=r,_.body=u,_.method="POST",_}async deserializeResponse(n,t,i){let s=this.deserializer,r=$t.of(n.output),e={};if(i.statusCode>=300){let o=await Qi(i.body,t);if(o.byteLength>0)Object.assign(e,await s.read(15,o));throw await this.handleError(n,t,i,e,this.deserializeMetadata(i)),Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(let o in i.headers){let h=i.headers[o];delete i.headers[o],i.headers[o.toLowerCase()]=h}let f=r.getEventStreamMember();if(f)e[f]=await this.deserializeEventStream({response:i,responseSchema:r,initialResponseContainer:e});else{let o=await Qi(i.body,t);if(o.byteLength>0)Object.assign(e,await s.read(r,o))}return e.$metadata=this.deserializeMetadata(i),e}}var rM=(n,t,i,s,r,e)=>{if(t!=null&&t[i]!==void 0){let f=s();if(f==null||f.length<=0)throw Error("Empty value provided for input HTTP label: "+i+".");n=n.replace(r,e?f.split("/").map((o)=>qr(o)).join("/"):qr(f))}else throw Error("No value provided for input HTTP label: "+i+".");return n};function TB(n,t){return new xu(n,t)}class xu{input;context;query={};method="";headers={};path="";body=null;hostname="";resolvePathStack=[];constructor(n,t){this.input=n,this.context=t}async build(){let{hostname:n,protocol:t="https",port:i,path:s}=await this.context.endpoint();this.path=s;for(let r of this.resolvePathStack)r(this.path);return new Js({protocol:t,hostname:this.hostname||n,port:i,method:this.method,path:this.path,query:this.query,body:this.body,headers:this.headers})}hn(n){return this.hostname=n,this}bp(n){return this.resolvePathStack.push((t)=>{this.path=`${t?.endsWith("/")?t.slice(0,-1):t||""}`+n}),this}p(n,t,i,s){return this.resolvePathStack.push((r)=>{this.path=rM(r,this.input,n,t,i,s)}),this}h(n){return this.headers=n,this}q(n){return this.query=n,this}b(n){return this.body=n,this}m(n){return this.method=n,this}}function Ku(n,t){if(t.timestampFormat.useTrait){if(n.isTimestampSchema()&&(n.getSchema()===5||n.getSchema()===6||n.getSchema()===7))return n.getSchema()}let{httpLabel:i,httpPrefixHeaders:s,httpHeader:r,httpQuery:e}=n.getMergedTraits();return(t.httpBindings?typeof s==="string"||Boolean(r)?6:Boolean(e)||Boolean(i)?5:void 0:void 0)??t.timestampFormat.default}class ku extends Xs{settings;constructor(n){super();this.settings=n}read(n,t){let i=$t.of(n);if(i.isListSchema())return aA(t).map((s)=>this.read(i.getValueSchema(),s));if(i.isBlobSchema())return(this.serdeContext?.base64Decoder??qA)(t);if(i.isTimestampSchema())switch(Ku(i,this.settings)){case 5:return cB(t);case 6:return uB(t);case 7:return hB(t);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",t),new Date(t)}if(i.isStringSchema()){let s=i.getMergedTraits().mediaType,r=t;if(s){if(i.getMergedTraits().httpHeader)r=this.base64ToUtf8(r);if(s==="application/json"||s.endsWith("+json"))r=vA.from(r);return r}}if(i.isNumericSchema())return Number(t);if(i.isBigIntegerSchema())return BigInt(t);if(i.isBigDecimalSchema())return new _B(t,"bigDecimal");if(i.isBooleanSchema())return String(t).toLowerCase()==="true";return t}base64ToUtf8(n){return(this.serdeContext?.utf8Encoder??ZA)((this.serdeContext?.base64Decoder??qA)(n))}}class eM extends Xs{codecDeserializer;stringDeserializer;constructor(n,t){super();this.codecDeserializer=n,this.stringDeserializer=new ku(t)}setSerdeContext(n){this.stringDeserializer.setSerdeContext(n),this.codecDeserializer.setSerdeContext(n),this.serdeContext=n}read(n,t){let i=$t.of(n),s=i.getMergedTraits(),r=this.serdeContext?.utf8Encoder??ZA;if(s.httpHeader||s.httpResponseCode)return this.stringDeserializer.read(i,r(t));if(s.httpPayload){if(i.isBlobSchema()){let e=this.serdeContext?.utf8Decoder??wB;if(typeof t==="string")return e(t);return t}else if(i.isStringSchema()){if("byteLength"in t)return r(t);return t}}return this.codecDeserializer.read(i,t)}}class qu extends Xs{settings;stringBuffer="";constructor(n){super();this.settings=n}write(n,t){let i=$t.of(n);switch(typeof t){case"object":if(t===null){this.stringBuffer="null";return}if(i.isTimestampSchema()){if(!(t instanceof Date))throw Error(`@smithy/core/protocols - received non-Date value ${t} when schema expected Date in ${i.getName(!0)}`);switch(Ku(i,this.settings)){case 5:this.stringBuffer=t.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=AB(t);break;case 7:this.stringBuffer=String(t.getTime()/1000);break;default:console.warn("Missing timestamp format, using epoch seconds",t),this.stringBuffer=String(t.getTime()/1000)}return}if(i.isBlobSchema()&&"byteLength"in t){this.stringBuffer=(this.serdeContext?.base64Encoder??VA)(t);return}if(i.isListSchema()&&Array.isArray(t)){let e="";for(let f of t){this.write([i.getValueSchema(),i.getMergedTraits()],f);let o=this.flush(),h=i.getValueSchema().isTimestampSchema()?o:MB(o);if(e!=="")e+=", ";e+=h}this.stringBuffer=e;return}this.stringBuffer=JSON.stringify(t,null,2);break;case"string":let s=i.getMergedTraits().mediaType,r=t;if(s){if(s==="application/json"||s.endsWith("+json"))r=vA.from(r);if(i.getMergedTraits().httpHeader){this.stringBuffer=(this.serdeContext?.base64Encoder??VA)(r.toString());return}}this.stringBuffer=t;break;default:if(i.isIdempotencyToken())this.stringBuffer=lB();else this.stringBuffer=String(t)}}flush(){let n=this.stringBuffer;return this.stringBuffer="",n}}class oM{codecSerializer;stringSerializer;buffer;constructor(n,t,i=new qu(t)){this.codecSerializer=n,this.stringSerializer=i}setSerdeContext(n){this.codecSerializer.setSerdeContext(n),this.stringSerializer.setSerdeContext(n)}write(n,t){let i=$t.of(n),s=i.getMergedTraits();if(s.httpHeader||s.httpLabel||s.httpQuery){this.stringSerializer.write(i,t),this.buffer=this.stringSerializer.flush();return}return this.codecSerializer.write(i,t)}flush(){if(this.buffer!==void 0){let n=this.buffer;return this.buffer=void 0,n}return this.codecSerializer.flush()}}class fM{name;kind;values;constructor({name:n,kind:t=yB.HEADER,values:i=[]}){this.name=n,this.kind=t,this.values=i}add(n){this.values.push(n)}set(n){this.values=n}remove(n){this.values=this.values.filter((t)=>t!==n)}toString(){return this.values.map((n)=>n.includes(",")||n.includes(" ")?`"${n}"`:n).join(", ")}get(){return this.values}}class hM{entries={};encoding;constructor({fields:n=[],encoding:t="utf-8"}){n.forEach(this.setField.bind(this)),this.encoding=t}setField(n){this.entries[n.name.toLowerCase()]=n}getField(n){return this.entries[n.toLowerCase()]}removeField(n){delete this.entries[n.toLowerCase()]}getByType(n){return Object.values(this.entries).filter((t)=>t.kind===n)}}var gB=(n)=>{return{setHttpHandler(t){n.httpHandler=t},httpHandler(){return n.httpHandler},updateHttpClientConfig(t,i){n.httpHandler?.updateHttpClientConfig(t,i)},httpHandlerConfigs(){return n.httpHandler.httpHandlerConfigs()}}},SB=(n)=>{return{httpHandler:n.httpHandler()}},jA="content-length";function uM(n){return(t)=>async(i)=>{let s=i.request;if(Js.isInstance(s)){let{body:r,headers:e}=s;if(r&&Object.keys(e).map((f)=>f.toLowerCase()).indexOf(jA)===-1)try{let f=n(r);s.headers={...s.headers,[jA]:String(f)}}catch(f){}}return t({...i,request:s})}}var cM={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},IB=(n)=>({applyToStack:(t)=>{t.add(uM(n.bodyLengthChecker),cM)}}),kr=(n)=>encodeURIComponent(n).replace(/[!'()*]/g,UB),UB=(n)=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`,bB=(n)=>n.split("/").map(kr).join("/");function $B(n){let t=[];for(let i of Object.keys(n).sort()){let s=n[i];if(i=kr(i),Array.isArray(s))for(let r=0,e=s.length;r<e;r++)t.push(`${i}=${kr(s[r])}`);else{let r=i;if(s||typeof s==="string")r+=`=${kr(s)}`;t.push(r)}}return t.join("&")}LB.Field=fM;LB.Fields=hM;LB.FromStringShapeDeserializer=ku;LB.HttpBindingProtocol=iM;LB.HttpInterceptingShapeDeserializer=eM;LB.HttpInterceptingShapeSerializer=oM;LB.HttpProtocol=Lo;LB.RequestBuilder=xu;LB.RpcProtocol=sM;LB.SerdeContext=Xs;LB.ToStringShapeSerializer=qu;LB.buildQueryString=$B;LB.collectBody=Qi;LB.contentLengthMiddleware=uM;LB.contentLengthMiddlewareOptions=cM;LB.determineTimestampFormat=Ku;LB.escapeUri=kr;LB.escapeUriPath=bB;LB.extendedEncodeURIComponent=qr;LB.getContentLengthPlugin=IB;LB.getHttpHandlerExtensionConfiguration=gB;LB.requestBuilder=TB;LB.resolveHttpHandlerRuntimeConfig=SB;LB.resolvedPath=rM});var Zr=k(($N)=>{var{Readable:sN}=p("stream"),{NoOpLogger:rN,normalizeProvider:_M}=Xt(),{HttpResponse:wM,HttpRequest:Bo}=Jn(),{parseRfc7231DateTime:eN,v4:lM}=mn(),AM=(n)=>n?.body instanceof sN||typeof ReadableStream<"u"&&n?.body instanceof ReadableStream,oN=["AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"],fN=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],hN=["TimeoutError","RequestTimeout","RequestTimeoutException"],uN=[500,502,503,504],cN=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],_N=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],vu=(n)=>n?.$retryable!==void 0,MM=(n)=>oN.includes(n.name),dM=(n)=>n.$metadata?.clockSkewCorrected,RM=(n)=>{let t=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);if(!(n&&n instanceof TypeError))return!1;return t.has(n.message)},jr=(n)=>n.$metadata?.httpStatusCode===429||fN.includes(n.name)||n.$retryable?.throttling==!0,ar=(n,t=0)=>vu(n)||dM(n)||n.name==="InvalidSignatureException"&&n.message?.includes("Signature expired")||hN.includes(n.name)||cN.includes(n?.code||"")||_N.includes(n?.code||"")||uN.includes(n.$metadata?.httpStatusCode||0)||RM(n)||yM(n)||n.cause!==void 0&&t<=10&&ar(n.cause,t+1),EM=(n)=>{if(n.$metadata?.httpStatusCode!==void 0){let t=n.$metadata.httpStatusCode;if(500<=t&&t<=599&&!ar(n))return!0;return!1}return!1};function yM(n){return n.code==="ERR_HTTP2_STREAM_ERROR"&&n.message.includes("NGHTTP2_REFUSED_STREAM")}var TM=100,Go=20000,gM=500,No=500,SM=5,IM=10,Zu=1,Ho="amz-sdk-invocation-id",Wo="amz-sdk-request";function UM(n,t){if(!wM.isInstance(n))return;for(let i of Object.keys(n.headers)){let s=i.toLowerCase();if(s==="retry-after"){let r=n.headers[i],e=NaN;if(r.endsWith("GMT"))try{e=(eN(r).getTime()-Date.now())/1000}catch(f){t?.trace?.("Failed to parse retry-after header"),t?.trace?.(f)}else if(r.match(/ GMT, ((\d+)|(\d+\.\d+))$/))e=Number(r.match(/ GMT, ([\d.]+)$/)?.[1]);else if(r.match(/^((\d+)|(\d+\.\d+))$/))e=Number(r);else if(Date.parse(r)>=Date.now())e=(Date.parse(r)-Date.now())/1000;if(isNaN(e))return;return new Date(Date.now()+e*1000)}else if(s==="x-amz-retry-after"){let r=n.headers[i],e=Number(r);if(isNaN(e)){t?.trace?.(`Failed to parse x-amz-retry-after=${r}`);return}return new Date(Date.now()+e)}}}function wN(n,t){return UM(n,t)}var bM=(n)=>{if(n instanceof Error)return n;if(n instanceof Object)return Object.assign(Error(),n);if(typeof n==="string")return Error(n);return Error(`AWS SDK error wrapper for ${n}`)};function $M(n){return(t)=>(i,s)=>async(r)=>{let e=await t.retryStrategy(),f=await t.maxAttempts();if(AN(e)){e=e;let o=await e.acquireInitialRetryToken((s.partition_id??"")+(s.__retryLongPoll?":longpoll":"")),h=Error(),u=0,c=0,{request:_}=r,w=Bo.isInstance(_);if(w)_.headers[Ho]=lM();while(!0)try{if(w)_.headers[Wo]=`attempt=${u+1}; max=${f}`;let{response:l,output:A}=await i(r);return e.recordSuccess(o),A.$metadata.attempts=u+1,A.$metadata.totalRetryDelay=c,{response:l,output:A}}catch(l){let A=MN(l,t.logger);if(h=bM(l),w&&n(_))throw(s.logger instanceof rN?console:s.logger)?.warn("An error was encountered in a non-retryable streaming request."),h;try{o=await e.refreshRetryTokenForRetry(o,A)}catch(E){if(!h.$metadata)h.$metadata={};throw h.$metadata.attempts=u+1,h.$metadata.totalRetryDelay=c,h}u=o.getRetryCount();let d=o.getRetryDelay();if(c+=(o?.$retryLog?.acquisitionDelay??0)+d,d>0)await lN(d)}}else{if(e=e,e?.mode)s.userAgent=[...s.userAgent||[],["cfg/retry-mode",e.mode]];return e.retry(i,r)}}}var lN=(n)=>new Promise((t)=>setTimeout(t,n)),AN=(n)=>typeof n.acquireInitialRetryToken<"u"&&typeof n.refreshRetryTokenForRetry<"u"&&typeof n.recordSuccess<"u",MN=(n,t)=>{let i={error:n,errorType:dN(n)},s=UM(n.$response,t);if(s)i.retryAfterHint=s;return i},dN=(n)=>{if(jr(n))return"THROTTLING";if(ar(n))return"TRANSIENT";if(EM(n))return"SERVER_ERROR";return"CLIENT_ERROR"},LM={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function RN(n){let t=$M(n);return(i)=>({applyToStack:(s)=>{s.add(t(i),LM)}})}class vr{static setTimeoutFn=(n,t)=>setTimeout(n,t);beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(n){this.beta=n?.beta??0.7,this.minCapacity=n?.minCapacity??1,this.minFillRate=n?.minFillRate??0.5,this.scaleConstant=n?.scaleConstant??0.4,this.smooth=n?.smooth??0.8,this.lastThrottleTime=this.getCurrentTimeInSeconds(),this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}async getSendToken(){return this.acquireTokenBucket(1)}updateClientSendingRate(n){let t;this.updateMeasuredRate();let i=n;if(i?.errorType==="THROTTLING"||jr(i?.error??n)){let e=!this.enabled?this.measuredTxRate:Math.min(this.measuredTxRate,this.fillRate);this.lastMaxRate=e,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),t=this.cubicThrottle(e),this.enableTokenBucket()}else this.calculateTimeWindow(),t=this.cubicSuccess(this.getCurrentTimeInSeconds());let r=Math.min(t,2*this.measuredTxRate);this.updateTokenBucketRate(r)}getCurrentTimeInSeconds(){return Date.now()/1000}async acquireTokenBucket(n){if(!this.enabled)return;this.refillTokenBucket();while(n>this.availableTokens){let t=(n-this.availableTokens)/this.fillRate*1000;await new Promise((i)=>vr.setTimeoutFn(i,t)),this.refillTokenBucket()}this.availableTokens=this.availableTokens-n}refillTokenBucket(){let n=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=n;return}let t=(n-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+t),this.lastTimestamp=n}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,0.3333333333333333))}cubicThrottle(n){return this.getPrecise(n*this.beta)}cubicSuccess(n){return this.getPrecise(this.scaleConstant*Math.pow(n-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(n){this.refillTokenBucket(),this.fillRate=Math.max(n,this.minFillRate),this.maxCapacity=Math.max(n,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){let n=this.getCurrentTimeInSeconds(),t=Math.floor(n*2)/2;if(this.requestCount++,t>this.lastTxRateBucket){let i=this.requestCount/(t-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(i*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=t}}getPrecise(n){return parseFloat(n.toFixed(8))}}class Un{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return Un.v2026?50:100}static throttlingDelay(){return Un.v2026?1000:500}static cost(){return Un.v2026?14:5}static throttlingCost(){return Un.v2026?5:10}static modifiedCostType(){return Un.v2026?"THROTTLING":"TRANSIENT"}}class OM{x=Un.delay();computeNextBackoffDelay(n){let t=Math.random(),i=2,s=t*Math.min(this.x*2**n,Go);return Math.floor(s)}setDelayBase(n){this.x=n}}class Vu{delay;count;cost;longPoll;$retryLog={acquisitionDelay:0};constructor(n,t,i,s){this.delay=n,this.count=t,this.cost=i,this.longPoll=s}getRetryCount(){return this.count}getRetryDelay(){return Math.min(Go,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var xt;(function(n){n.STANDARD="standard",n.ADAPTIVE="adaptive"})(xt||(xt={}));var Ci=3,BM=xt.STANDARD,Oo={incompatible:1,attempts:2,capacity:3},Vr=class{mode=xt.STANDARD;retryBackoffStrategy;capacity=No;maxAttemptsProvider;baseDelay;constructor(t){if(typeof t==="number")this.maxAttemptsProvider=async()=>t;else if(typeof t==="function")this.maxAttemptsProvider=t;else if(t&&typeof t==="object")this.maxAttemptsProvider=async()=>t.maxAttempts,this.baseDelay=t.baseDelay,this.retryBackoffStrategy=t.backoff;this.maxAttemptsProvider??=async()=>Ci,this.baseDelay??=Un.delay(),this.retryBackoffStrategy??=new OM}async acquireInitialRetryToken(t){return new Vu(Un.delay(),0,void 0,Un.v2026&&t.includes(":longpoll"))}async refreshRetryTokenForRetry(t,i){let s=await this.getMaxAttempts(),r=this.retryCode(t,i,s),e=r===0,f=t.isLongPoll?.();if(e||f){let o=i.errorType;this.retryBackoffStrategy.setDelayBase(o==="THROTTLING"?Un.throttlingDelay():this.baseDelay);let h=this.retryBackoffStrategy.computeNextBackoffDelay(t.getRetryCount()),u=h;if(i.retryAfterHint instanceof Date)u=Math.max(h,Math.min(i.retryAfterHint.getTime()-Date.now(),h+5000));if(!e){let c=Un.v2026&&r===Oo.capacity&&f?u:0;if(c>0)await new Promise((_)=>setTimeout(_,c))}else{let c=this.getCapacityCost(o);this.capacity-=c;let _=new Vu(0,t.getRetryCount()+1,c,t.isLongPoll?.()??!1);return await new Promise((w)=>setTimeout(w,u)),_.$retryLog.acquisitionDelay=u,_}}throw Error("No retry token available")}recordSuccess(t){this.capacity=Math.min(No,this.capacity+(t.getRetryCost()??Zu))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(t){return console.warn(`Max attempts provider could not resolve. Using default of ${Ci}`),Ci}}retryCode(t,i,s){let r=t.getRetryCount()+1,e=this.isRetryableError(i.errorType)?0:Oo.incompatible,f=r<s?0:Oo.attempts,o=this.capacity>=this.getCapacityCost(i.errorType)?0:Oo.capacity;return e||f||o}getCapacityCost(t){return t===Un.modifiedCostType()?Un.throttlingCost():Un.cost()}isRetryableError(t){return t==="THROTTLING"||t==="TRANSIENT"}},NM=class{mode=xt.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(t,i){let{rateLimiter:s}=i??{};this.rateLimiter=s??new vr,this.standardRetryStrategy=i?new Vr({maxAttempts:typeof t==="number"?t:3,...i}):new Vr(t)}async acquireInitialRetryToken(t){let i=await this.standardRetryStrategy.acquireInitialRetryToken(t);return await this.rateLimiter.getSendToken(),i}async refreshRetryTokenForRetry(t,i){this.rateLimiter.updateClientSendingRate(i);let s=await this.standardRetryStrategy.refreshRetryTokenForRetry(t,i);return await this.rateLimiter.getSendToken(),s}recordSuccess(t){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(t)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}};class GM extends Vr{computeNextBackoffDelay;constructor(n,t=Un.delay()){super(typeof n==="function"?n:async()=>n);if(typeof t==="number")this.computeNextBackoffDelay=()=>t;else this.computeNextBackoffDelay=t;this.retryBackoffStrategy.computeNextBackoffDelay=(i)=>{let s=i+1;return this.computeNextBackoffDelay(s)}}}var EN=(n,t)=>{let i=n,s=Zu,r=SM,e=IM,f=n,o=(_)=>_.name==="TimeoutError"?e:r,h=(_)=>o(_)<=f;return Object.freeze({hasRetryTokens:h,retrieveRetryTokens:(_)=>{if(!h(_))throw Error("No retry token available");let w=o(_);return f-=w,w},releaseRetryTokens:(_)=>{f+=_??s,f=Math.min(f,i)}})},HM=(n,t)=>Math.floor(Math.min(Go,Math.random()*2**t*n)),WM=(n)=>{if(!n)return!1;return vu(n)||MM(n)||jr(n)||ar(n)};class pu{maxAttemptsProvider;retryDecider;delayDecider;retryQuota;mode=xt.STANDARD;constructor(n,t){this.maxAttemptsProvider=n,this.retryDecider=t?.retryDecider??WM,this.delayDecider=t?.delayDecider??HM,this.retryQuota=t?.retryQuota??EN(No)}shouldRetry(n,t,i){return t<i&&this.retryDecider(n)&&this.retryQuota.hasRetryTokens(n)}async getMaxAttempts(){let n;try{n=await this.maxAttemptsProvider()}catch(t){n=Ci}return n}async retry(n,t,i){let s,r=0,e=0,f=await this.getMaxAttempts(),{request:o}=t;if(Bo.isInstance(o))o.headers[Ho]=lM();while(!0)try{if(Bo.isInstance(o))o.headers[Wo]=`attempt=${r+1}; max=${f}`;if(i?.beforeRequest)await i.beforeRequest();let{response:h,output:u}=await n(t);if(i?.afterRequest)i.afterRequest(h);return this.retryQuota.releaseRetryTokens(s),u.$metadata.attempts=r+1,u.$metadata.totalRetryDelay=e,{response:h,output:u}}catch(h){let u=bM(h);if(r++,this.shouldRetry(u,r,f)){s=this.retryQuota.retrieveRetryTokens(u);let c=this.delayDecider(jr(u)?gM:TM,r),_=yN(u.$response),w=Math.max(_||0,c);e+=w,await new Promise((l)=>setTimeout(l,w));continue}if(!u.$metadata)u.$metadata={};throw u.$metadata.attempts=r,u.$metadata.totalRetryDelay=e,u}}}var yN=(n)=>{if(!wM.isInstance(n))return;let t=Object.keys(n.headers).find((e)=>e.toLowerCase()==="retry-after");if(!t)return;let i=n.headers[t],s=Number(i);if(!Number.isNaN(s))return Math.min(s*1000,20000);let r=new Date(i);return Math.min(r.getTime()-Date.now(),20000)};class FM extends pu{rateLimiter;constructor(n,t){let{rateLimiter:i,...s}=t??{};super(n,s);this.rateLimiter=i??new vr,this.mode=xt.ADAPTIVE}async retry(n,t){return super.retry(n,t,{beforeRequest:async()=>{return this.rateLimiter.getSendToken()},afterRequest:(i)=>{this.rateLimiter.updateClientSendingRate(i)}})}}var ju="AWS_MAX_ATTEMPTS",au="max_attempts",TN={environmentVariableSelector:(n)=>{let t=n[ju];if(!t)return;let i=parseInt(t);if(Number.isNaN(i))throw Error(`Environment variable ${ju} mast be a number, got "${t}"`);return i},configFileSelector:(n)=>{let t=n[au];if(!t)return;let i=parseInt(t);if(Number.isNaN(i))throw Error(`Shared config file entry ${au} mast be a number, got "${t}"`);return i},default:Ci},gN=(n,t)=>{let{retryStrategy:i,retryMode:s}=n,{defaultMaxAttempts:r=Ci,defaultBaseDelay:e=Un.delay()}=t??{},f=_M(n.maxAttempts??r),o=i?Promise.resolve(i):void 0,h=async()=>{let u=await f();if(await _M(s)()===xt.ADAPTIVE)return new NM(f,{maxAttempts:u,baseDelay:e});return new Vr({maxAttempts:u,baseDelay:e})};return Object.assign(n,{maxAttempts:f,retryStrategy:()=>o??=h()})},PM="AWS_RETRY_MODE",DM="retry_mode",SN={environmentVariableSelector:(n)=>n[PM],configFileSelector:(n)=>n[DM],default:BM},YM=()=>(n)=>async(t)=>{let{request:i}=t;if(Bo.isInstance(i))delete i.headers[Ho],delete i.headers[Wo];return n(t)},mM={name:"omitRetryHeadersMiddleware",tags:["RETRY","HEADERS","OMIT_RETRY_HEADERS"],relation:"before",toMiddleware:"awsAuthMiddleware",override:!0},IN=(n)=>({applyToStack:(t)=>{t.addRelativeTo(YM(),mM)}}),UN=$M(AM),bN=RN(AM);$N.AdaptiveRetryStrategy=NM;$N.CONFIG_MAX_ATTEMPTS=au;$N.CONFIG_RETRY_MODE=DM;$N.ConfiguredRetryStrategy=GM;$N.DEFAULT_MAX_ATTEMPTS=Ci;$N.DEFAULT_RETRY_DELAY_BASE=TM;$N.DEFAULT_RETRY_MODE=BM;$N.DefaultRateLimiter=vr;$N.DeprecatedAdaptiveRetryStrategy=FM;$N.DeprecatedStandardRetryStrategy=pu;$N.ENV_MAX_ATTEMPTS=ju;$N.ENV_RETRY_MODE=PM;$N.INITIAL_RETRY_TOKENS=No;$N.INVOCATION_ID_HEADER=Ho;$N.MAXIMUM_RETRY_DELAY=Go;$N.NODE_MAX_ATTEMPT_CONFIG_OPTIONS=TN;$N.NODE_RETRY_MODE_CONFIG_OPTIONS=SN;$N.NO_RETRY_INCREMENT=Zu;$N.REQUEST_HEADER=Wo;$N.RETRY_COST=SM;$N.RETRY_MODES=xt;$N.Retry=Un;$N.StandardRetryStrategy=Vr;$N.THROTTLING_RETRY_DELAY_BASE=gM;$N.TIMEOUT_RETRY_COST=IM;$N.defaultDelayDecider=HM;$N.defaultRetryDecider=WM;$N.getOmitRetryHeadersPlugin=IN;$N.getRetryAfterHint=wN;$N.getRetryPlugin=bN;$N.isBrowserNetworkError=RM;$N.isClockSkewCorrectedError=dM;$N.isClockSkewError=MM;$N.isNodeJsHttp2TransientError=yM;$N.isRetryableByTrait=vu;$N.isServerError=EM;$N.isThrottlingError=jr;$N.isTransientError=ar;$N.omitRetryHeadersMiddleware=YM;$N.omitRetryHeadersMiddlewareOptions=mM;$N.resolveRetryConfig=gN;$N.retryMiddleware=UN;$N.retryMiddlewareOptions=LM});var XM=k((dG)=>{var ci={REQUEST_ID:Symbol.for("_AWS_LAMBDA_REQUEST_ID"),X_RAY_TRACE_ID:Symbol.for("_AWS_LAMBDA_X_RAY_TRACE_ID"),TENANT_ID:Symbol.for("_AWS_LAMBDA_TENANT_ID"),TRACEPARENT:Symbol.for("_AWS_LAMBDA_TRACEPARENT"),TRACESTATE:Symbol.for("_AWS_LAMBDA_TRACESTATE"),BAGGAGE:Symbol.for("_AWS_LAMBDA_BAGGAGE")},nc=["true","1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA??"");if(!nc)globalThis.awslambda=globalThis.awslambda||{};class Fo{static PROTECTED_KEYS=ci;isProtectedKey(n){return Object.values(ci).includes(n)}getRequestId(){return this.get(ci.REQUEST_ID)??"-"}getXRayTraceId(){return this.get(ci.X_RAY_TRACE_ID)}getTenantId(){return this.get(ci.TENANT_ID)}getTraceparent(){return this.get(ci.TRACEPARENT)}getTracestate(){return this.get(ci.TRACESTATE)}getBaggage(){return this.get(ci.BAGGAGE)}}class JM extends Fo{currentContext;getContext(){return this.currentContext}hasContext(){return this.currentContext!==void 0}get(n){return this.currentContext?.[n]}set(n,t){if(this.isProtectedKey(n))throw Error(`Cannot modify protected Lambda context field: ${String(n)}`);this.currentContext=this.currentContext||{},this.currentContext[n]=t}run(n,t){return this.currentContext=n,t()}}class ic extends Fo{als;static async create(){let n=new ic,t=await import("async_hooks");return n.als=new t.AsyncLocalStorage,n}getContext(){return this.als.getStore()}hasContext(){return this.als.getStore()!==void 0}get(n){return this.als.getStore()?.[n]}set(n,t){if(this.isProtectedKey(n))throw Error(`Cannot modify protected Lambda context field: ${String(n)}`);let i=this.als.getStore();if(!i)throw Error("No context available");i[n]=t}run(n,t){return this.als.run(n,t)}}dG.InvokeStore=void 0;(function(n){let t=null;async function i(s){if(!t)t=(async()=>{let e=s===!0||"AWS_LAMBDA_MAX_CONCURRENCY"in process.env?await ic.create():new JM;if(!nc&&globalThis.awslambda?.InvokeStore)return globalThis.awslambda.InvokeStore;else if(!nc&&globalThis.awslambda)return globalThis.awslambda.InvokeStore=e,e;else return e})();return t}n.getInstanceAsync=i,n._testing=process.env.AWS_LAMBDA_BENCHMARK_MODE==="1"?{reset:()=>{if(t=null,globalThis.awslambda?.InvokeStore)delete globalThis.awslambda.InvokeStore;globalThis.awslambda={InvokeStore:void 0}}}:void 0})(dG.InvokeStore||(dG.InvokeStore={}));dG.InvokeStoreBase=Fo});var _i=k((WG)=>{var{getSmithyContext:sc}=St();WG.getSmithyContext=sc;var{HttpRequest:rc}=Jn(),{requestBuilder:EG}=Jn();WG.requestBuilder=EG;var{HttpApiKeyAuthLocation:zM}=Di(),yG=(n,t)=>{if(!t||t.length===0)return n;let i=[];for(let s of t)for(let r of n)if(r.schemeId.split("#")[1]===s)i.push(r);for(let s of n)if(!i.find(({schemeId:r})=>r===s.schemeId))i.push(s);return i};function TG(n){let t=new Map;for(let i of n)t.set(i.schemeId,i);return t}var ec=(n,t)=>(i,s)=>async(r)=>{let e=n.httpAuthSchemeProvider(await t.httpAuthSchemeParametersProvider(n,s,r.input)),f=n.authSchemePreference?await n.authSchemePreference():[],o=yG(e,f),h=TG(n.httpAuthSchemes),u=sc(s),c=[];for(let _ of o){let w=h.get(_.schemeId);if(!w){c.push(`HttpAuthScheme \`${_.schemeId}\` was not enabled for this service.`);continue}let l=w.identityProvider(await t.identityProviderConfigProvider(n));if(!l){c.push(`HttpAuthScheme \`${_.schemeId}\` did not have an IdentityProvider configured.`);continue}let{identityProperties:A={},signingProperties:d={}}=_.propertiesExtractor?.(n,s)||{};_.identityProperties=Object.assign(_.identityProperties||{},A),_.signingProperties=Object.assign(_.signingProperties||{},d),u.selectedHttpAuthScheme={httpAuthOption:_,identity:await l(_.identityProperties),signer:w.signer};break}if(!u.selectedHttpAuthScheme)throw Error(c.join(`
|
|
24
|
-
`));return i(r)},QM={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},gG=(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i})=>({applyToStack:(s)=>{s.addRelativeTo(ec(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i}),QM)}}),CM={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"serializerMiddleware"},SG=(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i})=>({applyToStack:(s)=>{s.addRelativeTo(ec(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i}),CM)}}),IG=(n)=>(t)=>{throw t},UG=(n,t)=>{},xM=(n)=>(t,i)=>async(s)=>{if(!rc.isInstance(s.request))return t(s);let e=sc(i).selectedHttpAuthScheme;if(!e)throw Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:f={}},identity:o,signer:h}=e,u=await t({...s,request:await h.sign(s.request,o,f)}).catch((h.errorHandler||IG)(f));return(h.successHandler||UG)(u.response,f),u},KM={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},bG=(n)=>({applyToStack:(t)=>{t.addRelativeTo(xM(),KM)}}),$G=(n)=>{if(typeof n==="function")return n;let t=Promise.resolve(n);return()=>t},LG=async(n,t,i,s=(e)=>e,...r)=>{let e=new n(i);return e=s(e)??e,await t.send(e,...r)};function OG(n,t,i,s,r){return async function*(f,o,...h){let u=o,c=f.startingToken??u[i],_=!0,w;while(_){if(u[i]=c,r)u[r]=u[r]??f.pageSize;if(f.client instanceof n)w=await LG(t,f.client,o,f.withCommand,...h);else throw Error(`Invalid client, expected instance of ${n.name}`);yield w;let l=c;c=BG(w,s),_=!!(c&&(!f.stopOnSameToken||c!==l))}return}}var BG=(n,t)=>{let i=n,s=t.split(".");for(let r of s){if(!i||typeof i!=="object")return;i=i[r]}return i};function NG(n,t,i){if(!n.__smithy_context)n.__smithy_context={features:{}};else if(!n.__smithy_context.features)n.__smithy_context.features={};n.__smithy_context.features[t]=i}class kM{authSchemes=new Map;constructor(n){for(let t in n){let i=n[t];if(i!==void 0)this.authSchemes.set(t,i)}}getIdentityProvider(n){return this.authSchemes.get(n)}}class qM{async sign(n,t,i){if(!i)throw Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing");if(!i.name)throw Error("request could not be signed with `apiKey` since the `name` signer property is missing");if(!i.in)throw Error("request could not be signed with `apiKey` since the `in` signer property is missing");if(!t.apiKey)throw Error("request could not be signed with `apiKey` since the `apiKey` is not defined");let s=rc.clone(n);if(i.in===zM.QUERY)s.query[i.name]=t.apiKey;else if(i.in===zM.HEADER)s.headers[i.name]=i.scheme?`${i.scheme} ${t.apiKey}`:t.apiKey;else throw Error("request can only be signed with `apiKey` locations `query` or `header`, but found: `"+i.in+"`");return s}}class VM{async sign(n,t,i){let s=rc.clone(n);if(!t.token)throw Error("request could not be signed with `token` since the `token` is not defined");return s.headers.Authorization=`Bearer ${t.token}`,s}}class jM{async sign(n,t,i){return n}}var aM=(n)=>function(i){return ZM(i)&&i.expiration.getTime()-Date.now()<n},vM=300000,GG=aM(vM),ZM=(n)=>n.expiration!==void 0,HG=(n,t,i)=>{if(n===void 0)return;let s=typeof n!=="function"?async()=>Promise.resolve(n):n,r,e,f,o=!1,h=async(u)=>{if(!e)e=s(u);try{r=await e,f=!0,o=!1}finally{e=void 0}return r};if(t===void 0)return async(u)=>{if(!f||u?.forceRefresh)r=await h(u);return r};return async(u)=>{if(!f||u?.forceRefresh)r=await h(u);if(o)return r;if(!i(r))return o=!0,r;if(t(r))return await h(u),r;return r}};WG.DefaultIdentityProviderConfig=kM;WG.EXPIRATION_MS=vM;WG.HttpApiKeyAuthSigner=qM;WG.HttpBearerAuthSigner=VM;WG.NoAuthSigner=jM;WG.createIsIdentityExpiredFunction=aM;WG.createPaginator=OG;WG.doesIdentityRequireRefresh=ZM;WG.getHttpAuthSchemeEndpointRuleSetPlugin=gG;WG.getHttpAuthSchemePlugin=SG;WG.getHttpSigningPlugin=bG;WG.httpAuthSchemeEndpointRuleSetMiddlewareOptions=QM;WG.httpAuthSchemeMiddleware=ec;WG.httpAuthSchemeMiddlewareOptions=CM;WG.httpSigningMiddleware=xM;WG.httpSigningMiddlewareOptions=KM;WG.isIdentityExpired=GG;WG.memoizeIdentityProvider=HG;WG.normalizeProvider=$G;WG.setFeature=NG});var pM=k((pr,oc)=>{(function(n,t){typeof pr=="object"&&typeof oc=="object"?oc.exports=t():typeof define=="function"&&define.amd?define([],t):typeof pr=="object"?pr.bowser=t():n.bowser=t()})(pr,function(){return function(n){var t={};function i(s){if(t[s])return t[s].exports;var r=t[s]={i:s,l:!1,exports:{}};return n[s].call(r.exports,r,r.exports,i),r.l=!0,r.exports}return i.m=n,i.c=t,i.d=function(s,r,e){i.o(s,r)||Object.defineProperty(s,r,{enumerable:!0,get:e})},i.r=function(s){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(s,"__esModule",{value:!0})},i.t=function(s,r){if(1&r&&(s=i(s)),8&r)return s;if(4&r&&typeof s=="object"&&s&&s.__esModule)return s;var e=Object.create(null);if(i.r(e),Object.defineProperty(e,"default",{enumerable:!0,value:s}),2&r&&typeof s!="string")for(var f in s)i.d(e,f,function(o){return s[o]}.bind(null,f));return e},i.n=function(s){var r=s&&s.__esModule?function(){return s.default}:function(){return s};return i.d(r,"a",r),r},i.o=function(s,r){return Object.prototype.hasOwnProperty.call(s,r)},i.p="",i(i.s=90)}({17:function(n,t,i){t.__esModule=!0,t.default=void 0;var s=i(18),r=function(){function e(){}return e.getFirstMatch=function(f,o){var h=o.match(f);return h&&h.length>0&&h[1]||""},e.getSecondMatch=function(f,o){var h=o.match(f);return h&&h.length>1&&h[2]||""},e.matchAndReturnConst=function(f,o,h){if(f.test(o))return h},e.getWindowsVersionName=function(f){switch(f){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},e.getMacOSVersionName=function(f){var o=f.split(".").splice(0,2).map(function(c){return parseInt(c,10)||0});o.push(0);var h=o[0],u=o[1];if(h===10)switch(u){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}switch(h){case 11:return"Big Sur";case 12:return"Monterey";case 13:return"Ventura";case 14:return"Sonoma";case 15:return"Sequoia";default:return}},e.getAndroidVersionName=function(f){var o=f.split(".").splice(0,2).map(function(h){return parseInt(h,10)||0});if(o.push(0),!(o[0]===1&&o[1]<5))return o[0]===1&&o[1]<6?"Cupcake":o[0]===1&&o[1]>=6?"Donut":o[0]===2&&o[1]<2?"Eclair":o[0]===2&&o[1]===2?"Froyo":o[0]===2&&o[1]>2?"Gingerbread":o[0]===3?"Honeycomb":o[0]===4&&o[1]<1?"Ice Cream Sandwich":o[0]===4&&o[1]<4?"Jelly Bean":o[0]===4&&o[1]>=4?"KitKat":o[0]===5?"Lollipop":o[0]===6?"Marshmallow":o[0]===7?"Nougat":o[0]===8?"Oreo":o[0]===9?"Pie":void 0},e.getVersionPrecision=function(f){return f.split(".").length},e.compareVersions=function(f,o,h){h===void 0&&(h=!1);var u=e.getVersionPrecision(f),c=e.getVersionPrecision(o),_=Math.max(u,c),w=0,l=e.map([f,o],function(A){var d=_-e.getVersionPrecision(A),E=A+Array(d+1).join(".0");return e.map(E.split("."),function(R){return Array(20-R.length).join("0")+R}).reverse()});for(h&&(w=_-Math.min(u,c)),_-=1;_>=w;){if(l[0][_]>l[1][_])return 1;if(l[0][_]===l[1][_]){if(_===w)return 0;_-=1}else if(l[0][_]<l[1][_])return-1}},e.map=function(f,o){var h,u=[];if(Array.prototype.map)return Array.prototype.map.call(f,o);for(h=0;h<f.length;h+=1)u.push(o(f[h]));return u},e.find=function(f,o){var h,u;if(Array.prototype.find)return Array.prototype.find.call(f,o);for(h=0,u=f.length;h<u;h+=1){var c=f[h];if(o(c,h))return c}},e.assign=function(f){for(var o,h,u=f,c=arguments.length,_=Array(c>1?c-1:0),w=1;w<c;w++)_[w-1]=arguments[w];if(Object.assign)return Object.assign.apply(Object,[f].concat(_));var l=function(){var A=_[o];typeof A=="object"&&A!==null&&Object.keys(A).forEach(function(d){u[d]=A[d]})};for(o=0,h=_.length;o<h;o+=1)l();return f},e.getBrowserAlias=function(f){return s.BROWSER_ALIASES_MAP[f]},e.getBrowserTypeByAlias=function(f){return s.BROWSER_MAP[f]||""},e}();t.default=r,n.exports=t.default},18:function(n,t,i){t.__esModule=!0,t.ENGINE_MAP=t.OS_MAP=t.PLATFORMS_MAP=t.BROWSER_MAP=t.BROWSER_ALIASES_MAP=void 0,t.BROWSER_ALIASES_MAP={AmazonBot:"amazonbot","Amazon Silk":"amazon_silk","Android Browser":"android",BaiduSpider:"baiduspider",Bada:"bada",BingCrawler:"bingcrawler",Brave:"brave",BlackBerry:"blackberry","ChatGPT-User":"chatgpt_user",Chrome:"chrome",ClaudeBot:"claudebot",Chromium:"chromium",Diffbot:"diffbot",DuckDuckBot:"duckduckbot",DuckDuckGo:"duckduckgo",Electron:"electron",Epiphany:"epiphany",FacebookExternalHit:"facebookexternalhit",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot",GPTBot:"gptbot","Internet Explorer":"ie",InternetArchiveCrawler:"internetarchivecrawler","K-Meleon":"k_meleon",LibreWolf:"librewolf",Linespider:"linespider",Maxthon:"maxthon","Meta-ExternalAds":"meta_externalads","Meta-ExternalAgent":"meta_externalagent","Meta-ExternalFetcher":"meta_externalfetcher","Meta-WebIndexer":"meta_webindexer","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver","OAI-SearchBot":"oai_searchbot",Omgilibot:"omgilibot",Opera:"opera","Opera Coast":"opera_coast","Pale Moon":"pale_moon",PerplexityBot:"perplexitybot","Perplexity-User":"perplexity_user",PhantomJS:"phantomjs",PingdomBot:"pingdombot",Puffin:"puffin",QQ:"qq",QQLite:"qqlite",QupZilla:"qupzilla",Roku:"roku",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SlackBot:"slackbot",SeaMonkey:"seamonkey",Sleipnir:"sleipnir","Sogou Browser":"sogou",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat",YahooSlurp:"yahooslurp","Yandex Browser":"yandex",YandexBot:"yandexbot",YouBot:"youbot"},t.BROWSER_MAP={amazonbot:"AmazonBot",amazon_silk:"Amazon Silk",android:"Android Browser",baiduspider:"BaiduSpider",bada:"Bada",bingcrawler:"BingCrawler",blackberry:"BlackBerry",brave:"Brave",chatgpt_user:"ChatGPT-User",chrome:"Chrome",claudebot:"ClaudeBot",chromium:"Chromium",diffbot:"Diffbot",duckduckbot:"DuckDuckBot",duckduckgo:"DuckDuckGo",edge:"Microsoft Edge",electron:"Electron",epiphany:"Epiphany",facebookexternalhit:"FacebookExternalHit",firefox:"Firefox",focus:"Focus",generic:"Generic",google_search:"Google Search",googlebot:"Googlebot",gptbot:"GPTBot",ie:"Internet Explorer",internetarchivecrawler:"InternetArchiveCrawler",k_meleon:"K-Meleon",librewolf:"LibreWolf",linespider:"Linespider",maxthon:"Maxthon",meta_externalads:"Meta-ExternalAds",meta_externalagent:"Meta-ExternalAgent",meta_externalfetcher:"Meta-ExternalFetcher",meta_webindexer:"Meta-WebIndexer",mz:"MZ Browser",naver:"NAVER Whale Browser",oai_searchbot:"OAI-SearchBot",omgilibot:"Omgilibot",opera:"Opera",opera_coast:"Opera Coast",pale_moon:"Pale Moon",perplexitybot:"PerplexityBot",perplexity_user:"Perplexity-User",phantomjs:"PhantomJS",pingdombot:"PingdomBot",puffin:"Puffin",qq:"QQ Browser",qqlite:"QQ Browser Lite",qupzilla:"QupZilla",roku:"Roku",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",slackbot:"SlackBot",sleipnir:"Sleipnir",sogou:"Sogou Browser",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yahooslurp:"YahooSlurp",yandex:"Yandex Browser",yandexbot:"YandexBot",youbot:"YouBot"},t.PLATFORMS_MAP={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},t.OS_MAP={Android:"Android",Bada:"Bada",BlackBerry:"BlackBerry",ChromeOS:"Chrome OS",HarmonyOS:"HarmonyOS",iOS:"iOS",Linux:"Linux",MacOS:"macOS",PlayStation4:"PlayStation 4",Roku:"Roku",Tizen:"Tizen",WebOS:"WebOS",Windows:"Windows",WindowsPhone:"Windows Phone"},t.ENGINE_MAP={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"}},90:function(n,t,i){t.__esModule=!0,t.default=void 0;var s,r=(s=i(91))&&s.__esModule?s:{default:s},e=i(18);function f(h,u){for(var c=0;c<u.length;c++){var _=u[c];_.enumerable=_.enumerable||!1,_.configurable=!0,"value"in _&&(_.writable=!0),Object.defineProperty(h,_.key,_)}}var o=function(){function h(){}var u,c,_;return h.getParser=function(w,l,A){if(l===void 0&&(l=!1),A===void 0&&(A=null),typeof w!="string")throw Error("UserAgent should be a string");return new r.default(w,l,A)},h.parse=function(w,l){return l===void 0&&(l=null),new r.default(w,l).getResult()},u=h,_=[{key:"BROWSER_MAP",get:function(){return e.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return e.ENGINE_MAP}},{key:"OS_MAP",get:function(){return e.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return e.PLATFORMS_MAP}}],(c=null)&&f(u.prototype,c),_&&f(u,_),h}();t.default=o,n.exports=t.default},91:function(n,t,i){t.__esModule=!0,t.default=void 0;var s=h(i(92)),r=h(i(93)),e=h(i(94)),f=h(i(95)),o=h(i(17));function h(c){return c&&c.__esModule?c:{default:c}}var u=function(){function c(w,l,A){if(l===void 0&&(l=!1),A===void 0&&(A=null),w==null||w==="")throw Error("UserAgent parameter can't be empty");this._ua=w;var d=!1;typeof l=="boolean"?(d=l,this._hints=A):this._hints=l!=null&&typeof l=="object"?l:null,this.parsedResult={},d!==!0&&this.parse()}var _=c.prototype;return _.getHints=function(){return this._hints},_.hasBrand=function(w){if(!this._hints||!Array.isArray(this._hints.brands))return!1;var l=w.toLowerCase();return this._hints.brands.some(function(A){return A.brand&&A.brand.toLowerCase()===l})},_.getBrandVersion=function(w){if(this._hints&&Array.isArray(this._hints.brands)){var l=w.toLowerCase(),A=this._hints.brands.find(function(d){return d.brand&&d.brand.toLowerCase()===l});return A?A.version:void 0}},_.getUA=function(){return this._ua},_.test=function(w){return w.test(this._ua)},_.parseBrowser=function(){var w=this;this.parsedResult.browser={};var l=o.default.find(s.default,function(A){if(typeof A.test=="function")return A.test(w);if(Array.isArray(A.test))return A.test.some(function(d){return w.test(d)});throw Error("Browser's test function is not valid")});return l&&(this.parsedResult.browser=l.describe(this.getUA(),this)),this.parsedResult.browser},_.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},_.getBrowserName=function(w){return w?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},_.getBrowserVersion=function(){return this.getBrowser().version},_.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},_.parseOS=function(){var w=this;this.parsedResult.os={};var l=o.default.find(r.default,function(A){if(typeof A.test=="function")return A.test(w);if(Array.isArray(A.test))return A.test.some(function(d){return w.test(d)});throw Error("Browser's test function is not valid")});return l&&(this.parsedResult.os=l.describe(this.getUA())),this.parsedResult.os},_.getOSName=function(w){var l=this.getOS().name;return w?String(l).toLowerCase()||"":l||""},_.getOSVersion=function(){return this.getOS().version},_.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},_.getPlatformType=function(w){w===void 0&&(w=!1);var l=this.getPlatform().type;return w?String(l).toLowerCase()||"":l||""},_.parsePlatform=function(){var w=this;this.parsedResult.platform={};var l=o.default.find(e.default,function(A){if(typeof A.test=="function")return A.test(w);if(Array.isArray(A.test))return A.test.some(function(d){return w.test(d)});throw Error("Browser's test function is not valid")});return l&&(this.parsedResult.platform=l.describe(this.getUA())),this.parsedResult.platform},_.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},_.getEngineName=function(w){return w?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},_.parseEngine=function(){var w=this;this.parsedResult.engine={};var l=o.default.find(f.default,function(A){if(typeof A.test=="function")return A.test(w);if(Array.isArray(A.test))return A.test.some(function(d){return w.test(d)});throw Error("Browser's test function is not valid")});return l&&(this.parsedResult.engine=l.describe(this.getUA())),this.parsedResult.engine},_.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},_.getResult=function(){return o.default.assign({},this.parsedResult)},_.satisfies=function(w){var l=this,A={},d=0,E={},R=0;if(Object.keys(w).forEach(function(b){var $=w[b];typeof $=="string"?(E[b]=$,R+=1):typeof $=="object"&&(A[b]=$,d+=1)}),d>0){var y=Object.keys(A),T=o.default.find(y,function(b){return l.isOS(b)});if(T){var S=this.satisfies(A[T]);if(S!==void 0)return S}var I=o.default.find(y,function(b){return l.isPlatform(b)});if(I){var F=this.satisfies(A[I]);if(F!==void 0)return F}}if(R>0){var C=Object.keys(E),sn=o.default.find(C,function(b){return l.isBrowser(b,!0)});if(sn!==void 0)return this.compareVersion(E[sn])}},_.isBrowser=function(w,l){l===void 0&&(l=!1);var A=this.getBrowserName().toLowerCase(),d=w.toLowerCase(),E=o.default.getBrowserTypeByAlias(d);return l&&E&&(d=E.toLowerCase()),d===A},_.compareVersion=function(w){var l=[0],A=w,d=!1,E=this.getBrowserVersion();if(typeof E=="string")return w[0]===">"||w[0]==="<"?(A=w.substr(1),w[1]==="="?(d=!0,A=w.substr(2)):l=[],w[0]===">"?l.push(1):l.push(-1)):w[0]==="="?A=w.substr(1):w[0]==="~"&&(d=!0,A=w.substr(1)),l.indexOf(o.default.compareVersions(E,A,d))>-1},_.isOS=function(w){return this.getOSName(!0)===String(w).toLowerCase()},_.isPlatform=function(w){return this.getPlatformType(!0)===String(w).toLowerCase()},_.isEngine=function(w){return this.getEngineName(!0)===String(w).toLowerCase()},_.is=function(w,l){return l===void 0&&(l=!1),this.isBrowser(w,l)||this.isOS(w)||this.isPlatform(w)},_.some=function(w){var l=this;return w===void 0&&(w=[]),w.some(function(A){return l.is(A)})},c}();t.default=u,n.exports=t.default},92:function(n,t,i){t.__esModule=!0,t.default=void 0;var s,r=(s=i(17))&&s.__esModule?s:{default:s},e=/version\/(\d+(\.?_?\d+)+)/i,f=[{test:[/gptbot/i],describe:function(o){var h={name:"GPTBot"},u=r.default.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/chatgpt-user/i],describe:function(o){var h={name:"ChatGPT-User"},u=r.default.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/oai-searchbot/i],describe:function(o){var h={name:"OAI-SearchBot"},u=r.default.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(o){var h={name:"ClaudeBot"},u=r.default.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(o){var h={name:"Omgilibot"},u=r.default.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/diffbot/i],describe:function(o){var h={name:"Diffbot"},u=r.default.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/perplexitybot/i],describe:function(o){var h={name:"PerplexityBot"},u=r.default.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/perplexity-user/i],describe:function(o){var h={name:"Perplexity-User"},u=r.default.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/youbot/i],describe:function(o){var h={name:"YouBot"},u=r.default.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/meta-webindexer/i],describe:function(o){var h={name:"Meta-WebIndexer"},u=r.default.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/meta-externalads/i],describe:function(o){var h={name:"Meta-ExternalAds"},u=r.default.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/meta-externalagent/i],describe:function(o){var h={name:"Meta-ExternalAgent"},u=r.default.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/meta-externalfetcher/i],describe:function(o){var h={name:"Meta-ExternalFetcher"},u=r.default.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/googlebot/i],describe:function(o){var h={name:"Googlebot"},u=r.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/linespider/i],describe:function(o){var h={name:"Linespider"},u=r.default.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/amazonbot/i],describe:function(o){var h={name:"AmazonBot"},u=r.default.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/bingbot/i],describe:function(o){var h={name:"BingCrawler"},u=r.default.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/baiduspider/i],describe:function(o){var h={name:"BaiduSpider"},u=r.default.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/duckduckbot/i],describe:function(o){var h={name:"DuckDuckBot"},u=r.default.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/ia_archiver/i],describe:function(o){var h={name:"InternetArchiveCrawler"},u=r.default.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(o){var h={name:"SlackBot"},u=r.default.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/yahoo!?[\s/]*slurp/i],describe:function(){return{name:"YahooSlurp"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{name:"YandexBot"}}},{test:[/pingdom/i],describe:function(){return{name:"PingdomBot"}}},{test:[/opera/i],describe:function(o){var h={name:"Opera"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/opr\/|opios/i],describe:function(o){var h={name:"Opera"},u=r.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/SamsungBrowser/i],describe:function(o){var h={name:"Samsung Internet for Android"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/Whale/i],describe:function(o){var h={name:"NAVER Whale Browser"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/PaleMoon/i],describe:function(o){var h={name:"Pale Moon"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/MZBrowser/i],describe:function(o){var h={name:"MZ Browser"},u=r.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/focus/i],describe:function(o){var h={name:"Focus"},u=r.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/swing/i],describe:function(o){var h={name:"Swing"},u=r.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/coast/i],describe:function(o){var h={name:"Opera Coast"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(o){var h={name:"Opera Touch"},u=r.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/yabrowser/i],describe:function(o){var h={name:"Yandex Browser"},u=r.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/ucbrowser/i],describe:function(o){var h={name:"UC Browser"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/Maxthon|mxios/i],describe:function(o){var h={name:"Maxthon"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/epiphany/i],describe:function(o){var h={name:"Epiphany"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/puffin/i],describe:function(o){var h={name:"Puffin"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/sleipnir/i],describe:function(o){var h={name:"Sleipnir"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/k-meleon/i],describe:function(o){var h={name:"K-Meleon"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/micromessenger/i],describe:function(o){var h={name:"WeChat"},u=r.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/qqbrowser/i],describe:function(o){var h={name:/qqbrowserlite/i.test(o)?"QQ Browser Lite":"QQ Browser"},u=r.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/msie|trident/i],describe:function(o){var h={name:"Internet Explorer"},u=r.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/\sedg\//i],describe:function(o){var h={name:"Microsoft Edge"},u=r.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/edg([ea]|ios)/i],describe:function(o){var h={name:"Microsoft Edge"},u=r.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/vivaldi/i],describe:function(o){var h={name:"Vivaldi"},u=r.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/seamonkey/i],describe:function(o){var h={name:"SeaMonkey"},u=r.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/sailfish/i],describe:function(o){var h={name:"Sailfish"},u=r.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,o);return u&&(h.version=u),h}},{test:[/silk/i],describe:function(o){var h={name:"Amazon Silk"},u=r.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/phantom/i],describe:function(o){var h={name:"PhantomJS"},u=r.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/slimerjs/i],describe:function(o){var h={name:"SlimerJS"},u=r.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(o){var h={name:"BlackBerry"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/(web|hpw)[o0]s/i],describe:function(o){var h={name:"WebOS Browser"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/bada/i],describe:function(o){var h={name:"Bada"},u=r.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/tizen/i],describe:function(o){var h={name:"Tizen"},u=r.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/qupzilla/i],describe:function(o){var h={name:"QupZilla"},u=r.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/librewolf/i],describe:function(o){var h={name:"LibreWolf"},u=r.default.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/firefox|iceweasel|fxios/i],describe:function(o){var h={name:"Firefox"},u=r.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/electron/i],describe:function(o){var h={name:"Electron"},u=r.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe:function(o){var h={name:"Sogou Browser"},u=r.default.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,o),c=r.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,o),_=r.default.getFirstMatch(/se ([\d.]+)x/i,o),w=u||c||_;return w&&(h.version=w),h}},{test:[/MiuiBrowser/i],describe:function(o){var h={name:"Miui"},u=r.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:function(o){return!!o.hasBrand("DuckDuckGo")||o.test(/\sDdg\/[\d.]+$/i)},describe:function(o,h){var u={name:"DuckDuckGo"};if(h){var c=h.getBrandVersion("DuckDuckGo");if(c)return u.version=c,u}var _=r.default.getFirstMatch(/\sDdg\/([\d.]+)$/i,o);return _&&(u.version=_),u}},{test:function(o){return o.hasBrand("Brave")},describe:function(o,h){var u={name:"Brave"};if(h){var c=h.getBrandVersion("Brave");if(c)return u.version=c,u}return u}},{test:[/chromium/i],describe:function(o){var h={name:"Chromium"},u=r.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/chrome|crios|crmo/i],describe:function(o){var h={name:"Chrome"},u=r.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/GSA/i],describe:function(o){var h={name:"Google Search"},u=r.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:function(o){var h=!o.test(/like android/i),u=o.test(/android/i);return h&&u},describe:function(o){var h={name:"Android Browser"},u=r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/playstation 4/i],describe:function(o){var h={name:"PlayStation 4"},u=r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/safari|applewebkit/i],describe:function(o){var h={name:"Safari"},u=r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/.*/i],describe:function(o){var h=o.search("\\(")!==-1?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:r.default.getFirstMatch(h,o),version:r.default.getSecondMatch(h,o)}}}];t.default=f,n.exports=t.default},93:function(n,t,i){t.__esModule=!0,t.default=void 0;var s,r=(s=i(17))&&s.__esModule?s:{default:s},e=i(18),f=[{test:[/Roku\/DVP/],describe:function(o){var h=r.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,o);return{name:e.OS_MAP.Roku,version:h}}},{test:[/windows phone/i],describe:function(o){var h=r.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.WindowsPhone,version:h}}},{test:[/windows /i],describe:function(o){var h=r.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,o),u=r.default.getWindowsVersionName(h);return{name:e.OS_MAP.Windows,version:h,versionName:u}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(o){var h={name:e.OS_MAP.iOS},u=r.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,o);return u&&(h.version=u),h}},{test:[/macintosh/i],describe:function(o){var h=r.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,o).replace(/[_\s]/g,"."),u=r.default.getMacOSVersionName(h),c={name:e.OS_MAP.MacOS,version:h};return u&&(c.versionName=u),c}},{test:[/(ipod|iphone|ipad)/i],describe:function(o){var h=r.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,o).replace(/[_\s]/g,".");return{name:e.OS_MAP.iOS,version:h}}},{test:[/OpenHarmony/i],describe:function(o){var h=r.default.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.HarmonyOS,version:h}}},{test:function(o){var h=!o.test(/like android/i),u=o.test(/android/i);return h&&u},describe:function(o){var h=r.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,o),u=r.default.getAndroidVersionName(h),c={name:e.OS_MAP.Android,version:h};return u&&(c.versionName=u),c}},{test:[/(web|hpw)[o0]s/i],describe:function(o){var h=r.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,o),u={name:e.OS_MAP.WebOS};return h&&h.length&&(u.version=h),u}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(o){var h=r.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,o)||r.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,o)||r.default.getFirstMatch(/\bbb(\d+)/i,o);return{name:e.OS_MAP.BlackBerry,version:h}}},{test:[/bada/i],describe:function(o){var h=r.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.Bada,version:h}}},{test:[/tizen/i],describe:function(o){var h=r.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.Tizen,version:h}}},{test:[/linux/i],describe:function(){return{name:e.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:e.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(o){var h=r.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.PlayStation4,version:h}}}];t.default=f,n.exports=t.default},94:function(n,t,i){t.__esModule=!0,t.default=void 0;var s,r=(s=i(17))&&s.__esModule?s:{default:s},e=i(18),f=[{test:[/googlebot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Google"}}},{test:[/linespider/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Line"}}},{test:[/amazonbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Amazon"}}},{test:[/gptbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/chatgpt-user/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/oai-searchbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/baiduspider/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Baidu"}}},{test:[/bingbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Bing"}}},{test:[/duckduckbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"DuckDuckGo"}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Anthropic"}}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Webz.io"}}},{test:[/diffbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Diffbot"}}},{test:[/perplexitybot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/perplexity-user/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/youbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"You.com"}}},{test:[/ia_archiver/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Internet Archive"}}},{test:[/meta-webindexer/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalads/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalagent/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalfetcher/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Slack"}}},{test:[/yahoo/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Yahoo"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Yandex"}}},{test:[/pingdom/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Pingdom"}}},{test:[/huawei/i],describe:function(o){var h=r.default.getFirstMatch(/(can-l01)/i,o)&&"Nova",u={type:e.PLATFORMS_MAP.mobile,vendor:"Huawei"};return h&&(u.model=h),u}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet}}},{test:function(o){var h=o.test(/ipod|iphone/i),u=o.test(/like (ipod|iphone)/i);return h&&!u},describe:function(o){var h=r.default.getFirstMatch(/(ipod|iphone)/i,o);return{type:e.PLATFORMS_MAP.mobile,vendor:"Apple",model:h}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:e.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe:function(o){var h=r.default.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,o),u={type:e.PLATFORMS_MAP.mobile,vendor:"Nokia"};return h&&(u.model=h),u}},{test:[/[^-]mobi/i],describe:function(){return{type:e.PLATFORMS_MAP.mobile}}},{test:function(o){return o.getBrowserName(!0)==="blackberry"},describe:function(){return{type:e.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(o){return o.getBrowserName(!0)==="bada"},describe:function(){return{type:e.PLATFORMS_MAP.mobile}}},{test:function(o){return o.getBrowserName()==="windows phone"},describe:function(){return{type:e.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(o){var h=Number(String(o.getOSVersion()).split(".")[0]);return o.getOSName(!0)==="android"&&h>=3},describe:function(){return{type:e.PLATFORMS_MAP.tablet}}},{test:function(o){return o.getOSName(!0)==="android"},describe:function(){return{type:e.PLATFORMS_MAP.mobile}}},{test:[/smart-?tv|smarttv/i],describe:function(){return{type:e.PLATFORMS_MAP.tv}}},{test:[/netcast/i],describe:function(){return{type:e.PLATFORMS_MAP.tv}}},{test:function(o){return o.getOSName(!0)==="macos"},describe:function(){return{type:e.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(o){return o.getOSName(!0)==="windows"},describe:function(){return{type:e.PLATFORMS_MAP.desktop}}},{test:function(o){return o.getOSName(!0)==="linux"},describe:function(){return{type:e.PLATFORMS_MAP.desktop}}},{test:function(o){return o.getOSName(!0)==="playstation 4"},describe:function(){return{type:e.PLATFORMS_MAP.tv}}},{test:function(o){return o.getOSName(!0)==="roku"},describe:function(){return{type:e.PLATFORMS_MAP.tv}}}];t.default=f,n.exports=t.default},95:function(n,t,i){t.__esModule=!0,t.default=void 0;var s,r=(s=i(17))&&s.__esModule?s:{default:s},e=i(18),f=[{test:function(o){return o.getBrowserName(!0)==="microsoft edge"},describe:function(o){if(/\sedg\//i.test(o))return{name:e.ENGINE_MAP.Blink};var h=r.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,o);return{name:e.ENGINE_MAP.EdgeHTML,version:h}}},{test:[/trident/i],describe:function(o){var h={name:e.ENGINE_MAP.Trident},u=r.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:function(o){return o.test(/presto/i)},describe:function(o){var h={name:e.ENGINE_MAP.Presto},u=r.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:function(o){var h=o.test(/gecko/i),u=o.test(/like gecko/i);return h&&!u},describe:function(o){var h={name:e.ENGINE_MAP.Gecko},u=r.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:e.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(o){var h={name:e.ENGINE_MAP.WebKit},u=r.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}}];t.default=f,n.exports=t.default}})})});var ct=k((a3)=>{var{Retry:i3,RETRY_MODES:nd}=Zr(),{HttpRequest:wc,parseUrl:s3}=Jn(),{InvokeStore:td}=XM(),{normalizeProvider:r3}=_i(),{platform:e3,release:o3}=p("os"),{versions:fc,env:id}=p("process"),{isValidHostLabel:f3,isIpAddress:fd,customEndpointFunctions:h3}=Ji(),{EndpointError:u3,resolveEndpoint:c3}=Ji();a3.EndpointError=u3;a3.isIpAddress=fd;a3.resolveEndpoint=c3;var{loadConfig:_3,NODE_REGION_CONFIG_OPTIONS:hd,NODE_REGION_CONFIG_FILE_OPTIONS:ud}=Yn(),{REGION_ENV_NAME:w3,REGION_INI_NAME:l3,resolveRegionConfig:A3}=Yn();a3.NODE_REGION_CONFIG_FILE_OPTIONS=ud;a3.NODE_REGION_CONFIG_OPTIONS=hd;a3.REGION_ENV_NAME=w3;a3.REGION_INI_NAME=l3;a3.resolveRegionConfig=A3;var Do={warningEmitted:!1},M3=(n)=>{if(n&&!Do.warningEmitted){if(process.env.AWS_SDK_JS_NODE_VERSION_SUPPORT_WARNING_DISABLED==="true"){Do.warningEmitted=!0;return}let t=parseInt(n.substring(1,n.indexOf("."))),i=22;if(t<i)Do.warningEmitted=!0,process.emitWarning(`NodeVersionSupportWarning: The AWS SDK for JavaScript (v3)
|
|
11
|
+
`)},hf={warn:console.warn},Hb=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Vc=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Gb(n){let t=n.getUTCFullYear(),i=n.getUTCMonth(),r=n.getUTCDay(),s=n.getUTCDate(),f=n.getUTCHours(),h=n.getUTCMinutes(),_=n.getUTCSeconds(),c=s<10?`0${s}`:`${s}`,o=f<10?`0${f}`:`${f}`,w=h<10?`0${h}`:`${h}`,e=_<10?`0${_}`:`${_}`;return`${Hb[r]}, ${c} ${Vc[i]} ${t} ${o}:${w}:${e} GMT`}var Wb=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),Db=(n)=>{if(n===null||n===void 0)return;if(typeof n!=="string")throw TypeError("RFC-3339 date-times must be expressed as strings");let t=Wb.exec(n);if(!t)throw TypeError("Invalid RFC-3339 date-time value");let[i,r,s,f,h,_,c,o]=t,w=kr(qr(r)),e=Yt(s,"month",1,12),u=Yt(f,"day",1,31);return sf(w,e,u,{hours:h,minutes:_,seconds:c,fractionalMilliseconds:o})},Pb=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}:\d{2})|[zZ])$/),Yb=(n)=>{if(n===null||n===void 0)return;if(typeof n!=="string")throw TypeError("RFC-3339 date-times must be expressed as strings");let t=Pb.exec(n);if(!t)throw TypeError("Invalid RFC-3339 date-time value");let[i,r,s,f,h,_,c,o,w]=t,e=kr(qr(r)),u=Yt(s,"month",1,12),y=Yt(f,"day",1,31),A=sf(e,u,y,{hours:h,minutes:_,seconds:c,fractionalMilliseconds:o});if(w.toUpperCase()!="Z")A.setTime(A.getTime()-qb(w));return A},Fb=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$/),Xb=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$/),lb=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})$/),Jb=(n)=>{if(n===null||n===void 0)return;if(typeof n!=="string")throw TypeError("RFC-7231 date-times must be expressed as strings");let t=Fb.exec(n);if(t){let[i,r,s,f,h,_,c,o]=t;return sf(kr(qr(f)),Wc(s),Yt(r,"day",1,31),{hours:h,minutes:_,seconds:c,fractionalMilliseconds:o})}if(t=Xb.exec(n),t){let[i,r,s,f,h,_,c,o]=t;return Vb(sf(zb(f),Wc(s),Yt(r,"day",1,31),{hours:h,minutes:_,seconds:c,fractionalMilliseconds:o}))}if(t=lb.exec(n),t){let[i,r,s,f,h,_,c,o]=t;return sf(kr(qr(o)),Wc(r),Yt(s.trimLeft(),"day",1,31),{hours:f,minutes:h,seconds:_,fractionalMilliseconds:c})}throw TypeError("Invalid RFC-7231 date-time value")},Qb=(n)=>{if(n===null||n===void 0)return;let t;if(typeof n==="number")t=n;else if(typeof n==="string")t=zc(n);else if(typeof n==="object"&&n.tag===1)t=n.value;else throw TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(t)||t===1/0||t===-1/0)throw TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(t*1000))},sf=(n,t,i,r)=>{let s=t-1;return xb(n,s,i),new Date(Date.UTC(n,s,i,Yt(r.hours,"hour",0,23),Yt(r.minutes,"minute",0,59),Yt(r.seconds,"seconds",0,60),kb(r.fractionalMilliseconds)))},zb=(n)=>{let t=new Date().getUTCFullYear(),i=Math.floor(t/100)*100+kr(qr(n));if(i<t)return i+100;return i},Cb=1576800000000,Vb=(n)=>{if(n.getTime()-new Date().getTime()>Cb)return new Date(Date.UTC(n.getUTCFullYear()-100,n.getUTCMonth(),n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()));return n},Wc=(n)=>{let t=Vc.indexOf(n);if(t<0)throw TypeError(`Invalid month: ${n}`);return t+1},Kb=[31,28,31,30,31,30,31,31,30,31,30,31],xb=(n,t,i)=>{let r=Kb[t];if(t===1&&jb(n))r=29;if(i>r)throw TypeError(`Invalid day for ${Vc[t]} in ${n}: ${i}`)},jb=(n)=>{return n%4===0&&(n%100!==0||n%400===0)},Yt=(n,t,i,r)=>{let s=xd(qr(n));if(s<i||s>r)throw TypeError(`${t} must be between ${i} and ${r}, inclusive`);return s},kb=(n)=>{if(n===null||n===void 0)return 0;return Cd("0."+n)*1000},qb=(n)=>{let t=n[0],i=1;if(t=="+")i=1;else if(t=="-")i=-1;else throw TypeError(`Offset direction, ${t}, must be "+" or "-"`);let r=Number(n.substring(1,3)),s=Number(n.substring(4,6));return i*(r*60+s)*60*1000},qr=(n)=>{let t=0;while(t<n.length-1&&n.charAt(t)==="0")t++;if(t===0)return n;return n.slice(t)},pi=function(t){return Object.assign(new String(t),{deserializeJSON(){return JSON.parse(String(t))},toString(){return String(t)},toJSON(){return String(t)}})};pi.from=(n)=>{if(n&&typeof n==="object"&&(n instanceof pi||("deserializeJSON"in n)))return n;else if(typeof n==="string"||Object.getPrototypeOf(n)===String.prototype)return pi(String(n));return pi(JSON.stringify(n))};pi.fromObject=pi.from;function mb(n){if(n.includes(",")||n.includes('"'))n=`"${n.replace(/"/g,"\\\"")}"`;return n}var Kc="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",xc="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",jc="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",jd="(\\d?\\d)",kd="(\\d{4})",Zb=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),ab=new RegExp(`^${Kc}, ${jd} ${xc} ${kd} ${jc} GMT$`),vb=new RegExp(`^${Kc}, ${jd}-${xc}-(\\d\\d) ${jc} GMT$`),pb=new RegExp(`^${Kc} ${xc} ( [1-9]|\\d\\d) ${jc} ${kd}$`),nN=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],tN=(n)=>{if(n==null)return;let t=NaN;if(typeof n==="number")t=n;else if(typeof n==="string"){if(!/^-?\d*\.?\d+$/.test(n))throw TypeError("parseEpochTimestamp - numeric string invalid.");t=Number.parseFloat(n)}else if(typeof n==="object"&&n.tag===1)t=n.value;if(isNaN(t)||Math.abs(t)===1/0)throw TypeError("Epoch timestamps must be valid finite numbers.");return new Date(Math.round(t*1000))},iN=(n)=>{if(n==null)return;if(typeof n!=="string")throw TypeError("RFC3339 timestamps must be strings");let t=Zb.exec(n);if(!t)throw TypeError(`Invalid RFC3339 timestamp format ${n}`);let[,i,r,s,f,h,_,,c,o]=t;pt(r,1,12),pt(s,1,31),pt(f,0,23),pt(h,0,59),pt(_,0,60);let w=new Date(Date.UTC(Number(i),Number(r)-1,Number(s),Number(f),Number(h),Number(_),Number(c)?Math.round(parseFloat(`0.${c}`)*1000):0));if(w.setUTCFullYear(Number(i)),o.toUpperCase()!="Z"){let[,e,u,y]=/([+-])(\d\d):(\d\d)/.exec(o)||[void 0,"+",0,0],A=e==="-"?1:-1;w.setTime(w.getTime()+A*(Number(u)*60*60*1000+Number(y)*60*1000))}return w},rN=(n)=>{if(n==null)return;if(typeof n!=="string")throw TypeError("RFC7231 timestamps must be strings.");let t,i,r,s,f,h,_,c;if(c=ab.exec(n))[,t,i,r,s,f,h,_]=c;else if(c=vb.exec(n))[,t,i,r,s,f,h,_]=c,r=(Number(r)+1900).toString();else if(c=pb.exec(n))[,i,t,s,f,h,_,r]=c;if(r&&h){let o=Date.UTC(Number(r),nN.indexOf(i),Number(t),Number(s),Number(f),Number(h),_?Math.round(parseFloat(`0.${_}`)*1000):0);pt(t,1,31),pt(s,0,23),pt(f,0,59),pt(h,0,60);let w=new Date(o);return w.setUTCFullYear(Number(r)),w}throw TypeError(`Invalid RFC7231 date-time value ${n}.`)};function pt(n,t,i){let r=Number(n);if(r<t||r>i)throw Error(`Value ${r} out of range [${t}, ${i}]`)}function sN(n,t,i){if(i<=0||!Number.isInteger(i))throw Error("Invalid number of delimiters ("+i+") for splitEvery.");let r=n.split(t);if(i===1)return r;let s=[],f="";for(let h=0;h<r.length;h++){if(f==="")f=r[h];else f+=t+r[h];if((h+1)%i===0)s.push(f),f=""}if(f!=="")s.push(f);return s}var fN=(n)=>{let t=n.length,i=[],r=!1,s=void 0,f=0;for(let h=0;h<t;++h){let _=n[h];switch(_){case'"':if(s!=="\\")r=!r;break;case",":if(!r)i.push(n.slice(f,h)),f=h+1;break}s=_}return i.push(n.slice(f)),i.map((h)=>{h=h.trim();let _=h.length;if(_<2)return h;if(h[0]==='"'&&h[_-1]==='"')h=h.slice(1,_-1);return h.replace(/\\"/g,'"')})},Gd=/^-?\d*(\.\d+)?$/;class X_{string;type;constructor(n,t){if(this.string=n,this.type=t,!Gd.test(n))throw 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](n){if(!n||typeof n!=="object")return!1;let t=n;return X_.prototype.isPrototypeOf(n)||t.type==="bigDecimal"&&Gd.test(t.string)}}function _N(n){return new X_(String(n),"bigDecimal")}var qd={},lc={};for(let n=0;n<256;n++){let t=n.toString(16).toLowerCase();if(t.length===1)t=`0${t}`;qd[n]=t,lc[t]=n}function hN(n){if(n.length%2!==0)throw Error("Hex encoded strings must have an even number length");let t=new Uint8Array(n.length/2);for(let i=0;i<n.length;i+=2){let r=n.slice(i,i+2).toLowerCase();if(r in lc)t[i/2]=lc[r];else throw Error(`Cannot decode unrecognized sequence ${r} as hexadecimal`)}return t}function md(n){let t="";for(let i=0;i<n.byteLength;i++)t+=qd[n[i]];return t}var cN=(n)=>{if(!n)return 0;if(typeof n==="string")return Buffer.byteLength(n);else if(typeof n.byteLength==="number")return n.byteLength;else if(typeof n.size==="number")return n.size;else if(typeof n.start==="number"&&typeof n.end==="number")return n.end+1-n.start;else if(n instanceof _b){if(n.path!=null)return hb(n.path).size;else if(typeof n.fd==="number")return cb(n.fd).size}throw Error(`Body Length computation failed for ${n}`)},Zd=(n)=>{if(n instanceof Uint8Array)return n;if(typeof n==="string")return F_(n);if(ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT);return new Uint8Array(n)};function l_(n,t){if(t===void 0){t=0;for(let s of n)t+=s.byteLength}let i=new Uint8Array(t),r=0;for(let s of n)i.set(s,r),r+=s.byteLength;return i}var ad=(n,t)=>(i,r)=>async(s)=>{let{response:f}=await i(s);try{let h=await t(f,n);return{response:f,output:h}}catch(h){if(Object.defineProperty(h,"$response",{value:f,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in h)){try{h.message+=`
|
|
12
|
+
Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(c){if(!r.logger||r.logger?.constructor?.name==="NoOpLogger")console.warn("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.");else r.logger?.warn?.("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.")}if(typeof h.$responseBodyText<"u"){if(h.$response)h.$response.body=h.$responseBodyText}try{if(ob.isInstance(f)){let{headers:c={}}=f,o=Object.entries(c);h.$metadata={httpStatusCode:f.statusCode,requestId:Dc(/^x-[\w-]+-request-?id$/,o),extendedRequestId:Dc(/^x-[\w-]+-id-2$/,o),cfId:Dc(/^x-[\w-]+-cf-id$/,o)}}}catch(c){}}throw h}},Dc=(n,t)=>{return(t.find(([i])=>{return i.match(n)})||[void 0,void 0])[1]},vd=(n,t)=>(i,r)=>async(s)=>{let f=n,h=r.endpointV2?async()=>wb(r.endpointV2):f.endpoint;if(!h)throw Error("No valid endpoint provider available.");let _=await t(s.input,{...n,endpoint:h});return i({...s,request:_})},pd={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},nA={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function oN(n,t,i){return{applyToStack:(r)=>{r.add(ad(n,i),pd),r.add(vd(n,t),nA)}}}class tA{algorithmIdentifier;secret;hash;constructor(n,t){this.algorithmIdentifier=n,this.secret=t,this.reset()}update(n,t){this.hash.update(Zd(Wd(n,t)))}digest(){return Promise.resolve(this.hash.digest())}reset(){this.hash=this.secret?rb(this.algorithmIdentifier,Wd(this.secret)):sb(this.algorithmIdentifier)}}function Wd(n,t){if(Buffer.isBuffer(n))return n;if(typeof n==="string")return Y_(n,t);if(ArrayBuffer.isView(n))return jr(n.buffer,n.byteOffset,n.byteLength);return jr(n)}var iA=class extends Kr{expectedChecksum;checksumSourceLocation;checksum;source;base64Encoder;constructor({expectedChecksum:t,checksum:i,source:r,checksumSourceLocation:s,base64Encoder:f}){super();if(typeof r.pipe!=="function")throw Error(`@smithy/util-stream: unsupported source type ${r?.constructor?.name??r} in ChecksumStream.`);this.source=r,this.base64Encoder=f??Jc,this.expectedChecksum=t,this.checksum=i,this.checksumSourceLocation=s,this.source.on("data",this.onSourceData),this.source.on("end",this.onSourceEnd),this.source.on("error",this.onSourceError),this.source.on("close",this.onSourceClose),this.source.pause()}onSourceData=(t)=>{if(this.destroyed)return;try{this.checksum.update(t)}catch(i){this.destroy(i);return}if(!this.push(t))this.source.pause()};onSourceEnd=async()=>{if(this.destroyed)return;try{let t=await this.checksum.digest(),i=this.base64Encoder(t);if(this.expectedChecksum!==i){this.destroy(Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${i}" in response header "${this.checksumSourceLocation}".`));return}}catch(t){this.destroy(t);return}this.push(null)};onSourceError=(t)=>{this.destroy(t)};onSourceClose=()=>{if(!this.destroyed&&!this.source.readableEnded)this.destroy(Error("Connection lost or stream closed before all data was received."))};_read(t){this.source.resume()}_destroy(t,i){this.source?.removeListener("data",this.onSourceData),this.source?.removeListener("end",this.onSourceEnd),this.source?.removeListener("error",this.onSourceError),this.source?.removeListener("close",this.onSourceClose),this.source?.destroy(),i(t)}},Ft=(n)=>typeof ReadableStream==="function"&&(n?.constructor?.name===ReadableStream.name||n instanceof ReadableStream),J_=(n)=>{return typeof Blob==="function"&&(n?.constructor?.name===Blob.name||n instanceof Blob)},wN=(n)=>new TextEncoder().encode(n),rA="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";Object.entries(rA).reduce((n,[t,i])=>{return n[i]=Number(t),n},{});var eN=rA.split(""),Pc=6,Dd=8,uN=63;function sA(n){let t;if(typeof n==="string")t=wN(n);else t=n;let i=typeof t==="object"&&typeof t.length==="number",r=typeof t==="object"&&typeof t.byteOffset==="number"&&typeof t.byteLength==="number";if(!i&&!r)throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let s="";for(let f=0;f<t.length;f+=3){let h=0,_=0;for(let o=f,w=Math.min(f+3,t.length);o<w;o++)h|=t[o]<<(w-o-1)*Dd,_+=Dd;let c=Math.ceil(_/Pc);h<<=c*Pc-_;for(let o=1;o<=c;o++){let w=(c-o)*Pc;s+=eN[(h&uN<<w)>>w]}s+="==".slice(0,4-c)}return s}var yN=typeof ReadableStream==="function"?ReadableStream:function(){};class fA extends yN{}var dN=({expectedChecksum:n,checksum:t,source:i,checksumSourceLocation:r,base64Encoder:s})=>{if(!Ft(i))throw Error(`@smithy/util-stream: unsupported source type ${i?.constructor?.name??i} in ChecksumStream.`);let f=s??sA;if(typeof TransformStream!=="function")throw Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");let h=new TransformStream({start(){},async transform(c,o){t.update(c),o.enqueue(c)},async flush(c){let o=await t.digest(),w=f(o);if(n!==w){let e=Error(`Checksum mismatch: expected "${n}" but received "${w}" in response header "${r}".`);c.error(e)}else c.terminate()}});i.pipeThrough(h);let _=h.readable;return Object.setPrototypeOf(_,fA.prototype),_};function AN(n){if(typeof ReadableStream==="function"&&Ft(n.source))return dN(n);return new iA(n)}class P_{allocByteArray;byteLength=0;byteArrays=[];constructor(n){this.allocByteArray=n}push(n){this.byteArrays.push(n),this.byteLength+=n.byteLength}flush(){if(this.byteArrays.length===1){let i=this.byteArrays[0];return this.reset(),i}let n=this.allocByteArray(this.byteLength),t=0;for(let i=0;i<this.byteArrays.length;++i){let r=this.byteArrays[i];n.set(r,t),t+=r.byteLength}return this.reset(),n}reset(){this.byteArrays=[],this.byteLength=0}}function RN(n,t,i){let r=n.getReader(),s=!1,f=0,h=["",new P_((o)=>new Uint8Array(o))],_=-1,c=async(o)=>{let{value:w,done:e}=await r.read(),u=w;if(e){if(_!==-1){let y=xr(h,_);if(Si(y)>0)o.enqueue(y)}o.close()}else{let y=hA(u,!1);if(_!==y){if(_>=0)o.enqueue(xr(h,_));_=y}if(_===-1){o.enqueue(u);return}let A=Si(u);f+=A;let R=Si(h[_]);if(A>=t&&R===0)o.enqueue(u);else{let M=_A(h,_,u);if(!s&&f>t*2)s=!0,i?.warn(`@smithy/util-stream - stream chunk size ${A} is below threshold of ${t}, automatically buffering.`);if(M>=t)o.enqueue(xr(h,_));else await c(o)}}};return new ReadableStream({pull:c})}function _A(n,t,i){switch(t){case 0:return n[0]+=i,Si(n[0]);case 1:case 2:return n[t].push(i),Si(n[t])}}function xr(n,t){switch(t){case 0:let i=n[0];return n[0]="",i;case 1:case 2:return n[t].flush()}throw Error(`@smithy/util-stream - invalid index ${t} given to flush()`)}function Si(n){return n?.byteLength??n?.length??0}function hA(n,t=!0){if(t&&typeof Buffer<"u"&&n instanceof Buffer)return 2;if(n instanceof Uint8Array)return 1;if(typeof n==="string")return 0;return-1}function MN(n,t,i){if(Ft(n))return RN(n,t,i);let r=new Kr({read(){}}),s=!1,f=0,h=["",new P_((c)=>new Uint8Array(c)),new P_((c)=>Buffer.from(new Uint8Array(c)))],_=-1;return n.on("data",(c)=>{let o=hA(c,!0);if(_!==o){if(_>=0)r.push(xr(h,_));_=o}if(_===-1){r.push(c);return}let w=Si(c);f+=w;let e=Si(h[_]);if(w>=t&&e===0)r.push(c);else{let u=_A(h,_,c);if(!s&&f>t*2)s=!0,i?.warn(`@smithy/util-stream - stream chunk size ${w} is below threshold of ${t}, automatically buffering.`);if(u>=t)r.push(xr(h,_))}}),n.on("end",()=>{if(_!==-1){let c=xr(h,_);if(Si(c)>0)r.push(c)}r.push(null)}),r}var EN=(n,t)=>{let{base64Encoder:i,bodyLengthChecker:r,checksumAlgorithmFn:s,checksumLocationName:f,streamHasher:h}=t,_=i!==void 0&&r!==void 0&&s!==void 0&&f!==void 0&&h!==void 0,c=_?h(s,n):void 0,o=n.getReader();return new ReadableStream({async pull(w){let{value:e,done:u}=await o.read();if(u){if(w.enqueue(`0\r
|
|
13
|
+
`),_){let y=i(await c);w.enqueue(`${f}:${y}\r
|
|
14
|
+
`),w.enqueue(`\r
|
|
15
|
+
`)}w.close()}else w.enqueue(`${(r(e)||0).toString(16)}\r
|
|
16
|
+
${e}\r
|
|
17
|
+
`)}})};function TN(n,t){let i=n,r=n;if(Ft(r))return EN(r,t);let{base64Encoder:s,bodyLengthChecker:f,checksumAlgorithmFn:h,checksumLocationName:_,streamHasher:c}=t,o=s!==void 0&&h!==void 0&&_!==void 0&&c!==void 0,w=o?c(h,i):void 0,e=new Kr({read:()=>{}});return i.on("data",(u)=>{let y=f(u)||0;if(y===0)return;e.push(`${y.toString(16)}\r
|
|
18
|
+
`),e.push(u),e.push(`\r
|
|
19
|
+
`)}),i.on("end",async()=>{if(e.push(`0\r
|
|
20
|
+
`),o){let u=s(await w);e.push(`${_}:${u}\r
|
|
21
|
+
`),e.push(`\r
|
|
22
|
+
`)}e.push(null)}),e}async function gN(n,t){let i=0,r=[],s=n.getReader(),f=!1;while(!f){let{done:c,value:o}=await s.read();if(o)r.push(o),i+=o?.byteLength??0;if(i>=t)break;f=c}s.releaseLock();let h=new Uint8Array(Math.min(t,i)),_=0;for(let c of r){if(c.byteLength>h.byteLength-_){h.set(c.subarray(0,h.byteLength-_),_);break}else h.set(c,_);_+=c.length}return h}var SN=(n,t)=>{if(Ft(n))return gN(n,t);return new Promise((i,r)=>{let s=new LN;s.limit=t,n.pipe(s),n.on("error",(f)=>{s.end(),r(f)}),s.on("error",r),s.on("finish",function(){let f=l_(this.buffers);i(f)})})},LN=class extends Xd{buffers=[];limit=1/0;bytesBuffered=0;_write(t,i,r){if(this.buffers.push(t),this.bytesBuffered+=t.byteLength??0,this.bytesBuffered>=this.limit){let s=this.bytesBuffered-this.limit,f=this.buffers[this.buffers.length-1];this.buffers[this.buffers.length-1]=f.subarray(0,f.byteLength-s),this.emit("finish")}r()}},$N=(n)=>{if(typeof n==="string")return n;if(typeof n!=="object"||typeof n.byteOffset!=="number"||typeof n.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(n)},ON=async(n)=>{if(J_(n))return cA(n);return oA(n)};async function cA(n){return n.arrayBuffer().then((t)=>new Uint8Array(t))}async function oA(n){let t=[],i=n.getReader(),r=0;while(!0){let{done:s,value:f}=await i.read();if(f)t.push(f),r+=f.length;if(s)break}return l_(t,r)}var Pd="The stream has already been transformed.",UN=(n)=>{if(!Yd(n)&&!Ft(n)){let s=n?.__proto__?.constructor?.name||n;throw Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${s}`)}let t=!1,i=async()=>{if(t)throw Error(Pd);return t=!0,await ON(n)},r=(s)=>{if(typeof s.stream!=="function")throw Error(`Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.
|
|
23
|
+
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 s.stream()};return Object.assign(n,{transformToByteArray:i,transformToString:async(s)=>{let f=await i();if(s==="base64")return sA(f);else if(s==="hex")return md(f);else if(s===void 0||s==="utf8"||s==="utf-8")return $N(f);else if(typeof TextDecoder==="function")return new TextDecoder(s).decode(f);else throw Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(t)throw Error(Pd);if(t=!0,Yd(n))return r(n);else if(Ft(n))return n;else throw Error(`Cannot transform payload to web stream, got ${n}`)}})},Yd=(n)=>typeof Blob==="function"&&n instanceof Blob,wA=(n)=>{if(J_(n))return cA(n);if(Ft(n))return oA(n);return new Promise((t,i)=>{let r=new eA,s=n;s.pipe(r),s.on("error",(f)=>{r.end(),i(f)}),r.on("error",i),r.on("finish",function(){let f=l_(this.bufferedBytes);t(f)})})};class eA extends Xd{bufferedBytes=[];_write(n,t,i){this.bufferedBytes.push(n),i()}}var Fd="The stream has already been transformed.",bN=(n)=>{if(!(n instanceof Kr))try{return UN(n)}catch(r){let s=n?.__proto__?.constructor?.name||n;throw Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${s}`)}let t=!1,i=async()=>{if(t)throw Error(Fd);return t=!0,await wA(n)};return Object.assign(n,{transformToByteArray:i,transformToString:async(r)=>{let s=await i();if(r===void 0||Buffer.isEncoding(r))return jr(s.buffer,s.byteOffset,s.byteLength).toString(r);else return new TextDecoder(r).decode(s)},transformToWebStream:()=>{if(t)throw Error(Fd);if(n.readableFlowing!==null)throw Error("The stream has been consumed by other callbacks.");if(typeof Kr.toWeb!=="function")throw Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");return t=!0,Kr.toWeb(n)}})};async function NN(n){if(typeof n.stream==="function")n=n.stream();return n.tee()}async function BN(n){if(Ft(n)||J_(n))return NN(n);let t=new Hd,i=new Hd;return n.pipe(t),n.pipe(i),[t,i]}class uA extends ub(Qd,F_,Jc,Jd){}var IN=fb,yA=yb(IN),HN=yA;GN.ChecksumStream=iA;GN.Hash=tA;GN.LazyJsonString=pi;GN.NumericValue=X_;GN.Uint8ArrayBlobAdapter=uA;GN._parseEpochTimestamp=tN;GN._parseRfc3339DateTimeWithOffset=iN;GN._parseRfc7231DateTime=rN;GN.calculateBodyLength=cN;GN.concatBytes=l_;GN.copyDocumentWithTransform=db;GN.createBufferedReadable=MN;GN.createChecksumStream=AN;GN.dateToUtcString=Gb;GN.deserializerMiddleware=ad;GN.deserializerMiddlewareOption=pd;GN.expectBoolean=Rb;GN.expectByte=Xc;GN.expectFloat32=W_;GN.expectInt=Eb;GN.expectInt32=Yc;GN.expectLong=_f;GN.expectNonNull=gb;GN.expectNumber=ff;GN.expectObject=zd;GN.expectShort=Fc;GN.expectString=Sb;GN.expectUnion=Lb;GN.fromArrayBuffer=jr;GN.fromBase64=Jd;GN.fromHex=hN;GN.fromString=Y_;GN.fromUtf8=F_;GN.generateIdempotencyToken=HN;GN.getAwsChunkedEncodingStream=TN;GN.getSerdePlugin=oN;GN.handleFloat=Ub;GN.headStream=SN;GN.isArrayBuffer=ld;GN.isBlob=J_;GN.isReadableStream=Ft;GN.limitedParseDouble=Cc;GN.limitedParseFloat=bb;GN.limitedParseFloat32=Nb;GN.logger=hf;GN.nv=_N;GN.parseBoolean=Ab;GN.parseEpochTimestamp=Qb;GN.parseRfc3339DateTime=Db;GN.parseRfc3339DateTimeWithOffset=Yb;GN.parseRfc7231DateTime=Jb;GN.quoteHeader=mb;GN.sdkStreamMixin=bN;GN.serializerMiddleware=vd;GN.serializerMiddlewareOption=nA;GN.splitEvery=sN;GN.splitHeader=fN;GN.splitStream=BN;GN.streamCollector=wA;GN.strictParseByte=xd;GN.strictParseDouble=zc;GN.strictParseFloat=$b;GN.strictParseFloat32=Cd;GN.strictParseInt=Bb;GN.strictParseInt32=Ib;GN.strictParseLong=Kd;GN.strictParseShort=kr;GN.toBase64=Jc;GN.toHex=md;GN.toUint8Array=Zd;GN.toUtf8=Qd;GN.v4=yA});var vc=nn((EI)=>{var{createReadStream:ZB}=cn("fs"),{Writable:aB}=cn("stream"),{toUint8Array:Zr,concatBytes:vB}=jn(),{createHash:cf,createHmac:pB}=cn("crypto"),dA=cn("zlib");async function TA(n,t,i=1048576){let r=n.size,s=0;while(s<r){let f=n.slice(s,Math.min(r,s+i));t(new Uint8Array(await f.arrayBuffer())),s+=f.size}}var nI=async function(t,i){let r=new t;return await TA(i,(s)=>{r.update(s)}),r.digest()};class mc extends aB{hash;constructor(n,t){super(t);this.hash=n}_write(n,t,i){try{this.hash.update(Zr(n))}catch(r){return i(r)}i()}}var tI=(n,t)=>new Promise((i,r)=>{if(!iI(t)){r(Error("Unable to calculate hash for non-file streams."));return}let s=ZB(t.path,{start:t.start,end:t.end}),f=new n,h=new mc(f);s.pipe(h),s.on("error",(_)=>{h.end(),r(_)}),h.on("error",r),h.on("finish",function(){f.digest().then(i).catch(r)})}),iI=(n)=>typeof n.path==="string",rI=(n,t)=>{if(t.readableFlowing!==null)throw Error("Unable to calculate hash for flowing readable stream");let i=new n,r=new mc(i);return t.pipe(r),new Promise((s,f)=>{t.on("error",(h)=>{r.end(),f(h)}),r.on("error",f),r.on("finish",()=>{i.digest().then(s).catch(f)})})};class Zc{digestLength=16;state=Uint32Array.from(AA);writeBuffer=new DataView(new ArrayBuffer(64));bufferLength=0;bytesHashed=0;update(n){let t=Zr(n),i=0,r=t.byteLength;this.bytesHashed+=r;while(r>0)if(this.writeBuffer.setUint8(this.bufferLength++,t[i++]),--r,this.bufferLength===64)kc(this.state,this.writeBuffer),this.bufferLength=0}async digest(){let n=Uint32Array.from(this.state),t=new DataView(this.writeBuffer.buffer.slice(0)),i=this.bufferLength,r=this.bytesHashed*8;if(t.setUint8(i++,128),this.bufferLength%64>=56){for(let h=i;h<64;++h)t.setUint8(h,0);kc(n,t),i=0}for(let h=i;h<56;++h)t.setUint8(h,0);t.setUint32(56,r>>>0,!0),t.setUint32(60,Math.floor(r/4294967296),!0),kc(n,t);let s=new Uint8Array(16),f=new DataView(s.buffer);for(let h=0;h<4;++h)f.setUint32(h*4,n[h],!0);return s}reset(){this.state.set(AA),this.writeBuffer=new DataView(new ArrayBuffer(64)),this.bufferLength=0,this.bytesHashed=0}}var AA=[1732584193,4023233417,2562383102,271733878],Li=4294967295,sI=Uint8Array.of(7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21),fI=Array.from({length:64},(n,t)=>Math.abs(Math.sin(t+1))*4294967296>>>0);function kc(n,t){let i=n[0],r=n[1],s=n[2],f=n[3];for(let h=0;h<64;++h){let _,c;if(h<16)_=r&s|~r&f,c=h;else if(h<32)_=f&r|s&~f,c=(5*h+1)%16;else if(h<48)_=r^s^f,c=(3*h+5)%16;else _=s^(r|~f),c=7*h%16;let o=t.getUint32(c*4,!0),w=f;f=s,s=r;let e=sI[(h>>4)*4+(h&3)],u=(i+_&Li)+(o+fI[h]&Li)&Li;r=r+((u<<e|u>>>32-e)>>>0)&Li,i=w}n[0]=n[0]+i&Li,n[1]=n[1]+r&Li,n[2]=n[2]+s&Li,n[3]=n[3]+f&Li}var _I=(()=>{try{return cf("md5"),!0}catch{return!1}})(),gA=_I?hI():Zc;function hI(){return class{digestLength=16;hash=cf("md5");update(t){this.hash.update(Zr(t))}async digest(){let t=this.hash.copy().digest();return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}reset(){this.hash=cf("md5")}}}var SA=new Uint32Array(256);for(let n=0;n<256;++n){let t=n;for(let i=0;i<8;++i)t=t&1?3988292384^t>>>1:t>>>1;SA[n]=t>>>0}var qc=4294967295;class ac{digestLength=4;checksum=qc;update(n){for(let t=0;t<n.length;++t)this.checksum=this.checksum>>>8^SA[(this.checksum^n[t])&255]}digestSync(){return(this.checksum^qc)>>>0}async digest(){let n=this.digestSync(),t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n,!1),t}reset(){this.checksum=qc}}var RA=typeof dA.crc32==="function"?dA.crc32:void 0,LA=RA?cI(RA):ac;function cI(n){return class{digestLength=4;value=0;update(i){this.value=n(i,this.value)}digestSync(){return this.value>>>0}async digest(){let i=new Uint8Array(4);return new DataView(i.buffer).setUint32(0,this.digestSync(),!1),i}reset(){this.value=0}}}var Fn=64,MA=32,oI=9007199254740991;class ni{digestLength=MA;state=Int32Array.from(EA);w;buffer=new Uint8Array(64);bufferLength=0;bytesHashed=0;finished=!1;inner;outer;constructor(n){if(n){let t=ni.normalizeKey(n);this.inner=new ni,this.outer=new ni;let{inner:i,outer:r}=this,s=new Uint8Array(Fn*2);for(let f=0;f<Fn;++f)s[f]=54^t[f],s[f+Fn]=92^t[f];i.update(s.subarray(0,Fn)),r.update(s.subarray(Fn))}}update(n){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.inner){this.inner.update(n);return}let t=Zr(n),i=0,{byteLength:r}=t;if(this.bytesHashed+=r,this.bytesHashed*8>oI)throw Error("Cannot hash more than 2^53 - 1 bits");while(r>0)if(this.buffer[this.bufferLength++]=t[i++],r--,this.bufferLength===Fn)this.hashBuffer(),this.bufferLength=0}async digest(){let{inner:n,outer:t}=this;if(n&&t){if(this.finished)throw Error("Attempted to digest an already finished HMAC.");this.finished=!0;let i=n.digestSync();return t.update(i),t.digestSync()}return this.digestSync()}reset(){this.state=Int32Array.from(EA),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0}digestSync(){let n=this.state.slice(),t=this.buffer.slice(),i=this.bufferLength,r=this.bytesHashed*8,s=new DataView(t.buffer,t.byteOffset,t.byteLength);if(s.setUint8(i++,128),(i-1)%Fn>=Fn-8){for(let h=i;h<Fn;++h)s.setUint8(h,0);this.hashBufferWith(n,t),i=0}for(let h=i;h<Fn-8;++h)s.setUint8(h,0);s.setUint32(Fn-8,Math.floor(r/4294967296),!1),s.setUint32(Fn-4,r,!1),this.hashBufferWith(n,t);let f=new Uint8Array(MA);for(let h=0;h<8;++h)f[h*4]=n[h]>>>24&255,f[h*4+1]=n[h]>>>16&255,f[h*4+2]=n[h]>>>8&255,f[h*4+3]=n[h]>>>0&255;return f}static normalizeKey(n){let t=Zr(n);if(t.byteLength>Fn){let i=new ni;i.update(t);let r=i.digestSync(),s=new Uint8Array(Fn);return s.set(r),s}if(t.byteLength<Fn){let i=new Uint8Array(Fn);return i.set(t),i}return t}hashBuffer(){this.hashBufferWith(this.state,this.buffer)}hashBufferWith(n,t){let i=this.w??=new Int32Array(64),r=n[0],s=n[1],f=n[2],h=n[3],_=n[4],c=n[5],o=n[6],w=n[7];for(let e=0;e<Fn;++e){if(e<16)i[e]=(t[e*4]&255)<<24|(t[e*4+1]&255)<<16|(t[e*4+2]&255)<<8|t[e*4+3]&255;else{let A=i[e-2],R=(A>>>17|A<<15)^(A>>>19|A<<13)^A>>>10;A=i[e-15];let M=(A>>>7|A<<25)^(A>>>18|A<<14)^A>>>3;i[e]=(R+i[e-7]|0)+(M+i[e-16]|0)}let u=(((_>>>6|_<<26)^(_>>>11|_<<21)^(_>>>25|_<<7))+(_&c^~_&o)|0)+(w+(wI[e]+i[e]|0)|0)|0,y=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&s^r&f^s&f)|0;w=o,o=c,c=_,_=h+u|0,h=f,f=s,s=r,r=u+y|0}n[0]+=r,n[1]+=s,n[2]+=f,n[3]+=h,n[4]+=_,n[5]+=c,n[6]+=o,n[7]+=w}}var EA=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),wI=new Int32Array([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]),eI=(()=>{try{return cf("sha256"),!0}catch{return!1}})(),$A=eI?uI():ni;function uI(){return class{digestLength=32;secret;hash;isHmac;finished=!1;constructor(t){this.secret=t,this.isHmac=!!t,this.hash=this.createHash()}update(t){if(this.finished)throw Error("Attempted to update an already finished hash.");this.hash.update(t)}async digest(){let t;if(this.isHmac)this.finished=!0,t=this.hash.digest();else t=this.hash.copy().digest();return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}reset(){this.hash=this.createHash(),this.finished=!1}createHash(){return this.secret?pB("sha256",yI(this.secret)):cf("sha256")}}}function yI(n){if(typeof n==="string")return n;if(ArrayBuffer.isView(n))return Buffer.from(n.buffer,n.byteOffset,n.byteLength);return Buffer.from(n)}var{digest:dI,sign:AI,importKey:RI}=globalThis?.crypto?.subtle??{},Q_=typeof dI==="function"&&typeof AI==="function"&&typeof RI==="function"?globalThis.crypto.subtle:void 0,MI=8388608;class OA{digestLength=32;secret;pending=[];pendingBytes=0;fallback;finished=!1;constructor(n){if(n)this.secret=Zr(n)}update(n){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.fallback){this.fallback.update(n);return}if(this.pending.push(n.slice()),this.pendingBytes+=n.byteLength,this.pendingBytes>=MI)this.switchToFallback()}async digest(){if(this.fallback)return this.fallback.digest();if(this.secret&&this.finished)throw Error("Attempted to digest an already finished HMAC.");let n=vB(this.pending);if(Q_){if(this.secret){this.finished=!0;let r=await Q_.importKey("raw",this.secret,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),s=await Q_.sign("HMAC",r,n);return new Uint8Array(s)}let i=await Q_.digest("SHA-256",n);return new Uint8Array(i)}let t=new ni(this.secret);return t.update(n),t.digest()}reset(){this.pending=[],this.pendingBytes=0,this.fallback=void 0,this.finished=!1}switchToFallback(){let n=new ni(this.secret);for(let t of this.pending)n.update(t);this.fallback=n,this.pending=[],this.pendingBytes=0}}EI.Crc32=LA;EI.Crc32Js=ac;EI.Crc32Node=LA;EI.Md5=gA;EI.Md5Js=Zc;EI.Md5Node=gA;EI.Sha256=$A;EI.Sha256Js=ni;EI.Sha256Node=$A;EI.Sha256WebCrypto=OA;EI.blobHasher=nI;EI.blobReader=TA;EI.fileStreamHasher=tI;EI.readableStreamHasher=rI});var z_=nn((tH)=>{var{Crc32:NA}=vc(),{toHex:ar,fromHex:DI,toUtf8:PI,fromUtf8:YI}=jn(),{Readable:FI}=cn("stream");class vr{bytes;constructor(n){if(this.bytes=n,n.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(n){if(n>9223372036854776000||n<-9223372036854776000)throw Error(`${n} is too large (or, if negative, too small) to represent as an Int64`);let t=new Uint8Array(8);for(let i=7,r=Math.abs(Math.round(n));i>-1&&r>0;i--,r/=256)t[i]=r;if(n<0)UA(t);return new vr(t)}valueOf(){let n=this.bytes.slice(0),t=n[0]&128;if(t)UA(n);return parseInt(ar(n),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function UA(n){for(let t=0;t<8;t++)n[t]^=255;for(let t=7;t>-1;t--)if(n[t]++,n[t]!==0)break}class pc{toUtf8;fromUtf8;constructor(n,t){this.toUtf8=n,this.fromUtf8=t}format(n){let t=[];for(let s of Object.keys(n)){let f=this.fromUtf8(s);t.push(Uint8Array.from([f.byteLength]),f,this.formatHeaderValue(n[s]))}let i=new Uint8Array(t.reduce((s,f)=>s+f.byteLength,0)),r=0;for(let s of t)i.set(s,r),r+=s.byteLength;return i}formatHeaderValue(n){switch(n.type){case"boolean":return Uint8Array.from([n.value?$n.boolTrue:$n.boolFalse]);case"byte":return Uint8Array.from([$n.byte,n.value]);case"short":let t=new DataView(new ArrayBuffer(3));return t.setUint8(0,$n.short),t.setInt16(1,n.value,!1),new Uint8Array(t.buffer);case"integer":let i=new DataView(new ArrayBuffer(5));return i.setUint8(0,$n.integer),i.setInt32(1,n.value,!1),new Uint8Array(i.buffer);case"long":let r=new Uint8Array(9);return r[0]=$n.long,r.set(n.value.bytes,1),r;case"binary":let s=new DataView(new ArrayBuffer(3+n.value.byteLength));s.setUint8(0,$n.byteArray),s.setUint16(1,n.value.byteLength,!1);let f=new Uint8Array(s.buffer);return f.set(n.value,3),f;case"string":let h=this.fromUtf8(n.value),_=new DataView(new ArrayBuffer(3+h.byteLength));_.setUint8(0,$n.string),_.setUint16(1,h.byteLength,!1);let c=new Uint8Array(_.buffer);return c.set(h,3),c;case"timestamp":let o=new Uint8Array(9);return o[0]=$n.timestamp,o.set(vr.fromNumber(n.value.valueOf()).bytes,1),o;case"uuid":if(!xI.test(n.value))throw Error(`Invalid UUID received: ${n.value}`);let w=new Uint8Array(17);return w[0]=$n.uuid,w.set(DI(n.value.replace(/-/g,"")),1),w}}parse(n){let t={},i=0;while(i<n.byteLength){let r=n.getUint8(i++),s=this.toUtf8(new Uint8Array(n.buffer,n.byteOffset+i,r));switch(i+=r,n.getUint8(i++)){case $n.boolTrue:t[s]={type:bA,value:!0};break;case $n.boolFalse:t[s]={type:bA,value:!1};break;case $n.byte:t[s]={type:XI,value:n.getInt8(i++)};break;case $n.short:t[s]={type:lI,value:n.getInt16(i,!1)},i+=2;break;case $n.integer:t[s]={type:JI,value:n.getInt32(i,!1)},i+=4;break;case $n.long:t[s]={type:QI,value:new vr(new Uint8Array(n.buffer,n.byteOffset+i,8))},i+=8;break;case $n.byteArray:let f=n.getUint16(i,!1);i+=2,t[s]={type:zI,value:new Uint8Array(n.buffer,n.byteOffset+i,f)},i+=f;break;case $n.string:let h=n.getUint16(i,!1);i+=2,t[s]={type:CI,value:this.toUtf8(new Uint8Array(n.buffer,n.byteOffset+i,h))},i+=h;break;case $n.timestamp:t[s]={type:VI,value:new Date(new vr(new Uint8Array(n.buffer,n.byteOffset+i,8)).valueOf())},i+=8;break;case $n.uuid:let _=new Uint8Array(n.buffer,n.byteOffset+i,16);i+=16,t[s]={type:KI,value:`${ar(_.subarray(0,4))}-${ar(_.subarray(4,6))}-${ar(_.subarray(6,8))}-${ar(_.subarray(8,10))}-${ar(_.subarray(10))}`};break;default:throw Error("Unrecognized header type tag")}}return t}}var $n;(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"})($n||($n={}));var bA="boolean",XI="byte",lI="short",JI="integer",QI="long",zI="binary",CI="string",VI="timestamp",KI="uuid",xI=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,BA=4,$i=BA*2,nr=4,jI=$i+nr*2;function kI({byteLength:n,byteOffset:t,buffer:i}){if(n<jI)throw Error("Provided message too short to accommodate event stream message overhead");let r=new DataView(i,t,n),s=r.getUint32(0,!1);if(n!==s)throw Error("Reported message length does not match received message length");let f=r.getUint32(BA,!1),h=r.getUint32($i,!1),_=r.getUint32(n-nr,!1),c=new NA;if(c.update(new Uint8Array(i,t,$i)),h!==c.digestSync())throw Error(`The prelude checksum specified in the message (${h}) does not match the calculated CRC32 checksum (${c.digestSync()})`);if(c.update(new Uint8Array(i,t+$i,n-($i+nr))),_!==c.digestSync())throw Error(`The message checksum (${c.digestSync()}) did not match the expected value of ${_}`);return{headers:new DataView(i,t+$i+nr,f),body:new Uint8Array(i,t+$i+nr+f,s-f-($i+nr+nr))}}class no{headerMarshaller;messageBuffer;isEndOfStream;constructor(n,t){this.headerMarshaller=new pc(n,t),this.messageBuffer=[],this.isEndOfStream=!1}feed(n){this.messageBuffer.push(this.decode(n))}endOfStream(){this.isEndOfStream=!0}getMessage(){let n=this.messageBuffer.pop(),t=this.isEndOfStream;return{getMessage(){return n},isEndOfStream(){return t}}}getAvailableMessages(){let n=this.messageBuffer;this.messageBuffer=[];let t=this.isEndOfStream;return{getMessages(){return n},isEndOfStream(){return t}}}encode({headers:n,body:t}){let i=this.headerMarshaller.format(n),r=i.byteLength+t.byteLength+16,s=new Uint8Array(r),f=new DataView(s.buffer,s.byteOffset,s.byteLength),h=new NA;return f.setUint32(0,r,!1),f.setUint32(4,i.byteLength,!1),h.update(s.subarray(0,8)),f.setUint32(8,h.digestSync(),!1),s.set(i,12),s.set(t,i.byteLength+12),h.update(s.subarray(8,r-4)),f.setUint32(r-4,h.digestSync(),!1),s}decode(n){let{headers:t,body:i}=kI(n);return{headers:this.headerMarshaller.parse(t),body:i}}formatHeaders(n){return this.headerMarshaller.format(n)}}class to{options;constructor(n){this.options=n}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let n of this.options.inputStream)yield this.options.decoder.decode(n)}}class io{options;constructor(n){this.options=n}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let n of this.options.messageStream)yield this.options.encoder.encode(n);if(this.options.includeEndFrame)yield new Uint8Array(0)}}class ro{options;constructor(n){this.options=n}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let n of this.options.messageStream){let t=await this.options.deserializer(n);if(t===void 0)continue;yield t}}}class so{options;constructor(n){this.options=n}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let n of this.options.inputStream)yield this.options.serializer(n)}}function IA(n){let t=0,i=0,r=null,s=null,f=(_)=>{if(typeof _!=="number")throw Error("Attempted to allocate an event message where size was not a number: "+_);t=_,i=4,r=new Uint8Array(_),new DataView(r.buffer).setUint32(0,_,!1)},h=async function*(){let _=n[Symbol.asyncIterator]();while(!0){let{value:c,done:o}=await _.next();if(o){if(!t)return;else if(t===i)yield r;else throw Error("Truncated event message received.");return}let w=c.length,e=0;while(e<w){if(!r){let y=w-e;if(!s)s=new Uint8Array(4);let A=Math.min(4-i,y);if(s.set(c.slice(e,e+A),i),i+=A,e+=A,i<4)break;f(new DataView(s.buffer).getUint32(0,!1)),s=null}let u=Math.min(t-i,w-e);if(r.set(c.slice(e,e+u),i),i+=u,e+=u,t&&t===i)yield r,r=null,t=0,i=0}}};return{[Symbol.asyncIterator]:h}}function qI(n,t){let i=fo(t.deserializer,t.toUtf8);return{[Symbol.asyncIterator]:async function*(){for await(let r of n){let s=t.eventStreamCodec.decode(r),f=await i(s);if(f===void 0)continue;yield f}}}}function fo(n,t){return async function(i){let{value:r}=i.headers[":message-type"];if(r==="error"){let s=Error(i.headers[":error-message"].value||"UnknownError");throw s.name=i.headers[":error-code"].value,s}else if(r==="exception"){let s=i.headers[":exception-type"].value,f={[s]:i},h=await n(f);if(h.$unknown){let _=Error(t(i.body));throw _.name=s,_}throw h[s]}else if(r==="event"){let s={[i.headers[":event-type"].value]:i},f=await n(s);if(f.$unknown)return;return f}else throw Error(`Unrecognizable event type: ${i.headers[":event-type"].value}`)}}var _o=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:t,utf8Decoder:i}){this.eventStreamCodec=new no(t,i),this.utfEncoder=t}deserialize(t,i){let r=IA(t);return new ro({messageStream:new to({inputStream:r,decoder:this.eventStreamCodec}),deserializer:fo(i,this.utfEncoder)})}serialize(t,i){return new io({messageStream:new so({inputStream:t,serializer:i}),encoder:this.eventStreamCodec,includeEndFrame:!0})}},mI=(n)=>new _o(n);class ho{universalMarshaller;constructor({utf8Encoder:n,utf8Decoder:t}){this.universalMarshaller=new _o({utf8Decoder:t,utf8Encoder:n})}deserialize(n,t){let i=typeof n[Symbol.asyncIterator]==="function"?n:aI(n);return this.universalMarshaller.deserialize(i,t)}serialize(n,t){return FI.from(this.universalMarshaller.serialize(n,t))}}var ZI=(n)=>new ho(n);async function*aI(n){let t=!1,i=!1,r=[];n.on("error",(s)=>{if(!t)t=!0;if(s)throw s}),n.on("data",(s)=>{r.push(s)}),n.on("end",()=>{t=!0});while(!i){let s=await new Promise((f)=>setTimeout(()=>f(r.shift()),0));if(s)yield s;i=t&&r.length===0}}var vI=(n)=>({[Symbol.asyncIterator]:async function*(){let t=n.getReader();try{while(!0){let{done:i,value:r}=await t.read();if(i)return;yield r}}finally{t.releaseLock()}}}),pI=(n)=>{let t=n[Symbol.asyncIterator]();return new ReadableStream({async pull(i){let{done:r,value:s}=await t.next();if(r)return i.close();i.enqueue(s)}})},nH=(n)=>Object.assign(n,{eventStreamMarshaller:n.eventStreamSerdeProvider(n)});class HA{marshaller;serializer;deserializer;serdeContext;defaultContentType;constructor({marshaller:n,serializer:t,deserializer:i,serdeContext:r,defaultContentType:s}){this.marshaller=n,this.serializer=t,this.deserializer=i,this.serdeContext=r,this.defaultContentType=s}async serializeEventStream({eventStream:n,requestSchema:t,initialRequest:i}){let r=this.marshaller,s=t.getEventStreamMember(),f=t.getMemberSchema(s),h=this.serializer,_=this.defaultContentType,c=Symbol("initialRequestMarker"),o={async*[Symbol.asyncIterator](){if(i){let w={":event-type":{type:"string",value:"initial-request"},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:_}};h.write(t,i);let e=h.flush();yield{[c]:!0,headers:w,body:e}}for await(let w of n)yield w}};return r.serialize(o,(w)=>{if(w[c])return{headers:w.headers,body:w.body};let e="";for(let E in w)if(E!=="__type"){e=E;break}let{additionalHeaders:u,body:y,eventType:A,explicitPayloadContentType:R}=this.writeEventBody(e,f,w);return{headers:{":event-type":{type:"string",value:A},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:R??_},...u},body:y}})}async deserializeEventStream({response:n,responseSchema:t,initialResponseContainer:i}){let r=this.marshaller,s=t.getEventStreamMember(),h=t.getMemberSchema(s).getMemberSchemas(),_=Symbol("initialResponseMarker"),c=r.deserialize(n.body,async(e)=>{let u="";for(let A in e)if(A!=="__type"){u=A;break}let y=e[u].body;if(u==="initial-response"){let A=await this.deserializer.read(t,y);return delete A[s],{[_]:!0,...A}}else if(u in h){let A=h[u];if(A.isStructSchema()){let R={},M=!1;for(let[E,g]of A.structIterator()){let{eventHeader:T,eventPayload:S}=g.getMergedTraits();if(M=M||Boolean(T||S),S){if(g.isBlobSchema())R[E]=y;else if(g.isStringSchema())R[E]=(this.serdeContext?.utf8Encoder??PI)(y);else if(g.isStructSchema())R[E]=await this.deserializer.read(g,y)}else if(T){let L=e[u].headers[E]?.value;if(L!=null)if(g.isNumericSchema())if(L&&typeof L==="object"&&"bytes"in L)R[E]=BigInt(L.toString());else R[E]=Number(L);else R[E]=L}}if(M)return{[u]:R};if(y.byteLength===0)return{[u]:{}}}return{[u]:await this.deserializer.read(A,y)}}else return{$unknown:e}}),o=c[Symbol.asyncIterator](),w=await o.next();if(w.done)return c;if(w.value?.[_]){if(!t)throw Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");for(let e in w.value)i[e]=w.value[e]}return{async*[Symbol.asyncIterator](){if(!w?.value?.[_])yield w.value;while(!0){let{done:e,value:u}=await o.next();if(e)break;yield u}}}}writeEventBody(n,t,i){let r=this.serializer,s=n,f=null,h,_=(()=>{return t.getSchema()[4].includes(n)})(),c={};if(!_){let[e,u]=i[n];s=e,r.write(15,u)}else{let e=t.getMemberSchema(n);if(e.isStructSchema()){for(let[u,y]of e.structIterator()){let{eventHeader:A,eventPayload:R}=y.getMergedTraits();if(R)f=u;else if(A){let M=i[n][u],E="binary";if(y.isNumericSchema())if(-2147483648<=M&&M<=2147483647)E="integer";else E="long";else if(y.isTimestampSchema())E="timestamp";else if(y.isStringSchema())E="string";else if(y.isBooleanSchema())E="boolean";if(M!=null)c[u]={type:E,value:M},delete i[n][u]}}if(f!==null){let u=e.getMemberSchema(f);if(u.isBlobSchema())h="application/octet-stream";else if(u.isStringSchema())h="text/plain";r.write(u,i[n][f])}else r.write(e,i[n])}else if(e.isUnitSchema())r.write(e,{});else throw Error("@smithy/core/event-streams - non-struct member not supported in event stream union.")}let o=r.flush()??new Uint8Array;return{body:typeof o==="string"?(this.serdeContext?.utf8Decoder??YI)(o):o,eventType:s,explicitPayloadContentType:h,additionalHeaders:c}}}tH.EventStreamCodec=no;tH.EventStreamMarshaller=ho;tH.EventStreamSerde=HA;tH.HeaderMarshaller=pc;tH.Int64=vr;tH.MessageDecoderStream=to;tH.MessageEncoderStream=io;tH.SmithyMessageDecoderStream=ro;tH.SmithyMessageEncoderStream=so;tH.UniversalEventStreamMarshaller=_o;tH.eventStreamSerdeProvider=ZI;tH.getChunkedStream=IA;tH.getMessageUnmarshaller=fo;tH.getUnmarshalledStream=qI;tH.iterableToReadableStream=pI;tH.readableStreamToIterable=vI;tH.resolveEventStreamSerdeConfig=nH;tH.universalEventStreamSerdeProvider=mI});var kn=nn((zH)=>{var{Uint8ArrayBlobAdapter:co,sdkStreamMixin:gH,splitEvery:SH,splitHeader:PA,fromBase64:GA,_parseEpochTimestamp:LH,_parseRfc7231DateTime:$H,_parseRfc3339DateTimeWithOffset:OH,LazyJsonString:YA,NumericValue:UH,toUtf8:FA,fromUtf8:bH,generateIdempotencyToken:NH,toBase64:WA,dateToUtcString:BH,quoteHeader:IH}=jn(),{TypeRegistry:HH,NormalizedSchema:Xt,translateTraits:XA}=Ei(),{HttpRequest:pr,HttpResponse:lA,isValidHostname:JA}=Dt(),{parseQueryString:GH,parseUrl:WH}=Dt();zH.HttpRequest=pr;zH.HttpResponse=lA;zH.isValidHostname=JA;zH.parseQueryString=GH;zH.parseUrl=WH;var{FieldPosition:DH}=mi(),tr=async(n=new Uint8Array,t)=>{if(n instanceof Uint8Array)return co.mutate(n);if(!n)return co.mutate(new Uint8Array);let i=t.streamCollector(n);return co.mutate(await i)};function wf(n){return encodeURIComponent(n).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}class ns{serdeContext;setSerdeContext(n){this.serdeContext=n}}class C_ extends ns{options;compositeErrorRegistry;constructor(n){super();this.options=n,this.compositeErrorRegistry=HH.for(n.defaultNamespace);for(let t of n.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(t)}getRequestType(){return pr}getResponseType(){return lA}setSerdeContext(n){if(this.serdeContext=n,this.serializer.setSerdeContext(n),this.deserializer.setSerdeContext(n),this.getPayloadCodec())this.getPayloadCodec().setSerdeContext(n)}updateServiceEndpoint(n,t){if("url"in t){if(n.protocol=t.url.protocol,n.hostname=t.url.hostname,n.port=t.url.port?Number(t.url.port):void 0,n.path=t.url.pathname,n.fragment=t.url.hash||void 0,n.username=t.url.username||void 0,n.password=t.url.password||void 0,!n.query)n.query={};for(let[i,r]of t.url.searchParams.entries())n.query[i]=r;if(t.headers)for(let i in t.headers)n.headers[i]=t.headers[i].join(", ");return n}else{if(n.protocol=t.protocol,n.hostname=t.hostname,n.port=t.port?Number(t.port):void 0,n.path=t.path,n.query={...t.query},t.headers)for(let i in t.headers)n.headers[i]=t.headers[i];return n}}setHostPrefix(n,t,i){if(this.serdeContext?.disableHostPrefix)return;let r=Xt.of(t.input),s=XA(t.traits??{});if(s.endpoint){let f=s.endpoint?.[0];if(typeof f==="string"){for(let[h,_]of r.structIterator()){if(!_.getMergedTraits().hostLabel)continue;let c=i[h];if(typeof c!=="string")throw Error(`@smithy/core/schema - ${h} in input must be a string as hostLabel.`);f=f.replace(`{${h}}`,c)}if(n.hostname=f+n.hostname,!JA(n.hostname))throw Error(`[${n.hostname}] is not a valid hostname.`)}}}deserializeMetadata(n){return{httpStatusCode:n.statusCode,requestId:n.headers["x-amzn-requestid"]??n.headers["x-amzn-request-id"]??n.headers["x-amz-request-id"],extendedRequestId:n.headers["x-amz-id-2"],cfId:n.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream:n,requestSchema:t,initialRequest:i}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:n,requestSchema:t,initialRequest:i})}async deserializeEventStream({response:n,responseSchema:t,initialResponseContainer:i}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:n,responseSchema:t,initialResponseContainer:i})}async loadEventStreamCapability(){let{EventStreamSerde:n,eventStreamSerdeProvider:t}=z_(),i=this.resolveEventStreamMarshaller(t);return new n({marshaller:i,serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}resolveEventStreamMarshaller(n){let t=this.serdeContext;if(t.eventStreamMarshaller)return t.eventStreamMarshaller;return n(this.serdeContext)}getDefaultContentType(){throw Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(n,t,i,r,s){return[]}getEventStreamMarshaller(){let n=this.serdeContext;if(!n.eventStreamMarshaller)throw Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return n.eventStreamMarshaller}}class QA extends C_{async serializeRequest(n,t,i){let r=t&&typeof t==="object"?t:{},s=this.serializer,f={},h={},_=await i.endpoint(),c=Xt.of(n?.input),o=[],w=[],e=!1,u,y=new pr({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:f,headers:h,body:void 0});if(_){this.updateServiceEndpoint(y,_),this.setHostPrefix(y,n,r);let A=XA(n.traits);if(A.http){y.method=A.http[0];let[R,M]=A.http[1].split("?");if(y.path=="/")y.path=R;else y.path+=R;let E=new URLSearchParams(M??"");for(let[g,T]of E)f[g]=T}}for(let[A,R]of c.structIterator()){let M=R.getMergedTraits()??{},E=r[A];if(E==null&&!R.isIdempotencyToken()){if(M.httpLabel){if(y.path.includes(`{${A}+}`)||y.path.includes(`{${A}}`))throw Error(`No value provided for input HTTP label: ${A}.`)}continue}if(M.httpPayload)if(R.isStreaming())if(R.isStructSchema()){if(r[A])u=await this.serializeEventStream({eventStream:r[A],requestSchema:c})}else u=E;else s.write(R,E),u=s.flush();else if(M.httpLabel){s.write(R,E);let g=s.flush();if(y.path.includes(`{${A}+}`))y.path=y.path.replace(`{${A}+}`,g.split("/").map(wf).join("/"));else if(y.path.includes(`{${A}}`))y.path=y.path.replace(`{${A}}`,wf(g))}else if(M.httpHeader)s.write(R,E),h[M.httpHeader.toLowerCase()]=String(s.flush());else if(typeof M.httpPrefixHeaders==="string")for(let g in E){let T=E[g],S=M.httpPrefixHeaders+g;s.write([R.getValueSchema(),{httpHeader:S}],T),h[S.toLowerCase()]=s.flush()}else if(M.httpQuery||M.httpQueryParams)this.serializeQuery(R,E,f);else e=!0,o.push(A),w.push(R)}if(e&&r){let[A,R]=(c.getName(!0)??"#Unknown").split("#"),M=c.getSchema()[6],E=[3,A,R,c.getMergedTraits(),o,w,void 0];if(M)E[6]=M;else E.pop();s.write(E,r),u=s.flush()}return y.headers=h,y.query=f,y.body=u,y}serializeQuery(n,t,i){let r=this.serializer,s=n.getMergedTraits();if(s.httpQueryParams){for(let f in t)if(!(f in i)){let h=t[f],_=n.getValueSchema();Object.assign(_.getMergedTraits(),{...s,httpQuery:f,httpQueryParams:void 0}),this.serializeQuery(_,h,i)}return}if(n.isListSchema()){let f=!!n.getMergedTraits().sparse,h=[];for(let _ of t){r.write([n.getValueSchema(),s],_);let c=r.flush();if(f||c!==void 0)h.push(c)}i[s.httpQuery]=h}else r.write([n,s],t),i[s.httpQuery]=r.flush()}async deserializeResponse(n,t,i){let r=this.deserializer,s=Xt.of(n.output),f={};if(i.statusCode>=300){let _=await tr(i.body,t);if(_.byteLength>0)Object.assign(f,await r.read(15,_));throw await this.handleError(n,t,i,f,this.deserializeMetadata(i)),Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(let _ in i.headers){let c=i.headers[_];delete i.headers[_],i.headers[_.toLowerCase()]=c}let h=await this.deserializeHttpMessage(s,t,i,f);if(h.length){let _=await tr(i.body,t);if(_.byteLength>0){let c=await r.read(s,_);for(let o of h)if(c[o]!=null)f[o]=c[o]}}else if(h.discardResponseBody)await tr(i.body,t);return f.$metadata=this.deserializeMetadata(i),f}async deserializeHttpMessage(n,t,i,r,s){let f;if(r instanceof Set)f=s;else f=r;let h=!0,_=this.deserializer,c=Xt.of(n),o=[];for(let[w,e]of c.structIterator()){let u=e.getMemberTraits();if(u.httpPayload){if(h=!1,e.isStreaming())if(e.isStructSchema())f[w]=await this.deserializeEventStream({response:i,responseSchema:c});else f[w]=gH(i.body);else if(i.body){let A=await tr(i.body,t);if(A.byteLength>0)f[w]=await _.read(e,A)}}else if(u.httpHeader){let y=String(u.httpHeader).toLowerCase(),A=i.headers[y];if(A!=null)if(e.isListSchema()){let R=e.getValueSchema();R.getMergedTraits().httpHeader=y;let M;if(R.isTimestampSchema()&&R.getSchema()===4)M=SH(A,",",2);else M=PA(A);let E=[];for(let g of M)E.push(await _.read(R,g.trim()));f[w]=E}else f[w]=await _.read(e,A)}else if(u.httpPrefixHeaders!==void 0){f[w]={};for(let y in i.headers)if(y.startsWith(u.httpPrefixHeaders)){let A=i.headers[y],R=e.getValueSchema();R.getMergedTraits().httpHeader=y,f[w][y.slice(u.httpPrefixHeaders.length)]=await _.read(R,A)}}else if(u.httpResponseCode)f[w]=i.statusCode;else o.push(w)}return o.discardResponseBody=h,o}}class zA extends C_{async serializeRequest(n,t,i){let r=this.serializer,s={},f={},h=await i.endpoint(),_=Xt.of(n?.input),c=_.getSchema(),o,w=t&&typeof t==="object"?t:{},e=new pr({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:s,headers:f,body:void 0});if(h)this.updateServiceEndpoint(e,h),this.setHostPrefix(e,n,w);if(w){let u=_.getEventStreamMember();if(u){if(w[u]){let y={};for(let[A,R]of _.structIterator())if(A!==u&&w[A])r.write(R,w[A]),y[A]=r.flush();o=await this.serializeEventStream({eventStream:w[u],requestSchema:_,initialRequest:y})}}else r.write(c,w),o=r.flush()}return e.headers=Object.assign(e.headers,f),e.query=s,e.body=o,e.method="POST",e}async deserializeResponse(n,t,i){let r=this.deserializer,s=Xt.of(n.output),f={};if(i.statusCode>=300){let _=await tr(i.body,t);if(_.byteLength>0)Object.assign(f,await r.read(15,_));throw await this.handleError(n,t,i,f,this.deserializeMetadata(i)),Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(let _ in i.headers){let c=i.headers[_];delete i.headers[_],i.headers[_.toLowerCase()]=c}let h=s.getEventStreamMember();if(h)f[h]=await this.deserializeEventStream({response:i,responseSchema:s,initialResponseContainer:f});else{let _=await tr(i.body,t);if(_.byteLength>0)Object.assign(f,await r.read(s,_))}return f.$metadata=this.deserializeMetadata(i),f}}var CA=(n,t,i,r,s,f)=>{if(t!=null&&t[i]!==void 0){let h=r();if(h==null||h.length<=0)throw Error("Empty value provided for input HTTP label: "+i+".");n=n.replace(s,f?h.split("/").map((_)=>wf(_)).join("/"):wf(h))}else throw Error("No value provided for input HTTP label: "+i+".");return n};function PH(n,t){return new oo(n,t)}class oo{input;context;query={};method="";headers={};path="";body=null;hostname="";resolvePathStack=[];constructor(n,t){this.input=n,this.context=t}async build(){let{hostname:n,protocol:t="https",port:i,path:r}=await this.context.endpoint();this.path=r;for(let s of this.resolvePathStack)s(this.path);return new pr({protocol:t,hostname:this.hostname||n,port:i,method:this.method,path:this.path,query:this.query,body:this.body,headers:this.headers})}hn(n){return this.hostname=n,this}bp(n){return this.resolvePathStack.push((t)=>{this.path=`${t?.endsWith("/")?t.slice(0,-1):t||""}`+n}),this}p(n,t,i,r){return this.resolvePathStack.push((s)=>{this.path=CA(s,this.input,n,t,i,r)}),this}h(n){return this.headers=n,this}q(n){return this.query=n,this}b(n){return this.body=n,this}m(n){return this.method=n,this}}function wo(n,t){if(t.timestampFormat.useTrait){if(n.isTimestampSchema()&&(n.getSchema()===5||n.getSchema()===6||n.getSchema()===7))return n.getSchema()}let{httpLabel:i,httpPrefixHeaders:r,httpHeader:s,httpQuery:f}=n.getMergedTraits();return(t.httpBindings?typeof r==="string"||Boolean(s)?6:Boolean(f)||Boolean(i)?5:void 0:void 0)??t.timestampFormat.default}class eo extends ns{settings;constructor(n){super();this.settings=n}read(n,t){let i=Xt.of(n);if(i.isListSchema())return PA(t).map((r)=>this.read(i.getValueSchema(),r));if(i.isBlobSchema())return(this.serdeContext?.base64Decoder??GA)(t);if(i.isTimestampSchema())switch(wo(i,this.settings)){case 5:return OH(t);case 6:return $H(t);case 7:return LH(t);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",t),new Date(t)}if(i.isStringSchema()){let r=i.getMergedTraits().mediaType,s=t;if(r){if(i.getMergedTraits().httpHeader)s=this.base64ToUtf8(s);if(r==="application/json"||r.endsWith("+json"))s=YA.from(s);return s}}if(i.isNumericSchema())return Number(t);if(i.isBigIntegerSchema())return BigInt(t);if(i.isBigDecimalSchema())return new UH(t,"bigDecimal");if(i.isBooleanSchema())return String(t).toLowerCase()==="true";return t}base64ToUtf8(n){return(this.serdeContext?.utf8Encoder??FA)((this.serdeContext?.base64Decoder??GA)(n))}}class VA extends ns{codecDeserializer;stringDeserializer;constructor(n,t){super();this.codecDeserializer=n,this.stringDeserializer=new eo(t)}setSerdeContext(n){this.stringDeserializer.setSerdeContext(n),this.codecDeserializer.setSerdeContext(n),this.serdeContext=n}read(n,t){let i=Xt.of(n),r=i.getMergedTraits(),s=this.serdeContext?.utf8Encoder??FA;if(r.httpHeader||r.httpResponseCode)return this.stringDeserializer.read(i,s(t));if(r.httpPayload){if(i.isBlobSchema()){let f=this.serdeContext?.utf8Decoder??bH;if(typeof t==="string")return f(t);return t}else if(i.isStringSchema()){if("byteLength"in t)return s(t);return t}}return this.codecDeserializer.read(i,t)}}class uo extends ns{settings;stringBuffer="";constructor(n){super();this.settings=n}write(n,t){let i=Xt.of(n);switch(typeof t){case"object":if(t===null){this.stringBuffer="null";return}if(i.isTimestampSchema()){if(!(t instanceof Date))throw Error(`@smithy/core/protocols - received non-Date value ${t} when schema expected Date in ${i.getName(!0)}`);switch(wo(i,this.settings)){case 5:this.stringBuffer=t.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=BH(t);break;case 7:this.stringBuffer=String(t.getTime()/1000);break;default:console.warn("Missing timestamp format, using epoch seconds",t),this.stringBuffer=String(t.getTime()/1000)}return}if(i.isBlobSchema()&&"byteLength"in t){this.stringBuffer=(this.serdeContext?.base64Encoder??WA)(t);return}if(i.isListSchema()&&Array.isArray(t)){let f="";for(let h of t){this.write([i.getValueSchema(),i.getMergedTraits()],h);let _=this.flush(),c=i.getValueSchema().isTimestampSchema()?_:IH(_);if(f!=="")f+=", ";f+=c}this.stringBuffer=f;return}this.stringBuffer=JSON.stringify(t,null,2);break;case"string":let r=i.getMergedTraits().mediaType,s=t;if(r){if(r==="application/json"||r.endsWith("+json"))s=YA.from(s);if(i.getMergedTraits().httpHeader){this.stringBuffer=(this.serdeContext?.base64Encoder??WA)(s.toString());return}}this.stringBuffer=t;break;default:if(i.isIdempotencyToken())this.stringBuffer=NH();else this.stringBuffer=String(t)}}flush(){let n=this.stringBuffer;return this.stringBuffer="",n}}class KA{codecSerializer;stringSerializer;buffer;constructor(n,t,i=new uo(t)){this.codecSerializer=n,this.stringSerializer=i}setSerdeContext(n){this.codecSerializer.setSerdeContext(n),this.stringSerializer.setSerdeContext(n)}write(n,t){let i=Xt.of(n),r=i.getMergedTraits();if(r.httpHeader||r.httpLabel||r.httpQuery){this.stringSerializer.write(i,t),this.buffer=this.stringSerializer.flush();return}return this.codecSerializer.write(i,t)}flush(){if(this.buffer!==void 0){let n=this.buffer;return this.buffer=void 0,n}return this.codecSerializer.flush()}}class xA{name;kind;values;constructor({name:n,kind:t=DH.HEADER,values:i=[]}){this.name=n,this.kind=t,this.values=i}add(n){this.values.push(n)}set(n){this.values=n}remove(n){this.values=this.values.filter((t)=>t!==n)}toString(){return this.values.map((n)=>n.includes(",")||n.includes(" ")?`"${n}"`:n).join(", ")}get(){return this.values}}class jA{entries={};encoding;constructor({fields:n=[],encoding:t="utf-8"}){n.forEach(this.setField.bind(this)),this.encoding=t}setField(n){this.entries[n.name.toLowerCase()]=n}getField(n){return this.entries[n.toLowerCase()]}removeField(n){delete this.entries[n.toLowerCase()]}getByType(n){return Object.values(this.entries).filter((t)=>t.kind===n)}}var YH=(n)=>{return{setHttpHandler(t){n.httpHandler=t},httpHandler(){return n.httpHandler},updateHttpClientConfig(t,i){n.httpHandler?.updateHttpClientConfig(t,i)},httpHandlerConfigs(){return n.httpHandler.httpHandlerConfigs()}}},FH=(n)=>{return{httpHandler:n.httpHandler()}},DA="content-length";function kA(n){return(t)=>async(i)=>{let r=i.request;if(pr.isInstance(r)){let{body:s,headers:f}=r;if(s&&Object.keys(f).map((h)=>h.toLowerCase()).indexOf(DA)===-1)try{let h=n(s);r.headers={...r.headers,[DA]:String(h)}}catch(h){}}return t({...i,request:r})}}var qA={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},XH=(n)=>({applyToStack:(t)=>{t.add(kA(n.bodyLengthChecker),qA)}}),of=(n)=>encodeURIComponent(n).replace(/[!'()*]/g,lH),lH=(n)=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`,JH=(n)=>n.split("/").map(of).join("/");function QH(n){let t=[];for(let i of Object.keys(n).sort()){let r=n[i];if(i=of(i),Array.isArray(r))for(let s=0,f=r.length;s<f;s++)t.push(`${i}=${of(r[s])}`);else{let s=i;if(r||typeof r==="string")s+=`=${of(r)}`;t.push(s)}}return t.join("&")}zH.Field=xA;zH.Fields=jA;zH.FromStringShapeDeserializer=eo;zH.HttpBindingProtocol=QA;zH.HttpInterceptingShapeDeserializer=VA;zH.HttpInterceptingShapeSerializer=KA;zH.HttpProtocol=C_;zH.RequestBuilder=oo;zH.RpcProtocol=zA;zH.SerdeContext=ns;zH.ToStringShapeSerializer=uo;zH.buildQueryString=QH;zH.collectBody=tr;zH.contentLengthMiddleware=kA;zH.contentLengthMiddlewareOptions=qA;zH.determineTimestampFormat=wo;zH.escapeUri=of;zH.escapeUriPath=JH;zH.extendedEncodeURIComponent=wf;zH.getContentLengthPlugin=XH;zH.getHttpHandlerExtensionConfiguration=YH;zH.requestBuilder=PH;zH.resolveHttpHandlerRuntimeConfig=FH;zH.resolvedPath=CA});var Af=nn((QG)=>{var{Readable:MG}=cn("stream"),{NoOpLogger:EG,normalizeProvider:mA}=at(),{HttpResponse:ZA,HttpRequest:K_}=kn(),{parseRfc7231DateTime:TG,v4:aA}=jn(),vA=(n)=>n?.body instanceof MG||typeof ReadableStream<"u"&&n?.body instanceof ReadableStream,gG=["AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"],SG=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],LG=["TimeoutError","RequestTimeout","RequestTimeoutException"],$G=[500,502,503,504],OG=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],UG=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],Mo=(n)=>n?.$retryable!==void 0,pA=(n)=>gG.includes(n.name),nR=(n)=>n.$metadata?.clockSkewCorrected,tR=(n)=>{let t=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);if(!(n&&n instanceof TypeError))return!1;return t.has(n.message)},uf=(n)=>n.$metadata?.httpStatusCode===429||SG.includes(n.name)||n.$retryable?.throttling==!0,yf=(n,t=0)=>Mo(n)||nR(n)||n.name==="InvalidSignatureException"&&n.message?.includes("Signature expired")||LG.includes(n.name)||OG.includes(n?.code||"")||UG.includes(n?.code||"")||$G.includes(n.$metadata?.httpStatusCode||0)||tR(n)||rR(n)||n.cause!==void 0&&t<=10&&yf(n.cause,t+1),iR=(n)=>{if(n.$metadata?.httpStatusCode!==void 0){let t=n.$metadata.httpStatusCode;if(500<=t&&t<=599&&!yf(n))return!0;return!1}return!1};function rR(n){return n.code==="ERR_HTTP2_STREAM_ERROR"&&n.message.includes("NGHTTP2_REFUSED_STREAM")}var sR=100,j_=20000,fR=500,x_=500,_R=5,hR=10,Eo=1,k_="amz-sdk-invocation-id",q_="amz-sdk-request";function cR(n,t){if(!ZA.isInstance(n))return;for(let i of Object.keys(n.headers)){let r=i.toLowerCase();if(r==="retry-after"){let s=n.headers[i],f=NaN;if(s.endsWith("GMT"))try{f=(TG(s).getTime()-Date.now())/1000}catch(h){t?.trace?.("Failed to parse retry-after header"),t?.trace?.(h)}else if(s.match(/ GMT, ((\d+)|(\d+\.\d+))$/))f=Number(s.match(/ GMT, ([\d.]+)$/)?.[1]);else if(s.match(/^((\d+)|(\d+\.\d+))$/))f=Number(s);else if(Date.parse(s)>=Date.now())f=(Date.parse(s)-Date.now())/1000;if(isNaN(f))return;return new Date(Date.now()+f*1000)}else if(r==="x-amz-retry-after"){let s=n.headers[i],f=Number(s);if(isNaN(f)){t?.trace?.(`Failed to parse x-amz-retry-after=${s}`);return}return new Date(Date.now()+f)}}}function bG(n,t){return cR(n,t)}var oR=(n)=>{if(n instanceof Error)return n;if(n instanceof Object)return Object.assign(Error(),n);if(typeof n==="string")return Error(n);return Error(`AWS SDK error wrapper for ${n}`)};function wR(n){return(t)=>(i,r)=>async(s)=>{let f=await t.retryStrategy(),h=await t.maxAttempts();if(BG(f)){f=f;let _=await f.acquireInitialRetryToken((r.partition_id??"")+(r.__retryLongPoll?":longpoll":"")),c=Error(),o=0,w=0,{request:e}=s,u=K_.isInstance(e);if(u)e.headers[k_]=aA();while(!0)try{if(u)e.headers[q_]=`attempt=${o+1}; max=${h}`;let{response:y,output:A}=await i(s);return f.recordSuccess(_),A.$metadata.attempts=o+1,A.$metadata.totalRetryDelay=w,{response:y,output:A}}catch(y){let A=IG(y,t.logger);if(c=oR(y),u&&n(e))throw(r.logger instanceof EG?console:r.logger)?.warn("An error was encountered in a non-retryable streaming request."),c;try{_=await f.refreshRetryTokenForRetry(_,A)}catch(M){if(!c.$metadata)c.$metadata={};throw c.$metadata.attempts=o+1,c.$metadata.totalRetryDelay=w,c}o=_.getRetryCount();let R=_.getRetryDelay();if(w+=(_?.$retryLog?.acquisitionDelay??0)+R,R>0)await NG(R)}}else{if(f=f,f?.mode)r.userAgent=[...r.userAgent||[],["cfg/retry-mode",f.mode]];return f.retry(i,s)}}}var NG=(n)=>new Promise((t)=>setTimeout(t,n)),BG=(n)=>typeof n.acquireInitialRetryToken<"u"&&typeof n.refreshRetryTokenForRetry<"u"&&typeof n.recordSuccess<"u",IG=(n,t)=>{let i={error:n,errorType:HG(n)},r=cR(n.$response,t);if(r)i.retryAfterHint=r;return i},HG=(n)=>{if(uf(n))return"THROTTLING";if(yf(n))return"TRANSIENT";if(iR(n))return"SERVER_ERROR";return"CLIENT_ERROR"},eR={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function GG(n){let t=wR(n);return(i)=>({applyToStack:(r)=>{r.add(t(i),eR)}})}class df{static setTimeoutFn=(n,t)=>setTimeout(n,t);beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(n){this.beta=n?.beta??0.7,this.minCapacity=n?.minCapacity??1,this.minFillRate=n?.minFillRate??0.5,this.scaleConstant=n?.scaleConstant??0.4,this.smooth=n?.smooth??0.8,this.lastThrottleTime=this.getCurrentTimeInSeconds(),this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}async getSendToken(){return this.acquireTokenBucket(1)}updateClientSendingRate(n){let t;this.updateMeasuredRate();let i=n;if(i?.errorType==="THROTTLING"||uf(i?.error??n)){let f=!this.enabled?this.measuredTxRate:Math.min(this.measuredTxRate,this.fillRate);this.lastMaxRate=f,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),t=this.cubicThrottle(f),this.enableTokenBucket()}else this.calculateTimeWindow(),t=this.cubicSuccess(this.getCurrentTimeInSeconds());let s=Math.min(t,2*this.measuredTxRate);this.updateTokenBucketRate(s)}getCurrentTimeInSeconds(){return Date.now()/1000}async acquireTokenBucket(n){if(!this.enabled)return;this.refillTokenBucket();while(n>this.availableTokens){let t=(n-this.availableTokens)/this.fillRate*1000;await new Promise((i)=>df.setTimeoutFn(i,t)),this.refillTokenBucket()}this.availableTokens=this.availableTokens-n}refillTokenBucket(){let n=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=n;return}let t=(n-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+t),this.lastTimestamp=n}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,0.3333333333333333))}cubicThrottle(n){return this.getPrecise(n*this.beta)}cubicSuccess(n){return this.getPrecise(this.scaleConstant*Math.pow(n-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(n){this.refillTokenBucket(),this.fillRate=Math.max(n,this.minFillRate),this.maxCapacity=Math.max(n,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){let n=this.getCurrentTimeInSeconds(),t=Math.floor(n*2)/2;if(this.requestCount++,t>this.lastTxRateBucket){let i=this.requestCount/(t-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(i*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=t}}getPrecise(n){return parseFloat(n.toFixed(8))}}class Gn{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return Gn.v2026?50:100}static throttlingDelay(){return Gn.v2026?1000:500}static cost(){return Gn.v2026?14:5}static throttlingCost(){return Gn.v2026?5:10}static modifiedCostType(){return Gn.v2026?"THROTTLING":"TRANSIENT"}}class uR{x=Gn.delay();computeNextBackoffDelay(n){let t=Math.random(),i=2,r=t*Math.min(this.x*2**n,j_);return Math.floor(r)}setDelayBase(n){this.x=n}}class yo{delay;count;cost;longPoll;$retryLog={acquisitionDelay:0};constructor(n,t,i,r){this.delay=n,this.count=t,this.cost=i,this.longPoll=r}getRetryCount(){return this.count}getRetryDelay(){return Math.min(j_,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var ti;(function(n){n.STANDARD="standard",n.ADAPTIVE="adaptive"})(ti||(ti={}));var ir=3,yR=ti.STANDARD,V_={incompatible:1,attempts:2,capacity:3},ef=class{mode=ti.STANDARD;retryBackoffStrategy;capacity=x_;maxAttemptsProvider;baseDelay;constructor(t){if(typeof t==="number")this.maxAttemptsProvider=async()=>t;else if(typeof t==="function")this.maxAttemptsProvider=t;else if(t&&typeof t==="object")this.maxAttemptsProvider=async()=>t.maxAttempts,this.baseDelay=t.baseDelay,this.retryBackoffStrategy=t.backoff;this.maxAttemptsProvider??=async()=>ir,this.baseDelay??=Gn.delay(),this.retryBackoffStrategy??=new uR}async acquireInitialRetryToken(t){return new yo(Gn.delay(),0,void 0,Gn.v2026&&t.includes(":longpoll"))}async refreshRetryTokenForRetry(t,i){let r=await this.getMaxAttempts(),s=this.retryCode(t,i,r),f=s===0,h=t.isLongPoll?.();if(f||h){let _=i.errorType;this.retryBackoffStrategy.setDelayBase(_==="THROTTLING"?Gn.throttlingDelay():this.baseDelay);let c=this.retryBackoffStrategy.computeNextBackoffDelay(t.getRetryCount()),o=c;if(i.retryAfterHint instanceof Date)o=Math.max(c,Math.min(i.retryAfterHint.getTime()-Date.now(),c+5000));if(!f){let w=Gn.v2026&&s===V_.capacity&&h?o:0;if(w>0)await new Promise((e)=>setTimeout(e,w))}else{let w=this.getCapacityCost(_);this.capacity-=w;let e=new yo(0,t.getRetryCount()+1,w,t.isLongPoll?.()??!1);return await new Promise((u)=>setTimeout(u,o)),e.$retryLog.acquisitionDelay=o,e}}throw Error("No retry token available")}recordSuccess(t){this.capacity=Math.min(x_,this.capacity+(t.getRetryCost()??Eo))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(t){return console.warn(`Max attempts provider could not resolve. Using default of ${ir}`),ir}}retryCode(t,i,r){let s=t.getRetryCount()+1,f=this.isRetryableError(i.errorType)?0:V_.incompatible,h=s<r?0:V_.attempts,_=this.capacity>=this.getCapacityCost(i.errorType)?0:V_.capacity;return f||h||_}getCapacityCost(t){return t===Gn.modifiedCostType()?Gn.throttlingCost():Gn.cost()}isRetryableError(t){return t==="THROTTLING"||t==="TRANSIENT"}},dR=class{mode=ti.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(t,i){let{rateLimiter:r}=i??{};this.rateLimiter=r??new df,this.standardRetryStrategy=i?new ef({maxAttempts:typeof t==="number"?t:3,...i}):new ef(t)}async acquireInitialRetryToken(t){let i=await this.standardRetryStrategy.acquireInitialRetryToken(t);return await this.rateLimiter.getSendToken(),i}async refreshRetryTokenForRetry(t,i){this.rateLimiter.updateClientSendingRate(i);let r=await this.standardRetryStrategy.refreshRetryTokenForRetry(t,i);return await this.rateLimiter.getSendToken(),r}recordSuccess(t){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(t)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}};class AR extends ef{computeNextBackoffDelay;constructor(n,t=Gn.delay()){super(typeof n==="function"?n:async()=>n);if(typeof t==="number")this.computeNextBackoffDelay=()=>t;else this.computeNextBackoffDelay=t;this.retryBackoffStrategy.computeNextBackoffDelay=(i)=>{let r=i+1;return this.computeNextBackoffDelay(r)}}}var WG=(n,t)=>{let i=n,r=Eo,s=_R,f=hR,h=n,_=(e)=>e.name==="TimeoutError"?f:s,c=(e)=>_(e)<=h;return Object.freeze({hasRetryTokens:c,retrieveRetryTokens:(e)=>{if(!c(e))throw Error("No retry token available");let u=_(e);return h-=u,u},releaseRetryTokens:(e)=>{h+=e??r,h=Math.min(h,i)}})},RR=(n,t)=>Math.floor(Math.min(j_,Math.random()*2**t*n)),MR=(n)=>{if(!n)return!1;return Mo(n)||pA(n)||uf(n)||yf(n)};class To{maxAttemptsProvider;retryDecider;delayDecider;retryQuota;mode=ti.STANDARD;constructor(n,t){this.maxAttemptsProvider=n,this.retryDecider=t?.retryDecider??MR,this.delayDecider=t?.delayDecider??RR,this.retryQuota=t?.retryQuota??WG(x_)}shouldRetry(n,t,i){return t<i&&this.retryDecider(n)&&this.retryQuota.hasRetryTokens(n)}async getMaxAttempts(){let n;try{n=await this.maxAttemptsProvider()}catch(t){n=ir}return n}async retry(n,t,i){let r,s=0,f=0,h=await this.getMaxAttempts(),{request:_}=t;if(K_.isInstance(_))_.headers[k_]=aA();while(!0)try{if(K_.isInstance(_))_.headers[q_]=`attempt=${s+1}; max=${h}`;if(i?.beforeRequest)await i.beforeRequest();let{response:c,output:o}=await n(t);if(i?.afterRequest)i.afterRequest(c);return this.retryQuota.releaseRetryTokens(r),o.$metadata.attempts=s+1,o.$metadata.totalRetryDelay=f,{response:c,output:o}}catch(c){let o=oR(c);if(s++,this.shouldRetry(o,s,h)){r=this.retryQuota.retrieveRetryTokens(o);let w=this.delayDecider(uf(o)?fR:sR,s),e=DG(o.$response),u=Math.max(e||0,w);f+=u,await new Promise((y)=>setTimeout(y,u));continue}if(!o.$metadata)o.$metadata={};throw o.$metadata.attempts=s,o.$metadata.totalRetryDelay=f,o}}}var DG=(n)=>{if(!ZA.isInstance(n))return;let t=Object.keys(n.headers).find((f)=>f.toLowerCase()==="retry-after");if(!t)return;let i=n.headers[t],r=Number(i);if(!Number.isNaN(r))return Math.min(r*1000,20000);let s=new Date(i);return Math.min(s.getTime()-Date.now(),20000)};class ER extends To{rateLimiter;constructor(n,t){let{rateLimiter:i,...r}=t??{};super(n,r);this.rateLimiter=i??new df,this.mode=ti.ADAPTIVE}async retry(n,t){return super.retry(n,t,{beforeRequest:async()=>{return this.rateLimiter.getSendToken()},afterRequest:(i)=>{this.rateLimiter.updateClientSendingRate(i)}})}}var Ao="AWS_MAX_ATTEMPTS",Ro="max_attempts",PG={environmentVariableSelector:(n)=>{let t=n[Ao];if(!t)return;let i=parseInt(t);if(Number.isNaN(i))throw Error(`Environment variable ${Ao} mast be a number, got "${t}"`);return i},configFileSelector:(n)=>{let t=n[Ro];if(!t)return;let i=parseInt(t);if(Number.isNaN(i))throw Error(`Shared config file entry ${Ro} mast be a number, got "${t}"`);return i},default:ir},YG=(n,t)=>{let{retryStrategy:i,retryMode:r}=n,{defaultMaxAttempts:s=ir,defaultBaseDelay:f=Gn.delay()}=t??{},h=mA(n.maxAttempts??s),_=i?Promise.resolve(i):void 0,c=async()=>{let o=await h();if(await mA(r)()===ti.ADAPTIVE)return new dR(h,{maxAttempts:o,baseDelay:f});return new ef({maxAttempts:o,baseDelay:f})};return Object.assign(n,{maxAttempts:h,retryStrategy:()=>_??=c()})},TR="AWS_RETRY_MODE",gR="retry_mode",FG={environmentVariableSelector:(n)=>n[TR],configFileSelector:(n)=>n[gR],default:yR},SR=()=>(n)=>async(t)=>{let{request:i}=t;if(K_.isInstance(i))delete i.headers[k_],delete i.headers[q_];return n(t)},LR={name:"omitRetryHeadersMiddleware",tags:["RETRY","HEADERS","OMIT_RETRY_HEADERS"],relation:"before",toMiddleware:"awsAuthMiddleware",override:!0},XG=(n)=>({applyToStack:(t)=>{t.addRelativeTo(SR(),LR)}}),lG=wR(vA),JG=GG(vA);QG.AdaptiveRetryStrategy=dR;QG.CONFIG_MAX_ATTEMPTS=Ro;QG.CONFIG_RETRY_MODE=gR;QG.ConfiguredRetryStrategy=AR;QG.DEFAULT_MAX_ATTEMPTS=ir;QG.DEFAULT_RETRY_DELAY_BASE=sR;QG.DEFAULT_RETRY_MODE=yR;QG.DefaultRateLimiter=df;QG.DeprecatedAdaptiveRetryStrategy=ER;QG.DeprecatedStandardRetryStrategy=To;QG.ENV_MAX_ATTEMPTS=Ao;QG.ENV_RETRY_MODE=TR;QG.INITIAL_RETRY_TOKENS=x_;QG.INVOCATION_ID_HEADER=k_;QG.MAXIMUM_RETRY_DELAY=j_;QG.NODE_MAX_ATTEMPT_CONFIG_OPTIONS=PG;QG.NODE_RETRY_MODE_CONFIG_OPTIONS=FG;QG.NO_RETRY_INCREMENT=Eo;QG.REQUEST_HEADER=q_;QG.RETRY_COST=_R;QG.RETRY_MODES=ti;QG.Retry=Gn;QG.StandardRetryStrategy=ef;QG.THROTTLING_RETRY_DELAY_BASE=fR;QG.TIMEOUT_RETRY_COST=hR;QG.defaultDelayDecider=RR;QG.defaultRetryDecider=MR;QG.getOmitRetryHeadersPlugin=XG;QG.getRetryAfterHint=bG;QG.getRetryPlugin=JG;QG.isBrowserNetworkError=tR;QG.isClockSkewCorrectedError=nR;QG.isClockSkewError=pA;QG.isNodeJsHttp2TransientError=rR;QG.isRetryableByTrait=Mo;QG.isServerError=iR;QG.isThrottlingError=uf;QG.isTransientError=yf;QG.omitRetryHeadersMiddleware=SR;QG.omitRetryHeadersMiddlewareOptions=LR;QG.resolveRetryConfig=YG;QG.retryMiddleware=lG;QG.retryMiddlewareOptions=eR});var OR=nn((H3)=>{var Oi={REQUEST_ID:Symbol.for("_AWS_LAMBDA_REQUEST_ID"),X_RAY_TRACE_ID:Symbol.for("_AWS_LAMBDA_X_RAY_TRACE_ID"),TENANT_ID:Symbol.for("_AWS_LAMBDA_TENANT_ID"),TRACEPARENT:Symbol.for("_AWS_LAMBDA_TRACEPARENT"),TRACESTATE:Symbol.for("_AWS_LAMBDA_TRACESTATE"),BAGGAGE:Symbol.for("_AWS_LAMBDA_BAGGAGE")},go=["true","1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA??"");if(!go)globalThis.awslambda=globalThis.awslambda||{};class m_{static PROTECTED_KEYS=Oi;isProtectedKey(n){return Object.values(Oi).includes(n)}getRequestId(){return this.get(Oi.REQUEST_ID)??"-"}getXRayTraceId(){return this.get(Oi.X_RAY_TRACE_ID)}getTenantId(){return this.get(Oi.TENANT_ID)}getTraceparent(){return this.get(Oi.TRACEPARENT)}getTracestate(){return this.get(Oi.TRACESTATE)}getBaggage(){return this.get(Oi.BAGGAGE)}}class $R extends m_{currentContext;getContext(){return this.currentContext}hasContext(){return this.currentContext!==void 0}get(n){return this.currentContext?.[n]}set(n,t){if(this.isProtectedKey(n))throw Error(`Cannot modify protected Lambda context field: ${String(n)}`);this.currentContext=this.currentContext||{},this.currentContext[n]=t}run(n,t){return this.currentContext=n,t()}}class Lo extends m_{als;static async create(){let n=new Lo,t=await import("async_hooks");return n.als=new t.AsyncLocalStorage,n}getContext(){return this.als.getStore()}hasContext(){return this.als.getStore()!==void 0}get(n){return this.als.getStore()?.[n]}set(n,t){if(this.isProtectedKey(n))throw Error(`Cannot modify protected Lambda context field: ${String(n)}`);let i=this.als.getStore();if(!i)throw Error("No context available");i[n]=t}run(n,t){return this.als.run(n,t)}}H3.InvokeStore=void 0;(function(n){let t=null;async function i(r){if(!t)t=(async()=>{let f=r===!0||"AWS_LAMBDA_MAX_CONCURRENCY"in process.env?await Lo.create():new $R;if(!go&&globalThis.awslambda?.InvokeStore)return globalThis.awslambda.InvokeStore;else if(!go&&globalThis.awslambda)return globalThis.awslambda.InvokeStore=f,f;else return f})();return t}n.getInstanceAsync=i,n._testing=process.env.AWS_LAMBDA_BENCHMARK_MODE==="1"?{reset:()=>{if(t=null,globalThis.awslambda?.InvokeStore)delete globalThis.awslambda.InvokeStore;globalThis.awslambda={InvokeStore:void 0}}}:void 0})(H3.InvokeStore||(H3.InvokeStore={}));H3.InvokeStoreBase=m_});var Ui=nn((k3)=>{var{getSmithyContext:$o}=Dt();k3.getSmithyContext=$o;var{HttpRequest:Oo}=kn(),{requestBuilder:W3}=kn();k3.requestBuilder=W3;var{HttpApiKeyAuthLocation:UR}=mi(),D3=(n,t)=>{if(!t||t.length===0)return n;let i=[];for(let r of t)for(let s of n)if(s.schemeId.split("#")[1]===r)i.push(s);for(let r of n)if(!i.find(({schemeId:s})=>s===r.schemeId))i.push(r);return i};function P3(n){let t=new Map;for(let i of n)t.set(i.schemeId,i);return t}var Uo=(n,t)=>(i,r)=>async(s)=>{let f=n.httpAuthSchemeProvider(await t.httpAuthSchemeParametersProvider(n,r,s.input)),h=n.authSchemePreference?await n.authSchemePreference():[],_=D3(f,h),c=P3(n.httpAuthSchemes),o=$o(r),w=[];for(let e of _){let u=c.get(e.schemeId);if(!u){w.push(`HttpAuthScheme \`${e.schemeId}\` was not enabled for this service.`);continue}let y=u.identityProvider(await t.identityProviderConfigProvider(n));if(!y){w.push(`HttpAuthScheme \`${e.schemeId}\` did not have an IdentityProvider configured.`);continue}let{identityProperties:A={},signingProperties:R={}}=e.propertiesExtractor?.(n,r)||{};e.identityProperties=Object.assign(e.identityProperties||{},A),e.signingProperties=Object.assign(e.signingProperties||{},R),o.selectedHttpAuthScheme={httpAuthOption:e,identity:await y(e.identityProperties),signer:u.signer};break}if(!o.selectedHttpAuthScheme)throw Error(w.join(`
|
|
24
|
+
`));return i(s)},bR={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},Y3=(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i})=>({applyToStack:(r)=>{r.addRelativeTo(Uo(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i}),bR)}}),NR={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"serializerMiddleware"},F3=(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i})=>({applyToStack:(r)=>{r.addRelativeTo(Uo(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i}),NR)}}),X3=(n)=>(t)=>{throw t},l3=(n,t)=>{},BR=(n)=>(t,i)=>async(r)=>{if(!Oo.isInstance(r.request))return t(r);let f=$o(i).selectedHttpAuthScheme;if(!f)throw Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:h={}},identity:_,signer:c}=f,o=await t({...r,request:await c.sign(r.request,_,h)}).catch((c.errorHandler||X3)(h));return(c.successHandler||l3)(o.response,h),o},IR={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},J3=(n)=>({applyToStack:(t)=>{t.addRelativeTo(BR(),IR)}}),Q3=(n)=>{if(typeof n==="function")return n;let t=Promise.resolve(n);return()=>t},z3=async(n,t,i,r=(f)=>f,...s)=>{let f=new n(i);return f=r(f)??f,await t.send(f,...s)};function C3(n,t,i,r,s){return async function*(h,_,...c){let o=_,w=h.startingToken??o[i],e=!0,u;while(e){if(o[i]=w,s)o[s]=o[s]??h.pageSize;if(h.client instanceof n)u=await z3(t,h.client,_,h.withCommand,...c);else throw Error(`Invalid client, expected instance of ${n.name}`);yield u;let y=w;w=V3(u,r),e=!!(w&&(!h.stopOnSameToken||w!==y))}return}}var V3=(n,t)=>{let i=n,r=t.split(".");for(let s of r){if(!i||typeof i!=="object")return;i=i[s]}return i};function K3(n,t,i){if(!n.__smithy_context)n.__smithy_context={features:{}};else if(!n.__smithy_context.features)n.__smithy_context.features={};n.__smithy_context.features[t]=i}class HR{authSchemes=new Map;constructor(n){for(let t in n){let i=n[t];if(i!==void 0)this.authSchemes.set(t,i)}}getIdentityProvider(n){return this.authSchemes.get(n)}}class GR{async sign(n,t,i){if(!i)throw Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing");if(!i.name)throw Error("request could not be signed with `apiKey` since the `name` signer property is missing");if(!i.in)throw Error("request could not be signed with `apiKey` since the `in` signer property is missing");if(!t.apiKey)throw Error("request could not be signed with `apiKey` since the `apiKey` is not defined");let r=Oo.clone(n);if(i.in===UR.QUERY)r.query[i.name]=t.apiKey;else if(i.in===UR.HEADER)r.headers[i.name]=i.scheme?`${i.scheme} ${t.apiKey}`:t.apiKey;else throw Error("request can only be signed with `apiKey` locations `query` or `header`, but found: `"+i.in+"`");return r}}class WR{async sign(n,t,i){let r=Oo.clone(n);if(!t.token)throw Error("request could not be signed with `token` since the `token` is not defined");return r.headers.Authorization=`Bearer ${t.token}`,r}}class DR{async sign(n,t,i){return n}}var PR=(n)=>function(i){return FR(i)&&i.expiration.getTime()-Date.now()<n},YR=300000,x3=PR(YR),FR=(n)=>n.expiration!==void 0,j3=(n,t,i)=>{if(n===void 0)return;let r=typeof n!=="function"?async()=>Promise.resolve(n):n,s,f,h,_=!1,c=async(o)=>{if(!f)f=r(o);try{s=await f,h=!0,_=!1}finally{f=void 0}return s};if(t===void 0)return async(o)=>{if(!h||o?.forceRefresh)s=await c(o);return s};return async(o)=>{if(!h||o?.forceRefresh)s=await c(o);if(_)return s;if(!i(s))return _=!0,s;if(t(s))return await c(o),s;return s}};k3.DefaultIdentityProviderConfig=HR;k3.EXPIRATION_MS=YR;k3.HttpApiKeyAuthSigner=GR;k3.HttpBearerAuthSigner=WR;k3.NoAuthSigner=DR;k3.createIsIdentityExpiredFunction=PR;k3.createPaginator=C3;k3.doesIdentityRequireRefresh=FR;k3.getHttpAuthSchemeEndpointRuleSetPlugin=Y3;k3.getHttpAuthSchemePlugin=F3;k3.getHttpSigningPlugin=J3;k3.httpAuthSchemeEndpointRuleSetMiddlewareOptions=bR;k3.httpAuthSchemeMiddleware=Uo;k3.httpAuthSchemeMiddlewareOptions=NR;k3.httpSigningMiddleware=BR;k3.httpSigningMiddlewareOptions=IR;k3.isIdentityExpired=x3;k3.memoizeIdentityProvider=j3;k3.normalizeProvider=Q3;k3.setFeature=K3});var XR=nn((Rf,bo)=>{(function(n,t){typeof Rf=="object"&&typeof bo=="object"?bo.exports=t():typeof define=="function"&&define.amd?define([],t):typeof Rf=="object"?Rf.bowser=t():n.bowser=t()})(Rf,function(){return function(n){var t={};function i(r){if(t[r])return t[r].exports;var s=t[r]={i:r,l:!1,exports:{}};return n[r].call(s.exports,s,s.exports,i),s.l=!0,s.exports}return i.m=n,i.c=t,i.d=function(r,s,f){i.o(r,s)||Object.defineProperty(r,s,{enumerable:!0,get:f})},i.r=function(r){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(r,"__esModule",{value:!0})},i.t=function(r,s){if(1&s&&(r=i(r)),8&s)return r;if(4&s&&typeof r=="object"&&r&&r.__esModule)return r;var f=Object.create(null);if(i.r(f),Object.defineProperty(f,"default",{enumerable:!0,value:r}),2&s&&typeof r!="string")for(var h in r)i.d(f,h,function(_){return r[_]}.bind(null,h));return f},i.n=function(r){var s=r&&r.__esModule?function(){return r.default}:function(){return r};return i.d(s,"a",s),s},i.o=function(r,s){return Object.prototype.hasOwnProperty.call(r,s)},i.p="",i(i.s=90)}({17:function(n,t,i){t.__esModule=!0,t.default=void 0;var r=i(18),s=function(){function f(){}return f.getFirstMatch=function(h,_){var c=_.match(h);return c&&c.length>0&&c[1]||""},f.getSecondMatch=function(h,_){var c=_.match(h);return c&&c.length>1&&c[2]||""},f.matchAndReturnConst=function(h,_,c){if(h.test(_))return c},f.getWindowsVersionName=function(h){switch(h){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},f.getMacOSVersionName=function(h){var _=h.split(".").splice(0,2).map(function(w){return parseInt(w,10)||0});_.push(0);var c=_[0],o=_[1];if(c===10)switch(o){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}switch(c){case 11:return"Big Sur";case 12:return"Monterey";case 13:return"Ventura";case 14:return"Sonoma";case 15:return"Sequoia";default:return}},f.getAndroidVersionName=function(h){var _=h.split(".").splice(0,2).map(function(c){return parseInt(c,10)||0});if(_.push(0),!(_[0]===1&&_[1]<5))return _[0]===1&&_[1]<6?"Cupcake":_[0]===1&&_[1]>=6?"Donut":_[0]===2&&_[1]<2?"Eclair":_[0]===2&&_[1]===2?"Froyo":_[0]===2&&_[1]>2?"Gingerbread":_[0]===3?"Honeycomb":_[0]===4&&_[1]<1?"Ice Cream Sandwich":_[0]===4&&_[1]<4?"Jelly Bean":_[0]===4&&_[1]>=4?"KitKat":_[0]===5?"Lollipop":_[0]===6?"Marshmallow":_[0]===7?"Nougat":_[0]===8?"Oreo":_[0]===9?"Pie":void 0},f.getVersionPrecision=function(h){return h.split(".").length},f.compareVersions=function(h,_,c){c===void 0&&(c=!1);var o=f.getVersionPrecision(h),w=f.getVersionPrecision(_),e=Math.max(o,w),u=0,y=f.map([h,_],function(A){var R=e-f.getVersionPrecision(A),M=A+Array(R+1).join(".0");return f.map(M.split("."),function(E){return Array(20-E.length).join("0")+E}).reverse()});for(c&&(u=e-Math.min(o,w)),e-=1;e>=u;){if(y[0][e]>y[1][e])return 1;if(y[0][e]===y[1][e]){if(e===u)return 0;e-=1}else if(y[0][e]<y[1][e])return-1}},f.map=function(h,_){var c,o=[];if(Array.prototype.map)return Array.prototype.map.call(h,_);for(c=0;c<h.length;c+=1)o.push(_(h[c]));return o},f.find=function(h,_){var c,o;if(Array.prototype.find)return Array.prototype.find.call(h,_);for(c=0,o=h.length;c<o;c+=1){var w=h[c];if(_(w,c))return w}},f.assign=function(h){for(var _,c,o=h,w=arguments.length,e=Array(w>1?w-1:0),u=1;u<w;u++)e[u-1]=arguments[u];if(Object.assign)return Object.assign.apply(Object,[h].concat(e));var y=function(){var A=e[_];typeof A=="object"&&A!==null&&Object.keys(A).forEach(function(R){o[R]=A[R]})};for(_=0,c=e.length;_<c;_+=1)y();return h},f.getBrowserAlias=function(h){return r.BROWSER_ALIASES_MAP[h]},f.getBrowserTypeByAlias=function(h){return r.BROWSER_MAP[h]||""},f}();t.default=s,n.exports=t.default},18:function(n,t,i){t.__esModule=!0,t.ENGINE_MAP=t.OS_MAP=t.PLATFORMS_MAP=t.BROWSER_MAP=t.BROWSER_ALIASES_MAP=void 0,t.BROWSER_ALIASES_MAP={AmazonBot:"amazonbot","Amazon Silk":"amazon_silk","Android Browser":"android",BaiduSpider:"baiduspider",Bada:"bada",BingCrawler:"bingcrawler",Brave:"brave",BlackBerry:"blackberry","ChatGPT-User":"chatgpt_user",Chrome:"chrome",ClaudeBot:"claudebot",Chromium:"chromium",Diffbot:"diffbot",DuckDuckBot:"duckduckbot",DuckDuckGo:"duckduckgo",Electron:"electron",Epiphany:"epiphany",FacebookExternalHit:"facebookexternalhit",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot",GPTBot:"gptbot","Internet Explorer":"ie",InternetArchiveCrawler:"internetarchivecrawler","K-Meleon":"k_meleon",LibreWolf:"librewolf",Linespider:"linespider",Maxthon:"maxthon","Meta-ExternalAds":"meta_externalads","Meta-ExternalAgent":"meta_externalagent","Meta-ExternalFetcher":"meta_externalfetcher","Meta-WebIndexer":"meta_webindexer","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver","OAI-SearchBot":"oai_searchbot",Omgilibot:"omgilibot",Opera:"opera","Opera Coast":"opera_coast","Pale Moon":"pale_moon",PerplexityBot:"perplexitybot","Perplexity-User":"perplexity_user",PhantomJS:"phantomjs",PingdomBot:"pingdombot",Puffin:"puffin",QQ:"qq",QQLite:"qqlite",QupZilla:"qupzilla",Roku:"roku",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SlackBot:"slackbot",SeaMonkey:"seamonkey",Sleipnir:"sleipnir","Sogou Browser":"sogou",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat",YahooSlurp:"yahooslurp","Yandex Browser":"yandex",YandexBot:"yandexbot",YouBot:"youbot"},t.BROWSER_MAP={amazonbot:"AmazonBot",amazon_silk:"Amazon Silk",android:"Android Browser",baiduspider:"BaiduSpider",bada:"Bada",bingcrawler:"BingCrawler",blackberry:"BlackBerry",brave:"Brave",chatgpt_user:"ChatGPT-User",chrome:"Chrome",claudebot:"ClaudeBot",chromium:"Chromium",diffbot:"Diffbot",duckduckbot:"DuckDuckBot",duckduckgo:"DuckDuckGo",edge:"Microsoft Edge",electron:"Electron",epiphany:"Epiphany",facebookexternalhit:"FacebookExternalHit",firefox:"Firefox",focus:"Focus",generic:"Generic",google_search:"Google Search",googlebot:"Googlebot",gptbot:"GPTBot",ie:"Internet Explorer",internetarchivecrawler:"InternetArchiveCrawler",k_meleon:"K-Meleon",librewolf:"LibreWolf",linespider:"Linespider",maxthon:"Maxthon",meta_externalads:"Meta-ExternalAds",meta_externalagent:"Meta-ExternalAgent",meta_externalfetcher:"Meta-ExternalFetcher",meta_webindexer:"Meta-WebIndexer",mz:"MZ Browser",naver:"NAVER Whale Browser",oai_searchbot:"OAI-SearchBot",omgilibot:"Omgilibot",opera:"Opera",opera_coast:"Opera Coast",pale_moon:"Pale Moon",perplexitybot:"PerplexityBot",perplexity_user:"Perplexity-User",phantomjs:"PhantomJS",pingdombot:"PingdomBot",puffin:"Puffin",qq:"QQ Browser",qqlite:"QQ Browser Lite",qupzilla:"QupZilla",roku:"Roku",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",slackbot:"SlackBot",sleipnir:"Sleipnir",sogou:"Sogou Browser",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yahooslurp:"YahooSlurp",yandex:"Yandex Browser",yandexbot:"YandexBot",youbot:"YouBot"},t.PLATFORMS_MAP={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},t.OS_MAP={Android:"Android",Bada:"Bada",BlackBerry:"BlackBerry",ChromeOS:"Chrome OS",HarmonyOS:"HarmonyOS",iOS:"iOS",Linux:"Linux",MacOS:"macOS",PlayStation4:"PlayStation 4",Roku:"Roku",Tizen:"Tizen",WebOS:"WebOS",Windows:"Windows",WindowsPhone:"Windows Phone"},t.ENGINE_MAP={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"}},90:function(n,t,i){t.__esModule=!0,t.default=void 0;var r,s=(r=i(91))&&r.__esModule?r:{default:r},f=i(18);function h(c,o){for(var w=0;w<o.length;w++){var e=o[w];e.enumerable=e.enumerable||!1,e.configurable=!0,"value"in e&&(e.writable=!0),Object.defineProperty(c,e.key,e)}}var _=function(){function c(){}var o,w,e;return c.getParser=function(u,y,A){if(y===void 0&&(y=!1),A===void 0&&(A=null),typeof u!="string")throw Error("UserAgent should be a string");return new s.default(u,y,A)},c.parse=function(u,y){return y===void 0&&(y=null),new s.default(u,y).getResult()},o=c,e=[{key:"BROWSER_MAP",get:function(){return f.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return f.ENGINE_MAP}},{key:"OS_MAP",get:function(){return f.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return f.PLATFORMS_MAP}}],(w=null)&&h(o.prototype,w),e&&h(o,e),c}();t.default=_,n.exports=t.default},91:function(n,t,i){t.__esModule=!0,t.default=void 0;var r=c(i(92)),s=c(i(93)),f=c(i(94)),h=c(i(95)),_=c(i(17));function c(w){return w&&w.__esModule?w:{default:w}}var o=function(){function w(u,y,A){if(y===void 0&&(y=!1),A===void 0&&(A=null),u==null||u==="")throw Error("UserAgent parameter can't be empty");this._ua=u;var R=!1;typeof y=="boolean"?(R=y,this._hints=A):this._hints=y!=null&&typeof y=="object"?y:null,this.parsedResult={},R!==!0&&this.parse()}var e=w.prototype;return e.getHints=function(){return this._hints},e.hasBrand=function(u){if(!this._hints||!Array.isArray(this._hints.brands))return!1;var y=u.toLowerCase();return this._hints.brands.some(function(A){return A.brand&&A.brand.toLowerCase()===y})},e.getBrandVersion=function(u){if(this._hints&&Array.isArray(this._hints.brands)){var y=u.toLowerCase(),A=this._hints.brands.find(function(R){return R.brand&&R.brand.toLowerCase()===y});return A?A.version:void 0}},e.getUA=function(){return this._ua},e.test=function(u){return u.test(this._ua)},e.parseBrowser=function(){var u=this;this.parsedResult.browser={};var y=_.default.find(r.default,function(A){if(typeof A.test=="function")return A.test(u);if(Array.isArray(A.test))return A.test.some(function(R){return u.test(R)});throw Error("Browser's test function is not valid")});return y&&(this.parsedResult.browser=y.describe(this.getUA(),this)),this.parsedResult.browser},e.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},e.getBrowserName=function(u){return u?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},e.getBrowserVersion=function(){return this.getBrowser().version},e.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},e.parseOS=function(){var u=this;this.parsedResult.os={};var y=_.default.find(s.default,function(A){if(typeof A.test=="function")return A.test(u);if(Array.isArray(A.test))return A.test.some(function(R){return u.test(R)});throw Error("Browser's test function is not valid")});return y&&(this.parsedResult.os=y.describe(this.getUA())),this.parsedResult.os},e.getOSName=function(u){var y=this.getOS().name;return u?String(y).toLowerCase()||"":y||""},e.getOSVersion=function(){return this.getOS().version},e.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},e.getPlatformType=function(u){u===void 0&&(u=!1);var y=this.getPlatform().type;return u?String(y).toLowerCase()||"":y||""},e.parsePlatform=function(){var u=this;this.parsedResult.platform={};var y=_.default.find(f.default,function(A){if(typeof A.test=="function")return A.test(u);if(Array.isArray(A.test))return A.test.some(function(R){return u.test(R)});throw Error("Browser's test function is not valid")});return y&&(this.parsedResult.platform=y.describe(this.getUA())),this.parsedResult.platform},e.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},e.getEngineName=function(u){return u?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},e.parseEngine=function(){var u=this;this.parsedResult.engine={};var y=_.default.find(h.default,function(A){if(typeof A.test=="function")return A.test(u);if(Array.isArray(A.test))return A.test.some(function(R){return u.test(R)});throw Error("Browser's test function is not valid")});return y&&(this.parsedResult.engine=y.describe(this.getUA())),this.parsedResult.engine},e.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},e.getResult=function(){return _.default.assign({},this.parsedResult)},e.satisfies=function(u){var y=this,A={},R=0,M={},E=0;if(Object.keys(u).forEach(function($){var U=u[$];typeof U=="string"?(M[$]=U,E+=1):typeof U=="object"&&(A[$]=U,R+=1)}),R>0){var g=Object.keys(A),T=_.default.find(g,function($){return y.isOS($)});if(T){var S=this.satisfies(A[T]);if(S!==void 0)return S}var L=_.default.find(g,function($){return y.isPlatform($)});if(L){var b=this.satisfies(A[L]);if(b!==void 0)return b}}if(E>0){var I=Object.keys(M),Z=_.default.find(I,function($){return y.isBrowser($,!0)});if(Z!==void 0)return this.compareVersion(M[Z])}},e.isBrowser=function(u,y){y===void 0&&(y=!1);var A=this.getBrowserName().toLowerCase(),R=u.toLowerCase(),M=_.default.getBrowserTypeByAlias(R);return y&&M&&(R=M.toLowerCase()),R===A},e.compareVersion=function(u){var y=[0],A=u,R=!1,M=this.getBrowserVersion();if(typeof M=="string")return u[0]===">"||u[0]==="<"?(A=u.substr(1),u[1]==="="?(R=!0,A=u.substr(2)):y=[],u[0]===">"?y.push(1):y.push(-1)):u[0]==="="?A=u.substr(1):u[0]==="~"&&(R=!0,A=u.substr(1)),y.indexOf(_.default.compareVersions(M,A,R))>-1},e.isOS=function(u){return this.getOSName(!0)===String(u).toLowerCase()},e.isPlatform=function(u){return this.getPlatformType(!0)===String(u).toLowerCase()},e.isEngine=function(u){return this.getEngineName(!0)===String(u).toLowerCase()},e.is=function(u,y){return y===void 0&&(y=!1),this.isBrowser(u,y)||this.isOS(u)||this.isPlatform(u)},e.some=function(u){var y=this;return u===void 0&&(u=[]),u.some(function(A){return y.is(A)})},w}();t.default=o,n.exports=t.default},92:function(n,t,i){t.__esModule=!0,t.default=void 0;var r,s=(r=i(17))&&r.__esModule?r:{default:r},f=/version\/(\d+(\.?_?\d+)+)/i,h=[{test:[/gptbot/i],describe:function(_){var c={name:"GPTBot"},o=s.default.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/chatgpt-user/i],describe:function(_){var c={name:"ChatGPT-User"},o=s.default.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/oai-searchbot/i],describe:function(_){var c={name:"OAI-SearchBot"},o=s.default.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(_){var c={name:"ClaudeBot"},o=s.default.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(_){var c={name:"Omgilibot"},o=s.default.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/diffbot/i],describe:function(_){var c={name:"Diffbot"},o=s.default.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/perplexitybot/i],describe:function(_){var c={name:"PerplexityBot"},o=s.default.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/perplexity-user/i],describe:function(_){var c={name:"Perplexity-User"},o=s.default.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/youbot/i],describe:function(_){var c={name:"YouBot"},o=s.default.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/meta-webindexer/i],describe:function(_){var c={name:"Meta-WebIndexer"},o=s.default.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/meta-externalads/i],describe:function(_){var c={name:"Meta-ExternalAds"},o=s.default.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/meta-externalagent/i],describe:function(_){var c={name:"Meta-ExternalAgent"},o=s.default.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/meta-externalfetcher/i],describe:function(_){var c={name:"Meta-ExternalFetcher"},o=s.default.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/googlebot/i],describe:function(_){var c={name:"Googlebot"},o=s.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/linespider/i],describe:function(_){var c={name:"Linespider"},o=s.default.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/amazonbot/i],describe:function(_){var c={name:"AmazonBot"},o=s.default.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/bingbot/i],describe:function(_){var c={name:"BingCrawler"},o=s.default.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/baiduspider/i],describe:function(_){var c={name:"BaiduSpider"},o=s.default.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/duckduckbot/i],describe:function(_){var c={name:"DuckDuckBot"},o=s.default.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/ia_archiver/i],describe:function(_){var c={name:"InternetArchiveCrawler"},o=s.default.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(_){var c={name:"SlackBot"},o=s.default.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/yahoo!?[\s/]*slurp/i],describe:function(){return{name:"YahooSlurp"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{name:"YandexBot"}}},{test:[/pingdom/i],describe:function(){return{name:"PingdomBot"}}},{test:[/opera/i],describe:function(_){var c={name:"Opera"},o=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/opr\/|opios/i],describe:function(_){var c={name:"Opera"},o=s.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/SamsungBrowser/i],describe:function(_){var c={name:"Samsung Internet for Android"},o=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/Whale/i],describe:function(_){var c={name:"NAVER Whale Browser"},o=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/PaleMoon/i],describe:function(_){var c={name:"Pale Moon"},o=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/MZBrowser/i],describe:function(_){var c={name:"MZ Browser"},o=s.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/focus/i],describe:function(_){var c={name:"Focus"},o=s.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/swing/i],describe:function(_){var c={name:"Swing"},o=s.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/coast/i],describe:function(_){var c={name:"Opera Coast"},o=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(_){var c={name:"Opera Touch"},o=s.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/yabrowser/i],describe:function(_){var c={name:"Yandex Browser"},o=s.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/ucbrowser/i],describe:function(_){var c={name:"UC Browser"},o=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/Maxthon|mxios/i],describe:function(_){var c={name:"Maxthon"},o=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/epiphany/i],describe:function(_){var c={name:"Epiphany"},o=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/puffin/i],describe:function(_){var c={name:"Puffin"},o=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/sleipnir/i],describe:function(_){var c={name:"Sleipnir"},o=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/k-meleon/i],describe:function(_){var c={name:"K-Meleon"},o=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/micromessenger/i],describe:function(_){var c={name:"WeChat"},o=s.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/qqbrowser/i],describe:function(_){var c={name:/qqbrowserlite/i.test(_)?"QQ Browser Lite":"QQ Browser"},o=s.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/msie|trident/i],describe:function(_){var c={name:"Internet Explorer"},o=s.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/\sedg\//i],describe:function(_){var c={name:"Microsoft Edge"},o=s.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/edg([ea]|ios)/i],describe:function(_){var c={name:"Microsoft Edge"},o=s.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/vivaldi/i],describe:function(_){var c={name:"Vivaldi"},o=s.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/seamonkey/i],describe:function(_){var c={name:"SeaMonkey"},o=s.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/sailfish/i],describe:function(_){var c={name:"Sailfish"},o=s.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,_);return o&&(c.version=o),c}},{test:[/silk/i],describe:function(_){var c={name:"Amazon Silk"},o=s.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/phantom/i],describe:function(_){var c={name:"PhantomJS"},o=s.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/slimerjs/i],describe:function(_){var c={name:"SlimerJS"},o=s.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(_){var c={name:"BlackBerry"},o=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/(web|hpw)[o0]s/i],describe:function(_){var c={name:"WebOS Browser"},o=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/bada/i],describe:function(_){var c={name:"Bada"},o=s.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/tizen/i],describe:function(_){var c={name:"Tizen"},o=s.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/qupzilla/i],describe:function(_){var c={name:"QupZilla"},o=s.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/librewolf/i],describe:function(_){var c={name:"LibreWolf"},o=s.default.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/firefox|iceweasel|fxios/i],describe:function(_){var c={name:"Firefox"},o=s.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/electron/i],describe:function(_){var c={name:"Electron"},o=s.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe:function(_){var c={name:"Sogou Browser"},o=s.default.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,_),w=s.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,_),e=s.default.getFirstMatch(/se ([\d.]+)x/i,_),u=o||w||e;return u&&(c.version=u),c}},{test:[/MiuiBrowser/i],describe:function(_){var c={name:"Miui"},o=s.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:function(_){return!!_.hasBrand("DuckDuckGo")||_.test(/\sDdg\/[\d.]+$/i)},describe:function(_,c){var o={name:"DuckDuckGo"};if(c){var w=c.getBrandVersion("DuckDuckGo");if(w)return o.version=w,o}var e=s.default.getFirstMatch(/\sDdg\/([\d.]+)$/i,_);return e&&(o.version=e),o}},{test:function(_){return _.hasBrand("Brave")},describe:function(_,c){var o={name:"Brave"};if(c){var w=c.getBrandVersion("Brave");if(w)return o.version=w,o}return o}},{test:[/chromium/i],describe:function(_){var c={name:"Chromium"},o=s.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,_)||s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/chrome|crios|crmo/i],describe:function(_){var c={name:"Chrome"},o=s.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/GSA/i],describe:function(_){var c={name:"Google Search"},o=s.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:function(_){var c=!_.test(/like android/i),o=_.test(/android/i);return c&&o},describe:function(_){var c={name:"Android Browser"},o=s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/playstation 4/i],describe:function(_){var c={name:"PlayStation 4"},o=s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/safari|applewebkit/i],describe:function(_){var c={name:"Safari"},o=s.default.getFirstMatch(f,_);return o&&(c.version=o),c}},{test:[/.*/i],describe:function(_){var c=_.search("\\(")!==-1?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:s.default.getFirstMatch(c,_),version:s.default.getSecondMatch(c,_)}}}];t.default=h,n.exports=t.default},93:function(n,t,i){t.__esModule=!0,t.default=void 0;var r,s=(r=i(17))&&r.__esModule?r:{default:r},f=i(18),h=[{test:[/Roku\/DVP/],describe:function(_){var c=s.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,_);return{name:f.OS_MAP.Roku,version:c}}},{test:[/windows phone/i],describe:function(_){var c=s.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,_);return{name:f.OS_MAP.WindowsPhone,version:c}}},{test:[/windows /i],describe:function(_){var c=s.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,_),o=s.default.getWindowsVersionName(c);return{name:f.OS_MAP.Windows,version:c,versionName:o}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(_){var c={name:f.OS_MAP.iOS},o=s.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,_);return o&&(c.version=o),c}},{test:[/macintosh/i],describe:function(_){var c=s.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,_).replace(/[_\s]/g,"."),o=s.default.getMacOSVersionName(c),w={name:f.OS_MAP.MacOS,version:c};return o&&(w.versionName=o),w}},{test:[/(ipod|iphone|ipad)/i],describe:function(_){var c=s.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,_).replace(/[_\s]/g,".");return{name:f.OS_MAP.iOS,version:c}}},{test:[/OpenHarmony/i],describe:function(_){var c=s.default.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,_);return{name:f.OS_MAP.HarmonyOS,version:c}}},{test:function(_){var c=!_.test(/like android/i),o=_.test(/android/i);return c&&o},describe:function(_){var c=s.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,_),o=s.default.getAndroidVersionName(c),w={name:f.OS_MAP.Android,version:c};return o&&(w.versionName=o),w}},{test:[/(web|hpw)[o0]s/i],describe:function(_){var c=s.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,_),o={name:f.OS_MAP.WebOS};return c&&c.length&&(o.version=c),o}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(_){var c=s.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,_)||s.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,_)||s.default.getFirstMatch(/\bbb(\d+)/i,_);return{name:f.OS_MAP.BlackBerry,version:c}}},{test:[/bada/i],describe:function(_){var c=s.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,_);return{name:f.OS_MAP.Bada,version:c}}},{test:[/tizen/i],describe:function(_){var c=s.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,_);return{name:f.OS_MAP.Tizen,version:c}}},{test:[/linux/i],describe:function(){return{name:f.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:f.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(_){var c=s.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,_);return{name:f.OS_MAP.PlayStation4,version:c}}}];t.default=h,n.exports=t.default},94:function(n,t,i){t.__esModule=!0,t.default=void 0;var r,s=(r=i(17))&&r.__esModule?r:{default:r},f=i(18),h=[{test:[/googlebot/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Google"}}},{test:[/linespider/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Line"}}},{test:[/amazonbot/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Amazon"}}},{test:[/gptbot/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/chatgpt-user/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/oai-searchbot/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/baiduspider/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Baidu"}}},{test:[/bingbot/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Bing"}}},{test:[/duckduckbot/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"DuckDuckGo"}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Anthropic"}}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Webz.io"}}},{test:[/diffbot/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Diffbot"}}},{test:[/perplexitybot/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/perplexity-user/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/youbot/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"You.com"}}},{test:[/ia_archiver/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Internet Archive"}}},{test:[/meta-webindexer/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalads/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalagent/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalfetcher/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Slack"}}},{test:[/yahoo/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Yahoo"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Yandex"}}},{test:[/pingdom/i],describe:function(){return{type:f.PLATFORMS_MAP.bot,vendor:"Pingdom"}}},{test:[/huawei/i],describe:function(_){var c=s.default.getFirstMatch(/(can-l01)/i,_)&&"Nova",o={type:f.PLATFORMS_MAP.mobile,vendor:"Huawei"};return c&&(o.model=c),o}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:f.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:f.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:f.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:f.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:f.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:f.PLATFORMS_MAP.tablet}}},{test:function(_){var c=_.test(/ipod|iphone/i),o=_.test(/like (ipod|iphone)/i);return c&&!o},describe:function(_){var c=s.default.getFirstMatch(/(ipod|iphone)/i,_);return{type:f.PLATFORMS_MAP.mobile,vendor:"Apple",model:c}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:f.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe:function(_){var c=s.default.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,_),o={type:f.PLATFORMS_MAP.mobile,vendor:"Nokia"};return c&&(o.model=c),o}},{test:[/[^-]mobi/i],describe:function(){return{type:f.PLATFORMS_MAP.mobile}}},{test:function(_){return _.getBrowserName(!0)==="blackberry"},describe:function(){return{type:f.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(_){return _.getBrowserName(!0)==="bada"},describe:function(){return{type:f.PLATFORMS_MAP.mobile}}},{test:function(_){return _.getBrowserName()==="windows phone"},describe:function(){return{type:f.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(_){var c=Number(String(_.getOSVersion()).split(".")[0]);return _.getOSName(!0)==="android"&&c>=3},describe:function(){return{type:f.PLATFORMS_MAP.tablet}}},{test:function(_){return _.getOSName(!0)==="android"},describe:function(){return{type:f.PLATFORMS_MAP.mobile}}},{test:[/smart-?tv|smarttv/i],describe:function(){return{type:f.PLATFORMS_MAP.tv}}},{test:[/netcast/i],describe:function(){return{type:f.PLATFORMS_MAP.tv}}},{test:function(_){return _.getOSName(!0)==="macos"},describe:function(){return{type:f.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(_){return _.getOSName(!0)==="windows"},describe:function(){return{type:f.PLATFORMS_MAP.desktop}}},{test:function(_){return _.getOSName(!0)==="linux"},describe:function(){return{type:f.PLATFORMS_MAP.desktop}}},{test:function(_){return _.getOSName(!0)==="playstation 4"},describe:function(){return{type:f.PLATFORMS_MAP.tv}}},{test:function(_){return _.getOSName(!0)==="roku"},describe:function(){return{type:f.PLATFORMS_MAP.tv}}}];t.default=h,n.exports=t.default},95:function(n,t,i){t.__esModule=!0,t.default=void 0;var r,s=(r=i(17))&&r.__esModule?r:{default:r},f=i(18),h=[{test:function(_){return _.getBrowserName(!0)==="microsoft edge"},describe:function(_){if(/\sedg\//i.test(_))return{name:f.ENGINE_MAP.Blink};var c=s.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,_);return{name:f.ENGINE_MAP.EdgeHTML,version:c}}},{test:[/trident/i],describe:function(_){var c={name:f.ENGINE_MAP.Trident},o=s.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:function(_){return _.test(/presto/i)},describe:function(_){var c={name:f.ENGINE_MAP.Presto},o=s.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:function(_){var c=_.test(/gecko/i),o=_.test(/like gecko/i);return c&&!o},describe:function(_){var c={name:f.ENGINE_MAP.Gecko},o=s.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:f.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(_){var c={name:f.ENGINE_MAP.WebKit},o=s.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,_);return o&&(c.version=o),c}}];t.default=h,n.exports=t.default}})})});var gt=nn((wD)=>{var{Retry:RW,RETRY_MODES:lR}=Af(),{HttpRequest:Wo,parseUrl:MW}=kn(),{InvokeStore:JR}=OR(),{normalizeProvider:EW}=Ui(),{platform:TW,release:gW}=cn("os"),{versions:No,env:QR}=cn("process"),{isValidHostLabel:SW,isIpAddress:xR,customEndpointFunctions:LW}=vi(),{EndpointError:$W,resolveEndpoint:OW}=vi();wD.EndpointError=$W;wD.isIpAddress=xR;wD.resolveEndpoint=OW;var{loadConfig:UW,NODE_REGION_CONFIG_OPTIONS:jR,NODE_REGION_CONFIG_FILE_OPTIONS:kR}=xn(),{REGION_ENV_NAME:bW,REGION_INI_NAME:NW,resolveRegionConfig:BW}=xn();wD.NODE_REGION_CONFIG_FILE_OPTIONS=kR;wD.NODE_REGION_CONFIG_OPTIONS=jR;wD.REGION_ENV_NAME=bW;wD.REGION_INI_NAME=NW;wD.resolveRegionConfig=BW;var a_={warningEmitted:!1},IW=(n)=>{if(n&&!a_.warningEmitted){if(process.env.AWS_SDK_JS_NODE_VERSION_SUPPORT_WARNING_DISABLED==="true"){a_.warningEmitted=!0;return}let t=parseInt(n.substring(1,n.indexOf("."))),i=22;if(t<i)a_.warningEmitted=!0,process.emitWarning(`NodeVersionSupportWarning: The AWS SDK for JavaScript (v3)
|
|
25
25
|
versions published after the first week of January 2027
|
|
26
26
|
will require node >=${i}. You are running node ${n}.
|
|
27
27
|
|
|
28
28
|
To continue receiving updates to AWS services, bug fixes,
|
|
29
29
|
and security updates please upgrade to node >=${i}.
|
|
30
30
|
|
|
31
|
-
More information can be found at: https://a.co/c895JFp`)}},d3=()=>(n,t)=>async(i)=>{return t.__retryLongPoll=!0,n(i)},R3={name:"longPollMiddleware",tags:["RETRY"],step:"initialize",override:!0},E3=(n)=>({applyToStack:(t)=>{t.add(d3(),R3)}});function y3(n,t,i){if(!n.$source)n.$source={};return n.$source[t]=i,n}i3.v2026||=typeof process==="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function Lt(n,t,i){if(!n.__aws_sdk_context)n.__aws_sdk_context={features:{}};else if(!n.__aws_sdk_context.features)n.__aws_sdk_context.features={};n.__aws_sdk_context.features[t]=i}function T3(n,t,i){if(!n.$source)n.$source={};return n.$source[t]=i,n}function g3(n){return n}var cd=(n)=>(t)=>async(i)=>{if(!wc.isInstance(i.request))return t(i);let{request:s}=i,{handlerProtocol:r=""}=n.requestHandler.metadata||{};if(r.indexOf("h2")>=0&&!s.headers[":authority"])delete s.headers.host,s.headers[":authority"]=s.hostname+(s.port?":"+s.port:"");else if(!s.headers.host){let e=s.hostname;if(s.port!=null)e+=`:${s.port}`;s.headers.host=e}return t(i)},_d={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},S3=(n)=>({applyToStack:(t)=>{t.add(cd(n),_d)}}),wd=()=>(n,t)=>async(i)=>{try{let s=await n(i),{clientName:r,commandName:e,logger:f,dynamoDbDocumentClientOptions:o={}}=t,{overrideInputFilterSensitiveLog:h,overrideOutputFilterSensitiveLog:u}=o,c=h??t.inputFilterSensitiveLog,_=u??t.outputFilterSensitiveLog,{$metadata:w,...l}=s.output;return f?.info?.({clientName:r,commandName:e,input:c(i.input),output:_(l),metadata:w}),s}catch(s){let{clientName:r,commandName:e,logger:f,dynamoDbDocumentClientOptions:o={}}=t,{overrideInputFilterSensitiveLog:h}=o,u=h??t.inputFilterSensitiveLog;throw f?.error?.({clientName:r,commandName:e,input:u(i.input),error:s,metadata:s.$metadata}),s}},ld={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},I3=(n)=>({applyToStack:(t)=>{t.add(wd(),ld)}}),Ad={step:"build",tags:["RECURSION_DETECTION","TRACE_CONTEXT_PROPAGATION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},U3="AWS_LAMBDA_FUNCTION_NAME",b3="_X_AMZN_TRACE_ID",hc="X-Amzn-Trace-Id",_c="traceparent",Md="tracestate",dd="baggage",Rd=()=>(n)=>async(t)=>{let{request:i}=t;if(!wc.isInstance(i))return n(t);let s;{let r=Object.keys(i.headers??{}).find((e)=>e.toLowerCase()===hc.toLowerCase())??hc;if(!i.headers.hasOwnProperty(r)){let e=process.env[U3],f=process.env[b3];s??=await td.getInstanceAsync();let h=s?.getXRayTraceId()??f,u=(c)=>typeof c==="string"&&c.length>0;if(u(e)&&u(h))i.headers[hc]=h}}if($3(i.headers),!i.headers[_c]){let e=(s??=await td.getInstanceAsync())?.getTraceparent?.();if(e){i.headers[_c]=e;let f=s?.getTracestate?.();if(f)i.headers[Md]=f;let o=s?.getBaggage?.();if(o)i.headers[dd]=o}}return n(t)};function $3(n){for(let t of Object.keys(n)){let i=t.toLowerCase();if(t!==i&&(i===_c||i===Md||i===dd))n[i]=n[t],delete n[t]}}var L3=(n)=>({applyToStack:(t)=>{t.add(Rd(),Ad)}}),lc=void 0;function O3(n){if(n===void 0)return!0;return typeof n==="string"&&n.length<=50}function B3(n){let t=r3(n.userAgentAppId??lc),{customUserAgent:i}=n;return Object.assign(n,{customUserAgent:typeof i==="string"?[[i]]:i,userAgentAppId:async()=>{let s=await t();if(!O3(s)){let r=n.logger?.constructor?.name==="NoOpLogger"||!n.logger?console:n.logger;if(typeof s!=="string")r?.warn("userAgentAppId must be a string or undefined.");else if(s.length>50)r?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return s}})}var Ed={partitions:[{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)"}}}],version:"1.1"},yd=Ed,Td="",gd=(n)=>{let{partitions:t}=yd;for(let s of t){let{regions:r,outputs:e}=s;for(let[f,o]of Object.entries(r))if(f===n)return{...e,...o}}for(let s of t){let{regionRegex:r,outputs:e}=s;if(new RegExp(r).test(n))return{...e}}let i=t.find((s)=>s.id==="aws");if(!i)throw Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...i.outputs}},Sd=(n,t="")=>{yd=n,Td=t},N3=()=>{Sd(Ed,"")},Id=()=>Td,G3=/\d{12}\.ddb/;async function H3(n,t,i){if(i.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor")Lt(n,"PROTOCOL_RPC_V2_CBOR","M");if(typeof t.retryStrategy==="function"){let e=await t.retryStrategy();if(typeof e.mode==="string")switch(e.mode){case nd.ADAPTIVE:Lt(n,"RETRY_MODE_ADAPTIVE","F");break;case nd.STANDARD:Lt(n,"RETRY_MODE_STANDARD","E");break}}if(typeof t.accountIdEndpointMode==="function"){let e=n.endpointV2;if(String(e?.url?.hostname).match(G3))Lt(n,"ACCOUNT_ID_ENDPOINT","O");switch(await t.accountIdEndpointMode?.()){case"disabled":Lt(n,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":Lt(n,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":Lt(n,"ACCOUNT_ID_MODE_REQUIRED","R");break}}let r=n.__smithy_context?.selectedHttpAuthScheme?.identity;if(r?.$source){let e=r;if(e.accountId)Lt(n,"RESOLVED_ACCOUNT_ID","T");for(let[f,o]of Object.entries(e.$source??{}))Lt(n,f,o)}}var sd="user-agent",uc="x-amz-user-agent",rd=" ",cc="/",W3=/[^!$%&'*+\-.^_`|~\w]/g,F3=/[^!$%&'*+\-.^_`|~\w#]/g,ed="-",P3=1024;function D3(n){let t="";for(let i in n){let s=n[i];if(t.length+s.length+1<=P3){if(t.length)t+=","+s;else t+=s;continue}break}return t}var Ud=(n)=>(t,i)=>async(s)=>{let{request:r}=s;if(!wc.isInstance(r))return t(s);let{headers:e}=r,f=i?.userAgent?.map(Po)||[],o=(await n.defaultUserAgentProvider()).map(Po);await H3(i,n,s);let h=i;o.push(`m/${D3(Object.assign({},i.__smithy_context?.features,h.__aws_sdk_context?.features))}`);let u=n?.customUserAgent?.map(Po)||[],c=await n.userAgentAppId();if(c)o.push(Po(["app",`${c}`]));let _=Id(),w=(_?[_]:[]).concat([...o,...f,...u]).join(rd),l=[...o.filter((A)=>A.startsWith("aws-sdk-")),...u].join(rd);if(n.runtime!=="browser"){if(l)e[uc]=e[uc]?`${e[sd]} ${l}`:l;e[sd]=w}else e[uc]=w;return t({...s,request:r})},Po=(n)=>{let t=n[0].split(cc).map((f)=>f.replace(W3,ed)).join(cc),i=n[1]?.replace(F3,ed),s=t.indexOf(cc),r=t.substring(0,s),e=t.substring(s+1);if(r==="api")e=e.toLowerCase();return[r,e,i].filter((f)=>f&&f.length>0).reduce((f,o,h)=>{switch(h){case 0:return o;case 1:return`${f}/${o}`;default:return`${f}#${o}`}},"")},bd={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},Y3=(n)=>({applyToStack:(t)=>{t.add(Ud(n),bd)}}),m3=()=>{let n=["deno","bun","llrt"];for(let t of n)if(fc[t])return[`md/${t}`,fc[t]];return["md/nodejs",fc.node]},$d={isCrtAvailable:!1},J3=()=>{if($d.isCrtAvailable)return["md/crt-avail"];return null},Ld=({serviceId:n,clientVersion:t})=>{let i=m3();return async(s)=>{let r=[["aws-sdk-js",t],["ua","2.1"],[`os/${e3()}`,o3()],["lang/js"],i],e=J3();if(e)r.push(e);if(n)r.push([`api/${n}`,t]);if(id.AWS_EXECUTION_ENV)r.push([`exec-env/${id.AWS_EXECUTION_ENV}`]);let f=await s?.userAgentAppId?.();return f?[...r,[`app/${f}`]]:[...r]}},X3=Ld,Od="AWS_SDK_UA_APP_ID",Bd="sdk_ua_app_id",z3="sdk-ua-app-id",Q3={environmentVariableSelector:(n)=>n[Od],configFileSelector:(n)=>n[Bd]??n[z3],default:lc},C3=({serviceId:n,clientVersion:t})=>async(i)=>{let s=pM(),r=s.parse??s.default.parse??(()=>""),e=typeof window<"u"&&window?.navigator?.userAgent?r(window.navigator.userAgent):void 0,f=[["aws-sdk-js",t],["ua","2.1"],[`os/${e?.os?.name||"other"}`,e?.os?.version],["lang/js"],["md/browser",`${e?.browser?.name??"unknown"}_${e?.browser?.version??"unknown"}`]];if(n)f.push([`api/${n}`,t]);let o=await i?.userAgentAppId?.();if(o)f.push([`app/${o}`]);return f},x3={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";return},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";return}},Ac=(n,t=!1)=>{if(t){for(let i of n.split("."))if(!Ac(i))return!1;return!0}if(!f3(n))return!1;if(n.length<3||n.length>63)return!1;if(n!==n.toLowerCase())return!1;if(fd(n))return!1;return!0},od=":",K3="/",Nd=(n)=>{let t=n.split(od);if(t.length<6)return null;let[i,s,r,e,f,...o]=t;if(i!=="arn"||s===""||r===""||o.join(od)==="")return null;let h=o.map((u)=>u.split(K3)).flat();return{partition:s,service:r,region:e,accountId:f,resourceId:h}},Gd={isVirtualHostableS3Bucket:Ac,parseArn:Nd,partition:gd};h3.aws=Gd;var k3=(n)=>{if(typeof n.endpointProvider!=="function")throw Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client.");let{endpoint:t}=n;if(t===void 0)n.endpoint=async()=>{return Hd(n.endpointProvider({Region:typeof n.region==="function"?await n.region():n.region,UseDualStack:typeof n.useDualstackEndpoint==="function"?await n.useDualstackEndpoint():n.useDualstackEndpoint,UseFIPS:typeof n.useFipsEndpoint==="function"?await n.useFipsEndpoint():n.useFipsEndpoint,Endpoint:void 0},{logger:n.logger}))};return n},Hd=(n)=>s3(n.url);function q3(n={}){return _3({...hd,async default(){if(!Wd.silence)console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly.");return"us-east-1"}},{...ud,...n})}var Wd={silence:!1},V3=(n)=>{return{setRegion(t){n.region=t},region(){return n.region}}},j3=(n)=>{return{region:n.region()}};a3.DEFAULT_UA_APP_ID=lc;a3.NODE_APP_ID_CONFIG_OPTIONS=Q3;a3.UA_APP_ID_ENV_NAME=Od;a3.UA_APP_ID_INI_NAME=Bd;a3.awsEndpointFunctions=Gd;a3.createDefaultUserAgentProvider=Ld;a3.createUserAgentStringParsingProvider=C3;a3.crtAvailability=$d;a3.defaultUserAgent=X3;a3.emitWarningIfUnsupportedVersion=M3;a3.fallback=x3;a3.getAwsRegionExtensionConfiguration=V3;a3.getHostHeaderPlugin=S3;a3.getLoggerPlugin=I3;a3.getLongPollPlugin=E3;a3.getRecursionDetectionPlugin=L3;a3.getUserAgentMiddlewareOptions=bd;a3.getUserAgentPlugin=Y3;a3.getUserAgentPrefix=Id;a3.hostHeaderMiddleware=cd;a3.hostHeaderMiddlewareOptions=_d;a3.isVirtualHostableS3Bucket=Ac;a3.loggerMiddleware=wd;a3.loggerMiddlewareOptions=ld;a3.parseArn=Nd;a3.partition=gd;a3.recursionDetectionMiddleware=Rd;a3.recursionDetectionMiddlewareOptions=Ad;a3.resolveAwsRegionExtensionConfiguration=j3;a3.resolveDefaultAwsRegionalEndpointsConfig=k3;a3.resolveHostHeaderConfig=g3;a3.resolveUserAgentConfig=B3;a3.setCredentialFeature=y3;a3.setFeature=Lt;a3.setPartitionInfo=Sd;a3.setTokenFeature=T3;a3.state=Do;a3.stsRegionDefaultResolver=q3;a3.stsRegionWarning=Wd;a3.toEndpointV1=Hd;a3.useDefaultPartitionInfo=N3;a3.userAgentMiddleware=Ud});var w1=k((oW)=>{var{fromUtf8:Xd,fromHex:jH,toHex:xi,toUint8Array:se,isArrayBuffer:aH}=mn(),{normalizeProvider:zd}=Xt(),{escapeUri:Yo,HttpRequest:xd}=Jn();class Kd{format(n){let t=[];for(let r of Object.keys(n)){let e=Xd(r);t.push(Uint8Array.from([e.byteLength]),e,this.formatHeaderValue(n[r]))}let i=new Uint8Array(t.reduce((r,e)=>r+e.byteLength,0)),s=0;for(let r of t)i.set(r,s),s+=r.byteLength;return i}formatHeaderValue(n){switch(n.type){case"boolean":return Uint8Array.from([n.value?pn.boolTrue:pn.boolFalse]);case"byte":return Uint8Array.from([pn.byte,n.value]);case"short":let t=new DataView(new ArrayBuffer(3));return t.setUint8(0,pn.short),t.setInt16(1,n.value,!1),new Uint8Array(t.buffer);case"integer":let i=new DataView(new ArrayBuffer(5));return i.setUint8(0,pn.integer),i.setInt32(1,n.value,!1),new Uint8Array(i.buffer);case"long":let s=new Uint8Array(9);return s[0]=pn.long,s.set(n.value.bytes,1),s;case"binary":let r=new DataView(new ArrayBuffer(3+n.value.byteLength));r.setUint8(0,pn.byteArray),r.setUint16(1,n.value.byteLength,!1);let e=new Uint8Array(r.buffer);return e.set(n.value,3),e;case"string":let f=Xd(n.value),o=new DataView(new ArrayBuffer(3+f.byteLength));o.setUint8(0,pn.string),o.setUint16(1,f.byteLength,!1);let h=new Uint8Array(o.buffer);return h.set(f,3),h;case"timestamp":let u=new Uint8Array(9);return u[0]=pn.timestamp,u.set(Ec.fromNumber(n.value.valueOf()).bytes,1),u;case"uuid":if(!vH.test(n.value))throw Error(`Invalid UUID received: ${n.value}`);let c=new Uint8Array(17);return c[0]=pn.uuid,c.set(jH(n.value.replace(/-/g,"")),1),c}}}var pn;(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"})(pn||(pn={}));var vH=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class Ec{bytes;constructor(n){if(this.bytes=n,n.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(n){if(n>9223372036854776000||n<-9223372036854776000)throw Error(`${n} is too large (or, if negative, too small) to represent as an Int64`);let t=new Uint8Array(8);for(let i=7,s=Math.abs(Math.round(n));i>-1&&s>0;i--,s/=256)t[i]=s;if(n<0)Qd(t);return new Ec(t)}valueOf(){let n=this.bytes.slice(0),t=n[0]&128;if(t)Qd(n);return parseInt(xi(n),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function Qd(n){for(let t=0;t<8;t++)n[t]^=255;for(let t=7;t>-1;t--)if(n[t]++,n[t]!==0)break}var kd="X-Amz-Algorithm",qd="X-Amz-Credential",yc="X-Amz-Date",Vd="X-Amz-SignedHeaders",jd="X-Amz-Expires",Tc="X-Amz-Signature",gc="X-Amz-Security-Token",ZH="X-Amz-Region-Set",Sc="authorization",Ic=yc.toLowerCase(),ad="date",vd=[Sc,Ic,ad],Zd=Tc.toLowerCase(),Qo="x-amz-content-sha256",pd=gc.toLowerCase(),pH="host",n1={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},t1=/^proxy-/,i1=/^sec-/,nW=[/^proxy-/i,/^sec-/i],mo="AWS4-HMAC-SHA256",tW="AWS4-ECDSA-P256-SHA256",s1="AWS4-HMAC-SHA256-PAYLOAD",r1="UNSIGNED-PAYLOAD",e1=50,Uc="aws4_request",o1=604800,f1=({query:n={}})=>{let t=[],i={};for(let s of Object.keys(n)){if(s.toLowerCase()===Zd)continue;let r=Yo(s);t.push(r);let e=n[s];if(typeof e==="string")i[r]=`${r}=${Yo(e)}`;else if(Array.isArray(e))i[r]=e.slice(0).reduce((f,o)=>f.concat([`${r}=${Yo(o)}`]),[]).sort().join("&")}return t.sort().map((s)=>i[s]).filter((s)=>s).join("&")},iW=(n)=>sW(n).toISOString().replace(/\.\d{3}Z$/,"Z"),sW=(n)=>{if(typeof n==="number")return new Date(n*1000);if(typeof n==="string"){if(Number(n))return new Date(Number(n)*1000);return new Date(n)}return n};class bc{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:n,credentials:t,region:i,service:s,sha256:r,uriEscapePath:e=!0}){this.service=s,this.sha256=r,this.uriEscapePath=e,this.applyChecksum=typeof n==="boolean"?n:!0,this.regionProvider=zd(i),this.credentialProvider=zd(t)}createCanonicalRequest(n,t,i){let s=Object.keys(t).sort();return`${n.method}
|
|
31
|
+
More information can be found at: https://a.co/c895JFp`)}},HW=()=>(n,t)=>async(i)=>{return t.__retryLongPoll=!0,n(i)},GW={name:"longPollMiddleware",tags:["RETRY"],step:"initialize",override:!0},WW=(n)=>({applyToStack:(t)=>{t.add(HW(),GW)}});function DW(n,t,i){if(!n.$source)n.$source={};return n.$source[t]=i,n}RW.v2026||=typeof process==="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function lt(n,t,i){if(!n.__aws_sdk_context)n.__aws_sdk_context={features:{}};else if(!n.__aws_sdk_context.features)n.__aws_sdk_context.features={};n.__aws_sdk_context.features[t]=i}function PW(n,t,i){if(!n.$source)n.$source={};return n.$source[t]=i,n}function YW(n){return n}var qR=(n)=>(t)=>async(i)=>{if(!Wo.isInstance(i.request))return t(i);let{request:r}=i,{handlerProtocol:s=""}=n.requestHandler.metadata||{};if(s.indexOf("h2")>=0&&!r.headers[":authority"])delete r.headers.host,r.headers[":authority"]=r.hostname+(r.port?":"+r.port:"");else if(!r.headers.host){let f=r.hostname;if(r.port!=null)f+=`:${r.port}`;r.headers.host=f}return t(i)},mR={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},FW=(n)=>({applyToStack:(t)=>{t.add(qR(n),mR)}}),ZR=()=>(n,t)=>async(i)=>{try{let r=await n(i),{clientName:s,commandName:f,logger:h,dynamoDbDocumentClientOptions:_={}}=t,{overrideInputFilterSensitiveLog:c,overrideOutputFilterSensitiveLog:o}=_,w=c??t.inputFilterSensitiveLog,e=o??t.outputFilterSensitiveLog,{$metadata:u,...y}=r.output;return h?.info?.({clientName:s,commandName:f,input:w(i.input),output:e(y),metadata:u}),r}catch(r){let{clientName:s,commandName:f,logger:h,dynamoDbDocumentClientOptions:_={}}=t,{overrideInputFilterSensitiveLog:c}=_,o=c??t.inputFilterSensitiveLog;throw h?.error?.({clientName:s,commandName:f,input:o(i.input),error:r,metadata:r.$metadata}),r}},aR={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},XW=(n)=>({applyToStack:(t)=>{t.add(ZR(),aR)}}),vR={step:"build",tags:["RECURSION_DETECTION","TRACE_CONTEXT_PROPAGATION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},lW="AWS_LAMBDA_FUNCTION_NAME",JW="_X_AMZN_TRACE_ID",Bo="X-Amzn-Trace-Id",Go="traceparent",pR="tracestate",n1="baggage",t1=()=>(n)=>async(t)=>{let{request:i}=t;if(!Wo.isInstance(i))return n(t);let r;{let s=Object.keys(i.headers??{}).find((f)=>f.toLowerCase()===Bo.toLowerCase())??Bo;if(!i.headers.hasOwnProperty(s)){let f=process.env[lW],h=process.env[JW];r??=await JR.getInstanceAsync();let c=r?.getXRayTraceId()??h,o=(w)=>typeof w==="string"&&w.length>0;if(o(f)&&o(c))i.headers[Bo]=c}}if(QW(i.headers),!i.headers[Go]){let f=(r??=await JR.getInstanceAsync())?.getTraceparent?.();if(f){i.headers[Go]=f;let h=r?.getTracestate?.();if(h)i.headers[pR]=h;let _=r?.getBaggage?.();if(_)i.headers[n1]=_}}return n(t)};function QW(n){for(let t of Object.keys(n)){let i=t.toLowerCase();if(t!==i&&(i===Go||i===pR||i===n1))n[i]=n[t],delete n[t]}}var zW=(n)=>({applyToStack:(t)=>{t.add(t1(),vR)}}),Do=void 0;function CW(n){if(n===void 0)return!0;return typeof n==="string"&&n.length<=50}function VW(n){let t=EW(n.userAgentAppId??Do),{customUserAgent:i}=n;return Object.assign(n,{customUserAgent:typeof i==="string"?[[i]]:i,userAgentAppId:async()=>{let r=await t();if(!CW(r)){let s=n.logger?.constructor?.name==="NoOpLogger"||!n.logger?console:n.logger;if(typeof r!=="string")s?.warn("userAgentAppId must be a string or undefined.");else if(r.length>50)s?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return r}})}var i1={partitions:[{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)"}}}],version:"1.1"},r1=i1,s1="",f1=(n)=>{let{partitions:t}=r1;for(let r of t){let{regions:s,outputs:f}=r;for(let[h,_]of Object.entries(s))if(h===n)return{...f,..._}}for(let r of t){let{regionRegex:s,outputs:f}=r;if(new RegExp(s).test(n))return{...f}}let i=t.find((r)=>r.id==="aws");if(!i)throw Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...i.outputs}},_1=(n,t="")=>{r1=n,s1=t},KW=()=>{_1(i1,"")},h1=()=>s1,xW=/\d{12}\.ddb/;async function jW(n,t,i){if(i.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor")lt(n,"PROTOCOL_RPC_V2_CBOR","M");if(typeof t.retryStrategy==="function"){let f=await t.retryStrategy();if(typeof f.mode==="string")switch(f.mode){case lR.ADAPTIVE:lt(n,"RETRY_MODE_ADAPTIVE","F");break;case lR.STANDARD:lt(n,"RETRY_MODE_STANDARD","E");break}}if(typeof t.accountIdEndpointMode==="function"){let f=n.endpointV2;if(String(f?.url?.hostname).match(xW))lt(n,"ACCOUNT_ID_ENDPOINT","O");switch(await t.accountIdEndpointMode?.()){case"disabled":lt(n,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":lt(n,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":lt(n,"ACCOUNT_ID_MODE_REQUIRED","R");break}}let s=n.__smithy_context?.selectedHttpAuthScheme?.identity;if(s?.$source){let f=s;if(f.accountId)lt(n,"RESOLVED_ACCOUNT_ID","T");for(let[h,_]of Object.entries(f.$source??{}))lt(n,h,_)}}var zR="user-agent",Io="x-amz-user-agent",CR=" ",Ho="/",kW=/[^!$%&'*+\-.^_`|~\w]/g,qW=/[^!$%&'*+\-.^_`|~\w#]/g,VR="-",mW=1024;function ZW(n){let t="";for(let i in n){let r=n[i];if(t.length+r.length+1<=mW){if(t.length)t+=","+r;else t+=r;continue}break}return t}var c1=(n)=>(t,i)=>async(r)=>{let{request:s}=r;if(!Wo.isInstance(s))return t(r);let{headers:f}=s,h=i?.userAgent?.map(Z_)||[],_=(await n.defaultUserAgentProvider()).map(Z_);await jW(i,n,r);let c=i;_.push(`m/${ZW(Object.assign({},i.__smithy_context?.features,c.__aws_sdk_context?.features))}`);let o=n?.customUserAgent?.map(Z_)||[],w=await n.userAgentAppId();if(w)_.push(Z_(["app",`${w}`]));let e=h1(),u=(e?[e]:[]).concat([..._,...h,...o]).join(CR),y=[..._.filter((A)=>A.startsWith("aws-sdk-")),...o].join(CR);if(n.runtime!=="browser"){if(y)f[Io]=f[Io]?`${f[zR]} ${y}`:y;f[zR]=u}else f[Io]=u;return t({...r,request:s})},Z_=(n)=>{let t=n[0].split(Ho).map((h)=>h.replace(kW,VR)).join(Ho),i=n[1]?.replace(qW,VR),r=t.indexOf(Ho),s=t.substring(0,r),f=t.substring(r+1);if(s==="api")f=f.toLowerCase();return[s,f,i].filter((h)=>h&&h.length>0).reduce((h,_,c)=>{switch(c){case 0:return _;case 1:return`${h}/${_}`;default:return`${h}#${_}`}},"")},o1={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},aW=(n)=>({applyToStack:(t)=>{t.add(c1(n),o1)}}),vW=()=>{let n=["deno","bun","llrt"];for(let t of n)if(No[t])return[`md/${t}`,No[t]];return["md/nodejs",No.node]},w1={isCrtAvailable:!1},pW=()=>{if(w1.isCrtAvailable)return["md/crt-avail"];return null},e1=({serviceId:n,clientVersion:t})=>{let i=vW();return async(r)=>{let s=[["aws-sdk-js",t],["ua","2.1"],[`os/${TW()}`,gW()],["lang/js"],i],f=pW();if(f)s.push(f);if(n)s.push([`api/${n}`,t]);if(QR.AWS_EXECUTION_ENV)s.push([`exec-env/${QR.AWS_EXECUTION_ENV}`]);let h=await r?.userAgentAppId?.();return h?[...s,[`app/${h}`]]:[...s]}},nD=e1,u1="AWS_SDK_UA_APP_ID",y1="sdk_ua_app_id",tD="sdk-ua-app-id",iD={environmentVariableSelector:(n)=>n[u1],configFileSelector:(n)=>n[y1]??n[tD],default:Do},rD=({serviceId:n,clientVersion:t})=>async(i)=>{let r=XR(),s=r.parse??r.default.parse??(()=>""),f=typeof window<"u"&&window?.navigator?.userAgent?s(window.navigator.userAgent):void 0,h=[["aws-sdk-js",t],["ua","2.1"],[`os/${f?.os?.name||"other"}`,f?.os?.version],["lang/js"],["md/browser",`${f?.browser?.name??"unknown"}_${f?.browser?.version??"unknown"}`]];if(n)h.push([`api/${n}`,t]);let _=await i?.userAgentAppId?.();if(_)h.push([`app/${_}`]);return h},sD={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";return},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";return}},Po=(n,t=!1)=>{if(t){for(let i of n.split("."))if(!Po(i))return!1;return!0}if(!SW(n))return!1;if(n.length<3||n.length>63)return!1;if(n!==n.toLowerCase())return!1;if(xR(n))return!1;return!0},KR=":",fD="/",d1=(n)=>{let t=n.split(KR);if(t.length<6)return null;let[i,r,s,f,h,..._]=t;if(i!=="arn"||r===""||s===""||_.join(KR)==="")return null;let c=_.map((o)=>o.split(fD)).flat();return{partition:r,service:s,region:f,accountId:h,resourceId:c}},A1={isVirtualHostableS3Bucket:Po,parseArn:d1,partition:f1};LW.aws=A1;var _D=(n)=>{if(typeof n.endpointProvider!=="function")throw Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client.");let{endpoint:t}=n;if(t===void 0)n.endpoint=async()=>{return R1(n.endpointProvider({Region:typeof n.region==="function"?await n.region():n.region,UseDualStack:typeof n.useDualstackEndpoint==="function"?await n.useDualstackEndpoint():n.useDualstackEndpoint,UseFIPS:typeof n.useFipsEndpoint==="function"?await n.useFipsEndpoint():n.useFipsEndpoint,Endpoint:void 0},{logger:n.logger}))};return n},R1=(n)=>MW(n.url);function hD(n={}){return UW({...jR,async default(){if(!M1.silence)console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly.");return"us-east-1"}},{...kR,...n})}var M1={silence:!1},cD=(n)=>{return{setRegion(t){n.region=t},region(){return n.region}}},oD=(n)=>{return{region:n.region()}};wD.DEFAULT_UA_APP_ID=Do;wD.NODE_APP_ID_CONFIG_OPTIONS=iD;wD.UA_APP_ID_ENV_NAME=u1;wD.UA_APP_ID_INI_NAME=y1;wD.awsEndpointFunctions=A1;wD.createDefaultUserAgentProvider=e1;wD.createUserAgentStringParsingProvider=rD;wD.crtAvailability=w1;wD.defaultUserAgent=nD;wD.emitWarningIfUnsupportedVersion=IW;wD.fallback=sD;wD.getAwsRegionExtensionConfiguration=cD;wD.getHostHeaderPlugin=FW;wD.getLoggerPlugin=XW;wD.getLongPollPlugin=WW;wD.getRecursionDetectionPlugin=zW;wD.getUserAgentMiddlewareOptions=o1;wD.getUserAgentPlugin=aW;wD.getUserAgentPrefix=h1;wD.hostHeaderMiddleware=qR;wD.hostHeaderMiddlewareOptions=mR;wD.isVirtualHostableS3Bucket=Po;wD.loggerMiddleware=ZR;wD.loggerMiddlewareOptions=aR;wD.parseArn=d1;wD.partition=f1;wD.recursionDetectionMiddleware=t1;wD.recursionDetectionMiddlewareOptions=vR;wD.resolveAwsRegionExtensionConfiguration=oD;wD.resolveDefaultAwsRegionalEndpointsConfig=_D;wD.resolveHostHeaderConfig=YW;wD.resolveUserAgentConfig=VW;wD.setCredentialFeature=DW;wD.setFeature=lt;wD.setPartitionInfo=_1;wD.setTokenFeature=PW;wD.state=a_;wD.stsRegionDefaultResolver=hD;wD.stsRegionWarning=M1;wD.toEndpointV1=R1;wD.useDefaultPartitionInfo=KW;wD.userAgentMiddleware=c1});var Z1=nn((g7)=>{var{fromUtf8:O1,fromHex:o7,toHex:rr,toUint8Array:gf,isArrayBuffer:w7}=jn(),{normalizeProvider:U1}=at(),{escapeUri:v_,HttpRequest:B1}=kn();class I1{format(n){let t=[];for(let s of Object.keys(n)){let f=O1(s);t.push(Uint8Array.from([f.byteLength]),f,this.formatHeaderValue(n[s]))}let i=new Uint8Array(t.reduce((s,f)=>s+f.byteLength,0)),r=0;for(let s of t)i.set(s,r),r+=s.byteLength;return i}formatHeaderValue(n){switch(n.type){case"boolean":return Uint8Array.from([n.value?ct.boolTrue:ct.boolFalse]);case"byte":return Uint8Array.from([ct.byte,n.value]);case"short":let t=new DataView(new ArrayBuffer(3));return t.setUint8(0,ct.short),t.setInt16(1,n.value,!1),new Uint8Array(t.buffer);case"integer":let i=new DataView(new ArrayBuffer(5));return i.setUint8(0,ct.integer),i.setInt32(1,n.value,!1),new Uint8Array(i.buffer);case"long":let r=new Uint8Array(9);return r[0]=ct.long,r.set(n.value.bytes,1),r;case"binary":let s=new DataView(new ArrayBuffer(3+n.value.byteLength));s.setUint8(0,ct.byteArray),s.setUint16(1,n.value.byteLength,!1);let f=new Uint8Array(s.buffer);return f.set(n.value,3),f;case"string":let h=O1(n.value),_=new DataView(new ArrayBuffer(3+h.byteLength));_.setUint8(0,ct.string),_.setUint16(1,h.byteLength,!1);let c=new Uint8Array(_.buffer);return c.set(h,3),c;case"timestamp":let o=new Uint8Array(9);return o[0]=ct.timestamp,o.set(lo.fromNumber(n.value.valueOf()).bytes,1),o;case"uuid":if(!e7.test(n.value))throw Error(`Invalid UUID received: ${n.value}`);let w=new Uint8Array(17);return w[0]=ct.uuid,w.set(o7(n.value.replace(/-/g,"")),1),w}}}var ct;(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"})(ct||(ct={}));var e7=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class lo{bytes;constructor(n){if(this.bytes=n,n.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(n){if(n>9223372036854776000||n<-9223372036854776000)throw Error(`${n} is too large (or, if negative, too small) to represent as an Int64`);let t=new Uint8Array(8);for(let i=7,r=Math.abs(Math.round(n));i>-1&&r>0;i--,r/=256)t[i]=r;if(n<0)b1(t);return new lo(t)}valueOf(){let n=this.bytes.slice(0),t=n[0]&128;if(t)b1(n);return parseInt(rr(n),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function b1(n){for(let t=0;t<8;t++)n[t]^=255;for(let t=7;t>-1;t--)if(n[t]++,n[t]!==0)break}var H1="X-Amz-Algorithm",G1="X-Amz-Credential",Jo="X-Amz-Date",W1="X-Amz-SignedHeaders",D1="X-Amz-Expires",Qo="X-Amz-Signature",zo="X-Amz-Security-Token",u7="X-Amz-Region-Set",Co="authorization",Vo=Jo.toLowerCase(),P1="date",Y1=[Co,Vo,P1],F1=Qo.toLowerCase(),rh="x-amz-content-sha256",X1=zo.toLowerCase(),y7="host",l1={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},J1=/^proxy-/,Q1=/^sec-/,d7=[/^proxy-/i,/^sec-/i],p_="AWS4-HMAC-SHA256",A7="AWS4-ECDSA-P256-SHA256",z1="AWS4-HMAC-SHA256-PAYLOAD",C1="UNSIGNED-PAYLOAD",V1=50,Ko="aws4_request",K1=604800,x1=({query:n={}})=>{let t=[],i={};for(let r of Object.keys(n)){if(r.toLowerCase()===F1)continue;let s=v_(r);t.push(s);let f=n[r];if(typeof f==="string")i[s]=`${s}=${v_(f)}`;else if(Array.isArray(f))i[s]=f.slice(0).reduce((h,_)=>h.concat([`${s}=${v_(_)}`]),[]).sort().join("&")}return t.sort().map((r)=>i[r]).filter((r)=>r).join("&")},R7=(n)=>M7(n).toISOString().replace(/\.\d{3}Z$/,"Z"),M7=(n)=>{if(typeof n==="number")return new Date(n*1000);if(typeof n==="string"){if(Number(n))return new Date(Number(n)*1000);return new Date(n)}return n};class xo{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:n,credentials:t,region:i,service:r,sha256:s,uriEscapePath:f=!0}){this.service=r,this.sha256=s,this.uriEscapePath=f,this.applyChecksum=typeof n==="boolean"?n:!0,this.regionProvider=U1(i),this.credentialProvider=U1(t)}createCanonicalRequest(n,t,i){let r=Object.keys(t).sort();return`${n.method}
|
|
32
32
|
${this.getCanonicalPath(n)}
|
|
33
|
-
${
|
|
34
|
-
${
|
|
33
|
+
${x1(n)}
|
|
34
|
+
${r.map((s)=>`${s}:${t[s]}`).join(`
|
|
35
35
|
`)}
|
|
36
36
|
|
|
37
|
-
${
|
|
38
|
-
${i}`}async createStringToSign(n,t,i,
|
|
37
|
+
${r.join(";")}
|
|
38
|
+
${i}`}async createStringToSign(n,t,i,r){let s=new this.sha256;s.update(gf(i));let f=await s.digest();return`${r}
|
|
39
39
|
${n}
|
|
40
40
|
${t}
|
|
41
|
-
${
|
|
42
|
-
`);return this.signString(A,{signingDate:i,signingRegion:o,signingService:e,eventStreamCredentials:f})}async signMessage(n,{signingDate:t=new Date,signingRegion:i,signingService:s,eventStreamCredentials:r}){return this.signEvent({headers:this.headerFormatter.format(n.message.headers),payload:n.message.body},{signingDate:t,signingRegion:i,signingService:s,priorSignature:n.priorSignature,eventStreamCredentials:r}).then((f)=>{return{message:n.message,signature:f}})}async signString(n,{signingDate:t=new Date,signingRegion:i,signingService:s,eventStreamCredentials:r}={}){let e=r??await this.credentialProvider();this.validateResolvedCredentials(e);let f=i??await this.regionProvider(),{shortDate:o}=this.formatDate(t),h=new this.sha256(await this.getSigningKey(e,f,o,s));return h.update(se(n)),xi(await h.digest())}async signRequest(n,{signingDate:t=new Date,signableHeaders:i,unsignableHeaders:s,signingRegion:r,signingService:e}={}){let f=await this.credentialProvider();this.validateResolvedCredentials(f);let o=r??await this.regionProvider(),h=Rc(n),{longDate:u,shortDate:c}=this.formatDate(t),_=Xo(c,o,e??this.service);if(h.headers[Ic]=u,f.sessionToken)h.headers[pd]=f.sessionToken;let w=await zo(h,this.sha256);if(!u1(Qo,h.headers)&&this.applyChecksum)h.headers[Qo]=w;let l=dc(h,s,i),A=await this.getSignature(u,_,this.getSigningKey(f,o,c,e),this.createCanonicalRequest(h,l,w));return h.headers[Sc]=`${mo} Credential=${f.accessKeyId}/${_}, SignedHeaders=${this.getCanonicalHeaderList(l)}, Signature=${A}`,h}async getSignature(n,t,i,s){let r=await this.createStringToSign(n,t,s,mo),e=new this.sha256(await i);return e.update(se(r)),xi(await e.digest())}getSigningKey(n,t,i,s){return h1(this.sha256,n,i,t,s||this.service)}}var eW={SignatureV4a:null};oW.ALGORITHM_IDENTIFIER=mo;oW.ALGORITHM_IDENTIFIER_V4A=tW;oW.ALGORITHM_QUERY_PARAM=kd;oW.ALWAYS_UNSIGNABLE_HEADERS=n1;oW.AMZ_DATE_HEADER=Ic;oW.AMZ_DATE_QUERY_PARAM=yc;oW.AUTH_HEADER=Sc;oW.CREDENTIAL_QUERY_PARAM=qd;oW.DATE_HEADER=ad;oW.EVENT_ALGORITHM_IDENTIFIER=s1;oW.EXPIRES_QUERY_PARAM=jd;oW.GENERATED_HEADERS=vd;oW.HOST_HEADER=pH;oW.KEY_TYPE_IDENTIFIER=Uc;oW.MAX_CACHE_SIZE=e1;oW.MAX_PRESIGNED_TTL=o1;oW.PROXY_HEADER_PATTERN=t1;oW.REGION_SET_PARAM=ZH;oW.SEC_HEADER_PATTERN=i1;oW.SHA256_HEADER=Qo;oW.SIGNATURE_HEADER=Zd;oW.SIGNATURE_QUERY_PARAM=Tc;oW.SIGNED_HEADERS_QUERY_PARAM=Vd;oW.SignatureV4=_1;oW.SignatureV4Base=bc;oW.TOKEN_HEADER=pd;oW.TOKEN_QUERY_PARAM=gc;oW.UNSIGNABLE_PATTERNS=nW;oW.UNSIGNED_PAYLOAD=r1;oW.clearCredentialCache=rW;oW.createScope=Xo;oW.getCanonicalHeaders=dc;oW.getCanonicalQuery=f1;oW.getPayloadHash=zo;oW.getSigningKey=h1;oW.hasHeader=u1;oW.moveHeadersToQuery=c1;oW.prepareRequest=Rc;oW.signatureV4aContainer=eW});var Oc=k((eF)=>{var{HttpResponse:kW,HttpRequest:T1}=Jn(),{normalizeProvider:re,memoizeIdentityProvider:qW,isIdentityExpired:VW,doesIdentityRequireRefresh:jW}=_i(),{ProviderError:l1}=Yn(),{setCredentialFeature:aW}=ct(),{SignatureV4:A1}=w1(),M1=(n)=>kW.isInstance(n)?n.headers?.date??n.headers?.Date:void 0,$c=(n)=>new Date(Date.now()+n),vW=(n,t)=>Math.abs($c(t).getTime()-n)>=300000,d1=(n,t)=>{let i=Date.parse(n);if(vW(i,t))return i-Date.now();return t},ee=(n,t)=>{if(!t)throw Error(`Property \`${n}\` is not resolved for AWS SDK SigV4Auth`);return t},Lc=async(n)=>{let t=ee("context",n.context),i=ee("config",n.config),s=t.endpointV2?.properties?.authSchemes?.[0],e=await ee("signer",i.signer)(s),f=n?.signingRegion,o=n?.signingRegionSet,h=n?.signingName;return{config:i,signer:e,signingRegion:f,signingRegionSet:o,signingName:h}};class Co{async sign(n,t,i){if(!T1.isInstance(n))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let s=await Lc(i),{config:r,signer:e}=s,{signingRegion:f,signingName:o}=s,h=i.context;if(h?.authSchemes?.length??!1){let[c,_]=h.authSchemes;if(c?.name==="sigv4a"&&_?.name==="sigv4")f=_?.signingRegion??f,o=_?.signingName??o}return i._preRequestSystemClockOffset=r.systemClockOffset,await e.sign(n,{signingDate:$c(r.systemClockOffset),signingRegion:f,signingService:o})}errorHandler(n){return(t)=>{let i=t,s=i.ServerTime??M1(i.$response);if(s){let r=ee("config",n.config),e=n._preRequestSystemClockOffset,f=d1(s,r.systemClockOffset);if((f!==r.systemClockOffset||e!==void 0&&e!==f)&&i.$metadata)r.systemClockOffset=f,i.$metadata.clockSkewCorrected=!0}throw t}}successHandler(n,t){let i=M1(n);if(i){let s=ee("config",t.config);s.systemClockOffset=d1(i,s.systemClockOffset)}}}var ZW=Co;class g1 extends Co{async sign(n,t,i){if(!T1.isInstance(n))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let{config:s,signer:r,signingRegion:e,signingRegionSet:f,signingName:o}=await Lc(i),u=(await s.sigv4aSigningRegionSet?.()??f??[e]).join(",");return i._preRequestSystemClockOffset=s.systemClockOffset,await r.sign(n,{signingDate:$c(s.systemClockOffset),signingRegion:u,signingService:o})}}var R1=(n)=>typeof n==="string"&&n.length>0?n.split(",").map((t)=>t.trim()):[],S1=(n)=>`AWS_BEARER_TOKEN_${n.replace(/[\s-]/g,"_").toUpperCase()}`,E1="AWS_AUTH_SCHEME_PREFERENCE",y1="auth_scheme_preference",pW={environmentVariableSelector:(n,t)=>{if(t?.signingName){if(S1(t.signingName)in n)return["httpBearerAuth"]}if(!(E1 in n))return;return R1(n[E1])},configFileSelector:(n)=>{if(!(y1 in n))return;return R1(n[y1])},default:[]},nF=(n)=>{return n.sigv4aSigningRegionSet=re(n.sigv4aSigningRegionSet),n},tF={environmentVariableSelector(n){if(n.AWS_SIGV4A_SIGNING_REGION_SET)return n.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((t)=>t.trim());throw new l1("AWS_SIGV4A_SIGNING_REGION_SET not set in env.",{tryNextLink:!0})},configFileSelector(n){if(n.sigv4a_signing_region_set)return(n.sigv4a_signing_region_set??"").split(",").map((t)=>t.trim());throw new l1("sigv4a_signing_region_set not set in profile.",{tryNextLink:!0})},default:void 0},I1=(n)=>{let t=n.credentials,i=!!n.credentials,s=void 0;Object.defineProperty(n,"credentials",{set(u){if(u&&u!==t&&u!==s)i=!0;t=u;let c=sF(n,{credentials:t,credentialDefaultProvider:n.credentialDefaultProvider}),_=rF(n,c);if(i&&!_.attributed){let w=typeof t==="object"&&t!==null;s=async(l)=>{let d=await _(l);if(w&&(!d.$source||Object.keys(d.$source).length===0))return aW(d,"CREDENTIALS_CODE","e");return d},s.memoized=_.memoized,s.configBound=_.configBound,s.attributed=!0}else s=_},get(){return s},enumerable:!0,configurable:!0}),n.credentials=t;let{signingEscapePath:r=!0,systemClockOffset:e=n.systemClockOffset||0,sha256:f}=n,o;if(n.signer)o=re(n.signer);else if(n.regionInfoProvider)o=()=>re(n.region)().then(async(u)=>[await n.regionInfoProvider(u,{useFipsEndpoint:await n.useFipsEndpoint(),useDualstackEndpoint:await n.useDualstackEndpoint()})||{},u]).then(([u,c])=>{let{signingRegion:_,signingService:w}=u;n.signingRegion=n.signingRegion||_||c,n.signingName=n.signingName||w||n.serviceId;let l={...n,credentials:n.credentials,region:n.signingRegion,service:n.signingName,sha256:f,uriEscapePath:r};return new(n.signerConstructor||A1)(l)});else o=async(u)=>{u=Object.assign({},{name:"sigv4",signingName:n.signingName||n.defaultSigningName,signingRegion:await re(n.region)(),properties:{}},u);let{signingRegion:c,signingName:_}=u;n.signingRegion=n.signingRegion||c,n.signingName=n.signingName||_||n.serviceId;let w={...n,credentials:n.credentials,region:n.signingRegion,service:n.signingName,sha256:f,uriEscapePath:r};return new(n.signerConstructor||A1)(w)};return Object.assign(n,{systemClockOffset:e,signingEscapePath:r,signer:o})},iF=I1;function sF(n,{credentials:t,credentialDefaultProvider:i}){let s;if(t)if(!t?.memoized)s=qW(t,VW,jW);else s=t;else if(i)s=re(i(Object.assign({},n,{parentClientConfig:n})));else s=async()=>{throw Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")};return s.memoized=!0,s}function rF(n,t){if(t.configBound)return t;let i=async(s)=>t({...s,callerClientConfig:n});return i.memoized=t.memoized,i.configBound=!0,i}eF.AWSSDKSigV4Signer=ZW;eF.AwsSdkSigV4ASigner=g1;eF.AwsSdkSigV4Signer=Co;eF.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS=pW;eF.NODE_SIGV4A_CONFIG_OPTIONS=tF;eF.getBearerTokenEnvKey=S1;eF.resolveAWSSDKSigV4Config=iF;eF.resolveAwsSdkSigV4AConfig=nF;eF.resolveAwsSdkSigV4Config=I1;eF.validateSigningProperties=Lc});var jo=k((LF)=>{var{buildQueryString:N1,HttpResponse:G1}=Jn(),xo=p("https"),{Readable:dF}=p("stream"),Bc=p("http2"),{streamCollector:RF}=mn();LF.streamCollector=RF;function ko(n){let t=n&&typeof n==="object"&&"reason"in n?n.reason:void 0;if(t){if(t instanceof Error){let r=Error("Request aborted");return r.name="AbortError",r.cause=t,r}let s=Error(String(t));return s.name="AbortError",s}let i=Error("Request aborted");return i.name="AbortError",i}var EF=["ECONNRESET","EPIPE","ETIMEDOUT"],H1=(n)=>{let t={};for(let i in n){let s=n[i];t[i]=Array.isArray(s)?s.join(","):s}return t},Bn={setTimeout:(n,t)=>setTimeout(n,t),clearTimeout:(n)=>clearTimeout(n)},b1=1000,yF=(n,t,i=0)=>{if(!i)return-1;let s=(r)=>{let e=Bn.setTimeout(()=>{n.destroy(),t(Object.assign(Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${i} ms.`),{name:"TimeoutError"}))},i-r),f=(o)=>{if(o?.connecting)o.on("connect",()=>{Bn.clearTimeout(e)});else Bn.clearTimeout(e)};if(n.socket)f(n.socket);else n.on("socket",f)};if(i<2000)return s(0),0;return Bn.setTimeout(s.bind(null,b1),b1)},TF=(n,t,i=0,s,r)=>{if(i)return Bn.setTimeout(()=>{let e=`@smithy/node-http-handler - [${s?"ERROR":"WARN"}] a request has exceeded the configured ${i} ms requestTimeout.`;if(s){let f=Object.assign(Error(e),{name:"TimeoutError",code:"ETIMEDOUT"});n.destroy(f),t(f)}else e+=" Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.",r?.warn?.(e)},i);return-1},gF=3000,SF=(n,{keepAlive:t,keepAliveMsecs:i},s=gF)=>{if(t!==!0)return-1;let r=()=>{if(n.socket)n.socket.setKeepAlive(t,i||0);else n.on("socket",(e)=>{e.setKeepAlive(t,i||0)})};if(s===0)return r(),0;return Bn.setTimeout(r,s)},$1=3000,IF=(n,t,i=0)=>{let s=(r)=>{let e=i-r,f=()=>{n.destroy(),t(Object.assign(Error(`@smithy/node-http-handler - the request socket timed out after ${i} ms of inactivity (configured by client requestHandler).`),{name:"TimeoutError"}))};if(n.socket)n.socket.setTimeout(e,f),n.on("close",()=>n.socket?.removeListener("timeout",f));else n.setTimeout(e,f)};if(0<i&&i<6000)return s(0),0;return Bn.setTimeout(s.bind(null,i===0?0:$1),$1)},L1=6000;async function W1(n,t,i=L1,s=!1){let r=t.headers,e=r?r.Expect||r.expect:void 0,f=-1,o=!0;if(!s&&e==="100-continue")o=await Promise.race([new Promise((h)=>{f=Number(Bn.setTimeout(()=>h(!0),Math.max(L1,i)))}),new Promise((h)=>{n.on("continue",()=>{Bn.clearTimeout(f),h(!0)}),n.on("response",()=>{Bn.clearTimeout(f),h(!1)}),n.on("error",()=>{Bn.clearTimeout(f),h(!1)})})]);if(o)UF(n,t.body)}function UF(n,t){if(t instanceof dF){t.pipe(n);return}if(t){let i=Buffer.isBuffer(t);if(i||typeof t==="string"){if(i&&t.byteLength===0)n.end();else n.end(t);return}let r=t;if(typeof r==="object"&&r.buffer&&typeof r.byteOffset==="number"&&typeof r.byteLength==="number"){n.end(Buffer.from(r.buffer,r.byteOffset,r.byteLength));return}n.end(Buffer.from(t));return}n.end()}var bF=0,Ko=void 0,O1=void 0;class qo{config;configProvider;socketWarningTimestamp=0;externalAgent=!1;metadata={handlerProtocol:"http/1.1"};static create(n){if(typeof n?.handle==="function")return n;return new qo(n)}static checkSocketUsage(n,t,i=console){let{sockets:s,requests:r,maxSockets:e}=n;if(typeof e!=="number"||e===1/0)return t;let f=15000;if(Date.now()-f<t)return t;if(s&&r)for(let o in s){let h=s[o]?.length??0,u=r[o]?.length??0;if(h>=e&&u>=2*e)return i?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${h} and ${u} additional requests are enqueued.
|
|
41
|
+
${rr(f)}`}getCanonicalPath({path:n}){if(this.uriEscapePath){let t=[];for(let s of n.split("/")){if(s?.length===0)continue;if(s===".")continue;if(s==="..")t.pop();else t.push(s)}let i=`${n?.startsWith("/")?"/":""}${t.join("/")}${t.length>0&&n?.endsWith("/")?"/":""}`;return v_(i).replace(/%2F/g,"/")}return n}validateResolvedCredentials(n){if(typeof n!=="object"||typeof n.accessKeyId!=="string"||typeof n.secretAccessKey!=="string")throw Error("Resolved credential object is not valid")}formatDate(n){let t=R7(n).replace(/[-:]/g,"");return{longDate:t,shortDate:t.slice(0,8)}}getCanonicalHeaderList(n){return Object.keys(n).sort().join(";")}}var rs={},nh=[],th=(n,t,i)=>`${n}/${t}/${i}/${Ko}`,j1=async(n,t,i,r,s)=>{let f=await N1(n,t.secretAccessKey,t.accessKeyId),h=`${i}:${r}:${s}:${rr(f)}:${t.sessionToken}`;if(h in rs)return rs[h];nh.push(h);while(nh.length>V1)delete rs[nh.shift()];let _=`AWS4${t.secretAccessKey}`;for(let c of[i,r,s,Ko])_=await N1(n,_,c);return rs[h]=_},E7=()=>{nh.length=0,Object.keys(rs).forEach((n)=>{delete rs[n]})},N1=(n,t,i)=>{let r=new n(t);return r.update(gf(i)),r.digest()},Fo=({headers:n},t,i)=>{let r={};for(let s of Object.keys(n).sort()){if(n[s]==null)continue;let f=s.toLowerCase();if(f in l1||t?.has(f)||J1.test(f)||Q1.test(f)){if(!i||i&&!i.has(f))continue}r[f]=n[s].trim().replace(/\s+/g," ")}return r},ih=async({headers:n,body:t},i)=>{for(let r of Object.keys(n))if(r.toLowerCase()===rh)return n[r];if(t==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";else if(typeof t==="string"||ArrayBuffer.isView(t)||w7(t)){let r=new i;return r.update(gf(t)),rr(await r.digest())}return C1},k1=(n,t)=>{n=n.toLowerCase();for(let i of Object.keys(t))if(n===i.toLowerCase())return!0;return!1},q1=(n,t={})=>{let{headers:i,query:r={}}=B1.clone(n);for(let s of Object.keys(i)){let f=s.toLowerCase();if(f.slice(0,6)==="x-amz-"&&!t.unhoistableHeaders?.has(f)||t.hoistableHeaders?.has(f))r[s]=i[s],delete i[s]}return{...n,headers:i,query:r}},Xo=(n)=>{n=B1.clone(n);for(let t of Object.keys(n.headers))if(Y1.indexOf(t.toLowerCase())>-1)delete n.headers[t];return n};class m1 extends xo{headerFormatter=new I1;constructor({applyChecksum:n,credentials:t,region:i,service:r,sha256:s,uriEscapePath:f=!0}){super({applyChecksum:n,credentials:t,region:i,service:r,sha256:s,uriEscapePath:f})}async presign(n,t={}){let{signingDate:i=new Date,expiresIn:r=3600,unsignableHeaders:s,unhoistableHeaders:f,signableHeaders:h,hoistableHeaders:_,signingRegion:c,signingService:o}=t,w=await this.credentialProvider();this.validateResolvedCredentials(w);let e=c??await this.regionProvider(),{longDate:u,shortDate:y}=this.formatDate(i);if(r>K1)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let A=th(y,e,o??this.service),R=q1(Xo(n),{unhoistableHeaders:f,hoistableHeaders:_});if(w.sessionToken)R.query[zo]=w.sessionToken;R.query[H1]=p_,R.query[G1]=`${w.accessKeyId}/${A}`,R.query[Jo]=u,R.query[D1]=r.toString(10);let M=Fo(R,s,h);return R.query[W1]=this.getCanonicalHeaderList(M),R.query[Qo]=await this.getSignature(u,A,this.getSigningKey(w,e,y,o),this.createCanonicalRequest(R,M,await ih(n,this.sha256))),R}async sign(n,t){if(typeof n==="string")return this.signString(n,t);else if(n.headers&&n.payload)return this.signEvent(n,t);else if(n.message)return this.signMessage(n,t);else return this.signRequest(n,t)}async signEvent({headers:n,payload:t},{signingDate:i=new Date,priorSignature:r,signingRegion:s,signingService:f,eventStreamCredentials:h}){let _=s??await this.regionProvider(),{shortDate:c,longDate:o}=this.formatDate(i),w=th(c,_,f??this.service),e=await ih({headers:{},body:t},this.sha256),u=new this.sha256;u.update(n);let y=rr(await u.digest()),A=[z1,o,w,r,y,e].join(`
|
|
42
|
+
`);return this.signString(A,{signingDate:i,signingRegion:_,signingService:f,eventStreamCredentials:h})}async signMessage(n,{signingDate:t=new Date,signingRegion:i,signingService:r,eventStreamCredentials:s}){return this.signEvent({headers:this.headerFormatter.format(n.message.headers),payload:n.message.body},{signingDate:t,signingRegion:i,signingService:r,priorSignature:n.priorSignature,eventStreamCredentials:s}).then((h)=>{return{message:n.message,signature:h}})}async signString(n,{signingDate:t=new Date,signingRegion:i,signingService:r,eventStreamCredentials:s}={}){let f=s??await this.credentialProvider();this.validateResolvedCredentials(f);let h=i??await this.regionProvider(),{shortDate:_}=this.formatDate(t),c=new this.sha256(await this.getSigningKey(f,h,_,r));return c.update(gf(n)),rr(await c.digest())}async signRequest(n,{signingDate:t=new Date,signableHeaders:i,unsignableHeaders:r,signingRegion:s,signingService:f}={}){let h=await this.credentialProvider();this.validateResolvedCredentials(h);let _=s??await this.regionProvider(),c=Xo(n),{longDate:o,shortDate:w}=this.formatDate(t),e=th(w,_,f??this.service);if(c.headers[Vo]=o,h.sessionToken)c.headers[X1]=h.sessionToken;let u=await ih(c,this.sha256);if(!k1(rh,c.headers)&&this.applyChecksum)c.headers[rh]=u;let y=Fo(c,r,i),A=await this.getSignature(o,e,this.getSigningKey(h,_,w,f),this.createCanonicalRequest(c,y,u));return c.headers[Co]=`${p_} Credential=${h.accessKeyId}/${e}, SignedHeaders=${this.getCanonicalHeaderList(y)}, Signature=${A}`,c}async getSignature(n,t,i,r){let s=await this.createStringToSign(n,t,r,p_),f=new this.sha256(await i);return f.update(gf(s)),rr(await f.digest())}getSigningKey(n,t,i,r){return j1(this.sha256,n,i,t,r||this.service)}}var T7={SignatureV4a:null};g7.ALGORITHM_IDENTIFIER=p_;g7.ALGORITHM_IDENTIFIER_V4A=A7;g7.ALGORITHM_QUERY_PARAM=H1;g7.ALWAYS_UNSIGNABLE_HEADERS=l1;g7.AMZ_DATE_HEADER=Vo;g7.AMZ_DATE_QUERY_PARAM=Jo;g7.AUTH_HEADER=Co;g7.CREDENTIAL_QUERY_PARAM=G1;g7.DATE_HEADER=P1;g7.EVENT_ALGORITHM_IDENTIFIER=z1;g7.EXPIRES_QUERY_PARAM=D1;g7.GENERATED_HEADERS=Y1;g7.HOST_HEADER=y7;g7.KEY_TYPE_IDENTIFIER=Ko;g7.MAX_CACHE_SIZE=V1;g7.MAX_PRESIGNED_TTL=K1;g7.PROXY_HEADER_PATTERN=J1;g7.REGION_SET_PARAM=u7;g7.SEC_HEADER_PATTERN=Q1;g7.SHA256_HEADER=rh;g7.SIGNATURE_HEADER=F1;g7.SIGNATURE_QUERY_PARAM=Qo;g7.SIGNED_HEADERS_QUERY_PARAM=W1;g7.SignatureV4=m1;g7.SignatureV4Base=xo;g7.TOKEN_HEADER=X1;g7.TOKEN_QUERY_PARAM=zo;g7.UNSIGNABLE_PATTERNS=d7;g7.UNSIGNED_PAYLOAD=C1;g7.clearCredentialCache=E7;g7.createScope=th;g7.getCanonicalHeaders=Fo;g7.getCanonicalQuery=x1;g7.getPayloadHash=ih;g7.getSigningKey=j1;g7.hasHeader=k1;g7.moveHeadersToQuery=q1;g7.prepareRequest=Xo;g7.signatureV4aContainer=T7});var qo=nn((T9)=>{var{HttpResponse:_9,HttpRequest:sM}=kn(),{normalizeProvider:Sf,memoizeIdentityProvider:h9,isIdentityExpired:c9,doesIdentityRequireRefresh:o9}=Ui(),{ProviderError:a1}=xn(),{setCredentialFeature:w9}=gt(),{SignatureV4:v1}=Z1(),p1=(n)=>_9.isInstance(n)?n.headers?.date??n.headers?.Date:void 0,jo=(n)=>new Date(Date.now()+n),e9=(n,t)=>Math.abs(jo(t).getTime()-n)>=300000,nM=(n,t)=>{let i=Date.parse(n);if(e9(i,t))return i-Date.now();return t},Lf=(n,t)=>{if(!t)throw Error(`Property \`${n}\` is not resolved for AWS SDK SigV4Auth`);return t},ko=async(n)=>{let t=Lf("context",n.context),i=Lf("config",n.config),r=t.endpointV2?.properties?.authSchemes?.[0],f=await Lf("signer",i.signer)(r),h=n?.signingRegion,_=n?.signingRegionSet,c=n?.signingName;return{config:i,signer:f,signingRegion:h,signingRegionSet:_,signingName:c}};class sh{async sign(n,t,i){if(!sM.isInstance(n))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let r=await ko(i),{config:s,signer:f}=r,{signingRegion:h,signingName:_}=r,c=i.context;if(c?.authSchemes?.length??!1){let[w,e]=c.authSchemes;if(w?.name==="sigv4a"&&e?.name==="sigv4")h=e?.signingRegion??h,_=e?.signingName??_}return i._preRequestSystemClockOffset=s.systemClockOffset,await f.sign(n,{signingDate:jo(s.systemClockOffset),signingRegion:h,signingService:_})}errorHandler(n){return(t)=>{let i=t,r=i.ServerTime??p1(i.$response);if(r){let s=Lf("config",n.config),f=n._preRequestSystemClockOffset,h=nM(r,s.systemClockOffset);if((h!==s.systemClockOffset||f!==void 0&&f!==h)&&i.$metadata)s.systemClockOffset=h,i.$metadata.clockSkewCorrected=!0}throw t}}successHandler(n,t){let i=p1(n);if(i){let r=Lf("config",t.config);r.systemClockOffset=nM(i,r.systemClockOffset)}}}var u9=sh;class fM extends sh{async sign(n,t,i){if(!sM.isInstance(n))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let{config:r,signer:s,signingRegion:f,signingRegionSet:h,signingName:_}=await ko(i),o=(await r.sigv4aSigningRegionSet?.()??h??[f]).join(",");return i._preRequestSystemClockOffset=r.systemClockOffset,await s.sign(n,{signingDate:jo(r.systemClockOffset),signingRegion:o,signingService:_})}}var tM=(n)=>typeof n==="string"&&n.length>0?n.split(",").map((t)=>t.trim()):[],_M=(n)=>`AWS_BEARER_TOKEN_${n.replace(/[\s-]/g,"_").toUpperCase()}`,iM="AWS_AUTH_SCHEME_PREFERENCE",rM="auth_scheme_preference",y9={environmentVariableSelector:(n,t)=>{if(t?.signingName){if(_M(t.signingName)in n)return["httpBearerAuth"]}if(!(iM in n))return;return tM(n[iM])},configFileSelector:(n)=>{if(!(rM in n))return;return tM(n[rM])},default:[]},d9=(n)=>{return n.sigv4aSigningRegionSet=Sf(n.sigv4aSigningRegionSet),n},A9={environmentVariableSelector(n){if(n.AWS_SIGV4A_SIGNING_REGION_SET)return n.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((t)=>t.trim());throw new a1("AWS_SIGV4A_SIGNING_REGION_SET not set in env.",{tryNextLink:!0})},configFileSelector(n){if(n.sigv4a_signing_region_set)return(n.sigv4a_signing_region_set??"").split(",").map((t)=>t.trim());throw new a1("sigv4a_signing_region_set not set in profile.",{tryNextLink:!0})},default:void 0},hM=(n)=>{let t=n.credentials,i=!!n.credentials,r=void 0;Object.defineProperty(n,"credentials",{set(o){if(o&&o!==t&&o!==r)i=!0;t=o;let w=M9(n,{credentials:t,credentialDefaultProvider:n.credentialDefaultProvider}),e=E9(n,w);if(i&&!e.attributed){let u=typeof t==="object"&&t!==null;r=async(y)=>{let R=await e(y);if(u&&(!R.$source||Object.keys(R.$source).length===0))return w9(R,"CREDENTIALS_CODE","e");return R},r.memoized=e.memoized,r.configBound=e.configBound,r.attributed=!0}else r=e},get(){return r},enumerable:!0,configurable:!0}),n.credentials=t;let{signingEscapePath:s=!0,systemClockOffset:f=n.systemClockOffset||0,sha256:h}=n,_;if(n.signer)_=Sf(n.signer);else if(n.regionInfoProvider)_=()=>Sf(n.region)().then(async(o)=>[await n.regionInfoProvider(o,{useFipsEndpoint:await n.useFipsEndpoint(),useDualstackEndpoint:await n.useDualstackEndpoint()})||{},o]).then(([o,w])=>{let{signingRegion:e,signingService:u}=o;n.signingRegion=n.signingRegion||e||w,n.signingName=n.signingName||u||n.serviceId;let y={...n,credentials:n.credentials,region:n.signingRegion,service:n.signingName,sha256:h,uriEscapePath:s};return new(n.signerConstructor||v1)(y)});else _=async(o)=>{o=Object.assign({},{name:"sigv4",signingName:n.signingName||n.defaultSigningName,signingRegion:await Sf(n.region)(),properties:{}},o);let{signingRegion:w,signingName:e}=o;n.signingRegion=n.signingRegion||w,n.signingName=n.signingName||e||n.serviceId;let u={...n,credentials:n.credentials,region:n.signingRegion,service:n.signingName,sha256:h,uriEscapePath:s};return new(n.signerConstructor||v1)(u)};return Object.assign(n,{systemClockOffset:f,signingEscapePath:s,signer:_})},R9=hM;function M9(n,{credentials:t,credentialDefaultProvider:i}){let r;if(t)if(!t?.memoized)r=h9(t,c9,o9);else r=t;else if(i)r=Sf(i(Object.assign({},n,{parentClientConfig:n})));else r=async()=>{throw Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")};return r.memoized=!0,r}function E9(n,t){if(t.configBound)return t;let i=async(r)=>t({...r,callerClientConfig:n});return i.memoized=t.memoized,i.configBound=!0,i}T9.AWSSDKSigV4Signer=u9;T9.AwsSdkSigV4ASigner=fM;T9.AwsSdkSigV4Signer=sh;T9.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS=y9;T9.NODE_SIGV4A_CONFIG_OPTIONS=A9;T9.getBearerTokenEnvKey=_M;T9.resolveAWSSDKSigV4Config=R9;T9.resolveAwsSdkSigV4AConfig=d9;T9.resolveAwsSdkSigV4Config=hM;T9.validateSigningProperties=ko});var wh=nn((z9)=>{var{buildQueryString:dM,HttpResponse:AM}=kn(),fh=cn("https"),{Readable:H9}=cn("stream"),mo=cn("http2"),{streamCollector:G9}=jn();z9.streamCollector=G9;function hh(n){let t=n&&typeof n==="object"&&"reason"in n?n.reason:void 0;if(t){if(t instanceof Error){let s=Error("Request aborted");return s.name="AbortError",s.cause=t,s}let r=Error(String(t));return r.name="AbortError",r}let i=Error("Request aborted");return i.name="AbortError",i}var W9=["ECONNRESET","EPIPE","ETIMEDOUT"],RM=(n)=>{let t={};for(let i in n){let r=n[i];t[i]=Array.isArray(r)?r.join(","):r}return t},Xn={setTimeout:(n,t)=>setTimeout(n,t),clearTimeout:(n)=>clearTimeout(n)},oM=1000,D9=(n,t,i=0)=>{if(!i)return-1;let r=(s)=>{let f=Xn.setTimeout(()=>{n.destroy(),t(Object.assign(Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${i} ms.`),{name:"TimeoutError"}))},i-s),h=(_)=>{if(_?.connecting)_.on("connect",()=>{Xn.clearTimeout(f)});else Xn.clearTimeout(f)};if(n.socket)h(n.socket);else n.on("socket",h)};if(i<2000)return r(0),0;return Xn.setTimeout(r.bind(null,oM),oM)},P9=(n,t,i=0,r,s)=>{if(i)return Xn.setTimeout(()=>{let f=`@smithy/node-http-handler - [${r?"ERROR":"WARN"}] a request has exceeded the configured ${i} ms requestTimeout.`;if(r){let h=Object.assign(Error(f),{name:"TimeoutError",code:"ETIMEDOUT"});n.destroy(h),t(h)}else f+=" Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.",s?.warn?.(f)},i);return-1},Y9=3000,F9=(n,{keepAlive:t,keepAliveMsecs:i},r=Y9)=>{if(t!==!0)return-1;let s=()=>{if(n.socket)n.socket.setKeepAlive(t,i||0);else n.on("socket",(f)=>{f.setKeepAlive(t,i||0)})};if(r===0)return s(),0;return Xn.setTimeout(s,r)},wM=3000,X9=(n,t,i=0)=>{let r=(s)=>{let f=i-s,h=()=>{n.destroy(),t(Object.assign(Error(`@smithy/node-http-handler - the request socket timed out after ${i} ms of inactivity (configured by client requestHandler).`),{name:"TimeoutError"}))};if(n.socket)n.socket.setTimeout(f,h),n.on("close",()=>n.socket?.removeListener("timeout",h));else n.setTimeout(f,h)};if(0<i&&i<6000)return r(0),0;return Xn.setTimeout(r.bind(null,i===0?0:wM),wM)},eM=6000;async function MM(n,t,i=eM,r=!1){let s=t.headers,f=s?s.Expect||s.expect:void 0,h=-1,_=!0;if(!r&&f==="100-continue")_=await Promise.race([new Promise((c)=>{h=Number(Xn.setTimeout(()=>c(!0),Math.max(eM,i)))}),new Promise((c)=>{n.on("continue",()=>{Xn.clearTimeout(h),c(!0)}),n.on("response",()=>{Xn.clearTimeout(h),c(!1)}),n.on("error",()=>{Xn.clearTimeout(h),c(!1)})})]);if(_)l9(n,t.body)}function l9(n,t){if(t instanceof H9){t.pipe(n);return}if(t){let i=Buffer.isBuffer(t);if(i||typeof t==="string"){if(i&&t.byteLength===0)n.end();else n.end(t);return}let s=t;if(typeof s==="object"&&s.buffer&&typeof s.byteOffset==="number"&&typeof s.byteLength==="number"){n.end(Buffer.from(s.buffer,s.byteOffset,s.byteLength));return}n.end(Buffer.from(t));return}n.end()}var J9=0,_h=void 0,uM=void 0;class ch{config;configProvider;socketWarningTimestamp=0;externalAgent=!1;metadata={handlerProtocol:"http/1.1"};static create(n){if(typeof n?.handle==="function")return n;return new ch(n)}static checkSocketUsage(n,t,i=console){let{sockets:r,requests:s,maxSockets:f}=n;if(typeof f!=="number"||f===1/0)return t;let h=15000;if(Date.now()-h<t)return t;if(r&&s)for(let _ in r){let c=r[_]?.length??0,o=s[_]?.length??0;if(c>=f&&o>=2*f)return i?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${c} and ${o} additional requests are enqueued.
|
|
43
43
|
See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html
|
|
44
|
-
or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`),Date.now()}return t}constructor(n){this.configProvider=new Promise((t,i)=>{if(typeof n==="function")n().then((s)=>{t(this.resolveDefaultConfig(s))}).catch(i);else t(this.resolveDefaultConfig(n))})}destroy(){this.config?.httpAgent?.destroy(),this.config?.httpsAgent?.destroy()}async handle(n,{abortSignal:t,requestTimeout:i}={}){if(!this.config)this.config=await this.configProvider;let s=this.config,r=n.protocol==="https:";if(!r&&!this.config.httpAgent)this.config.httpAgent=await this.config.httpAgentProvider();return new Promise((e,f)=>{let o=void 0,h=-1,u=-1,c=-1,_=-1,w=-1,l=()=>{Bn.clearTimeout(h),Bn.clearTimeout(u),Bn.clearTimeout(c),Bn.clearTimeout(_),Bn.clearTimeout(w)},A=async(B)=>{await o,l(),e(B)},d=async(B)=>{await o,l(),f(B)};if(t?.aborted){let B=ko(t);d(B);return}let E=n.headers,R=E?(E.Expect??E.expect)==="100-continue":!1,y=r?s.httpsAgent:s.httpAgent;if(R&&!this.externalAgent)y=new(r?xo.Agent:Ko)({keepAlive:!1,maxSockets:1/0});h=Bn.setTimeout(()=>{this.socketWarningTimestamp=qo.checkSocketUsage(y,this.socketWarningTimestamp,s.logger)},s.socketAcquisitionWarningTimeout??(s.requestTimeout??2000)+(s.connectionTimeout??1000));let T=n.query?N1(n.query):"",S=void 0;if(n.username!=null||n.password!=null){let B=n.username??"",g=n.password??"";S=`${B}:${g}`}let I=n.path;if(T)I+=`?${T}`;if(n.fragment)I+=`#${n.fragment}`;let F=n.hostname??"";if(F[0]==="["&&F.endsWith("]"))F=n.hostname.slice(1,-1);else F=n.hostname;let C={headers:n.headers,host:F,method:n.method,path:I,port:n.port,agent:y,auth:S},b=(r?xo.request:O1)(C,(B)=>{let g=new G1({statusCode:B.statusCode||-1,reason:B.statusMessage,headers:H1(B.headers),body:B});A({response:g})});if(b.on("error",(B)=>{if(EF.includes(B.code))d(Object.assign(B,{name:"TimeoutError"}));else d(B)}),t){let B=()=>{b.destroy();let g=ko(t);d(g)};if(typeof t.addEventListener==="function"){let g=t;g.addEventListener("abort",B,{once:!0}),b.once("close",()=>g.removeEventListener("abort",B))}else t.onabort=B}let $=i??s.requestTimeout;u=yF(b,d,s.connectionTimeout),c=TF(b,d,$,s.throwOnRequestTimeout,s.logger??console),_=IF(b,d,s.socketTimeout);let N=C.agent;if(typeof N==="object"&&"keepAlive"in N)w=SF(b,{keepAlive:N.keepAlive,keepAliveMsecs:N.keepAliveMsecs});o=W1(b,n,$,this.externalAgent).catch((B)=>{return l(),f(B)})})}updateHttpClientConfig(n,t){this.config=void 0,this.configProvider=this.configProvider.then((i)=>{return{...i,[n]:t}})}httpHandlerConfigs(){return this.config??{}}resolveDefaultConfig(n){let{requestTimeout:t,connectionTimeout:i,socketTimeout:s,socketAcquisitionWarningTimeout:r,httpAgent:e,httpsAgent:f,throwOnRequestTimeout:o,logger:h}=n||{},u=!0,c=50;return{connectionTimeout:i,requestTimeout:t,socketTimeout:s,socketAcquisitionWarningTimeout:r,throwOnRequestTimeout:o,httpAgentProvider:async()=>{let _=p("http"),{Agent:w,request:l}=_.default??_;if(O1=l,Ko=w,e instanceof Ko||typeof e?.destroy==="function")return this.externalAgent=!0,e;return new Ko({keepAlive:!0,maxSockets:50,...e})},httpsAgent:(()=>{if(f instanceof xo.Agent||typeof f?.destroy==="function")return this.externalAgent=!0,f;return new xo.Agent({keepAlive:!0,maxSockets:50,...f})})(),logger:h}}}var $F=new Uint16Array(1);class Vo{id=$F[0]++;total=0;max=0;session;refs=0;constructor(n){n.unref(),this.session=n}retain(){if(this.session.destroyed)throw Error("@smithy/node-http-handler - cannot acquire reference to destroyed session.");this.refs+=1,this.total+=1,this.max=Math.max(this.refs,this.max),this.session.ref()}free(){if(this.session.destroyed)return;if(this.refs-=1,this.refs===0)this.session.unref();if(this.refs<0)throw Error("@smithy/node-http-handler - ClientHttp2Session refcount at zero, cannot decrement.")}deref(){return this.session}close(){if(!this.session.closed)this.session.close()}destroy(){if(this.refs=0,!this.session.destroyed)this.session.destroy()}useCount(){return this.refs}}class F1{sessions=[];maxConcurrency=0;constructor(n){this.sessions=(n??[]).map((t)=>new Vo(t))}poll(){let n=!1;for(let t of this.sessions){if(t.deref().destroyed){n=!0;continue}if(!this.maxConcurrency||t.useCount()<this.maxConcurrency)return t}if(n){for(let t of this.sessions)if(t.deref().destroyed)this.remove(t)}}offerLast(n){this.sessions.push(n)}remove(n){let t=this.sessions.indexOf(n);if(t>-1)this.sessions.splice(t,1)}[Symbol.iterator](){return this.sessions[Symbol.iterator]()}setMaxConcurrency(n){this.maxConcurrency=n}destroy(n){this.remove(n),n.destroy()}}class P1{config;connectOptions;connectionPools=new Map;constructor(n){if(this.config=n,this.config.maxConcurrency&&this.config.maxConcurrency<=0)throw RangeError("maxConcurrency must be greater than zero.")}lease(n,t){let i=this.getUrlString(n),s=this.getPool(i);if(!this.config.disableConcurrency&&!t.isEventStream){let h=s.poll();if(h)return h.retain(),h}let r=new Vo(this.connect(i)),e=r.deref();if(this.config.maxConcurrency)e.settings({maxConcurrentStreams:this.config.maxConcurrency},(h)=>{if(h)throw Error("Fail to set maxConcurrentStreams to "+this.config.maxConcurrency+"when creating new session for "+n.destination.toString())});let f=()=>{this.removeFromPoolAndClose(i,r)},o=()=>{this.removeFromPoolAndCheckedDestroy(i,r)};if(e.on("goaway",f),e.on("error",o),e.on("frameError",o),e.on("close",o),t.requestTimeout)e.setTimeout(t.requestTimeout,o);return s.offerLast(r),r.retain(),r}release(n,t){t.free()}createIsolatedSession(n,t){let i=this.getUrlString(n),s=new Vo(this.connect(i)),r=s.deref();r.settings({maxConcurrentStreams:1});let e=()=>{s.destroy()};if(r.on("error",e),r.on("frameError",e),r.on("close",e),t.requestTimeout)r.setTimeout(t.requestTimeout,e);return s.retain(),s}destroy(){for(let[n,t]of this.connectionPools){for(let i of[...t])i.destroy();this.connectionPools.delete(n)}}setMaxConcurrentStreams(n){if(n&&n<=0)throw RangeError("maxConcurrentStreams must be greater than zero.");this.config.maxConcurrency=n;for(let t of this.connectionPools.values())t.setMaxConcurrency(n)}setDisableConcurrentStreams(n){this.config.disableConcurrency=n}setNodeHttp2ConnectOptions(n){this.connectOptions=n}debug(){let n={};for(let[t,i]of this.connectionPools){let s=[];for(let r of i)s.push({id:r.id,active:r.useCount(),maxConcurrent:r.max,totalRequests:r.total});n[t]={sessions:s}}return n}removeFromPoolAndClose(n,t){this.connectionPools.get(n)?.remove(t),t.close()}removeFromPoolAndCheckedDestroy(n,t){this.connectionPools.get(n)?.remove(t),t.destroy()}getPool(n){if(!this.connectionPools.has(n)){let t=new F1;if(this.config.maxConcurrency)t.setMaxConcurrency(this.config.maxConcurrency);this.connectionPools.set(n,t)}return this.connectionPools.get(n)}getUrlString(n){return n.destination.toString()}connect(n){return this.connectOptions===void 0?Bc.connect(n):Bc.connect(n,this.connectOptions)}}var{constants:B1}=Bc;class Nc{config;configProvider;metadata={handlerProtocol:"h2"};connectionManager=new P1({});static create(n){if(typeof n?.handle==="function")return n;return new Nc(n)}constructor(n){this.configProvider=new Promise((t,i)=>{if(typeof n==="function")n().then((s)=>{t(s||{})}).catch(i);else t(n||{})})}destroy(){this.connectionManager.destroy()}async handle(n,{abortSignal:t,requestTimeout:i,isEventStream:s}={}){if(!this.config){this.config=await this.configProvider;let{disableConcurrentStreams:h,maxConcurrentStreams:u,nodeHttp2ConnectOptions:c}=this.config;if(this.connectionManager.setDisableConcurrentStreams(h??!1),u)this.connectionManager.setMaxConcurrentStreams(u);if(c)this.connectionManager.setNodeHttp2ConnectOptions(c)}let{requestTimeout:r,disableConcurrentStreams:e}=this.config,f=e||s,o=i??r;return new Promise((h,u)=>{let c=!1,_=void 0,w=async(g)=>{await _,h(g)},l=async(g)=>{await _,u(g)};if(t?.aborted){c=!0;let g=ko(t);l(g);return}let{hostname:A,method:d,port:E,protocol:R,query:y}=n,T="";if(n.username!=null||n.password!=null){let g=n.username??"",X=n.password??"";T=`${g}:${X}@`}let S=`${R}//${T}${A}${E?`:${E}`:""}`,I={destination:new URL(S)},F={requestTimeout:this.config?.sessionTimeout,isEventStream:s},C=f?this.connectionManager.createIsolatedSession(I,F):this.connectionManager.lease(I,F),sn=C.deref(),b=(g)=>{if(f)C.destroy();c=!0,l(g)},$=y?N1(y):"",N=n.path;if($)N+=`?${$}`;if(n.fragment)N+=`#${n.fragment}`;let B=sn.request({...n.headers,[B1.HTTP2_HEADER_PATH]:N,[B1.HTTP2_HEADER_METHOD]:d});if(o)B.setTimeout(o,()=>{B.close();let g=Error(`Stream timed out because of no activity for ${o} ms`);g.name="TimeoutError",b(g)});if(t){let g=()=>{B.close();let X=ko(t);b(X)};if(typeof t.addEventListener==="function"){let X=t;X.addEventListener("abort",g,{once:!0}),B.once("close",()=>X.removeEventListener("abort",g))}else t.onabort=g}B.on("frameError",(g,X,Z)=>{b(Error(`Frame type id ${g} in stream id ${Z} has failed with code ${X}.`))}),B.on("error",b),B.on("aborted",()=>{b(Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${B.rstCode}.`))}),B.on("response",(g)=>{let X=new G1({statusCode:g[":status"]??-1,headers:H1(g),body:B});if(c=!0,w({response:X}),f)sn.close()}),B.on("close",()=>{if(f)C.destroy();else this.connectionManager.release(I,C);if(!c)b(Error("Unexpected error: http2 request did not get a response"))}),_=W1(B,n,o)})}updateHttpClientConfig(n,t){this.config=void 0,this.configProvider=this.configProvider.then((i)=>{return{...i,[n]:t}})}httpHandlerConfigs(){return this.config??{}}}LF.DEFAULT_REQUEST_TIMEOUT=bF;LF.NodeHttp2Handler=Nc;LF.NodeHttpHandler=qo});var q1=k((cP)=>{var{nv:HF,NumericValue:X1,calculateBodyLength:WF,_parseEpochTimestamp:D1,fromBase64:z1,generateIdempotencyToken:FF}=mn(),{HttpRequest:PF,collectBody:DF,SerdeContext:Dc,RpcProtocol:YF}=Jn(),{NormalizedSchema:Yc,deref:mF,TypeRegistry:Y1}=ri(),{getSmithyContext:JF}=St();function qs(n){return typeof Buffer<"u"?Buffer.alloc(n):new Uint8Array(n)}var mc=Symbol("@smithy/core/cbor::tagSymbol");function Jc(n){return n[mc]=!0,n}var Q1=typeof Buffer<"u",Xc=new TextDecoder,a=qs(0),zc=!1,_t=new DataView(a.buffer,a.byteOffset,a.byteLength),x=0;function XF(n){a=n,zc=Q1&&a instanceof Buffer,_t=new DataView(a.buffer,a.byteOffset,a.byteLength)}function li(n,t){if(n>=t)throw Error("unexpected end of (decode) payload.");let i=(a[n]&224)>>5,s=a[n]&31;if(s===31&&2<=i&&i<=5)return zF(n,t);switch(i){case 0:case 1:case 6:{let r,e;if(s<24)r=s,e=1;else switch(s){case 24:if(t-n<2)Ot(1);r=a[n+1],e=2;break;case 25:if(t-n<3)Ot(2);r=_t.getUint16(n+1),e=3;break;case 26:if(t-n<5)Ot(4);r=_t.getUint32(n+1),e=5;break;case 27:if(t-n<9)Ot(8);{let f=_t.getUint32(n+1);if(f<2097152)r=f*4294967296+_t.getUint32(n+5);else r=_t.getBigUint64(n+1)}e=9;break;default:Cc(s)}if(i===0)return x=e,Wc(r);else if(i===1){let f;if(typeof r==="bigint")f=BigInt(-1)-r;else f=-1-r;return x=e,Wc(f)}else return jF(n,t,s,r,e)}case 3:return he(n,t);case 5:return CF(n,t);case 4:return kF(n,t);case 2:return Qc(n,t);default:return aF(n,t)}}function zF(n,t){let i=(a[n]&224)>>5;if((a[n]&31)===31)switch(i){case 3:return pF(n,t);case 5:return vF(n,t);case 4:return ZF(n,t);case 2:return nP(n,t)}}function QF(n,t){let i=n>>7,s=(n&124)>>2,r=(n&3)<<8|t,e=i===0?1:-1;if(s===0){if(r===0)return 0;return e*(Math.pow(2,-14)*(r/1024))}else if(s===31){if(r===0)return e*(1/0);return NaN}return e*(Math.pow(2,s-15)*(1+r/1024))}function CF(n,t){let i=ue(n,t);if(i<15)return KF(n,t,i);return xF(n,t,i)}function xF(n,t,i){let s=x;n+=s;let r=n,e=Object.create(null);for(let f=0;f<i;++f){let o=he(n,t);if(n+=x,(a[n]&224)>>5===3)e[o]=he(n,t);else e[o]=li(n,t);n+=x}return x=s+(n-r),Object.setPrototypeOf(e,Object.prototype),e}function KF(n,t,i){let s=x;n+=s;let r=n,e={};for(let f=0;f<i;++f){let o=he(n,t);n+=x,e[o]=li(n,t),n+=x}return x=s+(n-r),e}function kF(n,t){let i=ue(n,t),s=x;n+=s;let r=n,e=Array(i);for(let f=0;f<i;++f)e[f]=li(n,t),n+=x;return x=s+(n-r),e}function he(n,t){let i=ue(n,t),s=x;if(n+=s,t-n<i)Ot(i);if(x=s+i,i<24)return VF(n,i);if(zc)return a.toString("utf-8",n,n+i);return Xc.decode(a.subarray(n,n+i))}var m1=Array(2048),Gc=new Uint16Array(2048),oe=0;function qF(){oe=oe+1&65535}function VF(n,t){let i=t;for(let f=0;f<t;++f)i=i*31+a[n+f]|0;let s=i>>>0&2047,r=m1[s];if(r!==void 0){if(r.length===t){let f=!0;for(let o=0;o<t;++o)if(r.charCodeAt(o)!==a[n+o]){f=!1;break}if(f)return Gc[s]=oe,r}}let e=zc?a.toString("utf-8",n,n+t):Xc.decode(a.subarray(n,n+t));if(Gc[s]!==oe)m1[s]=e,Gc[s]=oe;return e}function Qc(n,t){let i=ue(n,t),s=x;if(n+=s,t-n<i)Ot(i);let r=a.subarray(n,n+i);return x=s+i,r}function jF(n,t,i,s,r){if(i===2||i===3){let e=ue(n+r,t),f=BigInt(0),o=n+r+x;for(let h=o;h<o+e;++h)f=f<<BigInt(8)|BigInt(a[h]);return x=r+x+e,i===3?-f-BigInt(1):f}else if(i===4){let e=li(n+r,t),[f,o]=e,h=o<0?-1:1,u="0".repeat(Math.abs(f)+1)+String(BigInt(h)*BigInt(o)),c,_=o<0?"-":"";if(c=f===0?u:u.slice(0,u.length+f)+"."+u.slice(f),c=c.replace(/^0+/g,""),c==="")c="0";if(c[0]===".")c="0"+c;return c=_+c,x=r+x,HF(c)}else{let e=li(n+r,t);return x=r+x,Jc({tag:Wc(s),value:e})}}function aF(n,t){let i=a[n]&31;switch(i){case 21:case 20:return x=1,i===21;case 22:return x=1,null;case 23:return x=1,null;case 25:if(t-n<3)throw Error("incomplete float16 at end of buf.");return x=3,QF(a[n+1],a[n+2]);case 26:if(t-n<5)throw Error("incomplete float32 at end of buf.");return x=5,_t.getFloat32(n+1);case 27:if(t-n<9)throw Error("incomplete float64 at end of buf.");return x=9,_t.getFloat64(n+1);default:Cc(i)}}function ue(n,t){let i=a[n]&31;if(i<24)return x=1,i;switch(i){case 24:if(t-n<2)Ot(1);return x=2,a[n+1];case 25:if(t-n<3)Ot(2);return x=3,_t.getUint16(n+1);case 26:if(t-n<5)Ot(4);return x=5,_t.getUint32(n+1);case 27:if(t-n<9)Ot(8);return x=9,tP(_t.getBigUint64(n+1));default:Cc(i)}}function vF(n,t){n+=1;let i=n,s={};for(;n<t;){if(a[n]===255)return x=n-i+2,s;let r=he(n,t);n+=x,s[r]=li(n,t),n+=x}throw Error("expected break marker.")}function ZF(n,t){n+=1;let i=[];for(let s=n;n<t;){if(a[n]===255)return x=n-s+2,i;i.push(li(n,t)),n+=x}throw Error("expected break marker.")}function pF(n,t){n+=1;let i=[];for(let s=n;n<t;){if(a[n]===255){let h=qs(i.length);if(h.set(i,0),x=n-s+2,Q1)return h.toString("utf-8",0,h.length);return Xc.decode(h)}let r=(a[n]&224)>>5,e=a[n]&31;if(r!==3)C1(r);if(e===31)throw Error("nested indefinite string.");let f=Qc(n,t);n+=x;for(let h=0;h<f.length;++h)i.push(f[h])}throw Error("expected break marker.")}function nP(n,t){n+=1;let i=[];for(let s=n;n<t;){if(a[n]===255){let h=qs(i.length);return h.set(i,0),x=n-s+2,h}let r=(a[n]&224)>>5,e=a[n]&31;if(r!==2)C1(r);if(e===31)throw Error("nested indefinite string.");let f=Qc(n,t);n+=x;for(let h=0;h<f.length;++h)i.push(f[h])}throw Error("expected break marker.")}function Wc(n){if(typeof n==="number")return n;let t=Number(n);if(Number.MIN_SAFE_INTEGER<=t&&t<=Number.MAX_SAFE_INTEGER)return t;return n}function tP(n){let t=Number(n);if(t<Number.MIN_SAFE_INTEGER||Number.MAX_SAFE_INTEGER<t)console.warn(Error(`@smithy/core/cbor - truncating BigInt(${n}) to ${t} with loss of precision.`));return t}function Ot(n){throw Error(`length ${n} greater than remaining buf len.`)}function Cc(n){throw Error(`unexpected minor value ${n}.`)}function C1(n){throw Error(`unexpected major type ${n} in indefinite string.`)}var iP=typeof Buffer<"u",Ks=new Map,fe=0,Fc=!1,sP=2048,m=qs(sP),nt=new DataView(m.buffer,m.byteOffset,m.byteLength),G=0;function rP(n){let t=[n];while(t.length){let i=t.pop();if(typeof i==="string"){let s=i.length;if(iP)if(ks(s*3+9),s>23)Hc(3,Buffer.byteLength(i)),G+=m.write(i,G);else oP(i);else{let r=s*3;ks(r+9);let e=G,o=new TextEncoder().encodeInto(i,m.subarray(G+9)).written,h;if(o<24)h=1;else if(o<256)h=2;else if(o<65536)h=3;else if(o<4294967296)h=5;else h=9;if(h<9)m.copyWithin(e+h,e+9,e+9+o);G=e,Ki(3,o),G+=o}continue}if(m.byteLength-G<9)ks(64);if(typeof i==="number"){if(Number.isInteger(i)){let s=i>=0,r=s?0:1,e=s?i:-i-1;if(e<24)m[G++]=r<<5|e;else if(e<256)m[G++]=r<<5|24,m[G++]=e;else if(e<65536)m[G++]=r<<5|25,m[G++]=e>>8,m[G++]=e&255;else if(e<4294967296)m[G++]=r<<5|26,nt.setUint32(G,e),G+=4;else{m[G++]=r<<5|27;let f=e/4294967296|0,o=e-f*4294967296|0;nt.setUint32(G,f),nt.setUint32(G+4,o),G+=8}continue}m[G++]=251,nt.setFloat64(G,i),G+=8;continue}else if(typeof i==="bigint"){let s=i>=0,r=s?0:1,e=s?i:-i-BigInt(1);if(e<BigInt("18446744073709551616")){let f=Number(e);if(f<4294967296)Ki(r,f);else m[G++]=r<<5|27,nt.setBigUint64(G,e),G+=8}else{let f=e.toString(2),o=new Uint8Array(Math.ceil(f.length/8)),h=e,u=0;while(o.byteLength-++u>=0)o[o.byteLength-u]=Number(h&BigInt(255)),h>>=BigInt(8);ks(o.byteLength*2+16),m[G++]=s?194:195,Hc(2,o.byteLength),m.set(o,G),G+=o.byteLength}continue}else if(i===null){m[G++]=246;continue}else if(typeof i==="boolean"){m[G++]=224|(i?21:20);continue}else if(typeof i>"u")throw Error("@smithy/core/cbor: client may not serialize undefined value.");else if(Array.isArray(i)){Ki(4,i.length),ks(i.length*9+64);for(let s=i.length-1;s>=0;--s)t.push(i[s]);continue}else if(typeof i.byteLength==="number"){ks(i.length*2+9),Ki(2,i.length),m.set(i,G),G+=i.byteLength;continue}else if(typeof i==="object"){if(i instanceof X1){let e=i.string.indexOf("."),f=e===-1?0:e-i.string.length+1,o=BigInt(i.string.replace(".",""));m[G++]=196,Ki(4,2),t.push(o),t.push(f);continue}if(i[mc])if("tag"in i&&"value"in i){t.push(i.value),Hc(6,i.tag);continue}else throw Error("tag encountered with missing fields, need 'tag' and 'value', found: "+JSON.stringify(i));let s=Object.keys(i),r=s.length;Ki(5,r);for(let e=r-1;e>=0;--e)t.push(i[s[e]]),t.push(s[e]);continue}throw Error(`data type ${i?.constructor?.name??typeof i} not compatible for encoding.`)}}function eP(){fe=fe+1&65535,Fc=!1}function J1(){let n=qs(G);return n.set(m.subarray(0,G),0),G=0,n}function Pc(n){let t=m;if(m=qs(n),t)if(t.copy)t.copy(m,0,0,t.byteLength);else m.set(t,0);nt=new DataView(m.buffer,m.byteOffset,m.byteLength)}function oP(n){let t=Ks.get(n);if(t!==void 0){m.set(t.bytes,G),G+=t.bytes.length,t.epoch=fe;return}let i=G,s=Buffer.byteLength(n);Ki(3,s),G+=m.write(n,G);let r=Uint8Array.prototype.slice.call(m,i,G);if(Ks.size>=2048){if(Fc)return;let e=0;for(let[f,o]of Ks){if(e>=1024)break;if(o.epoch!==fe)Ks.delete(f),e++}if(e===0){Fc=!0;return}}if(Ks.size<2048)Ks.set(n,{epoch:fe,bytes:r})}function ks(n){if(m.byteLength-G<n)if(G<16000000)Pc(Math.max(m.byteLength*4,m.byteLength+n));else Pc(m.byteLength+n+16000000)}function Hc(n,t){if(t<24)m[G++]=n<<5|t;else if(t<256)m[G++]=n<<5|24,m[G++]=t;else if(t<65536)m[G++]=n<<5|25,nt.setUint16(G,t),G+=2;else if(t<4294967296)m[G++]=n<<5|26,nt.setUint32(G,t),G+=4;else m[G++]=n<<5|27,nt.setBigUint64(G,typeof t==="bigint"?t:BigInt(t)),G+=8}function Ki(n,t){if(t<24)m[G++]=n<<5|t;else if(t<256)m[G++]=n<<5|24,m[G++]=t;else if(t<65536)m[G++]=n<<5|25,m[G++]=t>>8,m[G++]=t&255;else if(t<4294967296)m[G++]=n<<5|26,nt.setUint32(G,t),G+=4;else{m[G++]=n<<5|27;let i=t/4294967296|0,s=t-i*4294967296|0;nt.setUint32(G,i),nt.setUint32(G+4,s),G+=8}}var vo={deserialize(n){return qF(),XF(n),li(0,n.length)},serialize(n){eP();try{return rP(n),J1()}catch(t){throw J1(),t}},resizeEncodingBuffer(n){Pc(n)}},x1=(n,t)=>{return DF(n,t).then(async(i)=>{if(i.length)try{return vo.deserialize(i)}catch(s){throw Object.defineProperty(s,"$responseBodyText",{value:t.utf8Encoder(i)}),s}return{}})},ao=(n)=>{return Jc({tag:1,value:n.getTime()/1000})},fP=async(n,t)=>{let i=await x1(n,t);return i.message=i.message??i.Message,i},K1=(n,t)=>{let i=(r)=>{let e=r;if(typeof e==="number")e=e.toString();if(e.indexOf(",")>=0)e=e.split(",")[0];if(e.indexOf(":")>=0)e=e.split(":")[0];if(e.indexOf("#")>=0)e=e.split("#")[1];return e};if(t.__type!==void 0)return i(t.__type);let s;for(let r in t)if(r.toLowerCase()==="code"){s=r;break}if(s&&t[s]!==void 0)return i(t[s])},hP=(n)=>{if(String(n.headers["smithy-protocol"]).toLowerCase()!=="rpc-v2-cbor")throw Error("Malformed RPCv2 CBOR response, status: "+n.statusCode)},uP=async(n,t,i,s,r)=>{let e=await n.endpoint(),{hostname:f,protocol:o="https",port:h,path:u}=e,c={protocol:o,hostname:f,port:h,method:"POST",path:u.endsWith("/")?u.slice(0,-1)+i:u+i,headers:{...t}};if(s!==void 0)c.hostname=s;if(e.headers)for(let _ in e.headers)c.headers[_]=e.headers[_];if(r!==void 0){c.body=r;try{c.headers["content-length"]=String(WF(r))}catch(_){}}return new PF(c)};class xc extends Dc{createSerializer(){let n=new Kc;return n.setSerdeContext(this.serdeContext),n}createDeserializer(){let n=new kc;return n.setSerdeContext(this.serdeContext),n}}class Kc extends Dc{value;write(n,t){this.value=this.serialize(n,t)}serialize(n,t){let i=Yc.of(n);if(t==null){if(i.isIdempotencyToken())return FF();return t}if(i.isBlobSchema()){if(typeof t==="string")return(this.serdeContext?.base64Decoder??z1)(t);return t}if(i.isTimestampSchema()){if(typeof t==="number"||typeof t==="bigint")return ao(new Date(Number(t)/1000|0));return ao(t)}if(typeof t==="function"||typeof t==="object"){let s=t;if(i.isListSchema()&&Array.isArray(s)){let e=!!i.getMergedTraits().sparse,f=[],o=0;for(let h of s){let u=this.serialize(i.getValueSchema(),h);if(u!=null||e)f[o++]=u}return f}if(s instanceof Date)return ao(s);let r={};if(i.isMapSchema()){let e=!!i.getMergedTraits().sparse;for(let f in s){let o=this.serialize(i.getValueSchema(),s[f]);if(o!=null||e)r[f]=o}}else if(i.isStructSchema()){for(let[f,o]of i.structIterator()){let h=this.serialize(o,s[f]);if(h!=null)r[f]=h}if(i.isUnionSchema()&&Array.isArray(s.$unknown)){let[f,o]=s.$unknown;r[f]=o}else if(typeof s.__type==="string"){for(let f in s)if(!(f in r))r[f]=this.serialize(15,s[f])}}else if(i.isDocumentSchema())for(let e in s)r[e]=this.serialize(i.getValueSchema(),s[e]);else if(i.isBigDecimalSchema())return s;return r}return t}flush(){let n=vo.serialize(this.value);return this.value=void 0,n}}class kc extends Dc{read(n,t){let i=vo.deserialize(t);return this.readValue(n,i)}readValue(n,t){let i=Yc.of(n);if(i.isTimestampSchema()){if(typeof t==="number")return D1(t);if(typeof t==="object"){if(t.tag===1&&"value"in t)return D1(t.value)}}if(i.isBlobSchema()){if(typeof t==="string")return(this.serdeContext?.base64Decoder??z1)(t);return t}if(typeof t>"u"||typeof t==="boolean"||typeof t==="number"||typeof t==="string"||typeof t==="bigint"||typeof t==="symbol")return t;else if(typeof t==="object"){if(t===null)return null;if("byteLength"in t)return t;if(t instanceof Date)return t;if(i.isDocumentSchema())return t;if(i.isListSchema()){let r=[],e=i.getValueSchema();for(let f of t){let o=this.readValue(e,f);r.push(o)}return r}let s={};if(i.isMapSchema()){let r=i.getValueSchema();for(let e in t){let f=this.readValue(r,t[e]);s[e]=f}}else if(i.isStructSchema()){let r=i.isUnionSchema(),e;if(r){e=new Set;for(let f in t)if(f!=="__type")e.add(f)}for(let[f,o]of i.structIterator()){if(r)e.delete(f);if(t[f]!=null)s[f]=this.readValue(o,t[f])}if(r&&e?.size===1){let f=!0;for(let o in s){f=!1;break}if(f){let o=e.values().next().value;s.$unknown=[o,t[o]]}}else if(typeof t.__type==="string"){for(let f in t)if(!(f in s))s[f]=t[f]}}else if(t instanceof X1)return t;return s}else return t}}class k1 extends YF{codec=new xc;serializer=this.codec.createSerializer();deserializer=this.codec.createDeserializer();constructor({defaultNamespace:n,errorTypeRegistries:t}){super({defaultNamespace:n,errorTypeRegistries:t})}getShapeId(){return"smithy.protocols#rpcv2Cbor"}getPayloadCodec(){return this.codec}async serializeRequest(n,t,i){let s=await super.serializeRequest(n,t,i);if(Object.assign(s.headers,{"content-type":this.getDefaultContentType(),"smithy-protocol":"rpc-v2-cbor",accept:this.getDefaultContentType()}),mF(n.input)==="unit")delete s.body,delete s.headers["content-type"];else{if(!s.body)this.serializer.write(15,{}),s.body=this.serializer.flush();try{s.headers["content-length"]=String(s.body.byteLength)}catch(o){}}let{service:r,operation:e}=JF(i),f=`/service/${r}/operation/${e}`;if(s.path.endsWith("/"))s.path+=f.slice(1);else s.path+=f;return s}async deserializeResponse(n,t,i){return super.deserializeResponse(n,t,i)}async handleError(n,t,i,s,r){let e=K1(i,s)??"Unknown",f={$metadata:r,$fault:i.statusCode<=500?"client":"server"},o=this.options.defaultNamespace;if(e.includes("#"))[o]=e.split("#");let h=this.compositeErrorRegistry,u=Y1.for(o);h.copyFrom(u);let c;try{c=h.getSchema(e)}catch(E){if(s.Message)s.message=s.Message;let R=Y1.for("smithy.ts.sdk.synthetic."+o);h.copyFrom(R);let y=h.getBaseException();if(y){let T=h.getErrorCtor(y);throw Object.assign(new T({name:e}),f,s)}throw Object.assign(Error(e),f,s)}let _=Yc.of(c),w=h.getErrorCtor(c),l=s.message??s.Message??"Unknown",A=new w({}),d={};for(let[E,R]of _.structIterator())d[E]=this.deserializer.readValue(R,s[E]);throw Object.assign(A,f,{$fault:_.getMergedTraits().error,message:l},d)}getDefaultContentType(){return"application/cbor"}}cP.CborCodec=xc;cP.CborShapeDeserializer=kc;cP.CborShapeSerializer=Kc;cP.SmithyRpcV2CborProtocol=k1;cP.buildHttpRpcRequest=uP;cP.cbor=vo;cP.checkCborResponse=hP;cP.dateToTag=ao;cP.loadSmithyRpcV2CborErrorCode=K1;cP.parseCborBody=x1;cP.parseCborErrorBody=fP;cP.tag=Jc;cP.tagSymbol=mc});var V1=k((GP)=>{var UP=/[&<>"]/g,bP={"&":"&","<":"<",">":">",'"':"""};function $P(n){return n.replace(UP,(t)=>bP[t])}var LP=/[&"'<>\r\n\u0085\u2028]/g,OP={"&":"&",'"':""","'":"'","<":"<",">":">","\r":"
","\n":"
","\x85":"…","\u2028":"
"};function BP(n){return n.replace(LP,(t)=>OP[t])}class qc{value;constructor(n){this.value=n}toString(){return BP(""+this.value)}}class ce{name;children;attributes={};static of(n,t,i){let s=new ce(n);if(t!==void 0)s.addChildNode(new qc(t));if(i!==void 0)s.withName(i);return s}constructor(n,t=[]){this.name=n,this.children=t}withName(n){return this.name=n,this}addAttribute(n,t){return this.attributes[n]=t,this}addChildNode(n){return this.children.push(n),this}removeAttribute(n){return delete this.attributes[n],this}n(n){return this.name=n,this}c(n){return this.children.push(n),this}a(n,t){if(t!=null)this.attributes[n]=t;return this}cc(n,t,i=t){if(n[t]!=null){let s=ce.of(t,n[t]).withName(i);this.c(s)}}l(n,t,i,s){if(n[t]!=null)s().map((e)=>{e.withName(i),this.c(e)})}lc(n,t,i,s){if(n[t]!=null){let r=s(),e=new ce(i);r.map((f)=>{e.c(f)}),this.c(e)}}toString(){let n=Boolean(this.children.length),t=`<${this.name}`,i=this.attributes;for(let s of Object.keys(i)){let r=i[s];if(r!=null)t+=` ${s}="${$P(""+r)}"`}return t+=!n?"/>":`>${this.children.map((s)=>s.toString()).join("")}</${this.name}>`}}function NP(n){return new Vc(n).parse()}class Vc{x;i=0;z;constructor(n){this.x=n,this.x=n.replace(/\r\n?/g,`
|
|
45
|
-
`),this.z=this.x.length}parse(){let n=this,{z:t}=n;while(n.i<t){if(n.trim(),n.i>=t)break;if(n.isNext("<?"))n.readTo("?>"),n.trim();else if(n.isNext("<!--"))n.readTo("-->"),n.trim();else if(n.isNext("<!DOCTYPE",!1))n.skipDoctype(),n.trim();else if(n.x[n.i]==="<"){let i=n.parseTag();return{[i.tag]:i.value}}else throw Error("@aws-sdk XML parse error: unexpected content.")}throw Error("@aws-sdk XML parse error: no root element.")}isNext(n,t=!0){let i=this;if(t)return i.x.startsWith(n,i.i);return i.x.toLowerCase().startsWith(n.toLowerCase(),i.i)}readTo(n){let t=this,i=t.x.indexOf(n,t.i);if(i===-1)throw Error(`@aws-sdk XML parse error: expected "${n}" not found.`);let
|
|
44
|
+
or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`),Date.now()}return t}constructor(n){this.configProvider=new Promise((t,i)=>{if(typeof n==="function")n().then((r)=>{t(this.resolveDefaultConfig(r))}).catch(i);else t(this.resolveDefaultConfig(n))})}destroy(){this.config?.httpAgent?.destroy(),this.config?.httpsAgent?.destroy()}async handle(n,{abortSignal:t,requestTimeout:i}={}){if(!this.config)this.config=await this.configProvider;let r=this.config,s=n.protocol==="https:";if(!s&&!this.config.httpAgent)this.config.httpAgent=await this.config.httpAgentProvider();return new Promise((f,h)=>{let _=void 0,c=-1,o=-1,w=-1,e=-1,u=-1,y=()=>{Xn.clearTimeout(c),Xn.clearTimeout(o),Xn.clearTimeout(w),Xn.clearTimeout(e),Xn.clearTimeout(u)},A=async(H)=>{await _,y(),f(H)},R=async(H)=>{await _,y(),h(H)};if(t?.aborted){let H=hh(t);R(H);return}let M=n.headers,E=M?(M.Expect??M.expect)==="100-continue":!1,g=s?r.httpsAgent:r.httpAgent;if(E&&!this.externalAgent)g=new(s?fh.Agent:_h)({keepAlive:!1,maxSockets:1/0});c=Xn.setTimeout(()=>{this.socketWarningTimestamp=ch.checkSocketUsage(g,this.socketWarningTimestamp,r.logger)},r.socketAcquisitionWarningTimeout??(r.requestTimeout??2000)+(r.connectionTimeout??1000));let T=n.query?dM(n.query):"",S=void 0;if(n.username!=null||n.password!=null){let H=n.username??"",W=n.password??"";S=`${H}:${W}`}let L=n.path;if(T)L+=`?${T}`;if(n.fragment)L+=`#${n.fragment}`;let b=n.hostname??"";if(b[0]==="["&&b.endsWith("]"))b=n.hostname.slice(1,-1);else b=n.hostname;let I={headers:n.headers,host:b,method:n.method,path:L,port:n.port,agent:g,auth:S},$=(s?fh.request:uM)(I,(H)=>{let W=new AM({statusCode:H.statusCode||-1,reason:H.statusMessage,headers:RM(H.headers),body:H});A({response:W})});if($.on("error",(H)=>{if(W9.includes(H.code))R(Object.assign(H,{name:"TimeoutError"}));else R(H)}),t){let H=()=>{$.destroy();let W=hh(t);R(W)};if(typeof t.addEventListener==="function"){let W=t;W.addEventListener("abort",H,{once:!0}),$.once("close",()=>W.removeEventListener("abort",H))}else t.onabort=H}let U=i??r.requestTimeout;o=D9($,R,r.connectionTimeout),w=P9($,R,U,r.throwOnRequestTimeout,r.logger??console),e=X9($,R,r.socketTimeout);let X=I.agent;if(typeof X==="object"&&"keepAlive"in X)u=F9($,{keepAlive:X.keepAlive,keepAliveMsecs:X.keepAliveMsecs});_=MM($,n,U,this.externalAgent).catch((H)=>{return y(),h(H)})})}updateHttpClientConfig(n,t){this.config=void 0,this.configProvider=this.configProvider.then((i)=>{return{...i,[n]:t}})}httpHandlerConfigs(){return this.config??{}}resolveDefaultConfig(n){let{requestTimeout:t,connectionTimeout:i,socketTimeout:r,socketAcquisitionWarningTimeout:s,httpAgent:f,httpsAgent:h,throwOnRequestTimeout:_,logger:c}=n||{},o=!0,w=50;return{connectionTimeout:i,requestTimeout:t,socketTimeout:r,socketAcquisitionWarningTimeout:s,throwOnRequestTimeout:_,httpAgentProvider:async()=>{let e=cn("http"),{Agent:u,request:y}=e.default??e;if(uM=y,_h=u,f instanceof _h||typeof f?.destroy==="function")return this.externalAgent=!0,f;return new _h({keepAlive:!0,maxSockets:50,...f})},httpsAgent:(()=>{if(h instanceof fh.Agent||typeof h?.destroy==="function")return this.externalAgent=!0,h;return new fh.Agent({keepAlive:!0,maxSockets:50,...h})})(),logger:c}}}var Q9=new Uint16Array(1);class oh{id=Q9[0]++;total=0;max=0;session;refs=0;constructor(n){n.unref(),this.session=n}retain(){if(this.session.destroyed)throw Error("@smithy/node-http-handler - cannot acquire reference to destroyed session.");this.refs+=1,this.total+=1,this.max=Math.max(this.refs,this.max),this.session.ref()}free(){if(this.session.destroyed)return;if(this.refs-=1,this.refs===0)this.session.unref();if(this.refs<0)throw Error("@smithy/node-http-handler - ClientHttp2Session refcount at zero, cannot decrement.")}deref(){return this.session}close(){if(!this.session.closed)this.session.close()}destroy(){if(this.refs=0,!this.session.destroyed)this.session.destroy()}useCount(){return this.refs}}class EM{sessions=[];maxConcurrency=0;constructor(n){this.sessions=(n??[]).map((t)=>new oh(t))}poll(){let n=!1;for(let t of this.sessions){if(t.deref().destroyed){n=!0;continue}if(!this.maxConcurrency||t.useCount()<this.maxConcurrency)return t}if(n){for(let t of this.sessions)if(t.deref().destroyed)this.remove(t)}}offerLast(n){this.sessions.push(n)}remove(n){let t=this.sessions.indexOf(n);if(t>-1)this.sessions.splice(t,1)}[Symbol.iterator](){return this.sessions[Symbol.iterator]()}setMaxConcurrency(n){this.maxConcurrency=n}destroy(n){this.remove(n),n.destroy()}}class TM{config;connectOptions;connectionPools=new Map;constructor(n){if(this.config=n,this.config.maxConcurrency&&this.config.maxConcurrency<=0)throw RangeError("maxConcurrency must be greater than zero.")}lease(n,t){let i=this.getUrlString(n),r=this.getPool(i);if(!this.config.disableConcurrency&&!t.isEventStream){let c=r.poll();if(c)return c.retain(),c}let s=new oh(this.connect(i)),f=s.deref();if(this.config.maxConcurrency)f.settings({maxConcurrentStreams:this.config.maxConcurrency},(c)=>{if(c)throw Error("Fail to set maxConcurrentStreams to "+this.config.maxConcurrency+"when creating new session for "+n.destination.toString())});let h=()=>{this.removeFromPoolAndClose(i,s)},_=()=>{this.removeFromPoolAndCheckedDestroy(i,s)};if(f.on("goaway",h),f.on("error",_),f.on("frameError",_),f.on("close",_),t.requestTimeout)f.setTimeout(t.requestTimeout,_);return r.offerLast(s),s.retain(),s}release(n,t){t.free()}createIsolatedSession(n,t){let i=this.getUrlString(n),r=new oh(this.connect(i)),s=r.deref();s.settings({maxConcurrentStreams:1});let f=()=>{r.destroy()};if(s.on("error",f),s.on("frameError",f),s.on("close",f),t.requestTimeout)s.setTimeout(t.requestTimeout,f);return r.retain(),r}destroy(){for(let[n,t]of this.connectionPools){for(let i of[...t])i.destroy();this.connectionPools.delete(n)}}setMaxConcurrentStreams(n){if(n&&n<=0)throw RangeError("maxConcurrentStreams must be greater than zero.");this.config.maxConcurrency=n;for(let t of this.connectionPools.values())t.setMaxConcurrency(n)}setDisableConcurrentStreams(n){this.config.disableConcurrency=n}setNodeHttp2ConnectOptions(n){this.connectOptions=n}debug(){let n={};for(let[t,i]of this.connectionPools){let r=[];for(let s of i)r.push({id:s.id,active:s.useCount(),maxConcurrent:s.max,totalRequests:s.total});n[t]={sessions:r}}return n}removeFromPoolAndClose(n,t){this.connectionPools.get(n)?.remove(t),t.close()}removeFromPoolAndCheckedDestroy(n,t){this.connectionPools.get(n)?.remove(t),t.destroy()}getPool(n){if(!this.connectionPools.has(n)){let t=new EM;if(this.config.maxConcurrency)t.setMaxConcurrency(this.config.maxConcurrency);this.connectionPools.set(n,t)}return this.connectionPools.get(n)}getUrlString(n){return n.destination.toString()}connect(n){return this.connectOptions===void 0?mo.connect(n):mo.connect(n,this.connectOptions)}}var{constants:yM}=mo;class Zo{config;configProvider;metadata={handlerProtocol:"h2"};connectionManager=new TM({});static create(n){if(typeof n?.handle==="function")return n;return new Zo(n)}constructor(n){this.configProvider=new Promise((t,i)=>{if(typeof n==="function")n().then((r)=>{t(r||{})}).catch(i);else t(n||{})})}destroy(){this.connectionManager.destroy()}async handle(n,{abortSignal:t,requestTimeout:i,isEventStream:r}={}){if(!this.config){this.config=await this.configProvider;let{disableConcurrentStreams:c,maxConcurrentStreams:o,nodeHttp2ConnectOptions:w}=this.config;if(this.connectionManager.setDisableConcurrentStreams(c??!1),o)this.connectionManager.setMaxConcurrentStreams(o);if(w)this.connectionManager.setNodeHttp2ConnectOptions(w)}let{requestTimeout:s,disableConcurrentStreams:f}=this.config,h=f||r,_=i??s;return new Promise((c,o)=>{let w=!1,e=void 0,u=async(W)=>{await e,c(W)},y=async(W)=>{await e,o(W)};if(t?.aborted){w=!0;let W=hh(t);y(W);return}let{hostname:A,method:R,port:M,protocol:E,query:g}=n,T="";if(n.username!=null||n.password!=null){let W=n.username??"",K=n.password??"";T=`${W}:${K}@`}let S=`${E}//${T}${A}${M?`:${M}`:""}`,L={destination:new URL(S)},b={requestTimeout:this.config?.sessionTimeout,isEventStream:r},I=h?this.connectionManager.createIsolatedSession(L,b):this.connectionManager.lease(L,b),Z=I.deref(),$=(W)=>{if(h)I.destroy();w=!0,y(W)},U=g?dM(g):"",X=n.path;if(U)X+=`?${U}`;if(n.fragment)X+=`#${n.fragment}`;let H=Z.request({...n.headers,[yM.HTTP2_HEADER_PATH]:X,[yM.HTTP2_HEADER_METHOD]:R});if(_)H.setTimeout(_,()=>{H.close();let W=Error(`Stream timed out because of no activity for ${_} ms`);W.name="TimeoutError",$(W)});if(t){let W=()=>{H.close();let K=hh(t);$(K)};if(typeof t.addEventListener==="function"){let K=t;K.addEventListener("abort",W,{once:!0}),H.once("close",()=>K.removeEventListener("abort",W))}else t.onabort=W}H.on("frameError",(W,K,P)=>{$(Error(`Frame type id ${W} in stream id ${P} has failed with code ${K}.`))}),H.on("error",$),H.on("aborted",()=>{$(Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${H.rstCode}.`))}),H.on("response",(W)=>{let K=new AM({statusCode:W[":status"]??-1,headers:RM(W),body:H});if(w=!0,u({response:K}),h)Z.close()}),H.on("close",()=>{if(h)I.destroy();else this.connectionManager.release(L,I);if(!w)$(Error("Unexpected error: http2 request did not get a response"))}),e=MM(H,n,_)})}updateHttpClientConfig(n,t){this.config=void 0,this.configProvider=this.configProvider.then((i)=>{return{...i,[n]:t}})}httpHandlerConfigs(){return this.config??{}}}z9.DEFAULT_REQUEST_TIMEOUT=J9;z9.NodeHttp2Handler=Zo;z9.NodeHttpHandler=ch});var GM=nn((OP)=>{var{nv:j9,NumericValue:OM,calculateBodyLength:k9,_parseEpochTimestamp:gM,fromBase64:UM,generateIdempotencyToken:q9}=jn(),{HttpRequest:m9,collectBody:Z9,SerdeContext:iw,RpcProtocol:a9}=kn(),{NormalizedSchema:rw,deref:v9,TypeRegistry:SM}=Ei(),{getSmithyContext:p9}=Dt();function hs(n){return typeof Buffer<"u"?Buffer.alloc(n):new Uint8Array(n)}var sw=Symbol("@smithy/core/cbor::tagSymbol");function fw(n){return n[sw]=!0,n}var bM=typeof Buffer<"u",_w=new TextDecoder,_n=hs(0),hw=!1,St=new DataView(_n.buffer,_n.byteOffset,_n.byteLength),m=0;function nP(n){_n=n,hw=bM&&_n instanceof Buffer,St=new DataView(_n.buffer,_n.byteOffset,_n.byteLength)}function Ni(n,t){if(n>=t)throw Error("unexpected end of (decode) payload.");let i=(_n[n]&224)>>5,r=_n[n]&31;if(r===31&&2<=i&&i<=5)return tP(n,t);switch(i){case 0:case 1:case 6:{let s,f;if(r<24)s=r,f=1;else switch(r){case 24:if(t-n<2)Jt(1);s=_n[n+1],f=2;break;case 25:if(t-n<3)Jt(2);s=St.getUint16(n+1),f=3;break;case 26:if(t-n<5)Jt(4);s=St.getUint32(n+1),f=5;break;case 27:if(t-n<9)Jt(8);{let h=St.getUint32(n+1);if(h<2097152)s=h*4294967296+St.getUint32(n+5);else s=St.getBigUint64(n+1)}f=9;break;default:ow(r)}if(i===0)return m=f,po(s);else if(i===1){let h;if(typeof s==="bigint")h=BigInt(-1)-s;else h=-1-s;return m=f,po(h)}else return oP(n,t,r,s,f)}case 3:return Uf(n,t);case 5:return rP(n,t);case 4:return _P(n,t);case 2:return cw(n,t);default:return wP(n,t)}}function tP(n,t){let i=(_n[n]&224)>>5;if((_n[n]&31)===31)switch(i){case 3:return yP(n,t);case 5:return eP(n,t);case 4:return uP(n,t);case 2:return dP(n,t)}}function iP(n,t){let i=n>>7,r=(n&124)>>2,s=(n&3)<<8|t,f=i===0?1:-1;if(r===0){if(s===0)return 0;return f*(Math.pow(2,-14)*(s/1024))}else if(r===31){if(s===0)return f*(1/0);return NaN}return f*(Math.pow(2,r-15)*(1+s/1024))}function rP(n,t){let i=bf(n,t);if(i<15)return fP(n,t,i);return sP(n,t,i)}function sP(n,t,i){let r=m;n+=r;let s=n,f=Object.create(null);for(let h=0;h<i;++h){let _=Uf(n,t);if(n+=m,(_n[n]&224)>>5===3)f[_]=Uf(n,t);else f[_]=Ni(n,t);n+=m}return m=r+(n-s),Object.setPrototypeOf(f,Object.prototype),f}function fP(n,t,i){let r=m;n+=r;let s=n,f={};for(let h=0;h<i;++h){let _=Uf(n,t);n+=m,f[_]=Ni(n,t),n+=m}return m=r+(n-s),f}function _P(n,t){let i=bf(n,t),r=m;n+=r;let s=n,f=Array(i);for(let h=0;h<i;++h)f[h]=Ni(n,t),n+=m;return m=r+(n-s),f}function Uf(n,t){let i=bf(n,t),r=m;if(n+=r,t-n<i)Jt(i);if(m=r+i,i<24)return cP(n,i);if(hw)return _n.toString("utf-8",n,n+i);return _w.decode(_n.subarray(n,n+i))}var LM=Array(2048),ao=new Uint16Array(2048),$f=0;function hP(){$f=$f+1&65535}function cP(n,t){let i=t;for(let h=0;h<t;++h)i=i*31+_n[n+h]|0;let r=i>>>0&2047,s=LM[r];if(s!==void 0){if(s.length===t){let h=!0;for(let _=0;_<t;++_)if(s.charCodeAt(_)!==_n[n+_]){h=!1;break}if(h)return ao[r]=$f,s}}let f=hw?_n.toString("utf-8",n,n+t):_w.decode(_n.subarray(n,n+t));if(ao[r]!==$f)LM[r]=f,ao[r]=$f;return f}function cw(n,t){let i=bf(n,t),r=m;if(n+=r,t-n<i)Jt(i);let s=_n.subarray(n,n+i);return m=r+i,s}function oP(n,t,i,r,s){if(i===2||i===3){let f=bf(n+s,t),h=BigInt(0),_=n+s+m;for(let c=_;c<_+f;++c)h=h<<BigInt(8)|BigInt(_n[c]);return m=s+m+f,i===3?-h-BigInt(1):h}else if(i===4){let f=Ni(n+s,t),[h,_]=f,c=_<0?-1:1,o="0".repeat(Math.abs(h)+1)+String(BigInt(c)*BigInt(_)),w,e=_<0?"-":"";if(w=h===0?o:o.slice(0,o.length+h)+"."+o.slice(h),w=w.replace(/^0+/g,""),w==="")w="0";if(w[0]===".")w="0"+w;return w=e+w,m=s+m,j9(w)}else{let f=Ni(n+s,t);return m=s+m,fw({tag:po(r),value:f})}}function wP(n,t){let i=_n[n]&31;switch(i){case 21:case 20:return m=1,i===21;case 22:return m=1,null;case 23:return m=1,null;case 25:if(t-n<3)throw Error("incomplete float16 at end of buf.");return m=3,iP(_n[n+1],_n[n+2]);case 26:if(t-n<5)throw Error("incomplete float32 at end of buf.");return m=5,St.getFloat32(n+1);case 27:if(t-n<9)throw Error("incomplete float64 at end of buf.");return m=9,St.getFloat64(n+1);default:ow(i)}}function bf(n,t){let i=_n[n]&31;if(i<24)return m=1,i;switch(i){case 24:if(t-n<2)Jt(1);return m=2,_n[n+1];case 25:if(t-n<3)Jt(2);return m=3,St.getUint16(n+1);case 26:if(t-n<5)Jt(4);return m=5,St.getUint32(n+1);case 27:if(t-n<9)Jt(8);return m=9,AP(St.getBigUint64(n+1));default:ow(i)}}function eP(n,t){n+=1;let i=n,r={};for(;n<t;){if(_n[n]===255)return m=n-i+2,r;let s=Uf(n,t);n+=m,r[s]=Ni(n,t),n+=m}throw Error("expected break marker.")}function uP(n,t){n+=1;let i=[];for(let r=n;n<t;){if(_n[n]===255)return m=n-r+2,i;i.push(Ni(n,t)),n+=m}throw Error("expected break marker.")}function yP(n,t){n+=1;let i=[];for(let r=n;n<t;){if(_n[n]===255){let c=hs(i.length);if(c.set(i,0),m=n-r+2,bM)return c.toString("utf-8",0,c.length);return _w.decode(c)}let s=(_n[n]&224)>>5,f=_n[n]&31;if(s!==3)NM(s);if(f===31)throw Error("nested indefinite string.");let h=cw(n,t);n+=m;for(let c=0;c<h.length;++c)i.push(h[c])}throw Error("expected break marker.")}function dP(n,t){n+=1;let i=[];for(let r=n;n<t;){if(_n[n]===255){let c=hs(i.length);return c.set(i,0),m=n-r+2,c}let s=(_n[n]&224)>>5,f=_n[n]&31;if(s!==2)NM(s);if(f===31)throw Error("nested indefinite string.");let h=cw(n,t);n+=m;for(let c=0;c<h.length;++c)i.push(h[c])}throw Error("expected break marker.")}function po(n){if(typeof n==="number")return n;let t=Number(n);if(Number.MIN_SAFE_INTEGER<=t&&t<=Number.MAX_SAFE_INTEGER)return t;return n}function AP(n){let t=Number(n);if(t<Number.MIN_SAFE_INTEGER||Number.MAX_SAFE_INTEGER<t)console.warn(Error(`@smithy/core/cbor - truncating BigInt(${n}) to ${t} with loss of precision.`));return t}function Jt(n){throw Error(`length ${n} greater than remaining buf len.`)}function ow(n){throw Error(`unexpected minor value ${n}.`)}function NM(n){throw Error(`unexpected major type ${n} in indefinite string.`)}var RP=typeof Buffer<"u",fs=new Map,Of=0,nw=!1,MP=2048,Q=hs(MP),ot=new DataView(Q.buffer,Q.byteOffset,Q.byteLength),G=0;function EP(n){let t=[n];while(t.length){let i=t.pop();if(typeof i==="string"){let r=i.length;if(RP)if(_s(r*3+9),r>23)vo(3,Buffer.byteLength(i)),G+=Q.write(i,G);else gP(i);else{let s=r*3;_s(s+9);let f=G,_=new TextEncoder().encodeInto(i,Q.subarray(G+9)).written,c;if(_<24)c=1;else if(_<256)c=2;else if(_<65536)c=3;else if(_<4294967296)c=5;else c=9;if(c<9)Q.copyWithin(f+c,f+9,f+9+_);G=f,sr(3,_),G+=_}continue}if(Q.byteLength-G<9)_s(64);if(typeof i==="number"){if(Number.isInteger(i)){let r=i>=0,s=r?0:1,f=r?i:-i-1;if(f<24)Q[G++]=s<<5|f;else if(f<256)Q[G++]=s<<5|24,Q[G++]=f;else if(f<65536)Q[G++]=s<<5|25,Q[G++]=f>>8,Q[G++]=f&255;else if(f<4294967296)Q[G++]=s<<5|26,ot.setUint32(G,f),G+=4;else{Q[G++]=s<<5|27;let h=f/4294967296|0,_=f-h*4294967296|0;ot.setUint32(G,h),ot.setUint32(G+4,_),G+=8}continue}Q[G++]=251,ot.setFloat64(G,i),G+=8;continue}else if(typeof i==="bigint"){let r=i>=0,s=r?0:1,f=r?i:-i-BigInt(1);if(f<BigInt("18446744073709551616")){let h=Number(f);if(h<4294967296)sr(s,h);else Q[G++]=s<<5|27,ot.setBigUint64(G,f),G+=8}else{let h=f.toString(2),_=new Uint8Array(Math.ceil(h.length/8)),c=f,o=0;while(_.byteLength-++o>=0)_[_.byteLength-o]=Number(c&BigInt(255)),c>>=BigInt(8);_s(_.byteLength*2+16),Q[G++]=r?194:195,vo(2,_.byteLength),Q.set(_,G),G+=_.byteLength}continue}else if(i===null){Q[G++]=246;continue}else if(typeof i==="boolean"){Q[G++]=224|(i?21:20);continue}else if(typeof i>"u")throw Error("@smithy/core/cbor: client may not serialize undefined value.");else if(Array.isArray(i)){sr(4,i.length),_s(i.length*9+64);for(let r=i.length-1;r>=0;--r)t.push(i[r]);continue}else if(typeof i.byteLength==="number"){_s(i.length*2+9),sr(2,i.length),Q.set(i,G),G+=i.byteLength;continue}else if(typeof i==="object"){if(i instanceof OM){let f=i.string.indexOf("."),h=f===-1?0:f-i.string.length+1,_=BigInt(i.string.replace(".",""));Q[G++]=196,sr(4,2),t.push(_),t.push(h);continue}if(i[sw])if("tag"in i&&"value"in i){t.push(i.value),vo(6,i.tag);continue}else throw Error("tag encountered with missing fields, need 'tag' and 'value', found: "+JSON.stringify(i));let r=Object.keys(i),s=r.length;sr(5,s);for(let f=s-1;f>=0;--f)t.push(i[r[f]]),t.push(r[f]);continue}throw Error(`data type ${i?.constructor?.name??typeof i} not compatible for encoding.`)}}function TP(){Of=Of+1&65535,nw=!1}function $M(){let n=hs(G);return n.set(Q.subarray(0,G),0),G=0,n}function tw(n){let t=Q;if(Q=hs(n),t)if(t.copy)t.copy(Q,0,0,t.byteLength);else Q.set(t,0);ot=new DataView(Q.buffer,Q.byteOffset,Q.byteLength)}function gP(n){let t=fs.get(n);if(t!==void 0){Q.set(t.bytes,G),G+=t.bytes.length,t.epoch=Of;return}let i=G,r=Buffer.byteLength(n);sr(3,r),G+=Q.write(n,G);let s=Uint8Array.prototype.slice.call(Q,i,G);if(fs.size>=2048){if(nw)return;let f=0;for(let[h,_]of fs){if(f>=1024)break;if(_.epoch!==Of)fs.delete(h),f++}if(f===0){nw=!0;return}}if(fs.size<2048)fs.set(n,{epoch:Of,bytes:s})}function _s(n){if(Q.byteLength-G<n)if(G<16000000)tw(Math.max(Q.byteLength*4,Q.byteLength+n));else tw(Q.byteLength+n+16000000)}function vo(n,t){if(t<24)Q[G++]=n<<5|t;else if(t<256)Q[G++]=n<<5|24,Q[G++]=t;else if(t<65536)Q[G++]=n<<5|25,ot.setUint16(G,t),G+=2;else if(t<4294967296)Q[G++]=n<<5|26,ot.setUint32(G,t),G+=4;else Q[G++]=n<<5|27,ot.setBigUint64(G,typeof t==="bigint"?t:BigInt(t)),G+=8}function sr(n,t){if(t<24)Q[G++]=n<<5|t;else if(t<256)Q[G++]=n<<5|24,Q[G++]=t;else if(t<65536)Q[G++]=n<<5|25,Q[G++]=t>>8,Q[G++]=t&255;else if(t<4294967296)Q[G++]=n<<5|26,ot.setUint32(G,t),G+=4;else{Q[G++]=n<<5|27;let i=t/4294967296|0,r=t-i*4294967296|0;ot.setUint32(G,i),ot.setUint32(G+4,r),G+=8}}var uh={deserialize(n){return hP(),nP(n),Ni(0,n.length)},serialize(n){TP();try{return EP(n),$M()}catch(t){throw $M(),t}},resizeEncodingBuffer(n){tw(n)}},BM=(n,t)=>{return Z9(n,t).then(async(i)=>{if(i.length)try{return uh.deserialize(i)}catch(r){throw Object.defineProperty(r,"$responseBodyText",{value:t.utf8Encoder(i)}),r}return{}})},eh=(n)=>{return fw({tag:1,value:n.getTime()/1000})},SP=async(n,t)=>{let i=await BM(n,t);return i.message=i.message??i.Message,i},IM=(n,t)=>{let i=(s)=>{let f=s;if(typeof f==="number")f=f.toString();if(f.indexOf(",")>=0)f=f.split(",")[0];if(f.indexOf(":")>=0)f=f.split(":")[0];if(f.indexOf("#")>=0)f=f.split("#")[1];return f};if(t.__type!==void 0)return i(t.__type);let r;for(let s in t)if(s.toLowerCase()==="code"){r=s;break}if(r&&t[r]!==void 0)return i(t[r])},LP=(n)=>{if(String(n.headers["smithy-protocol"]).toLowerCase()!=="rpc-v2-cbor")throw Error("Malformed RPCv2 CBOR response, status: "+n.statusCode)},$P=async(n,t,i,r,s)=>{let f=await n.endpoint(),{hostname:h,protocol:_="https",port:c,path:o}=f,w={protocol:_,hostname:h,port:c,method:"POST",path:o.endsWith("/")?o.slice(0,-1)+i:o+i,headers:{...t}};if(r!==void 0)w.hostname=r;if(f.headers)for(let e in f.headers)w.headers[e]=f.headers[e];if(s!==void 0){w.body=s;try{w.headers["content-length"]=String(k9(s))}catch(e){}}return new m9(w)};class ww extends iw{createSerializer(){let n=new ew;return n.setSerdeContext(this.serdeContext),n}createDeserializer(){let n=new uw;return n.setSerdeContext(this.serdeContext),n}}class ew extends iw{value;write(n,t){this.value=this.serialize(n,t)}serialize(n,t){let i=rw.of(n);if(t==null){if(i.isIdempotencyToken())return q9();return t}if(i.isBlobSchema()){if(typeof t==="string")return(this.serdeContext?.base64Decoder??UM)(t);return t}if(i.isTimestampSchema()){if(typeof t==="number"||typeof t==="bigint")return eh(new Date(Number(t)/1000|0));return eh(t)}if(typeof t==="function"||typeof t==="object"){let r=t;if(i.isListSchema()&&Array.isArray(r)){let f=!!i.getMergedTraits().sparse,h=[],_=0;for(let c of r){let o=this.serialize(i.getValueSchema(),c);if(o!=null||f)h[_++]=o}return h}if(r instanceof Date)return eh(r);let s={};if(i.isMapSchema()){let f=!!i.getMergedTraits().sparse;for(let h in r){let _=this.serialize(i.getValueSchema(),r[h]);if(_!=null||f)s[h]=_}}else if(i.isStructSchema()){for(let[h,_]of i.structIterator()){let c=this.serialize(_,r[h]);if(c!=null)s[h]=c}if(i.isUnionSchema()&&Array.isArray(r.$unknown)){let[h,_]=r.$unknown;s[h]=_}else if(typeof r.__type==="string"){for(let h in r)if(!(h in s))s[h]=this.serialize(15,r[h])}}else if(i.isDocumentSchema())for(let f in r)s[f]=this.serialize(i.getValueSchema(),r[f]);else if(i.isBigDecimalSchema())return r;return s}return t}flush(){let n=uh.serialize(this.value);return this.value=void 0,n}}class uw extends iw{read(n,t){let i=uh.deserialize(t);return this.readValue(n,i)}readValue(n,t){let i=rw.of(n);if(i.isTimestampSchema()){if(typeof t==="number")return gM(t);if(typeof t==="object"){if(t.tag===1&&"value"in t)return gM(t.value)}}if(i.isBlobSchema()){if(typeof t==="string")return(this.serdeContext?.base64Decoder??UM)(t);return t}if(typeof t>"u"||typeof t==="boolean"||typeof t==="number"||typeof t==="string"||typeof t==="bigint"||typeof t==="symbol")return t;else if(typeof t==="object"){if(t===null)return null;if("byteLength"in t)return t;if(t instanceof Date)return t;if(i.isDocumentSchema())return t;if(i.isListSchema()){let s=[],f=i.getValueSchema();for(let h of t){let _=this.readValue(f,h);s.push(_)}return s}let r={};if(i.isMapSchema()){let s=i.getValueSchema();for(let f in t){let h=this.readValue(s,t[f]);r[f]=h}}else if(i.isStructSchema()){let s=i.isUnionSchema(),f;if(s){f=new Set;for(let h in t)if(h!=="__type")f.add(h)}for(let[h,_]of i.structIterator()){if(s)f.delete(h);if(t[h]!=null)r[h]=this.readValue(_,t[h])}if(s&&f?.size===1){let h=!0;for(let _ in r){h=!1;break}if(h){let _=f.values().next().value;r.$unknown=[_,t[_]]}}else if(typeof t.__type==="string"){for(let h in t)if(!(h in r))r[h]=t[h]}}else if(t instanceof OM)return t;return r}else return t}}class HM extends a9{codec=new ww;serializer=this.codec.createSerializer();deserializer=this.codec.createDeserializer();constructor({defaultNamespace:n,errorTypeRegistries:t}){super({defaultNamespace:n,errorTypeRegistries:t})}getShapeId(){return"smithy.protocols#rpcv2Cbor"}getPayloadCodec(){return this.codec}async serializeRequest(n,t,i){let r=await super.serializeRequest(n,t,i);if(Object.assign(r.headers,{"content-type":this.getDefaultContentType(),"smithy-protocol":"rpc-v2-cbor",accept:this.getDefaultContentType()}),v9(n.input)==="unit")delete r.body,delete r.headers["content-type"];else{if(!r.body)this.serializer.write(15,{}),r.body=this.serializer.flush();try{r.headers["content-length"]=String(r.body.byteLength)}catch(_){}}let{service:s,operation:f}=p9(i),h=`/service/${s}/operation/${f}`;if(r.path.endsWith("/"))r.path+=h.slice(1);else r.path+=h;return r}async deserializeResponse(n,t,i){return super.deserializeResponse(n,t,i)}async handleError(n,t,i,r,s){let f=IM(i,r)??"Unknown",h={$metadata:s,$fault:i.statusCode<=500?"client":"server"},_=this.options.defaultNamespace;if(f.includes("#"))[_]=f.split("#");let c=this.compositeErrorRegistry,o=SM.for(_);c.copyFrom(o);let w;try{w=c.getSchema(f)}catch(M){if(r.Message)r.message=r.Message;let E=SM.for("smithy.ts.sdk.synthetic."+_);c.copyFrom(E);let g=c.getBaseException();if(g){let T=c.getErrorCtor(g);throw Object.assign(new T({name:f}),h,r)}throw Object.assign(Error(f),h,r)}let e=rw.of(w),u=c.getErrorCtor(w),y=r.message??r.Message??"Unknown",A=new u({}),R={};for(let[M,E]of e.structIterator())R[M]=this.deserializer.readValue(E,r[M]);throw Object.assign(A,h,{$fault:e.getMergedTraits().error,message:y},R)}getDefaultContentType(){return"application/cbor"}}OP.CborCodec=ww;OP.CborShapeDeserializer=uw;OP.CborShapeSerializer=ew;OP.SmithyRpcV2CborProtocol=HM;OP.buildHttpRpcRequest=$P;OP.cbor=uh;OP.checkCborResponse=LP;OP.dateToTag=eh;OP.loadSmithyRpcV2CborErrorCode=IM;OP.parseCborBody=BM;OP.parseCborErrorBody=SP;OP.tag=fw;OP.tagSymbol=sw});var WM=nn((xP)=>{var lP=/[&<>"]/g,JP={"&":"&","<":"<",">":">",'"':"""};function QP(n){return n.replace(lP,(t)=>JP[t])}var zP=/[&"'<>\r\n\u0085\u2028]/g,CP={"&":"&",'"':""","'":"'","<":"<",">":">","\r":"
","\n":"
","\x85":"…","\u2028":"
"};function VP(n){return n.replace(zP,(t)=>CP[t])}class yw{value;constructor(n){this.value=n}toString(){return VP(""+this.value)}}class Nf{name;children;attributes={};static of(n,t,i){let r=new Nf(n);if(t!==void 0)r.addChildNode(new yw(t));if(i!==void 0)r.withName(i);return r}constructor(n,t=[]){this.name=n,this.children=t}withName(n){return this.name=n,this}addAttribute(n,t){return this.attributes[n]=t,this}addChildNode(n){return this.children.push(n),this}removeAttribute(n){return delete this.attributes[n],this}n(n){return this.name=n,this}c(n){return this.children.push(n),this}a(n,t){if(t!=null)this.attributes[n]=t;return this}cc(n,t,i=t){if(n[t]!=null){let r=Nf.of(t,n[t]).withName(i);this.c(r)}}l(n,t,i,r){if(n[t]!=null)r().map((f)=>{f.withName(i),this.c(f)})}lc(n,t,i,r){if(n[t]!=null){let s=r(),f=new Nf(i);s.map((h)=>{f.c(h)}),this.c(f)}}toString(){let n=Boolean(this.children.length),t=`<${this.name}`,i=this.attributes;for(let r of Object.keys(i)){let s=i[r];if(s!=null)t+=` ${r}="${QP(""+s)}"`}return t+=!n?"/>":`>${this.children.map((r)=>r.toString()).join("")}</${this.name}>`}}function KP(n){return new dw(n).parse()}class dw{x;i=0;z;constructor(n){this.x=n,this.x=n.replace(/\r\n?/g,`
|
|
45
|
+
`),this.z=this.x.length}parse(){let n=this,{z:t}=n;while(n.i<t){if(n.trim(),n.i>=t)break;if(n.isNext("<?"))n.readTo("?>"),n.trim();else if(n.isNext("<!--"))n.readTo("-->"),n.trim();else if(n.isNext("<!DOCTYPE",!1))n.skipDoctype(),n.trim();else if(n.x[n.i]==="<"){let i=n.parseTag();return{[i.tag]:i.value}}else throw Error("@aws-sdk XML parse error: unexpected content.")}throw Error("@aws-sdk XML parse error: no root element.")}isNext(n,t=!0){let i=this;if(t)return i.x.startsWith(n,i.i);return i.x.toLowerCase().startsWith(n.toLowerCase(),i.i)}readTo(n){let t=this,i=t.x.indexOf(n,t.i);if(i===-1)throw Error(`@aws-sdk XML parse error: expected "${n}" not found.`);let r=t.x.slice(t.i,i);return t.i=i+n.length,r}trim(){let n=this;while(n.i<n.z&&` \r
|
|
46
46
|
`.includes(n.x[n.i]))++n.i}readAttrValue(){let n=this,t=n.x[n.i];++n.i;let i="";while(n.i<n.z&&n.x[n.i]!==t)i+=n.x[n.i++];return++n.i,n.decodeEntities(i)}parseTag(){let n=this;++n.i;let t="";while(n.i<n.z&&!` \r
|
|
47
|
-
>/`.includes(n.x[n.i]))t+=n.x[n.i++];let i=!1,
|
|
48
|
-
>/?`.includes(n.x[n.i]))
|
|
49
|
-
`))return{tag:t,value:""};return{tag:t,value:
|
|
50
|
-
`))continue;h["#text"]="#text"in h?h["#text"]+u:u}for(let u of e)if(u.tag in h)if(Array.isArray(h[u.tag]))h[u.tag].push(u.value);else h[u.tag]=[h[u.tag],u.value];else h[u.tag]=u.value;for(let[u,c]of Object.entries(s))h[u]=c;return Object.setPrototypeOf(h,Object.prototype),{tag:t,value:h}}static ENTITIES={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};skipDoctype(){let n=this;n.i+=9;let t=0;while(n.i<n.z){let i=n.x[n.i];if(i==="[")++t;else if(i==="]")--t;else if(i===">"&&t===0){++n.i;return}++n.i}throw Error("@aws-sdk XML parse error: unclosed DOCTYPE.")}decodeEntities(n){return n.replace(/&(?:#x([0-9a-fA-F]{1,6})|#(\d{1,7})|([a-zA-Z][a-zA-Z0-9]{0,30}));/g,(t,i,s,r)=>{if(i)return String.fromCharCode(parseInt(i,16));if(s)return String.fromCharCode(parseInt(s,10));return Vc.ENTITIES[r]??""})}}GP.XmlNode=ce;GP.XmlText=qc;GP.parseXML=NP});var o_=k((jP)=>{var{SmithyRpcV2CborProtocol:PP,loadSmithyRpcV2CborErrorCode:DP}=q1(),{TypeRegistry:j1,NormalizedSchema:En,deref:tR}=ri(),{decorateServiceException:a1,getValueFromTextNode:iR}=Xt(),{collectBody:ac,determineTimestampFormat:nf,RpcProtocol:sR,HttpBindingProtocol:rR,HttpInterceptingShapeSerializer:eR,HttpInterceptingShapeDeserializer:oR,FromStringShapeDeserializer:YP,extendedEncodeURIComponent:v1}=Jn(),{NumericValue:Bt,toUtf8:fR,fromBase64:hR,LazyJsonString:uR,parseEpochTimestamp:mP,parseRfc7231DateTime:JP,parseRfc3339DateTimeWithOffset:XP,toBase64:Zo,dateToUtcString:po,generateIdempotencyToken:vc,expectUnion:zP}=mn(),{parseXML:cR,XmlNode:wt,XmlText:Z1}=V1();class Vs{queryCompat;errorRegistry;constructor(n=!1){this.queryCompat=n}resolveRestContentType(n,t){let i=t.getMemberSchemas(),s=Object.values(i).find((r)=>{return!!r.getMergedTraits().httpPayload});if(s){let r=s.getMergedTraits().mediaType;if(r)return r;else if(s.isStringSchema())return"text/plain";else if(s.isBlobSchema())return"application/octet-stream";else return n}else if(!t.isUnitSchema()){if(Object.values(i).find((e)=>{let{httpQuery:f,httpQueryParams:o,httpHeader:h,httpLabel:u,httpPrefixHeaders:c}=e.getMergedTraits();return!f&&!o&&!h&&!u&&c===void 0}))return n}}async getErrorSchemaOrThrowBaseException(n,t,i,s,r,e){let f=n;if(n.includes("#"))[,f]=n.split("#");let o={$metadata:r,$fault:i.statusCode<500?"client":"server"};if(!this.errorRegistry)throw Error("@aws-sdk/core/protocols - error handler not initialized.");try{return{errorSchema:e?.(this.errorRegistry,f)??this.errorRegistry.getSchema(n),errorMetadata:o}}catch(h){s.message=s.message??s.Message??"UnknownError";let u=this.errorRegistry,c=u.getBaseException();if(c){let l=u.getErrorCtor(c)??Error;throw this.decorateServiceException(Object.assign(new l({name:f}),o),s)}let _=s,w=_?.message??_?.Message??_?.Error?.Message??_?.Error?.message;throw this.decorateServiceException(Object.assign(Error(w),{name:f},o),s)}}compose(n,t,i){let s=i;if(t.includes("#"))[s]=t.split("#");let r=j1.for(s),e=j1.for("smithy.ts.sdk.synthetic."+i);n.copyFrom(r),n.copyFrom(e),this.errorRegistry=n}decorateServiceException(n,t={}){if(this.queryCompat){let i=n.Message??t.Message,s=a1(n,t);if(i)s.message=i;let r=s.Error??{};r.Type=s.Error?.Type,r.Code=s.Error?.Code,r.Message=s.Error?.message??s.Error?.Message??i,s.Error=r;let e=s.$metadata.requestId;if(e)s.RequestId=e;return s}return a1(n,t)}setQueryCompatError(n,t){let i=t.headers?.["x-amzn-query-error"];if(n!==void 0&&i!=null){let[s,r]=i.split(";"),e=Object.keys(n),f={Code:s,Type:r};n.Code=s,n.Type=r;for(let o=0;o<e.length;o++){let h=e[o];f[h==="message"?"Message":h]=n[h]}delete f.__type,n.Error=f}}queryCompatOutput(n,t){if(n.Error)t.Error=n.Error;if(n.Type)t.Type=n.Type;if(n.Code)t.Code=n.Code}findQueryCompatibleError(n,t){try{return n.getSchema(t)}catch(i){return n.find((s)=>En.of(s).getMergedTraits().awsQueryError?.[0]===t)}}}class _R extends PP{awsQueryCompatible;mixin;constructor({defaultNamespace:n,errorTypeRegistries:t,awsQueryCompatible:i}){super({defaultNamespace:n,errorTypeRegistries:t});this.awsQueryCompatible=!!i,this.mixin=new Vs(this.awsQueryCompatible)}async serializeRequest(n,t,i){let s=await super.serializeRequest(n,t,i);if(this.awsQueryCompatible)s.headers["x-amzn-query-mode"]="true";return s}async handleError(n,t,i,s,r){if(this.awsQueryCompatible)this.mixin.setQueryCompatError(s,i);let e=(()=>{let l=i.headers["x-amzn-query-error"];if(l&&this.awsQueryCompatible)return l.split(";")[0];return DP(i,s)??"Unknown"})();this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace);let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,i,s,r,this.awsQueryCompatible?this.mixin.findQueryCompatibleError:void 0),h=En.of(f),u=s.message??s.Message??"UnknownError",_=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({}),w={};for(let[l,A]of h.structIterator())if(s[l]!=null)w[l]=this.deserializer.readValue(A,s[l]);if(this.awsQueryCompatible)this.mixin.queryCompatOutput(s,w);throw this.mixin.decorateServiceException(Object.assign(_,o,{$fault:h.getMergedTraits().error,message:u},w),s)}}var QP=(n)=>{if(n==null)return n;if(typeof n==="number"||typeof n==="bigint"){let t=Error(`Received number ${n} where a string was expected.`);return t.name="Warning",console.warn(t),String(n)}if(typeof n==="boolean"){let t=Error(`Received boolean ${n} where a string was expected.`);return t.name="Warning",console.warn(t),String(n)}return n},CP=(n)=>{if(n==null)return n;if(typeof n==="string"){let t=n.toLowerCase();if(n!==""&&t!=="false"&&t!=="true"){let i=Error(`Received string "${n}" where a boolean was expected.`);i.name="Warning",console.warn(i)}return n!==""&&t!=="false"}return n},xP=(n)=>{if(n==null)return n;if(typeof n==="string"){let t=Number(n);if(t.toString()!==n){let i=Error(`Received string "${n}" where a number was expected.`);return i.name="Warning",console.warn(i),n}return t}return n};class Ai{serdeContext;setSerdeContext(n){this.serdeContext=n}}class Zc{from;to;keys;constructor(n,t){this.from=n,this.to=t;let i=Object.keys(this.from),s=new Set(i);s.delete("__type"),this.keys=s}mark(n){this.keys.delete(n)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){let n=this.keys.values().next().value,t=this.from[n];this.to.$unknown=[n,t]}}}function KP(n,t,i){if(i?.source){let s=i.source;if(typeof t==="number"){if(t>Number.MAX_SAFE_INTEGER||t<Number.MIN_SAFE_INTEGER||s!==String(t))if(s.includes("."))return new Bt(s,"bigDecimal");else return BigInt(s)}}return t}var wR=(n,t)=>ac(n,t).then((i)=>(t?.utf8Encoder??fR)(i)),pc=(n,t)=>wR(n,t).then((i)=>{if(i.length)try{return JSON.parse(i)}catch(s){if(s?.name==="SyntaxError")Object.defineProperty(s,"$responseBodyText",{value:i});throw s}return{}}),kP=async(n,t)=>{let i=await pc(n,t);return i.message=i.message??i.Message,i},p1=(n,t)=>Object.keys(n).find((i)=>i.toLowerCase()===t.toLowerCase()),jc=(n)=>{let t=n;if(typeof t==="number")t=t.toString();if(t.indexOf(",")>=0)t=t.split(",")[0];if(t.indexOf(":")>=0)t=t.split(":")[0];if(t.indexOf("#")>=0)t=t.split("#")[1];return t},lR=(n,t)=>{return MR(n,t,["header","code","type"])},AR=(n,t,i=!1)=>{return MR(n,t,i?["code","header","type"]:["type","code","header"])},MR=({headers:n},t,i)=>{while(i.length>0)switch(i.shift()){case"header":let r=p1(n??{},"x-amzn-errortype");if(r!==void 0)return jc(n[r]);break;case"code":let e=p1(t??{},"code");if(e&&t[e]!==void 0)return jc(t[e]);break;case"type":if(t?.__type!==void 0)return jc(t.__type);break}};class n_ extends Ai{settings;constructor(n){super();this.settings=n}async read(n,t){return this._read(n,typeof t==="string"?JSON.parse(t,KP):await pc(t,this.serdeContext))}readObject(n,t){return this._read(n,t)}_read(n,t){let i=t!==null&&typeof t==="object",s=En.of(n);if(i){if(s.isStructSchema()){let e=t,f=s.isUnionSchema(),o={},h=void 0,{jsonName:u}=this.settings;if(u)h={};let c;if(f)c=new Zc(e,o);for(let[_,w]of s.structIterator()){let l=_;if(u)l=w.getMergedTraits().jsonName??l,h[l]=_;if(f)c.mark(l);if(e[l]!=null)o[_]=this._read(w,e[l])}if(f)c.writeUnknown();else if(typeof e.__type==="string")for(let _ in e){let w=e[_],l=u?h[_]??_:_;if(!(l in o))o[l]=w}return o}if(Array.isArray(t)&&s.isListSchema()){let e=s.getValueSchema(),f=[];for(let o of t)f.push(this._read(e,o));return f}if(s.isMapSchema()){let e=s.getValueSchema(),f={};for(let o in t)f[o]=this._read(e,t[o]);return f}}if(s.isBlobSchema()&&typeof t==="string")return hR(t);let r=s.getMergedTraits().mediaType;if(s.isStringSchema()&&typeof t==="string"&&r){if(r==="application/json"||r.endsWith("+json"))return uR.from(t);return t}if(s.isTimestampSchema()&&t!=null)switch(nf(s,this.settings)){case 5:return XP(t);case 6:return JP(t);case 7:return mP(t);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",t),new Date(t)}if(s.isBigIntegerSchema()&&(typeof t==="number"||typeof t==="string"))return BigInt(t);if(s.isBigDecimalSchema()&&t!=null){if(t instanceof Bt)return t;let e=t;if(e.type==="bigDecimal"&&"string"in e)return new Bt(e.string,e.type);return new Bt(String(t),"bigDecimal")}if(s.isNumericSchema()&&typeof t==="string"){switch(t){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return t}if(s.isDocumentSchema())if(i){let e=Array.isArray(t)?[]:{};for(let f in t){let o=t[f];if(o instanceof Bt)e[f]=o;else e[f]=this._read(s,o)}return e}else return structuredClone(t);return t}}var nR=String.fromCharCode(925);class dR{values=new Map;counter=0;stage=0;createReplacer(){if(this.stage===1)throw Error("@aws-sdk/core/protocols - JsonReplacer already created.");if(this.stage===2)throw Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");return this.stage=1,(n,t)=>{if(t instanceof Bt){let i=`${nR+"nv"+this.counter++}_`+t.string;return this.values.set(`"${i}"`,t.string),i}if(typeof t==="bigint"){let i=t.toString(),s=`${nR+"b"+this.counter++}_`+i;return this.values.set(`"${s}"`,i),s}return t}}replaceInJson(n){if(this.stage===0)throw Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");if(this.stage===2)throw Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");if(this.stage=2,this.counter===0)return n;for(let[t,i]of this.values)n=n.replace(t,i);return n}}class t_ extends Ai{settings;buffer;useReplacer=!1;rootSchema;constructor(n){super();this.settings=n}write(n,t){this.rootSchema=En.of(n),this.buffer=this._write(this.rootSchema,t)}flush(){let{rootSchema:n,useReplacer:t}=this;if(this.rootSchema=void 0,this.useReplacer=!1,n?.isStructSchema()||n?.isDocumentSchema()){if(!t)return JSON.stringify(this.buffer);let i=new dR;return i.replaceInJson(JSON.stringify(this.buffer,i.createReplacer(),0))}return this.buffer}writeDiscriminatedDocument(n,t){if(this.write(n,t),typeof this.buffer==="object")this.buffer.__type=En.of(n).getName(!0)}_write(n,t,i){let s=t!==null&&typeof t==="object",r=En.of(n);if(s){if(r.isStructSchema()){let e=t,f={},{jsonName:o}=this.settings,h=void 0;if(o)h={};let u=0;for(let[c,_]of r.structIterator()){let w=this._write(_,e[c],r);if(w!==void 0){let l=c;if(o)l=_.getMergedTraits().jsonName??c,h[c]=l;f[l]=w,u++}}if(r.isUnionSchema()&&u===0){let{$unknown:c}=e;if(Array.isArray(c)){let[_,w]=c;f[_]=this._write(15,w)}}else if(typeof e.__type==="string")for(let c in e){let _=e[c],w=o?h[c]??c:c;if(!(w in f))f[w]=this._write(15,_)}return f}if(Array.isArray(t)&&r.isListSchema()){let e=r.getValueSchema(),f=[],o=!!r.getMergedTraits().sparse;for(let h of t)if(o||h!=null)f.push(this._write(e,h));return f}if(r.isMapSchema()){let e=r.getValueSchema(),f={},o=!!r.getMergedTraits().sparse;for(let h in t){let u=t[h];if(o||u!=null)f[h]=this._write(e,u)}return f}if(t instanceof Uint8Array&&(r.isBlobSchema()||r.isDocumentSchema())){if(r===this.rootSchema)return t;return(this.serdeContext?.base64Encoder??Zo)(t)}if(t instanceof Date&&(r.isTimestampSchema()||r.isDocumentSchema()))switch(nf(r,this.settings)){case 5:return t.toISOString().replace(".000Z","Z");case 6:return po(t);case 7:return t.getTime()/1000;default:return console.warn("Missing timestamp format, using epoch seconds",t),t.getTime()/1000}if(t instanceof Bt)this.useReplacer=!0}if(t===null&&i?.isStructSchema())return;if(r.isStringSchema()){if(typeof t>"u"&&r.isIdempotencyToken())return vc();let e=r.getMergedTraits().mediaType;if(t!=null&&e){if(e==="application/json"||e.endsWith("+json"))return uR.from(t)}return t}if(typeof t==="number"&&r.isNumericSchema()){if(Math.abs(t)===1/0||isNaN(t))return String(t);return t}if(typeof t==="string"&&r.isBlobSchema()){if(r===this.rootSchema)return t;return(this.serdeContext?.base64Encoder??Zo)(t)}if(typeof t==="bigint")this.useReplacer=!0;if(r.isDocumentSchema())if(s){let e=Array.isArray(t)?[]:{};for(let f in t){let o=t[f];if(o instanceof Bt)this.useReplacer=!0,e[f]=o;else e[f]=this._write(r,o)}return e}else return structuredClone(t);return t}}class tf extends Ai{settings;constructor(n){super();this.settings=n}createSerializer(){let n=new t_(this.settings);return n.setSerdeContext(this.serdeContext),n}createDeserializer(){let n=new n_(this.settings);return n.setSerdeContext(this.serdeContext),n}}class sf extends sR{serializer;deserializer;serviceTarget;codec;mixin;awsQueryCompatible;constructor({defaultNamespace:n,errorTypeRegistries:t,serviceTarget:i,awsQueryCompatible:s,jsonCodec:r}){super({defaultNamespace:n,errorTypeRegistries:t});this.serviceTarget=i,this.codec=r??new tf({timestampFormat:{useTrait:!0,default:7},jsonName:!1}),this.serializer=this.codec.createSerializer(),this.deserializer=this.codec.createDeserializer(),this.awsQueryCompatible=!!s,this.mixin=new Vs(this.awsQueryCompatible)}async serializeRequest(n,t,i){let s=await super.serializeRequest(n,t,i);if(!s.path.endsWith("/"))s.path+="/";if(s.headers["content-type"]=`application/x-amz-json-${this.getJsonRpcVersion()}`,s.headers["x-amz-target"]=`${this.serviceTarget}.${n.name}`,this.awsQueryCompatible)s.headers["x-amzn-query-mode"]="true";if(tR(n.input)==="unit"||!s.body)s.body="{}";return s}getPayloadCodec(){return this.codec}async handleError(n,t,i,s,r){let{awsQueryCompatible:e}=this;if(e)this.mixin.setQueryCompatError(s,i);let f=AR(i,s,e)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,f,this.options.defaultNamespace);let{errorSchema:o,errorMetadata:h}=await this.mixin.getErrorSchemaOrThrowBaseException(f,this.options.defaultNamespace,i,s,r,e?this.mixin.findQueryCompatibleError:void 0),u=En.of(o),c=s.message??s.Message??"UnknownError",w=new(this.compositeErrorRegistry.getErrorCtor(o)??Error)({}),l={},A=this.codec.createDeserializer();for(let[d,E]of u.structIterator())if(s[d]!=null)l[d]=A.readObject(E,s[d]);if(e)this.mixin.queryCompatOutput(s,l);throw this.mixin.decorateServiceException(Object.assign(w,h,{$fault:u.getMergedTraits().error,message:c},l),s)}}class RR extends sf{constructor({defaultNamespace:n,errorTypeRegistries:t,serviceTarget:i,awsQueryCompatible:s,jsonCodec:r}){super({defaultNamespace:n,errorTypeRegistries:t,serviceTarget:i,awsQueryCompatible:s,jsonCodec:r})}getShapeId(){return"aws.protocols#awsJson1_0"}getJsonRpcVersion(){return"1.0"}getDefaultContentType(){return"application/x-amz-json-1.0"}}class ER extends sf{constructor({defaultNamespace:n,errorTypeRegistries:t,serviceTarget:i,awsQueryCompatible:s,jsonCodec:r}){super({defaultNamespace:n,errorTypeRegistries:t,serviceTarget:i,awsQueryCompatible:s,jsonCodec:r})}getShapeId(){return"aws.protocols#awsJson1_1"}getJsonRpcVersion(){return"1.1"}getDefaultContentType(){return"application/x-amz-json-1.1"}}class yR extends rR{serializer;deserializer;codec;mixin=new Vs;constructor({defaultNamespace:n,errorTypeRegistries:t}){super({defaultNamespace:n,errorTypeRegistries:t});let i={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=new tf(i),this.serializer=new eR(this.codec.createSerializer(),i),this.deserializer=new oR(this.codec.createDeserializer(),i)}getShapeId(){return"aws.protocols#restJson1"}getPayloadCodec(){return this.codec}setSerdeContext(n){this.codec.setSerdeContext(n),super.setSerdeContext(n)}async serializeRequest(n,t,i){let s=await super.serializeRequest(n,t,i),r=En.of(n.input);if(!s.headers["content-type"]){let e=this.mixin.resolveRestContentType(this.getDefaultContentType(),r);if(e)s.headers["content-type"]=e}if(s.body==null&&s.headers["content-type"]===this.getDefaultContentType())s.body="{}";return s}async deserializeResponse(n,t,i){let s=await super.deserializeResponse(n,t,i),r=En.of(n.output);for(let[e,f]of r.structIterator())if(f.getMemberTraits().httpPayload&&!(e in s))s[e]=null;return s}async handleError(n,t,i,s,r){let e=lR(i,s)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace);let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,i,s,r),h=En.of(f),u=s.message??s.Message??"UnknownError",_=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({});await this.deserializeHttpMessage(f,t,i,s);let w={},l=this.codec.createDeserializer();for(let[A,d]of h.structIterator()){let E=d.getMergedTraits().jsonName??A;w[A]=l.readObject(d,s[E])}throw this.mixin.decorateServiceException(Object.assign(_,o,{$fault:h.getMergedTraits().error,message:u},w),s)}getDefaultContentType(){return"application/json"}}var qP=(n)=>{if(n==null)return;if(typeof n==="object"&&"__type"in n)delete n.__type;return zP(n)};class rf extends Ai{settings;stringDeserializer;constructor(n){super();this.settings=n,this.stringDeserializer=new YP(n)}setSerdeContext(n){this.serdeContext=n,this.stringDeserializer.setSerdeContext(n)}read(n,t,i){let s=En.of(n),r=s.getMemberSchemas();if(s.isStructSchema()&&s.isMemberSchema()&&!!Object.values(r).find((h)=>{return!!h.getMemberTraits().eventPayload})){let h={},u=Object.keys(r)[0];if(r[u].isBlobSchema())h[u]=t;else h[u]=this.read(r[u],t);return h}let f=(this.serdeContext?.utf8Encoder??fR)(t),o=this.parseXml(f);return this.readSchema(n,i?o[i]:o)}readSchema(n,t){let i=En.of(n);if(i.isUnitSchema())return;let s=i.getMergedTraits();if(i.isListSchema()&&!Array.isArray(t))return this.readSchema(i,[t]);if(t==null)return t;if(typeof t==="object"){let r=!!s.xmlFlattened;if(i.isListSchema()){let f=i.getValueSchema(),o=[],h=f.getMergedTraits().xmlName??"member",u=r?t:(t[0]??t)[h];if(u==null)return o;let c=Array.isArray(u)?u:[u];for(let _ of c)o.push(this.readSchema(f,_));return o}let e={};if(i.isMapSchema()){let f=i.getKeySchema(),o=i.getValueSchema(),h;if(r)h=Array.isArray(t)?t:[t];else h=Array.isArray(t.entry)?t.entry:[t.entry];let u=f.getMergedTraits().xmlName??"key",c=o.getMergedTraits().xmlName??"value";for(let _ of h){let w=_[u],l=_[c];e[w]=this.readSchema(o,l)}return e}if(i.isStructSchema()){let f=i.isUnionSchema(),o;if(f)o=new Zc(t,e);for(let[h,u]of i.structIterator()){let c=u.getMergedTraits(),_=!c.httpPayload?u.getMemberTraits().xmlName??h:c.xmlName??u.getName();if(f)o.mark(_);if(t[_]!=null)e[h]=this.readSchema(u,t[_])}if(f)o.writeUnknown();return e}if(i.isDocumentSchema())return t;throw Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${i.getName(!0)}`)}if(i.isListSchema())return[];if(i.isMapSchema()||i.isStructSchema())return{};return this.stringDeserializer.read(i,t)}parseXml(n){if(n.length){let t;try{t=cR(n)}catch(e){if(e&&typeof e==="object")Object.defineProperty(e,"$responseBodyText",{value:n});throw e}let i="#text",s=Object.keys(t)[0],r=t[s];if(r[i])r[s]=r[i],delete r[i];return iR(r)}return{}}}class i_ extends Ai{settings;buffer;constructor(n){super();this.settings=n}write(n,t,i=""){if(this.buffer===void 0)this.buffer="";let s=En.of(n);if(i&&!i.endsWith("."))i+=".";if(s.isBlobSchema()){if(typeof t==="string"||t instanceof Uint8Array)this.writeKey(i),this.writeValue((this.serdeContext?.base64Encoder??Zo)(t))}else if(s.isBooleanSchema()||s.isNumericSchema()||s.isStringSchema()){if(t!=null)this.writeKey(i),this.writeValue(String(t));else if(s.isIdempotencyToken())this.writeKey(i),this.writeValue(vc())}else if(s.isBigIntegerSchema()){if(t!=null)this.writeKey(i),this.writeValue(String(t))}else if(s.isBigDecimalSchema()){if(t!=null)this.writeKey(i),this.writeValue(t instanceof Bt?t.string:String(t))}else if(s.isTimestampSchema()){if(t instanceof Date)switch(this.writeKey(i),nf(s,this.settings)){case 5:this.writeValue(t.toISOString().replace(".000Z","Z"));break;case 6:this.writeValue(po(t));break;case 7:this.writeValue(String(t.getTime()/1000));break}}else if(s.isDocumentSchema())if(Array.isArray(t))this.write(79,t,i);else if(t instanceof Date)this.write(4,t,i);else if(t instanceof Uint8Array)this.write(21,t,i);else if(t&&typeof t==="object")this.write(143,t,i);else this.writeKey(i),this.writeValue(String(t));else if(s.isListSchema()){if(Array.isArray(t))if(t.length===0){if(this.settings.serializeEmptyLists)this.writeKey(i),this.writeValue("")}else{let r=s.getValueSchema(),e=this.settings.flattenLists||s.getMergedTraits().xmlFlattened,f=1;for(let o of t){if(o==null)continue;let h=r.getMergedTraits(),u=this.getKey("member",h.xmlName,h.ec2QueryName),c=e?`${i}${f}`:`${i}${u}.${f}`;this.write(r,o,c),++f}}}else if(s.isMapSchema()){if(t&&typeof t==="object"){let r=s.getKeySchema(),e=s.getValueSchema(),f=s.getMergedTraits().xmlFlattened,o=1;for(let h in t){let u=t[h];if(u==null)continue;let c=r.getMergedTraits(),_=this.getKey("key",c.xmlName,c.ec2QueryName),w=f?`${i}${o}.${_}`:`${i}entry.${o}.${_}`,l=e.getMergedTraits(),A=this.getKey("value",l.xmlName,l.ec2QueryName),d=f?`${i}${o}.${A}`:`${i}entry.${o}.${A}`;this.write(r,h,w),this.write(e,u,d),++o}}}else if(s.isStructSchema()){if(t&&typeof t==="object"){let r=!1;for(let[e,f]of s.structIterator()){if(t[e]==null&&!f.isIdempotencyToken())continue;let o=f.getMergedTraits(),h=this.getKey(e,o.xmlName,o.ec2QueryName,"struct"),u=`${i}${h}`;this.write(f,t[e],u),r=!0}if(!r&&s.isUnionSchema()){let{$unknown:e}=t;if(Array.isArray(e)){let[f,o]=e,h=`${i}${f}`;this.write(15,o,h)}}}}else if(s.isUnitSchema());else throw Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${s.getName(!0)}`)}flush(){if(this.buffer===void 0)throw Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer.");let n=this.buffer;return delete this.buffer,n}getKey(n,t,i,s){let{ec2:r,capitalizeKeys:e}=this.settings;if(r&&i)return i;let f=t??n;if(e&&s==="struct")return f[0].toUpperCase()+f.slice(1);return f}writeKey(n){if(n.endsWith("."))n=n.slice(0,n.length-1);this.buffer+=`&${v1(n)}=`}writeValue(n){this.buffer+=v1(n)}}class s_ extends sR{options;serializer;deserializer;mixin=new Vs;constructor(n){super({defaultNamespace:n.defaultNamespace,errorTypeRegistries:n.errorTypeRegistries});this.options=n;let t={timestampFormat:{useTrait:!0,default:5},httpBindings:!1,xmlNamespace:n.xmlNamespace,serviceNamespace:n.defaultNamespace,serializeEmptyLists:!0};this.serializer=new i_(t),this.deserializer=new rf(t)}getShapeId(){return"aws.protocols#awsQuery"}setSerdeContext(n){this.serializer.setSerdeContext(n),this.deserializer.setSerdeContext(n)}getPayloadCodec(){throw Error("AWSQuery protocol has no payload codec.")}async serializeRequest(n,t,i){let s=await super.serializeRequest(n,t,i);if(!s.path.endsWith("/"))s.path+="/";if(s.headers["content-type"]="application/x-www-form-urlencoded",tR(n.input)==="unit"||!s.body)s.body="";let r=n.name.split("#")[1]??n.name;if(s.body=`Action=${r}&Version=${this.options.version}`+s.body,s.body.endsWith("&"))s.body=s.body.slice(-1);return s}async deserializeResponse(n,t,i){let s=this.deserializer,r=En.of(n.output),e={};if(i.statusCode>=300){let u=await ac(i.body,t);if(u.byteLength>0)Object.assign(e,await s.read(15,u));await this.handleError(n,t,i,e,this.deserializeMetadata(i))}for(let u in i.headers){let c=i.headers[u];delete i.headers[u],i.headers[u.toLowerCase()]=c}let f=n.name.split("#")[1]??n.name,o=r.isStructSchema()&&this.useNestedResult()?f+"Result":void 0,h=await ac(i.body,t);if(h.byteLength>0)Object.assign(e,await s.read(r,h,o));return e.$metadata=this.deserializeMetadata(i),e}useNestedResult(){return!0}async handleError(n,t,i,s,r){let e=this.loadQueryErrorCode(i,s)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace);let f=this.loadQueryError(s)??{},o=this.loadQueryErrorMessage(s);f.message=o,f.Error={Type:f.Type,Code:f.Code,Message:o};let{errorSchema:h,errorMetadata:u}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,i,f,r,this.mixin.findQueryCompatibleError),c=En.of(h),w=new(this.compositeErrorRegistry.getErrorCtor(h)??Error)({}),l={Type:f.Error.Type,Code:f.Error.Code,Error:f.Error};for(let[A,d]of c.structIterator()){let E=d.getMergedTraits().xmlName??A,R=f[E]??s[E];l[A]=this.deserializer.readSchema(d,R)}throw this.mixin.decorateServiceException(Object.assign(w,u,{$fault:c.getMergedTraits().error,message:o},l),s)}loadQueryErrorCode(n,t){let i=(t.Errors?.[0]?.Error??t.Errors?.Error??t.Error)?.Code;if(i!==void 0)return i;if(n.statusCode==404)return"NotFound"}loadQueryError(n){return n.Errors?.[0]?.Error??n.Errors?.Error??n.Error}loadQueryErrorMessage(n){let t=this.loadQueryError(n);return t?.message??t?.Message??n.message??n.Message??"Unknown"}getDefaultContentType(){return"application/x-www-form-urlencoded"}}class TR extends s_{options;constructor(n){super(n);this.options=n;let t={capitalizeKeys:!0,flattenLists:!0,serializeEmptyLists:!1,ec2:!0};Object.assign(this.serializer.settings,t)}getShapeId(){return"aws.protocols#ec2Query"}useNestedResult(){return!1}}var gR=(n,t)=>wR(n,t).then((i)=>{if(i.length){let s;try{s=cR(i)}catch(o){if(o&&typeof o==="object")Object.defineProperty(o,"$responseBodyText",{value:i});throw o}let r="#text",e=Object.keys(s)[0],f=s[e];if(f[r])f[e]=f[r],delete f[r];return iR(f)}return{}}),VP=async(n,t)=>{let i=await gR(n,t);if(i.Error)i.Error.message=i.Error.message??i.Error.Message;return i},SR=(n,t)=>{if(t?.Error?.Code!==void 0)return t.Error.Code;if(t?.Code!==void 0)return t.Code;if(n.statusCode==404)return"NotFound"};class r_ extends Ai{settings;stringBuffer;byteBuffer;buffer;constructor(n){super();this.settings=n}write(n,t){let i=En.of(n);if(i.isStringSchema()&&typeof t==="string")this.stringBuffer=t;else if(i.isBlobSchema())this.byteBuffer="byteLength"in t?t:(this.serdeContext?.base64Decoder??hR)(t);else{this.buffer=this.writeStruct(i,t,void 0);let s=i.getMergedTraits();if(s.httpPayload&&!s.xmlName)this.buffer.withName(i.getName())}}flush(){if(this.byteBuffer!==void 0){let t=this.byteBuffer;return delete this.byteBuffer,t}if(this.stringBuffer!==void 0){let t=this.stringBuffer;return delete this.stringBuffer,t}let n=this.buffer;if(this.settings.xmlNamespace){if(!n?.attributes?.xmlns)n.addAttribute("xmlns",this.settings.xmlNamespace)}return delete this.buffer,n.toString()}writeStruct(n,t,i){let s=n.getMergedTraits(),r=n.isMemberSchema()&&!s.httpPayload?n.getMemberTraits().xmlName??n.getMemberName():s.xmlName??n.getName();if(!r||!n.isStructSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${n.getName(!0)}.`);let e=wt.of(r),[f,o]=this.getXmlnsAttribute(n,i);for(let[u,c]of n.structIterator()){let _=t[u];if(_!=null||c.isIdempotencyToken()){if(c.getMergedTraits().xmlAttribute){e.addAttribute(c.getMergedTraits().xmlName??u,this.writeSimple(c,_));continue}if(c.isListSchema())this.writeList(c,_,e,o);else if(c.isMapSchema())this.writeMap(c,_,e,o);else if(c.isStructSchema())e.addChildNode(this.writeStruct(c,_,o));else{let w=wt.of(c.getMergedTraits().xmlName??c.getMemberName());this.writeSimpleInto(c,_,w,o),e.addChildNode(w)}}}let{$unknown:h}=t;if(h&&n.isUnionSchema()&&Array.isArray(h)&&Object.keys(t).length===1){let[u,c]=h,_=wt.of(u);if(typeof c!=="string")if(t instanceof wt||t instanceof Z1)e.addChildNode(t);else throw Error("@aws-sdk - $unknown union member in XML requires value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.");this.writeSimpleInto(0,c,_,o),e.addChildNode(_)}if(o)e.addAttribute(f,o);return e}writeList(n,t,i,s){if(!n.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${n.getName(!0)}`);let r=n.getMergedTraits(),e=n.getValueSchema(),f=e.getMergedTraits(),o=!!f.sparse,h=!!r.xmlFlattened,[u,c]=this.getXmlnsAttribute(n,s),_=(w,l)=>{if(e.isListSchema())this.writeList(e,Array.isArray(l)?l:[l],w,c);else if(e.isMapSchema())this.writeMap(e,l,w,c);else if(e.isStructSchema()){let A=this.writeStruct(e,l,c);w.addChildNode(A.withName(h?r.xmlName??n.getMemberName():f.xmlName??"member"))}else{let A=wt.of(h?r.xmlName??n.getMemberName():f.xmlName??"member");this.writeSimpleInto(e,l,A,c),w.addChildNode(A)}};if(h){for(let w of t)if(o||w!=null)_(i,w)}else{let w=wt.of(r.xmlName??n.getMemberName());if(c)w.addAttribute(u,c);for(let l of t)if(o||l!=null)_(w,l);i.addChildNode(w)}}writeMap(n,t,i,s,r=!1){if(!n.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${n.getName(!0)}`);let e=n.getMergedTraits(),f=n.getKeySchema(),h=f.getMergedTraits().xmlName??"key",u=n.getValueSchema(),c=u.getMergedTraits(),_=c.xmlName??"value",w=!!c.sparse,l=!!e.xmlFlattened,[A,d]=this.getXmlnsAttribute(n,s),E=(R,y,T)=>{let S=wt.of(h,y),[I,F]=this.getXmlnsAttribute(f,d);if(F)S.addAttribute(I,F);R.addChildNode(S);let C=wt.of(_);if(u.isListSchema())this.writeList(u,T,C,d);else if(u.isMapSchema())this.writeMap(u,T,C,d,!0);else if(u.isStructSchema())C=this.writeStruct(u,T,d);else this.writeSimpleInto(u,T,C,d);R.addChildNode(C)};if(l)for(let R in t){let y=t[R];if(w||y!=null){let T=wt.of(e.xmlName??n.getMemberName());E(T,R,y),i.addChildNode(T)}}else{let R;if(!r){if(R=wt.of(e.xmlName??n.getMemberName()),d)R.addAttribute(A,d);i.addChildNode(R)}for(let y in t){let T=t[y];if(w||T!=null){let S=wt.of("entry");E(S,y,T),(r?i:R).addChildNode(S)}}}}writeSimple(n,t){if(t===null)throw Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value.");let i=En.of(n),s=null;if(t&&typeof t==="object")if(i.isBlobSchema())s=(this.serdeContext?.base64Encoder??Zo)(t);else if(i.isTimestampSchema()&&t instanceof Date)switch(nf(i,this.settings)){case 5:s=t.toISOString().replace(".000Z","Z");break;case 6:s=po(t);break;case 7:s=String(t.getTime()/1000);break;default:console.warn("Missing timestamp format, using http date",t),s=po(t);break}else if(i.isBigDecimalSchema()&&t){if(t instanceof Bt)return t.string;return String(t)}else if(i.isMapSchema()||i.isListSchema())throw Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead.");else throw Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${i.getName(!0)}`);if(i.isBooleanSchema()||i.isNumericSchema()||i.isBigIntegerSchema()||i.isBigDecimalSchema())s=String(t);if(i.isStringSchema())if(t===void 0&&i.isIdempotencyToken())s=vc();else s=String(t);if(s===null)throw Error(`Unhandled schema-value pair ${i.getName(!0)}=${t}`);return s}writeSimpleInto(n,t,i,s){let r=this.writeSimple(n,t),e=En.of(n),f=new Z1(r),[o,h]=this.getXmlnsAttribute(e,s);if(h)i.addAttribute(o,h);i.addChildNode(f)}getXmlnsAttribute(n,t){let i=n.getMergedTraits(),[s,r]=i.xmlNamespace??[];if(r&&r!==t)return[s?`xmlns:${s}`:"xmlns",r];return[void 0,void 0]}}class e_ extends Ai{settings;constructor(n){super();this.settings=n}createSerializer(){let n=new r_(this.settings);return n.setSerdeContext(this.serdeContext),n}createDeserializer(){let n=new rf(this.settings);return n.setSerdeContext(this.serdeContext),n}}class IR extends rR{codec;serializer;deserializer;mixin=new Vs;constructor(n){super(n);let t={timestampFormat:{useTrait:!0,default:5},httpBindings:!0,xmlNamespace:n.xmlNamespace,serviceNamespace:n.defaultNamespace};this.codec=new e_(t),this.serializer=new eR(this.codec.createSerializer(),t),this.deserializer=new oR(this.codec.createDeserializer(),t)}getPayloadCodec(){return this.codec}getShapeId(){return"aws.protocols#restXml"}async serializeRequest(n,t,i){let s=await super.serializeRequest(n,t,i),r=En.of(n.input);if(!s.headers["content-type"]){let e=this.mixin.resolveRestContentType(this.getDefaultContentType(),r);if(e)s.headers["content-type"]=e}if(typeof s.body==="string"&&s.headers["content-type"]===this.getDefaultContentType()&&!s.body.startsWith("<?xml ")&&!this.hasUnstructuredPayloadBinding(r))s.body='<?xml version="1.0" encoding="UTF-8"?>'+s.body;return s}async deserializeResponse(n,t,i){return super.deserializeResponse(n,t,i)}async handleError(n,t,i,s,r){let e=SR(i,s)??"Unknown";if(this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace),s.Error&&typeof s.Error==="object"){for(let A of Object.keys(s.Error))if(s[A]=s.Error[A],A.toLowerCase()==="message")s.message=s.Error[A]}if(s.RequestId&&!r.requestId)r.requestId=s.RequestId;let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,i,s,r),h=En.of(f),u=s.Error?.message??s.Error?.Message??s.message??s.Message??"UnknownError",_=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({});await this.deserializeHttpMessage(f,t,i,s);let w={},l=this.codec.createDeserializer();for(let[A,d]of h.structIterator()){let E=d.getMergedTraits().xmlName??A,R=s.Error?.[E]??s[E];w[A]=l.readSchema(d,R)}throw this.mixin.decorateServiceException(Object.assign(_,o,{$fault:h.getMergedTraits().error,message:u},w),s)}getDefaultContentType(){return"application/xml"}hasUnstructuredPayloadBinding(n){for(let[,t]of n.structIterator())if(t.getMergedTraits().httpPayload)return!(t.isStructSchema()||t.isMapSchema()||t.isListSchema());return!1}}jP.AwsEc2QueryProtocol=TR;jP.AwsJson1_0Protocol=RR;jP.AwsJson1_1Protocol=ER;jP.AwsJsonRpcProtocol=sf;jP.AwsQueryProtocol=s_;jP.AwsRestJsonProtocol=yR;jP.AwsRestXmlProtocol=IR;jP.AwsSmithyRpcV2CborProtocol=_R;jP.JsonCodec=tf;jP.JsonShapeDeserializer=n_;jP.JsonShapeSerializer=t_;jP.QueryShapeSerializer=i_;jP.XmlCodec=e_;jP.XmlShapeDeserializer=rf;jP.XmlShapeSerializer=r_;jP._toBool=CP;jP._toNum=xP;jP._toStr=QP;jP.awsExpectUnion=qP;jP.loadJsonRpcErrorCode=AR;jP.loadRestJsonErrorCode=lR;jP.loadRestXmlErrorCode=SR;jP.parseJsonBody=pc;jP.parseJsonErrorBody=kP;jP.parseXmlBody=gR;jP.parseXmlErrorBody=VP});var w_=k((D9)=>{var{awsEndpointFunctions:SD,emitWarningIfUnsupportedVersion:ID,createDefaultUserAgentProvider:UD,NODE_APP_ID_CONFIG_OPTIONS:bD,getAwsRegionExtensionConfiguration:$D,resolveAwsRegionExtensionConfiguration:LD,resolveUserAgentConfig:OD,resolveHostHeaderConfig:BD,getUserAgentPlugin:ND,getHostHeaderPlugin:GD,getLoggerPlugin:HD,getRecursionDetectionPlugin:WD}=ct(),{NoAuthSigner:FD,getHttpAuthSchemeEndpointRuleSetPlugin:PD,DefaultIdentityProviderConfig:DD,getHttpSigningPlugin:YD}=_i(),{normalizeProvider:OR,getSmithyContext:mD,ServiceException:JD,NoOpLogger:XD,emitWarningIfUnsupportedVersion:zD,loadConfigsForDefaultMode:QD,getDefaultExtensionConfiguration:CD,resolveDefaultRuntimeConfig:xD,Client:BR,makeBuilder:KD,createAggregatedClient:kD}=Xt(),{Command:qD}=Xt();D9.$Command=qD;D9.__Client=BR;var{resolveDefaultsModeConfig:VD,loadConfig:ki,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:jD,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:aD,NODE_REGION_CONFIG_OPTIONS:vD,NODE_REGION_CONFIG_FILE_OPTIONS:ZD,resolveRegionConfig:pD}=Yn(),{BinaryDecisionDiagram:n7,EndpointCache:t7,decideEndpoint:i7,customEndpointFunctions:s7,resolveEndpointConfig:r7,getEndpointPlugin:e7}=Ji(),{parseUrl:o7,getHttpHandlerExtensionConfiguration:f7,resolveHttpHandlerRuntimeConfig:h7,getContentLengthPlugin:u7}=Jn(),{DEFAULT_RETRY_MODE:c7,NODE_RETRY_MODE_CONFIG_OPTIONS:_7,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:w7,resolveRetryConfig:l7,getRetryPlugin:A7}=Zr(),{TypeRegistry:NR,getSchemaSerdePlugin:M7}=ri(),{resolveAwsSdkSigV4Config:d7,AwsSdkSigV4Signer:R7,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:E7}=Oc(),{toUtf8:y7,fromUtf8:T7,toBase64:g7,fromBase64:S7,calculateBodyLength:I7}=mn(),{streamCollector:U7,NodeHttpHandler:b7}=jo(),{AwsRestJsonProtocol:$7}=o_(),{Sha256:L7}=Wu(),O7=async(n,t,i)=>{return{operation:mD(t).operation,region:await OR(n.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()}};function B7(n){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:n.region},propertiesExtractor:(t,i)=>({signingProperties:{config:t,context:i}})}}function N7(n){return{schemeId:"smithy.api#noAuth"}}var G7=(n)=>{let t=[];switch(n.operation){case"CreateToken":{t.push(N7());break}default:t.push(B7(n))}return t},H7=(n)=>{let t=d7(n);return Object.assign(t,{authSchemePreference:OR(n.authSchemePreference??[])})},W7=(n)=>{return Object.assign(n,{useDualstackEndpoint:n.useDualstackEndpoint??!1,useFipsEndpoint:n.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"})},F7={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},P7="3.997.32",D7={version:P7},_e="ref",qi=-1,ef=!0,UR="isSet",GR="PartitionResult",of="booleanEquals",f_="getAttr",bR={[_e]:"Endpoint"},h_={[_e]:GR},js={},$R=[{[_e]:"Region"}],LR={conditions:[[UR,[bR]],[UR,$R],["aws.partition",$R,GR],[of,[{[_e]:"UseFIPS"},ef]],[of,[{[_e]:"UseDualStack"},ef]],[of,[{fn:f_,argv:[h_,"supportsDualStack"]},ef]],[of,[{fn:f_,argv:[h_,"supportsFIPS"]},ef]],["stringEquals",[{fn:f_,argv:[h_,"name"]},"aws-us-gov"]]],results:[[qi],[qi,"Invalid Configuration: FIPS and custom endpoint are not supported"],[qi,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[bR,js],["https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",js],[qi,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://oidc.{Region}.amazonaws.com",js],["https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",js],[qi,"FIPS is enabled but this partition does not support FIPS"],["https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",js],[qi,"DualStack is enabled but this partition does not support DualStack"],["https://oidc.{Region}.{PartitionResult#dnsSuffix}",js],[qi,"Invalid Configuration: Missing Region"]]},Y7=2,Xn=1e8,m7=new Int32Array([-1,1,-1,0,13,3,1,4,Xn+12,2,5,Xn+12,3,8,6,4,7,Xn+11,5,Xn+9,Xn+10,4,11,9,6,10,Xn+8,7,Xn+6,Xn+7,5,12,Xn+5,6,Xn+4,Xn+5,3,Xn+1,14,4,Xn+2,Xn+3]),J7=n7.from(m7,Y7,LR.conditions,LR.results),X7=new t7({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),z7=(n,t={})=>{return X7.get(n,()=>i7(J7,{endpointParams:n,logger:t.logger}))};s7.aws=SD;class Fn extends JD{constructor(n){super(n);Object.setPrototypeOf(this,Fn.prototype)}}class ff extends Fn{name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(n){super({name:"AccessDeniedException",$fault:"client",...n});Object.setPrototypeOf(this,ff.prototype),this.error=n.error,this.reason=n.reason,this.error_description=n.error_description}}class hf extends Fn{name="AuthorizationPendingException";$fault="client";error;error_description;constructor(n){super({name:"AuthorizationPendingException",$fault:"client",...n});Object.setPrototypeOf(this,hf.prototype),this.error=n.error,this.error_description=n.error_description}}class uf extends Fn{name="ExpiredTokenException";$fault="client";error;error_description;constructor(n){super({name:"ExpiredTokenException",$fault:"client",...n});Object.setPrototypeOf(this,uf.prototype),this.error=n.error,this.error_description=n.error_description}}class cf extends Fn{name="InternalServerException";$fault="server";error;error_description;constructor(n){super({name:"InternalServerException",$fault:"server",...n});Object.setPrototypeOf(this,cf.prototype),this.error=n.error,this.error_description=n.error_description}}class _f extends Fn{name="InvalidClientException";$fault="client";error;error_description;constructor(n){super({name:"InvalidClientException",$fault:"client",...n});Object.setPrototypeOf(this,_f.prototype),this.error=n.error,this.error_description=n.error_description}}class wf extends Fn{name="InvalidGrantException";$fault="client";error;error_description;constructor(n){super({name:"InvalidGrantException",$fault:"client",...n});Object.setPrototypeOf(this,wf.prototype),this.error=n.error,this.error_description=n.error_description}}class lf extends Fn{name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(n){super({name:"InvalidRequestException",$fault:"client",...n});Object.setPrototypeOf(this,lf.prototype),this.error=n.error,this.reason=n.reason,this.error_description=n.error_description}}class Af extends Fn{name="InvalidScopeException";$fault="client";error;error_description;constructor(n){super({name:"InvalidScopeException",$fault:"client",...n});Object.setPrototypeOf(this,Af.prototype),this.error=n.error,this.error_description=n.error_description}}class Mf extends Fn{name="SlowDownException";$fault="client";error;error_description;constructor(n){super({name:"SlowDownException",$fault:"client",...n});Object.setPrototypeOf(this,Mf.prototype),this.error=n.error,this.error_description=n.error_description}}class df extends Fn{name="UnauthorizedClientException";$fault="client";error;error_description;constructor(n){super({name:"UnauthorizedClientException",$fault:"client",...n});Object.setPrototypeOf(this,df.prototype),this.error=n.error,this.error_description=n.error_description}}class Rf extends Fn{name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(n){super({name:"UnsupportedGrantTypeException",$fault:"client",...n});Object.setPrototypeOf(this,Rf.prototype),this.error=n.error,this.error_description=n.error_description}}var Q7="AccessDeniedException",C7="AuthorizationPendingException",x7="AccessToken",K7="ClientSecret",k7="CreateToken",q7="CreateTokenRequest",V7="CreateTokenResponse",j7="CodeVerifier",a7="ExpiredTokenException",v7="InvalidClientException",Z7="InvalidGrantException",p7="InvalidRequestException",n9="InternalServerException",t9="InvalidScopeException",i9="IdToken",s9="RefreshToken",r9="SlowDownException",e9="UnauthorizedClientException",o9="UnsupportedGrantTypeException",f9="accessToken",Nt="client",h9="clientId",u9="clientSecret",c9="codeVerifier",_9="code",w9="deviceCode",dn="error",l9="expiresIn",lt="error_description",A9="grantType",M9="http",At="httpError",d9="idToken",HR="reason",WR="refreshToken",R9="redirectUri",FR="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",E9="scope",y9="server",T9="tokenType",yn="com.amazonaws.ssooidc",PR=NR.for(FR),DR=[-3,FR,"SSOOIDCServiceException",0,[],[]];PR.registerError(DR,Fn);var tt=NR.for(yn),YR=[-3,yn,Q7,{[dn]:Nt,[At]:400},[dn,HR,lt],[0,0,0]];tt.registerError(YR,ff);var mR=[-3,yn,C7,{[dn]:Nt,[At]:400},[dn,lt],[0,0]];tt.registerError(mR,hf);var JR=[-3,yn,a7,{[dn]:Nt,[At]:400},[dn,lt],[0,0]];tt.registerError(JR,uf);var XR=[-3,yn,n9,{[dn]:y9,[At]:500},[dn,lt],[0,0]];tt.registerError(XR,cf);var zR=[-3,yn,v7,{[dn]:Nt,[At]:401},[dn,lt],[0,0]];tt.registerError(zR,_f);var QR=[-3,yn,Z7,{[dn]:Nt,[At]:400},[dn,lt],[0,0]];tt.registerError(QR,wf);var CR=[-3,yn,p7,{[dn]:Nt,[At]:400},[dn,HR,lt],[0,0,0]];tt.registerError(CR,lf);var xR=[-3,yn,t9,{[dn]:Nt,[At]:400},[dn,lt],[0,0]];tt.registerError(xR,Af);var KR=[-3,yn,r9,{[dn]:Nt,[At]:400},[dn,lt],[0,0]];tt.registerError(KR,Mf);var kR=[-3,yn,e9,{[dn]:Nt,[At]:400},[dn,lt],[0,0]];tt.registerError(kR,df);var qR=[-3,yn,o9,{[dn]:Nt,[At]:400},[dn,lt],[0,0]];tt.registerError(qR,Rf);var VR=[PR,tt],g9=[0,yn,x7,8,0],S9=[0,yn,K7,8,0],I9=[0,yn,j7,8,0],U9=[0,yn,i9,8,0],jR=[0,yn,s9,8,0],aR=[3,yn,q7,0,[h9,u9,A9,w9,_9,WR,E9,R9,c9],[0,[()=>S9,0],0,0,0,[()=>jR,0],64,0,[()=>I9,0]],3],vR=[3,yn,V7,0,[f9,T9,l9,WR,d9],[[()=>g9,0],0,1,[()=>jR,0],[()=>U9,0]]],ZR=[9,yn,k7,{[M9]:["POST","/token",200]},()=>aR,()=>vR],b9=(n)=>{return{apiVersion:"2019-06-10",base64Decoder:n?.base64Decoder??S7,base64Encoder:n?.base64Encoder??g7,disableHostPrefix:n?.disableHostPrefix??!1,endpointProvider:n?.endpointProvider??z7,extensions:n?.extensions??[],httpAuthSchemeProvider:n?.httpAuthSchemeProvider??G7,httpAuthSchemes:n?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(t)=>t.getIdentityProvider("aws.auth#sigv4"),signer:new R7},{schemeId:"smithy.api#noAuth",identityProvider:(t)=>t.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new FD}],logger:n?.logger??new XD,protocol:n?.protocol??$7,protocolSettings:n?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:VR,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:n?.serviceId??"SSO OIDC",sha256:n?.sha256??L7,urlParser:n?.urlParser??o7,utf8Decoder:n?.utf8Decoder??T7,utf8Encoder:n?.utf8Encoder??y7}},$9=(n)=>{zD(process.version);let t=VD(n),i=()=>t().then(QD),s=b9(n);ID(process.version);let r={profile:n?.profile,logger:s.logger};return{...s,...n,runtime:"node",defaultsMode:t,authSchemePreference:n?.authSchemePreference??ki(E7,r),bodyLengthChecker:n?.bodyLengthChecker??I7,defaultUserAgentProvider:n?.defaultUserAgentProvider??UD({serviceId:s.serviceId,clientVersion:D7.version}),maxAttempts:n?.maxAttempts??ki(w7,n),region:n?.region??ki(vD,{...ZD,...r}),requestHandler:b7.create(n?.requestHandler??i),retryMode:n?.retryMode??ki({..._7,default:async()=>(await i()).retryMode||c7},n),streamCollector:n?.streamCollector??U7,useDualstackEndpoint:n?.useDualstackEndpoint??ki(aD,r),useFipsEndpoint:n?.useFipsEndpoint??ki(jD,r),userAgentAppId:n?.userAgentAppId??ki(bD,r)}},L9=(n)=>{let{httpAuthSchemes:t,httpAuthSchemeProvider:i,credentials:s}=n;return{setHttpAuthScheme(r){let e=t.findIndex((f)=>f.schemeId===r.schemeId);if(e===-1)t.push(r);else t.splice(e,1,r)},httpAuthSchemes(){return t},setHttpAuthSchemeProvider(r){i=r},httpAuthSchemeProvider(){return i},setCredentials(r){s=r},credentials(){return s}}},O9=(n)=>{return{httpAuthSchemes:n.httpAuthSchemes(),httpAuthSchemeProvider:n.httpAuthSchemeProvider(),credentials:n.credentials()}},B9=(n,t)=>{let i=Object.assign($D(n),CD(n),f7(n),L9(n));return t.forEach((s)=>s.configure(i)),Object.assign(n,LD(i),xD(i),h7(i),O9(i))};class u_ extends BR{config;constructor(...[n]){let t=$9(n||{});super(t);this.initConfig=t;let i=W7(t),s=OD(i),r=l7(s),e=pD(r),f=BD(e),o=r7(f),h=H7(o),u=B9(h,n?.extensions||[]);this.config=u,this.middlewareStack.use(M7(this.config)),this.middlewareStack.use(ND(this.config)),this.middlewareStack.use(A7(this.config)),this.middlewareStack.use(u7(this.config)),this.middlewareStack.use(GD(this.config)),this.middlewareStack.use(HD(this.config)),this.middlewareStack.use(WD(this.config)),this.middlewareStack.use(PD(this.config,{httpAuthSchemeParametersProvider:O7,identityProviderConfigProvider:async(c)=>new DD({"aws.auth#sigv4":c.credentials})})),this.middlewareStack.use(YD(this.config))}destroy(){super.destroy()}}var N9=KD(F7,"AWSSSOOIDCService","SSOOIDCClient",e7),G9={},H9=(n,t,i,s)=>[];class c_ extends N9(G9,H9,"CreateToken",ZR){}var W9={CreateTokenCommand:c_};class __ extends u_{}kD(W9,__);var F9={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},P9={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"};D9.AccessDeniedException=ff;D9.AccessDeniedException$=YR;D9.AccessDeniedExceptionReason=F9;D9.AuthorizationPendingException=hf;D9.AuthorizationPendingException$=mR;D9.CreateToken$=ZR;D9.CreateTokenCommand=c_;D9.CreateTokenRequest$=aR;D9.CreateTokenResponse$=vR;D9.ExpiredTokenException=uf;D9.ExpiredTokenException$=JR;D9.InternalServerException=cf;D9.InternalServerException$=XR;D9.InvalidClientException=_f;D9.InvalidClientException$=zR;D9.InvalidGrantException=wf;D9.InvalidGrantException$=QR;D9.InvalidRequestException=lf;D9.InvalidRequestException$=CR;D9.InvalidRequestExceptionReason=P9;D9.InvalidScopeException=Af;D9.InvalidScopeException$=xR;D9.SSOOIDC=__;D9.SSOOIDCClient=u_;D9.SSOOIDCServiceException=Fn;D9.SSOOIDCServiceException$=DR;D9.SlowDownException=Mf;D9.SlowDownException$=KR;D9.UnauthorizedClientException=df;D9.UnauthorizedClientException$=kR;D9.UnsupportedGrantTypeException=Rf;D9.UnsupportedGrantTypeException$=qR;D9.errorTypeRegistries=VR});import{Database as JT}from"bun:sqlite";import{existsSync as XT}from"fs";import{homedir as o0}from"os";import{dirname as zT,join as ge}from"path";var f0=5000,QT=30000,CT=25,xT=500,KT=new Set(["id","email","auth_method","region","oidc_region","client_id","client_secret","profile_arn","start_url","refresh_token","access_token","expires_at","rate_limit_reset","is_healthy","unhealthy_reason","recovery_time","fail_count","last_used","used_count","limit_count","last_sync","overage_count"]);class or extends Error{constructor(n,t){super(n,t);this.name="OpenCodeAuthStoreError"}}function kT(n){if(typeof n!=="object"||n===null||!("code"in n))return!1;return String(n.code).toUpperCase().startsWith("SQLITE_BUSY")}function qT(n,t){let i=Math.min(CT*2**Math.min(n,5),xT,t),s=Math.max(1,Math.floor(i/2)),r=s+Math.floor(Math.random()*(i-s+1));Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,r)}function gi(n){return{id:n.id,email:n.email,authMethod:n.auth_method,region:n.region,oidcRegion:n.oidc_region??void 0,clientId:n.client_id??void 0,clientSecret:n.client_secret??void 0,profileArn:n.profile_arn??void 0,startUrl:n.start_url??void 0,refreshToken:n.refresh_token,accessToken:n.access_token,expiresAt:n.expires_at,rateLimitResetTime:n.rate_limit_reset??0,isHealthy:(n.is_healthy??1)===1,unhealthyReason:n.unhealthy_reason??void 0,recoveryTime:n.recovery_time??void 0,failCount:n.fail_count??0,lastUsed:n.last_used??0,usedCount:n.used_count??0,limitCount:n.limit_count??0,lastSync:n.last_sync??0,overageCount:n.overage_count??0}}function VT(n,t){return t.refreshToken===n.refreshToken&&t.accessToken===n.accessToken&&t.expiresAt===n.expiresAt&&t.authMethod===n.authMethod&&t.clientId===n.clientId&&t.clientSecret===n.clientSecret&&t.profileArn===n.profileArn&&t.email===n.email&&t.startUrl===n.startUrl}function fr(n=process.env){let t=process.platform==="win32"?n.APPDATA??ge(o0(),"AppData","Roaming"):n.XDG_CONFIG_HOME??ge(o0(),".config");return ge(t,"opencode","kiro.db")}function h0(n){return ge(zT(n),"kiro-auth-plugin")}class pf{path;db;constructor(n=fr()){this.path=n;if(!XT(n))throw new or(`OpenCode Kiro auth database not found: ${n}. Run OpenCode Kiro authentication first or set auth_source to "local".`);this.db=new JT(n,{strict:!0}),this.db.run(`PRAGMA busy_timeout = ${f0}`),this.validateSchema()}getAccounts(){return this.db.query(`
|
|
47
|
+
>/`.includes(n.x[n.i]))t+=n.x[n.i++];let i=!1,r=Object.create(null);while(n.i<n.z){if(n.trim(),">/".includes(n.x[n.i]))break;let o="";while(n.i<n.z&&!`= \r
|
|
48
|
+
>/?`.includes(n.x[n.i]))o+=n.x[n.i++];if(n.trim(),n.x[n.i]!=="=")break;++n.i,n.trim(),r[o]=n.readAttrValue(),i=!0}if(n.i>=n.z)throw Error("@aws-sdk XML parse error: unexpected end of input.");if(n.x[n.i]==="/"){if(++n.i,n.i>=n.z||n.x[n.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of self-closing tag.");return++n.i,Object.setPrototypeOf(r,Object.prototype),{tag:t,value:i?r:""}}if(n.x[n.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of opening tag.");++n.i;let s=[],f=[],h=!1;while(n.i<n.z){if(n.isNext("</"))break;if(n.x[n.i]==="<")if(n.isNext("<!--"))n.readTo("-->");else if(n.isNext("<![CDATA["))n.i+=9,s.push(n.readTo("]]>"));else if(n.isNext("<?"))n.readTo("?>");else h=!0,f.push(n.parseTag());else{let o="";while(n.i<n.z&&n.x[n.i]!=="<")o+=n.x[n.i++];s.push(n.decodeEntities(o))}}if(!n.isNext("</"))throw Error(`@aws-sdk XML parse error: missing closing tag </${t}>.`);n.i+=2;let _=n.readTo(">").trim();if(_!==t)throw Error(`@aws-sdk XML parse error: mismatched tags <${t}> and </${_}>.`);if(!i&&s.length===0&&!h)return{tag:t,value:""};if(!i&&!h){let o=s.length===1?s[0]:s.join("");if(o.trim()===""&&o.includes(`
|
|
49
|
+
`))return{tag:t,value:""};return{tag:t,value:o}}let c=Object.create(null);for(let o of s){if(o.trim()===""&&o.includes(`
|
|
50
|
+
`))continue;c["#text"]="#text"in c?c["#text"]+o:o}for(let o of f)if(o.tag in c)if(Array.isArray(c[o.tag]))c[o.tag].push(o.value);else c[o.tag]=[c[o.tag],o.value];else c[o.tag]=o.value;for(let[o,w]of Object.entries(r))c[o]=w;return Object.setPrototypeOf(c,Object.prototype),{tag:t,value:c}}static ENTITIES={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};skipDoctype(){let n=this;n.i+=9;let t=0;while(n.i<n.z){let i=n.x[n.i];if(i==="[")++t;else if(i==="]")--t;else if(i===">"&&t===0){++n.i;return}++n.i}throw Error("@aws-sdk XML parse error: unclosed DOCTYPE.")}decodeEntities(n){return n.replace(/&(?:#x([0-9a-fA-F]{1,6})|#(\d{1,7})|([a-zA-Z][a-zA-Z0-9]{0,30}));/g,(t,i,r,s)=>{if(i)return String.fromCharCode(parseInt(i,16));if(r)return String.fromCharCode(parseInt(r,10));return dw.ENTITIES[s]??""})}}xP.XmlNode=Nf;xP.XmlText=yw;xP.parseXML=KP});var bw=nn((oY)=>{var{SmithyRpcV2CborProtocol:mP,loadSmithyRpcV2CborErrorCode:ZP}=GM(),{TypeRegistry:DM,NormalizedSchema:Un,deref:JM}=Ei(),{decorateServiceException:PM,getValueFromTextNode:QM}=at(),{collectBody:Rw,determineTimestampFormat:Ah,RpcProtocol:zM,HttpBindingProtocol:CM,HttpInterceptingShapeSerializer:VM,HttpInterceptingShapeDeserializer:KM,FromStringShapeDeserializer:aP,extendedEncodeURIComponent:YM}=kn(),{NumericValue:Qt,toUtf8:xM,fromBase64:jM,LazyJsonString:kM,parseEpochTimestamp:vP,parseRfc7231DateTime:pP,parseRfc3339DateTimeWithOffset:nY,toBase64:yh,dateToUtcString:dh,generateIdempotencyToken:Mw,expectUnion:tY}=jn(),{parseXML:qM,XmlNode:Lt,XmlText:FM}=WM();class cs{queryCompat;errorRegistry;constructor(n=!1){this.queryCompat=n}resolveRestContentType(n,t){let i=t.getMemberSchemas(),r=Object.values(i).find((s)=>{return!!s.getMergedTraits().httpPayload});if(r){let s=r.getMergedTraits().mediaType;if(s)return s;else if(r.isStringSchema())return"text/plain";else if(r.isBlobSchema())return"application/octet-stream";else return n}else if(!t.isUnitSchema()){if(Object.values(i).find((f)=>{let{httpQuery:h,httpQueryParams:_,httpHeader:c,httpLabel:o,httpPrefixHeaders:w}=f.getMergedTraits();return!h&&!_&&!c&&!o&&w===void 0}))return n}}async getErrorSchemaOrThrowBaseException(n,t,i,r,s,f){let h=n;if(n.includes("#"))[,h]=n.split("#");let _={$metadata:s,$fault:i.statusCode<500?"client":"server"};if(!this.errorRegistry)throw Error("@aws-sdk/core/protocols - error handler not initialized.");try{return{errorSchema:f?.(this.errorRegistry,h)??this.errorRegistry.getSchema(n),errorMetadata:_}}catch(c){r.message=r.message??r.Message??"UnknownError";let o=this.errorRegistry,w=o.getBaseException();if(w){let y=o.getErrorCtor(w)??Error;throw this.decorateServiceException(Object.assign(new y({name:h}),_),r)}let e=r,u=e?.message??e?.Message??e?.Error?.Message??e?.Error?.message;throw this.decorateServiceException(Object.assign(Error(u),{name:h},_),r)}}compose(n,t,i){let r=i;if(t.includes("#"))[r]=t.split("#");let s=DM.for(r),f=DM.for("smithy.ts.sdk.synthetic."+i);n.copyFrom(s),n.copyFrom(f),this.errorRegistry=n}decorateServiceException(n,t={}){if(this.queryCompat){let i=n.Message??t.Message,r=PM(n,t);if(i)r.message=i;let s=r.Error??{};s.Type=r.Error?.Type,s.Code=r.Error?.Code,s.Message=r.Error?.message??r.Error?.Message??i,r.Error=s;let f=r.$metadata.requestId;if(f)r.RequestId=f;return r}return PM(n,t)}setQueryCompatError(n,t){let i=t.headers?.["x-amzn-query-error"];if(n!==void 0&&i!=null){let[r,s]=i.split(";"),f=Object.keys(n),h={Code:r,Type:s};n.Code=r,n.Type=s;for(let _=0;_<f.length;_++){let c=f[_];h[c==="message"?"Message":c]=n[c]}delete h.__type,n.Error=h}}queryCompatOutput(n,t){if(n.Error)t.Error=n.Error;if(n.Type)t.Type=n.Type;if(n.Code)t.Code=n.Code}findQueryCompatibleError(n,t){try{return n.getSchema(t)}catch(i){return n.find((r)=>Un.of(r).getMergedTraits().awsQueryError?.[0]===t)}}}class mM extends mP{awsQueryCompatible;mixin;constructor({defaultNamespace:n,errorTypeRegistries:t,awsQueryCompatible:i}){super({defaultNamespace:n,errorTypeRegistries:t});this.awsQueryCompatible=!!i,this.mixin=new cs(this.awsQueryCompatible)}async serializeRequest(n,t,i){let r=await super.serializeRequest(n,t,i);if(this.awsQueryCompatible)r.headers["x-amzn-query-mode"]="true";return r}async handleError(n,t,i,r,s){if(this.awsQueryCompatible)this.mixin.setQueryCompatError(r,i);let f=(()=>{let y=i.headers["x-amzn-query-error"];if(y&&this.awsQueryCompatible)return y.split(";")[0];return ZP(i,r)??"Unknown"})();this.mixin.compose(this.compositeErrorRegistry,f,this.options.defaultNamespace);let{errorSchema:h,errorMetadata:_}=await this.mixin.getErrorSchemaOrThrowBaseException(f,this.options.defaultNamespace,i,r,s,this.awsQueryCompatible?this.mixin.findQueryCompatibleError:void 0),c=Un.of(h),o=r.message??r.Message??"UnknownError",e=new(this.compositeErrorRegistry.getErrorCtor(h)??Error)({}),u={};for(let[y,A]of c.structIterator())if(r[y]!=null)u[y]=this.deserializer.readValue(A,r[y]);if(this.awsQueryCompatible)this.mixin.queryCompatOutput(r,u);throw this.mixin.decorateServiceException(Object.assign(e,_,{$fault:c.getMergedTraits().error,message:o},u),r)}}var iY=(n)=>{if(n==null)return n;if(typeof n==="number"||typeof n==="bigint"){let t=Error(`Received number ${n} where a string was expected.`);return t.name="Warning",console.warn(t),String(n)}if(typeof n==="boolean"){let t=Error(`Received boolean ${n} where a string was expected.`);return t.name="Warning",console.warn(t),String(n)}return n},rY=(n)=>{if(n==null)return n;if(typeof n==="string"){let t=n.toLowerCase();if(n!==""&&t!=="false"&&t!=="true"){let i=Error(`Received string "${n}" where a boolean was expected.`);i.name="Warning",console.warn(i)}return n!==""&&t!=="false"}return n},sY=(n)=>{if(n==null)return n;if(typeof n==="string"){let t=Number(n);if(t.toString()!==n){let i=Error(`Received string "${n}" where a number was expected.`);return i.name="Warning",console.warn(i),n}return t}return n};class Bi{serdeContext;setSerdeContext(n){this.serdeContext=n}}class Ew{from;to;keys;constructor(n,t){this.from=n,this.to=t;let i=Object.keys(this.from),r=new Set(i);r.delete("__type"),this.keys=r}mark(n){this.keys.delete(n)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){let n=this.keys.values().next().value,t=this.from[n];this.to.$unknown=[n,t]}}}function fY(n,t,i){if(i?.source){let r=i.source;if(typeof t==="number"){if(t>Number.MAX_SAFE_INTEGER||t<Number.MIN_SAFE_INTEGER||r!==String(t))if(r.includes("."))return new Qt(r,"bigDecimal");else return BigInt(r)}}return t}var ZM=(n,t)=>Rw(n,t).then((i)=>(t?.utf8Encoder??xM)(i)),Tw=(n,t)=>ZM(n,t).then((i)=>{if(i.length)try{return JSON.parse(i)}catch(r){if(r?.name==="SyntaxError")Object.defineProperty(r,"$responseBodyText",{value:i});throw r}return{}}),_Y=async(n,t)=>{let i=await Tw(n,t);return i.message=i.message??i.Message,i},XM=(n,t)=>Object.keys(n).find((i)=>i.toLowerCase()===t.toLowerCase()),Aw=(n)=>{let t=n;if(typeof t==="number")t=t.toString();if(t.indexOf(",")>=0)t=t.split(",")[0];if(t.indexOf(":")>=0)t=t.split(":")[0];if(t.indexOf("#")>=0)t=t.split("#")[1];return t},aM=(n,t)=>{return pM(n,t,["header","code","type"])},vM=(n,t,i=!1)=>{return pM(n,t,i?["code","header","type"]:["type","code","header"])},pM=({headers:n},t,i)=>{while(i.length>0)switch(i.shift()){case"header":let s=XM(n??{},"x-amzn-errortype");if(s!==void 0)return Aw(n[s]);break;case"code":let f=XM(t??{},"code");if(f&&t[f]!==void 0)return Aw(t[f]);break;case"type":if(t?.__type!==void 0)return Aw(t.__type);break}};class gw extends Bi{settings;constructor(n){super();this.settings=n}async read(n,t){return this._read(n,typeof t==="string"?JSON.parse(t,fY):await Tw(t,this.serdeContext))}readObject(n,t){return this._read(n,t)}_read(n,t){let i=t!==null&&typeof t==="object",r=Un.of(n);if(i){if(r.isStructSchema()){let f=t,h=r.isUnionSchema(),_={},c=void 0,{jsonName:o}=this.settings;if(o)c={};let w;if(h)w=new Ew(f,_);for(let[e,u]of r.structIterator()){let y=e;if(o)y=u.getMergedTraits().jsonName??y,c[y]=e;if(h)w.mark(y);if(f[y]!=null)_[e]=this._read(u,f[y])}if(h)w.writeUnknown();else if(typeof f.__type==="string")for(let e in f){let u=f[e],y=o?c[e]??e:e;if(!(y in _))_[y]=u}return _}if(Array.isArray(t)&&r.isListSchema()){let f=r.getValueSchema(),h=[];for(let _ of t)h.push(this._read(f,_));return h}if(r.isMapSchema()){let f=r.getValueSchema(),h={};for(let _ in t)h[_]=this._read(f,t[_]);return h}}if(r.isBlobSchema()&&typeof t==="string")return jM(t);let s=r.getMergedTraits().mediaType;if(r.isStringSchema()&&typeof t==="string"&&s){if(s==="application/json"||s.endsWith("+json"))return kM.from(t);return t}if(r.isTimestampSchema()&&t!=null)switch(Ah(r,this.settings)){case 5:return nY(t);case 6:return pP(t);case 7:return vP(t);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",t),new Date(t)}if(r.isBigIntegerSchema()&&(typeof t==="number"||typeof t==="string"))return BigInt(t);if(r.isBigDecimalSchema()&&t!=null){if(t instanceof Qt)return t;let f=t;if(f.type==="bigDecimal"&&"string"in f)return new Qt(f.string,f.type);return new Qt(String(t),"bigDecimal")}if(r.isNumericSchema()&&typeof t==="string"){switch(t){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return t}if(r.isDocumentSchema())if(i){let f=Array.isArray(t)?[]:{};for(let h in t){let _=t[h];if(_ instanceof Qt)f[h]=_;else f[h]=this._read(r,_)}return f}else return structuredClone(t);return t}}var lM=String.fromCharCode(925);class nE{values=new Map;counter=0;stage=0;createReplacer(){if(this.stage===1)throw Error("@aws-sdk/core/protocols - JsonReplacer already created.");if(this.stage===2)throw Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");return this.stage=1,(n,t)=>{if(t instanceof Qt){let i=`${lM+"nv"+this.counter++}_`+t.string;return this.values.set(`"${i}"`,t.string),i}if(typeof t==="bigint"){let i=t.toString(),r=`${lM+"b"+this.counter++}_`+i;return this.values.set(`"${r}"`,i),r}return t}}replaceInJson(n){if(this.stage===0)throw Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");if(this.stage===2)throw Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");if(this.stage=2,this.counter===0)return n;for(let[t,i]of this.values)n=n.replace(t,i);return n}}class Sw extends Bi{settings;buffer;useReplacer=!1;rootSchema;constructor(n){super();this.settings=n}write(n,t){this.rootSchema=Un.of(n),this.buffer=this._write(this.rootSchema,t)}flush(){let{rootSchema:n,useReplacer:t}=this;if(this.rootSchema=void 0,this.useReplacer=!1,n?.isStructSchema()||n?.isDocumentSchema()){if(!t)return JSON.stringify(this.buffer);let i=new nE;return i.replaceInJson(JSON.stringify(this.buffer,i.createReplacer(),0))}return this.buffer}writeDiscriminatedDocument(n,t){if(this.write(n,t),typeof this.buffer==="object")this.buffer.__type=Un.of(n).getName(!0)}_write(n,t,i){let r=t!==null&&typeof t==="object",s=Un.of(n);if(r){if(s.isStructSchema()){let f=t,h={},{jsonName:_}=this.settings,c=void 0;if(_)c={};let o=0;for(let[w,e]of s.structIterator()){let u=this._write(e,f[w],s);if(u!==void 0){let y=w;if(_)y=e.getMergedTraits().jsonName??w,c[w]=y;h[y]=u,o++}}if(s.isUnionSchema()&&o===0){let{$unknown:w}=f;if(Array.isArray(w)){let[e,u]=w;h[e]=this._write(15,u)}}else if(typeof f.__type==="string")for(let w in f){let e=f[w],u=_?c[w]??w:w;if(!(u in h))h[u]=this._write(15,e)}return h}if(Array.isArray(t)&&s.isListSchema()){let f=s.getValueSchema(),h=[],_=!!s.getMergedTraits().sparse;for(let c of t)if(_||c!=null)h.push(this._write(f,c));return h}if(s.isMapSchema()){let f=s.getValueSchema(),h={},_=!!s.getMergedTraits().sparse;for(let c in t){let o=t[c];if(_||o!=null)h[c]=this._write(f,o)}return h}if(t instanceof Uint8Array&&(s.isBlobSchema()||s.isDocumentSchema())){if(s===this.rootSchema)return t;return(this.serdeContext?.base64Encoder??yh)(t)}if(t instanceof Date&&(s.isTimestampSchema()||s.isDocumentSchema()))switch(Ah(s,this.settings)){case 5:return t.toISOString().replace(".000Z","Z");case 6:return dh(t);case 7:return t.getTime()/1000;default:return console.warn("Missing timestamp format, using epoch seconds",t),t.getTime()/1000}if(t instanceof Qt)this.useReplacer=!0}if(t===null&&i?.isStructSchema())return;if(s.isStringSchema()){if(typeof t>"u"&&s.isIdempotencyToken())return Mw();let f=s.getMergedTraits().mediaType;if(t!=null&&f){if(f==="application/json"||f.endsWith("+json"))return kM.from(t)}return t}if(typeof t==="number"&&s.isNumericSchema()){if(Math.abs(t)===1/0||isNaN(t))return String(t);return t}if(typeof t==="string"&&s.isBlobSchema()){if(s===this.rootSchema)return t;return(this.serdeContext?.base64Encoder??yh)(t)}if(typeof t==="bigint")this.useReplacer=!0;if(s.isDocumentSchema())if(r){let f=Array.isArray(t)?[]:{};for(let h in t){let _=t[h];if(_ instanceof Qt)this.useReplacer=!0,f[h]=_;else f[h]=this._write(s,_)}return f}else return structuredClone(t);return t}}class Rh extends Bi{settings;constructor(n){super();this.settings=n}createSerializer(){let n=new Sw(this.settings);return n.setSerdeContext(this.serdeContext),n}createDeserializer(){let n=new gw(this.settings);return n.setSerdeContext(this.serdeContext),n}}class Mh extends zM{serializer;deserializer;serviceTarget;codec;mixin;awsQueryCompatible;constructor({defaultNamespace:n,errorTypeRegistries:t,serviceTarget:i,awsQueryCompatible:r,jsonCodec:s}){super({defaultNamespace:n,errorTypeRegistries:t});this.serviceTarget=i,this.codec=s??new Rh({timestampFormat:{useTrait:!0,default:7},jsonName:!1}),this.serializer=this.codec.createSerializer(),this.deserializer=this.codec.createDeserializer(),this.awsQueryCompatible=!!r,this.mixin=new cs(this.awsQueryCompatible)}async serializeRequest(n,t,i){let r=await super.serializeRequest(n,t,i);if(!r.path.endsWith("/"))r.path+="/";if(r.headers["content-type"]=`application/x-amz-json-${this.getJsonRpcVersion()}`,r.headers["x-amz-target"]=`${this.serviceTarget}.${n.name}`,this.awsQueryCompatible)r.headers["x-amzn-query-mode"]="true";if(JM(n.input)==="unit"||!r.body)r.body="{}";return r}getPayloadCodec(){return this.codec}async handleError(n,t,i,r,s){let{awsQueryCompatible:f}=this;if(f)this.mixin.setQueryCompatError(r,i);let h=vM(i,r,f)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,h,this.options.defaultNamespace);let{errorSchema:_,errorMetadata:c}=await this.mixin.getErrorSchemaOrThrowBaseException(h,this.options.defaultNamespace,i,r,s,f?this.mixin.findQueryCompatibleError:void 0),o=Un.of(_),w=r.message??r.Message??"UnknownError",u=new(this.compositeErrorRegistry.getErrorCtor(_)??Error)({}),y={},A=this.codec.createDeserializer();for(let[R,M]of o.structIterator())if(r[R]!=null)y[R]=A.readObject(M,r[R]);if(f)this.mixin.queryCompatOutput(r,y);throw this.mixin.decorateServiceException(Object.assign(u,c,{$fault:o.getMergedTraits().error,message:w},y),r)}}class tE extends Mh{constructor({defaultNamespace:n,errorTypeRegistries:t,serviceTarget:i,awsQueryCompatible:r,jsonCodec:s}){super({defaultNamespace:n,errorTypeRegistries:t,serviceTarget:i,awsQueryCompatible:r,jsonCodec:s})}getShapeId(){return"aws.protocols#awsJson1_0"}getJsonRpcVersion(){return"1.0"}getDefaultContentType(){return"application/x-amz-json-1.0"}}class iE extends Mh{constructor({defaultNamespace:n,errorTypeRegistries:t,serviceTarget:i,awsQueryCompatible:r,jsonCodec:s}){super({defaultNamespace:n,errorTypeRegistries:t,serviceTarget:i,awsQueryCompatible:r,jsonCodec:s})}getShapeId(){return"aws.protocols#awsJson1_1"}getJsonRpcVersion(){return"1.1"}getDefaultContentType(){return"application/x-amz-json-1.1"}}class rE extends CM{serializer;deserializer;codec;mixin=new cs;constructor({defaultNamespace:n,errorTypeRegistries:t}){super({defaultNamespace:n,errorTypeRegistries:t});let i={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=new Rh(i),this.serializer=new VM(this.codec.createSerializer(),i),this.deserializer=new KM(this.codec.createDeserializer(),i)}getShapeId(){return"aws.protocols#restJson1"}getPayloadCodec(){return this.codec}setSerdeContext(n){this.codec.setSerdeContext(n),super.setSerdeContext(n)}async serializeRequest(n,t,i){let r=await super.serializeRequest(n,t,i),s=Un.of(n.input);if(!r.headers["content-type"]){let f=this.mixin.resolveRestContentType(this.getDefaultContentType(),s);if(f)r.headers["content-type"]=f}if(r.body==null&&r.headers["content-type"]===this.getDefaultContentType())r.body="{}";return r}async deserializeResponse(n,t,i){let r=await super.deserializeResponse(n,t,i),s=Un.of(n.output);for(let[f,h]of s.structIterator())if(h.getMemberTraits().httpPayload&&!(f in r))r[f]=null;return r}async handleError(n,t,i,r,s){let f=aM(i,r)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,f,this.options.defaultNamespace);let{errorSchema:h,errorMetadata:_}=await this.mixin.getErrorSchemaOrThrowBaseException(f,this.options.defaultNamespace,i,r,s),c=Un.of(h),o=r.message??r.Message??"UnknownError",e=new(this.compositeErrorRegistry.getErrorCtor(h)??Error)({});await this.deserializeHttpMessage(h,t,i,r);let u={},y=this.codec.createDeserializer();for(let[A,R]of c.structIterator()){let M=R.getMergedTraits().jsonName??A;u[A]=y.readObject(R,r[M])}throw this.mixin.decorateServiceException(Object.assign(e,_,{$fault:c.getMergedTraits().error,message:o},u),r)}getDefaultContentType(){return"application/json"}}var hY=(n)=>{if(n==null)return;if(typeof n==="object"&&"__type"in n)delete n.__type;return tY(n)};class Eh extends Bi{settings;stringDeserializer;constructor(n){super();this.settings=n,this.stringDeserializer=new aP(n)}setSerdeContext(n){this.serdeContext=n,this.stringDeserializer.setSerdeContext(n)}read(n,t,i){let r=Un.of(n),s=r.getMemberSchemas();if(r.isStructSchema()&&r.isMemberSchema()&&!!Object.values(s).find((c)=>{return!!c.getMemberTraits().eventPayload})){let c={},o=Object.keys(s)[0];if(s[o].isBlobSchema())c[o]=t;else c[o]=this.read(s[o],t);return c}let h=(this.serdeContext?.utf8Encoder??xM)(t),_=this.parseXml(h);return this.readSchema(n,i?_[i]:_)}readSchema(n,t){let i=Un.of(n);if(i.isUnitSchema())return;let r=i.getMergedTraits();if(i.isListSchema()&&!Array.isArray(t))return this.readSchema(i,[t]);if(t==null)return t;if(typeof t==="object"){let s=!!r.xmlFlattened;if(i.isListSchema()){let h=i.getValueSchema(),_=[],c=h.getMergedTraits().xmlName??"member",o=s?t:(t[0]??t)[c];if(o==null)return _;let w=Array.isArray(o)?o:[o];for(let e of w)_.push(this.readSchema(h,e));return _}let f={};if(i.isMapSchema()){let h=i.getKeySchema(),_=i.getValueSchema(),c;if(s)c=Array.isArray(t)?t:[t];else c=Array.isArray(t.entry)?t.entry:[t.entry];let o=h.getMergedTraits().xmlName??"key",w=_.getMergedTraits().xmlName??"value";for(let e of c){let u=e[o],y=e[w];f[u]=this.readSchema(_,y)}return f}if(i.isStructSchema()){let h=i.isUnionSchema(),_;if(h)_=new Ew(t,f);for(let[c,o]of i.structIterator()){let w=o.getMergedTraits(),e=!w.httpPayload?o.getMemberTraits().xmlName??c:w.xmlName??o.getName();if(h)_.mark(e);if(t[e]!=null)f[c]=this.readSchema(o,t[e])}if(h)_.writeUnknown();return f}if(i.isDocumentSchema())return t;throw Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${i.getName(!0)}`)}if(i.isListSchema())return[];if(i.isMapSchema()||i.isStructSchema())return{};return this.stringDeserializer.read(i,t)}parseXml(n){if(n.length){let t;try{t=qM(n)}catch(f){if(f&&typeof f==="object")Object.defineProperty(f,"$responseBodyText",{value:n});throw f}let i="#text",r=Object.keys(t)[0],s=t[r];if(s[i])s[r]=s[i],delete s[i];return QM(s)}return{}}}class Lw extends Bi{settings;buffer;constructor(n){super();this.settings=n}write(n,t,i=""){if(this.buffer===void 0)this.buffer="";let r=Un.of(n);if(i&&!i.endsWith("."))i+=".";if(r.isBlobSchema()){if(typeof t==="string"||t instanceof Uint8Array)this.writeKey(i),this.writeValue((this.serdeContext?.base64Encoder??yh)(t))}else if(r.isBooleanSchema()||r.isNumericSchema()||r.isStringSchema()){if(t!=null)this.writeKey(i),this.writeValue(String(t));else if(r.isIdempotencyToken())this.writeKey(i),this.writeValue(Mw())}else if(r.isBigIntegerSchema()){if(t!=null)this.writeKey(i),this.writeValue(String(t))}else if(r.isBigDecimalSchema()){if(t!=null)this.writeKey(i),this.writeValue(t instanceof Qt?t.string:String(t))}else if(r.isTimestampSchema()){if(t instanceof Date)switch(this.writeKey(i),Ah(r,this.settings)){case 5:this.writeValue(t.toISOString().replace(".000Z","Z"));break;case 6:this.writeValue(dh(t));break;case 7:this.writeValue(String(t.getTime()/1000));break}}else if(r.isDocumentSchema())if(Array.isArray(t))this.write(79,t,i);else if(t instanceof Date)this.write(4,t,i);else if(t instanceof Uint8Array)this.write(21,t,i);else if(t&&typeof t==="object")this.write(143,t,i);else this.writeKey(i),this.writeValue(String(t));else if(r.isListSchema()){if(Array.isArray(t))if(t.length===0){if(this.settings.serializeEmptyLists)this.writeKey(i),this.writeValue("")}else{let s=r.getValueSchema(),f=this.settings.flattenLists||r.getMergedTraits().xmlFlattened,h=1;for(let _ of t){if(_==null)continue;let c=s.getMergedTraits(),o=this.getKey("member",c.xmlName,c.ec2QueryName),w=f?`${i}${h}`:`${i}${o}.${h}`;this.write(s,_,w),++h}}}else if(r.isMapSchema()){if(t&&typeof t==="object"){let s=r.getKeySchema(),f=r.getValueSchema(),h=r.getMergedTraits().xmlFlattened,_=1;for(let c in t){let o=t[c];if(o==null)continue;let w=s.getMergedTraits(),e=this.getKey("key",w.xmlName,w.ec2QueryName),u=h?`${i}${_}.${e}`:`${i}entry.${_}.${e}`,y=f.getMergedTraits(),A=this.getKey("value",y.xmlName,y.ec2QueryName),R=h?`${i}${_}.${A}`:`${i}entry.${_}.${A}`;this.write(s,c,u),this.write(f,o,R),++_}}}else if(r.isStructSchema()){if(t&&typeof t==="object"){let s=!1;for(let[f,h]of r.structIterator()){if(t[f]==null&&!h.isIdempotencyToken())continue;let _=h.getMergedTraits(),c=this.getKey(f,_.xmlName,_.ec2QueryName,"struct"),o=`${i}${c}`;this.write(h,t[f],o),s=!0}if(!s&&r.isUnionSchema()){let{$unknown:f}=t;if(Array.isArray(f)){let[h,_]=f,c=`${i}${h}`;this.write(15,_,c)}}}}else if(r.isUnitSchema());else throw Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${r.getName(!0)}`)}flush(){if(this.buffer===void 0)throw Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer.");let n=this.buffer;return delete this.buffer,n}getKey(n,t,i,r){let{ec2:s,capitalizeKeys:f}=this.settings;if(s&&i)return i;let h=t??n;if(f&&r==="struct")return h[0].toUpperCase()+h.slice(1);return h}writeKey(n){if(n.endsWith("."))n=n.slice(0,n.length-1);this.buffer+=`&${YM(n)}=`}writeValue(n){this.buffer+=YM(n)}}class $w extends zM{options;serializer;deserializer;mixin=new cs;constructor(n){super({defaultNamespace:n.defaultNamespace,errorTypeRegistries:n.errorTypeRegistries});this.options=n;let t={timestampFormat:{useTrait:!0,default:5},httpBindings:!1,xmlNamespace:n.xmlNamespace,serviceNamespace:n.defaultNamespace,serializeEmptyLists:!0};this.serializer=new Lw(t),this.deserializer=new Eh(t)}getShapeId(){return"aws.protocols#awsQuery"}setSerdeContext(n){this.serializer.setSerdeContext(n),this.deserializer.setSerdeContext(n)}getPayloadCodec(){throw Error("AWSQuery protocol has no payload codec.")}async serializeRequest(n,t,i){let r=await super.serializeRequest(n,t,i);if(!r.path.endsWith("/"))r.path+="/";if(r.headers["content-type"]="application/x-www-form-urlencoded",JM(n.input)==="unit"||!r.body)r.body="";let s=n.name.split("#")[1]??n.name;if(r.body=`Action=${s}&Version=${this.options.version}`+r.body,r.body.endsWith("&"))r.body=r.body.slice(-1);return r}async deserializeResponse(n,t,i){let r=this.deserializer,s=Un.of(n.output),f={};if(i.statusCode>=300){let o=await Rw(i.body,t);if(o.byteLength>0)Object.assign(f,await r.read(15,o));await this.handleError(n,t,i,f,this.deserializeMetadata(i))}for(let o in i.headers){let w=i.headers[o];delete i.headers[o],i.headers[o.toLowerCase()]=w}let h=n.name.split("#")[1]??n.name,_=s.isStructSchema()&&this.useNestedResult()?h+"Result":void 0,c=await Rw(i.body,t);if(c.byteLength>0)Object.assign(f,await r.read(s,c,_));return f.$metadata=this.deserializeMetadata(i),f}useNestedResult(){return!0}async handleError(n,t,i,r,s){let f=this.loadQueryErrorCode(i,r)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,f,this.options.defaultNamespace);let h=this.loadQueryError(r)??{},_=this.loadQueryErrorMessage(r);h.message=_,h.Error={Type:h.Type,Code:h.Code,Message:_};let{errorSchema:c,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(f,this.options.defaultNamespace,i,h,s,this.mixin.findQueryCompatibleError),w=Un.of(c),u=new(this.compositeErrorRegistry.getErrorCtor(c)??Error)({}),y={Type:h.Error.Type,Code:h.Error.Code,Error:h.Error};for(let[A,R]of w.structIterator()){let M=R.getMergedTraits().xmlName??A,E=h[M]??r[M];y[A]=this.deserializer.readSchema(R,E)}throw this.mixin.decorateServiceException(Object.assign(u,o,{$fault:w.getMergedTraits().error,message:_},y),r)}loadQueryErrorCode(n,t){let i=(t.Errors?.[0]?.Error??t.Errors?.Error??t.Error)?.Code;if(i!==void 0)return i;if(n.statusCode==404)return"NotFound"}loadQueryError(n){return n.Errors?.[0]?.Error??n.Errors?.Error??n.Error}loadQueryErrorMessage(n){let t=this.loadQueryError(n);return t?.message??t?.Message??n.message??n.Message??"Unknown"}getDefaultContentType(){return"application/x-www-form-urlencoded"}}class sE extends $w{options;constructor(n){super(n);this.options=n;let t={capitalizeKeys:!0,flattenLists:!0,serializeEmptyLists:!1,ec2:!0};Object.assign(this.serializer.settings,t)}getShapeId(){return"aws.protocols#ec2Query"}useNestedResult(){return!1}}var fE=(n,t)=>ZM(n,t).then((i)=>{if(i.length){let r;try{r=qM(i)}catch(_){if(_&&typeof _==="object")Object.defineProperty(_,"$responseBodyText",{value:i});throw _}let s="#text",f=Object.keys(r)[0],h=r[f];if(h[s])h[f]=h[s],delete h[s];return QM(h)}return{}}),cY=async(n,t)=>{let i=await fE(n,t);if(i.Error)i.Error.message=i.Error.message??i.Error.Message;return i},_E=(n,t)=>{if(t?.Error?.Code!==void 0)return t.Error.Code;if(t?.Code!==void 0)return t.Code;if(n.statusCode==404)return"NotFound"};class Ow extends Bi{settings;stringBuffer;byteBuffer;buffer;constructor(n){super();this.settings=n}write(n,t){let i=Un.of(n);if(i.isStringSchema()&&typeof t==="string")this.stringBuffer=t;else if(i.isBlobSchema())this.byteBuffer="byteLength"in t?t:(this.serdeContext?.base64Decoder??jM)(t);else{this.buffer=this.writeStruct(i,t,void 0);let r=i.getMergedTraits();if(r.httpPayload&&!r.xmlName)this.buffer.withName(i.getName())}}flush(){if(this.byteBuffer!==void 0){let t=this.byteBuffer;return delete this.byteBuffer,t}if(this.stringBuffer!==void 0){let t=this.stringBuffer;return delete this.stringBuffer,t}let n=this.buffer;if(this.settings.xmlNamespace){if(!n?.attributes?.xmlns)n.addAttribute("xmlns",this.settings.xmlNamespace)}return delete this.buffer,n.toString()}writeStruct(n,t,i){let r=n.getMergedTraits(),s=n.isMemberSchema()&&!r.httpPayload?n.getMemberTraits().xmlName??n.getMemberName():r.xmlName??n.getName();if(!s||!n.isStructSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${n.getName(!0)}.`);let f=Lt.of(s),[h,_]=this.getXmlnsAttribute(n,i);for(let[o,w]of n.structIterator()){let e=t[o];if(e!=null||w.isIdempotencyToken()){if(w.getMergedTraits().xmlAttribute){f.addAttribute(w.getMergedTraits().xmlName??o,this.writeSimple(w,e));continue}if(w.isListSchema())this.writeList(w,e,f,_);else if(w.isMapSchema())this.writeMap(w,e,f,_);else if(w.isStructSchema())f.addChildNode(this.writeStruct(w,e,_));else{let u=Lt.of(w.getMergedTraits().xmlName??w.getMemberName());this.writeSimpleInto(w,e,u,_),f.addChildNode(u)}}}let{$unknown:c}=t;if(c&&n.isUnionSchema()&&Array.isArray(c)&&Object.keys(t).length===1){let[o,w]=c,e=Lt.of(o);if(typeof w!=="string")if(t instanceof Lt||t instanceof FM)f.addChildNode(t);else throw Error("@aws-sdk - $unknown union member in XML requires value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.");this.writeSimpleInto(0,w,e,_),f.addChildNode(e)}if(_)f.addAttribute(h,_);return f}writeList(n,t,i,r){if(!n.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${n.getName(!0)}`);let s=n.getMergedTraits(),f=n.getValueSchema(),h=f.getMergedTraits(),_=!!h.sparse,c=!!s.xmlFlattened,[o,w]=this.getXmlnsAttribute(n,r),e=(u,y)=>{if(f.isListSchema())this.writeList(f,Array.isArray(y)?y:[y],u,w);else if(f.isMapSchema())this.writeMap(f,y,u,w);else if(f.isStructSchema()){let A=this.writeStruct(f,y,w);u.addChildNode(A.withName(c?s.xmlName??n.getMemberName():h.xmlName??"member"))}else{let A=Lt.of(c?s.xmlName??n.getMemberName():h.xmlName??"member");this.writeSimpleInto(f,y,A,w),u.addChildNode(A)}};if(c){for(let u of t)if(_||u!=null)e(i,u)}else{let u=Lt.of(s.xmlName??n.getMemberName());if(w)u.addAttribute(o,w);for(let y of t)if(_||y!=null)e(u,y);i.addChildNode(u)}}writeMap(n,t,i,r,s=!1){if(!n.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${n.getName(!0)}`);let f=n.getMergedTraits(),h=n.getKeySchema(),c=h.getMergedTraits().xmlName??"key",o=n.getValueSchema(),w=o.getMergedTraits(),e=w.xmlName??"value",u=!!w.sparse,y=!!f.xmlFlattened,[A,R]=this.getXmlnsAttribute(n,r),M=(E,g,T)=>{let S=Lt.of(c,g),[L,b]=this.getXmlnsAttribute(h,R);if(b)S.addAttribute(L,b);E.addChildNode(S);let I=Lt.of(e);if(o.isListSchema())this.writeList(o,T,I,R);else if(o.isMapSchema())this.writeMap(o,T,I,R,!0);else if(o.isStructSchema())I=this.writeStruct(o,T,R);else this.writeSimpleInto(o,T,I,R);E.addChildNode(I)};if(y)for(let E in t){let g=t[E];if(u||g!=null){let T=Lt.of(f.xmlName??n.getMemberName());M(T,E,g),i.addChildNode(T)}}else{let E;if(!s){if(E=Lt.of(f.xmlName??n.getMemberName()),R)E.addAttribute(A,R);i.addChildNode(E)}for(let g in t){let T=t[g];if(u||T!=null){let S=Lt.of("entry");M(S,g,T),(s?i:E).addChildNode(S)}}}}writeSimple(n,t){if(t===null)throw Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value.");let i=Un.of(n),r=null;if(t&&typeof t==="object")if(i.isBlobSchema())r=(this.serdeContext?.base64Encoder??yh)(t);else if(i.isTimestampSchema()&&t instanceof Date)switch(Ah(i,this.settings)){case 5:r=t.toISOString().replace(".000Z","Z");break;case 6:r=dh(t);break;case 7:r=String(t.getTime()/1000);break;default:console.warn("Missing timestamp format, using http date",t),r=dh(t);break}else if(i.isBigDecimalSchema()&&t){if(t instanceof Qt)return t.string;return String(t)}else if(i.isMapSchema()||i.isListSchema())throw Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead.");else throw Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${i.getName(!0)}`);if(i.isBooleanSchema()||i.isNumericSchema()||i.isBigIntegerSchema()||i.isBigDecimalSchema())r=String(t);if(i.isStringSchema())if(t===void 0&&i.isIdempotencyToken())r=Mw();else r=String(t);if(r===null)throw Error(`Unhandled schema-value pair ${i.getName(!0)}=${t}`);return r}writeSimpleInto(n,t,i,r){let s=this.writeSimple(n,t),f=Un.of(n),h=new FM(s),[_,c]=this.getXmlnsAttribute(f,r);if(c)i.addAttribute(_,c);i.addChildNode(h)}getXmlnsAttribute(n,t){let i=n.getMergedTraits(),[r,s]=i.xmlNamespace??[];if(s&&s!==t)return[r?`xmlns:${r}`:"xmlns",s];return[void 0,void 0]}}class Uw extends Bi{settings;constructor(n){super();this.settings=n}createSerializer(){let n=new Ow(this.settings);return n.setSerdeContext(this.serdeContext),n}createDeserializer(){let n=new Eh(this.settings);return n.setSerdeContext(this.serdeContext),n}}class hE extends CM{codec;serializer;deserializer;mixin=new cs;constructor(n){super(n);let t={timestampFormat:{useTrait:!0,default:5},httpBindings:!0,xmlNamespace:n.xmlNamespace,serviceNamespace:n.defaultNamespace};this.codec=new Uw(t),this.serializer=new VM(this.codec.createSerializer(),t),this.deserializer=new KM(this.codec.createDeserializer(),t)}getPayloadCodec(){return this.codec}getShapeId(){return"aws.protocols#restXml"}async serializeRequest(n,t,i){let r=await super.serializeRequest(n,t,i),s=Un.of(n.input);if(!r.headers["content-type"]){let f=this.mixin.resolveRestContentType(this.getDefaultContentType(),s);if(f)r.headers["content-type"]=f}if(typeof r.body==="string"&&r.headers["content-type"]===this.getDefaultContentType()&&!r.body.startsWith("<?xml ")&&!this.hasUnstructuredPayloadBinding(s))r.body='<?xml version="1.0" encoding="UTF-8"?>'+r.body;return r}async deserializeResponse(n,t,i){return super.deserializeResponse(n,t,i)}async handleError(n,t,i,r,s){let f=_E(i,r)??"Unknown";if(this.mixin.compose(this.compositeErrorRegistry,f,this.options.defaultNamespace),r.Error&&typeof r.Error==="object"){for(let A of Object.keys(r.Error))if(r[A]=r.Error[A],A.toLowerCase()==="message")r.message=r.Error[A]}if(r.RequestId&&!s.requestId)s.requestId=r.RequestId;let{errorSchema:h,errorMetadata:_}=await this.mixin.getErrorSchemaOrThrowBaseException(f,this.options.defaultNamespace,i,r,s),c=Un.of(h),o=r.Error?.message??r.Error?.Message??r.message??r.Message??"UnknownError",e=new(this.compositeErrorRegistry.getErrorCtor(h)??Error)({});await this.deserializeHttpMessage(h,t,i,r);let u={},y=this.codec.createDeserializer();for(let[A,R]of c.structIterator()){let M=R.getMergedTraits().xmlName??A,E=r.Error?.[M]??r[M];u[A]=y.readSchema(R,E)}throw this.mixin.decorateServiceException(Object.assign(e,_,{$fault:c.getMergedTraits().error,message:o},u),r)}getDefaultContentType(){return"application/xml"}hasUnstructuredPayloadBinding(n){for(let[,t]of n.structIterator())if(t.getMergedTraits().httpPayload)return!(t.isStructSchema()||t.isMapSchema()||t.isListSchema());return!1}}oY.AwsEc2QueryProtocol=sE;oY.AwsJson1_0Protocol=tE;oY.AwsJson1_1Protocol=iE;oY.AwsJsonRpcProtocol=Mh;oY.AwsQueryProtocol=$w;oY.AwsRestJsonProtocol=rE;oY.AwsRestXmlProtocol=hE;oY.AwsSmithyRpcV2CborProtocol=mM;oY.JsonCodec=Rh;oY.JsonShapeDeserializer=gw;oY.JsonShapeSerializer=Sw;oY.QueryShapeSerializer=Lw;oY.XmlCodec=Uw;oY.XmlShapeDeserializer=Eh;oY.XmlShapeSerializer=Ow;oY._toBool=rY;oY._toNum=sY;oY._toStr=iY;oY.awsExpectUnion=hY;oY.loadJsonRpcErrorCode=vM;oY.loadRestJsonErrorCode=aM;oY.loadRestXmlErrorCode=_E;oY.parseJsonBody=Tw;oY.parseJsonErrorBody=_Y;oY.parseXmlBody=fE;oY.parseXmlErrorBody=cY});var Ww=nn((ZX)=>{var{awsEndpointFunctions:FY,emitWarningIfUnsupportedVersion:XY,createDefaultUserAgentProvider:lY,NODE_APP_ID_CONFIG_OPTIONS:JY,getAwsRegionExtensionConfiguration:QY,resolveAwsRegionExtensionConfiguration:zY,resolveUserAgentConfig:CY,resolveHostHeaderConfig:VY,getUserAgentPlugin:KY,getHostHeaderPlugin:xY,getLoggerPlugin:jY,getRecursionDetectionPlugin:kY}=gt(),{NoAuthSigner:qY,getHttpAuthSchemeEndpointRuleSetPlugin:mY,DefaultIdentityProviderConfig:ZY,getHttpSigningPlugin:aY}=Ui(),{normalizeProvider:uE,getSmithyContext:vY,ServiceException:pY,NoOpLogger:nF,emitWarningIfUnsupportedVersion:tF,loadConfigsForDefaultMode:iF,getDefaultExtensionConfiguration:rF,resolveDefaultRuntimeConfig:sF,Client:yE,makeBuilder:fF,createAggregatedClient:_F}=at(),{Command:hF}=at();ZX.$Command=hF;ZX.__Client=yE;var{resolveDefaultsModeConfig:cF,loadConfig:fr,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:oF,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:wF,NODE_REGION_CONFIG_OPTIONS:eF,NODE_REGION_CONFIG_FILE_OPTIONS:uF,resolveRegionConfig:yF}=xn(),{BinaryDecisionDiagram:dF,EndpointCache:AF,decideEndpoint:RF,customEndpointFunctions:MF,resolveEndpointConfig:EF,getEndpointPlugin:TF}=vi(),{parseUrl:gF,getHttpHandlerExtensionConfiguration:SF,resolveHttpHandlerRuntimeConfig:LF,getContentLengthPlugin:$F}=kn(),{DEFAULT_RETRY_MODE:OF,NODE_RETRY_MODE_CONFIG_OPTIONS:UF,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:bF,resolveRetryConfig:NF,getRetryPlugin:BF}=Af(),{TypeRegistry:dE,getSchemaSerdePlugin:IF}=Ei(),{resolveAwsSdkSigV4Config:HF,AwsSdkSigV4Signer:GF,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:WF}=qo(),{toUtf8:DF,fromUtf8:PF,toBase64:YF,fromBase64:FF,calculateBodyLength:XF}=jn(),{streamCollector:lF,NodeHttpHandler:JF}=wh(),{AwsRestJsonProtocol:QF}=bw(),{Sha256:zF}=vc(),CF=async(n,t,i)=>{return{operation:vY(t).operation,region:await uE(n.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()}};function VF(n){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:n.region},propertiesExtractor:(t,i)=>({signingProperties:{config:t,context:i}})}}function KF(n){return{schemeId:"smithy.api#noAuth"}}var xF=(n)=>{let t=[];switch(n.operation){case"CreateToken":{t.push(KF());break}default:t.push(VF(n))}return t},jF=(n)=>{let t=HF(n);return Object.assign(t,{authSchemePreference:uE(n.authSchemePreference??[])})},kF=(n)=>{return Object.assign(n,{useDualstackEndpoint:n.useDualstackEndpoint??!1,useFipsEndpoint:n.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"})},qF={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},mF="3.997.32",ZF={version:mF},Bf="ref",_r=-1,Th=!0,cE="isSet",AE="PartitionResult",gh="booleanEquals",Nw="getAttr",oE={[Bf]:"Endpoint"},Bw={[Bf]:AE},os={},wE=[{[Bf]:"Region"}],eE={conditions:[[cE,[oE]],[cE,wE],["aws.partition",wE,AE],[gh,[{[Bf]:"UseFIPS"},Th]],[gh,[{[Bf]:"UseDualStack"},Th]],[gh,[{fn:Nw,argv:[Bw,"supportsDualStack"]},Th]],[gh,[{fn:Nw,argv:[Bw,"supportsFIPS"]},Th]],["stringEquals",[{fn:Nw,argv:[Bw,"name"]},"aws-us-gov"]]],results:[[_r],[_r,"Invalid Configuration: FIPS and custom endpoint are not supported"],[_r,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[oE,os],["https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",os],[_r,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://oidc.{Region}.amazonaws.com",os],["https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",os],[_r,"FIPS is enabled but this partition does not support FIPS"],["https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",os],[_r,"DualStack is enabled but this partition does not support DualStack"],["https://oidc.{Region}.{PartitionResult#dnsSuffix}",os],[_r,"Invalid Configuration: Missing Region"]]},aF=2,qn=1e8,vF=new Int32Array([-1,1,-1,0,13,3,1,4,qn+12,2,5,qn+12,3,8,6,4,7,qn+11,5,qn+9,qn+10,4,11,9,6,10,qn+8,7,qn+6,qn+7,5,12,qn+5,6,qn+4,qn+5,3,qn+1,14,4,qn+2,qn+3]),pF=dF.from(vF,aF,eE.conditions,eE.results),nX=new AF({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),tX=(n,t={})=>{return nX.get(n,()=>RF(pF,{endpointParams:n,logger:t.logger}))};MF.aws=FY;class Cn extends pY{constructor(n){super(n);Object.setPrototypeOf(this,Cn.prototype)}}class Sh extends Cn{name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(n){super({name:"AccessDeniedException",$fault:"client",...n});Object.setPrototypeOf(this,Sh.prototype),this.error=n.error,this.reason=n.reason,this.error_description=n.error_description}}class Lh extends Cn{name="AuthorizationPendingException";$fault="client";error;error_description;constructor(n){super({name:"AuthorizationPendingException",$fault:"client",...n});Object.setPrototypeOf(this,Lh.prototype),this.error=n.error,this.error_description=n.error_description}}class $h extends Cn{name="ExpiredTokenException";$fault="client";error;error_description;constructor(n){super({name:"ExpiredTokenException",$fault:"client",...n});Object.setPrototypeOf(this,$h.prototype),this.error=n.error,this.error_description=n.error_description}}class Oh extends Cn{name="InternalServerException";$fault="server";error;error_description;constructor(n){super({name:"InternalServerException",$fault:"server",...n});Object.setPrototypeOf(this,Oh.prototype),this.error=n.error,this.error_description=n.error_description}}class Uh extends Cn{name="InvalidClientException";$fault="client";error;error_description;constructor(n){super({name:"InvalidClientException",$fault:"client",...n});Object.setPrototypeOf(this,Uh.prototype),this.error=n.error,this.error_description=n.error_description}}class bh extends Cn{name="InvalidGrantException";$fault="client";error;error_description;constructor(n){super({name:"InvalidGrantException",$fault:"client",...n});Object.setPrototypeOf(this,bh.prototype),this.error=n.error,this.error_description=n.error_description}}class Nh extends Cn{name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(n){super({name:"InvalidRequestException",$fault:"client",...n});Object.setPrototypeOf(this,Nh.prototype),this.error=n.error,this.reason=n.reason,this.error_description=n.error_description}}class Bh extends Cn{name="InvalidScopeException";$fault="client";error;error_description;constructor(n){super({name:"InvalidScopeException",$fault:"client",...n});Object.setPrototypeOf(this,Bh.prototype),this.error=n.error,this.error_description=n.error_description}}class Ih extends Cn{name="SlowDownException";$fault="client";error;error_description;constructor(n){super({name:"SlowDownException",$fault:"client",...n});Object.setPrototypeOf(this,Ih.prototype),this.error=n.error,this.error_description=n.error_description}}class Hh extends Cn{name="UnauthorizedClientException";$fault="client";error;error_description;constructor(n){super({name:"UnauthorizedClientException",$fault:"client",...n});Object.setPrototypeOf(this,Hh.prototype),this.error=n.error,this.error_description=n.error_description}}class Gh extends Cn{name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(n){super({name:"UnsupportedGrantTypeException",$fault:"client",...n});Object.setPrototypeOf(this,Gh.prototype),this.error=n.error,this.error_description=n.error_description}}var iX="AccessDeniedException",rX="AuthorizationPendingException",sX="AccessToken",fX="ClientSecret",_X="CreateToken",hX="CreateTokenRequest",cX="CreateTokenResponse",oX="CodeVerifier",wX="ExpiredTokenException",eX="InvalidClientException",uX="InvalidGrantException",yX="InvalidRequestException",dX="InternalServerException",AX="InvalidScopeException",RX="IdToken",MX="RefreshToken",EX="SlowDownException",TX="UnauthorizedClientException",gX="UnsupportedGrantTypeException",SX="accessToken",zt="client",LX="clientId",$X="clientSecret",OX="codeVerifier",UX="code",bX="deviceCode",On="error",NX="expiresIn",$t="error_description",BX="grantType",IX="http",Ot="httpError",HX="idToken",RE="reason",ME="refreshToken",GX="redirectUri",EE="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",WX="scope",DX="server",PX="tokenType",bn="com.amazonaws.ssooidc",TE=dE.for(EE),gE=[-3,EE,"SSOOIDCServiceException",0,[],[]];TE.registerError(gE,Cn);var wt=dE.for(bn),SE=[-3,bn,iX,{[On]:zt,[Ot]:400},[On,RE,$t],[0,0,0]];wt.registerError(SE,Sh);var LE=[-3,bn,rX,{[On]:zt,[Ot]:400},[On,$t],[0,0]];wt.registerError(LE,Lh);var $E=[-3,bn,wX,{[On]:zt,[Ot]:400},[On,$t],[0,0]];wt.registerError($E,$h);var OE=[-3,bn,dX,{[On]:DX,[Ot]:500},[On,$t],[0,0]];wt.registerError(OE,Oh);var UE=[-3,bn,eX,{[On]:zt,[Ot]:401},[On,$t],[0,0]];wt.registerError(UE,Uh);var bE=[-3,bn,uX,{[On]:zt,[Ot]:400},[On,$t],[0,0]];wt.registerError(bE,bh);var NE=[-3,bn,yX,{[On]:zt,[Ot]:400},[On,RE,$t],[0,0,0]];wt.registerError(NE,Nh);var BE=[-3,bn,AX,{[On]:zt,[Ot]:400},[On,$t],[0,0]];wt.registerError(BE,Bh);var IE=[-3,bn,EX,{[On]:zt,[Ot]:400},[On,$t],[0,0]];wt.registerError(IE,Ih);var HE=[-3,bn,TX,{[On]:zt,[Ot]:400},[On,$t],[0,0]];wt.registerError(HE,Hh);var GE=[-3,bn,gX,{[On]:zt,[Ot]:400},[On,$t],[0,0]];wt.registerError(GE,Gh);var WE=[TE,wt],YX=[0,bn,sX,8,0],FX=[0,bn,fX,8,0],XX=[0,bn,oX,8,0],lX=[0,bn,RX,8,0],DE=[0,bn,MX,8,0],PE=[3,bn,hX,0,[LX,$X,BX,bX,UX,ME,WX,GX,OX],[0,[()=>FX,0],0,0,0,[()=>DE,0],64,0,[()=>XX,0]],3],YE=[3,bn,cX,0,[SX,PX,NX,ME,HX],[[()=>YX,0],0,1,[()=>DE,0],[()=>lX,0]]],FE=[9,bn,_X,{[IX]:["POST","/token",200]},()=>PE,()=>YE],JX=(n)=>{return{apiVersion:"2019-06-10",base64Decoder:n?.base64Decoder??FF,base64Encoder:n?.base64Encoder??YF,disableHostPrefix:n?.disableHostPrefix??!1,endpointProvider:n?.endpointProvider??tX,extensions:n?.extensions??[],httpAuthSchemeProvider:n?.httpAuthSchemeProvider??xF,httpAuthSchemes:n?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(t)=>t.getIdentityProvider("aws.auth#sigv4"),signer:new GF},{schemeId:"smithy.api#noAuth",identityProvider:(t)=>t.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new qY}],logger:n?.logger??new nF,protocol:n?.protocol??QF,protocolSettings:n?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:WE,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:n?.serviceId??"SSO OIDC",sha256:n?.sha256??zF,urlParser:n?.urlParser??gF,utf8Decoder:n?.utf8Decoder??PF,utf8Encoder:n?.utf8Encoder??DF}},QX=(n)=>{tF(process.version);let t=cF(n),i=()=>t().then(iF),r=JX(n);XY(process.version);let s={profile:n?.profile,logger:r.logger};return{...r,...n,runtime:"node",defaultsMode:t,authSchemePreference:n?.authSchemePreference??fr(WF,s),bodyLengthChecker:n?.bodyLengthChecker??XF,defaultUserAgentProvider:n?.defaultUserAgentProvider??lY({serviceId:r.serviceId,clientVersion:ZF.version}),maxAttempts:n?.maxAttempts??fr(bF,n),region:n?.region??fr(eF,{...uF,...s}),requestHandler:JF.create(n?.requestHandler??i),retryMode:n?.retryMode??fr({...UF,default:async()=>(await i()).retryMode||OF},n),streamCollector:n?.streamCollector??lF,useDualstackEndpoint:n?.useDualstackEndpoint??fr(wF,s),useFipsEndpoint:n?.useFipsEndpoint??fr(oF,s),userAgentAppId:n?.userAgentAppId??fr(JY,s)}},zX=(n)=>{let{httpAuthSchemes:t,httpAuthSchemeProvider:i,credentials:r}=n;return{setHttpAuthScheme(s){let f=t.findIndex((h)=>h.schemeId===s.schemeId);if(f===-1)t.push(s);else t.splice(f,1,s)},httpAuthSchemes(){return t},setHttpAuthSchemeProvider(s){i=s},httpAuthSchemeProvider(){return i},setCredentials(s){r=s},credentials(){return r}}},CX=(n)=>{return{httpAuthSchemes:n.httpAuthSchemes(),httpAuthSchemeProvider:n.httpAuthSchemeProvider(),credentials:n.credentials()}},VX=(n,t)=>{let i=Object.assign(QY(n),rF(n),SF(n),zX(n));return t.forEach((r)=>r.configure(i)),Object.assign(n,zY(i),sF(i),LF(i),CX(i))};class Iw extends yE{config;constructor(...[n]){let t=QX(n||{});super(t);this.initConfig=t;let i=kF(t),r=CY(i),s=NF(r),f=yF(s),h=VY(f),_=EF(h),c=jF(_),o=VX(c,n?.extensions||[]);this.config=o,this.middlewareStack.use(IF(this.config)),this.middlewareStack.use(KY(this.config)),this.middlewareStack.use(BF(this.config)),this.middlewareStack.use($F(this.config)),this.middlewareStack.use(xY(this.config)),this.middlewareStack.use(jY(this.config)),this.middlewareStack.use(kY(this.config)),this.middlewareStack.use(mY(this.config,{httpAuthSchemeParametersProvider:CF,identityProviderConfigProvider:async(w)=>new ZY({"aws.auth#sigv4":w.credentials})})),this.middlewareStack.use(aY(this.config))}destroy(){super.destroy()}}var KX=fF(qF,"AWSSSOOIDCService","SSOOIDCClient",TF),xX={},jX=(n,t,i,r)=>[];class Hw extends KX(xX,jX,"CreateToken",FE){}var kX={CreateTokenCommand:Hw};class Gw extends Iw{}_F(kX,Gw);var qX={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},mX={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"};ZX.AccessDeniedException=Sh;ZX.AccessDeniedException$=SE;ZX.AccessDeniedExceptionReason=qX;ZX.AuthorizationPendingException=Lh;ZX.AuthorizationPendingException$=LE;ZX.CreateToken$=FE;ZX.CreateTokenCommand=Hw;ZX.CreateTokenRequest$=PE;ZX.CreateTokenResponse$=YE;ZX.ExpiredTokenException=$h;ZX.ExpiredTokenException$=$E;ZX.InternalServerException=Oh;ZX.InternalServerException$=OE;ZX.InvalidClientException=Uh;ZX.InvalidClientException$=UE;ZX.InvalidGrantException=bh;ZX.InvalidGrantException$=bE;ZX.InvalidRequestException=Nh;ZX.InvalidRequestException$=NE;ZX.InvalidRequestExceptionReason=mX;ZX.InvalidScopeException=Bh;ZX.InvalidScopeException$=BE;ZX.SSOOIDC=Gw;ZX.SSOOIDCClient=Iw;ZX.SSOOIDCServiceException=Cn;ZX.SSOOIDCServiceException$=gE;ZX.SlowDownException=Ih;ZX.SlowDownException$=IE;ZX.UnauthorizedClientException=Hh;ZX.UnauthorizedClientException$=HE;ZX.UnsupportedGrantTypeException=Gh;ZX.UnsupportedGrantTypeException$=GE;ZX.errorTypeRegistries=WE});import{Database as P2}from"bun:sqlite";import{existsSync as Y2}from"fs";import{homedir as He}from"os";import{dirname as F2,join as Ff}from"path";var Ge=5000,X2=30000,l2=25,J2=500,Q2=new Set(["id","email","auth_method","region","oidc_region","client_id","client_secret","profile_arn","start_url","refresh_token","access_token","expires_at","rate_limit_reset","is_healthy","unhealthy_reason","recovery_time","fail_count","last_used","used_count","limit_count","last_sync","overage_count"]);class Ls extends Error{constructor(n,t){super(n,t);this.name="OpenCodeAuthStoreError"}}function z2(n){if(typeof n!=="object"||n===null||!("code"in n))return!1;return String(n.code).toUpperCase().startsWith("SQLITE_BUSY")}function C2(n,t){let i=Math.min(l2*2**Math.min(n,5),J2,t),r=Math.max(1,Math.floor(i/2)),s=r+Math.floor(Math.random()*(i-r+1));Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,s)}function Pi(n){return{id:n.id,email:n.email,authMethod:n.auth_method,region:n.region,oidcRegion:n.oidc_region??void 0,clientId:n.client_id??void 0,clientSecret:n.client_secret??void 0,profileArn:n.profile_arn??void 0,startUrl:n.start_url??void 0,refreshToken:n.refresh_token,accessToken:n.access_token,expiresAt:n.expires_at,rateLimitResetTime:n.rate_limit_reset??0,isHealthy:(n.is_healthy??1)===1,unhealthyReason:n.unhealthy_reason??void 0,recoveryTime:n.recovery_time??void 0,failCount:n.fail_count??0,lastUsed:n.last_used??0,usedCount:n.used_count??0,limitCount:n.limit_count??0,lastSync:n.last_sync??0,overageCount:n.overage_count??0}}function V2(n,t){return t.refreshToken===n.refreshToken&&t.accessToken===n.accessToken&&t.expiresAt===n.expiresAt&&t.authMethod===n.authMethod&&t.clientId===n.clientId&&t.clientSecret===n.clientSecret&&t.profileArn===n.profileArn&&t.email===n.email&&t.startUrl===n.startUrl}function $s(n=process.env){let t=process.platform==="win32"?n.APPDATA??Ff(He(),"AppData","Roaming"):n.XDG_CONFIG_HOME??Ff(He(),".config");return Ff(t,"opencode","kiro.db")}function We(n){return Ff(F2(n),"kiro-auth-plugin")}class e0{path;db;constructor(n=$s()){this.path=n;if(!Y2(n))throw new Ls(`OpenCode Kiro auth database not found: ${n}. Run OpenCode Kiro authentication first or set auth_source to "local".`);this.db=new P2(n,{strict:!0}),this.db.run(`PRAGMA busy_timeout = ${Ge}`),this.validateSchema()}getAccounts(){return this.db.query(`
|
|
51
51
|
SELECT accounts.*
|
|
52
52
|
FROM accounts
|
|
53
53
|
WHERE NOT EXISTS (
|
|
54
54
|
SELECT 1 FROM removed_accounts
|
|
55
55
|
WHERE removed_accounts.id = accounts.id
|
|
56
56
|
)
|
|
57
|
-
`).all().map(
|
|
57
|
+
`).all().map(Pi)}getById(n){let t=this.selectById(n);return t===void 0?void 0:Pi(t)}recordSelection(n,t){return this.withImmediateTransaction(()=>{if(this.db.query(`
|
|
58
58
|
UPDATE accounts
|
|
59
59
|
SET last_used = ?,
|
|
60
60
|
used_count = COALESCE(used_count, 0) + 1
|
|
@@ -63,11 +63,11 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
63
63
|
SELECT 1 FROM removed_accounts
|
|
64
64
|
WHERE removed_accounts.id = accounts.id
|
|
65
65
|
)
|
|
66
|
-
`).run(t,n).changes!==1)return;let
|
|
66
|
+
`).run(t,n).changes!==1)return;let r=this.selectById(n);return r===void 0?void 0:Pi(r)})}markRateLimited(n,t){return this.withImmediateTransaction(()=>{this.db.query(`
|
|
67
67
|
UPDATE accounts
|
|
68
68
|
SET rate_limit_reset = MAX(COALESCE(rate_limit_reset, 0), ?)
|
|
69
69
|
WHERE id = ?
|
|
70
|
-
`).run(t,n);let i=this.selectById(n);return i===void 0?void 0:
|
|
70
|
+
`).run(t,n);let i=this.selectById(n);return i===void 0?void 0:Pi(i)})}markUnhealthy(n,t,i,r,s){return this.withImmediateTransaction(()=>{if(i)this.db.query(`
|
|
71
71
|
UPDATE accounts
|
|
72
72
|
SET fail_count = 10,
|
|
73
73
|
is_healthy = 0,
|
|
@@ -75,7 +75,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
75
75
|
recovery_time = NULL,
|
|
76
76
|
last_used = ?
|
|
77
77
|
WHERE id = ?
|
|
78
|
-
`).run(t,
|
|
78
|
+
`).run(t,s,n);else this.db.query(`
|
|
79
79
|
UPDATE accounts
|
|
80
80
|
SET fail_count = COALESCE(fail_count, 0) + 1,
|
|
81
81
|
is_healthy =
|
|
@@ -88,7 +88,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
88
88
|
END,
|
|
89
89
|
last_used = ?
|
|
90
90
|
WHERE id = ?
|
|
91
|
-
`).run(t,s
|
|
91
|
+
`).run(t,r??s+3600000,s,n);let f=this.selectById(n);return f===void 0?void 0:Pi(f)})}persistRefreshedAccount(n,t){return this.withImmediateTransaction(()=>{let i=this.selectById(n.id);if(i===void 0)return;let r=Pi(i);if(!V2(n,r))return r;this.db.query(`
|
|
92
92
|
UPDATE accounts
|
|
93
93
|
SET email = ?,
|
|
94
94
|
oidc_region = ?,
|
|
@@ -105,7 +105,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
105
105
|
fail_count = 0,
|
|
106
106
|
last_used = ?
|
|
107
107
|
WHERE id = ?
|
|
108
|
-
`).run(t.email,t.oidcRegion??null,t.clientId??null,t.clientSecret??null,t.profileArn??null,t.startUrl??null,t.refreshToken,t.accessToken,t.expiresAt,t.lastUsed??Date.now(),t.id);let
|
|
108
|
+
`).run(t.email,t.oidcRegion??null,t.clientId??null,t.clientSecret??null,t.profileArn??null,t.startUrl??null,t.refreshToken,t.accessToken,t.expiresAt,t.lastUsed??Date.now(),t.id);let s=this.selectById(t.id);return s===void 0?void 0:Pi(s)})}close(){this.db.close()}selectById(n){let t=this.db.query(`
|
|
109
109
|
SELECT accounts.*
|
|
110
110
|
FROM accounts
|
|
111
111
|
WHERE accounts.id = ?
|
|
@@ -113,17 +113,18 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
113
113
|
SELECT 1 FROM removed_accounts
|
|
114
114
|
WHERE removed_accounts.id = accounts.id
|
|
115
115
|
)
|
|
116
|
-
`).get(n);return t===null?void 0:t}validateSchema(){let n=new Set(this.db.query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map(({name:s})=>s));for(let s of["accounts","removed_accounts"])if(!n.has(s))throw new or(`OpenCode Kiro auth database ${this.path} is missing table ${s}; update opencode-kiro-auth and authenticate again.`);let t=new Set(this.db.query("PRAGMA table_info(accounts)").all().map(({name:s})=>s)),i=[...KT].filter((s)=>!t.has(s));if(i.length>0)throw new or(`OpenCode Kiro auth database ${this.path} is missing required account columns: ${i.join(", ")}`)}withImmediateTransaction(n){let t=Date.now()+QT,i=0;for(;;){let s=!1,r;try{this.db.run("PRAGMA busy_timeout = 0"),this.db.exec("BEGIN IMMEDIATE"),s=!0}catch(e){r=e}finally{this.db.run(`PRAGMA busy_timeout = ${f0}`)}if(!s){if(!kT(r))throw r;let e=t-Date.now();if(e<=0)throw new or(`Timed out waiting for the OpenCode Kiro auth database write lock: ${this.path}`,{cause:r});qT(i,e),i+=1;continue}try{let e=n();return this.db.exec("COMMIT"),e}catch(e){throw this.db.exec("ROLLBACK"),e}}}}import{existsSync as h2,readFileSync as u2}from"fs";import{homedir as c2}from"os";import{join as T0}from"path";var M={};mT(M,{void:()=>H4,util:()=>j,unknown:()=>N4,union:()=>D4,undefined:()=>L4,tuple:()=>J4,transformer:()=>j4,symbol:()=>$4,string:()=>R0,strictObject:()=>P4,setErrorMap:()=>vT,set:()=>Q4,record:()=>X4,quotelessJson:()=>jT,promise:()=>V4,preprocess:()=>Z4,pipeline:()=>p4,ostring:()=>n2,optional:()=>a4,onumber:()=>t2,oboolean:()=>i2,objectUtil:()=>nh,object:()=>F4,number:()=>E0,nullable:()=>v4,null:()=>O4,never:()=>G4,nativeEnum:()=>q4,nan:()=>I4,map:()=>z4,makeIssue:()=>hr,literal:()=>K4,lazy:()=>x4,late:()=>g4,isValid:()=>qt,isDirty:()=>Ie,isAsync:()=>is,isAborted:()=>Se,intersection:()=>m4,instanceof:()=>S4,getParsedType:()=>Rt,getErrorMap:()=>ts,function:()=>C4,enum:()=>k4,effect:()=>j4,discriminatedUnion:()=>Y4,defaultErrorMap:()=>Ft,datetimeRegex:()=>A0,date:()=>b4,custom:()=>d0,coerce:()=>s2,boolean:()=>y0,bigint:()=>U4,array:()=>W4,any:()=>B4,addIssueToContext:()=>O,ZodVoid:()=>cr,ZodUnknown:()=>Vt,ZodUnion:()=>hs,ZodUndefined:()=>os,ZodType:()=>q,ZodTuple:()=>yt,ZodTransformer:()=>ht,ZodSymbol:()=>ur,ZodString:()=>rt,ZodSet:()=>bi,ZodSchema:()=>q,ZodRecord:()=>_r,ZodReadonly:()=>Ms,ZodPromise:()=>$i,ZodPipeline:()=>Ar,ZodParsedType:()=>L,ZodOptional:()=>ot,ZodObject:()=>wn,ZodNumber:()=>jt,ZodNullable:()=>Dt,ZodNull:()=>fs,ZodNever:()=>Et,ZodNativeEnum:()=>ws,ZodNaN:()=>lr,ZodMap:()=>wr,ZodLiteral:()=>_s,ZodLazy:()=>cs,ZodIssueCode:()=>U,ZodIntersection:()=>us,ZodFunction:()=>rs,ZodFirstPartyTypeKind:()=>z,ZodError:()=>Pn,ZodEnum:()=>vt,ZodEffects:()=>ht,ZodDiscriminatedUnion:()=>Ue,ZodDefault:()=>ls,ZodDate:()=>Ii,ZodCatch:()=>As,ZodBranded:()=>be,ZodBoolean:()=>es,ZodBigInt:()=>at,ZodArray:()=>et,ZodAny:()=>Ui,Schema:()=>q,ParseStatus:()=>bn,OK:()=>Nn,NEVER:()=>r2,INVALID:()=>J,EMPTY_PATH:()=>ZT,DIRTY:()=>Si,BRAND:()=>T4});var j;(function(n){n.assertEqual=(r)=>{};function t(r){}n.assertIs=t;function i(r){throw Error()}n.assertNever=i,n.arrayToEnum=(r)=>{let e={};for(let f of r)e[f]=f;return e},n.getValidEnumValues=(r)=>{let e=n.objectKeys(r).filter((o)=>typeof r[r[o]]!=="number"),f={};for(let o of e)f[o]=r[o];return n.objectValues(f)},n.objectValues=(r)=>{return n.objectKeys(r).map(function(e){return r[e]})},n.objectKeys=typeof Object.keys==="function"?(r)=>Object.keys(r):(r)=>{let e=[];for(let f in r)if(Object.prototype.hasOwnProperty.call(r,f))e.push(f);return e},n.find=(r,e)=>{for(let f of r)if(e(f))return f;return},n.isInteger=typeof Number.isInteger==="function"?(r)=>Number.isInteger(r):(r)=>typeof r==="number"&&Number.isFinite(r)&&Math.floor(r)===r;function s(r,e=" | "){return r.map((f)=>typeof f==="string"?`'${f}'`:f).join(e)}n.joinValues=s,n.jsonStringifyReplacer=(r,e)=>{if(typeof e==="bigint")return e.toString();return e}})(j||(j={}));var nh;(function(n){n.mergeShapes=(t,i)=>{return{...t,...i}}})(nh||(nh={}));var L=j.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Rt=(n)=>{switch(typeof n){case"undefined":return L.undefined;case"string":return L.string;case"number":return Number.isNaN(n)?L.nan:L.number;case"boolean":return L.boolean;case"function":return L.function;case"bigint":return L.bigint;case"symbol":return L.symbol;case"object":if(Array.isArray(n))return L.array;if(n===null)return L.null;if(n.then&&typeof n.then==="function"&&n.catch&&typeof n.catch==="function")return L.promise;if(typeof Map<"u"&&n instanceof Map)return L.map;if(typeof Set<"u"&&n instanceof Set)return L.set;if(typeof Date<"u"&&n instanceof Date)return L.date;return L.object;default:return L.unknown}};var U=j.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),jT=(n)=>{return JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:")};class Pn extends Error{get errors(){return this.issues}constructor(n){super();this.issues=[],this.addIssue=(i)=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=n}format(n){let t=n||function(r){return r.message},i={_errors:[]},s=(r)=>{for(let e of r.issues)if(e.code==="invalid_union")e.unionErrors.map(s);else if(e.code==="invalid_return_type")s(e.returnTypeError);else if(e.code==="invalid_arguments")s(e.argumentsError);else if(e.path.length===0)i._errors.push(t(e));else{let f=i,o=0;while(o<e.path.length){let h=e.path[o];if(o!==e.path.length-1)f[h]=f[h]||{_errors:[]};else f[h]=f[h]||{_errors:[]},f[h]._errors.push(t(e));f=f[h],o++}}};return s(this),i}static assert(n){if(!(n instanceof Pn))throw Error(`Not a ZodError: ${n}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,j.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(n=(t)=>t.message){let t={},i=[];for(let s of this.issues)if(s.path.length>0){let r=s.path[0];t[r]=t[r]||[],t[r].push(n(s))}else i.push(n(s));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}Pn.create=(n)=>{return new Pn(n)};var aT=(n,t)=>{let i;switch(n.code){case U.invalid_type:if(n.received===L.undefined)i="Required";else i=`Expected ${n.expected}, received ${n.received}`;break;case U.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(n.expected,j.jsonStringifyReplacer)}`;break;case U.unrecognized_keys:i=`Unrecognized key(s) in object: ${j.joinValues(n.keys,", ")}`;break;case U.invalid_union:i="Invalid input";break;case U.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${j.joinValues(n.options)}`;break;case U.invalid_enum_value:i=`Invalid enum value. Expected ${j.joinValues(n.options)}, received '${n.received}'`;break;case U.invalid_arguments:i="Invalid function arguments";break;case U.invalid_return_type:i="Invalid function return type";break;case U.invalid_date:i="Invalid date";break;case U.invalid_string:if(typeof n.validation==="object")if("includes"in n.validation){if(i=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position==="number")i=`${i} at one or more positions greater than or equal to ${n.validation.position}`}else if("startsWith"in n.validation)i=`Invalid input: must start with "${n.validation.startsWith}"`;else if("endsWith"in n.validation)i=`Invalid input: must end with "${n.validation.endsWith}"`;else j.assertNever(n.validation);else if(n.validation!=="regex")i=`Invalid ${n.validation}`;else i="Invalid";break;case U.too_small:if(n.type==="array")i=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`;else if(n.type==="string")i=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`;else if(n.type==="number")i=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`;else if(n.type==="bigint")i=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`;else if(n.type==="date")i=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`;else i="Invalid input";break;case U.too_big:if(n.type==="array")i=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`;else if(n.type==="string")i=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`;else if(n.type==="number")i=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`;else if(n.type==="bigint")i=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`;else if(n.type==="date")i=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`;else i="Invalid input";break;case U.custom:i="Invalid input";break;case U.invalid_intersection_types:i="Intersection results could not be merged";break;case U.not_multiple_of:i=`Number must be a multiple of ${n.multipleOf}`;break;case U.not_finite:i="Number must be finite";break;default:i=t.defaultError,j.assertNever(n)}return{message:i}},Ft=aT;var u0=Ft;function vT(n){u0=n}function ts(){return u0}var hr=(n)=>{let{data:t,path:i,errorMaps:s,issueData:r}=n,e=[...i,...r.path||[]],f={...r,path:e};if(r.message!==void 0)return{...r,path:e,message:r.message};let o="",h=s.filter((u)=>!!u).slice().reverse();for(let u of h)o=u(f,{data:t,defaultError:o}).message;return{...r,path:e,message:o}},ZT=[];function O(n,t){let i=ts(),s=hr({issueData:t,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,i,i===Ft?void 0:Ft].filter((r)=>!!r)});n.common.issues.push(s)}class bn{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(n,t){let i=[];for(let s of t){if(s.status==="aborted")return J;if(s.status==="dirty")n.dirty();i.push(s.value)}return{status:n.value,value:i}}static async mergeObjectAsync(n,t){let i=[];for(let s of t){let r=await s.key,e=await s.value;i.push({key:r,value:e})}return bn.mergeObjectSync(n,i)}static mergeObjectSync(n,t){let i={};for(let s of t){let{key:r,value:e}=s;if(r.status==="aborted")return J;if(e.status==="aborted")return J;if(r.status==="dirty")n.dirty();if(e.status==="dirty")n.dirty();if(r.value!=="__proto__"&&(typeof e.value<"u"||s.alwaysSet))i[r.value]=e.value}return{status:n.value,value:i}}}var J=Object.freeze({status:"aborted"}),Si=(n)=>({status:"dirty",value:n}),Nn=(n)=>({status:"valid",value:n}),Se=(n)=>n.status==="aborted",Ie=(n)=>n.status==="dirty",qt=(n)=>n.status==="valid",is=(n)=>typeof Promise<"u"&&n instanceof Promise;var P;(function(n){n.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},n.toString=(t)=>typeof t==="string"?t:t?.message})(P||(P={}));class ft{constructor(n,t,i,s){this._cachedPath=[],this.parent=n,this.data=t,this._path=i,this._key=s}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var c0=(n,t)=>{if(qt(t))return{success:!0,data:t.value};else{if(!n.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let i=new Pn(n.common.issues);return this._error=i,this._error}}}};function K(n){if(!n)return{};let{errorMap:t,invalid_type_error:i,required_error:s,description:r}=n;if(t&&(i||s))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:r};return{errorMap:(f,o)=>{let{message:h}=n;if(f.code==="invalid_enum_value")return{message:h??o.defaultError};if(typeof o.data>"u")return{message:h??s??o.defaultError};if(f.code!=="invalid_type")return{message:o.defaultError};return{message:h??i??o.defaultError}},description:r}}class q{get description(){return this._def.description}_getType(n){return Rt(n.data)}_getOrReturnCtx(n,t){return t||{common:n.parent.common,data:n.data,parsedType:Rt(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}_processInputParams(n){return{status:new bn,ctx:{common:n.parent.common,data:n.data,parsedType:Rt(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}}_parseSync(n){let t=this._parse(n);if(is(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(n){let t=this._parse(n);return Promise.resolve(t)}parse(n,t){let i=this.safeParse(n,t);if(i.success)return i.data;throw i.error}safeParse(n,t){let i={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Rt(n)},s=this._parseSync({data:n,path:i.path,parent:i});return c0(i,s)}"~validate"(n){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Rt(n)};if(!this["~standard"].async)try{let i=this._parseSync({data:n,path:[],parent:t});return qt(i)?{value:i.value}:{issues:t.common.issues}}catch(i){if(i?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:n,path:[],parent:t}).then((i)=>qt(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(n,t){let i=await this.safeParseAsync(n,t);if(i.success)return i.data;throw i.error}async safeParseAsync(n,t){let i={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Rt(n)},s=this._parse({data:n,path:i.path,parent:i}),r=await(is(s)?s:Promise.resolve(s));return c0(i,r)}refine(n,t){let i=(s)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(s);else return t};return this._refinement((s,r)=>{let e=n(s),f=()=>r.addIssue({code:U.custom,...i(s)});if(typeof Promise<"u"&&e instanceof Promise)return e.then((o)=>{if(!o)return f(),!1;else return!0});if(!e)return f(),!1;else return!0})}refinement(n,t){return this._refinement((i,s)=>{if(!n(i))return s.addIssue(typeof t==="function"?t(i,s):t),!1;else return!0})}_refinement(n){return new ht({schema:this,typeName:z.ZodEffects,effect:{type:"refinement",refinement:n}})}superRefine(n){return this._refinement(n)}constructor(n){this.spa=this.safeParseAsync,this._def=n,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(t)=>this["~validate"](t)}}optional(){return ot.create(this,this._def)}nullable(){return Dt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return et.create(this)}promise(){return $i.create(this,this._def)}or(n){return hs.create([this,n],this._def)}and(n){return us.create(this,n,this._def)}transform(n){return new ht({...K(this._def),schema:this,typeName:z.ZodEffects,effect:{type:"transform",transform:n}})}default(n){let t=typeof n==="function"?n:()=>n;return new ls({...K(this._def),innerType:this,defaultValue:t,typeName:z.ZodDefault})}brand(){return new be({typeName:z.ZodBranded,type:this,...K(this._def)})}catch(n){let t=typeof n==="function"?n:()=>n;return new As({...K(this._def),innerType:this,catchValue:t,typeName:z.ZodCatch})}describe(n){return new this.constructor({...this._def,description:n})}pipe(n){return Ar.create(this,n)}readonly(){return Ms.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var pT=/^c[^\s-]{8,}$/i,n4=/^[0-9a-z]+$/,t4=/^[0-9A-HJKMNP-TV-Z]{26}$/i,i4=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,s4=/^[a-z0-9_-]{21}$/i,r4=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,e4=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,o4=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,f4="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",th,h4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,u4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,c4=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,_4=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,w4=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,l4=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,w0="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",A4=new RegExp(`^${w0}$`);function l0(n){let t="[0-5]\\d";if(n.precision)t=`${t}\\.\\d{${n.precision}}`;else if(n.precision==null)t=`${t}(\\.\\d+)?`;let i=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${i}`}function M4(n){return new RegExp(`^${l0(n)}$`)}function A0(n){let t=`${w0}T${l0(n)}`,i=[];if(i.push(n.local?"Z?":"Z"),n.offset)i.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${i.join("|")})`,new RegExp(`^${t}$`)}function d4(n,t){if((t==="v4"||!t)&&h4.test(n))return!0;if((t==="v6"||!t)&&c4.test(n))return!0;return!1}function R4(n,t){if(!r4.test(n))return!1;try{let[i]=n.split(".");if(!i)return!1;let s=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(i.length+(4-i.length%4)%4,"="),r=JSON.parse(atob(s));if(typeof r!=="object"||r===null)return!1;if("typ"in r&&r?.typ!=="JWT")return!1;if(!r.alg)return!1;if(t&&r.alg!==t)return!1;return!0}catch{return!1}}function E4(n,t){if((t==="v4"||!t)&&u4.test(n))return!0;if((t==="v6"||!t)&&_4.test(n))return!0;return!1}class rt extends q{_parse(n){if(this._def.coerce)n.data=String(n.data);if(this._getType(n)!==L.string){let r=this._getOrReturnCtx(n);return O(r,{code:U.invalid_type,expected:L.string,received:r.parsedType}),J}let i=new bn,s=void 0;for(let r of this._def.checks)if(r.kind==="min"){if(n.data.length<r.value)s=this._getOrReturnCtx(n,s),O(s,{code:U.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty()}else if(r.kind==="max"){if(n.data.length>r.value)s=this._getOrReturnCtx(n,s),O(s,{code:U.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty()}else if(r.kind==="length"){let e=n.data.length>r.value,f=n.data.length<r.value;if(e||f){if(s=this._getOrReturnCtx(n,s),e)O(s,{code:U.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message});else if(f)O(s,{code:U.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message});i.dirty()}}else if(r.kind==="email"){if(!o4.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"email",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="emoji"){if(!th)th=new RegExp(f4,"u");if(!th.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"emoji",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="uuid"){if(!i4.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"uuid",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="nanoid"){if(!s4.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"nanoid",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="cuid"){if(!pT.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"cuid",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="cuid2"){if(!n4.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"cuid2",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="ulid"){if(!t4.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"ulid",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="url")try{new URL(n.data)}catch{s=this._getOrReturnCtx(n,s),O(s,{validation:"url",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="regex"){if(r.regex.lastIndex=0,!r.regex.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"regex",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="trim")n.data=n.data.trim();else if(r.kind==="includes"){if(!n.data.includes(r.value,r.position))s=this._getOrReturnCtx(n,s),O(s,{code:U.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),i.dirty()}else if(r.kind==="toLowerCase")n.data=n.data.toLowerCase();else if(r.kind==="toUpperCase")n.data=n.data.toUpperCase();else if(r.kind==="startsWith"){if(!n.data.startsWith(r.value))s=this._getOrReturnCtx(n,s),O(s,{code:U.invalid_string,validation:{startsWith:r.value},message:r.message}),i.dirty()}else if(r.kind==="endsWith"){if(!n.data.endsWith(r.value))s=this._getOrReturnCtx(n,s),O(s,{code:U.invalid_string,validation:{endsWith:r.value},message:r.message}),i.dirty()}else if(r.kind==="datetime"){if(!A0(r).test(n.data))s=this._getOrReturnCtx(n,s),O(s,{code:U.invalid_string,validation:"datetime",message:r.message}),i.dirty()}else if(r.kind==="date"){if(!A4.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{code:U.invalid_string,validation:"date",message:r.message}),i.dirty()}else if(r.kind==="time"){if(!M4(r).test(n.data))s=this._getOrReturnCtx(n,s),O(s,{code:U.invalid_string,validation:"time",message:r.message}),i.dirty()}else if(r.kind==="duration"){if(!e4.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"duration",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="ip"){if(!d4(n.data,r.version))s=this._getOrReturnCtx(n,s),O(s,{validation:"ip",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="jwt"){if(!R4(n.data,r.alg))s=this._getOrReturnCtx(n,s),O(s,{validation:"jwt",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="cidr"){if(!E4(n.data,r.version))s=this._getOrReturnCtx(n,s),O(s,{validation:"cidr",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="base64"){if(!w4.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"base64",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="base64url"){if(!l4.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"base64url",code:U.invalid_string,message:r.message}),i.dirty()}else j.assertNever(r);return{status:i.value,value:n.data}}_regex(n,t,i){return this.refinement((s)=>n.test(s),{validation:t,code:U.invalid_string,...P.errToObj(i)})}_addCheck(n){return new rt({...this._def,checks:[...this._def.checks,n]})}email(n){return this._addCheck({kind:"email",...P.errToObj(n)})}url(n){return this._addCheck({kind:"url",...P.errToObj(n)})}emoji(n){return this._addCheck({kind:"emoji",...P.errToObj(n)})}uuid(n){return this._addCheck({kind:"uuid",...P.errToObj(n)})}nanoid(n){return this._addCheck({kind:"nanoid",...P.errToObj(n)})}cuid(n){return this._addCheck({kind:"cuid",...P.errToObj(n)})}cuid2(n){return this._addCheck({kind:"cuid2",...P.errToObj(n)})}ulid(n){return this._addCheck({kind:"ulid",...P.errToObj(n)})}base64(n){return this._addCheck({kind:"base64",...P.errToObj(n)})}base64url(n){return this._addCheck({kind:"base64url",...P.errToObj(n)})}jwt(n){return this._addCheck({kind:"jwt",...P.errToObj(n)})}ip(n){return this._addCheck({kind:"ip",...P.errToObj(n)})}cidr(n){return this._addCheck({kind:"cidr",...P.errToObj(n)})}datetime(n){if(typeof n==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:n});return this._addCheck({kind:"datetime",precision:typeof n?.precision>"u"?null:n?.precision,offset:n?.offset??!1,local:n?.local??!1,...P.errToObj(n?.message)})}date(n){return this._addCheck({kind:"date",message:n})}time(n){if(typeof n==="string")return this._addCheck({kind:"time",precision:null,message:n});return this._addCheck({kind:"time",precision:typeof n?.precision>"u"?null:n?.precision,...P.errToObj(n?.message)})}duration(n){return this._addCheck({kind:"duration",...P.errToObj(n)})}regex(n,t){return this._addCheck({kind:"regex",regex:n,...P.errToObj(t)})}includes(n,t){return this._addCheck({kind:"includes",value:n,position:t?.position,...P.errToObj(t?.message)})}startsWith(n,t){return this._addCheck({kind:"startsWith",value:n,...P.errToObj(t)})}endsWith(n,t){return this._addCheck({kind:"endsWith",value:n,...P.errToObj(t)})}min(n,t){return this._addCheck({kind:"min",value:n,...P.errToObj(t)})}max(n,t){return this._addCheck({kind:"max",value:n,...P.errToObj(t)})}length(n,t){return this._addCheck({kind:"length",value:n,...P.errToObj(t)})}nonempty(n){return this.min(1,P.errToObj(n))}trim(){return new rt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new rt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new rt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((n)=>n.kind==="datetime")}get isDate(){return!!this._def.checks.find((n)=>n.kind==="date")}get isTime(){return!!this._def.checks.find((n)=>n.kind==="time")}get isDuration(){return!!this._def.checks.find((n)=>n.kind==="duration")}get isEmail(){return!!this._def.checks.find((n)=>n.kind==="email")}get isURL(){return!!this._def.checks.find((n)=>n.kind==="url")}get isEmoji(){return!!this._def.checks.find((n)=>n.kind==="emoji")}get isUUID(){return!!this._def.checks.find((n)=>n.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((n)=>n.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((n)=>n.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((n)=>n.kind==="cuid2")}get isULID(){return!!this._def.checks.find((n)=>n.kind==="ulid")}get isIP(){return!!this._def.checks.find((n)=>n.kind==="ip")}get isCIDR(){return!!this._def.checks.find((n)=>n.kind==="cidr")}get isBase64(){return!!this._def.checks.find((n)=>n.kind==="base64")}get isBase64url(){return!!this._def.checks.find((n)=>n.kind==="base64url")}get minLength(){let n=null;for(let t of this._def.checks)if(t.kind==="min"){if(n===null||t.value>n)n=t.value}return n}get maxLength(){let n=null;for(let t of this._def.checks)if(t.kind==="max"){if(n===null||t.value<n)n=t.value}return n}}rt.create=(n)=>{return new rt({checks:[],typeName:z.ZodString,coerce:n?.coerce??!1,...K(n)})};function y4(n,t){let i=(n.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,r=i>s?i:s,e=Number.parseInt(n.toFixed(r).replace(".","")),f=Number.parseInt(t.toFixed(r).replace(".",""));return e%f/10**r}class jt extends q{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(n){if(this._def.coerce)n.data=Number(n.data);if(this._getType(n)!==L.number){let r=this._getOrReturnCtx(n);return O(r,{code:U.invalid_type,expected:L.number,received:r.parsedType}),J}let i=void 0,s=new bn;for(let r of this._def.checks)if(r.kind==="int"){if(!j.isInteger(n.data))i=this._getOrReturnCtx(n,i),O(i,{code:U.invalid_type,expected:"integer",received:"float",message:r.message}),s.dirty()}else if(r.kind==="min"){if(r.inclusive?n.data<r.value:n.data<=r.value)i=this._getOrReturnCtx(n,i),O(i,{code:U.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),s.dirty()}else if(r.kind==="max"){if(r.inclusive?n.data>r.value:n.data>=r.value)i=this._getOrReturnCtx(n,i),O(i,{code:U.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),s.dirty()}else if(r.kind==="multipleOf"){if(y4(n.data,r.value)!==0)i=this._getOrReturnCtx(n,i),O(i,{code:U.not_multiple_of,multipleOf:r.value,message:r.message}),s.dirty()}else if(r.kind==="finite"){if(!Number.isFinite(n.data))i=this._getOrReturnCtx(n,i),O(i,{code:U.not_finite,message:r.message}),s.dirty()}else j.assertNever(r);return{status:s.value,value:n.data}}gte(n,t){return this.setLimit("min",n,!0,P.toString(t))}gt(n,t){return this.setLimit("min",n,!1,P.toString(t))}lte(n,t){return this.setLimit("max",n,!0,P.toString(t))}lt(n,t){return this.setLimit("max",n,!1,P.toString(t))}setLimit(n,t,i,s){return new jt({...this._def,checks:[...this._def.checks,{kind:n,value:t,inclusive:i,message:P.toString(s)}]})}_addCheck(n){return new jt({...this._def,checks:[...this._def.checks,n]})}int(n){return this._addCheck({kind:"int",message:P.toString(n)})}positive(n){return this._addCheck({kind:"min",value:0,inclusive:!1,message:P.toString(n)})}negative(n){return this._addCheck({kind:"max",value:0,inclusive:!1,message:P.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:0,inclusive:!0,message:P.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:0,inclusive:!0,message:P.toString(n)})}multipleOf(n,t){return this._addCheck({kind:"multipleOf",value:n,message:P.toString(t)})}finite(n){return this._addCheck({kind:"finite",message:P.toString(n)})}safe(n){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:P.toString(n)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:P.toString(n)})}get minValue(){let n=null;for(let t of this._def.checks)if(t.kind==="min"){if(n===null||t.value>n)n=t.value}return n}get maxValue(){let n=null;for(let t of this._def.checks)if(t.kind==="max"){if(n===null||t.value<n)n=t.value}return n}get isInt(){return!!this._def.checks.find((n)=>n.kind==="int"||n.kind==="multipleOf"&&j.isInteger(n.value))}get isFinite(){let n=null,t=null;for(let i of this._def.checks)if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;else if(i.kind==="min"){if(t===null||i.value>t)t=i.value}else if(i.kind==="max"){if(n===null||i.value<n)n=i.value}return Number.isFinite(t)&&Number.isFinite(n)}}jt.create=(n)=>{return new jt({checks:[],typeName:z.ZodNumber,coerce:n?.coerce||!1,...K(n)})};class at extends q{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(n){if(this._def.coerce)try{n.data=BigInt(n.data)}catch{return this._getInvalidInput(n)}if(this._getType(n)!==L.bigint)return this._getInvalidInput(n);let i=void 0,s=new bn;for(let r of this._def.checks)if(r.kind==="min"){if(r.inclusive?n.data<r.value:n.data<=r.value)i=this._getOrReturnCtx(n,i),O(i,{code:U.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),s.dirty()}else if(r.kind==="max"){if(r.inclusive?n.data>r.value:n.data>=r.value)i=this._getOrReturnCtx(n,i),O(i,{code:U.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),s.dirty()}else if(r.kind==="multipleOf"){if(n.data%r.value!==BigInt(0))i=this._getOrReturnCtx(n,i),O(i,{code:U.not_multiple_of,multipleOf:r.value,message:r.message}),s.dirty()}else j.assertNever(r);return{status:s.value,value:n.data}}_getInvalidInput(n){let t=this._getOrReturnCtx(n);return O(t,{code:U.invalid_type,expected:L.bigint,received:t.parsedType}),J}gte(n,t){return this.setLimit("min",n,!0,P.toString(t))}gt(n,t){return this.setLimit("min",n,!1,P.toString(t))}lte(n,t){return this.setLimit("max",n,!0,P.toString(t))}lt(n,t){return this.setLimit("max",n,!1,P.toString(t))}setLimit(n,t,i,s){return new at({...this._def,checks:[...this._def.checks,{kind:n,value:t,inclusive:i,message:P.toString(s)}]})}_addCheck(n){return new at({...this._def,checks:[...this._def.checks,n]})}positive(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:P.toString(n)})}negative(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:P.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:P.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:P.toString(n)})}multipleOf(n,t){return this._addCheck({kind:"multipleOf",value:n,message:P.toString(t)})}get minValue(){let n=null;for(let t of this._def.checks)if(t.kind==="min"){if(n===null||t.value>n)n=t.value}return n}get maxValue(){let n=null;for(let t of this._def.checks)if(t.kind==="max"){if(n===null||t.value<n)n=t.value}return n}}at.create=(n)=>{return new at({checks:[],typeName:z.ZodBigInt,coerce:n?.coerce??!1,...K(n)})};class es extends q{_parse(n){if(this._def.coerce)n.data=Boolean(n.data);if(this._getType(n)!==L.boolean){let i=this._getOrReturnCtx(n);return O(i,{code:U.invalid_type,expected:L.boolean,received:i.parsedType}),J}return Nn(n.data)}}es.create=(n)=>{return new es({typeName:z.ZodBoolean,coerce:n?.coerce||!1,...K(n)})};class Ii extends q{_parse(n){if(this._def.coerce)n.data=new Date(n.data);if(this._getType(n)!==L.date){let r=this._getOrReturnCtx(n);return O(r,{code:U.invalid_type,expected:L.date,received:r.parsedType}),J}if(Number.isNaN(n.data.getTime())){let r=this._getOrReturnCtx(n);return O(r,{code:U.invalid_date}),J}let i=new bn,s=void 0;for(let r of this._def.checks)if(r.kind==="min"){if(n.data.getTime()<r.value)s=this._getOrReturnCtx(n,s),O(s,{code:U.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),i.dirty()}else if(r.kind==="max"){if(n.data.getTime()>r.value)s=this._getOrReturnCtx(n,s),O(s,{code:U.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),i.dirty()}else j.assertNever(r);return{status:i.value,value:new Date(n.data.getTime())}}_addCheck(n){return new Ii({...this._def,checks:[...this._def.checks,n]})}min(n,t){return this._addCheck({kind:"min",value:n.getTime(),message:P.toString(t)})}max(n,t){return this._addCheck({kind:"max",value:n.getTime(),message:P.toString(t)})}get minDate(){let n=null;for(let t of this._def.checks)if(t.kind==="min"){if(n===null||t.value>n)n=t.value}return n!=null?new Date(n):null}get maxDate(){let n=null;for(let t of this._def.checks)if(t.kind==="max"){if(n===null||t.value<n)n=t.value}return n!=null?new Date(n):null}}Ii.create=(n)=>{return new Ii({checks:[],coerce:n?.coerce||!1,typeName:z.ZodDate,...K(n)})};class ur extends q{_parse(n){if(this._getType(n)!==L.symbol){let i=this._getOrReturnCtx(n);return O(i,{code:U.invalid_type,expected:L.symbol,received:i.parsedType}),J}return Nn(n.data)}}ur.create=(n)=>{return new ur({typeName:z.ZodSymbol,...K(n)})};class os extends q{_parse(n){if(this._getType(n)!==L.undefined){let i=this._getOrReturnCtx(n);return O(i,{code:U.invalid_type,expected:L.undefined,received:i.parsedType}),J}return Nn(n.data)}}os.create=(n)=>{return new os({typeName:z.ZodUndefined,...K(n)})};class fs extends q{_parse(n){if(this._getType(n)!==L.null){let i=this._getOrReturnCtx(n);return O(i,{code:U.invalid_type,expected:L.null,received:i.parsedType}),J}return Nn(n.data)}}fs.create=(n)=>{return new fs({typeName:z.ZodNull,...K(n)})};class Ui extends q{constructor(){super(...arguments);this._any=!0}_parse(n){return Nn(n.data)}}Ui.create=(n)=>{return new Ui({typeName:z.ZodAny,...K(n)})};class Vt extends q{constructor(){super(...arguments);this._unknown=!0}_parse(n){return Nn(n.data)}}Vt.create=(n)=>{return new Vt({typeName:z.ZodUnknown,...K(n)})};class Et extends q{_parse(n){let t=this._getOrReturnCtx(n);return O(t,{code:U.invalid_type,expected:L.never,received:t.parsedType}),J}}Et.create=(n)=>{return new Et({typeName:z.ZodNever,...K(n)})};class cr extends q{_parse(n){if(this._getType(n)!==L.undefined){let i=this._getOrReturnCtx(n);return O(i,{code:U.invalid_type,expected:L.void,received:i.parsedType}),J}return Nn(n.data)}}cr.create=(n)=>{return new cr({typeName:z.ZodVoid,...K(n)})};class et extends q{_parse(n){let{ctx:t,status:i}=this._processInputParams(n),s=this._def;if(t.parsedType!==L.array)return O(t,{code:U.invalid_type,expected:L.array,received:t.parsedType}),J;if(s.exactLength!==null){let e=t.data.length>s.exactLength.value,f=t.data.length<s.exactLength.value;if(e||f)O(t,{code:e?U.too_big:U.too_small,minimum:f?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty()}if(s.minLength!==null){if(t.data.length<s.minLength.value)O(t,{code:U.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()}if(s.maxLength!==null){if(t.data.length>s.maxLength.value)O(t,{code:U.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()}if(t.common.async)return Promise.all([...t.data].map((e,f)=>{return s.type._parseAsync(new ft(t,e,t.path,f))})).then((e)=>{return bn.mergeArray(i,e)});let r=[...t.data].map((e,f)=>{return s.type._parseSync(new ft(t,e,t.path,f))});return bn.mergeArray(i,r)}get element(){return this._def.type}min(n,t){return new et({...this._def,minLength:{value:n,message:P.toString(t)}})}max(n,t){return new et({...this._def,maxLength:{value:n,message:P.toString(t)}})}length(n,t){return new et({...this._def,exactLength:{value:n,message:P.toString(t)}})}nonempty(n){return this.min(1,n)}}et.create=(n,t)=>{return new et({type:n,minLength:null,maxLength:null,exactLength:null,typeName:z.ZodArray,...K(t)})};function ss(n){if(n instanceof wn){let t={};for(let i in n.shape){let s=n.shape[i];t[i]=ot.create(ss(s))}return new wn({...n._def,shape:()=>t})}else if(n instanceof et)return new et({...n._def,type:ss(n.element)});else if(n instanceof ot)return ot.create(ss(n.unwrap()));else if(n instanceof Dt)return Dt.create(ss(n.unwrap()));else if(n instanceof yt)return yt.create(n.items.map((t)=>ss(t)));else return n}class wn extends q{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let n=this._def.shape(),t=j.objectKeys(n);return this._cached={shape:n,keys:t},this._cached}_parse(n){if(this._getType(n)!==L.object){let h=this._getOrReturnCtx(n);return O(h,{code:U.invalid_type,expected:L.object,received:h.parsedType}),J}let{status:i,ctx:s}=this._processInputParams(n),{shape:r,keys:e}=this._getCached(),f=[];if(!(this._def.catchall instanceof Et&&this._def.unknownKeys==="strip")){for(let h in s.data)if(!e.includes(h))f.push(h)}let o=[];for(let h of e){let u=r[h],c=s.data[h];o.push({key:{status:"valid",value:h},value:u._parse(new ft(s,c,s.path,h)),alwaysSet:h in s.data})}if(this._def.catchall instanceof Et){let h=this._def.unknownKeys;if(h==="passthrough")for(let u of f)o.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(h==="strict"){if(f.length>0)O(s,{code:U.unrecognized_keys,keys:f}),i.dirty()}else if(h==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let h=this._def.catchall;for(let u of f){let c=s.data[u];o.push({key:{status:"valid",value:u},value:h._parse(new ft(s,c,s.path,u)),alwaysSet:u in s.data})}}if(s.common.async)return Promise.resolve().then(async()=>{let h=[];for(let u of o){let c=await u.key,_=await u.value;h.push({key:c,value:_,alwaysSet:u.alwaysSet})}return h}).then((h)=>{return bn.mergeObjectSync(i,h)});else return bn.mergeObjectSync(i,o)}get shape(){return this._def.shape()}strict(n){return P.errToObj,new wn({...this._def,unknownKeys:"strict",...n!==void 0?{errorMap:(t,i)=>{let s=this._def.errorMap?.(t,i).message??i.defaultError;if(t.code==="unrecognized_keys")return{message:P.errToObj(n).message??s};return{message:s}}}:{}})}strip(){return new wn({...this._def,unknownKeys:"strip"})}passthrough(){return new wn({...this._def,unknownKeys:"passthrough"})}extend(n){return new wn({...this._def,shape:()=>({...this._def.shape(),...n})})}merge(n){return new wn({unknownKeys:n._def.unknownKeys,catchall:n._def.catchall,shape:()=>({...this._def.shape(),...n._def.shape()}),typeName:z.ZodObject})}setKey(n,t){return this.augment({[n]:t})}catchall(n){return new wn({...this._def,catchall:n})}pick(n){let t={};for(let i of j.objectKeys(n))if(n[i]&&this.shape[i])t[i]=this.shape[i];return new wn({...this._def,shape:()=>t})}omit(n){let t={};for(let i of j.objectKeys(this.shape))if(!n[i])t[i]=this.shape[i];return new wn({...this._def,shape:()=>t})}deepPartial(){return ss(this)}partial(n){let t={};for(let i of j.objectKeys(this.shape)){let s=this.shape[i];if(n&&!n[i])t[i]=s;else t[i]=s.optional()}return new wn({...this._def,shape:()=>t})}required(n){let t={};for(let i of j.objectKeys(this.shape))if(n&&!n[i])t[i]=this.shape[i];else{let r=this.shape[i];while(r instanceof ot)r=r._def.innerType;t[i]=r}return new wn({...this._def,shape:()=>t})}keyof(){return M0(j.objectKeys(this.shape))}}wn.create=(n,t)=>{return new wn({shape:()=>n,unknownKeys:"strip",catchall:Et.create(),typeName:z.ZodObject,...K(t)})};wn.strictCreate=(n,t)=>{return new wn({shape:()=>n,unknownKeys:"strict",catchall:Et.create(),typeName:z.ZodObject,...K(t)})};wn.lazycreate=(n,t)=>{return new wn({shape:n,unknownKeys:"strip",catchall:Et.create(),typeName:z.ZodObject,...K(t)})};class hs extends q{_parse(n){let{ctx:t}=this._processInputParams(n),i=this._def.options;function s(r){for(let f of r)if(f.result.status==="valid")return f.result;for(let f of r)if(f.result.status==="dirty")return t.common.issues.push(...f.ctx.common.issues),f.result;let e=r.map((f)=>new Pn(f.ctx.common.issues));return O(t,{code:U.invalid_union,unionErrors:e}),J}if(t.common.async)return Promise.all(i.map(async(r)=>{let e={...t,common:{...t.common,issues:[]},parent:null};return{result:await r._parseAsync({data:t.data,path:t.path,parent:e}),ctx:e}})).then(s);else{let r=void 0,e=[];for(let o of i){let h={...t,common:{...t.common,issues:[]},parent:null},u=o._parseSync({data:t.data,path:t.path,parent:h});if(u.status==="valid")return u;else if(u.status==="dirty"&&!r)r={result:u,ctx:h};if(h.common.issues.length)e.push(h.common.issues)}if(r)return t.common.issues.push(...r.ctx.common.issues),r.result;let f=e.map((o)=>new Pn(o));return O(t,{code:U.invalid_union,unionErrors:f}),J}}get options(){return this._def.options}}hs.create=(n,t)=>{return new hs({options:n,typeName:z.ZodUnion,...K(t)})};var Pt=(n)=>{if(n instanceof cs)return Pt(n.schema);else if(n instanceof ht)return Pt(n.innerType());else if(n instanceof _s)return[n.value];else if(n instanceof vt)return n.options;else if(n instanceof ws)return j.objectValues(n.enum);else if(n instanceof ls)return Pt(n._def.innerType);else if(n instanceof os)return[void 0];else if(n instanceof fs)return[null];else if(n instanceof ot)return[void 0,...Pt(n.unwrap())];else if(n instanceof Dt)return[null,...Pt(n.unwrap())];else if(n instanceof be)return Pt(n.unwrap());else if(n instanceof Ms)return Pt(n.unwrap());else if(n instanceof As)return Pt(n._def.innerType);else return[]};class Ue extends q{_parse(n){let{ctx:t}=this._processInputParams(n);if(t.parsedType!==L.object)return O(t,{code:U.invalid_type,expected:L.object,received:t.parsedType}),J;let i=this.discriminator,s=t.data[i],r=this.optionsMap.get(s);if(!r)return O(t,{code:U.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),J;if(t.common.async)return r._parseAsync({data:t.data,path:t.path,parent:t});else return r._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(n,t,i){let s=new Map;for(let r of t){let e=Pt(r.shape[n]);if(!e.length)throw Error(`A discriminator value for key \`${n}\` could not be extracted from all schema options`);for(let f of e){if(s.has(f))throw Error(`Discriminator property ${String(n)} has duplicate value ${String(f)}`);s.set(f,r)}}return new Ue({typeName:z.ZodDiscriminatedUnion,discriminator:n,options:t,optionsMap:s,...K(i)})}}function ih(n,t){let i=Rt(n),s=Rt(t);if(n===t)return{valid:!0,data:n};else if(i===L.object&&s===L.object){let r=j.objectKeys(t),e=j.objectKeys(n).filter((o)=>r.indexOf(o)!==-1),f={...n,...t};for(let o of e){let h=ih(n[o],t[o]);if(!h.valid)return{valid:!1};f[o]=h.data}return{valid:!0,data:f}}else if(i===L.array&&s===L.array){if(n.length!==t.length)return{valid:!1};let r=[];for(let e=0;e<n.length;e++){let f=n[e],o=t[e],h=ih(f,o);if(!h.valid)return{valid:!1};r.push(h.data)}return{valid:!0,data:r}}else if(i===L.date&&s===L.date&&+n===+t)return{valid:!0,data:n};else return{valid:!1}}class us extends q{_parse(n){let{status:t,ctx:i}=this._processInputParams(n),s=(r,e)=>{if(Se(r)||Se(e))return J;let f=ih(r.value,e.value);if(!f.valid)return O(i,{code:U.invalid_intersection_types}),J;if(Ie(r)||Ie(e))t.dirty();return{status:t.value,value:f.data}};if(i.common.async)return Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([r,e])=>s(r,e));else return s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}us.create=(n,t,i)=>{return new us({left:n,right:t,typeName:z.ZodIntersection,...K(i)})};class yt extends q{_parse(n){let{status:t,ctx:i}=this._processInputParams(n);if(i.parsedType!==L.array)return O(i,{code:U.invalid_type,expected:L.array,received:i.parsedType}),J;if(i.data.length<this._def.items.length)return O(i,{code:U.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;if(!this._def.rest&&i.data.length>this._def.items.length)O(i,{code:U.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let r=[...i.data].map((e,f)=>{let o=this._def.items[f]||this._def.rest;if(!o)return null;return o._parse(new ft(i,e,i.path,f))}).filter((e)=>!!e);if(i.common.async)return Promise.all(r).then((e)=>{return bn.mergeArray(t,e)});else return bn.mergeArray(t,r)}get items(){return this._def.items}rest(n){return new yt({...this._def,rest:n})}}yt.create=(n,t)=>{if(!Array.isArray(n))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new yt({items:n,typeName:z.ZodTuple,rest:null,...K(t)})};class _r extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){let{status:t,ctx:i}=this._processInputParams(n);if(i.parsedType!==L.object)return O(i,{code:U.invalid_type,expected:L.object,received:i.parsedType}),J;let s=[],r=this._def.keyType,e=this._def.valueType;for(let f in i.data)s.push({key:r._parse(new ft(i,f,i.path,f)),value:e._parse(new ft(i,i.data[f],i.path,f)),alwaysSet:f in i.data});if(i.common.async)return bn.mergeObjectAsync(t,s);else return bn.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(n,t,i){if(t instanceof q)return new _r({keyType:n,valueType:t,typeName:z.ZodRecord,...K(i)});return new _r({keyType:rt.create(),valueType:n,typeName:z.ZodRecord,...K(t)})}}class wr extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){let{status:t,ctx:i}=this._processInputParams(n);if(i.parsedType!==L.map)return O(i,{code:U.invalid_type,expected:L.map,received:i.parsedType}),J;let s=this._def.keyType,r=this._def.valueType,e=[...i.data.entries()].map(([f,o],h)=>{return{key:s._parse(new ft(i,f,i.path,[h,"key"])),value:r._parse(new ft(i,o,i.path,[h,"value"]))}});if(i.common.async){let f=new Map;return Promise.resolve().then(async()=>{for(let o of e){let h=await o.key,u=await o.value;if(h.status==="aborted"||u.status==="aborted")return J;if(h.status==="dirty"||u.status==="dirty")t.dirty();f.set(h.value,u.value)}return{status:t.value,value:f}})}else{let f=new Map;for(let o of e){let{key:h,value:u}=o;if(h.status==="aborted"||u.status==="aborted")return J;if(h.status==="dirty"||u.status==="dirty")t.dirty();f.set(h.value,u.value)}return{status:t.value,value:f}}}}wr.create=(n,t,i)=>{return new wr({valueType:t,keyType:n,typeName:z.ZodMap,...K(i)})};class bi extends q{_parse(n){let{status:t,ctx:i}=this._processInputParams(n);if(i.parsedType!==L.set)return O(i,{code:U.invalid_type,expected:L.set,received:i.parsedType}),J;let s=this._def;if(s.minSize!==null){if(i.data.size<s.minSize.value)O(i,{code:U.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()}if(s.maxSize!==null){if(i.data.size>s.maxSize.value)O(i,{code:U.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty()}let r=this._def.valueType;function e(o){let h=new Set;for(let u of o){if(u.status==="aborted")return J;if(u.status==="dirty")t.dirty();h.add(u.value)}return{status:t.value,value:h}}let f=[...i.data.values()].map((o,h)=>r._parse(new ft(i,o,i.path,h)));if(i.common.async)return Promise.all(f).then((o)=>e(o));else return e(f)}min(n,t){return new bi({...this._def,minSize:{value:n,message:P.toString(t)}})}max(n,t){return new bi({...this._def,maxSize:{value:n,message:P.toString(t)}})}size(n,t){return this.min(n,t).max(n,t)}nonempty(n){return this.min(1,n)}}bi.create=(n,t)=>{return new bi({valueType:n,minSize:null,maxSize:null,typeName:z.ZodSet,...K(t)})};class rs extends q{constructor(){super(...arguments);this.validate=this.implement}_parse(n){let{ctx:t}=this._processInputParams(n);if(t.parsedType!==L.function)return O(t,{code:U.invalid_type,expected:L.function,received:t.parsedType}),J;function i(f,o){return hr({data:f,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ts(),Ft].filter((h)=>!!h),issueData:{code:U.invalid_arguments,argumentsError:o}})}function s(f,o){return hr({data:f,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ts(),Ft].filter((h)=>!!h),issueData:{code:U.invalid_return_type,returnTypeError:o}})}let r={errorMap:t.common.contextualErrorMap},e=t.data;if(this._def.returns instanceof $i){let f=this;return Nn(async function(...o){let h=new Pn([]),u=await f._def.args.parseAsync(o,r).catch((w)=>{throw h.addIssue(i(o,w)),h}),c=await Reflect.apply(e,this,u);return await f._def.returns._def.type.parseAsync(c,r).catch((w)=>{throw h.addIssue(s(c,w)),h})})}else{let f=this;return Nn(function(...o){let h=f._def.args.safeParse(o,r);if(!h.success)throw new Pn([i(o,h.error)]);let u=Reflect.apply(e,this,h.data),c=f._def.returns.safeParse(u,r);if(!c.success)throw new Pn([s(u,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...n){return new rs({...this._def,args:yt.create(n).rest(Vt.create())})}returns(n){return new rs({...this._def,returns:n})}implement(n){return this.parse(n)}strictImplement(n){return this.parse(n)}static create(n,t,i){return new rs({args:n?n:yt.create([]).rest(Vt.create()),returns:t||Vt.create(),typeName:z.ZodFunction,...K(i)})}}class cs extends q{get schema(){return this._def.getter()}_parse(n){let{ctx:t}=this._processInputParams(n);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}cs.create=(n,t)=>{return new cs({getter:n,typeName:z.ZodLazy,...K(t)})};class _s extends q{_parse(n){if(n.data!==this._def.value){let t=this._getOrReturnCtx(n);return O(t,{received:t.data,code:U.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:n.data}}get value(){return this._def.value}}_s.create=(n,t)=>{return new _s({value:n,typeName:z.ZodLiteral,...K(t)})};function M0(n,t){return new vt({values:n,typeName:z.ZodEnum,...K(t)})}class vt extends q{_parse(n){if(typeof n.data!=="string"){let t=this._getOrReturnCtx(n),i=this._def.values;return O(t,{expected:j.joinValues(i),received:t.parsedType,code:U.invalid_type}),J}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(n.data)){let t=this._getOrReturnCtx(n),i=this._def.values;return O(t,{received:t.data,code:U.invalid_enum_value,options:i}),J}return Nn(n.data)}get options(){return this._def.values}get enum(){let n={};for(let t of this._def.values)n[t]=t;return n}get Values(){let n={};for(let t of this._def.values)n[t]=t;return n}get Enum(){let n={};for(let t of this._def.values)n[t]=t;return n}extract(n,t=this._def){return vt.create(n,{...this._def,...t})}exclude(n,t=this._def){return vt.create(this.options.filter((i)=>!n.includes(i)),{...this._def,...t})}}vt.create=M0;class ws extends q{_parse(n){let t=j.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(n);if(i.parsedType!==L.string&&i.parsedType!==L.number){let s=j.objectValues(t);return O(i,{expected:j.joinValues(s),received:i.parsedType,code:U.invalid_type}),J}if(!this._cache)this._cache=new Set(j.getValidEnumValues(this._def.values));if(!this._cache.has(n.data)){let s=j.objectValues(t);return O(i,{received:i.data,code:U.invalid_enum_value,options:s}),J}return Nn(n.data)}get enum(){return this._def.values}}ws.create=(n,t)=>{return new ws({values:n,typeName:z.ZodNativeEnum,...K(t)})};class $i extends q{unwrap(){return this._def.type}_parse(n){let{ctx:t}=this._processInputParams(n);if(t.parsedType!==L.promise&&t.common.async===!1)return O(t,{code:U.invalid_type,expected:L.promise,received:t.parsedType}),J;let i=t.parsedType===L.promise?t.data:Promise.resolve(t.data);return Nn(i.then((s)=>{return this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})}))}}$i.create=(n,t)=>{return new $i({type:n,typeName:z.ZodPromise,...K(t)})};class ht extends q{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(n){let{status:t,ctx:i}=this._processInputParams(n),s=this._def.effect||null,r={addIssue:(e)=>{if(O(i,e),e.fatal)t.abort();else t.dirty()},get path(){return i.path}};if(r.addIssue=r.addIssue.bind(r),s.type==="preprocess"){let e=s.transform(i.data,r);if(i.common.async)return Promise.resolve(e).then(async(f)=>{if(t.value==="aborted")return J;let o=await this._def.schema._parseAsync({data:f,path:i.path,parent:i});if(o.status==="aborted")return J;if(o.status==="dirty")return Si(o.value);if(t.value==="dirty")return Si(o.value);return o});else{if(t.value==="aborted")return J;let f=this._def.schema._parseSync({data:e,path:i.path,parent:i});if(f.status==="aborted")return J;if(f.status==="dirty")return Si(f.value);if(t.value==="dirty")return Si(f.value);return f}}if(s.type==="refinement"){let e=(f)=>{let o=s.refinement(f,r);if(i.common.async)return Promise.resolve(o);if(o instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return f};if(i.common.async===!1){let f=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(f.status==="aborted")return J;if(f.status==="dirty")t.dirty();return e(f.value),{status:t.value,value:f.value}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then((f)=>{if(f.status==="aborted")return J;if(f.status==="dirty")t.dirty();return e(f.value).then(()=>{return{status:t.value,value:f.value}})})}if(s.type==="transform")if(i.common.async===!1){let e=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!qt(e))return J;let f=s.transform(e.value,r);if(f instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:f}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then((e)=>{if(!qt(e))return J;return Promise.resolve(s.transform(e.value,r)).then((f)=>({status:t.value,value:f}))});j.assertNever(s)}}ht.create=(n,t,i)=>{return new ht({schema:n,typeName:z.ZodEffects,effect:t,...K(i)})};ht.createWithPreprocess=(n,t,i)=>{return new ht({schema:t,effect:{type:"preprocess",transform:n},typeName:z.ZodEffects,...K(i)})};class ot extends q{_parse(n){if(this._getType(n)===L.undefined)return Nn(void 0);return this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}ot.create=(n,t)=>{return new ot({innerType:n,typeName:z.ZodOptional,...K(t)})};class Dt extends q{_parse(n){if(this._getType(n)===L.null)return Nn(null);return this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}Dt.create=(n,t)=>{return new Dt({innerType:n,typeName:z.ZodNullable,...K(t)})};class ls extends q{_parse(n){let{ctx:t}=this._processInputParams(n),i=t.data;if(t.parsedType===L.undefined)i=this._def.defaultValue();return this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ls.create=(n,t)=>{return new ls({innerType:n,typeName:z.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...K(t)})};class As extends q{_parse(n){let{ctx:t}=this._processInputParams(n),i={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});if(is(s))return s.then((r)=>{return{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Pn(i.common.issues)},input:i.data})}});else return{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Pn(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}As.create=(n,t)=>{return new As({innerType:n,typeName:z.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...K(t)})};class lr extends q{_parse(n){if(this._getType(n)!==L.nan){let i=this._getOrReturnCtx(n);return O(i,{code:U.invalid_type,expected:L.nan,received:i.parsedType}),J}return{status:"valid",value:n.data}}}lr.create=(n)=>{return new lr({typeName:z.ZodNaN,...K(n)})};var T4=Symbol("zod_brand");class be extends q{_parse(n){let{ctx:t}=this._processInputParams(n),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ar extends q{_parse(n){let{status:t,ctx:i}=this._processInputParams(n);if(i.common.async)return(async()=>{let r=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});if(r.status==="aborted")return J;if(r.status==="dirty")return t.dirty(),Si(r.value);else return this._def.out._parseAsync({data:r.value,path:i.path,parent:i})})();else{let s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});if(s.status==="aborted")return J;if(s.status==="dirty")return t.dirty(),{status:"dirty",value:s.value};else return this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(n,t){return new Ar({in:n,out:t,typeName:z.ZodPipeline})}}class Ms extends q{_parse(n){let t=this._def.innerType._parse(n),i=(s)=>{if(qt(s))s.value=Object.freeze(s.value);return s};return is(t)?t.then((s)=>i(s)):i(t)}unwrap(){return this._def.innerType}}Ms.create=(n,t)=>{return new Ms({innerType:n,typeName:z.ZodReadonly,...K(t)})};function _0(n,t){let i=typeof n==="function"?n(t):typeof n==="string"?{message:n}:n;return typeof i==="string"?{message:i}:i}function d0(n,t={},i){if(n)return Ui.create().superRefine((s,r)=>{let e=n(s);if(e instanceof Promise)return e.then((f)=>{if(!f){let o=_0(t,s),h=o.fatal??i??!0;r.addIssue({code:"custom",...o,fatal:h})}});if(!e){let f=_0(t,s),o=f.fatal??i??!0;r.addIssue({code:"custom",...f,fatal:o})}return});return Ui.create()}var g4={object:wn.lazycreate},z;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(z||(z={}));var S4=(n,t={message:`Input not instance of ${n.name}`})=>d0((i)=>i instanceof n,t),R0=rt.create,E0=jt.create,I4=lr.create,U4=at.create,y0=es.create,b4=Ii.create,$4=ur.create,L4=os.create,O4=fs.create,B4=Ui.create,N4=Vt.create,G4=Et.create,H4=cr.create,W4=et.create,F4=wn.create,P4=wn.strictCreate,D4=hs.create,Y4=Ue.create,m4=us.create,J4=yt.create,X4=_r.create,z4=wr.create,Q4=bi.create,C4=rs.create,x4=cs.create,K4=_s.create,k4=vt.create,q4=ws.create,V4=$i.create,j4=ht.create,a4=ot.create,v4=Dt.create,Z4=ht.createWithPreprocess,p4=Ar.create,n2=()=>R0().optional(),t2=()=>E0().optional(),i2=()=>y0().optional(),s2={string:(n)=>rt.create({...n,coerce:!0}),number:(n)=>jt.create({...n,coerce:!0}),boolean:(n)=>es.create({...n,coerce:!0}),bigint:(n)=>at.create({...n,coerce:!0}),date:(n)=>Ii.create({...n,coerce:!0})};var r2=J;var $e=M.enum(["low","medium","high","xhigh","max"]),Li=M.enum(["us-east-1","us-east-2","us-west-1","us-west-2","af-south-1","ap-east-1","ap-south-2","ap-southeast-3","ap-southeast-5","ap-southeast-4","ap-south-1","ap-southeast-6","ap-northeast-3","ap-northeast-2","ap-southeast-1","ap-southeast-2","ap-east-2","ap-southeast-7","ap-northeast-1","ca-central-1","ca-west-1","eu-central-1","eu-west-1","eu-west-2","eu-south-1","eu-west-3","eu-south-2","eu-north-1","eu-central-2","il-central-1","mx-central-1","me-south-1","me-central-1","sa-east-1"]);var e2=M.array(M.string()).transform((n)=>n.map((t)=>t.trim()).filter((t)=>t.length>0)).refine((n)=>n.length>0,{message:"api_keys must contain at least one non-empty key"}),o2=M.preprocess((n)=>typeof n==="string"&&n.trim().length===0?null:n,M.string().trim().refine((n)=>URL.canParse(n),{message:"proxy_url must be a valid URL"}).refine((n)=>{if(!URL.canParse(n))return!1;let t=new URL(n).protocol;return t==="http:"||t==="https:"},{message:"proxy_url must be http(s)"}).nullable()).default(null),f2=M.preprocess((n)=>typeof n==="string"&&n.trim().length===0?null:n,M.string().trim().min(1).nullable()).default(null),sh=M.object({host:M.string().default("127.0.0.1"),port:M.number().default(8787),api_keys:e2,enable_legacy_chat_completions:M.boolean().default(!1),proxy_url:o2,auth_source:M.enum(["opencode-shared","local"]).default("opencode-shared"),opencode_auth_db_path:f2,default_region:M.string().default("us-east-1"),account_selection_strategy:M.enum(["sticky","round-robin","lowest-usage"]).default("lowest-usage"),rate_limit_max_retries:M.number().default(3),rate_limit_retry_delay_ms:M.number().default(5000),max_request_iterations:M.number().default(20),request_timeout_ms:M.number().int().min(1).max(2147483647).default(120000),stream_idle_timeout_ms:M.number().int().min(1).max(2147483647).default(60000),max_request_body_bytes:M.number().default(10485760),token_expiry_buffer_ms:M.number().default(300000),session_affinity_ttl_ms:M.number().int().min(1).max(2147483647).default(86400000),session_affinity_max_entries:M.number().int().min(1).max(1e6).default(1e4),effort:$e.nullable().default(null),auto_effort_mapping:M.boolean().default(!0),log_level:M.string().default("info"),test_upstream_endpoint:M.string().url().optional()});class Mr extends Error{constructor(n,t){super(n,t);this.name="ConfigLoadError"}}var _2=sh.partial();function w2(n){let t=n.XDG_CONFIG_HOME??T0(c2(),".config");return T0(t,"kiro-provider","config.json")}function l2(n){if(!h2(n))return{};try{let t=JSON.parse(u2(n,"utf8"));return _2.parse(t)}catch(t){if(t instanceof M.ZodError)throw new Mr(`Invalid configuration file ${n}: ${g0(t)}`,{cause:t});if(t instanceof Error)throw new Mr(`Unable to read configuration file ${n}: ${t.message}`,{cause:t});throw t}}function A2(n){let t=n.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;return n}function M2(n){let t={},i={KIRO_PROVIDER_HOST:"host",KIRO_PROVIDER_AUTH_SOURCE:"auth_source",KIRO_PROVIDER_DEFAULT_REGION:"default_region",KIRO_PROVIDER_ACCOUNT_SELECTION_STRATEGY:"account_selection_strategy",KIRO_PROVIDER_EFFORT:"effort",KIRO_PROVIDER_LOG_LEVEL:"log_level",KIRO_PROVIDER_TEST_UPSTREAM:"test_upstream_endpoint"};for(let[h,u]of Object.entries(i)){let c=n[h];if(c!==void 0)t[u]=c}let s={KIRO_PROVIDER_PORT:"port",KIRO_PROVIDER_RATE_LIMIT_MAX_RETRIES:"rate_limit_max_retries",KIRO_PROVIDER_RATE_LIMIT_RETRY_DELAY_MS:"rate_limit_retry_delay_ms",KIRO_PROVIDER_MAX_REQUEST_ITERATIONS:"max_request_iterations",KIRO_PROVIDER_REQUEST_TIMEOUT_MS:"request_timeout_ms",KIRO_PROVIDER_STREAM_IDLE_TIMEOUT_MS:"stream_idle_timeout_ms",KIRO_PROVIDER_MAX_REQUEST_BODY_BYTES:"max_request_body_bytes",KIRO_PROVIDER_TOKEN_EXPIRY_BUFFER_MS:"token_expiry_buffer_ms",KIRO_PROVIDER_SESSION_AFFINITY_TTL_MS:"session_affinity_ttl_ms",KIRO_PROVIDER_SESSION_AFFINITY_MAX_ENTRIES:"session_affinity_max_entries"};for(let[h,u]of Object.entries(s)){let c=n[h];if(c!==void 0)t[u]=Number(c)}let r=n.KIRO_PROVIDER_API_KEYS;if(r!==void 0)t.api_keys=r.split(",");let e=n.KIRO_PROVIDER_PROXY_URL;if(e!==void 0)t.proxy_url=e.trim();let f=n.KIRO_PROVIDER_OPENCODE_AUTH_DB_PATH;if(f!==void 0)t.opencode_auth_db_path=f.trim();let o={KIRO_PROVIDER_ENABLE_LEGACY_CHAT_COMPLETIONS:"enable_legacy_chat_completions",KIRO_PROVIDER_AUTO_EFFORT_MAPPING:"auto_effort_mapping"};for(let[h,u]of Object.entries(o)){let c=n[h];if(c!==void 0)t[u]=A2(c)}return t}function g0(n){return n.issues.map((t)=>`${t.path.length>0?t.path.join("."):"config"}: ${t.message}`).join(", ")}function S0(n={}){let t=n.env??process.env,i=n.configPath??w2(t);try{return sh.parse({...l2(i),...M2(t),...n.overrides})}catch(s){if(s instanceof Mr)throw s;if(s instanceof M.ZodError)throw new Mr(`Invalid configuration: ${g0(s)}`,{cause:s});throw s}}function ds(n){let t=n.split("|"),i=t[0]??"";if(t.length<2)return{refreshToken:i,authMethod:"desktop"};if(t.at(-1)==="idc")return{refreshToken:i,clientId:t[1],clientSecret:t[2],authMethod:"idc"};return{refreshToken:i,authMethod:"desktop"}}function dr(n,t=120000){if(!n.access||!n.expires)return!0;return Date.now()>=n.expires-t}function Le(n){if(n.authMethod==="idc"){if(!n.clientId||!n.clientSecret)throw Error("Missing credentials");return`${n.refreshToken}|${n.clientId}|${n.clientSecret}|idc`}return`${n.refreshToken}|desktop`}function Oe(n){if(!n)return!1;return n.includes("Invalid refresh token")||n.includes("Invalid grant provided")||n.includes("invalid_grant")||n.includes("ExpiredTokenException")||n.includes("InvalidTokenException")||n.includes("ExpiredClientException")||n.includes("Client is expired")||n.includes("HTTP_401")||n.includes("HTTP_403")}function Rs(n){if(!n)return!1;let t=n.toLowerCase();return t.includes("bearer token included in the request is invalid")||t.includes("access token has expired")||t.includes("access_token expired")||t.includes("the access token expired")}function Es(n){return Oe(n)}function I0(n){let t=n&&n.length>0?n:"Account needs re-authentication";return Oe(t)?t:`InvalidTokenException: ${t}`}var U0=4;class b0 extends Error{accountId;constructor(n){super(`Account ${n} changed too frequently to update`);this.accountId=n;this.name="AccountConcurrentUpdateError"}}function d2(n){throw TypeError(`Unsupported account selection strategy: ${String(n)}`)}function Rr(n){return{...n}}function rh(n){return{refresh:Le({refreshToken:n.refreshToken,authMethod:n.authMethod,...n.clientId?{clientId:n.clientId}:{},...n.clientSecret?{clientSecret:n.clientSecret}:{},...n.profileArn?{profileArn:n.profileArn}:{}}),access:n.accessToken,expires:n.expiresAt,authMethod:n.authMethod,region:n.region,...n.oidcRegion?{oidcRegion:n.oidcRegion}:{},...n.clientId?{clientId:n.clientId}:{},...n.clientSecret?{clientSecret:n.clientSecret}:{},...n.email?{email:n.email}:{},...n.profileArn?{profileArn:n.profileArn}:{}}}class eh{strategy;database;accounts;stickyId;roundRobinCursor=0;constructor(n,t,i){this.strategy=t;this.database=i;this.accounts=n.map(Rr)}getAccountCount(){return this.accounts.length}getAccounts(){return this.accounts.map(Rr)}getMinWaitTime(){let n=Date.now(),t=this.accounts.map(({rateLimitResetTime:i})=>i-n).filter((i)=>i>0);return t.length===0?0:Math.min(...t)}reconcileFromDb(n=this.database){let t=new Map(this.accounts.map((i)=>[i.id,i]));if(this.accounts=n.getAccounts().map((i)=>{let s=t.get(i.id);return s?.generation===i.generation?s:Rr(i)}),this.stickyId&&!this.accounts.some(({id:i})=>i===this.stickyId))this.stickyId=void 0;return this.getAccounts()}selectHealthyAccount(n){let t=Date.now(),i=this.accounts.filter((r)=>this.isSelectable(r,t)).sort((r,e)=>r.id.localeCompare(e.id));if(i.length===0)return null;let s=i.find(({id:r})=>r===n)??this.selectCandidate(i);return this.patchAccount(s.id,(r)=>({...r,isHealthy:!0,unhealthyReason:void 0,recoveryTime:void 0,lastUsed:t,usedCount:(r.usedCount??0)+1}))??null}getCurrentOrNext(){return this.selectHealthyAccount()}markRateLimited(n,t){return this.patchAccount(n.id,(i)=>({...i,rateLimitResetTime:t}))}markUnhealthy(n,t,i){let s=Date.now();return this.patchAccount(n.id,(r)=>{if(Es(t))return{...r,failCount:10,isHealthy:!1,unhealthyReason:t,recoveryTime:void 0,lastUsed:s};let e=r.failCount+1;return{...r,failCount:e,isHealthy:e<10,unhealthyReason:t,recoveryTime:e>=10?i??s+3600000:void 0,lastUsed:s}})}updateFromAuth(n,t){let i=ds(t.refresh);for(let s=0;s<U0;s+=1){let r=s===0?n:this.database.getById(n.id);if(!r||!this.isSameLogin(n,r)){this.reconcileFromDb();return}let e={...r,refreshToken:i.refreshToken,accessToken:t.access,expiresAt:t.expires};if(this.database.updateExistingAccounts([e])===1){let f={...e,generation:r.generation+1};return this.replaceAccount(f),Rr(f)}}this.reconcileFromDb();return}toAuthDetails(n){return rh(n)}isSelectable(n,t){if(Es(n.unhealthyReason))return!1;if(n.rateLimitResetTime>t)return!1;if(n.isHealthy||Rs(n.unhealthyReason))return!0;return n.recoveryTime!==void 0&&n.recoveryTime<=t}isSameLogin(n,t){return t.refreshToken===n.refreshToken&&t.authMethod===n.authMethod&&t.clientId===n.clientId&&t.email===n.email&&t.startUrl===n.startUrl}selectCandidate(n){switch(this.strategy){case"sticky":{let i=n.find(({id:s})=>s===this.stickyId)??n[0];if(!i)throw RangeError("Candidate list cannot be empty");return this.stickyId=i.id,i}case"round-robin":{let t=n[this.roundRobinCursor%n.length];if(!t)throw RangeError("Candidate list cannot be empty");return this.roundRobinCursor+=1,t}case"lowest-usage":{let t=[...n].sort((i,s)=>(i.usedCount??0)-(s.usedCount??0)||(i.lastUsed??0)-(s.lastUsed??0)||i.id.localeCompare(s.id))[0];if(!t)throw RangeError("Candidate list cannot be empty");return t}default:return d2(this.strategy)}}patchAccount(n,t){for(let i=0;i<U0;i+=1){let s=this.database.getById(n);if(!s){this.accounts=this.accounts.filter((e)=>e.id!==n);return}let r=t(s);if(this.database.updateExistingAccounts([r])===1){let e={...r,generation:s.generation+1};return this.replaceAccount(e),Rr(e)}}throw this.reconcileFromDb(),new b0(n)}replaceAccount(n){let t=this.accounts.findIndex(({id:i})=>i===n.id);if(t===-1)this.accounts.push(n);else this.accounts[t]=n}}var p0=Q(v0(),1);import{existsSync as r6,promises as Z0}from"fs";import{join as e6}from"path";var o6={stale:15000,retries:0,realpath:!1},f6=15000,h6=25,u6=250;function c6(n){if(typeof n!=="object"||n===null||!("code"in n))return!1;return n.code==="ELOCKED"||n.code==="ENOENT"}function gh(n){return n.reason??new DOMException("The operation was aborted","AbortError")}function _6(n,t){if(t?.aborted)return Promise.reject(gh(t));return new Promise((i,s)=>{let r=setTimeout(()=>{t?.removeEventListener("abort",e),i()},n),e=()=>{clearTimeout(r),s(gh(t))};t?.addEventListener("abort",e,{once:!0})})}function w6(n,t){let i=t.replace(/[^A-Za-z0-9_-]/g,"");return e6(n,`.kiro-refresh-${i}.lock`)}async function l6(n,t){let i=Date.now()+f6,s=0;for(;;){if(t?.aborted)throw gh(t);try{return await p0.default.lock(n,o6)}catch(r){let e=i-Date.now();if(!c6(r)||e<=0)throw r;let f=Math.min(h6*2**Math.min(s,4),u6,e),o=Math.max(1,Math.floor(f/2)),h=o+Math.floor(Math.random()*(f-o+1));s+=1,await _6(h,t)}}}async function nw(n,t,i,s){let r=w6(n,t);if(await Z0.mkdir(n,{recursive:!0}),!r6(r))await(await Z0.open(r,"a")).close();let e=await l6(r,s);try{return await i()}finally{try{await e()}catch{}}}var Mw=Q(Uh(),1);import*as gt from"net";import*as Ur from"tls";import j6 from"assert";import*as cw from"net";import*as _w from"http";import{Agent as V6}from"https";var Tt=Symbol("AgentBaseInternalState");class bh extends _w.Agent{constructor(n){super(n);this[Tt]={}}isSecureEndpoint(n){if(n){if(typeof n.secureEndpoint==="boolean")return n.secureEndpoint;if(typeof n.protocol==="string")return n.protocol==="https:"}let{stack:t}=Error();if(typeof t!=="string")return!1;return t.split(`
|
|
117
|
-
`).some((i)=>i.indexOf("(https.js:")!==-1||i.indexOf("node:https:")!==-1)}incrementSockets(n){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;if(!this.sockets[n])this.sockets[n]=[];let t=new
|
|
116
|
+
`).get(n);return t===null?void 0:t}validateSchema(){let n=new Set(this.db.query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map(({name:r})=>r));for(let r of["accounts","removed_accounts"])if(!n.has(r))throw new Ls(`OpenCode Kiro auth database ${this.path} is missing table ${r}; update opencode-kiro-auth and authenticate again.`);let t=new Set(this.db.query("PRAGMA table_info(accounts)").all().map(({name:r})=>r)),i=[...Q2].filter((r)=>!t.has(r));if(i.length>0)throw new Ls(`OpenCode Kiro auth database ${this.path} is missing required account columns: ${i.join(", ")}`)}withImmediateTransaction(n){let t=Date.now()+X2,i=0;for(;;){let r=!1,s;try{this.db.run("PRAGMA busy_timeout = 0"),this.db.exec("BEGIN IMMEDIATE"),r=!0}catch(f){s=f}finally{this.db.run(`PRAGMA busy_timeout = ${Ge}`)}if(!r){if(!z2(s))throw s;let f=t-Date.now();if(f<=0)throw new Ls(`Timed out waiting for the OpenCode Kiro auth database write lock: ${this.path}`,{cause:s});C2(i,f),i+=1;continue}try{let f=n();return this.db.exec("COMMIT"),f}catch(f){throw this.db.exec("ROLLBACK"),f}}}}import{existsSync as ig,readFileSync as rg}from"fs";import{homedir as sg}from"os";import{join as xe}from"path";var d={};D2(d,{void:()=>N6,util:()=>sn,unknown:()=>U6,union:()=>G6,undefined:()=>L6,tuple:()=>P6,transformer:()=>K6,symbol:()=>S6,string:()=>ze,strictObject:()=>H6,setErrorMap:()=>j2,set:()=>X6,record:()=>Y6,quotelessJson:()=>K2,promise:()=>V6,preprocess:()=>k6,pipeline:()=>q6,ostring:()=>m6,optional:()=>x6,onumber:()=>Z6,oboolean:()=>a6,objectUtil:()=>u0,object:()=>I6,number:()=>Ce,nullable:()=>j6,null:()=>$6,never:()=>b6,nativeEnum:()=>C6,nan:()=>E6,map:()=>F6,makeIssue:()=>Os,literal:()=>Q6,lazy:()=>J6,late:()=>R6,isValid:()=>hi,isDirty:()=>lf,isAsync:()=>Rr,isAborted:()=>Xf,intersection:()=>D6,instanceof:()=>M6,getParsedType:()=>Bt,getErrorMap:()=>Ar,function:()=>l6,enum:()=>z6,effect:()=>K6,discriminatedUnion:()=>W6,defaultErrorMap:()=>xt,datetimeRegex:()=>le,date:()=>g6,custom:()=>Qe,coerce:()=>v6,boolean:()=>Ve,bigint:()=>T6,array:()=>B6,any:()=>O6,addIssueToContext:()=>B,ZodVoid:()=>bs,ZodUnknown:()=>ci,ZodUnion:()=>Lr,ZodUndefined:()=>gr,ZodType:()=>tn,ZodTuple:()=>Ht,ZodTransformer:()=>Et,ZodSymbol:()=>Us,ZodString:()=>dt,ZodSet:()=>li,ZodSchema:()=>tn,ZodRecord:()=>Ns,ZodReadonly:()=>Ir,ZodPromise:()=>Ji,ZodPipeline:()=>Hs,ZodParsedType:()=>N,ZodOptional:()=>Rt,ZodObject:()=>Tn,ZodNumber:()=>oi,ZodNullable:()=>kt,ZodNull:()=>Sr,ZodNever:()=>It,ZodNativeEnum:()=>br,ZodNaN:()=>Is,ZodMap:()=>Bs,ZodLiteral:()=>Ur,ZodLazy:()=>Or,ZodIssueCode:()=>O,ZodIntersection:()=>$r,ZodFunction:()=>Er,ZodFirstPartyTypeKind:()=>V,ZodError:()=>Vn,ZodEnum:()=>ei,ZodEffects:()=>Et,ZodDiscriminatedUnion:()=>Jf,ZodDefault:()=>Nr,ZodDate:()=>Fi,ZodCatch:()=>Br,ZodBranded:()=>Qf,ZodBoolean:()=>Tr,ZodBigInt:()=>wi,ZodArray:()=>At,ZodAny:()=>Xi,Schema:()=>tn,ParseStatus:()=>Wn,OK:()=>ln,NEVER:()=>p6,INVALID:()=>C,EMPTY_PATH:()=>k2,DIRTY:()=>Yi,BRAND:()=>A6});var sn;(function(n){n.assertEqual=(s)=>{};function t(s){}n.assertIs=t;function i(s){throw Error()}n.assertNever=i,n.arrayToEnum=(s)=>{let f={};for(let h of s)f[h]=h;return f},n.getValidEnumValues=(s)=>{let f=n.objectKeys(s).filter((_)=>typeof s[s[_]]!=="number"),h={};for(let _ of f)h[_]=s[_];return n.objectValues(h)},n.objectValues=(s)=>{return n.objectKeys(s).map(function(f){return s[f]})},n.objectKeys=typeof Object.keys==="function"?(s)=>Object.keys(s):(s)=>{let f=[];for(let h in s)if(Object.prototype.hasOwnProperty.call(s,h))f.push(h);return f},n.find=(s,f)=>{for(let h of s)if(f(h))return h;return},n.isInteger=typeof Number.isInteger==="function"?(s)=>Number.isInteger(s):(s)=>typeof s==="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,f=" | "){return s.map((h)=>typeof h==="string"?`'${h}'`:h).join(f)}n.joinValues=r,n.jsonStringifyReplacer=(s,f)=>{if(typeof f==="bigint")return f.toString();return f}})(sn||(sn={}));var u0;(function(n){n.mergeShapes=(t,i)=>{return{...t,...i}}})(u0||(u0={}));var N=sn.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Bt=(n)=>{switch(typeof n){case"undefined":return N.undefined;case"string":return N.string;case"number":return Number.isNaN(n)?N.nan:N.number;case"boolean":return N.boolean;case"function":return N.function;case"bigint":return N.bigint;case"symbol":return N.symbol;case"object":if(Array.isArray(n))return N.array;if(n===null)return N.null;if(n.then&&typeof n.then==="function"&&n.catch&&typeof n.catch==="function")return N.promise;if(typeof Map<"u"&&n instanceof Map)return N.map;if(typeof Set<"u"&&n instanceof Set)return N.set;if(typeof Date<"u"&&n instanceof Date)return N.date;return N.object;default:return N.unknown}};var O=sn.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),K2=(n)=>{return JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:")};class Vn extends Error{get errors(){return this.issues}constructor(n){super();this.issues=[],this.addIssue=(i)=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=n}format(n){let t=n||function(s){return s.message},i={_errors:[]},r=(s)=>{for(let f of s.issues)if(f.code==="invalid_union")f.unionErrors.map(r);else if(f.code==="invalid_return_type")r(f.returnTypeError);else if(f.code==="invalid_arguments")r(f.argumentsError);else if(f.path.length===0)i._errors.push(t(f));else{let h=i,_=0;while(_<f.path.length){let c=f.path[_];if(_!==f.path.length-1)h[c]=h[c]||{_errors:[]};else h[c]=h[c]||{_errors:[]},h[c]._errors.push(t(f));h=h[c],_++}}};return r(this),i}static assert(n){if(!(n instanceof Vn))throw Error(`Not a ZodError: ${n}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,sn.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(n=(t)=>t.message){let t={},i=[];for(let r of this.issues)if(r.path.length>0){let s=r.path[0];t[s]=t[s]||[],t[s].push(n(r))}else i.push(n(r));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}Vn.create=(n)=>{return new Vn(n)};var x2=(n,t)=>{let i;switch(n.code){case O.invalid_type:if(n.received===N.undefined)i="Required";else i=`Expected ${n.expected}, received ${n.received}`;break;case O.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(n.expected,sn.jsonStringifyReplacer)}`;break;case O.unrecognized_keys:i=`Unrecognized key(s) in object: ${sn.joinValues(n.keys,", ")}`;break;case O.invalid_union:i="Invalid input";break;case O.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${sn.joinValues(n.options)}`;break;case O.invalid_enum_value:i=`Invalid enum value. Expected ${sn.joinValues(n.options)}, received '${n.received}'`;break;case O.invalid_arguments:i="Invalid function arguments";break;case O.invalid_return_type:i="Invalid function return type";break;case O.invalid_date:i="Invalid date";break;case O.invalid_string:if(typeof n.validation==="object")if("includes"in n.validation){if(i=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position==="number")i=`${i} at one or more positions greater than or equal to ${n.validation.position}`}else if("startsWith"in n.validation)i=`Invalid input: must start with "${n.validation.startsWith}"`;else if("endsWith"in n.validation)i=`Invalid input: must end with "${n.validation.endsWith}"`;else sn.assertNever(n.validation);else if(n.validation!=="regex")i=`Invalid ${n.validation}`;else i="Invalid";break;case O.too_small:if(n.type==="array")i=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`;else if(n.type==="string")i=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`;else if(n.type==="number")i=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`;else if(n.type==="bigint")i=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`;else if(n.type==="date")i=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`;else i="Invalid input";break;case O.too_big:if(n.type==="array")i=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`;else if(n.type==="string")i=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`;else if(n.type==="number")i=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`;else if(n.type==="bigint")i=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`;else if(n.type==="date")i=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`;else i="Invalid input";break;case O.custom:i="Invalid input";break;case O.invalid_intersection_types:i="Intersection results could not be merged";break;case O.not_multiple_of:i=`Number must be a multiple of ${n.multipleOf}`;break;case O.not_finite:i="Number must be finite";break;default:i=t.defaultError,sn.assertNever(n)}return{message:i}},xt=x2;var De=xt;function j2(n){De=n}function Ar(){return De}var Os=(n)=>{let{data:t,path:i,errorMaps:r,issueData:s}=n,f=[...i,...s.path||[]],h={...s,path:f};if(s.message!==void 0)return{...s,path:f,message:s.message};let _="",c=r.filter((o)=>!!o).slice().reverse();for(let o of c)_=o(h,{data:t,defaultError:_}).message;return{...s,path:f,message:_}},k2=[];function B(n,t){let i=Ar(),r=Os({issueData:t,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,i,i===xt?void 0:xt].filter((s)=>!!s)});n.common.issues.push(r)}class Wn{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(n,t){let i=[];for(let r of t){if(r.status==="aborted")return C;if(r.status==="dirty")n.dirty();i.push(r.value)}return{status:n.value,value:i}}static async mergeObjectAsync(n,t){let i=[];for(let r of t){let s=await r.key,f=await r.value;i.push({key:s,value:f})}return Wn.mergeObjectSync(n,i)}static mergeObjectSync(n,t){let i={};for(let r of t){let{key:s,value:f}=r;if(s.status==="aborted")return C;if(f.status==="aborted")return C;if(s.status==="dirty")n.dirty();if(f.status==="dirty")n.dirty();if(s.value!=="__proto__"&&(typeof f.value<"u"||r.alwaysSet))i[s.value]=f.value}return{status:n.value,value:i}}}var C=Object.freeze({status:"aborted"}),Yi=(n)=>({status:"dirty",value:n}),ln=(n)=>({status:"valid",value:n}),Xf=(n)=>n.status==="aborted",lf=(n)=>n.status==="dirty",hi=(n)=>n.status==="valid",Rr=(n)=>typeof Promise<"u"&&n instanceof Promise;var F;(function(n){n.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},n.toString=(t)=>typeof t==="string"?t:t?.message})(F||(F={}));class Mt{constructor(n,t,i,r){this._cachedPath=[],this.parent=n,this.data=t,this._path=i,this._key=r}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var Pe=(n,t)=>{if(hi(t))return{success:!0,data:t.value};else{if(!n.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let i=new Vn(n.common.issues);return this._error=i,this._error}}}};function a(n){if(!n)return{};let{errorMap:t,invalid_type_error:i,required_error:r,description:s}=n;if(t&&(i||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:s};return{errorMap:(h,_)=>{let{message:c}=n;if(h.code==="invalid_enum_value")return{message:c??_.defaultError};if(typeof _.data>"u")return{message:c??r??_.defaultError};if(h.code!=="invalid_type")return{message:_.defaultError};return{message:c??i??_.defaultError}},description:s}}class tn{get description(){return this._def.description}_getType(n){return Bt(n.data)}_getOrReturnCtx(n,t){return t||{common:n.parent.common,data:n.data,parsedType:Bt(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}_processInputParams(n){return{status:new Wn,ctx:{common:n.parent.common,data:n.data,parsedType:Bt(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}}_parseSync(n){let t=this._parse(n);if(Rr(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(n){let t=this._parse(n);return Promise.resolve(t)}parse(n,t){let i=this.safeParse(n,t);if(i.success)return i.data;throw i.error}safeParse(n,t){let i={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Bt(n)},r=this._parseSync({data:n,path:i.path,parent:i});return Pe(i,r)}"~validate"(n){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Bt(n)};if(!this["~standard"].async)try{let i=this._parseSync({data:n,path:[],parent:t});return hi(i)?{value:i.value}:{issues:t.common.issues}}catch(i){if(i?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:n,path:[],parent:t}).then((i)=>hi(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(n,t){let i=await this.safeParseAsync(n,t);if(i.success)return i.data;throw i.error}async safeParseAsync(n,t){let i={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Bt(n)},r=this._parse({data:n,path:i.path,parent:i}),s=await(Rr(r)?r:Promise.resolve(r));return Pe(i,s)}refine(n,t){let i=(r)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(r);else return t};return this._refinement((r,s)=>{let f=n(r),h=()=>s.addIssue({code:O.custom,...i(r)});if(typeof Promise<"u"&&f instanceof Promise)return f.then((_)=>{if(!_)return h(),!1;else return!0});if(!f)return h(),!1;else return!0})}refinement(n,t){return this._refinement((i,r)=>{if(!n(i))return r.addIssue(typeof t==="function"?t(i,r):t),!1;else return!0})}_refinement(n){return new Et({schema:this,typeName:V.ZodEffects,effect:{type:"refinement",refinement:n}})}superRefine(n){return this._refinement(n)}constructor(n){this.spa=this.safeParseAsync,this._def=n,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(t)=>this["~validate"](t)}}optional(){return Rt.create(this,this._def)}nullable(){return kt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return At.create(this)}promise(){return Ji.create(this,this._def)}or(n){return Lr.create([this,n],this._def)}and(n){return $r.create(this,n,this._def)}transform(n){return new Et({...a(this._def),schema:this,typeName:V.ZodEffects,effect:{type:"transform",transform:n}})}default(n){let t=typeof n==="function"?n:()=>n;return new Nr({...a(this._def),innerType:this,defaultValue:t,typeName:V.ZodDefault})}brand(){return new Qf({typeName:V.ZodBranded,type:this,...a(this._def)})}catch(n){let t=typeof n==="function"?n:()=>n;return new Br({...a(this._def),innerType:this,catchValue:t,typeName:V.ZodCatch})}describe(n){return new this.constructor({...this._def,description:n})}pipe(n){return Hs.create(this,n)}readonly(){return Ir.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var q2=/^c[^\s-]{8,}$/i,m2=/^[0-9a-z]+$/,Z2=/^[0-9A-HJKMNP-TV-Z]{26}$/i,a2=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,v2=/^[a-z0-9_-]{21}$/i,p2=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,n6=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,t6=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,i6="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",y0,r6=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,s6=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,f6=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,_6=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,h6=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,c6=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Fe="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",o6=new RegExp(`^${Fe}$`);function Xe(n){let t="[0-5]\\d";if(n.precision)t=`${t}\\.\\d{${n.precision}}`;else if(n.precision==null)t=`${t}(\\.\\d+)?`;let i=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${i}`}function w6(n){return new RegExp(`^${Xe(n)}$`)}function le(n){let t=`${Fe}T${Xe(n)}`,i=[];if(i.push(n.local?"Z?":"Z"),n.offset)i.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${i.join("|")})`,new RegExp(`^${t}$`)}function e6(n,t){if((t==="v4"||!t)&&r6.test(n))return!0;if((t==="v6"||!t)&&f6.test(n))return!0;return!1}function u6(n,t){if(!p2.test(n))return!1;try{let[i]=n.split(".");if(!i)return!1;let r=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(i.length+(4-i.length%4)%4,"="),s=JSON.parse(atob(r));if(typeof s!=="object"||s===null)return!1;if("typ"in s&&s?.typ!=="JWT")return!1;if(!s.alg)return!1;if(t&&s.alg!==t)return!1;return!0}catch{return!1}}function y6(n,t){if((t==="v4"||!t)&&s6.test(n))return!0;if((t==="v6"||!t)&&_6.test(n))return!0;return!1}class dt extends tn{_parse(n){if(this._def.coerce)n.data=String(n.data);if(this._getType(n)!==N.string){let s=this._getOrReturnCtx(n);return B(s,{code:O.invalid_type,expected:N.string,received:s.parsedType}),C}let i=new Wn,r=void 0;for(let s of this._def.checks)if(s.kind==="min"){if(n.data.length<s.value)r=this._getOrReturnCtx(n,r),B(r,{code:O.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),i.dirty()}else if(s.kind==="max"){if(n.data.length>s.value)r=this._getOrReturnCtx(n,r),B(r,{code:O.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),i.dirty()}else if(s.kind==="length"){let f=n.data.length>s.value,h=n.data.length<s.value;if(f||h){if(r=this._getOrReturnCtx(n,r),f)B(r,{code:O.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message});else if(h)B(r,{code:O.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message});i.dirty()}}else if(s.kind==="email"){if(!t6.test(n.data))r=this._getOrReturnCtx(n,r),B(r,{validation:"email",code:O.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="emoji"){if(!y0)y0=new RegExp(i6,"u");if(!y0.test(n.data))r=this._getOrReturnCtx(n,r),B(r,{validation:"emoji",code:O.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="uuid"){if(!a2.test(n.data))r=this._getOrReturnCtx(n,r),B(r,{validation:"uuid",code:O.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="nanoid"){if(!v2.test(n.data))r=this._getOrReturnCtx(n,r),B(r,{validation:"nanoid",code:O.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="cuid"){if(!q2.test(n.data))r=this._getOrReturnCtx(n,r),B(r,{validation:"cuid",code:O.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="cuid2"){if(!m2.test(n.data))r=this._getOrReturnCtx(n,r),B(r,{validation:"cuid2",code:O.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="ulid"){if(!Z2.test(n.data))r=this._getOrReturnCtx(n,r),B(r,{validation:"ulid",code:O.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="url")try{new URL(n.data)}catch{r=this._getOrReturnCtx(n,r),B(r,{validation:"url",code:O.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="regex"){if(s.regex.lastIndex=0,!s.regex.test(n.data))r=this._getOrReturnCtx(n,r),B(r,{validation:"regex",code:O.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="trim")n.data=n.data.trim();else if(s.kind==="includes"){if(!n.data.includes(s.value,s.position))r=this._getOrReturnCtx(n,r),B(r,{code:O.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),i.dirty()}else if(s.kind==="toLowerCase")n.data=n.data.toLowerCase();else if(s.kind==="toUpperCase")n.data=n.data.toUpperCase();else if(s.kind==="startsWith"){if(!n.data.startsWith(s.value))r=this._getOrReturnCtx(n,r),B(r,{code:O.invalid_string,validation:{startsWith:s.value},message:s.message}),i.dirty()}else if(s.kind==="endsWith"){if(!n.data.endsWith(s.value))r=this._getOrReturnCtx(n,r),B(r,{code:O.invalid_string,validation:{endsWith:s.value},message:s.message}),i.dirty()}else if(s.kind==="datetime"){if(!le(s).test(n.data))r=this._getOrReturnCtx(n,r),B(r,{code:O.invalid_string,validation:"datetime",message:s.message}),i.dirty()}else if(s.kind==="date"){if(!o6.test(n.data))r=this._getOrReturnCtx(n,r),B(r,{code:O.invalid_string,validation:"date",message:s.message}),i.dirty()}else if(s.kind==="time"){if(!w6(s).test(n.data))r=this._getOrReturnCtx(n,r),B(r,{code:O.invalid_string,validation:"time",message:s.message}),i.dirty()}else if(s.kind==="duration"){if(!n6.test(n.data))r=this._getOrReturnCtx(n,r),B(r,{validation:"duration",code:O.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="ip"){if(!e6(n.data,s.version))r=this._getOrReturnCtx(n,r),B(r,{validation:"ip",code:O.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="jwt"){if(!u6(n.data,s.alg))r=this._getOrReturnCtx(n,r),B(r,{validation:"jwt",code:O.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="cidr"){if(!y6(n.data,s.version))r=this._getOrReturnCtx(n,r),B(r,{validation:"cidr",code:O.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="base64"){if(!h6.test(n.data))r=this._getOrReturnCtx(n,r),B(r,{validation:"base64",code:O.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="base64url"){if(!c6.test(n.data))r=this._getOrReturnCtx(n,r),B(r,{validation:"base64url",code:O.invalid_string,message:s.message}),i.dirty()}else sn.assertNever(s);return{status:i.value,value:n.data}}_regex(n,t,i){return this.refinement((r)=>n.test(r),{validation:t,code:O.invalid_string,...F.errToObj(i)})}_addCheck(n){return new dt({...this._def,checks:[...this._def.checks,n]})}email(n){return this._addCheck({kind:"email",...F.errToObj(n)})}url(n){return this._addCheck({kind:"url",...F.errToObj(n)})}emoji(n){return this._addCheck({kind:"emoji",...F.errToObj(n)})}uuid(n){return this._addCheck({kind:"uuid",...F.errToObj(n)})}nanoid(n){return this._addCheck({kind:"nanoid",...F.errToObj(n)})}cuid(n){return this._addCheck({kind:"cuid",...F.errToObj(n)})}cuid2(n){return this._addCheck({kind:"cuid2",...F.errToObj(n)})}ulid(n){return this._addCheck({kind:"ulid",...F.errToObj(n)})}base64(n){return this._addCheck({kind:"base64",...F.errToObj(n)})}base64url(n){return this._addCheck({kind:"base64url",...F.errToObj(n)})}jwt(n){return this._addCheck({kind:"jwt",...F.errToObj(n)})}ip(n){return this._addCheck({kind:"ip",...F.errToObj(n)})}cidr(n){return this._addCheck({kind:"cidr",...F.errToObj(n)})}datetime(n){if(typeof n==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:n});return this._addCheck({kind:"datetime",precision:typeof n?.precision>"u"?null:n?.precision,offset:n?.offset??!1,local:n?.local??!1,...F.errToObj(n?.message)})}date(n){return this._addCheck({kind:"date",message:n})}time(n){if(typeof n==="string")return this._addCheck({kind:"time",precision:null,message:n});return this._addCheck({kind:"time",precision:typeof n?.precision>"u"?null:n?.precision,...F.errToObj(n?.message)})}duration(n){return this._addCheck({kind:"duration",...F.errToObj(n)})}regex(n,t){return this._addCheck({kind:"regex",regex:n,...F.errToObj(t)})}includes(n,t){return this._addCheck({kind:"includes",value:n,position:t?.position,...F.errToObj(t?.message)})}startsWith(n,t){return this._addCheck({kind:"startsWith",value:n,...F.errToObj(t)})}endsWith(n,t){return this._addCheck({kind:"endsWith",value:n,...F.errToObj(t)})}min(n,t){return this._addCheck({kind:"min",value:n,...F.errToObj(t)})}max(n,t){return this._addCheck({kind:"max",value:n,...F.errToObj(t)})}length(n,t){return this._addCheck({kind:"length",value:n,...F.errToObj(t)})}nonempty(n){return this.min(1,F.errToObj(n))}trim(){return new dt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new dt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new dt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((n)=>n.kind==="datetime")}get isDate(){return!!this._def.checks.find((n)=>n.kind==="date")}get isTime(){return!!this._def.checks.find((n)=>n.kind==="time")}get isDuration(){return!!this._def.checks.find((n)=>n.kind==="duration")}get isEmail(){return!!this._def.checks.find((n)=>n.kind==="email")}get isURL(){return!!this._def.checks.find((n)=>n.kind==="url")}get isEmoji(){return!!this._def.checks.find((n)=>n.kind==="emoji")}get isUUID(){return!!this._def.checks.find((n)=>n.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((n)=>n.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((n)=>n.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((n)=>n.kind==="cuid2")}get isULID(){return!!this._def.checks.find((n)=>n.kind==="ulid")}get isIP(){return!!this._def.checks.find((n)=>n.kind==="ip")}get isCIDR(){return!!this._def.checks.find((n)=>n.kind==="cidr")}get isBase64(){return!!this._def.checks.find((n)=>n.kind==="base64")}get isBase64url(){return!!this._def.checks.find((n)=>n.kind==="base64url")}get minLength(){let n=null;for(let t of this._def.checks)if(t.kind==="min"){if(n===null||t.value>n)n=t.value}return n}get maxLength(){let n=null;for(let t of this._def.checks)if(t.kind==="max"){if(n===null||t.value<n)n=t.value}return n}}dt.create=(n)=>{return new dt({checks:[],typeName:V.ZodString,coerce:n?.coerce??!1,...a(n)})};function d6(n,t){let i=(n.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=i>r?i:r,f=Number.parseInt(n.toFixed(s).replace(".","")),h=Number.parseInt(t.toFixed(s).replace(".",""));return f%h/10**s}class oi extends tn{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(n){if(this._def.coerce)n.data=Number(n.data);if(this._getType(n)!==N.number){let s=this._getOrReturnCtx(n);return B(s,{code:O.invalid_type,expected:N.number,received:s.parsedType}),C}let i=void 0,r=new Wn;for(let s of this._def.checks)if(s.kind==="int"){if(!sn.isInteger(n.data))i=this._getOrReturnCtx(n,i),B(i,{code:O.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty()}else if(s.kind==="min"){if(s.inclusive?n.data<s.value:n.data<=s.value)i=this._getOrReturnCtx(n,i),B(i,{code:O.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()}else if(s.kind==="max"){if(s.inclusive?n.data>s.value:n.data>=s.value)i=this._getOrReturnCtx(n,i),B(i,{code:O.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()}else if(s.kind==="multipleOf"){if(d6(n.data,s.value)!==0)i=this._getOrReturnCtx(n,i),B(i,{code:O.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()}else if(s.kind==="finite"){if(!Number.isFinite(n.data))i=this._getOrReturnCtx(n,i),B(i,{code:O.not_finite,message:s.message}),r.dirty()}else sn.assertNever(s);return{status:r.value,value:n.data}}gte(n,t){return this.setLimit("min",n,!0,F.toString(t))}gt(n,t){return this.setLimit("min",n,!1,F.toString(t))}lte(n,t){return this.setLimit("max",n,!0,F.toString(t))}lt(n,t){return this.setLimit("max",n,!1,F.toString(t))}setLimit(n,t,i,r){return new oi({...this._def,checks:[...this._def.checks,{kind:n,value:t,inclusive:i,message:F.toString(r)}]})}_addCheck(n){return new oi({...this._def,checks:[...this._def.checks,n]})}int(n){return this._addCheck({kind:"int",message:F.toString(n)})}positive(n){return this._addCheck({kind:"min",value:0,inclusive:!1,message:F.toString(n)})}negative(n){return this._addCheck({kind:"max",value:0,inclusive:!1,message:F.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:0,inclusive:!0,message:F.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:0,inclusive:!0,message:F.toString(n)})}multipleOf(n,t){return this._addCheck({kind:"multipleOf",value:n,message:F.toString(t)})}finite(n){return this._addCheck({kind:"finite",message:F.toString(n)})}safe(n){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:F.toString(n)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:F.toString(n)})}get minValue(){let n=null;for(let t of this._def.checks)if(t.kind==="min"){if(n===null||t.value>n)n=t.value}return n}get maxValue(){let n=null;for(let t of this._def.checks)if(t.kind==="max"){if(n===null||t.value<n)n=t.value}return n}get isInt(){return!!this._def.checks.find((n)=>n.kind==="int"||n.kind==="multipleOf"&&sn.isInteger(n.value))}get isFinite(){let n=null,t=null;for(let i of this._def.checks)if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;else if(i.kind==="min"){if(t===null||i.value>t)t=i.value}else if(i.kind==="max"){if(n===null||i.value<n)n=i.value}return Number.isFinite(t)&&Number.isFinite(n)}}oi.create=(n)=>{return new oi({checks:[],typeName:V.ZodNumber,coerce:n?.coerce||!1,...a(n)})};class wi extends tn{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(n){if(this._def.coerce)try{n.data=BigInt(n.data)}catch{return this._getInvalidInput(n)}if(this._getType(n)!==N.bigint)return this._getInvalidInput(n);let i=void 0,r=new Wn;for(let s of this._def.checks)if(s.kind==="min"){if(s.inclusive?n.data<s.value:n.data<=s.value)i=this._getOrReturnCtx(n,i),B(i,{code:O.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()}else if(s.kind==="max"){if(s.inclusive?n.data>s.value:n.data>=s.value)i=this._getOrReturnCtx(n,i),B(i,{code:O.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()}else if(s.kind==="multipleOf"){if(n.data%s.value!==BigInt(0))i=this._getOrReturnCtx(n,i),B(i,{code:O.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()}else sn.assertNever(s);return{status:r.value,value:n.data}}_getInvalidInput(n){let t=this._getOrReturnCtx(n);return B(t,{code:O.invalid_type,expected:N.bigint,received:t.parsedType}),C}gte(n,t){return this.setLimit("min",n,!0,F.toString(t))}gt(n,t){return this.setLimit("min",n,!1,F.toString(t))}lte(n,t){return this.setLimit("max",n,!0,F.toString(t))}lt(n,t){return this.setLimit("max",n,!1,F.toString(t))}setLimit(n,t,i,r){return new wi({...this._def,checks:[...this._def.checks,{kind:n,value:t,inclusive:i,message:F.toString(r)}]})}_addCheck(n){return new wi({...this._def,checks:[...this._def.checks,n]})}positive(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:F.toString(n)})}negative(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:F.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:F.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:F.toString(n)})}multipleOf(n,t){return this._addCheck({kind:"multipleOf",value:n,message:F.toString(t)})}get minValue(){let n=null;for(let t of this._def.checks)if(t.kind==="min"){if(n===null||t.value>n)n=t.value}return n}get maxValue(){let n=null;for(let t of this._def.checks)if(t.kind==="max"){if(n===null||t.value<n)n=t.value}return n}}wi.create=(n)=>{return new wi({checks:[],typeName:V.ZodBigInt,coerce:n?.coerce??!1,...a(n)})};class Tr extends tn{_parse(n){if(this._def.coerce)n.data=Boolean(n.data);if(this._getType(n)!==N.boolean){let i=this._getOrReturnCtx(n);return B(i,{code:O.invalid_type,expected:N.boolean,received:i.parsedType}),C}return ln(n.data)}}Tr.create=(n)=>{return new Tr({typeName:V.ZodBoolean,coerce:n?.coerce||!1,...a(n)})};class Fi extends tn{_parse(n){if(this._def.coerce)n.data=new Date(n.data);if(this._getType(n)!==N.date){let s=this._getOrReturnCtx(n);return B(s,{code:O.invalid_type,expected:N.date,received:s.parsedType}),C}if(Number.isNaN(n.data.getTime())){let s=this._getOrReturnCtx(n);return B(s,{code:O.invalid_date}),C}let i=new Wn,r=void 0;for(let s of this._def.checks)if(s.kind==="min"){if(n.data.getTime()<s.value)r=this._getOrReturnCtx(n,r),B(r,{code:O.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),i.dirty()}else if(s.kind==="max"){if(n.data.getTime()>s.value)r=this._getOrReturnCtx(n,r),B(r,{code:O.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),i.dirty()}else sn.assertNever(s);return{status:i.value,value:new Date(n.data.getTime())}}_addCheck(n){return new Fi({...this._def,checks:[...this._def.checks,n]})}min(n,t){return this._addCheck({kind:"min",value:n.getTime(),message:F.toString(t)})}max(n,t){return this._addCheck({kind:"max",value:n.getTime(),message:F.toString(t)})}get minDate(){let n=null;for(let t of this._def.checks)if(t.kind==="min"){if(n===null||t.value>n)n=t.value}return n!=null?new Date(n):null}get maxDate(){let n=null;for(let t of this._def.checks)if(t.kind==="max"){if(n===null||t.value<n)n=t.value}return n!=null?new Date(n):null}}Fi.create=(n)=>{return new Fi({checks:[],coerce:n?.coerce||!1,typeName:V.ZodDate,...a(n)})};class Us extends tn{_parse(n){if(this._getType(n)!==N.symbol){let i=this._getOrReturnCtx(n);return B(i,{code:O.invalid_type,expected:N.symbol,received:i.parsedType}),C}return ln(n.data)}}Us.create=(n)=>{return new Us({typeName:V.ZodSymbol,...a(n)})};class gr extends tn{_parse(n){if(this._getType(n)!==N.undefined){let i=this._getOrReturnCtx(n);return B(i,{code:O.invalid_type,expected:N.undefined,received:i.parsedType}),C}return ln(n.data)}}gr.create=(n)=>{return new gr({typeName:V.ZodUndefined,...a(n)})};class Sr extends tn{_parse(n){if(this._getType(n)!==N.null){let i=this._getOrReturnCtx(n);return B(i,{code:O.invalid_type,expected:N.null,received:i.parsedType}),C}return ln(n.data)}}Sr.create=(n)=>{return new Sr({typeName:V.ZodNull,...a(n)})};class Xi extends tn{constructor(){super(...arguments);this._any=!0}_parse(n){return ln(n.data)}}Xi.create=(n)=>{return new Xi({typeName:V.ZodAny,...a(n)})};class ci extends tn{constructor(){super(...arguments);this._unknown=!0}_parse(n){return ln(n.data)}}ci.create=(n)=>{return new ci({typeName:V.ZodUnknown,...a(n)})};class It extends tn{_parse(n){let t=this._getOrReturnCtx(n);return B(t,{code:O.invalid_type,expected:N.never,received:t.parsedType}),C}}It.create=(n)=>{return new It({typeName:V.ZodNever,...a(n)})};class bs extends tn{_parse(n){if(this._getType(n)!==N.undefined){let i=this._getOrReturnCtx(n);return B(i,{code:O.invalid_type,expected:N.void,received:i.parsedType}),C}return ln(n.data)}}bs.create=(n)=>{return new bs({typeName:V.ZodVoid,...a(n)})};class At extends tn{_parse(n){let{ctx:t,status:i}=this._processInputParams(n),r=this._def;if(t.parsedType!==N.array)return B(t,{code:O.invalid_type,expected:N.array,received:t.parsedType}),C;if(r.exactLength!==null){let f=t.data.length>r.exactLength.value,h=t.data.length<r.exactLength.value;if(f||h)B(t,{code:f?O.too_big:O.too_small,minimum:h?r.exactLength.value:void 0,maximum:f?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),i.dirty()}if(r.minLength!==null){if(t.data.length<r.minLength.value)B(t,{code:O.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),i.dirty()}if(r.maxLength!==null){if(t.data.length>r.maxLength.value)B(t,{code:O.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),i.dirty()}if(t.common.async)return Promise.all([...t.data].map((f,h)=>{return r.type._parseAsync(new Mt(t,f,t.path,h))})).then((f)=>{return Wn.mergeArray(i,f)});let s=[...t.data].map((f,h)=>{return r.type._parseSync(new Mt(t,f,t.path,h))});return Wn.mergeArray(i,s)}get element(){return this._def.type}min(n,t){return new At({...this._def,minLength:{value:n,message:F.toString(t)}})}max(n,t){return new At({...this._def,maxLength:{value:n,message:F.toString(t)}})}length(n,t){return new At({...this._def,exactLength:{value:n,message:F.toString(t)}})}nonempty(n){return this.min(1,n)}}At.create=(n,t)=>{return new At({type:n,minLength:null,maxLength:null,exactLength:null,typeName:V.ZodArray,...a(t)})};function Mr(n){if(n instanceof Tn){let t={};for(let i in n.shape){let r=n.shape[i];t[i]=Rt.create(Mr(r))}return new Tn({...n._def,shape:()=>t})}else if(n instanceof At)return new At({...n._def,type:Mr(n.element)});else if(n instanceof Rt)return Rt.create(Mr(n.unwrap()));else if(n instanceof kt)return kt.create(Mr(n.unwrap()));else if(n instanceof Ht)return Ht.create(n.items.map((t)=>Mr(t)));else return n}class Tn extends tn{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let n=this._def.shape(),t=sn.objectKeys(n);return this._cached={shape:n,keys:t},this._cached}_parse(n){if(this._getType(n)!==N.object){let c=this._getOrReturnCtx(n);return B(c,{code:O.invalid_type,expected:N.object,received:c.parsedType}),C}let{status:i,ctx:r}=this._processInputParams(n),{shape:s,keys:f}=this._getCached(),h=[];if(!(this._def.catchall instanceof It&&this._def.unknownKeys==="strip")){for(let c in r.data)if(!f.includes(c))h.push(c)}let _=[];for(let c of f){let o=s[c],w=r.data[c];_.push({key:{status:"valid",value:c},value:o._parse(new Mt(r,w,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof It){let c=this._def.unknownKeys;if(c==="passthrough")for(let o of h)_.push({key:{status:"valid",value:o},value:{status:"valid",value:r.data[o]}});else if(c==="strict"){if(h.length>0)B(r,{code:O.unrecognized_keys,keys:h}),i.dirty()}else if(c==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let o of h){let w=r.data[o];_.push({key:{status:"valid",value:o},value:c._parse(new Mt(r,w,r.path,o)),alwaysSet:o in r.data})}}if(r.common.async)return Promise.resolve().then(async()=>{let c=[];for(let o of _){let w=await o.key,e=await o.value;c.push({key:w,value:e,alwaysSet:o.alwaysSet})}return c}).then((c)=>{return Wn.mergeObjectSync(i,c)});else return Wn.mergeObjectSync(i,_)}get shape(){return this._def.shape()}strict(n){return F.errToObj,new Tn({...this._def,unknownKeys:"strict",...n!==void 0?{errorMap:(t,i)=>{let r=this._def.errorMap?.(t,i).message??i.defaultError;if(t.code==="unrecognized_keys")return{message:F.errToObj(n).message??r};return{message:r}}}:{}})}strip(){return new Tn({...this._def,unknownKeys:"strip"})}passthrough(){return new Tn({...this._def,unknownKeys:"passthrough"})}extend(n){return new Tn({...this._def,shape:()=>({...this._def.shape(),...n})})}merge(n){return new Tn({unknownKeys:n._def.unknownKeys,catchall:n._def.catchall,shape:()=>({...this._def.shape(),...n._def.shape()}),typeName:V.ZodObject})}setKey(n,t){return this.augment({[n]:t})}catchall(n){return new Tn({...this._def,catchall:n})}pick(n){let t={};for(let i of sn.objectKeys(n))if(n[i]&&this.shape[i])t[i]=this.shape[i];return new Tn({...this._def,shape:()=>t})}omit(n){let t={};for(let i of sn.objectKeys(this.shape))if(!n[i])t[i]=this.shape[i];return new Tn({...this._def,shape:()=>t})}deepPartial(){return Mr(this)}partial(n){let t={};for(let i of sn.objectKeys(this.shape)){let r=this.shape[i];if(n&&!n[i])t[i]=r;else t[i]=r.optional()}return new Tn({...this._def,shape:()=>t})}required(n){let t={};for(let i of sn.objectKeys(this.shape))if(n&&!n[i])t[i]=this.shape[i];else{let s=this.shape[i];while(s instanceof Rt)s=s._def.innerType;t[i]=s}return new Tn({...this._def,shape:()=>t})}keyof(){return Je(sn.objectKeys(this.shape))}}Tn.create=(n,t)=>{return new Tn({shape:()=>n,unknownKeys:"strip",catchall:It.create(),typeName:V.ZodObject,...a(t)})};Tn.strictCreate=(n,t)=>{return new Tn({shape:()=>n,unknownKeys:"strict",catchall:It.create(),typeName:V.ZodObject,...a(t)})};Tn.lazycreate=(n,t)=>{return new Tn({shape:n,unknownKeys:"strip",catchall:It.create(),typeName:V.ZodObject,...a(t)})};class Lr extends tn{_parse(n){let{ctx:t}=this._processInputParams(n),i=this._def.options;function r(s){for(let h of s)if(h.result.status==="valid")return h.result;for(let h of s)if(h.result.status==="dirty")return t.common.issues.push(...h.ctx.common.issues),h.result;let f=s.map((h)=>new Vn(h.ctx.common.issues));return B(t,{code:O.invalid_union,unionErrors:f}),C}if(t.common.async)return Promise.all(i.map(async(s)=>{let f={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:f}),ctx:f}})).then(r);else{let s=void 0,f=[];for(let _ of i){let c={...t,common:{...t.common,issues:[]},parent:null},o=_._parseSync({data:t.data,path:t.path,parent:c});if(o.status==="valid")return o;else if(o.status==="dirty"&&!s)s={result:o,ctx:c};if(c.common.issues.length)f.push(c.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;let h=f.map((_)=>new Vn(_));return B(t,{code:O.invalid_union,unionErrors:h}),C}}get options(){return this._def.options}}Lr.create=(n,t)=>{return new Lr({options:n,typeName:V.ZodUnion,...a(t)})};var jt=(n)=>{if(n instanceof Or)return jt(n.schema);else if(n instanceof Et)return jt(n.innerType());else if(n instanceof Ur)return[n.value];else if(n instanceof ei)return n.options;else if(n instanceof br)return sn.objectValues(n.enum);else if(n instanceof Nr)return jt(n._def.innerType);else if(n instanceof gr)return[void 0];else if(n instanceof Sr)return[null];else if(n instanceof Rt)return[void 0,...jt(n.unwrap())];else if(n instanceof kt)return[null,...jt(n.unwrap())];else if(n instanceof Qf)return jt(n.unwrap());else if(n instanceof Ir)return jt(n.unwrap());else if(n instanceof Br)return jt(n._def.innerType);else return[]};class Jf extends tn{_parse(n){let{ctx:t}=this._processInputParams(n);if(t.parsedType!==N.object)return B(t,{code:O.invalid_type,expected:N.object,received:t.parsedType}),C;let i=this.discriminator,r=t.data[i],s=this.optionsMap.get(r);if(!s)return B(t,{code:O.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),C;if(t.common.async)return s._parseAsync({data:t.data,path:t.path,parent:t});else return s._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(n,t,i){let r=new Map;for(let s of t){let f=jt(s.shape[n]);if(!f.length)throw Error(`A discriminator value for key \`${n}\` could not be extracted from all schema options`);for(let h of f){if(r.has(h))throw Error(`Discriminator property ${String(n)} has duplicate value ${String(h)}`);r.set(h,s)}}return new Jf({typeName:V.ZodDiscriminatedUnion,discriminator:n,options:t,optionsMap:r,...a(i)})}}function d0(n,t){let i=Bt(n),r=Bt(t);if(n===t)return{valid:!0,data:n};else if(i===N.object&&r===N.object){let s=sn.objectKeys(t),f=sn.objectKeys(n).filter((_)=>s.indexOf(_)!==-1),h={...n,...t};for(let _ of f){let c=d0(n[_],t[_]);if(!c.valid)return{valid:!1};h[_]=c.data}return{valid:!0,data:h}}else if(i===N.array&&r===N.array){if(n.length!==t.length)return{valid:!1};let s=[];for(let f=0;f<n.length;f++){let h=n[f],_=t[f],c=d0(h,_);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else if(i===N.date&&r===N.date&&+n===+t)return{valid:!0,data:n};else return{valid:!1}}class $r extends tn{_parse(n){let{status:t,ctx:i}=this._processInputParams(n),r=(s,f)=>{if(Xf(s)||Xf(f))return C;let h=d0(s.value,f.value);if(!h.valid)return B(i,{code:O.invalid_intersection_types}),C;if(lf(s)||lf(f))t.dirty();return{status:t.value,value:h.data}};if(i.common.async)return Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([s,f])=>r(s,f));else return r(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}$r.create=(n,t,i)=>{return new $r({left:n,right:t,typeName:V.ZodIntersection,...a(i)})};class Ht extends tn{_parse(n){let{status:t,ctx:i}=this._processInputParams(n);if(i.parsedType!==N.array)return B(i,{code:O.invalid_type,expected:N.array,received:i.parsedType}),C;if(i.data.length<this._def.items.length)return B(i,{code:O.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),C;if(!this._def.rest&&i.data.length>this._def.items.length)B(i,{code:O.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let s=[...i.data].map((f,h)=>{let _=this._def.items[h]||this._def.rest;if(!_)return null;return _._parse(new Mt(i,f,i.path,h))}).filter((f)=>!!f);if(i.common.async)return Promise.all(s).then((f)=>{return Wn.mergeArray(t,f)});else return Wn.mergeArray(t,s)}get items(){return this._def.items}rest(n){return new Ht({...this._def,rest:n})}}Ht.create=(n,t)=>{if(!Array.isArray(n))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ht({items:n,typeName:V.ZodTuple,rest:null,...a(t)})};class Ns extends tn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){let{status:t,ctx:i}=this._processInputParams(n);if(i.parsedType!==N.object)return B(i,{code:O.invalid_type,expected:N.object,received:i.parsedType}),C;let r=[],s=this._def.keyType,f=this._def.valueType;for(let h in i.data)r.push({key:s._parse(new Mt(i,h,i.path,h)),value:f._parse(new Mt(i,i.data[h],i.path,h)),alwaysSet:h in i.data});if(i.common.async)return Wn.mergeObjectAsync(t,r);else return Wn.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(n,t,i){if(t instanceof tn)return new Ns({keyType:n,valueType:t,typeName:V.ZodRecord,...a(i)});return new Ns({keyType:dt.create(),valueType:n,typeName:V.ZodRecord,...a(t)})}}class Bs extends tn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){let{status:t,ctx:i}=this._processInputParams(n);if(i.parsedType!==N.map)return B(i,{code:O.invalid_type,expected:N.map,received:i.parsedType}),C;let r=this._def.keyType,s=this._def.valueType,f=[...i.data.entries()].map(([h,_],c)=>{return{key:r._parse(new Mt(i,h,i.path,[c,"key"])),value:s._parse(new Mt(i,_,i.path,[c,"value"]))}});if(i.common.async){let h=new Map;return Promise.resolve().then(async()=>{for(let _ of f){let c=await _.key,o=await _.value;if(c.status==="aborted"||o.status==="aborted")return C;if(c.status==="dirty"||o.status==="dirty")t.dirty();h.set(c.value,o.value)}return{status:t.value,value:h}})}else{let h=new Map;for(let _ of f){let{key:c,value:o}=_;if(c.status==="aborted"||o.status==="aborted")return C;if(c.status==="dirty"||o.status==="dirty")t.dirty();h.set(c.value,o.value)}return{status:t.value,value:h}}}}Bs.create=(n,t,i)=>{return new Bs({valueType:t,keyType:n,typeName:V.ZodMap,...a(i)})};class li extends tn{_parse(n){let{status:t,ctx:i}=this._processInputParams(n);if(i.parsedType!==N.set)return B(i,{code:O.invalid_type,expected:N.set,received:i.parsedType}),C;let r=this._def;if(r.minSize!==null){if(i.data.size<r.minSize.value)B(i,{code:O.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()}if(r.maxSize!==null){if(i.data.size>r.maxSize.value)B(i,{code:O.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty()}let s=this._def.valueType;function f(_){let c=new Set;for(let o of _){if(o.status==="aborted")return C;if(o.status==="dirty")t.dirty();c.add(o.value)}return{status:t.value,value:c}}let h=[...i.data.values()].map((_,c)=>s._parse(new Mt(i,_,i.path,c)));if(i.common.async)return Promise.all(h).then((_)=>f(_));else return f(h)}min(n,t){return new li({...this._def,minSize:{value:n,message:F.toString(t)}})}max(n,t){return new li({...this._def,maxSize:{value:n,message:F.toString(t)}})}size(n,t){return this.min(n,t).max(n,t)}nonempty(n){return this.min(1,n)}}li.create=(n,t)=>{return new li({valueType:n,minSize:null,maxSize:null,typeName:V.ZodSet,...a(t)})};class Er extends tn{constructor(){super(...arguments);this.validate=this.implement}_parse(n){let{ctx:t}=this._processInputParams(n);if(t.parsedType!==N.function)return B(t,{code:O.invalid_type,expected:N.function,received:t.parsedType}),C;function i(h,_){return Os({data:h,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ar(),xt].filter((c)=>!!c),issueData:{code:O.invalid_arguments,argumentsError:_}})}function r(h,_){return Os({data:h,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ar(),xt].filter((c)=>!!c),issueData:{code:O.invalid_return_type,returnTypeError:_}})}let s={errorMap:t.common.contextualErrorMap},f=t.data;if(this._def.returns instanceof Ji){let h=this;return ln(async function(..._){let c=new Vn([]),o=await h._def.args.parseAsync(_,s).catch((u)=>{throw c.addIssue(i(_,u)),c}),w=await Reflect.apply(f,this,o);return await h._def.returns._def.type.parseAsync(w,s).catch((u)=>{throw c.addIssue(r(w,u)),c})})}else{let h=this;return ln(function(..._){let c=h._def.args.safeParse(_,s);if(!c.success)throw new Vn([i(_,c.error)]);let o=Reflect.apply(f,this,c.data),w=h._def.returns.safeParse(o,s);if(!w.success)throw new Vn([r(o,w.error)]);return w.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...n){return new Er({...this._def,args:Ht.create(n).rest(ci.create())})}returns(n){return new Er({...this._def,returns:n})}implement(n){return this.parse(n)}strictImplement(n){return this.parse(n)}static create(n,t,i){return new Er({args:n?n:Ht.create([]).rest(ci.create()),returns:t||ci.create(),typeName:V.ZodFunction,...a(i)})}}class Or extends tn{get schema(){return this._def.getter()}_parse(n){let{ctx:t}=this._processInputParams(n);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Or.create=(n,t)=>{return new Or({getter:n,typeName:V.ZodLazy,...a(t)})};class Ur extends tn{_parse(n){if(n.data!==this._def.value){let t=this._getOrReturnCtx(n);return B(t,{received:t.data,code:O.invalid_literal,expected:this._def.value}),C}return{status:"valid",value:n.data}}get value(){return this._def.value}}Ur.create=(n,t)=>{return new Ur({value:n,typeName:V.ZodLiteral,...a(t)})};function Je(n,t){return new ei({values:n,typeName:V.ZodEnum,...a(t)})}class ei extends tn{_parse(n){if(typeof n.data!=="string"){let t=this._getOrReturnCtx(n),i=this._def.values;return B(t,{expected:sn.joinValues(i),received:t.parsedType,code:O.invalid_type}),C}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(n.data)){let t=this._getOrReturnCtx(n),i=this._def.values;return B(t,{received:t.data,code:O.invalid_enum_value,options:i}),C}return ln(n.data)}get options(){return this._def.values}get enum(){let n={};for(let t of this._def.values)n[t]=t;return n}get Values(){let n={};for(let t of this._def.values)n[t]=t;return n}get Enum(){let n={};for(let t of this._def.values)n[t]=t;return n}extract(n,t=this._def){return ei.create(n,{...this._def,...t})}exclude(n,t=this._def){return ei.create(this.options.filter((i)=>!n.includes(i)),{...this._def,...t})}}ei.create=Je;class br extends tn{_parse(n){let t=sn.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(n);if(i.parsedType!==N.string&&i.parsedType!==N.number){let r=sn.objectValues(t);return B(i,{expected:sn.joinValues(r),received:i.parsedType,code:O.invalid_type}),C}if(!this._cache)this._cache=new Set(sn.getValidEnumValues(this._def.values));if(!this._cache.has(n.data)){let r=sn.objectValues(t);return B(i,{received:i.data,code:O.invalid_enum_value,options:r}),C}return ln(n.data)}get enum(){return this._def.values}}br.create=(n,t)=>{return new br({values:n,typeName:V.ZodNativeEnum,...a(t)})};class Ji extends tn{unwrap(){return this._def.type}_parse(n){let{ctx:t}=this._processInputParams(n);if(t.parsedType!==N.promise&&t.common.async===!1)return B(t,{code:O.invalid_type,expected:N.promise,received:t.parsedType}),C;let i=t.parsedType===N.promise?t.data:Promise.resolve(t.data);return ln(i.then((r)=>{return this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})}))}}Ji.create=(n,t)=>{return new Ji({type:n,typeName:V.ZodPromise,...a(t)})};class Et extends tn{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===V.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(n){let{status:t,ctx:i}=this._processInputParams(n),r=this._def.effect||null,s={addIssue:(f)=>{if(B(i,f),f.fatal)t.abort();else t.dirty()},get path(){return i.path}};if(s.addIssue=s.addIssue.bind(s),r.type==="preprocess"){let f=r.transform(i.data,s);if(i.common.async)return Promise.resolve(f).then(async(h)=>{if(t.value==="aborted")return C;let _=await this._def.schema._parseAsync({data:h,path:i.path,parent:i});if(_.status==="aborted")return C;if(_.status==="dirty")return Yi(_.value);if(t.value==="dirty")return Yi(_.value);return _});else{if(t.value==="aborted")return C;let h=this._def.schema._parseSync({data:f,path:i.path,parent:i});if(h.status==="aborted")return C;if(h.status==="dirty")return Yi(h.value);if(t.value==="dirty")return Yi(h.value);return h}}if(r.type==="refinement"){let f=(h)=>{let _=r.refinement(h,s);if(i.common.async)return Promise.resolve(_);if(_ instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return h};if(i.common.async===!1){let h=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(h.status==="aborted")return C;if(h.status==="dirty")t.dirty();return f(h.value),{status:t.value,value:h.value}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then((h)=>{if(h.status==="aborted")return C;if(h.status==="dirty")t.dirty();return f(h.value).then(()=>{return{status:t.value,value:h.value}})})}if(r.type==="transform")if(i.common.async===!1){let f=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!hi(f))return C;let h=r.transform(f.value,s);if(h instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:h}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then((f)=>{if(!hi(f))return C;return Promise.resolve(r.transform(f.value,s)).then((h)=>({status:t.value,value:h}))});sn.assertNever(r)}}Et.create=(n,t,i)=>{return new Et({schema:n,typeName:V.ZodEffects,effect:t,...a(i)})};Et.createWithPreprocess=(n,t,i)=>{return new Et({schema:t,effect:{type:"preprocess",transform:n},typeName:V.ZodEffects,...a(i)})};class Rt extends tn{_parse(n){if(this._getType(n)===N.undefined)return ln(void 0);return this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}Rt.create=(n,t)=>{return new Rt({innerType:n,typeName:V.ZodOptional,...a(t)})};class kt extends tn{_parse(n){if(this._getType(n)===N.null)return ln(null);return this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}kt.create=(n,t)=>{return new kt({innerType:n,typeName:V.ZodNullable,...a(t)})};class Nr extends tn{_parse(n){let{ctx:t}=this._processInputParams(n),i=t.data;if(t.parsedType===N.undefined)i=this._def.defaultValue();return this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Nr.create=(n,t)=>{return new Nr({innerType:n,typeName:V.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...a(t)})};class Br extends tn{_parse(n){let{ctx:t}=this._processInputParams(n),i={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});if(Rr(r))return r.then((s)=>{return{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Vn(i.common.issues)},input:i.data})}});else return{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Vn(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Br.create=(n,t)=>{return new Br({innerType:n,typeName:V.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...a(t)})};class Is extends tn{_parse(n){if(this._getType(n)!==N.nan){let i=this._getOrReturnCtx(n);return B(i,{code:O.invalid_type,expected:N.nan,received:i.parsedType}),C}return{status:"valid",value:n.data}}}Is.create=(n)=>{return new Is({typeName:V.ZodNaN,...a(n)})};var A6=Symbol("zod_brand");class Qf extends tn{_parse(n){let{ctx:t}=this._processInputParams(n),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class Hs extends tn{_parse(n){let{status:t,ctx:i}=this._processInputParams(n);if(i.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});if(s.status==="aborted")return C;if(s.status==="dirty")return t.dirty(),Yi(s.value);else return this._def.out._parseAsync({data:s.value,path:i.path,parent:i})})();else{let r=this._def.in._parseSync({data:i.data,path:i.path,parent:i});if(r.status==="aborted")return C;if(r.status==="dirty")return t.dirty(),{status:"dirty",value:r.value};else return this._def.out._parseSync({data:r.value,path:i.path,parent:i})}}static create(n,t){return new Hs({in:n,out:t,typeName:V.ZodPipeline})}}class Ir extends tn{_parse(n){let t=this._def.innerType._parse(n),i=(r)=>{if(hi(r))r.value=Object.freeze(r.value);return r};return Rr(t)?t.then((r)=>i(r)):i(t)}unwrap(){return this._def.innerType}}Ir.create=(n,t)=>{return new Ir({innerType:n,typeName:V.ZodReadonly,...a(t)})};function Ye(n,t){let i=typeof n==="function"?n(t):typeof n==="string"?{message:n}:n;return typeof i==="string"?{message:i}:i}function Qe(n,t={},i){if(n)return Xi.create().superRefine((r,s)=>{let f=n(r);if(f instanceof Promise)return f.then((h)=>{if(!h){let _=Ye(t,r),c=_.fatal??i??!0;s.addIssue({code:"custom",..._,fatal:c})}});if(!f){let h=Ye(t,r),_=h.fatal??i??!0;s.addIssue({code:"custom",...h,fatal:_})}return});return Xi.create()}var R6={object:Tn.lazycreate},V;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(V||(V={}));var M6=(n,t={message:`Input not instance of ${n.name}`})=>Qe((i)=>i instanceof n,t),ze=dt.create,Ce=oi.create,E6=Is.create,T6=wi.create,Ve=Tr.create,g6=Fi.create,S6=Us.create,L6=gr.create,$6=Sr.create,O6=Xi.create,U6=ci.create,b6=It.create,N6=bs.create,B6=At.create,I6=Tn.create,H6=Tn.strictCreate,G6=Lr.create,W6=Jf.create,D6=$r.create,P6=Ht.create,Y6=Ns.create,F6=Bs.create,X6=li.create,l6=Er.create,J6=Or.create,Q6=Ur.create,z6=ei.create,C6=br.create,V6=Ji.create,K6=Et.create,x6=Rt.create,j6=kt.create,k6=Et.createWithPreprocess,q6=Hs.create,m6=()=>ze().optional(),Z6=()=>Ce().optional(),a6=()=>Ve().optional(),v6={string:(n)=>dt.create({...n,coerce:!0}),number:(n)=>oi.create({...n,coerce:!0}),boolean:(n)=>Tr.create({...n,coerce:!0}),bigint:(n)=>wi.create({...n,coerce:!0}),date:(n)=>Fi.create({...n,coerce:!0})};var p6=C;var zf=d.enum(["low","medium","high","xhigh","max"]),Qi=d.enum(["us-east-1","us-east-2","us-west-1","us-west-2","af-south-1","ap-east-1","ap-south-2","ap-southeast-3","ap-southeast-5","ap-southeast-4","ap-south-1","ap-southeast-6","ap-northeast-3","ap-northeast-2","ap-southeast-1","ap-southeast-2","ap-east-2","ap-southeast-7","ap-northeast-1","ca-central-1","ca-west-1","eu-central-1","eu-west-1","eu-west-2","eu-south-1","eu-west-3","eu-south-2","eu-north-1","eu-central-2","il-central-1","mx-central-1","me-south-1","me-central-1","sa-east-1"]);var ng=d.array(d.string()).transform((n)=>n.map((t)=>t.trim()).filter((t)=>t.length>0)).refine((n)=>n.length>0,{message:"api_keys must contain at least one non-empty key"}),tg=d.preprocess((n)=>typeof n==="string"&&n.trim().length===0?null:n,d.string().trim().refine((n)=>URL.canParse(n),{message:"proxy_url must be a valid URL"}).refine((n)=>{if(!URL.canParse(n))return!1;let t=new URL(n).protocol;return t==="http:"||t==="https:"},{message:"proxy_url must be http(s)"}).nullable()).default(null),Ke=d.preprocess((n)=>typeof n==="string"&&n.trim().length===0?null:n,d.string().trim().min(1).nullable()).default(null),A0=d.object({host:d.string().default("127.0.0.1"),port:d.number().default(8787),api_keys:ng,enable_legacy_chat_completions:d.boolean().default(!1),protocol_projection_mode:d.enum(["safe","legacy-user-prefix"]).default("safe"),session_affinity_mode:d.enum(["explicit-only","legacy-initial-input"]).default("explicit-only"),proxy_url:tg,sdk_http_keep_alive:d.boolean().default(!1),auth_source:d.enum(["opencode-shared","local"]).default("opencode-shared"),opencode_auth_db_path:Ke,default_region:d.string().default("us-east-1"),account_selection_strategy:d.enum(["sticky","round-robin","lowest-usage"]).default("lowest-usage"),rate_limit_max_retries:d.number().default(3),rate_limit_retry_delay_ms:d.number().default(5000),max_request_iterations:d.number().default(20),request_timeout_ms:d.number().int().min(1).max(2147483647).default(120000),stream_idle_timeout_ms:d.number().int().min(1).max(2147483647).default(60000),max_request_body_bytes:d.number().default(10485760),token_expiry_buffer_ms:d.number().default(300000),session_affinity_ttl_ms:d.number().int().min(1).max(2147483647).default(86400000),session_affinity_max_entries:d.number().int().min(1).max(1e6).default(1e4),reasoning_replay_key_path:Ke,reasoning_replay_keys:d.array(d.string().trim().min(1)).default([]),reasoning_replay_ttl_ms:d.number().int().min(1).max(2147483647).default(86400000),reasoning_replay_max_entries:d.number().int().min(1).max(1e6).default(1e4),effort:zf.nullable().default(null),auto_effort_mapping:d.boolean().default(!0),log_level:d.string().default("info"),test_upstream_endpoint:d.string().url().optional()});class Gs extends Error{constructor(n,t){super(n,t);this.name="ConfigLoadError"}}var fg=A0.partial();function _g(n){let t=n.XDG_CONFIG_HOME??xe(sg(),".config");return xe(t,"kiro-provider","config.json")}function hg(n){if(!ig(n))return{};try{let t=JSON.parse(rg(n,"utf8"));return fg.parse(t)}catch(t){if(t instanceof d.ZodError)throw new Gs(`Invalid configuration file ${n}: ${je(t)}`,{cause:t});if(t instanceof Error)throw new Gs(`Unable to read configuration file ${n}: ${t.message}`,{cause:t});throw t}}function cg(n){let t=n.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;return n}function og(n){let t={},i={KIRO_PROVIDER_HOST:"host",KIRO_PROVIDER_AUTH_SOURCE:"auth_source",KIRO_PROVIDER_DEFAULT_REGION:"default_region",KIRO_PROVIDER_ACCOUNT_SELECTION_STRATEGY:"account_selection_strategy",KIRO_PROVIDER_PROTOCOL_PROJECTION_MODE:"protocol_projection_mode",KIRO_PROVIDER_SESSION_AFFINITY_MODE:"session_affinity_mode",KIRO_PROVIDER_EFFORT:"effort",KIRO_PROVIDER_LOG_LEVEL:"log_level",KIRO_PROVIDER_TEST_UPSTREAM:"test_upstream_endpoint"};for(let[w,e]of Object.entries(i)){let u=n[w];if(u!==void 0)t[e]=u}let r={KIRO_PROVIDER_PORT:"port",KIRO_PROVIDER_RATE_LIMIT_MAX_RETRIES:"rate_limit_max_retries",KIRO_PROVIDER_RATE_LIMIT_RETRY_DELAY_MS:"rate_limit_retry_delay_ms",KIRO_PROVIDER_MAX_REQUEST_ITERATIONS:"max_request_iterations",KIRO_PROVIDER_REQUEST_TIMEOUT_MS:"request_timeout_ms",KIRO_PROVIDER_STREAM_IDLE_TIMEOUT_MS:"stream_idle_timeout_ms",KIRO_PROVIDER_MAX_REQUEST_BODY_BYTES:"max_request_body_bytes",KIRO_PROVIDER_TOKEN_EXPIRY_BUFFER_MS:"token_expiry_buffer_ms",KIRO_PROVIDER_SESSION_AFFINITY_TTL_MS:"session_affinity_ttl_ms",KIRO_PROVIDER_SESSION_AFFINITY_MAX_ENTRIES:"session_affinity_max_entries",KIRO_PROVIDER_REASONING_REPLAY_TTL_MS:"reasoning_replay_ttl_ms",KIRO_PROVIDER_REASONING_REPLAY_MAX_ENTRIES:"reasoning_replay_max_entries"};for(let[w,e]of Object.entries(r)){let u=n[w];if(u!==void 0)t[e]=Number(u)}let s=n.KIRO_PROVIDER_API_KEYS;if(s!==void 0)t.api_keys=s.split(",");let f=n.KIRO_PROVIDER_PROXY_URL;if(f!==void 0)t.proxy_url=f.trim();let h=n.KIRO_PROVIDER_OPENCODE_AUTH_DB_PATH;if(h!==void 0)t.opencode_auth_db_path=h.trim();let _=n.KIRO_PROVIDER_REASONING_REPLAY_KEY_PATH;if(_!==void 0)t.reasoning_replay_key_path=_.trim();let c=n.KIRO_PROVIDER_REASONING_REPLAY_KEYS;if(c!==void 0)t.reasoning_replay_keys=c.split(",").map((w)=>w.trim()).filter((w)=>w.length>0);let o={KIRO_PROVIDER_ENABLE_LEGACY_CHAT_COMPLETIONS:"enable_legacy_chat_completions",KIRO_PROVIDER_SDK_HTTP_KEEP_ALIVE:"sdk_http_keep_alive",KIRO_PROVIDER_AUTO_EFFORT_MAPPING:"auto_effort_mapping"};for(let[w,e]of Object.entries(o)){let u=n[w];if(u!==void 0)t[e]=cg(u)}return t}function je(n){return n.issues.map((t)=>`${t.path.length>0?t.path.join("."):"config"}: ${t.message}`).join(", ")}function ke(n={}){let t=n.env??process.env,i=n.configPath??_g(t);try{return A0.parse({...hg(i),...og(t),...n.overrides})}catch(r){if(r instanceof Gs)throw r;if(r instanceof d.ZodError)throw new Gs(`Invalid configuration: ${je(r)}`,{cause:r});throw r}}function Hr(n){let t=n.split("|"),i=t[0]??"";if(t.length<2)return{refreshToken:i,authMethod:"desktop"};if(t.at(-1)==="idc")return{refreshToken:i,clientId:t[1],clientSecret:t[2],authMethod:"idc"};return{refreshToken:i,authMethod:"desktop"}}function Ws(n,t=120000){if(!n.access||!n.expires)return!0;return Date.now()>=n.expires-t}function Cf(n){if(n.authMethod==="idc"){if(!n.clientId||!n.clientSecret)throw Error("Missing credentials");return`${n.refreshToken}|${n.clientId}|${n.clientSecret}|idc`}return`${n.refreshToken}|desktop`}function Vf(n){if(!n)return!1;return n.includes("Invalid refresh token")||n.includes("Invalid grant provided")||n.includes("invalid_grant")||n.includes("ExpiredTokenException")||n.includes("InvalidTokenException")||n.includes("ExpiredClientException")||n.includes("Client is expired")||n.includes("HTTP_401")||n.includes("HTTP_403")}function Gr(n){if(!n)return!1;let t=n.toLowerCase();return t.includes("bearer token included in the request is invalid")||t.includes("access token has expired")||t.includes("access_token expired")||t.includes("the access token expired")}function Wr(n){return Vf(n)}function qe(n){let t=n&&n.length>0?n:"Account needs re-authentication";return Vf(t)?t:`InvalidTokenException: ${t}`}var me=4;class Ze extends Error{accountId;constructor(n){super(`Account ${n} changed too frequently to update`);this.accountId=n;this.name="AccountConcurrentUpdateError"}}function wg(n){throw TypeError(`Unsupported account selection strategy: ${String(n)}`)}function Ds(n){return{...n}}function R0(n){return{refresh:Cf({refreshToken:n.refreshToken,authMethod:n.authMethod,...n.clientId?{clientId:n.clientId}:{},...n.clientSecret?{clientSecret:n.clientSecret}:{},...n.profileArn?{profileArn:n.profileArn}:{}}),access:n.accessToken,expires:n.expiresAt,authMethod:n.authMethod,region:n.region,...n.oidcRegion?{oidcRegion:n.oidcRegion}:{},...n.clientId?{clientId:n.clientId}:{},...n.clientSecret?{clientSecret:n.clientSecret}:{},...n.email?{email:n.email}:{},...n.profileArn?{profileArn:n.profileArn}:{}}}class M0{strategy;database;accounts;stickyId;roundRobinCursor=0;constructor(n,t,i){this.strategy=t;this.database=i;this.accounts=n.map(Ds)}getAccountCount(){return this.accounts.length}getAccounts(){return this.accounts.map(Ds)}getMinWaitTime(){let n=Date.now(),t=this.accounts.map(({rateLimitResetTime:i})=>i-n).filter((i)=>i>0);return t.length===0?0:Math.min(...t)}reconcileFromDb(n=this.database){let t=new Map(this.accounts.map((i)=>[i.id,i]));if(this.accounts=n.getAccounts().map((i)=>{let r=t.get(i.id);return r?.generation===i.generation?r:Ds(i)}),this.stickyId&&!this.accounts.some(({id:i})=>i===this.stickyId))this.stickyId=void 0;return this.getAccounts()}selectHealthyAccount(n){let t=Date.now(),i=this.accounts.filter((s)=>this.isSelectable(s,t)).sort((s,f)=>s.id.localeCompare(f.id));if(i.length===0)return null;let r=i.find(({id:s})=>s===n)??this.selectCandidate(i);return this.patchAccount(r.id,(s)=>({...s,isHealthy:!0,unhealthyReason:void 0,recoveryTime:void 0,lastUsed:t,usedCount:(s.usedCount??0)+1}))??null}getCurrentOrNext(){return this.selectHealthyAccount()}markRateLimited(n,t){return this.patchAccount(n.id,(i)=>({...i,rateLimitResetTime:t}))}markUnhealthy(n,t,i){let r=Date.now();return this.patchAccount(n.id,(s)=>{if(Wr(t))return{...s,failCount:10,isHealthy:!1,unhealthyReason:t,recoveryTime:void 0,lastUsed:r};let f=s.failCount+1;return{...s,failCount:f,isHealthy:f<10,unhealthyReason:t,recoveryTime:f>=10?i??r+3600000:void 0,lastUsed:r}})}updateFromAuth(n,t){let i=Hr(t.refresh);for(let r=0;r<me;r+=1){let s=r===0?n:this.database.getById(n.id);if(!s||!this.isSameLogin(n,s)){this.reconcileFromDb();return}let f={...s,refreshToken:i.refreshToken,accessToken:t.access,expiresAt:t.expires};if(this.database.updateExistingAccounts([f])===1){let h={...f,generation:s.generation+1};return this.replaceAccount(h),Ds(h)}}this.reconcileFromDb();return}toAuthDetails(n){return R0(n)}isSelectable(n,t){if(Wr(n.unhealthyReason))return!1;if(n.rateLimitResetTime>t)return!1;if(n.isHealthy||Gr(n.unhealthyReason))return!0;return n.recoveryTime!==void 0&&n.recoveryTime<=t}isSameLogin(n,t){return t.refreshToken===n.refreshToken&&t.authMethod===n.authMethod&&t.clientId===n.clientId&&t.email===n.email&&t.startUrl===n.startUrl}selectCandidate(n){switch(this.strategy){case"sticky":{let i=n.find(({id:r})=>r===this.stickyId)??n[0];if(!i)throw RangeError("Candidate list cannot be empty");return this.stickyId=i.id,i}case"round-robin":{let t=n[this.roundRobinCursor%n.length];if(!t)throw RangeError("Candidate list cannot be empty");return this.roundRobinCursor+=1,t}case"lowest-usage":{let t=[...n].sort((i,r)=>(i.usedCount??0)-(r.usedCount??0)||(i.lastUsed??0)-(r.lastUsed??0)||i.id.localeCompare(r.id))[0];if(!t)throw RangeError("Candidate list cannot be empty");return t}default:return wg(this.strategy)}}patchAccount(n,t){for(let i=0;i<me;i+=1){let r=this.database.getById(n);if(!r){this.accounts=this.accounts.filter((f)=>f.id!==n);return}let s=t(r);if(this.database.updateExistingAccounts([s])===1){let f={...s,generation:r.generation+1};return this.replaceAccount(f),Ds(f)}}throw this.reconcileFromDb(),new Ze(n)}replaceAccount(n){let t=this.accounts.findIndex(({id:i})=>i===n.id);if(t===-1)this.accounts.push(n);else this.accounts[t]=n}}import{createHash as eg}from"crypto";function ft(n){return eg("sha256").update("kiro-provider-audit-v1\x00").update(n).digest("hex").slice(0,16)}function dn(n,t,i={}){let r=Object.fromEntries(Object.entries(i).filter((s)=>s[1]!==void 0));console.error(JSON.stringify({timestamp:new Date().toISOString(),level:n,event:t,...r}))}var Ou=k(Lu(),1);import{existsSync as pg,promises as $u}from"fs";import{join as n8}from"path";var t8={stale:15000,retries:0,realpath:!1},i8=15000,r8=25,s8=250;function f8(n){if(typeof n!=="object"||n===null||!("code"in n))return!1;return n.code==="ELOCKED"||n.code==="ENOENT"}function D0(n){return n.reason??new DOMException("The operation was aborted","AbortError")}function _8(n,t){if(t?.aborted)return Promise.reject(D0(t));return new Promise((i,r)=>{let s=setTimeout(()=>{t?.removeEventListener("abort",f),i()},n),f=()=>{clearTimeout(s),r(D0(t))};t?.addEventListener("abort",f,{once:!0})})}function h8(n,t){let i=t.replace(/[^A-Za-z0-9_-]/g,"");return n8(n,`.kiro-refresh-${i}.lock`)}async function c8(n,t){let i=Date.now()+i8,r=0;for(;;){if(t?.aborted)throw D0(t);try{return await Ou.default.lock(n,t8)}catch(s){let f=i-Date.now();if(!f8(s)||f<=0)throw s;let h=Math.min(r8*2**Math.min(r,4),s8,f),_=Math.max(1,Math.floor(h/2)),c=_+Math.floor(Math.random()*(h-_+1));r+=1,await _8(c,t)}}}async function Uu(n,t,i,r){let s=h8(n,t);if(await $u.mkdir(n,{recursive:!0}),!pg(s))await(await $u.open(s,"a")).close();let f=await c8(s,r);try{return await i()}finally{try{await f()}catch{}}}var Qu=k(F0(),1);import*as Wt from"net";import*as Qs from"tls";import K8 from"assert";import*as Yu from"net";import*as Fu from"http";import{Agent as V8}from"https";var Gt=Symbol("AgentBaseInternalState");class X0 extends Fu.Agent{constructor(n){super(n);this[Gt]={}}isSecureEndpoint(n){if(n){if(typeof n.secureEndpoint==="boolean")return n.secureEndpoint;if(typeof n.protocol==="string")return n.protocol==="https:"}let{stack:t}=Error();if(typeof t!=="string")return!1;return t.split(`
|
|
117
|
+
`).some((i)=>i.indexOf("(https.js:")!==-1||i.indexOf("node:https:")!==-1)}incrementSockets(n){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;if(!this.sockets[n])this.sockets[n]=[];let t=new Yu.Socket({writable:!1});return this.sockets[n].push(t),this.totalSocketCount++,t}decrementSockets(n,t){if(!this.sockets[n]||t===null)return;let i=this.sockets[n],r=i.indexOf(t);if(r!==-1){if(i.splice(r,1),this.totalSocketCount--,i.length===0)delete this.sockets[n]}}getName(n){if(this.isSecureEndpoint(n))return V8.prototype.getName.call(this,n);return super.getName(n)}createSocket(n,t,i){let r={...t,secureEndpoint:this.isSecureEndpoint(t)},s=this.getName(r),f=this.incrementSockets(s);Promise.resolve().then(()=>this.connect(n,r)).then((h)=>{if(this.decrementSockets(s,f),typeof h.addRequest==="function")try{return h.addRequest(n,r)}catch(_){return i(_)}this[Gt].currentSocket=h,super.createSocket(n,t,i)},(h)=>{this.decrementSockets(s,f),i(h)})}createConnection(){let n=this[Gt].currentSocket;if(this[Gt].currentSocket=void 0,!n)throw Error("No socket was returned in the `connect()` function");return n}get defaultPort(){return this[Gt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(n){if(this[Gt])this[Gt].defaultPort=n}get protocol(){return this[Gt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(n){if(this[Gt])this[Gt].protocol=n}}import{URL as x8}from"url";var Xu=k(F0(),1),f_=Xu.default("https-proxy-agent:parse-proxy-response");function l0(n){return new Promise((t,i)=>{let r=0,s=[];function f(){let w=n.read();if(w)o(w);else n.once("readable",f)}function h(){n.removeListener("end",_),n.removeListener("error",c),n.removeListener("readable",f)}function _(){h(),f_("onend"),i(Error("Proxy connection ended before receiving CONNECT response"))}function c(w){h(),f_("onerror %o",w),i(w)}function o(w){s.push(w),r+=w.length;let e=Buffer.concat(s,r),u=e.indexOf(`\r
|
|
118
118
|
\r
|
|
119
|
-
`);if(
|
|
120
|
-
`),A=
|
|
121
|
-
`;if(i.username||i.password){let
|
|
122
|
-
`;let
|
|
123
|
-
`);let{connect:
|
|
124
|
-
`;if(
|
|
125
|
-
`;let
|
|
126
|
-
`);let{connect:u}=await h;if(n.emit("proxyConnect",u),this.emit("proxyConnect",u,n),u.statusCode===200){if(n.once("socket",Aw),t.secureEndpoint)return Fi("Upgrading socket connection to TLS"),Ur.connect({...Lh(Ke(t),"host","path","port"),socket:r});return r}throw r.destroy(),Error(`Proxy authentication failed with status ${u.statusCode} after retry`)}}br.protocols=["http","https"];function Aw(n){setImmediate(()=>{n.resume()})}function Lh(n,...t){let i={},s;for(s in n)if(!t.includes(s))i[s]=n[s];return i}function $s(n){return n.proxy_url||void 0}function dw(n){return n===void 0?{}:{proxy:n}}var v6=Li.options;function Rw(n){return v6.includes(n)}function Oh(n){if(!n||!Rw(n))return"us-east-1";return n}function $r(n,t){let i=n.replace("{{region}}",t);try{return new URL(i),i}catch{throw Error(`Invalid URL generated: ${i}`)}}function Ew(n){if(!n)return;let t=n.split(":");if(t.length<6)return;if(t[0]!=="arn")return;let i=t[3];if(typeof i!=="string"||!i)return;return Rw(i)?i:void 0}var Rn={REFRESH_URL:"https://prod.{{region}}.auth.desktop.kiro.dev/refreshToken",REFRESH_IDC_URL:"https://oidc.{{region}}.amazonaws.com/token",BASE_URL:"https://q.{{region}}.amazonaws.com/generateAssistantResponse",USAGE_LIMITS_URL:"https://q.{{region}}.amazonaws.com/getUsageLimits",DEFAULT_REGION:"us-east-1",AXIOS_TIMEOUT:120000,USER_AGENT:"KiroIDE",SDK_VERSION:"3.738.0",SDK_VERSION_USAGE:"3.0.0",CHAT_TRIGGER_TYPE_MANUAL:"MANUAL",ORIGIN_AI_EDITOR:"AI_EDITOR"},Lr={"claude-haiku-4-5":"claude-haiku-4.5","claude-haiku-4-5-thinking":"claude-haiku-4.5","claude-sonnet-4":"claude-sonnet-4","claude-sonnet-4-5":"claude-sonnet-4.5","claude-sonnet-4-5-thinking":"claude-sonnet-4.5","claude-sonnet-4-5-1m":"claude-sonnet-4.5-1m","claude-sonnet-4-5-1m-thinking":"claude-sonnet-4.5-1m","claude-sonnet-4-6":"claude-sonnet-4.6","claude-sonnet-4-6-thinking":"claude-sonnet-4.6","claude-sonnet-4-6-1m":"claude-sonnet-4.6-1m","claude-sonnet-4-6-1m-thinking":"claude-sonnet-4.6-1m","claude-sonnet-5":"claude-sonnet-5","claude-sonnet-5-thinking":"claude-sonnet-5","claude-opus-4-5":"claude-opus-4.5","claude-opus-4-5-thinking":"claude-opus-4.5","claude-opus-4-6":"claude-opus-4.6","claude-opus-4-6-thinking":"claude-opus-4.6","claude-opus-4-6-1m":"claude-opus-4.6-1m","claude-opus-4-6-1m-thinking":"claude-opus-4.6-1m","claude-opus-4-7":"claude-opus-4.7","claude-opus-4-7-thinking":"claude-opus-4.7","claude-opus-4-8":"claude-opus-4.8","claude-opus-4-8-thinking":"claude-opus-4.8",auto:"auto","deepseek-3.2":"deepseek-3.2","glm-5":"glm-5","minimax-m2.5":"minimax-m2.5","minimax-m2.1":"minimax-m2.1","qwen3-coder-next":"qwen3-coder-next","gpt-5.6-sol":"gpt-5.6-sol","gpt-5.6-terra":"gpt-5.6-terra","gpt-5.6-luna":"gpt-5.6-luna","claude-3-7-sonnet":"CLAUDE_3_7_SONNET_20250219_V1_0","nova-swe":"AGI_NOVA_SWE_V1_5","gpt-oss-120b":"OPENAI_GPT_OSS_120B_1_0","minimax-m2":"MINIMAX_MINIMAX_M2","kimi-k2-thinking":"MOONSHOT_KIMI_K2_THINKING"},yw=Object.keys(Lr),Sx=new Set(Object.keys(Lr).filter((n)=>n.includes("-1m")));var Z6=200000,p6={auto:200000,"claude-haiku-4-5":200000,"claude-sonnet-4":200000,"claude-sonnet-4-5":200000,"claude-sonnet-4-5-1m":1e6,"claude-sonnet-4-6":1e6,"claude-sonnet-4-6-1m":1e6,"claude-sonnet-5":1e6,"claude-opus-4-5":200000,"claude-opus-4-6":1e6,"claude-opus-4-6-1m":1e6,"claude-opus-4-7":1e6,"claude-opus-4-8":1e6,"deepseek-3.2":128000,"glm-5":200000,"minimax-m2.5":200000,"minimax-m2.1":200000,"qwen3-coder-next":256000,"gpt-5.6-sol":272000,"gpt-5.6-terra":272000,"gpt-5.6-luna":272000};function D(n){return p6[n]??Z6}var Or={ENDPOINT:"https://prod.{{region}}.auth.desktop.kiro.dev",SSO_OIDC_ENDPOINT:"https://oidc.{{region}}.amazonaws.com",BUILDER_ID_START_URL:"https://view.awsapps.com/start",USER_INFO_URL:"https://view.awsapps.com/api/user/info",SCOPES:["codewhisperer:completions","codewhisperer:analysis","codewhisperer:conversations","codewhisperer:transformations","codewhisperer:taskassist"]};class ti extends Error{code;originalError;constructor(n,t,i){super(n);this.name="KiroTokenRefreshError",this.code=t,this.originalError=i}}function Bh(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function ke(n,t,i){let s=n[t];if(typeof s==="string"&&s)return s;let r=n[i];return typeof r==="string"&&r?r:void 0}function ng(n,t,i){let s=n[t];if(typeof s==="number")return s;let r=n[i];return typeof r==="number"?r:void 0}function tg(n,t){let i;try{i=JSON.parse(n)}catch{return{message:n,code:`HTTP_${t}`}}if(!Bh(i))return{message:n,code:`HTTP_${t}`};let s=ke(i,"message","error_description")??n,r=ke(i,"__type","error")??`HTTP_${t}`;return{message:s,code:r}}function Tw(n){let t=n.userInfo;if(!Bh(t))return;let i=t.email;return typeof i==="string"?i:void 0}async function qe(n,t,i){let s=ds(n.refresh),r=n.authMethod==="idc",e=r?n.oidcRegion??n.region:n.region,f=$r(r?Rn.REFRESH_IDC_URL:Rn.REFRESH_URL,e);if(r&&(!s.clientId||!s.clientSecret))throw new ti("Missing creds","MISSING_CREDENTIALS");let o=r?{refreshToken:s.refreshToken,clientId:s.clientId,clientSecret:s.clientSecret,grantType:"refresh_token"}:{refreshToken:s.refreshToken},h=r?`aws-sdk-js/${Rn.SDK_VERSION} ua/2.1 os/other lang/js md/browser#unknown_unknown api/sso-oidc#${Rn.SDK_VERSION} m/E ${Rn.USER_AGENT}`:`aws-sdk-js/3.0.0 ${Rn.USER_AGENT}-0.1.0 os/macos lang/js md/nodejs/18.0.0`;try{let u=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","amz-sdk-request":"attempt=1; max=1","x-amzn-kiro-agent-mode":"vibe","user-agent":h,Connection:"close"},body:JSON.stringify(o),...t?{signal:t}:{},...dw(i)});if(!u.ok){let l=tg(await u.text(),u.status);throw new ti(`Refresh failed: ${l.message}`,l.code)}let c=await u.json();if(!Bh(c))throw new ti("No access token","INVALID_RESPONSE");let _=ke(c,"access_token","accessToken");if(!_)throw new ti("No access token","INVALID_RESPONSE");let w={refreshToken:ke(c,"refresh_token","refreshToken")??s.refreshToken,authMethod:n.authMethod,...s.clientId?{clientId:s.clientId}:{},...s.clientSecret?{clientSecret:s.clientSecret}:{}};return{refresh:Le(w),access:_,expires:Date.now()+(ng(c,"expires_in","expiresIn")??3600)*1000,authMethod:n.authMethod,region:n.region,...n.oidcRegion?{oidcRegion:n.oidcRegion}:{},...n.profileArn?{profileArn:n.profileArn}:{},...n.clientId?{clientId:n.clientId}:{},...n.clientSecret?{clientSecret:n.clientSecret}:{},...n.email||Tw(c)?{email:n.email??Tw(c)}:{}}}catch(u){if(u instanceof ti)throw u;if(u instanceof Error&&u.name==="AbortError")throw u;throw new ti(`Token refresh failed: ${u instanceof Error?u.message:"Unknown error"}`,"NETWORK_ERROR",u instanceof Error?u:void 0)}}class ii extends Error{accountId;constructor(n){super(`Account ${n} is no longer available`);this.accountId=n;this.name="AccountUnavailableError"}}class Nh{accountManager;tokenExpiryBufferMs;proxyUrl;inFlight=new Map;constructor(n,t,i){this.accountManager=n;this.tokenExpiryBufferMs=t;this.proxyUrl=i}async refreshIfNeeded(n,t,i){if(!dr(t,this.tokenExpiryBufferMs)){let s=this.accountManager.getAccounts().find(({id:r})=>r===n.id);if(!s)throw new ii(n.id);return s}return this.startOrJoinRefresh(n,t,i)}async forceRefresh(n,t){return this.startOrJoinRefresh(n,this.accountManager.toAuthDetails(n),t)}startOrJoinRefresh(n,t,i){if(!("generation"in n)||typeof n.generation!=="number")throw new ii(n.id);let s={...n,generation:n.generation},r=`${s.id}:${s.generation}`,e=this.inFlight.get(r);if(e)return e;let f=this.runRefresh(s,t,i).finally(()=>{if(this.inFlight.get(r)===f)this.inFlight.delete(r)});return this.inFlight.set(r,f),f}async runRefresh(n,t,i){let s=await qe(t,i,this.proxyUrl),r=this.accountManager.updateFromAuth(n,s);if(!r)throw new ii(n.id);return r}}function Ls(n){return{...n}}function ig(n){throw TypeError(`Unsupported account selection strategy: ${String(n)}`)}function sg(n,t){return n.refreshToken===t.refreshToken&&n.accessToken===t.accessToken&&n.expiresAt===t.expiresAt&&n.authMethod===t.authMethod&&n.clientId===t.clientId&&n.clientSecret===t.clientSecret&&n.profileArn===t.profileArn&&n.email===t.email&&n.startUrl===t.startUrl}class Gh{store;strategy;accounts=[];stickyId;roundRobinCursor=0;constructor(n,t){this.store=n;this.strategy=t;this.reconcileFromDb()}reconcileFromDb(){if(this.accounts=this.store.getAccounts(),this.stickyId&&!this.accounts.some(({id:n})=>n===this.stickyId))this.stickyId=void 0;return this.accounts.map(Ls)}selectHealthyAccount(n){for(let t=0;t<2;t+=1){let i=Date.now(),s=this.accounts.filter((f)=>this.isSelectable(f,i)).sort((f,o)=>f.id.localeCompare(o.id));if(s.length===0)return null;let r=s.find(({id:f})=>f===n)??this.selectCandidate(s),e=this.store.recordSelection(r.id,i);if(e)return this.publishLatest(e),Ls(e);this.reconcileFromDb()}return null}getAccountCount(){return this.accounts.length}toAuthDetails(n){return rh(n)}markRateLimited(n,t){let i=this.store.markRateLimited(n.id,t);if(i)this.publishLatest(i);else this.reconcileFromDb();return i===void 0?void 0:Ls(i)}markUnhealthy(n,t,i){let s=this.store.markUnhealthy(n.id,t,Es(t),i,Date.now());if(s)this.publishLatest(s);else this.reconcileFromDb();return s===void 0?void 0:Ls(s)}publishLatest(n){let t=this.accounts.findIndex(({id:i})=>i===n.id);if(t===-1)this.accounts.push(Ls(n));else this.accounts[t]=Ls(n)}isSelectable(n,t){if(Es(n.unhealthyReason))return!1;if(n.rateLimitResetTime>t)return!1;if(n.isHealthy||Rs(n.unhealthyReason))return!0;return n.recoveryTime!==void 0&&n.recoveryTime<=t}selectCandidate(n){switch(this.strategy){case"sticky":{let i=n.find(({id:s})=>s===this.stickyId)??n[0];if(!i)throw RangeError("Candidate list cannot be empty");return this.stickyId=i.id,i}case"round-robin":{let t=n[this.roundRobinCursor%n.length];if(!t)throw RangeError("Candidate list cannot be empty");return this.roundRobinCursor+=1,t}case"lowest-usage":{let t=[...n].sort((i,s)=>(i.usedCount??0)-(s.usedCount??0)||(i.lastUsed??0)-(s.lastUsed??0)||i.id.localeCompare(s.id))[0];if(!t)throw RangeError("Candidate list cannot be empty");return t}default:return ig(this.strategy)}}}class Hh{accountManager;store;tokenExpiryBufferMs;proxyUrl;inFlight=new Map;lockDirectory;constructor(n,t,i,s,r=h0(t.path)){this.accountManager=n;this.store=t;this.tokenExpiryBufferMs=i;this.proxyUrl=s;this.lockDirectory=r}async refreshIfNeeded(n,t,i){let s=this.store.getById(n.id);if(!s)throw new ii(n.id);if(this.accountManager.publishLatest(s),!dr(this.accountManager.toAuthDetails(s),this.tokenExpiryBufferMs))return s;return this.startOrJoinRefresh(n,!1,i)}async forceRefresh(n,t){return this.startOrJoinRefresh(n,!0,t)}startOrJoinRefresh(n,t,i){let s=this.inFlight.get(n.id);if(s)return s;let r=this.runLockedRefresh(n,t,i).finally(()=>{if(this.inFlight.get(n.id)===r)this.inFlight.delete(n.id)});return this.inFlight.set(n.id,r),r}async runLockedRefresh(n,t,i){return nw(this.lockDirectory,n.id,async()=>{let s=this.store.getById(n.id);if(!s)throw new ii(n.id);let r=this.accountManager.toAuthDetails(s);if(t&&!sg(n,s)||!t&&!dr(r,this.tokenExpiryBufferMs))return this.accountManager.publishLatest(s),s;try{let e=await qe(r,i,this.proxyUrl),f=ds(e.refresh),o={...s,refreshToken:f.refreshToken,accessToken:e.access,expiresAt:e.expires,lastUsed:Date.now(),isHealthy:!0,failCount:0,unhealthyReason:void 0,recoveryTime:void 0,...e.email?{email:e.email}:{},...f.clientId?{clientId:f.clientId}:{},...f.clientSecret?{clientSecret:f.clientSecret}:{}},h=this.store.persistRefreshedAccount(s,o);if(!h)throw new ii(n.id);return this.accountManager.publishLatest(h),h}catch(e){let f=typeof e==="object"&&e!==null&&"code"in e?String(e.code):"",o=e instanceof Error?e.message:String(e),h=f?`${f}: ${o}`:o;if(Oe(h))this.accountManager.markUnhealthy(s,I0(h));throw e}},i)}}function rg(n){console.error("stream-cleanup: cleanup step failed",n)}function gw(n,t){try{n()}catch(i){let s=t??rg;try{s(i)}catch{}}}function Wn(...n){for(let t of n)gw(t)}function cn(n){let t,i=Promise.resolve().then(n).then(()=>{return},()=>{return}),s=new Promise((r)=>{t=setTimeout(r,500)});return Promise.race([i,s]).then(()=>{if(t!==void 0)clearTimeout(t)},()=>{if(t!==void 0)clearTimeout(t)})}import{Database as eg}from"bun:sqlite";import{chmodSync as og,existsSync as fg,mkdirSync as hg}from"fs";import{homedir as Sw}from"os";import{dirname as ug,join as Ph}from"path";function Wh(n,t){return{id:n.id,email:n.email,auth_method:n.authMethod,region:n.region,oidc_region:n.oidcRegion??null,client_id:n.clientId??null,client_secret:n.clientSecret??null,profile_arn:n.profileArn??null,start_url:n.startUrl??null,refresh_token:n.refreshToken,access_token:n.accessToken,expires_at:n.expiresAt,rate_limit_reset:n.rateLimitResetTime,is_healthy:n.isHealthy?1:0,unhealthy_reason:n.unhealthyReason??null,recovery_time:n.recoveryTime??null,fail_count:n.failCount,last_used:n.lastUsed??0,used_count:n.usedCount??0,limit_count:n.limitCount??0,last_sync:n.lastSync??0,overage_count:n.overageCount??0,generation:t}}function Ve(n){return{id:n.id,email:n.email,authMethod:n.auth_method,region:n.region,oidcRegion:n.oidc_region??void 0,clientId:n.client_id??void 0,clientSecret:n.client_secret??void 0,profileArn:n.profile_arn??void 0,startUrl:n.start_url??void 0,refreshToken:n.refresh_token,accessToken:n.access_token,expiresAt:n.expires_at,rateLimitResetTime:n.rate_limit_reset,isHealthy:n.is_healthy===1,unhealthyReason:n.unhealthy_reason??void 0,recoveryTime:n.recovery_time??void 0,failCount:n.fail_count,lastUsed:n.last_used,usedCount:n.used_count,limitCount:n.limit_count,lastSync:n.last_sync,overageCount:n.overage_count,generation:n.generation}}function Fh(n){return[n.id,n.email,n.auth_method,n.region??null,n.oidc_region??null,n.client_id??null,n.client_secret??null,n.profile_arn??null,n.start_url??null,n.refresh_token,n.access_token,n.expires_at,n.rate_limit_reset,n.is_healthy,n.unhealthy_reason??null,n.recovery_time??null,n.fail_count,n.last_used,n.used_count,n.limit_count,n.last_sync,n.overage_count,n.generation]}function Dh(n){return{keyHash:n.key_hash,accountId:n.account_id,conversationId:n.conversation_id,createdAt:n.created_at,lastSeen:n.last_seen,expiresAt:n.expires_at}}function cg(){let n=process.platform==="win32"?process.env.APPDATA??Ph(Sw(),"AppData","Roaming"):process.env.XDG_CONFIG_HOME??Ph(Sw(),".config");return Ph(n,"kiro-provider","accounts.db")}var si=cg();class Pi{db;path;constructor(n=si){if(this.path=n,n!==":memory:")hg(ug(n),{recursive:!0});this.db=new eg(n,{create:!0,strict:!0}),this.tightenPermissions(),this.db.run("PRAGMA busy_timeout = 5000"),this.db.run("PRAGMA journal_mode = WAL"),this.withImmediateTransaction(()=>{if(this.db.run(`
|
|
119
|
+
`);if(u===-1){f_("have not received end of HTTP headers yet..."),f();return}let y=e.slice(0,u).toString("ascii").split(`\r
|
|
120
|
+
`),A=y.shift();if(!A)return n.destroy(),i(Error("No header received from proxy CONNECT response"));let R=A.split(" "),M=+R[1],E=R.slice(2).join(" "),g={};for(let T of y){if(!T)continue;let S=T.indexOf(":");if(S===-1)return n.destroy(),i(Error(`Invalid header from proxy CONNECT response: "${T}"`));let L=T.slice(0,S).toLowerCase(),b=T.slice(S+1).trimStart(),I=g[L];if(typeof I==="string")g[L]=[I,b];else if(Array.isArray(I))I.push(b);else g[L]=b}f_("got proxy server response: %o %o",A,g),h(),t({connect:{statusCode:M,statusText:E,headers:g},buffered:e})}n.on("error",c),n.on("end",_),f()})}function lu(){return async({response:n,scheme:t})=>{if(t.toLowerCase()!=="negotiate")throw Error(`Expected Negotiate scheme but got "${t}"`);let i;try{i=await import("kerberos")}catch{throw Error('The "kerberos" package is required for Negotiate proxy authentication. Install it with: npm install kerberos')}let r=n.headers["proxy-authenticate"]||"",s=Array.isArray(r)?r[0]:r,f=typeof s==="string"&&s.includes(" ")?s.split(" ").slice(1).join(" "):void 0,_=await(await i.initializeClient("HTTP@proxy",{mechOID:i.GSS_MECH_OID_SPNEGO})).step(f||"");if(!_)throw Error("Kerberos client.step() returned no token");return{headers:{"Proxy-Authorization":`Negotiate ${_}`}}}}var ki=Qu.default("https-proxy-agent"),__=(n)=>{if(n.servername===void 0&&n.host&&!Wt.isIP(n.host))return{...n,servername:n.host};return n};class zs extends X0{constructor(n,t){super(t);if(this.options={path:void 0},this.proxy=typeof n==="string"?new x8(n):n,this.proxyHeaders=t?.headers??{},ki("Creating new HttpsProxyAgent instance: %o",this.proxy.href),t?.negotiate)this.onProxyAuth=lu();else if(t?.onProxyAuth)this.onProxyAuth=t.onProxyAuth;let i=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),r=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...t?J0(t,"headers","onProxyAuth","negotiate"):null,host:i,port:r}}async connect(n,t){let{proxy:i}=this;if(!t.host)throw TypeError('No "host" provided');let r;if(i.protocol==="https:")ki("Creating `tls.Socket`: %o",this.connectOpts),r=Qs.connect(__(this.connectOpts));else ki("Creating `net.Socket`: %o",this.connectOpts),r=Wt.connect(this.connectOpts);let s=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},f=Wt.isIPv6(t.host)?`[${t.host}]`:t.host,h=`CONNECT ${f}:${t.port} HTTP/1.1\r
|
|
121
|
+
`;if(i.username||i.password){let e=`${decodeURIComponent(i.username)}:${decodeURIComponent(i.password)}`;s["Proxy-Authorization"]=`Basic ${Buffer.from(e).toString("base64")}`}if(s.Host=`${f}:${t.port}`,!s["Proxy-Connection"])s["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let e of Object.keys(s))h+=`${e}: ${s[e]}\r
|
|
122
|
+
`;let _=l0(r);r.write(`${h}\r
|
|
123
|
+
`);let{connect:c,buffered:o}=await _;if(n.emit("proxyConnect",c),this.emit("proxyConnect",c,n),n.emit("proxy",{proxy:this.proxy.href,socket:r}),c.statusCode===200){if(n.once("socket",Ju),t.secureEndpoint)return ki("Upgrading socket connection to TLS"),Qs.connect({...J0(__(t),"host","path","port"),socket:r});return r}if(c.statusCode===407&&this.onProxyAuth){ki("Got 407 response, invoking onProxyAuth callback"),r.destroy();let e=c.headers["proxy-authenticate"]||"",u=Array.isArray(e)?e[0].split(/\s/)[0]:e.split(/\s/)[0],y=await this.onProxyAuth({response:c,scheme:u});return this._connectWithAuth(n,t,y.headers)}r.destroy();let w=new Wt.Socket({writable:!1});return w.readable=!0,n.once("socket",(e)=>{ki("Replaying proxy buffer for failed request"),K8(e.listenerCount("data")>0),e.push(o),e.push(null)}),w}async _connectWithAuth(n,t,i){let{proxy:r}=this,s;if(r.protocol==="https:")s=Qs.connect(__(this.connectOpts));else s=Wt.connect(this.connectOpts);let f=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},h=Wt.isIPv6(t.host)?`[${t.host}]`:t.host,_=`CONNECT ${h}:${t.port} HTTP/1.1\r
|
|
124
|
+
`;if(r.username||r.password){let w=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;f["Proxy-Authorization"]=`Basic ${Buffer.from(w).toString("base64")}`}if(Object.assign(f,i),f.Host=`${h}:${t.port}`,!f["Proxy-Connection"])f["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let w of Object.keys(f))_+=`${w}: ${f[w]}\r
|
|
125
|
+
`;let c=l0(s);s.write(`${_}\r
|
|
126
|
+
`);let{connect:o}=await c;if(n.emit("proxyConnect",o),this.emit("proxyConnect",o,n),o.statusCode===200){if(n.once("socket",Ju),t.secureEndpoint)return ki("Upgrading socket connection to TLS"),Qs.connect({...J0(__(t),"host","path","port"),socket:s});return s}throw s.destroy(),Error(`Proxy authentication failed with status ${o.statusCode} after retry`)}}zs.protocols=["http","https"];function Ju(n){setImmediate(()=>{n.resume()})}function J0(n,...t){let i={},r;for(r in n)if(!t.includes(r))i[r]=n[r];return i}function Qr(n){return n.proxy_url||void 0}function zu(n){return n===void 0?{}:{proxy:n}}var j8=Qi.options;function Cu(n){return j8.includes(n)}function Q0(n){if(!n||!Cu(n))return"us-east-1";return n}function Cs(n,t){let i=n.replace("{{region}}",t);try{return new URL(i),i}catch{throw Error(`Invalid URL generated: ${i}`)}}function Vu(n){if(!n)return;let t=n.split(":");if(t.length<6)return;if(t[0]!=="arn")return;let i=t[3];if(typeof i!=="string"||!i)return;return Cu(i)?i:void 0}var Hn={REFRESH_URL:"https://prod.{{region}}.auth.desktop.kiro.dev/refreshToken",REFRESH_IDC_URL:"https://oidc.{{region}}.amazonaws.com/token",BASE_URL:"https://q.{{region}}.amazonaws.com/generateAssistantResponse",USAGE_LIMITS_URL:"https://q.{{region}}.amazonaws.com/getUsageLimits",DEFAULT_REGION:"us-east-1",AXIOS_TIMEOUT:120000,USER_AGENT:"KiroIDE",SDK_VERSION:"3.738.0",SDK_VERSION_USAGE:"3.0.0",CHAT_TRIGGER_TYPE_MANUAL:"MANUAL",ORIGIN_AI_EDITOR:"AI_EDITOR"},Vs={"claude-haiku-4-5":"claude-haiku-4.5","claude-haiku-4-5-thinking":"claude-haiku-4.5","claude-sonnet-4":"claude-sonnet-4","claude-sonnet-4-5":"claude-sonnet-4.5","claude-sonnet-4-5-thinking":"claude-sonnet-4.5","claude-sonnet-4-5-1m":"claude-sonnet-4.5-1m","claude-sonnet-4-5-1m-thinking":"claude-sonnet-4.5-1m","claude-sonnet-4-6":"claude-sonnet-4.6","claude-sonnet-4-6-thinking":"claude-sonnet-4.6","claude-sonnet-4-6-1m":"claude-sonnet-4.6-1m","claude-sonnet-4-6-1m-thinking":"claude-sonnet-4.6-1m","claude-sonnet-5":"claude-sonnet-5","claude-sonnet-5-thinking":"claude-sonnet-5","claude-opus-4-5":"claude-opus-4.5","claude-opus-4-5-thinking":"claude-opus-4.5","claude-opus-4-6":"claude-opus-4.6","claude-opus-4-6-thinking":"claude-opus-4.6","claude-opus-4-6-1m":"claude-opus-4.6-1m","claude-opus-4-6-1m-thinking":"claude-opus-4.6-1m","claude-opus-4-7":"claude-opus-4.7","claude-opus-4-7-thinking":"claude-opus-4.7","claude-opus-4-8":"claude-opus-4.8","claude-opus-4-8-thinking":"claude-opus-4.8",auto:"auto","deepseek-3.2":"deepseek-3.2","glm-5":"glm-5","minimax-m2.5":"minimax-m2.5","minimax-m2.1":"minimax-m2.1","qwen3-coder-next":"qwen3-coder-next","gpt-5.6-sol":"gpt-5.6-sol","gpt-5.6-terra":"gpt-5.6-terra","gpt-5.6-luna":"gpt-5.6-luna","claude-3-7-sonnet":"CLAUDE_3_7_SONNET_20250219_V1_0","nova-swe":"AGI_NOVA_SWE_V1_5","gpt-oss-120b":"OPENAI_GPT_OSS_120B_1_0","minimax-m2":"MINIMAX_MINIMAX_M2","kimi-k2-thinking":"MOONSHOT_KIMI_K2_THINKING"},Ku=Object.keys(Vs),rj=new Set(Object.keys(Vs).filter((n)=>n.includes("-1m")));var k8=200000,q8={auto:200000,"claude-haiku-4-5":200000,"claude-sonnet-4":200000,"claude-sonnet-4-5":200000,"claude-sonnet-4-5-1m":1e6,"claude-sonnet-4-6":1e6,"claude-sonnet-4-6-1m":1e6,"claude-sonnet-5":1e6,"claude-opus-4-5":200000,"claude-opus-4-6":1e6,"claude-opus-4-6-1m":1e6,"claude-opus-4-7":1e6,"claude-opus-4-8":1e6,"deepseek-3.2":128000,"glm-5":200000,"minimax-m2.5":200000,"minimax-m2.1":200000,"qwen3-coder-next":256000,"gpt-5.6-sol":272000,"gpt-5.6-terra":272000,"gpt-5.6-luna":272000};function l(n){return q8[n]??k8}var Ks={ENDPOINT:"https://prod.{{region}}.auth.desktop.kiro.dev",SSO_OIDC_ENDPOINT:"https://oidc.{{region}}.amazonaws.com",BUILDER_ID_START_URL:"https://view.awsapps.com/start",USER_INFO_URL:"https://view.awsapps.com/api/user/info",SCOPES:["codewhisperer:completions","codewhisperer:analysis","codewhisperer:conversations","codewhisperer:transformations","codewhisperer:taskassist"]};class Ai extends Error{code;originalError;constructor(n,t,i){super(n);this.name="KiroTokenRefreshError",this.code=t,this.originalError=i}}function z0(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function h_(n,t,i){let r=n[t];if(typeof r==="string"&&r)return r;let s=n[i];return typeof s==="string"&&s?s:void 0}function m8(n,t,i){let r=n[t];if(typeof r==="number")return r;let s=n[i];return typeof s==="number"?s:void 0}function Z8(n,t){let i;try{i=JSON.parse(n)}catch{return{message:n,code:`HTTP_${t}`}}if(!z0(i))return{message:n,code:`HTTP_${t}`};let r=h_(i,"message","error_description")??n,s=h_(i,"__type","error")??`HTTP_${t}`;return{message:r,code:s}}function xu(n){let t=n.userInfo;if(!z0(t))return;let i=t.email;return typeof i==="string"?i:void 0}async function c_(n,t,i){let r=Hr(n.refresh),s=n.authMethod==="idc",f=s?n.oidcRegion??n.region:n.region,h=Cs(s?Hn.REFRESH_IDC_URL:Hn.REFRESH_URL,f);if(s&&(!r.clientId||!r.clientSecret))throw new Ai("Missing creds","MISSING_CREDENTIALS");let _=s?{refreshToken:r.refreshToken,clientId:r.clientId,clientSecret:r.clientSecret,grantType:"refresh_token"}:{refreshToken:r.refreshToken},c=s?`aws-sdk-js/${Hn.SDK_VERSION} ua/2.1 os/other lang/js md/browser#unknown_unknown api/sso-oidc#${Hn.SDK_VERSION} m/E ${Hn.USER_AGENT}`:`aws-sdk-js/3.0.0 ${Hn.USER_AGENT}-0.1.0 os/macos lang/js md/nodejs/18.0.0`;try{let o=await fetch(h,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","amz-sdk-request":"attempt=1; max=1","x-amzn-kiro-agent-mode":"vibe","user-agent":c,Connection:"close"},body:JSON.stringify(_),...t?{signal:t}:{},...zu(i)});if(!o.ok){let y=Z8(await o.text(),o.status);throw new Ai(`Refresh failed: ${y.message}`,y.code)}let w=await o.json();if(!z0(w))throw new Ai("No access token","INVALID_RESPONSE");let e=h_(w,"access_token","accessToken");if(!e)throw new Ai("No access token","INVALID_RESPONSE");let u={refreshToken:h_(w,"refresh_token","refreshToken")??r.refreshToken,authMethod:n.authMethod,...r.clientId?{clientId:r.clientId}:{},...r.clientSecret?{clientSecret:r.clientSecret}:{}};return{refresh:Cf(u),access:e,expires:Date.now()+(m8(w,"expires_in","expiresIn")??3600)*1000,authMethod:n.authMethod,region:n.region,...n.oidcRegion?{oidcRegion:n.oidcRegion}:{},...n.profileArn?{profileArn:n.profileArn}:{},...n.clientId?{clientId:n.clientId}:{},...n.clientSecret?{clientSecret:n.clientSecret}:{},...n.email||xu(w)?{email:n.email??xu(w)}:{}}}catch(o){if(o instanceof Ai)throw o;if(o instanceof Error&&o.name==="AbortError")throw o;throw new Ai(`Token refresh failed: ${o instanceof Error?o.message:"Unknown error"}`,"NETWORK_ERROR",o instanceof Error?o:void 0)}}class Ri extends Error{accountId;constructor(n){super(`Account ${n} is no longer available`);this.accountId=n;this.name="AccountUnavailableError"}}class C0{accountManager;tokenExpiryBufferMs;proxyUrl;inFlight=new Map;constructor(n,t,i){this.accountManager=n;this.tokenExpiryBufferMs=t;this.proxyUrl=i}async refreshIfNeeded(n,t,i){if(!Ws(t,this.tokenExpiryBufferMs)){let r=this.accountManager.getAccounts().find(({id:s})=>s===n.id);if(!r)throw new Ri(n.id);return r}return this.startOrJoinRefresh(n,t,i)}async forceRefresh(n,t){return this.startOrJoinRefresh(n,this.accountManager.toAuthDetails(n),t)}startOrJoinRefresh(n,t,i){if(!("generation"in n)||typeof n.generation!=="number")throw new Ri(n.id);let r={...n,generation:n.generation},s=`${r.id}:${r.generation}`,f=this.inFlight.get(s);if(f)return f;let h=this.runRefresh(r,t,i).finally(()=>{if(this.inFlight.get(s)===h)this.inFlight.delete(s)});return this.inFlight.set(s,h),h}async runRefresh(n,t,i){let r=await c_(t,i,this.proxyUrl),s=this.accountManager.updateFromAuth(n,r);if(!s)throw new Ri(n.id);return s}}function zr(n){return{...n}}function a8(n){throw TypeError(`Unsupported account selection strategy: ${String(n)}`)}function v8(n,t){return n.refreshToken===t.refreshToken&&n.accessToken===t.accessToken&&n.expiresAt===t.expiresAt&&n.authMethod===t.authMethod&&n.clientId===t.clientId&&n.clientSecret===t.clientSecret&&n.profileArn===t.profileArn&&n.email===t.email&&n.startUrl===t.startUrl}class V0{store;strategy;accounts=[];stickyId;roundRobinCursor=0;constructor(n,t){this.store=n;this.strategy=t;this.reconcileFromDb()}reconcileFromDb(){if(this.accounts=this.store.getAccounts(),this.stickyId&&!this.accounts.some(({id:n})=>n===this.stickyId))this.stickyId=void 0;return this.accounts.map(zr)}selectHealthyAccount(n){for(let t=0;t<2;t+=1){let i=Date.now(),r=this.accounts.filter((h)=>this.isSelectable(h,i)).sort((h,_)=>h.id.localeCompare(_.id));if(r.length===0)return null;let s=r.find(({id:h})=>h===n)??this.selectCandidate(r),f=this.store.recordSelection(s.id,i);if(f)return this.publishLatest(f),zr(f);this.reconcileFromDb()}return null}getAccountCount(){return this.accounts.length}toAuthDetails(n){return R0(n)}markRateLimited(n,t){let i=this.store.markRateLimited(n.id,t);if(i)this.publishLatest(i);else this.reconcileFromDb();return i===void 0?void 0:zr(i)}markUnhealthy(n,t,i){let r=this.store.markUnhealthy(n.id,t,Wr(t),i,Date.now());if(r)this.publishLatest(r);else this.reconcileFromDb();return r===void 0?void 0:zr(r)}publishLatest(n){let t=this.accounts.findIndex(({id:i})=>i===n.id);if(t===-1)this.accounts.push(zr(n));else this.accounts[t]=zr(n)}isSelectable(n,t){if(Wr(n.unhealthyReason))return!1;if(n.rateLimitResetTime>t)return!1;if(n.isHealthy||Gr(n.unhealthyReason))return!0;return n.recoveryTime!==void 0&&n.recoveryTime<=t}selectCandidate(n){switch(this.strategy){case"sticky":{let i=n.find(({id:r})=>r===this.stickyId)??n[0];if(!i)throw RangeError("Candidate list cannot be empty");return this.stickyId=i.id,i}case"round-robin":{let t=n[this.roundRobinCursor%n.length];if(!t)throw RangeError("Candidate list cannot be empty");return this.roundRobinCursor+=1,t}case"lowest-usage":{let t=[...n].sort((i,r)=>(i.usedCount??0)-(r.usedCount??0)||(i.lastUsed??0)-(r.lastUsed??0)||i.id.localeCompare(r.id))[0];if(!t)throw RangeError("Candidate list cannot be empty");return t}default:return a8(this.strategy)}}}class K0{accountManager;store;tokenExpiryBufferMs;proxyUrl;inFlight=new Map;lockDirectory;constructor(n,t,i,r,s=We(t.path)){this.accountManager=n;this.store=t;this.tokenExpiryBufferMs=i;this.proxyUrl=r;this.lockDirectory=s}async refreshIfNeeded(n,t,i){let r=this.store.getById(n.id);if(!r)throw new Ri(n.id);if(this.accountManager.publishLatest(r),!Ws(this.accountManager.toAuthDetails(r),this.tokenExpiryBufferMs))return r;return this.startOrJoinRefresh(n,!1,i)}async forceRefresh(n,t){return this.startOrJoinRefresh(n,!0,t)}startOrJoinRefresh(n,t,i){let r=this.inFlight.get(n.id);if(r)return r;let s=this.runLockedRefresh(n,t,i).finally(()=>{if(this.inFlight.get(n.id)===s)this.inFlight.delete(n.id)});return this.inFlight.set(n.id,s),s}async runLockedRefresh(n,t,i){return Uu(this.lockDirectory,n.id,async()=>{let r=this.store.getById(n.id);if(!r)throw new Ri(n.id);let s=this.accountManager.toAuthDetails(r);if(t&&!v8(n,r)||!t&&!Ws(s,this.tokenExpiryBufferMs))return this.accountManager.publishLatest(r),r;try{let f=await c_(s,i,this.proxyUrl),h=Hr(f.refresh),_={...r,refreshToken:h.refreshToken,accessToken:f.access,expiresAt:f.expires,lastUsed:Date.now(),isHealthy:!0,failCount:0,unhealthyReason:void 0,recoveryTime:void 0,...f.email?{email:f.email}:{},...h.clientId?{clientId:h.clientId}:{},...h.clientSecret?{clientSecret:h.clientSecret}:{}},c=this.store.persistRefreshedAccount(r,_);if(!c)throw new Ri(n.id);return this.accountManager.publishLatest(c),c}catch(f){let h=typeof f==="object"&&f!==null&&"code"in f?String(f.code):"",_=f instanceof Error?f.message:String(f),c=h?`${h}: ${_}`:_;if(Vf(c))this.accountManager.markUnhealthy(r,qe(c));throw f}},i)}}var ju=500;function p8(n){dn("warn","stream_cleanup_failed",{error_type:n instanceof Error?n.name:typeof n})}function ku(n,t){try{n()}catch(i){let r=t??p8;try{r(i)}catch{}}}function zn(...n){for(let t of n)ku(t)}function An(n){let t,i=Promise.resolve().then(n).then(()=>{return},()=>{return}),r=new Promise((s)=>{t=setTimeout(s,ju)});return Promise.race([i,r]).then(()=>{if(t!==void 0)clearTimeout(t)},()=>{if(t!==void 0)clearTimeout(t)})}import{createCipheriv as y5,createDecipheriv as d5,createHash as A5,randomBytes as ny,timingSafeEqual as R5}from"crypto";import{createHash as n5,randomBytes as qu}from"crypto";import{chmodSync as au,closeSync as t5,existsSync as o_,fsyncSync as i5,mkdirSync as r5,openSync as s5,readFileSync as f5,renameSync as _5,unlinkSync as mu,writeFileSync as h5}from"fs";import{homedir as Zu}from"os";import{dirname as c5,join as x0}from"path";function o5(){let n=process.platform==="win32"?process.env.APPDATA??x0(Zu(),"AppData","Roaming"):process.env.XDG_CONFIG_HOME??x0(Zu(),".config");return x0(n,"kiro-provider","reasoning-replay-keys.json")}var w5=o5();function j0(n){return`rk_${n5("sha256").update(n).digest("hex").slice(0,16)}`}function e5(n,t){let i;try{i=Buffer.from(n,"base64url")}catch{throw TypeError(`${t} contains invalid base64url key material`)}if(i.byteLength!==32)throw TypeError(`${t} must decode to exactly 32 bytes for AES-256-GCM`);return Uint8Array.from(i)}function vu(n,t){let i=n.indexOf(":"),r=i>0?n.slice(0,i):void 0,s=i>0?n.slice(i+1):n,f=e5(s,t),h=r??j0(f);if(!/^[A-Za-z0-9._-]{1,128}$/.test(h))throw TypeError(`${t} contains an invalid key id`);return{id:h,key:f}}function q0(n,t,i){if(n.length===0)throw TypeError("Reasoning replay keyring is empty");let r=new Map;for(let f of n){if(r.has(f.id))throw TypeError(`Duplicate reasoning replay key id ${f.id}`);r.set(f.id,f)}let s=n[0];if(!s)throw TypeError("Reasoning replay keyring is empty");return i===void 0?{active:s,byId:r,source:t}:{active:s,byId:r,source:t,path:i}}function k0(n){let t;try{t=JSON.parse(f5(n,"utf8"))}catch(r){throw TypeError(`Unable to read reasoning replay key file ${n}`,{cause:r})}if(typeof t!=="object"||t===null||!("version"in t)||t.version!==1||!("keys"in t)||!Array.isArray(t.keys))throw TypeError(`Reasoning replay key file ${n} has an invalid format`);let i=t.keys.map((r,s)=>{if(typeof r!=="object"||r===null||!("id"in r)||typeof r.id!=="string"||!("key"in r)||typeof r.key!=="string")throw TypeError(`Reasoning replay key file ${n} has an invalid keys.${s}`);return vu(`${r.id}:${r.key}`,`${n} keys.${s}`)});if(process.platform!=="win32")au(n,384);return q0(i,"file",n)}function u5(n){r5(c5(n),{recursive:!0});let t=Uint8Array.from(qu(32)),i={version:1,keys:[{id:j0(t),key:Buffer.from(t).toString("base64url")}]},r=`${n}.tmp-${process.pid}-${qu(6).toString("hex")}`,s=s5(r,"wx",384);try{h5(s,`${JSON.stringify(i,null,2)}
|
|
127
|
+
`,"utf8"),i5(s)}finally{t5(s)}try{if(o_(n))return mu(r),k0(n);if(_5(r,n),process.platform!=="win32")au(n,384)}catch(f){if(o_(r))mu(r);if(o_(n))return k0(n);throw f}return q0([{id:j0(t),key:t}],"file",n)}function pu(n){if(n.reasoning_replay_keys.length>0)return q0(n.reasoning_replay_keys.map((i,r)=>vu(i,`KIRO_PROVIDER_REASONING_REPLAY_KEYS[${r}]`)),"environment");let t=n.reasoning_replay_key_path??w5;return o_(t)?k0(t):u5(t)}class Sn extends Error{code;retryable;name="ReasoningReplayError";constructor(n,t,i=!1){super(n);this.code=t;this.retryable=i}}function m0(n,...t){let i=A5("sha256").update(n).update("\x00");for(let r of t)i.update(r).update("\x00");return i.digest("hex")}function ty(n){return m0("kiro-provider-reasoning-token-v1",n)}function iy(n){return m0("kiro-provider-reasoning-fingerprint-v1",n)}function ry(n,t){return m0("kiro-provider-reasoning-chat-lookup-v1",n,t)}function sy(n,t){let i=Buffer.from(n),r=Buffer.from(t);return i.byteLength===r.byteLength&&R5(i,r)}function fy(n){return Buffer.from(JSON.stringify({version:1,tenantId:n.tenantId,model:n.model,accountId:n.accountId,conversationId:n.conversationId,fingerprintHash:n.fingerprintHash,expiresAt:n.expiresAt,keyId:n.keyId}),"utf8")}function M5(n){let t=JSON.parse(n);if(typeof t!=="object"||t===null||!("version"in t)||t.version!==1||!("outputFingerprint"in t)||typeof t.outputFingerprint!=="string")throw TypeError("Invalid reasoning replay envelope");let i="text"in t&&typeof t.text==="string"?t.text:void 0,r="signature"in t&&typeof t.signature==="string"?t.signature:void 0,s="redactedContent"in t&&typeof t.redactedContent==="string"?t.redactedContent:void 0;return{version:1,outputFingerprint:t.outputFingerprint,...i!==void 0?{text:i}:{},...r!==void 0?{signature:r}:{},...s!==void 0?{redactedContent:s}:{}}}function E5(n){if(n.redactedContent!==void 0){if(n.signature!==void 0||n.text!==void 0)throw new Sn("Reasoning replay contains ambiguous text and redacted payloads","reasoning_replay_ambiguous");return{kind:"redacted_content",bytes:Uint8Array.from(Buffer.from(n.redactedContent,"base64"))}}if(n.text!==void 0&&n.signature!==void 0)return{kind:"reasoning_text",text:n.text,signature:n.signature};throw new Sn("Reasoning replay does not contain complete signed upstream material","reasoning_replay_incomplete")}class Z0{#n;#t;#i;#r;constructor(n,t,i=pu(t)){this.#n=n,this.#t=i,this.#i=t.reasoning_replay_ttl_ms,this.#r=t.reasoning_replay_max_entries;let r=this.readiness().missingKeyIds;if(r.length>0)throw TypeError(`Reasoning replay keyring is missing active key ids: ${r.join(", ")}`)}readiness(){let n=this.#n.activeReasoningReplayKeyIds();return{writable:this.#n.checkWritable(),keyringAvailable:this.#t.byId.size>0,missingKeyIds:n.filter((t)=>!this.#t.byId.has(t))}}store(n,t,i=Date.now()){let r=n.redactedContent!==void 0,s=n.text.length>0&&n.signature!==void 0;if(!r&&!s)return;if(r&&(n.text.length>0||n.signature!==void 0))throw new Sn("Upstream returned both signed text and redacted reasoning payloads","reasoning_replay_ambiguous");let f=`kr1_${ny(32).toString("base64url")}`,h=ty(f),_=iy(t.outputFingerprint),c=i+this.#i,o=this.#t.active,w=ny(12),e={version:1,outputFingerprint:t.outputFingerprint,...s?{text:n.text,signature:n.signature}:{},...r?{redactedContent:Buffer.from(n.redactedContent).toString("base64")}:{}},u=y5("aes-256-gcm",o.key,w);u.setAAD(fy({...t,fingerprintHash:_,expiresAt:c,keyId:o.id}));let y=Buffer.concat([u.update(JSON.stringify(e),"utf8"),u.final()]),A=u.getAuthTag();return this.#n.insertReasoningReplay({tokenHash:h,chatLookupHash:s?ry(n.text,t.outputFingerprint):null,fingerprintHash:_,tenantId:t.tenantId,accountId:t.accountId,conversationId:t.conversationId,model:t.model,keyId:o.id,nonce:Uint8Array.from(w),ciphertext:Uint8Array.from(y),authTag:Uint8Array.from(A),createdAt:i,lastSeen:i,expiresAt:c},this.#r,i),f}resolveResponses(n,t,i){if(!n.startsWith("kr1_"))throw new Sn("Reasoning encrypted_content token has an invalid format","invalid_reasoning_replay");let r=t.now??Date.now(),s=ty(n),f=this.#n.getReasoningReplayRecord(s);if(!f)throw dn("info","reasoning_replay_miss",{lookup:"responses-token",token_hash:s.slice(0,16)}),new Sn("Reasoning replay token was not found","reasoning_replay_not_found");if(f.expiresAt<=r)throw dn("info","reasoning_replay_expired",{lookup:"responses-token",token_hash:s.slice(0,16)}),new Sn("Reasoning replay token has expired","reasoning_replay_expired");return this.resolveRecord(f,t,i,r)}resolveChat(n,t,i){let r=t.now??Date.now(),s=this.#n.findReasoningReplayByChatHash(t.tenantId,t.model,ry(n,t.outputFingerprint),r);if(t.accountId!==void 0)s=s.filter((h)=>h.accountId===t.accountId);if(t.conversationId!==void 0)s=s.filter((h)=>h.conversationId===t.conversationId);if(s.length===0)throw dn("info","reasoning_replay_miss",{lookup:"chat-hash",tenant_hash:ft(t.tenantId)}),new Sn("No exact signed reasoning record matches reasoning_content and assistant output","reasoning_replay_not_found");if(s.length!==1)throw new Sn("Reasoning replay lookup is ambiguous across accounts or conversations","reasoning_replay_ambiguous");let f=s[0];if(!f)throw new Sn("Reasoning replay lookup failed","reasoning_replay_not_found");return this.resolveRecord(f,t,i,r)}resolveRecord(n,t,i,r){let s=iy(t.outputFingerprint);if(!sy(n.tenantId,t.tenantId)||n.model!==t.model||!sy(n.fingerprintHash,s)||t.accountId!==void 0&&n.accountId!==t.accountId||t.conversationId!==void 0&&n.conversationId!==t.conversationId)throw new Sn("Reasoning replay context does not match tenant, model, account, conversation, or output","reasoning_replay_context_mismatch");let f=this.#t.byId.get(n.keyId);if(!f)throw new Sn("Reasoning replay decryption key is unavailable","reasoning_replay_key_unavailable");let h;try{let _=d5("aes-256-gcm",f.key,n.nonce);_.setAAD(fy({tenantId:n.tenantId,model:n.model,accountId:n.accountId,conversationId:n.conversationId,fingerprintHash:n.fingerprintHash,expiresAt:n.expiresAt,keyId:n.keyId})),_.setAuthTag(n.authTag);let c=Buffer.concat([_.update(n.ciphertext),_.final()]).toString("utf8");h=M5(c)}catch(_){if(_ instanceof Sn)throw _;throw new Sn("Reasoning replay authentication or decryption failed","reasoning_replay_decryption_failed")}if(h.outputFingerprint!==t.outputFingerprint)throw new Sn("Reasoning replay output fingerprint does not match","reasoning_replay_context_mismatch");return this.#n.touchReasoningReplay(n.tokenHash,r),dn("info","reasoning_replay_hit",{key_id:n.keyId,account_hash:ft(n.accountId),conversation_hash:ft(n.conversationId),model:n.model}),{accountId:n.accountId,conversationId:n.conversationId,replay:{insertBeforeMessage:i,content:E5(h)}}}}import{Database as T5}from"bun:sqlite";import{chmodSync as g5,existsSync as S5,mkdirSync as L5}from"fs";import{homedir as _y}from"os";import{dirname as $5,join as p0}from"path";function a0(n,t){return{id:n.id,email:n.email,auth_method:n.authMethod,region:n.region,oidc_region:n.oidcRegion??null,client_id:n.clientId??null,client_secret:n.clientSecret??null,profile_arn:n.profileArn??null,start_url:n.startUrl??null,refresh_token:n.refreshToken,access_token:n.accessToken,expires_at:n.expiresAt,rate_limit_reset:n.rateLimitResetTime,is_healthy:n.isHealthy?1:0,unhealthy_reason:n.unhealthyReason??null,recovery_time:n.recoveryTime??null,fail_count:n.failCount,last_used:n.lastUsed??0,used_count:n.usedCount??0,limit_count:n.limitCount??0,last_sync:n.lastSync??0,overage_count:n.overageCount??0,generation:t}}function w_(n){return{id:n.id,email:n.email,authMethod:n.auth_method,region:n.region,oidcRegion:n.oidc_region??void 0,clientId:n.client_id??void 0,clientSecret:n.client_secret??void 0,profileArn:n.profile_arn??void 0,startUrl:n.start_url??void 0,refreshToken:n.refresh_token,accessToken:n.access_token,expiresAt:n.expires_at,rateLimitResetTime:n.rate_limit_reset,isHealthy:n.is_healthy===1,unhealthyReason:n.unhealthy_reason??void 0,recoveryTime:n.recovery_time??void 0,failCount:n.fail_count,lastUsed:n.last_used,usedCount:n.used_count,limitCount:n.limit_count,lastSync:n.last_sync,overageCount:n.overage_count,generation:n.generation}}function v0(n){return[n.id,n.email,n.auth_method,n.region??null,n.oidc_region??null,n.client_id??null,n.client_secret??null,n.profile_arn??null,n.start_url??null,n.refresh_token,n.access_token,n.expires_at,n.rate_limit_reset,n.is_healthy,n.unhealthy_reason??null,n.recovery_time??null,n.fail_count,n.last_used,n.used_count,n.limit_count,n.last_sync,n.overage_count,n.generation]}function nc(n){return{keyHash:n.key_hash,accountId:n.account_id,conversationId:n.conversation_id,createdAt:n.created_at,lastSeen:n.last_seen,expiresAt:n.expires_at}}function tc(n){return{tokenHash:n.token_hash,chatLookupHash:n.chat_lookup_hash,fingerprintHash:n.fingerprint_hash,tenantId:n.tenant_id,accountId:n.account_id,conversationId:n.conversation_id,model:n.model,keyId:n.key_id,nonce:n.nonce,ciphertext:n.ciphertext,authTag:n.auth_tag,createdAt:n.created_at,lastSeen:n.last_seen,expiresAt:n.expires_at}}function O5(){let n=process.platform==="win32"?process.env.APPDATA??p0(_y(),"AppData","Roaming"):process.env.XDG_CONFIG_HOME??p0(_y(),".config");return p0(n,"kiro-provider","accounts.db")}var Mi=O5();class qi{db;path;constructor(n=Mi){if(this.path=n,n!==":memory:")L5($5(n),{recursive:!0});this.db=new T5(n,{create:!0,strict:!0}),this.tightenPermissions(),this.db.run("PRAGMA busy_timeout = 5000"),this.db.run("PRAGMA journal_mode = WAL"),this.withImmediateTransaction(()=>{if(this.db.run(`
|
|
127
128
|
CREATE TABLE IF NOT EXISTS accounts (
|
|
128
129
|
id TEXT PRIMARY KEY, email TEXT NOT NULL, auth_method TEXT NOT NULL,
|
|
129
130
|
region TEXT NOT NULL, oidc_region TEXT, client_id TEXT, client_secret TEXT,
|
|
@@ -156,24 +157,50 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
156
157
|
`),this.db.run(`
|
|
157
158
|
CREATE INDEX IF NOT EXISTS session_affinity_last_seen_idx
|
|
158
159
|
ON session_affinity (last_seen)
|
|
160
|
+
`),this.db.run(`
|
|
161
|
+
CREATE TABLE IF NOT EXISTS reasoning_replay (
|
|
162
|
+
token_hash TEXT PRIMARY KEY,
|
|
163
|
+
chat_lookup_hash TEXT,
|
|
164
|
+
fingerprint_hash TEXT NOT NULL,
|
|
165
|
+
tenant_id TEXT NOT NULL,
|
|
166
|
+
account_id TEXT NOT NULL,
|
|
167
|
+
conversation_id TEXT NOT NULL,
|
|
168
|
+
model TEXT NOT NULL,
|
|
169
|
+
key_id TEXT NOT NULL,
|
|
170
|
+
nonce BLOB NOT NULL,
|
|
171
|
+
ciphertext BLOB NOT NULL,
|
|
172
|
+
auth_tag BLOB NOT NULL,
|
|
173
|
+
created_at INTEGER NOT NULL,
|
|
174
|
+
last_seen INTEGER NOT NULL,
|
|
175
|
+
expires_at INTEGER NOT NULL
|
|
176
|
+
)
|
|
177
|
+
`),this.db.run(`
|
|
178
|
+
CREATE INDEX IF NOT EXISTS reasoning_replay_lookup_idx
|
|
179
|
+
ON reasoning_replay (tenant_id, model, chat_lookup_hash, expires_at)
|
|
180
|
+
`),this.db.run(`
|
|
181
|
+
CREATE INDEX IF NOT EXISTS reasoning_replay_lru_idx
|
|
182
|
+
ON reasoning_replay (last_seen, token_hash)
|
|
183
|
+
`),this.db.run(`
|
|
184
|
+
CREATE INDEX IF NOT EXISTS reasoning_replay_key_id_idx
|
|
185
|
+
ON reasoning_replay (key_id, expires_at)
|
|
159
186
|
`)})}getAccounts(){return this.db.query(`
|
|
160
187
|
SELECT accounts.* FROM accounts
|
|
161
188
|
WHERE NOT EXISTS (
|
|
162
189
|
SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
|
|
163
190
|
)
|
|
164
|
-
`).all().map(
|
|
191
|
+
`).all().map(w_)}getById(n){let t=this.db.query(`
|
|
165
192
|
SELECT accounts.* FROM accounts
|
|
166
193
|
WHERE accounts.id = ? AND NOT EXISTS (
|
|
167
194
|
SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
|
|
168
195
|
)
|
|
169
|
-
`).get(n);return t===null?void 0:
|
|
196
|
+
`).get(n);return t===null?void 0:w_(t)}insertAccount(n){return this.withImmediateTransaction(()=>{let t=this.db.query("SELECT generation FROM accounts WHERE id = ?").get(n.id),i=this.db.query("SELECT last_generation FROM removed_accounts WHERE id = ?").get(n.id),r=Math.max(t?.generation??0,i?.last_generation??0)+1,s=a0(n,r);return this.db.query(`
|
|
170
197
|
INSERT OR REPLACE INTO accounts (
|
|
171
198
|
id, email, auth_method, region, oidc_region, client_id, client_secret,
|
|
172
199
|
profile_arn, start_url, refresh_token, access_token, expires_at,
|
|
173
200
|
rate_limit_reset, is_healthy, unhealthy_reason, recovery_time, fail_count,
|
|
174
201
|
last_used, used_count, limit_count, last_sync, overage_count, generation
|
|
175
202
|
) VALUES (${Array.from({length:23},()=>"?").join(", ")})
|
|
176
|
-
`).run(...
|
|
203
|
+
`).run(...v0(s)),this.clearRemovedAccountInternal(n.id),w_(s)})}updateExistingAccounts(n){return this.withImmediateTransaction(()=>{let t=0,i=this.db.query(`
|
|
177
204
|
UPDATE accounts SET
|
|
178
205
|
email = ?, auth_method = ?, region = ?, oidc_region = ?, client_id = ?,
|
|
179
206
|
client_secret = ?, profile_arn = ?, start_url = ?, refresh_token = ?,
|
|
@@ -184,21 +211,21 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
184
211
|
WHERE id = ? AND generation = ? AND NOT EXISTS (
|
|
185
212
|
SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
|
|
186
213
|
)
|
|
187
|
-
`);for(let
|
|
214
|
+
`);for(let r of n){let s=v0(a0(r,r.generation)),f=s.shift();s.pop(),t+=i.run(...s,f??r.id,r.generation).changes}return t})}removeAccount(n){this.withImmediateTransaction(()=>{let t=this.db.query("SELECT generation FROM accounts WHERE id = ?").get(n),i=this.db.query("SELECT last_generation FROM removed_accounts WHERE id = ?").get(n),r=t?.generation??i?.last_generation??0;this.db.query("DELETE FROM accounts WHERE id = ?").run(n),this.db.query("DELETE FROM session_affinity WHERE account_id = ?").run(n),this.db.query("DELETE FROM reasoning_replay WHERE account_id = ?").run(n),this.db.query(`
|
|
188
215
|
INSERT OR REPLACE INTO removed_accounts (id, removed_at, last_generation)
|
|
189
216
|
VALUES (?, ?, ?)
|
|
190
|
-
`).run(n,Date.now(),
|
|
217
|
+
`).run(n,Date.now(),r)})}clearRemovedAccount(n){this.withImmediateTransaction(()=>this.clearRemovedAccountInternal(n))}getSessionAffinity(n,t=Date.now()){let i=this.db.query(`
|
|
191
218
|
SELECT * FROM session_affinity
|
|
192
219
|
WHERE key_hash = ? AND expires_at > ?
|
|
193
|
-
`).get(n,t);return i===null?void 0:
|
|
220
|
+
`).get(n,t);return i===null?void 0:nc(i)}claimSessionAffinity(n,t,i,r,s,f){return this.withImmediateTransaction(()=>{this.db.query("DELETE FROM session_affinity WHERE key_hash = ? AND expires_at <= ?").run(n,r),this.db.query(`
|
|
194
221
|
INSERT OR IGNORE INTO session_affinity (
|
|
195
222
|
key_hash, account_id, conversation_id, created_at, last_seen, expires_at
|
|
196
223
|
) VALUES (?, ?, ?, ?, ?, ?)
|
|
197
|
-
`).run(n,t,i,
|
|
224
|
+
`).run(n,t,i,r,r,r+s),this.db.query(`
|
|
198
225
|
UPDATE session_affinity
|
|
199
226
|
SET last_seen = ?, expires_at = ?
|
|
200
227
|
WHERE key_hash = ?
|
|
201
|
-
`).run(
|
|
228
|
+
`).run(r,r+s,n),this.pruneSessionAffinitiesInternal(r,f,n);let h=this.selectSessionAffinity(n);if(h===void 0)throw TypeError("Session affinity claim did not persist");return nc(h)})}rebindSessionAffinity(n,t,i,r,s,f){return this.withImmediateTransaction(()=>{this.db.query(`
|
|
202
229
|
INSERT INTO session_affinity (
|
|
203
230
|
key_hash, account_id, conversation_id, created_at, last_seen, expires_at
|
|
204
231
|
) VALUES (?, ?, ?, ?, ?, ?)
|
|
@@ -208,7 +235,23 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
208
235
|
created_at = excluded.created_at,
|
|
209
236
|
last_seen = excluded.last_seen,
|
|
210
237
|
expires_at = excluded.expires_at
|
|
211
|
-
`).run(n,t,i,
|
|
238
|
+
`).run(n,t,i,r,r,r+s),this.pruneSessionAffinitiesInternal(r,f,n);let h=this.selectSessionAffinity(n);if(h===void 0)throw TypeError("Session affinity rebind did not persist");return nc(h)})}pruneSessionAffinities(n=Date.now(),t=1e4){return this.withImmediateTransaction(()=>this.pruneSessionAffinitiesInternal(n,t))}insertReasoningReplay(n,t,i=Date.now()){this.withImmediateTransaction(()=>{this.db.query("DELETE FROM reasoning_replay WHERE expires_at <= ?").run(i),this.db.query(`
|
|
239
|
+
INSERT INTO reasoning_replay (
|
|
240
|
+
token_hash, chat_lookup_hash, fingerprint_hash, tenant_id, account_id,
|
|
241
|
+
conversation_id, model, key_id, nonce, ciphertext, auth_tag,
|
|
242
|
+
created_at, last_seen, expires_at
|
|
243
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
244
|
+
`).run(n.tokenHash,n.chatLookupHash,n.fingerprintHash,n.tenantId,n.accountId,n.conversationId,n.model,n.keyId,n.nonce,n.ciphertext,n.authTag,n.createdAt,n.lastSeen,n.expiresAt),this.pruneReasoningReplayInternal(i,t,n.tokenHash)})}getReasoningReplayByTokenHash(n,t=Date.now()){let i=this.db.query(`
|
|
245
|
+
SELECT * FROM reasoning_replay
|
|
246
|
+
WHERE token_hash = ? AND expires_at > ?
|
|
247
|
+
`).get(n,t);return i===null?void 0:tc(i)}getReasoningReplayRecord(n){let t=this.db.query("SELECT * FROM reasoning_replay WHERE token_hash = ?").get(n);return t===null?void 0:tc(t)}findReasoningReplayByChatHash(n,t,i,r=Date.now()){return this.db.query(`
|
|
248
|
+
SELECT * FROM reasoning_replay
|
|
249
|
+
WHERE tenant_id = ? AND model = ? AND chat_lookup_hash = ? AND expires_at > ?
|
|
250
|
+
ORDER BY last_seen DESC, token_hash ASC
|
|
251
|
+
`).all(n,t,i,r).map(tc)}touchReasoningReplay(n,t=Date.now()){this.db.query("UPDATE reasoning_replay SET last_seen = ? WHERE token_hash = ?").run(t,n)}activeReasoningReplayKeyIds(n=Date.now()){return this.db.query(`
|
|
252
|
+
SELECT DISTINCT key_id FROM reasoning_replay
|
|
253
|
+
WHERE expires_at > ? ORDER BY key_id ASC
|
|
254
|
+
`).all(n).map((t)=>t.key_id)}pruneReasoningReplay(n=Date.now(),t=1e4){return this.withImmediateTransaction(()=>this.pruneReasoningReplayInternal(n,t))}checkWritable(){try{return this.withImmediateTransaction(()=>{this.db.run("UPDATE reasoning_replay SET last_seen = last_seen WHERE 0")}),!0}catch{return!1}}close(){this.db.close()}clearRemovedAccountInternal(n){this.db.query("DELETE FROM removed_accounts WHERE id = ?").run(n)}selectSessionAffinity(n){let t=this.db.query("SELECT * FROM session_affinity WHERE key_hash = ?").get(n);return t===null?void 0:t}pruneSessionAffinitiesInternal(n,t,i){let r=this.db.query("DELETE FROM session_affinity WHERE expires_at <= ?").run(n).changes,s=this.db.query("SELECT COUNT(*) AS count FROM session_affinity").get(),f=Math.max(0,(s?.count??0)-t);if(f>0){let h=i?this.db.query(`
|
|
212
255
|
DELETE FROM session_affinity
|
|
213
256
|
WHERE key_hash IN (
|
|
214
257
|
SELECT key_hash FROM session_affinity
|
|
@@ -223,46 +266,49 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
223
266
|
ORDER BY last_seen ASC, key_hash ASC
|
|
224
267
|
LIMIT ?
|
|
225
268
|
)
|
|
226
|
-
`);
|
|
269
|
+
`);r+=(i?h.run(i,f):h.run(f)).changes}return r}pruneReasoningReplayInternal(n,t,i){let r=this.db.query("DELETE FROM reasoning_replay WHERE expires_at <= ?").run(n).changes,s=this.db.query("SELECT COUNT(*) AS count FROM reasoning_replay").get(),f=Math.max(0,(s?.count??0)-t);if(f<=0)return r;let h=i?this.db.query(`
|
|
270
|
+
DELETE FROM reasoning_replay
|
|
271
|
+
WHERE token_hash IN (
|
|
272
|
+
SELECT token_hash FROM reasoning_replay
|
|
273
|
+
WHERE token_hash != ?
|
|
274
|
+
ORDER BY last_seen ASC, token_hash ASC
|
|
275
|
+
LIMIT ?
|
|
276
|
+
)
|
|
277
|
+
`):this.db.query(`
|
|
278
|
+
DELETE FROM reasoning_replay
|
|
279
|
+
WHERE token_hash IN (
|
|
280
|
+
SELECT token_hash FROM reasoning_replay
|
|
281
|
+
ORDER BY last_seen ASC, token_hash ASC
|
|
282
|
+
LIMIT ?
|
|
283
|
+
)
|
|
284
|
+
`);return r+=(i?h.run(i,f):h.run(f)).changes,r}withImmediateTransaction(n){this.db.exec("BEGIN IMMEDIATE");try{let t=n();return this.db.exec("COMMIT"),t}catch(t){throw this.db.exec("ROLLBACK"),t}finally{this.tightenPermissions()}}tightenPermissions(){if(this.path===":memory:")return;for(let n of[this.path,`${this.path}-wal`,`${this.path}-shm`])if(S5(n))g5(n,384)}}import{randomUUID as U5}from"crypto";function Pn(n,t,i){return Response.json({type:"error",error:{type:i,message:t},request_id:`req_${U5()}`},{status:n})}function hy(n,t){return`event: error
|
|
227
285
|
data: ${JSON.stringify({type:"error",error:{type:t,message:n}})}
|
|
228
286
|
|
|
229
|
-
`}import{createHash as wg,timingSafeEqual as lg}from"crypto";function v(n,t,i,s){let r={message:t,type:i};if(s!==void 0)r.code=s;return new Response(JSON.stringify({error:r}),{status:n,headers:{"Content-Type":"application/json"}})}var Uw="Bearer ";function bw(n,t){let i=Buffer.from(n);for(let s of t){let r=Buffer.from(s);if(i.byteLength===r.byteLength&&lg(i,r))return s}return}function $w(n){return wg("sha256").update("kiro-provider-tenant-v1\x00").update(n).digest("hex")}function Yh(n,t,i=v){let s=n.headers.get("Authorization");if(s===null){let f=n.headers.get("x-api-key"),o=f===null?void 0:bw(f,t);if(o!==void 0)return{ok:!0,tenantId:$w(o)};return{ok:!1,response:i(401,"Missing Authorization or x-api-key header.","authentication_error","missing_api_key")}}if(!s.startsWith(Uw))return{ok:!1,response:i(401,"Authorization header must use the Bearer scheme.","authentication_error","invalid_api_key")};let r=s.slice(Uw.length),e=bw(r,t);if(e===void 0)return{ok:!1,response:i(401,"Incorrect API key provided.","authentication_error","invalid_api_key")};return{ok:!0,tenantId:$w(e)}}var wi=Q(ct(),1);var ne=Q(ct(),1);var te=Q(ct(),1);var Kt=Q(ct(),1);var jn=Q(ct(),1);var hn=Q(Yn(),1);var ps=Q(_i(),1),zE=Q(ri(),1);var Mc=Q($o(),1);var ie=Q(Jn(),1);var Zn=Q(Ji(),1);var un=Q(Zr(),1);var V=Q(Xt(),1);var Qs=Q(_i(),1);var zs=Q(Xt(),1);var Fd=async(n,t,i)=>{return{operation:zs.getSmithyContext(t).operation}};function qH(n){return{schemeId:"smithy.api#httpBearerAuth",propertiesExtractor:({profile:t,filepath:i,configFilepath:s,ignoreCache:r},e)=>({identityProperties:{profile:t,filepath:i,configFilepath:s,ignoreCache:r}})}}var Pd=(n)=>{let t=[];switch(n.operation){default:t.push(qH(n))}return t},Dd=(n)=>{let t=Qs.memoizeIdentityProvider(n.token,Qs.isIdentityExpired,Qs.doesIdentityRequireRefresh);return Object.assign(n,{authSchemePreference:zs.normalizeProvider(n.authSchemePreference??[]),token:t})};var Yd=(n)=>{return Object.assign(n,{useDualstackEndpoint:n.useDualstackEndpoint??!1,useFipsEndpoint:n.useFipsEndpoint??!1,defaultSigningName:"amazoncodewhispererstreamingservice"})},md={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};var Jd={name:"@aws/codewhisperer-streaming-client",description:"@aws/codewhisperer-streaming-client",version:"1.0.45",scripts:{build:"concurrently 'npm:build:cjs' 'npm:build:es' 'npm:build:types'","build:cjs":"tsc -p tsconfig.cjs.json","build:es":"tsc -p tsconfig.es.json","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4",clean:"premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo",prepack:"npm run clean && npm run build"},main:"./dist-cjs/index.js",types:"./dist-types/index.d.ts",module:"./dist-es/index.js",sideEffects:!1,dependencies:{tslib:"^2.6.2","@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"^3.974.7","@aws-sdk/middleware-host-header":"^3.972.10","@aws-sdk/middleware-logger":"^3.972.10","@aws-sdk/middleware-recursion-detection":"^3.972.11","@aws-sdk/middleware-user-agent":"^3.972.37","@aws-sdk/region-config-resolver":"^3.972.13","@aws-sdk/token-providers":"^3.1040.0","@aws-sdk/types":"^3.973.8","@aws-sdk/util-endpoints":"^3.996.8","@aws-sdk/util-user-agent-browser":"^3.972.10","@aws-sdk/util-user-agent-node":"^3.973.23","@smithy/config-resolver":"^4.4.17","@smithy/core":"^3.23.17","@smithy/eventstream-serde-browser":"^4.2.14","@smithy/eventstream-serde-config-resolver":"^4.3.14","@smithy/eventstream-serde-node":"^4.2.14","@smithy/fetch-http-handler":"^5.3.17","@smithy/hash-node":"^4.2.14","@smithy/invalid-dependency":"^4.2.14","@smithy/middleware-content-length":"^4.2.14","@smithy/middleware-endpoint":"^4.4.32","@smithy/middleware-retry":"^4.5.7","@smithy/middleware-serde":"^4.2.20","@smithy/middleware-stack":"^4.2.14","@smithy/node-config-provider":"^4.3.14","@smithy/node-http-handler":"^4.6.1","@smithy/protocol-http":"^5.3.14","@smithy/smithy-client":"^4.12.13","@smithy/types":"^4.14.1","@smithy/url-parser":"^4.2.14","@smithy/util-base64":"^4.3.2","@smithy/util-body-length-browser":"^4.2.2","@smithy/util-body-length-node":"^4.2.3","@smithy/util-defaults-mode-browser":"^4.3.49","@smithy/util-defaults-mode-node":"^4.2.54","@smithy/util-endpoints":"^3.4.2","@smithy/util-middleware":"^4.2.14","@smithy/util-retry":"^4.3.6","@smithy/util-utf8":"^4.2.2"},devDependencies:{"@tsconfig/node20":"20.1.8",concurrently:"7.0.0","downlevel-dts":"0.10.1",premove:"4.0.0",typescript:"~5.8.3","@types/node":"^20.14.8"},engines:{node:">=20.0.0"},typesVersions:{"<4.5":{"dist-types/*":["dist-types/ts3.4/*"]}},files:["dist-*/**"],browser:{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.browser"},"react-native":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.native"},license:"Apache-2.0"};var FE=Q(ct(),1),PE=Q(Oc(),1);var as=Q(Yn(),1);var zn=Q(Yn(),1);var U1=300000,xs="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var pR=async(n,t={},i)=>{let{SSOOIDCClient:s}=await Promise.resolve().then(() => Q(w_(),1)),r=(f)=>t.clientConfig?.[f]??t.parentClientConfig?.[f]??i?.[f];return new s(Object.assign({},t.clientConfig??{},{region:n??t.clientConfig?.region,logger:r("logger"),userAgentAppId:r("userAgentAppId")}))};var nE=async(n,t,i={},s)=>{let{CreateTokenCommand:r}=await Promise.resolve().then(() => Q(w_(),1));return(await pR(t,i,s)).send(new r({clientId:n.clientId,clientSecret:n.clientSecret,refreshToken:n.refreshToken,grantType:"refresh_token"}))};var tE=Q(Yn(),1);var l_=(n)=>{if(n.expiration&&n.expiration.getTime()<Date.now())throw new tE.TokenProviderError(`Token is expired. ${xs}`,!1)};var iE=Q(Yn(),1);var Mi=(n,t,i=!1)=>{if(typeof t>"u")throw new iE.TokenProviderError(`Value not present for '${n}' in SSO Token${i?". Cannot refresh":""}. ${xs}`,!1)};var sE=Q(Yn(),1);import{promises as EY}from"fs";var{writeFile:yY}=EY,rE=(n,t)=>{let i=sE.getSSOTokenFilepath(n),s=JSON.stringify(t,null,2);return yY(i,s)};var eE=new Date(0),oE=(n={})=>async({callerClientConfig:t}={})=>{n.logger?.debug("@aws-sdk/token-providers - fromSso");let i=await zn.parseKnownFiles(n),s=zn.getProfileName({profile:n.profile??t?.profile}),r=i[s];if(!r)throw new zn.TokenProviderError(`Profile '${s}' could not be found in shared credentials file.`,!1);else if(!r.sso_session)throw new zn.TokenProviderError(`Profile '${s}' is missing required property 'sso_session'.`);let e=r.sso_session,o=(await zn.loadSsoSessionData(n))[e];if(!o)throw new zn.TokenProviderError(`Sso session '${e}' could not be found in shared credentials file.`,!1);for(let A of["sso_start_url","sso_region"])if(!o[A])throw new zn.TokenProviderError(`Sso session '${e}' is missing required property '${A}'.`,!1);let{sso_start_url:h,sso_region:u}=o,c;try{c=await zn.getSSOTokenFromFile(e)}catch(A){throw new zn.TokenProviderError(`The SSO session token associated with profile=${s} was not found or is invalid. ${xs}`,!1)}Mi("accessToken",c.accessToken),Mi("expiresAt",c.expiresAt);let{accessToken:_,expiresAt:w}=c,l={token:_,expiration:new Date(w)};if(l.expiration.getTime()-Date.now()>U1)return l;if(Date.now()-eE.getTime()<30000)return l_(l),l;Mi("clientId",c.clientId,!0),Mi("clientSecret",c.clientSecret,!0),Mi("refreshToken",c.refreshToken,!0);try{eE.setTime(Date.now());let A=await nE(c,u,n,t);Mi("accessToken",A.accessToken),Mi("expiresIn",A.expiresIn);let d=new Date(Date.now()+A.expiresIn*1000);try{await rE(e,{...c,accessToken:A.accessToken,expiresAt:d.toISOString(),refreshToken:A.refreshToken})}catch(E){}return{token:A.accessToken,expiration:d}}catch(A){return l_(l),l}};var A_=(n={})=>as.memoize(as.chain(oE(n),async()=>{throw new as.TokenProviderError("Could not load token from any providers",!1)}),(t)=>t.expiration!==void 0&&t.expiration.getTime()-Date.now()<300000,(t)=>t.expiration!==void 0);var Gt=Q(ct(),1);var DE=Q(_i(),1);var Ef=Q($o(),1);var M_=Q(mn(),1);var kt=Q(Yn(),1);var Gf=Q(jo(),1);var d_=Q(mn(),1);var R_=Q(Yn(),1);var Sn=Q(Zr(),1);var GE=Q(o_(),1),HE=Q(_i(),1);var E_=Q(Jn(),1);var vs=Q(mn(),1);var Vi=Q(mn(),1);var Hn=Q(Ji(),1);var we="ref",ji=-1,yf=!0,fE="isSet",_E="PartitionResult",Tf="booleanEquals",y_="getAttr",hE={[we]:"Endpoint"},T_={[we]:_E},Zs={},uE=[{[we]:"Region"}],cE={conditions:[[fE,[hE]],[fE,uE],["aws.partition",uE,_E],[Tf,[{[we]:"UseFIPS"},yf]],[Tf,[{[we]:"UseDualStack"},yf]],[Tf,[{fn:y_,argv:[T_,"supportsDualStack"]},yf]],[Tf,[{fn:y_,argv:[T_,"supportsFIPS"]},yf]],["stringEquals",[{fn:y_,argv:[T_,"name"]},"aws-us-gov"]]],results:[[ji],[ji,"Invalid Configuration: FIPS and custom endpoint are not supported"],[ji,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[hE,Zs],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",Zs],[ji,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://amazoncodewhispererstreamingservice.{Region}.amazonaws.com",Zs],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dnsSuffix}",Zs],[ji,"FIPS is enabled but this partition does not support FIPS"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dualStackDnsSuffix}",Zs],[ji,"DualStack is enabled but this partition does not support DualStack"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dnsSuffix}",Zs],[ji,"Invalid Configuration: Missing Region"]]},TY=2,Qn=1e8,gY=new Int32Array([-1,1,-1,0,13,3,1,4,Qn+12,2,5,Qn+12,3,8,6,4,7,Qn+11,5,Qn+9,Qn+10,4,11,9,6,10,Qn+8,7,Qn+6,Qn+7,5,12,Qn+5,6,Qn+4,Qn+5,3,Qn+1,14,4,Qn+2,Qn+3]),wE=Hn.BinaryDecisionDiagram.from(gY,TY,cE.conditions,cE.results);var SY=new Hn.EndpointCache({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),lE=(n,t={})=>{return SY.get(n,()=>Hn.decideEndpoint(wE,{endpointParams:n,logger:t.logger}))};Hn.customEndpointFunctions.aws=jn.awsEndpointFunctions;var I_=Q(ri(),1);class Cn extends V.ServiceException{constructor(n){super(n);Object.setPrototypeOf(this,Cn.prototype)}}class gf extends Cn{name="AccessDeniedException";$fault="client";reason;constructor(n){super({name:"AccessDeniedException",$fault:"client",...n});Object.setPrototypeOf(this,gf.prototype),this.reason=n.reason}}class Sf extends Cn{name="ConflictException";$fault="client";reason;constructor(n){super({name:"ConflictException",$fault:"client",...n});Object.setPrototypeOf(this,Sf.prototype),this.reason=n.reason}}class If extends Cn{name="InternalServerException";$fault="server";$retryable={};reason;constructor(n){super({name:"InternalServerException",$fault:"server",...n});Object.setPrototypeOf(this,If.prototype),this.reason=n.reason}}class Uf extends Cn{name="ThrottlingException";$fault="client";$retryable={throttling:!0};reason;constructor(n){super({name:"ThrottlingException",$fault:"client",...n});Object.setPrototypeOf(this,Uf.prototype),this.reason=n.reason}}class bf extends Cn{name="ValidationException";$fault="client";reason;constructor(n){super({name:"ValidationException",$fault:"client",...n});Object.setPrototypeOf(this,bf.prototype),this.reason=n.reason}}class $f extends Cn{name="ResourceNotFoundException";$fault="client";constructor(n){super({name:"ResourceNotFoundException",$fault:"client",...n});Object.setPrototypeOf(this,$f.prototype)}}class Lf extends Cn{name="ServiceUnavailableException";$fault="server";constructor(n){super({name:"ServiceUnavailableException",$fault:"server",...n});Object.setPrototypeOf(this,Lf.prototype)}}class Of extends Cn{name="ServiceQuotaExceededException";$fault="client";reason;constructor(n){super({name:"ServiceQuotaExceededException",$fault:"client",...n});Object.setPrototypeOf(this,Of.prototype),this.reason=n.reason}}class Bf extends Cn{name="DryRunOperationException";$fault="client";responseCode;constructor(n){super({name:"DryRunOperationException",$fault:"client",...n});Object.setPrototypeOf(this,Bf.prototype),this.responseCode=n.responseCode}}var AE=I_.TypeRegistry.for("smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming"),IY=[-3,"smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming","CodeWhispererStreamingServiceException",0,[],[]];AE.registerError(IY,Cn);var Ht=I_.TypeRegistry.for("com.amazon.aws.codewhisperer"),UY=[-3,"com.amazon.aws.codewhisperer","AccessDeniedException",{["error"]:"client",["httpError"]:403},["message","reason"],[0,0],1];Ht.registerError(UY,gf);var bY=[-3,"com.amazon.aws.codewhisperer","ConflictException",{["error"]:"client",["httpError"]:409},["message","reason"],[0,0],1];Ht.registerError(bY,Sf);var $Y=[-3,"com.amazon.aws.codewhisperer","DryRunOperationException",{["error"]:"client"},["message","responseCode"],[0,[1,32]]];Ht.registerError($Y,Bf);var ME=[-3,"com.amazon.aws.codewhisperer","InternalServerException",{["error"]:"server",["httpError"]:500},["message","reason"],[0,0],1];Ht.registerError(ME,If);var LY=[-3,"com.amazon.aws.codewhisperer","ResourceNotFoundException",{["error"]:"client",["httpError"]:404},["message"],[0],1];Ht.registerError(LY,$f);var OY=[-3,"com.amazon.aws.codewhisperer","ServiceQuotaExceededException",{["error"]:"client",["httpError"]:402},["message","reason"],[0,0],1];Ht.registerError(OY,Of);var BY=[-3,"com.amazon.aws.codewhisperer","ServiceUnavailableException",{["error"]:"server",["httpError"]:503},["message"],[0],1];Ht.registerError(BY,Lf);var NY=[-3,"com.amazon.aws.codewhisperer","ThrottlingException",{["error"]:"client",["httpError"]:429},["message","reason"],[0,0],1];Ht.registerError(NY,Uf);var GY=[-3,"com.amazon.aws.codewhisperer","ValidationException",{["error"]:"client",["httpError"]:400},["message","reason"],[0,0],1];Ht.registerError(GY,bf);var dE=[AE,Ht];var U_=[0,"com.amazon.aws.codewhisperer","SensitiveDocument",8,15],Y=[0,"com.amazon.aws.codewhisperer","SensitiveString",8,0],HY=[0,"com.amazon.aws.codewhisperer","ToolDescription",8,0],Nf=[0,"com.amazon.aws.codewhisperer","ToolName",8,0],rn=[0,"com.amazon.aws.q","SensitiveString",8,0],WY=[3,"com.amazon.aws.codewhisperer","AdditionalContentEntry",0,["name","description","innerContext"],[[()=>Y,0],[()=>Y,0],[()=>Y,0]],2],FY=[3,"com.amazon.aws.codewhisperer","AppStudioState",0,["namespace","propertyName","propertyContext","propertyValue"],[[()=>Y,0],[()=>Y,0],[()=>Y,0],[()=>Y,0]],3],PY=[3,"com.amazon.aws.codewhisperer","AssistantResponseEvent",0,["content","modelId"],[[()=>Y,0],0],1],DY=[3,"com.amazon.aws.codewhisperer","AssistantResponseMessage",0,["content","messageId","supplementaryWebLinks","references","followupPrompt","toolUses","cachePoint","reasoningContent"],[[()=>Y,0],0,[()=>OE,0],()=>LE,[()=>RE,0],[()=>MJ,0],()=>b_,[()=>JJ,0]],1];var b_=[3,"com.amazon.aws.codewhisperer","CachePoint",0,["type"],[0],1],YY=[3,"com.amazon.aws.codewhisperer","CitationEvent",0,["target","citationLink","citationText"],[()=>HJ,[()=>Y,0],[()=>Y,0]],2],mY=[3,"com.amazon.aws.codewhisperer","ClientCacheConfig",0,["useClientCachingOnly"],[2]],JY=[3,"com.amazon.aws.codewhisperer","CodeDescription",0,["href"],[[()=>Y,0]],1],XY=[3,"com.amazon.aws.codewhisperer","CodeEvent",0,["content"],[[()=>Y,0]],1],zY=[3,"com.amazon.aws.codewhisperer","CodeReferenceEvent",0,["references"],[()=>LE]],QY=[3,"com.amazon.aws.codewhisperer","ConsoleState",0,["region","consoleUrl","serviceId","serviceConsolePage","serviceSubconsolePage","taskName","uxErrorMessage"],[0,[()=>Y,0],0,0,0,[()=>Y,0],[()=>Y,0]]],CY=[3,"com.amazon.aws.codewhisperer","ContextUsageEvent",0,["contextUsagePercentage"],[1]],xY=[3,"com.amazon.aws.codewhisperer","ConversationState",0,["currentMessage","chatTriggerType","conversationId","workspaceId","history","customizationArn","agentContinuationId","agentTaskType"],[[()=>BE,0],0,0,0,[()=>rJ,0],0,0,0],2],KY=[3,"com.amazon.aws.codewhisperer","DiagnosticLocation",0,["uri","range"],[[()=>Y,0],()=>$_],2],kY=[3,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformation",0,["location","message"],[[()=>KY,0],[()=>Y,0]],2],qY=[3,"com.amazon.aws.codewhisperer","DocumentBlock",0,["name","format","source"],[0,0,[()=>DJ,0]],3],VY=[3,"com.amazon.aws.codewhisperer","DocumentCitationEvent",0,["source","title","location","sourceContent"],[[()=>Y,0],[()=>Y,0],[()=>PJ,0],[()=>fJ,0]]],jY=[3,"com.amazon.aws.codewhisperer","DocumentCitationSearchResultSpan",0,["searchResultIndex","start","end"],[1,1,1]],aY=[3,"com.amazon.aws.codewhisperer","DocumentCitationSourceContent",0,["text"],[[()=>Y,0]]],g_=[3,"com.amazon.aws.codewhisperer","DocumentCitationSpan",0,["documentIndex","start","end"],[1,1,1]],vY=[3,"com.amazon.aws.codewhisperer","DocumentCitationWebLocation",0,["url","domain"],[[()=>Y,0],[()=>Y,0]]],ZY=[3,"com.amazon.aws.codewhisperer","DocumentSymbol",0,["name","type","source"],[0,0,0],2],pY=[3,"com.amazon.aws.codewhisperer","DryRunSucceedEvent",0,[],[]],nm=[3,"com.amazon.aws.codewhisperer","EditorState",0,["document","cursorState","relevantDocuments","useRelevantDocuments","workspaceFolders"],[[()=>TE,0],()=>WJ,[()=>cJ,0],2,[()=>dJ,0]]],tm=[3,"com.amazon.aws.codewhisperer","EnvironmentVariable",0,["key","value"],[[()=>Y,0],[()=>Y,0]]],im=[3,"com.amazon.aws.codewhisperer","EnvState",0,["operatingSystem","currentWorkingDirectory","environmentVariables","timezoneOffset"],[0,[()=>Y,0],[()=>hJ,0],1]],RE=[3,"com.amazon.aws.codewhisperer","FollowupPrompt",0,["content","userIntent"],[[()=>Y,0],0],1],sm=[3,"com.amazon.aws.codewhisperer","FollowupPromptEvent",0,["followupPrompt"],[[()=>RE,0]]],rm=[3,"com.amazon.aws.codewhisperer","GitState",0,["status"],[[()=>Y,0]]],em=[3,"com.amazon.aws.codewhisperer","ImageBlock",0,["format","source"],[0,[()=>YJ,0]],2],om=[3,"com.amazon.aws.codewhisperer","IntentsEvent",0,["intents"],[[()=>BJ,0]]],fm=[3,"com.amazon.aws.codewhisperer","InvalidStateEvent",0,["reason","message"],[0,0],2],hm=[3,"com.amazon.aws.codewhisperer","MessageMetadataEvent",0,["conversationId","utteranceId"],[0,0]],um=[3,"com.amazon.aws.codewhisperer","MetadataEvent",0,["tokenUsage"],[()=>Bm]],cm=[3,"com.amazon.aws.codewhisperer","MeteringEvent",0,["usage","unit","unitPlural"],[1,0,0]],S_=[3,"com.amazon.aws.codewhisperer","Position",0,["line","character"],[1,1],2],EE=[3,"com.amazon.aws.codewhisperer","ProgrammingLanguage",0,["languageName"],[0],1],$_=[3,"com.amazon.aws.codewhisperer","Range",0,["start","end"],[()=>S_,()=>S_],2],_m=[3,"com.amazon.aws.codewhisperer","ReasoningContentEvent",8,["text","redactedContent","signature"],[[()=>Y,0],21,[()=>Y,0]]],wm=[3,"com.amazon.aws.codewhisperer","ReasoningText",8,["text","signature"],[[()=>Y,0],[()=>Y,0]],1],lm=[3,"com.amazon.aws.codewhisperer","Reference",0,["licenseName","repository","url","recommendationContentSpan"],[0,0,0,()=>yE]],Am=[3,"com.amazon.aws.codewhisperer","RelevantTextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols","type"],[[()=>Y,0],()=>EE,[()=>Y,0],()=>$E,0],1],Mm=[3,"com.amazon.aws.codewhisperer","RuntimeDiagnostic",0,["source","severity","message"],[[()=>Y,0],0,[()=>Y,0]],3],dm=[3,"com.amazon.aws.codewhisperer","ShellHistoryEntry",0,["command","directory","exitCode","stdout","stderr"],[[()=>Y,0],[()=>Y,0],1,[()=>Y,0],[()=>Y,0]],1],Rm=[3,"com.amazon.aws.codewhisperer","ShellState",0,["shellName","shellHistory"],[0,[()=>_J,0]],1],yE=[3,"com.amazon.aws.codewhisperer","Span",0,["start","end"],[1,1]],Em=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLink",0,["url","title","snippet"],[[()=>Y,0],[()=>Y,0],[()=>Y,0]],2],ym=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLinksEvent",0,["supplementaryWebLinks"],[[()=>OE,0]]],TE=[3,"com.amazon.aws.codewhisperer","TextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols"],[[()=>Y,0],()=>EE,[()=>Y,0],()=>$E],1],Tm=[3,"com.amazon.aws.codewhisperer","TextDocumentDiagnostic",0,["document","range","source","severity","message","code","codeDescription","tags","relatedInformation","data"],[[()=>TE,0],()=>$_,[()=>Y,0],0,[()=>Y,0],[()=>Y,0],[()=>JY,0],64,[()=>eJ,0],[()=>Y,0]],5],gm=[3,"com.amazon.aws.codewhisperer","ToolInputSchema",0,["json"],[[()=>U_,0]]],gE=[3,"com.amazon.aws.codewhisperer","ToolResult",0,["toolUseId","content","status","toolName"],[0,[()=>wJ,0],0,[()=>Nf,0]],2],Sm=[3,"com.amazon.aws.codewhisperer","ToolResultEvent",0,["toolResult"],[[()=>gE,0]]],Im=[3,"com.amazon.aws.codewhisperer","ToolSpecification",0,["inputSchema","name","description"],[[()=>gm,0],[()=>Nf,0],[()=>HY,0]],2],Um=[3,"com.amazon.aws.codewhisperer","ToolUse",0,["toolUseId","name","input"],[0,[()=>Nf,0],[()=>U_,0]],3],bm=[3,"com.amazon.aws.codewhisperer","ToolUseEvent",0,["toolUseId","name","input","stop"],[0,[()=>Nf,0],[()=>Y,0],2],2];var $m=[3,"com.amazon.aws.codewhisperer","UserInputMessage",0,["content","userInputMessageContext","userIntent","origin","images","documents","modelId","cachePoint","clientCacheConfig"],[[()=>Y,0],[()=>Lm,0],0,0,[()=>uJ,0],[()=>oJ,0],0,()=>b_,()=>mY],1],Lm=[3,"com.amazon.aws.codewhisperer","UserInputMessageContext",0,["editorState","shellState","gitState","envState","appStudioContext","diagnostic","consoleState","userSettings","additionalContext","toolResults","tools"],[[()=>nm,0],[()=>Rm,0],[()=>rm,0],[()=>im,0],[()=>FY,0],[()=>FJ,0],[()=>QY,0],()=>Om,[()=>sJ,0],[()=>lJ,0],[()=>AJ,0]]],Om=[3,"com.amazon.aws.codewhisperer","UserSettings",0,["hasConsentedToCrossRegionCalls"],[2]];var Bm=[3,"com.amazon.aws.codewhisperer.internal","TokenUsage",0,["uncachedInputTokens","outputTokens","totalTokens","cacheReadInputTokens","cacheWriteInputTokens","contextUsagePercentage","normalizedTokenUsage"],[1,1,1,1,1,1,1],3];var Nm=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseRequest",0,["conversationState","profileArn","agentMode","additionalModelRequestFields"],[[()=>xY,0],0,[0,{["httpHeader"]:"x-amzn-kiro-agent-mode"}],15],1],Gm=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseResponse",0,["conversationId","generateAssistantResponseResponse"],[[0,{["httpHeader"]:"x-amzn-codewhisperer-conversation-id"}],[()=>GJ,16]],2];var Hm=[3,"com.amazon.aws.q","InteractionComponentsEvent",0,["interactionComponentEntries"],[[()=>TJ,0]],1],L_=[3,"com.amazon.aws.q.interactioncomponents","Action",0,["webLink","moduleLink"],[[()=>iJ,0],[()=>Qm,0]]],O_=[3,"com.amazon.aws.q.interactioncomponents","Alert",0,["type","content"],[0,[()=>RJ,0]],2],Wm=[3,"com.amazon.aws.q.interactioncomponents","AlertComponent",0,["text"],[[()=>le,0]]],Fm=[3,"com.amazon.aws.q.interactioncomponents","Clarification",0,["questions","dismissible"],[[()=>yJ,0],2],1],Pm=[3,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOption",0,["label","value"],[[()=>rn,0],[()=>rn,0]],2],Dm=[3,"com.amazon.aws.q.interactioncomponents","ClarificationQuestion",0,["question","options","allowCustom","skippable"],[[()=>rn,0],[()=>EJ,0],2,2],2],Ym=[3,"com.amazon.aws.q.interactioncomponents","CloudWatchTroubleshootingLink",0,["label","investigationPayload","defaultText"],[[()=>rn,0],[()=>rn,0],[()=>rn,0]],2],SE=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdate",0,["transition"],[[()=>mm,0]]],mm=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdateTransition",0,["currentState","nextState"],[[()=>rn,0],[()=>rn,0]],2],Jm=[3,"com.amazon.aws.q.interactioncomponents","InlineArtifact",0,["dsl","summary","title","artifactLabel"],[[()=>rn,0],[()=>rn,0],[()=>rn,0],[()=>rn,0]],4],Xm=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponent",0,["text","alert","infrastructureUpdate","progress","step","taskDetails","taskReference","suggestions","section","resource","resourceList","action","clarification","inlineArtifact"],[[()=>le,0],[()=>O_,0],[()=>SE,0],[()=>IE,0],[()=>bE,0],[()=>pm,0],()=>tJ,[()=>Vm,0],[()=>xm,0],[()=>B_,0],[()=>UE,0],[()=>L_,0],[()=>Fm,0],[()=>Jm,0]]],zm=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntry",0,["interactionComponent","interactionComponentId"],[[()=>Xm,0],0],1],Qm=[3,"com.amazon.aws.q.interactioncomponents","ModuleLink",0,["cloudWatchTroubleshootingLink"],[[()=>Ym,0]]],IE=[3,"com.amazon.aws.q.interactioncomponents","Progress",0,["content"],[[()=>gJ,0]],1],Cm=[3,"com.amazon.aws.q.interactioncomponents","ProgressComponent",0,["step"],[[()=>bE,0]]],B_=[3,"com.amazon.aws.q.interactioncomponents","Resource",0,["title","link","description","type","ARN","resourceJsonString"],[[()=>rn,0],[()=>rn,0],[()=>rn,0],[()=>rn,0],[()=>rn,0],[()=>rn,0]],6],UE=[3,"com.amazon.aws.q.interactioncomponents","ResourceList",0,["items","action"],[[()=>SJ,0],[()=>L_,0]],1],xm=[3,"com.amazon.aws.q.interactioncomponents","Section",0,["title","content","action"],[[()=>rn,0],[()=>IJ,0],[()=>L_,0]],2],Km=[3,"com.amazon.aws.q.interactioncomponents","SectionComponent",0,["text","alert","resource","resourceList"],[[()=>le,0],[()=>O_,0],[()=>B_,0],[()=>UE,0]]],bE=[3,"com.amazon.aws.q.interactioncomponents","Step",0,["id","state","label","content"],[1,0,[()=>rn,0],[()=>UJ,0]],3],km=[3,"com.amazon.aws.q.interactioncomponents","StepComponent",0,["text"],[[()=>le,0]]],qm=[3,"com.amazon.aws.q.interactioncomponents","Suggestion",0,["value"],[[()=>rn,0]],1],Vm=[3,"com.amazon.aws.q.interactioncomponents","Suggestions",0,["items"],[[()=>bJ,0]],1],jm=[3,"com.amazon.aws.q.interactioncomponents","TaskAction",0,["label","payload","note","primary","disabled","confirmation"],[[()=>rn,0],[()=>NJ,0],[()=>vm,0],2,2,[()=>am,0]],2],am=[3,"com.amazon.aws.q.interactioncomponents","TaskActionConfirmation",0,["content"],[[()=>rn,0]]],vm=[3,"com.amazon.aws.q.interactioncomponents","TaskActionNote",0,["content","type"],[[()=>rn,0],0],1],Zm=[3,"com.amazon.aws.q.interactioncomponents","TaskComponent",0,["text","infrastructureUpdate","alert","progress"],[[()=>le,0],[()=>SE,0],[()=>O_,0],[()=>IE,0]]],pm=[3,"com.amazon.aws.q.interactioncomponents","TaskDetails",0,["overview","content","actions"],[[()=>nJ,0],[()=>LJ,0],[()=>$J,0]],2],nJ=[3,"com.amazon.aws.q.interactioncomponents","TaskOverview",0,["label","description"],[[()=>rn,0],[()=>rn,0]],2],tJ=[3,"com.amazon.aws.q.interactioncomponents","TaskReference",0,["taskId"],[0],1],le=[3,"com.amazon.aws.q.interactioncomponents","Text",0,["content"],[[()=>rn,0]],1],iJ=[3,"com.amazon.aws.q.interactioncomponents","WebLink",0,["label","url"],[[()=>rn,0],[()=>rn,0]],2];var sJ=[1,"com.amazon.aws.codewhisperer","AdditionalContentList",0,[()=>WY,0]],rJ=[1,"com.amazon.aws.codewhisperer","ChatHistory",0,[()=>BE,0]],eJ=[1,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformationList",0,[()=>kY,0]];var oJ=[1,"com.amazon.aws.codewhisperer","DocumentBlocks",0,[()=>qY,0]],fJ=[1,"com.amazon.aws.codewhisperer","DocumentCitationSourceContents",0,[()=>aY,0]],$E=[1,"com.amazon.aws.codewhisperer","DocumentSymbols",0,()=>ZY],hJ=[1,"com.amazon.aws.codewhisperer","EnvironmentVariables",0,[()=>tm,0]],uJ=[1,"com.amazon.aws.codewhisperer","ImageBlocks",0,[()=>em,0]],LE=[1,"com.amazon.aws.codewhisperer","References",0,()=>lm],cJ=[1,"com.amazon.aws.codewhisperer","RelevantDocumentList",0,[()=>Am,0]],_J=[1,"com.amazon.aws.codewhisperer","ShellHistory",0,[()=>dm,0]],OE=[1,"com.amazon.aws.codewhisperer","SupplementaryWebLinks",0,[()=>Em,0]],wJ=[1,"com.amazon.aws.codewhisperer","ToolResultContent",0,[()=>zJ,0]],lJ=[1,"com.amazon.aws.codewhisperer","ToolResults",0,[()=>gE,0]],AJ=[1,"com.amazon.aws.codewhisperer","Tools",0,[()=>XJ,0]],MJ=[1,"com.amazon.aws.codewhisperer","ToolUses",0,[()=>Um,0]],dJ=[1,"com.amazon.aws.codewhisperer","WorkspaceFolderList",0,[()=>Y,0]],RJ=[1,"com.amazon.aws.q.interactioncomponents","AlertComponentList",0,[()=>Wm,0]],EJ=[1,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOptionsList",0,[()=>Pm,0]],yJ=[1,"com.amazon.aws.q.interactioncomponents","ClarificationQuestionList",0,[()=>Dm,0]],TJ=[1,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntryList",0,[()=>zm,0]],gJ=[1,"com.amazon.aws.q.interactioncomponents","ProgressComponentList",0,[()=>Cm,0]],SJ=[1,"com.amazon.aws.q.interactioncomponents","Resources",0,[()=>B_,0]],IJ=[1,"com.amazon.aws.q.interactioncomponents","SectionComponentList",0,[()=>Km,0]],UJ=[1,"com.amazon.aws.q.interactioncomponents","StepComponentList",0,[()=>km,0]],bJ=[1,"com.amazon.aws.q.interactioncomponents","SuggestionList",0,[()=>qm,0]],$J=[1,"com.amazon.aws.q.interactioncomponents","TaskActionList",0,[()=>jm,0]],LJ=[1,"com.amazon.aws.q.interactioncomponents","TaskComponentList",0,[()=>Zm,0]],OJ=[2,"com.amazon.aws.codewhisperer","IntentData",8,0,()=>mJ],BJ=[2,"com.amazon.aws.codewhisperer","IntentMap",0,[0,0],[()=>OJ,0]],NJ=[2,"com.amazon.aws.q.interactioncomponents","TaskActionPayload",0,[0,0],[()=>rn,0]],BE=[4,"com.amazon.aws.codewhisperer","ChatMessage",0,["userInputMessage","assistantResponseMessage"],[[()=>$m,0],[()=>DY,0]]],GJ=[4,"com.amazon.aws.codewhisperer","ChatResponseStream",{["streaming"]:1},["messageMetadataEvent","assistantResponseEvent","reasoningContentEvent","dryRunSucceedEvent","codeReferenceEvent","supplementaryWebLinksEvent","followupPromptEvent","codeEvent","intentsEvent","interactionComponentsEvent","toolUseEvent","toolResultEvent","metadataEvent","meteringEvent","contextUsageEvent","citationEvent","documentCitationEvent","invalidStateEvent","error"],[()=>hm,[()=>PY,0],[()=>_m,0],()=>pY,()=>zY,[()=>ym,0],[()=>sm,0],[()=>XY,0],[()=>om,0],[()=>Hm,0],[()=>bm,0],[()=>Sm,0],()=>um,()=>cm,()=>CY,[()=>YY,0],[()=>VY,0],()=>fm,[()=>ME,0]]],HJ=[4,"com.amazon.aws.codewhisperer","CitationTarget",0,["location","range"],[1,()=>yE]],WJ=[4,"com.amazon.aws.codewhisperer","CursorState",0,["position","range"],[()=>S_,()=>$_]],FJ=[4,"com.amazon.aws.codewhisperer","Diagnostic",0,["textDocumentDiagnostic","runtimeDiagnostic"],[[()=>Tm,0],[()=>Mm,0]]],PJ=[4,"com.amazon.aws.codewhisperer","DocumentCitationLocation",0,["documentPage","documentChar","documentChunk","searchResult","web"],[()=>g_,()=>g_,()=>g_,()=>jY,[()=>vY,0]]],DJ=[4,"com.amazon.aws.codewhisperer","DocumentSource",8,["bytes"],[21]];var YJ=[4,"com.amazon.aws.codewhisperer","ImageSource",8,["bytes"],[21]],mJ=[4,"com.amazon.aws.codewhisperer","IntentDataType",0,["string"],[0]],JJ=[4,"com.amazon.aws.codewhisperer","ReasoningContent",8,["reasoningText","redactedContent"],[[()=>wm,0],21]];var XJ=[4,"com.amazon.aws.codewhisperer","Tool",0,["toolSpecification","cachePoint"],[[()=>Im,0],()=>b_]],zJ=[4,"com.amazon.aws.codewhisperer","ToolResultContentBlock",0,["text","json"],[[()=>Y,0],[()=>U_,0]]];var NE=[9,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponse",{["http"]:["POST","/generateAssistantResponse",200]},()=>Nm,()=>Gm];var WE=(n)=>{return{apiVersion:"2023-11-27",base64Decoder:n?.base64Decoder??vs.fromBase64,base64Encoder:n?.base64Encoder??vs.toBase64,disableHostPrefix:n?.disableHostPrefix??!1,endpointProvider:n?.endpointProvider??lE,extensions:n?.extensions??[],httpAuthSchemeProvider:n?.httpAuthSchemeProvider??Pd,httpAuthSchemes:n?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(t)=>t.getIdentityProvider("smithy.api#httpBearerAuth"),signer:new HE.HttpBearerAuthSigner}],logger:n?.logger??new V.NoOpLogger,protocol:n?.protocol??GE.AwsRestJsonProtocol,protocolSettings:n?.protocolSettings??{defaultNamespace:"com.amazon.aws.codewhisperer.streaming",errorTypeRegistries:dE,version:"2023-11-27",serviceTarget:"AmazonCodeWhispererStreamingService"},serviceId:n?.serviceId??"CodeWhispererStreaming",urlParser:n?.urlParser??E_.parseUrl,utf8Decoder:n?.utf8Decoder??Vi.fromUtf8,utf8Encoder:n?.utf8Encoder??Vi.toUtf8}};var YE=(n)=>{V.emitWarningIfUnsupportedVersion(process.version);let t=R_.resolveDefaultsModeConfig(n),i=()=>t().then(V.loadConfigsForDefaultMode),s=WE(n);FE.emitWarningIfUnsupportedVersion(process.version);let r={profile:n?.profile,logger:s.logger};return{...s,...n,runtime:"node",defaultsMode:t,authSchemePreference:n?.authSchemePreference??kt.loadConfig(PE.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,r),bodyLengthChecker:n?.bodyLengthChecker??d_.calculateBodyLength,defaultUserAgentProvider:n?.defaultUserAgentProvider??Gt.createDefaultUserAgentProvider({serviceId:s.serviceId,clientVersion:Jd.version}),eventStreamSerdeProvider:n?.eventStreamSerdeProvider??Ef.eventStreamSerdeProvider,httpAuthSchemes:n?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(e)=>e.getIdentityProvider("smithy.api#httpBearerAuth")||(async(f)=>{return await A_(f)(f)}),signer:new DE.HttpBearerAuthSigner}],maxAttempts:n?.maxAttempts??kt.loadConfig(un.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,n),region:n?.region??kt.loadConfig(hn.NODE_REGION_CONFIG_OPTIONS,{...hn.NODE_REGION_CONFIG_FILE_OPTIONS,...r}),requestHandler:Gf.NodeHttpHandler.create(n?.requestHandler??i),retryMode:n?.retryMode??kt.loadConfig({...un.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await i()).retryMode||Sn.DEFAULT_RETRY_MODE},n),sha256:n?.sha256??M_.Hash.bind(null,"sha256"),streamCollector:n?.streamCollector??Gf.streamCollector,useDualstackEndpoint:n?.useDualstackEndpoint??kt.loadConfig(hn.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,r),useFipsEndpoint:n?.useFipsEndpoint??kt.loadConfig(hn.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,r),userAgentAppId:n?.userAgentAppId??kt.loadConfig(Gt.NODE_APP_ID_CONFIG_OPTIONS,r)}};var an=Q(ct(),1);var xn=Q(Jn(),1);var mE=(n)=>{let{httpAuthSchemes:t,httpAuthSchemeProvider:i,token:s}=n;return{setHttpAuthScheme(r){let e=t.findIndex((f)=>f.schemeId===r.schemeId);if(e===-1)t.push(r);else t.splice(e,1,r)},httpAuthSchemes(){return t},setHttpAuthSchemeProvider(r){i=r},httpAuthSchemeProvider(){return i},setToken(r){s=r},token(){return s}}},JE=(n)=>{return{httpAuthSchemes:n.httpAuthSchemes(),httpAuthSchemeProvider:n.httpAuthSchemeProvider(),token:n.token()}};var XE=(n,t)=>{let i=Object.assign(an.getAwsRegionExtensionConfiguration(n),V.getDefaultExtensionConfiguration(n),xn.getHttpHandlerExtensionConfiguration(n),mE(n));return t.forEach((s)=>s.configure(i)),Object.assign(n,an.resolveAwsRegionExtensionConfiguration(i),V.resolveDefaultRuntimeConfig(i),xn.resolveHttpHandlerRuntimeConfig(i),JE(i))};class N_ extends V.Client{config;constructor(...[n]){let t=YE(n||{});super(t);this.initConfig=t;let i=Yd(t),s=Kt.resolveUserAgentConfig(i),r=un.resolveRetryConfig(s),e=hn.resolveRegionConfig(r),f=wi.resolveHostHeaderConfig(e),o=Zn.resolveEndpointConfig(f),h=jn.resolveDefaultAwsRegionalEndpointsConfig(o),u=Mc.resolveEventStreamSerdeConfig(h),c=Dd(u),_=XE(c,n?.extensions||[]);this.config=_,this.middlewareStack.use(zE.getSchemaSerdePlugin(this.config)),this.middlewareStack.use(Kt.getUserAgentPlugin(this.config)),this.middlewareStack.use(un.getRetryPlugin(this.config)),this.middlewareStack.use(ie.getContentLengthPlugin(this.config)),this.middlewareStack.use(wi.getHostHeaderPlugin(this.config)),this.middlewareStack.use(ne.getLoggerPlugin(this.config)),this.middlewareStack.use(te.getRecursionDetectionPlugin(this.config)),this.middlewareStack.use(ps.getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:Fd,identityProviderConfigProvider:async(w)=>new ps.DefaultIdentityProviderConfig({"smithy.api#httpBearerAuth":w.token})})),this.middlewareStack.use(ps.getHttpSigningPlugin(this.config))}destroy(){super.destroy()}}class G_ extends V.Command.classBuilder().ep(md).m(function(n,t,i,s){return[Zn.getEndpointPlugin(i,n.getEndpointParameterInstructions())]}).s("AmazonCodeWhispererStreamingService","GenerateAssistantResponse",{eventStream:{output:!0}}).n("CodeWhispererStreamingClient","GenerateAssistantResponseCommand").sc(NE).build(){}import{randomUUID as Q_}from"crypto";function QE(n){let t=Lr[n];if(!t)throw Error(`Unsupported model: ${n}. Supported models: ${yw.join(", ")}`);return t}var CE=new Set(["claude-opus-4-8","claude-opus-4-7","claude-sonnet-5","claude-sonnet-4-6","gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),xE=["low","medium","high","xhigh","max"];function Hf(n){for(let t of xE){let i=`-${t}`;if(n.endsWith(i)){let s=n.slice(0,-i.length);if(CE.has(s))return{wireId:QE(s),effort:t}}}return{wireId:QE(n),effort:void 0}}function QJ(n){for(let t of xE){let i=`-${t}`;if(n.endsWith(i)){let s=n.slice(0,-i.length);if(CE.has(s))return s}}if(n.endsWith("-thinking")){let t=n.slice(0,-9);if(Lr[t])return t}return n}function KE(n){return D(QJ(n))}var CJ=["low","medium","high","xhigh","max"];function xJ(n){return typeof n==="string"&&CJ.some((t)=>t===n)}var kE=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),qE=new Set(["claude-opus-4.7","claude-opus-4.8","claude-sonnet-5",...kE]),KJ=new Set(["claude-opus-4.5","claude-opus-4.6","claude-opus-4.6-1m","claude-sonnet-4.6","claude-sonnet-4.6-1m",...qE]);function ai(n){return KJ.has(n)}function H_(n){return qE.has(n)}function VE(n,t){if(kE.has(n))return{reasoning:{effort:t}};return{output_config:{effort:t}}}function kJ(n,t){if(!ai(n))return;if(t==="xhigh"&&!H_(n))return"max";return t}function qJ(n,t){if(!ai(t))return;let i;if(n<=1e4)i="low";else if(n<=20000)i="medium";else if(n<=28000)i="high";else i="max";return i}function jE(n){let t;if(ai(n.model))t={wireId:n.model,effort:void 0};else try{t=Hf(n.model)}catch(s){if(s instanceof Error&&s.message.startsWith("Unsupported model:"))return;throw s}if(!ai(t.wireId))return;let i=[t.effort,n.reasoningEffort,n.configEffort];for(let s of i)if(xJ(s))return kJ(t.wireId,s);if(!n.think)return;if(n.autoEffortMapping??!0)return qJ(n.budget,t.wireId);return"medium"}import{randomUUID as pJ}from"crypto";class Kn extends Error{code;name="RequestTransformError";constructor(n,t="invalid_request"){super(n);this.code=t}}function Ae(n){return typeof n==="object"&&n!==null}function VJ(n){let t=atob(n),i=new Uint8Array(t.length);for(let s=0;s<t.length;s++)i[s]=t.charCodeAt(s);return i}function jJ(n){let t=[];for(let i of n){if(!Ae(i)||i.type!=="image"||!Ae(i.source))continue;let s=i.source;if(s.type!=="base64"||typeof s.data!=="string")continue;t.push({mediaType:typeof s.media_type==="string"?s.media_type:"image/jpeg",data:s.data})}return t}function aJ(n){let t=[];for(let i of n){if(!Ae(i)||i.type!=="image_url"||!Ae(i.image_url))continue;let s=i.image_url.url;if(typeof s!=="string"||!s.startsWith("data:"))continue;let[r="",e]=s.split(",",2);if(!e)continue;let f=r.split(";")[0]?.replace("data:","");t.push({mediaType:f||"image/jpeg",data:e})}return t}function Wf(n){if(!Array.isArray(n))return[];return[...jJ(n),...aJ(n)]}function Ff(n){let t=[],i=0;for(let s of n){if(t.length>=4)break;if(i+s.data.length>3750000)break;t.push(s),i+=s.data.length}return{images:t.map((s)=>({format:s.mediaType.split("/")[1]||"png",source:{bytes:VJ(s.data)}})),omitted:n.length-t.length}}function Pf(n){let t=[];for(let i of n){if(!Ae(i))continue;if(typeof i.text==="string")t.push(i.text);else if(i.type==="text"&&i.text)t.push(String(i.text))}return t.join("")}function W_(n){return typeof n==="object"&&n!==null}function aE(n,t){for(let i of n){if(i.role!=="assistant")continue;if(i.tool_calls){for(let s of i.tool_calls)if(s.id===t)return s}if(Array.isArray(i.content)){for(let s of i.content)if(W_(s)&&s.type==="tool_use"&&s.id===t)return s}}return null}function vE(n){let t=[];for(let i of n){if(t.length===0){t.push({...i});continue}let s=t[t.length-1];if(!s||i.role!==s.role){t.push({...i});continue}if(Array.isArray(s.content)&&Array.isArray(i.content))s.content.push(...i.content);else if(typeof s.content==="string"&&typeof i.content==="string")s.content+=`
|
|
230
|
-
${i.content}`;else if(Array.isArray(s.content)&&typeof i.content==="string")s.content.push({type:"text",text:i.content});else if(typeof s.content==="string"&&Array.isArray(i.content))s.content=[{type:"text",text:s.content},...i.content];if(i.tool_calls){if(!s.tool_calls)s.tool_calls=[];s.tool_calls.push(...i.tool_calls)}if(i.role==="tool"){if(!s.tool_results)s.tool_results=[{content:s.content,tool_call_id:s.tool_call_id}];s.tool_results.push({content:i.content,tool_call_id:i.tool_call_id})}}return t}function kn(n){if(n===null||n===void 0)return"";if(typeof n==="string")return n;if(!W_(n))return"";if(typeof n.content==="string")return n.content;if(Array.isArray(n.content))return n.content.filter((t)=>W_(t)&&t.type==="text").map((t)=>typeof t.text==="string"?t.text:"").join("");return typeof n.text==="string"?n.text:""}function ZE(n){return n.map((t)=>({toolSpecification:{name:t.name||t.function?.name,description:(t.description||t.function?.description||"").substring(0,9216),inputSchema:{json:t.input_schema||t.function?.parameters||{}}}}))}function nr(n){let t=[],i=new Set;for(let s of n)if(!i.has(s.toolUseId))i.add(s.toolUseId),t.push(s);return t}function pE(n){return typeof n==="object"&&n!==null}function vJ(n){if(typeof n.id!=="string"||n.id.length===0||typeof n.function?.name!=="string"||n.function.name.length===0)throw new Kn("Assistant tool calls require non-empty id and name","invalid_tool_history");let t=n.function?.arguments,i=t;if(typeof t==="string")try{i=JSON.parse(t)}catch(s){if(s instanceof SyntaxError)throw new Kn(`Tool call ${n.id} contains invalid JSON arguments`,"invalid_tool_history");throw s}return{input:i,name:n.function.name,toolUseId:n.id}}function ZJ(n){if(n.length<4)return n;let t=[],i=0;while(i<n.length){let s=n[i];if(s?.assistantResponseMessage?.toolUses&&i+1<n.length&&n[i+1]?.userInputMessage?.userInputMessageContext?.toolResults){let r=i,e=i;while(e<n.length){let h=n[e],u=e+1<n.length?n[e+1]:void 0;if(!h?.assistantResponseMessage?.toolUses||!u?.userInputMessage?.userInputMessageContext?.toolResults)break;e+=2}let f=(e-r)/2,o;for(let h=r;h<e;h+=2){let u=n[h],c=n[h+1];if(!u||!c)continue;let _=u.assistantResponseMessage,w=f>1&&h!==r&&_!==void 0&&_.content.length>0&&_.content===o;if(o=_?.content,w&&_?.toolUses)t.push({assistantResponseMessage:{content:"",toolUses:_.toolUses}});else t.push(u);t.push(c)}i=e}else{if(s)t.push(s);i++}}return t}function ny(n,t){let i=n.at(-1)?.userInputMessage;if(!i)return!1;if(t.content)i.content=i.content?`${i.content}
|
|
231
|
-
|
|
232
|
-
${t.content}`:t.content;let s=t.userInputMessageContext?.toolResults;if(s&&s.length>0){i.userInputMessageContext??={};let r=i.userInputMessageContext;r.toolResults=nr([...r.toolResults??[],...s])}if(t.images&&t.images.length>0){if((i.images?.length??0)+t.images.length>4)throw new Kn("A Kiro request supports at most 4 images in one user turn","too_many_images");i.images=[...i.images??[],...t.images]}return!0}function ty(n,t){let i=[];for(let s=0;s<n.length-1;s++){let r=n[s];if(!r)continue;if(r.role==="user"){let h={content:"",modelId:t,origin:Rn.ORIGIN_AI_EDITOR},u=[];if(Array.isArray(r.content)){h.content=Pf(r.content);for(let _ of r.content){if(!pE(_)||_.type!=="tool_result"||typeof _.tool_use_id!=="string")continue;u.push({content:[{text:kn(_.content??_)}],status:_.is_error===!0?"error":"success",toolUseId:_.tool_use_id})}let c=Wf(r.content);if(c.length>0){let _=Ff(c);if(h.images=_.images,_.omitted>0)throw new Kn("A Kiro request supports at most 4 images and 3.75 MB of base64 image data per user turn","too_many_images")}}else h.content=kn(r);if(u.length>0)h.userInputMessageContext={toolResults:nr(u)};if(!ny(i,h))i.push({userInputMessage:h});continue}if(r.role==="tool"){let h=[];if(r.tool_results)for(let c of r.tool_results){if(!c.tool_call_id)continue;h.push({content:[{text:kn(c)}],status:c.is_error===!0?"error":"success",toolUseId:c.tool_call_id})}else if(r.tool_call_id)h.push({content:[{text:kn(r)}],status:r.is_error===!0?"error":"success",toolUseId:r.tool_call_id});let u={content:"",modelId:t,origin:Rn.ORIGIN_AI_EDITOR,userInputMessageContext:{toolResults:nr(h)}};if(!ny(i,u))i.push({userInputMessage:u});continue}if(r.role!=="assistant")continue;let e={content:""},f=[];if(Array.isArray(r.content))for(let h of r.content){if(!pE(h))continue;if(h.type==="text")e.content+=typeof h.text==="string"?h.text:"";else if(h.type==="tool_use"&&typeof h.id==="string"&&typeof h.name==="string")f.push({input:h.input,name:h.name,toolUseId:h.id})}else e.content=kn(r);if(r.tool_calls)for(let h of r.tool_calls)f.push(vJ(h));if(f.length>0)e.toolUses=f;if(!e.content&&!e.toolUses)continue;let o=i[i.length-1]?.assistantResponseMessage;if(o){if(e.content)o.content=o.content?`${o.content}
|
|
233
|
-
|
|
234
|
-
${e.content}`:e.content;if(e.toolUses)o.toolUses=[...o.toolUses??[],...e.toolUses]}else i.push({assistantResponseMessage:e})}return ZJ(i)}function iy(n,t,i){if(!t)return n;let s=n.find((r)=>r.userInputMessage);if(s?.userInputMessage)s.userInputMessage.content=`${t}
|
|
235
|
-
|
|
236
|
-
${s.userInputMessage.content||""}`;else n.unshift({userInputMessage:{content:t,modelId:i,origin:Rn.ORIGIN_AI_EDITOR}});return n}function sy(n){return n.some((t)=>Boolean(t.assistantResponseMessage?.toolUses)||Boolean(t.userInputMessage?.userInputMessageContext?.toolResults))}function ry(n){let t=new Set;for(let i of n)for(let s of i.assistantResponseMessage?.toolUses??[])if(s.name)t.add(s.name);return t}function Wt(n){return typeof n==="object"&&n!==null}function nX(n){return Wt(n)}function tX(n){return Wt(n)}function iX(n){let t=typeof n==="string"?JSON.parse(n):n;if(!Wt(t))return{messages:[],tools:[],system:""};return{messages:Array.isArray(t.messages)?t.messages.filter(nX):[],tools:Array.isArray(t.tools)?t.tools.filter(tX):[],system:typeof t.system==="string"?t.system:""}}function sX(n){if(Array.isArray(n))return"array";if(n===null)return"string";let t=typeof n;return t==="number"||t==="boolean"||t==="string"||t==="object"?t:"string"}function rX(n,t){let i=t.find((e)=>e.name===n&&Wt(e.input)),s={};if(i&&Wt(i.input))for(let[e,f]of Object.entries(i.input))s[e]={type:sX(f)};let r=Object.keys(s).length>0?{type:"object",properties:s}:{type:"object"};return{toolSpecification:{name:n,description:"",inputSchema:{json:r}}}}function eX(n,t){let i={content:""},s=[];if(Array.isArray(t.content))for(let r of t.content){if(!Wt(r))continue;if(r.type==="text"&&typeof r.text==="string")i.content+=r.text;else if(r.type==="tool_use"&&typeof r.id==="string"&&typeof r.name==="string")s.push({input:r.input,name:r.name,toolUseId:r.id})}else i.content=kn(t);for(let r of t.tool_calls??[]){if(typeof r.id!=="string"||typeof r.function?.name!=="string")continue;let e=r.function.arguments;try{s.push({input:typeof e==="string"?JSON.parse(e):e,name:r.function.name,toolUseId:r.id})}catch(f){if(f instanceof SyntaxError)throw new Kn(`Tool call ${r.id} contains invalid JSON arguments`,"invalid_tool_history");throw f}}if(s.length>0)i.toolUses=s;if(i.content||i.toolUses)n.push({assistantResponseMessage:i})}function oX(n){let t="",i=[],s=[];if(n.role==="tool"){let r=n.tool_results??[{content:n.content,tool_call_id:n.tool_call_id}];for(let e of r){if(typeof e.tool_call_id!=="string")continue;i.push({content:[{text:kn(e)}],status:e.is_error===!0?"error":"success",toolUseId:e.tool_call_id})}}else if(Array.isArray(n.content)){t=Pf(n.content);for(let e of n.content){if(!Wt(e)||e.type!=="tool_result"||typeof e.tool_use_id!=="string")continue;i.push({content:[{text:kn(e.content??e)}],status:e.is_error===!0?"error":"success",toolUseId:e.tool_use_id})}let r=Ff(Wf(n.content));if(s.push(...r.images),r.omitted>0)throw new Kn("A Kiro request supports at most 4 images and 3.75 MB of base64 image data per user turn","too_many_images")}else t=kn(n);return{content:t,toolResults:i,images:s}}function fX(n,t){let i=aE(n,t.toolUseId);if(!Wt(i))return;let s=Wt(i.function)?i.function:void 0,r=typeof i.name==="string"?i.name:typeof s?.name==="string"?s.name:void 0;if(!r)throw new Kn(`Tool result ${t.toolUseId} references a call without a valid name`,"invalid_tool_history");let e=i.input??s?.arguments,f=e??{};if(typeof e==="string")try{f=JSON.parse(e)}catch(o){if(o instanceof SyntaxError)throw new Kn(`Tool call ${t.toolUseId} contains invalid JSON arguments`,"invalid_tool_history");throw o}return{name:r,toolUseId:t.toolUseId,input:f}}function ey(n,t,i,s=!1,r=20000,e={}){let f=iX(n);if(f.messages.length===0)throw Error("No messages");let{wireId:o,effort:h}=Hf(t),u=f.messages.filter((g)=>g.role==="system"),c=vE(f.messages.filter((g)=>g.role!=="system")),_=f.system,w=u.map(kn).join(`
|
|
237
|
-
|
|
238
|
-
`);if(w)_=_?`${_}
|
|
239
|
-
|
|
240
|
-
${w}`:w;let l=c.at(-1);if(l?.role==="assistant"&&kn(l)==="{")c.pop();let A=c.at(-1);if(!A)throw Error("Empty");let d=ty(c,o),E=A.role==="user"&&!(Array.isArray(A.content)&&A.content.some((g)=>Wt(g)&&g.type==="tool_result")),R=c.at(-2);if(E&&R?.role==="assistant"&&d.at(-1)?.userInputMessage){let g=kn(R);if(g)d.push({assistantResponseMessage:{content:g}})}d=iy(d,_,o);let y="",T=[],S=[];if(A.role==="assistant")eX(d,A);else{if(d.at(-1)&&!d.at(-1)?.assistantResponseMessage)d.push({assistantResponseMessage:{content:""}});let g=oX(A);y=g.content,T=g.toolResults,S=g.images}let I=d.flatMap((g)=>g.assistantResponseMessage?.toolUses??[]),F=new Set(I.map((g)=>g.toolUseId)),C=[],sn=[];for(let g of T)if(F.has(g.toolUseId))C.push(g);else{let X=fX(f.messages,g);if(X)sn.push({call:X,result:g});else throw new Kn(`Tool result ${g.toolUseId} has no matching tool call`,"invalid_tool_history")}if(sn.length>0){if(!d.at(-1)||d.at(-1)?.assistantResponseMessage)d.push({userInputMessage:{content:"",modelId:o,origin:Rn.ORIGIN_AI_EDITOR}});d.push({assistantResponseMessage:{content:"",toolUses:sn.map(({call:g})=>g)}}),C.push(...sn.map(({result:g})=>g))}let b={content:y,modelId:o,origin:Rn.ORIGIN_AI_EDITOR};if(S.length>0)b.images=S;let $=ZE(f.tools).filter((g)=>typeof g.toolSpecification.name==="string").map((g)=>({toolSpecification:{...g.toolSpecification,name:g.toolSpecification.name??""}}));if(C.length>0||$.length>0){if(b.userInputMessageContext={},C.length>0)b.userInputMessageContext.toolResults=nr(C);if($.length>0)b.userInputMessageContext.tools=$}if(sy(d)){let g=b.userInputMessageContext?.tools??[],X=new Set(g.map((tn)=>tn.toolSpecification.name)),Z=[...ry(d)].filter((tn)=>!X.has(tn));if(Z.length>0)b.userInputMessageContext??={},b.userInputMessageContext.tools=[...g,...Z.map((tn)=>rX(tn,I))]}let N=e.conversationId??pJ(),B={conversationState:{chatTriggerType:Rn.CHAT_TRIGGER_TYPE_MANUAL,conversationId:N,currentMessage:{userInputMessage:b},...d.length>0?{history:d}:{}},...i.profileArn?{profileArn:i.profileArn}:{}};return h===void 0?{request:B,resolved:o,convId:N}:{request:B,resolved:o,convId:N,variantEffort:h}}function hX(n){let t=typeof n==="string"?JSON.parse(n):n;if(typeof t!=="object"||t===null||!("reasoning_effort"in t))return;let i=t.reasoning_effort;return typeof i==="string"||i===null?i:void 0}function oy(n,t,i,s=!1,r=20000,e){let{request:f,resolved:o,convId:h}=ey(n,t,i,s,r,{conversationId:e?.conversationId}),u=jE({model:t,think:s,budget:r,reasoningEffort:hX(n),configEffort:e?.effort,autoEffortMapping:e?.autoEffortMapping});return{conversationState:f.conversationState,...f.profileArn?{profileArn:f.profileArn}:{},streaming:!0,effectiveModel:o,conversationId:h,region:Ew(i.profileArn)??i.region,...u?{effort:u}:{}}}function Df(n){return Math.ceil(n.length/4)}async function Yf(n,t){if(t?.aborted)return{kind:"aborted"};let i=n.next();if(!t)return{kind:"event",result:await i};return new Promise((s,r)=>{let e=()=>s({kind:"aborted"});t.addEventListener("abort",e,{once:!0}),i.then((f)=>{t.removeEventListener("abort",e),s({kind:"event",result:f})},(f)=>{t.removeEventListener("abort",e),r(f)})})}function Me(n,t){if(!t?.name||!t.toolUseId)return;let i=n.get(t.toolUseId);if(i){i.input+=t.input??"";return}n.set(t.toolUseId,{toolUseId:t.toolUseId,name:t.name,input:t.input??""})}function fy(n){let t=[],i=0;for(let s of n.values()){let r=s.input;try{r=JSON.stringify(JSON.parse(s.input))}catch{r=s.input}t.push({type:"content_block_start",index:i,content_block:{type:"tool_use",id:s.toolUseId,name:s.name,input:{}}},{type:"content_block_delta",index:i,delta:{type:"input_json_delta",partial_json:r}},{type:"content_block_stop",index:i}),i+=1}return t}function mf(n,t){let i=t.metadataEvent?.tokenUsage;if(i)n.outputTokens=i.outputTokens??n.outputTokens,n.totalTokens=i.totalTokens??n.totalTokens,n.inputTokens=i.inputTokens??(i.uncachedInputTokens===void 0?n.inputTokens:i.uncachedInputTokens+(i.cacheReadInputTokens??0)+(i.cacheWriteInputTokens??0));n.contextUsagePercentage=t.contextUsageEvent?.contextUsagePercentage??t.metadataEvent?.contextUsagePercentage??i?.contextUsagePercentage??n.contextUsagePercentage}function Jf(n,t,i){let s=n.outputTokens??Df(t),r=n.inputTokens;if(r===void 0&&n.totalTokens!==void 0)r=Math.max(0,n.totalTokens-s);if(r===void 0&&n.contextUsagePercentage!==void 0&&n.contextUsagePercentage>0){let e=Math.round(KE(i)*n.contextUsagePercentage/100);r=Math.max(0,e-s)}return{inputTokens:r??0,outputTokens:s}}class hy extends Error{name="MissingSdkEventStreamError";constructor(){super("SDK response has no event stream")}}async function uy(n,t,i,s){let r=n.generateAssistantResponseResponse;if(!r)throw new hy;let e=r[Symbol.asyncIterator](),f=new Map,o={},h="",u="",c=!1,_=!1;try{while(!0){let A=await Yf(e,s);if(A.kind==="aborted"){if(e.return)await e.return();_=!0;break}if(A.result.done){c=!0;break}let d=A.result.value;mf(o,d),u+=d.reasoningContentEvent?.text??"",h+=d.assistantResponseEvent?.content??"",Me(f,d.toolUseEvent)}}finally{if(!c&&!_&&e.return)await e.return()}let w=Jf(o,h,t),l={role:"assistant",content:h,...u?{reasoning_content:u}:{},...f.size>0?{tool_calls:Array.from(f.values(),(A)=>({id:A.toolUseId,type:"function",function:{name:A.name,arguments:A.input}}))}:{}};return{id:i,object:"chat.completion",created:Math.floor(Date.now()/1000),model:t,choices:[{index:0,message:l,finish_reason:f.size>0?"tool_calls":"stop"}],usage:{prompt_tokens:w.inputTokens,completion_tokens:w.outputTokens,total_tokens:w.inputTokens+w.outputTokens}}}var uX=[/input is too long/i,/CONTENT_LENGTH_EXCEEDS_THRESHOLD/i],cX=/econnreset|etimedout|enotfound|network|fetch failed|socket/i;function Xf(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function F_(n,t){let i=n[t];return typeof i==="string"?i:void 0}function _X(n){let t=n.$metadata;if(!Xf(t))return;let i=t.httpStatusCode;return typeof i==="number"?i:void 0}function wX(n){let t=n.$response;if(!Xf(t))return;let i=t.headers;if(!Xf(i))return;let s={};for(let[r,e]of Object.entries(i))if(typeof e==="string")s[r]=e;else if(typeof e==="number")s[r]=String(e);return Object.keys(s).length>0?s:void 0}function P_(n){if(!Xf(n))return{message:n instanceof Error?n.message:String(n)};let t=_X(n),i=F_(n,"message")??String(n),s=F_(n,"name"),r=F_(n,"reason"),e=wX(n);return{message:i,...t!==void 0?{status:t}:{},...s!==void 0?{code:s}:{},...r!==void 0?{reason:r}:{},...e!==void 0?{headers:e}:{}}}function lX(n){let t=Object.entries(n??{}).find(([s])=>s.toLowerCase()==="retry-after"),i=Number.parseInt(t?.[1]??"60",10);return Number.isFinite(i)&&i>=0?i*1000:60000}function AX(n){return uX.some((t)=>t.test(n))}function cy(n,t){if(n.reason==="INVALID_MODEL_ID"){let i=n.status??400;return{action:"fail",status:i,terminalStatus:i}}if(n.reason==="TEMPORARILY_SUSPENDED")return t.accountCount>1?{action:"switch",...n.status!==void 0?{status:n.status}:{}}:{action:"fail",...n.status!==void 0?{status:n.status}:{},terminalStatus:n.status??403};switch(n.status){case 400:return{action:"fail",status:400,terminalStatus:AX(n.message)?413:400};case 401:return t.retryCount<t.maxRetries?{action:"retry",status:401}:{action:"fail",status:401,terminalStatus:401};case 402:return{action:"fail",status:402,terminalStatus:402};case 403:if(Rs(n.message)){if(!t.forcedRefreshAccountIds.has(t.accountId))return t.forcedRefreshAccountIds.add(t.accountId),{action:"refresh-then-retry",status:403};return t.accountCount>1?{action:"switch",status:403}:{action:"fail",status:403,terminalStatus:403}}if(t.accountCount>1)return{action:"switch",status:403};return t.retryCount<t.maxRetries?{action:"retry",status:403,retryAfterMs:t.retryDelayMs*2**t.retryCount}:{action:"fail",status:403,terminalStatus:403};case 429:{let i=lX(n.headers);return t.accountCount>1?{action:"switch",status:429,retryAfterMs:i}:{action:"retry",status:429,retryAfterMs:i}}case 500:return t.serverErrorCount<5?{action:"retry",status:500,retryAfterMs:1000*2**Math.max(0,t.serverErrorCount-1)}:{action:"switch",status:500};case void 0:if(cX.test(n.message))return t.retryCount<t.maxRetries?{action:"retry",retryAfterMs:t.retryDelayMs*2**t.retryCount}:{action:"fail",terminalStatus:500};return{action:"fail",terminalStatus:500};default:return{action:"fail",status:n.status,terminalStatus:n.status}}}var MX=new Map,dX=new Map;function di(n){return n.reason instanceof Error?n.reason:new DOMException("The request was aborted","AbortError")}function tr(n,t){if(t.aborted)return Promise.reject(di(t));return new Promise((i,s)=>{let r=()=>s(di(t));t.addEventListener("abort",r,{once:!0}),n.then((e)=>{t.removeEventListener("abort",r),i(e)},(e)=>{t.removeEventListener("abort",r),s(e)})})}function _y(n,t){if(n<=0)return Promise.resolve();return tr(Bun.sleep(n),t)}async function wy(n,t,i){let s=n.get(t);if(!s)s={tail:Promise.resolve(),waiters:0},n.set(t,s);let r=s,e=r.tail,f,o=new Promise((_)=>{f=_});if(!f)throw TypeError("Queue release was not initialized");let h=f;r.waiters+=1,r.tail=e.catch(()=>{return}).then(()=>o);let u=()=>{if(r.waiters-=1,r.waiters!==0)return;r.tail.finally(()=>{if(r.waiters===0&&n.get(t)===r)n.delete(t)})};try{await tr(e,i)}catch(_){throw h(),u(),_}let c=!1;return()=>{if(c)return;c=!0,h(),u()}}function ly(n,t){return wy(MX,n,t)}function Ay(n,t){return wy(dX,n,t)}function My(n,t){if(n)return{signal:n,dispose:()=>{return}};let i=new AbortController,s=setTimeout(()=>i.abort(new DOMException("Request deadline exceeded","TimeoutError")),t);return{signal:i.signal,dispose:()=>clearTimeout(s)}}var de="<\uFF5CDSML\uFF5Cfunction_calls";function D_(){return`tool_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}function RX(n){let t=[],i=/```[\s\S]*?```/g;for(let e=i.exec(n);e!==null;e=i.exec(n))t.push([e.index,e.index+e[0].length]);let s=(e)=>t.some(([f,o])=>e>=f&&e<o),r=/`[^`\n]+`/g;for(let e=r.exec(n);e!==null;e=r.exec(n))if(!s(e.index))t.push([e.index,e.index+e[0].length]);return t}function vi(n,t,i){return i.some(([s,r])=>n<r&&t>s)}function EX(n){let t={},i=/<parameter\s+name="([^"]+)"\s*>([\s\S]*?)<\/parameter>/g;for(let s=i.exec(n);s!==null;s=i.exec(n)){let r=s[1];if(r===void 0)continue;let e=s[2]??"";try{t[r]=JSON.parse(e)}catch{t[r]=e}}return t}function dy(n,t){return{toolUseId:D_(),name:n,input:EX(t)}}function yX(n,t,i){let s=[],r=/<function_calls>[\s\S]*?<\/function_calls>/g;for(let f=r.exec(n);f!==null;f=r.exec(n)){let o=f.index,h=o+f[0].length;if(vi(o,h,t))continue;let u=/<invoke\s+name="([^"]+)"\s*>([\s\S]*?)<\/invoke>/g,c=[];for(let _=u.exec(f[0]);_!==null;_=u.exec(f[0])){let w=_[1];if(w)c.push(dy(w,_[2]??""))}if(c.length===0)continue;s.push({start:o,end:h,toolCalls:c}),i.push([o,h])}let e=/<invoke\s+name="([^"]+)"\s*>([\s\S]*?)<\/invoke>/g;for(let f=e.exec(n);f!==null;f=e.exec(n)){let o=f.index,h=o+f[0].length,u=f[1];if(!u||vi(o,h,t)||vi(o,h,i))continue;s.push({start:o,end:h,toolCalls:[dy(u,f[2]??"")]}),i.push([o,h])}return s}function TX(n,t,i){let s=[],r=0;for(;;){let e=n.indexOf(de,r);if(e===-1)break;let f=n.slice(e+de.length),o=/<\uFF5C[^>]*?end[^>]*?>|<\/\uFF5CDSML[^>]*?>/.exec(f),h=o!==null?e+de.length+o.index+o[0].length:n.length;if(r=h,vi(e,h,t)||vi(e,h,i))continue;let u=n.slice(e,h),c=[],_=/name["\uFF5C=:\s]+["']?([A-Za-z0-9_]+)/.exec(u),w=/(\{[\s\S]*\})/.exec(u);if(_?.[1]&&w?.[1])try{c.push({toolUseId:D_(),name:_[1],input:JSON.parse(w[1])})}catch{}s.push({start:e,end:h,toolCalls:c}),i.push([e,h])}return s}function gX(n,t,i){let s=[],r=/\[Called\s+(\w+)\s+with\s+args:\s*(\{[^}]*(?:\{[^}]*\}[^}]*)*\})\]/gs;for(let e=r.exec(n);e!==null;e=r.exec(n)){let f=e.index,o=f+e[0].length,h=e[1],u=e[2];if(!h||!u||vi(f,o,t)||vi(f,o,i))continue;let c;try{c=JSON.parse(u)}catch{continue}s.push({start:f,end:o,toolCalls:[{toolUseId:D_(),name:h,input:c}]}),i.push([f,o])}return s}function Ry(n){if(!n)return{toolCalls:[],cleanedText:n};let t=RX(n),i=[],s=[...yX(n,t,i),...TX(n,t,i),...gX(n,t,i)];if(s.length===0)return{toolCalls:[],cleanedText:n};s.sort((o,h)=>o.start-h.start);let r=[],e="",f=0;for(let o of s){if(o.start<f)continue;e+=n.slice(f,o.start),f=o.end,r.push(...o.toolCalls)}return e+=n.slice(f),{toolCalls:r,cleanedText:e}}var Y_=["<function_calls","<invoke name=",de],SX=Math.max(...Y_.map((n)=>n.length));function Ey(n){let t=-1;for(let i of Y_){let s=n.indexOf(i);if(s!==-1&&(t===-1||s<t))t=s}return t}function IX(n){let t=Math.min(n.length,SX-1);for(let i=t;i>0;i--){let s=n.slice(n.length-i);for(let r of Y_)if(r.length>i&&r.startsWith(s))return i}return 0}class m_{accumulated="";emitted=0;markerSeen=!1;ingest(n){if(!n)return"";if(this.accumulated+=n,!this.markerSeen&&Ey(this.accumulated)!==-1)this.markerSeen=!0;let t;if(this.markerSeen){let s=Ey(this.accumulated);t=s===-1?this.accumulated.length:s}else t=this.accumulated.length-IX(this.accumulated);if(t<=this.emitted)return"";let i=this.accumulated.slice(this.emitted,t);return this.emitted=t,i}get suppressing(){return this.markerSeen}finalize(){let{toolCalls:n,cleanedText:t}=Ry(this.accumulated),i=t.length>this.emitted?t.slice(this.emitted):"";return{toolCalls:n,remainderText:i}}}function J_(n,t,i){let s=[];if(n.type==="content_block_delta"){if(n.delta?.type==="text_delta")s.push({index:0,delta:{content:n.delta.text??""},finish_reason:null});else if(n.delta?.type==="thinking_delta"){if(n.delta.thinking)s.push({index:0,delta:{reasoning_content:n.delta.thinking},finish_reason:null})}else if(n.delta?.type==="input_json_delta")s.push({index:0,delta:{tool_calls:[{index:n.index,function:{arguments:n.delta.partial_json??""}}]},finish_reason:null})}else if(n.type==="content_block_start"&&n.content_block?.type==="tool_use")s.push({index:0,delta:{tool_calls:[{index:n.index,id:n.content_block.id,type:"function",function:{name:n.content_block.name,arguments:""}}]},finish_reason:null});else if(n.type==="message_delta")s.push({index:0,delta:{},finish_reason:n.delta?.stop_reason==="tool_use"?"tool_calls":"stop"});else return null;if(s.length===0)return null;let r={id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1000),model:i,choices:s};if(n.type!=="message_delta")return r;let e=n.usage?.input_tokens??0,f=n.usage?.output_tokens??0;return{...r,usage:{prompt_tokens:e,completion_tokens:f,total_tokens:e+f}}}function X_(n,t){let i=/```[\s\S]*?```/g,s=[],r=i.exec(n);while(r!==null)s.push([r.index,r.index+r[0].length]),r=i.exec(n);let e=n.indexOf(t,0);while(e!==-1){if(!s.some(([o,h])=>e>=o&&e<h))return e;e=n.indexOf(t,e+t.length)}return-1}function yy(n,t){if(n==="thinking"){if(t.thinkingBlockIndex!==null)return[];let s=t.nextBlockIndex++;return t.thinkingBlockIndex=s,[{type:"content_block_start",index:s,content_block:{type:"thinking",thinking:""}}]}if(t.textBlockIndex!==null)return[];let i=t.nextBlockIndex++;return t.textBlockIndex=i,[{type:"content_block_start",index:i,content_block:{type:"text",text:""}}]}function Zi(n,t){if(n===null||t.stoppedBlocks.has(n))return[];return t.stoppedBlocks.add(n),[{type:"content_block_stop",index:n}]}function Ri(n,t){if(!n)return[];let i=yy("text",t),s=t.textBlockIndex;if(s===null)return i;return i.push({type:"content_block_delta",index:s,delta:{type:"text_delta",text:n}}),i}function Ei(n,t){let i=yy("thinking",t),s=t.thinkingBlockIndex;if(s===null)return i;return i.push({type:"content_block_delta",index:s,delta:{type:"thinking_delta",thinking:n}}),i}var zf="<thinking>",Qf="</thinking>";function Ty(n,t){t.buffer+=n;let i=[];while(t.buffer.length>0){if(!t.inThinking&&!t.thinkingExtracted){let r=X_(t.buffer,zf);if(r!==-1){let f=t.buffer.slice(0,r);i.push(...Ri(f,t)),t.buffer=t.buffer.slice(r+zf.length),t.inThinking=!0;continue}let e=Math.max(0,t.buffer.length-zf.length);if(e>0)i.push(...Ri(t.buffer.slice(0,e),t)),t.buffer=t.buffer.slice(e);break}if(t.inThinking){let r=X_(t.buffer,Qf);if(r!==-1){if(i.push(...Ei(t.buffer.slice(0,r),t)),t.buffer=t.buffer.slice(r+Qf.length),t.inThinking=!1,t.thinkingExtracted=!0,i.push(...Ei("",t)),i.push(...Zi(t.thinkingBlockIndex,t)),t.buffer.startsWith(`
|
|
287
|
+
`}import{createHash as b5,timingSafeEqual as N5}from"crypto";function fn(n,t,i,r,s){let f={message:t,type:i};if(r!==void 0)f.code=r;if(s!==void 0)f.param=s;return new Response(JSON.stringify({error:f}),{status:n,headers:{"Content-Type":"application/json"}})}var cy="Bearer ";function oy(n,t){let i=Buffer.from(n);for(let r of t){let s=Buffer.from(r);if(i.byteLength===s.byteLength&&N5(i,s))return r}return}function wy(n){return b5("sha256").update("kiro-provider-tenant-v1\x00").update(n).digest("hex")}function ic(n,t,i=fn){let r=n.headers.get("Authorization");if(r===null){let h=n.headers.get("x-api-key"),_=h===null?void 0:oy(h,t);if(_!==void 0)return{ok:!0,tenantId:wy(_)};return{ok:!1,response:i(401,"Missing Authorization or x-api-key header.","authentication_error","missing_api_key")}}if(!r.startsWith(cy))return{ok:!1,response:i(401,"Authorization header must use the Bearer scheme.","authentication_error","invalid_api_key")};let s=r.slice(cy.length),f=oy(s,t);if(f===void 0)return{ok:!1,response:i(401,"Incorrect API key provided.","authentication_error","invalid_api_key")};return{ok:!0,tenantId:wy(f)}}var bi=k(gt(),1);var Mf=k(gt(),1);var Ef=k(gt(),1);var ii=k(gt(),1);var it=k(gt(),1);var un=k(xn(),1);var ys=k(Ui(),1),U4=k(Ei(),1);var Yo=k(z_(),1);var Tf=k(kn(),1);var ht=k(vi(),1);var yn=k(Af(),1);var rn=k(at(),1);var is=k(Ui(),1);var ts=k(at(),1);var E1=async(n,t,i)=>{return{operation:ts.getSmithyContext(t).operation}};function h7(n){return{schemeId:"smithy.api#httpBearerAuth",propertiesExtractor:({profile:t,filepath:i,configFilepath:r,ignoreCache:s},f)=>({identityProperties:{profile:t,filepath:i,configFilepath:r,ignoreCache:s}})}}var T1=(n)=>{let t=[];switch(n.operation){default:t.push(h7(n))}return t},g1=(n)=>{let t=is.memoizeIdentityProvider(n.token,is.isIdentityExpired,is.doesIdentityRequireRefresh);return Object.assign(n,{authSchemePreference:ts.normalizeProvider(n.authSchemePreference??[]),token:t})};var S1=(n)=>{return Object.assign(n,{useDualstackEndpoint:n.useDualstackEndpoint??!1,useFipsEndpoint:n.useFipsEndpoint??!1,defaultSigningName:"amazoncodewhispererstreamingservice"})},L1={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};var $1={name:"@aws/codewhisperer-streaming-client",description:"@aws/codewhisperer-streaming-client",version:"1.0.45",scripts:{build:"concurrently 'npm:build:cjs' 'npm:build:es' 'npm:build:types'","build:cjs":"tsc -p tsconfig.cjs.json","build:es":"tsc -p tsconfig.es.json","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4",clean:"premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo",prepack:"npm run clean && npm run build"},main:"./dist-cjs/index.js",types:"./dist-types/index.d.ts",module:"./dist-es/index.js",sideEffects:!1,dependencies:{tslib:"^2.6.2","@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"^3.974.7","@aws-sdk/middleware-host-header":"^3.972.10","@aws-sdk/middleware-logger":"^3.972.10","@aws-sdk/middleware-recursion-detection":"^3.972.11","@aws-sdk/middleware-user-agent":"^3.972.37","@aws-sdk/region-config-resolver":"^3.972.13","@aws-sdk/token-providers":"^3.1040.0","@aws-sdk/types":"^3.973.8","@aws-sdk/util-endpoints":"^3.996.8","@aws-sdk/util-user-agent-browser":"^3.972.10","@aws-sdk/util-user-agent-node":"^3.973.23","@smithy/config-resolver":"^4.4.17","@smithy/core":"^3.23.17","@smithy/eventstream-serde-browser":"^4.2.14","@smithy/eventstream-serde-config-resolver":"^4.3.14","@smithy/eventstream-serde-node":"^4.2.14","@smithy/fetch-http-handler":"^5.3.17","@smithy/hash-node":"^4.2.14","@smithy/invalid-dependency":"^4.2.14","@smithy/middleware-content-length":"^4.2.14","@smithy/middleware-endpoint":"^4.4.32","@smithy/middleware-retry":"^4.5.7","@smithy/middleware-serde":"^4.2.20","@smithy/middleware-stack":"^4.2.14","@smithy/node-config-provider":"^4.3.14","@smithy/node-http-handler":"^4.6.1","@smithy/protocol-http":"^5.3.14","@smithy/smithy-client":"^4.12.13","@smithy/types":"^4.14.1","@smithy/url-parser":"^4.2.14","@smithy/util-base64":"^4.3.2","@smithy/util-body-length-browser":"^4.2.2","@smithy/util-body-length-node":"^4.2.3","@smithy/util-defaults-mode-browser":"^4.3.49","@smithy/util-defaults-mode-node":"^4.2.54","@smithy/util-endpoints":"^3.4.2","@smithy/util-middleware":"^4.2.14","@smithy/util-retry":"^4.3.6","@smithy/util-utf8":"^4.2.2"},devDependencies:{"@tsconfig/node20":"20.1.8",concurrently:"7.0.0","downlevel-dts":"0.10.1",premove:"4.0.0",typescript:"~5.8.3","@types/node":"^20.14.8"},engines:{node:">=20.0.0"},typesVersions:{"<4.5":{"dist-types/*":["dist-types/ts3.4/*"]}},files:["dist-*/**"],browser:{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.browser"},"react-native":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.native"},license:"Apache-2.0"};var E4=k(gt(),1),T4=k(qo(),1);var ws=k(xn(),1);var mn=k(xn(),1);var cM=300000,ss="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var XE=async(n,t={},i)=>{let{SSOOIDCClient:r}=await Promise.resolve().then(() => k(Ww(),1)),s=(h)=>t.clientConfig?.[h]??t.parentClientConfig?.[h]??i?.[h];return new r(Object.assign({},t.clientConfig??{},{region:n??t.clientConfig?.region,logger:s("logger"),userAgentAppId:s("userAgentAppId")}))};var lE=async(n,t,i={},r)=>{let{CreateTokenCommand:s}=await Promise.resolve().then(() => k(Ww(),1));return(await XE(t,i,r)).send(new s({clientId:n.clientId,clientSecret:n.clientSecret,refreshToken:n.refreshToken,grantType:"refresh_token"}))};var JE=k(xn(),1);var Dw=(n)=>{if(n.expiration&&n.expiration.getTime()<Date.now())throw new JE.TokenProviderError(`Token is expired. ${ss}`,!1)};var QE=k(xn(),1);var Ii=(n,t,i=!1)=>{if(typeof t>"u")throw new QE.TokenProviderError(`Value not present for '${n}' in SSO Token${i?". Cannot refresh":""}. ${ss}`,!1)};var zE=k(xn(),1);import{promises as Wl}from"fs";var{writeFile:Dl}=Wl,CE=(n,t)=>{let i=zE.getSSOTokenFilepath(n),r=JSON.stringify(t,null,2);return Dl(i,r)};var VE=new Date(0),KE=(n={})=>async({callerClientConfig:t}={})=>{n.logger?.debug("@aws-sdk/token-providers - fromSso");let i=await mn.parseKnownFiles(n),r=mn.getProfileName({profile:n.profile??t?.profile}),s=i[r];if(!s)throw new mn.TokenProviderError(`Profile '${r}' could not be found in shared credentials file.`,!1);else if(!s.sso_session)throw new mn.TokenProviderError(`Profile '${r}' is missing required property 'sso_session'.`);let f=s.sso_session,_=(await mn.loadSsoSessionData(n))[f];if(!_)throw new mn.TokenProviderError(`Sso session '${f}' could not be found in shared credentials file.`,!1);for(let A of["sso_start_url","sso_region"])if(!_[A])throw new mn.TokenProviderError(`Sso session '${f}' is missing required property '${A}'.`,!1);let{sso_start_url:c,sso_region:o}=_,w;try{w=await mn.getSSOTokenFromFile(f)}catch(A){throw new mn.TokenProviderError(`The SSO session token associated with profile=${r} was not found or is invalid. ${ss}`,!1)}Ii("accessToken",w.accessToken),Ii("expiresAt",w.expiresAt);let{accessToken:e,expiresAt:u}=w,y={token:e,expiration:new Date(u)};if(y.expiration.getTime()-Date.now()>cM)return y;if(Date.now()-VE.getTime()<30000)return Dw(y),y;Ii("clientId",w.clientId,!0),Ii("clientSecret",w.clientSecret,!0),Ii("refreshToken",w.refreshToken,!0);try{VE.setTime(Date.now());let A=await lE(w,o,n,t);Ii("accessToken",A.accessToken),Ii("expiresIn",A.expiresIn);let R=new Date(Date.now()+A.expiresIn*1000);try{await CE(f,{...w,accessToken:A.accessToken,expiresAt:R.toISOString(),refreshToken:A.refreshToken})}catch(M){}return{token:A.accessToken,expiration:R}}catch(A){return Dw(y),y}};var Pw=(n={})=>ws.memoize(ws.chain(KE(n),async()=>{throw new ws.TokenProviderError("Could not load token from any providers",!1)}),(t)=>t.expiration!==void 0&&t.expiration.getTime()-Date.now()<300000,(t)=>t.expiration!==void 0);var Ct=k(gt(),1);var g4=k(Ui(),1);var Wh=k(z_(),1);var Yw=k(jn(),1);var ri=k(xn(),1);var xh=k(wh(),1);var Fw=k(jn(),1);var Xw=k(xn(),1);var Bn=k(Af(),1);var A4=k(bw(),1),R4=k(Ui(),1);var lw=k(kn(),1);var es=k(jn(),1);var hr=k(jn(),1);var Qn=k(vi(),1);var If="ref",cr=-1,Dh=!0,xE="isSet",mE="PartitionResult",Ph="booleanEquals",Jw="getAttr",jE={[If]:"Endpoint"},Qw={[If]:mE},us={},kE=[{[If]:"Region"}],qE={conditions:[[xE,[jE]],[xE,kE],["aws.partition",kE,mE],[Ph,[{[If]:"UseFIPS"},Dh]],[Ph,[{[If]:"UseDualStack"},Dh]],[Ph,[{fn:Jw,argv:[Qw,"supportsDualStack"]},Dh]],[Ph,[{fn:Jw,argv:[Qw,"supportsFIPS"]},Dh]],["stringEquals",[{fn:Jw,argv:[Qw,"name"]},"aws-us-gov"]]],results:[[cr],[cr,"Invalid Configuration: FIPS and custom endpoint are not supported"],[cr,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[jE,us],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",us],[cr,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://amazoncodewhispererstreamingservice.{Region}.amazonaws.com",us],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dnsSuffix}",us],[cr,"FIPS is enabled but this partition does not support FIPS"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dualStackDnsSuffix}",us],[cr,"DualStack is enabled but this partition does not support DualStack"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dnsSuffix}",us],[cr,"Invalid Configuration: Missing Region"]]},Pl=2,Zn=1e8,Yl=new Int32Array([-1,1,-1,0,13,3,1,4,Zn+12,2,5,Zn+12,3,8,6,4,7,Zn+11,5,Zn+9,Zn+10,4,11,9,6,10,Zn+8,7,Zn+6,Zn+7,5,12,Zn+5,6,Zn+4,Zn+5,3,Zn+1,14,4,Zn+2,Zn+3]),ZE=Qn.BinaryDecisionDiagram.from(Yl,Pl,qE.conditions,qE.results);var Fl=new Qn.EndpointCache({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),aE=(n,t={})=>{return Fl.get(n,()=>Qn.decideEndpoint(ZE,{endpointParams:n,logger:t.logger}))};Qn.customEndpointFunctions.aws=it.awsEndpointFunctions;var Vw=k(Ei(),1);class an extends rn.ServiceException{constructor(n){super(n);Object.setPrototypeOf(this,an.prototype)}}class Yh extends an{name="AccessDeniedException";$fault="client";reason;constructor(n){super({name:"AccessDeniedException",$fault:"client",...n});Object.setPrototypeOf(this,Yh.prototype),this.reason=n.reason}}class Fh extends an{name="ConflictException";$fault="client";reason;constructor(n){super({name:"ConflictException",$fault:"client",...n});Object.setPrototypeOf(this,Fh.prototype),this.reason=n.reason}}class Xh extends an{name="InternalServerException";$fault="server";$retryable={};reason;constructor(n){super({name:"InternalServerException",$fault:"server",...n});Object.setPrototypeOf(this,Xh.prototype),this.reason=n.reason}}class lh extends an{name="ThrottlingException";$fault="client";$retryable={throttling:!0};reason;constructor(n){super({name:"ThrottlingException",$fault:"client",...n});Object.setPrototypeOf(this,lh.prototype),this.reason=n.reason}}class Jh extends an{name="ValidationException";$fault="client";reason;constructor(n){super({name:"ValidationException",$fault:"client",...n});Object.setPrototypeOf(this,Jh.prototype),this.reason=n.reason}}class Qh extends an{name="ResourceNotFoundException";$fault="client";constructor(n){super({name:"ResourceNotFoundException",$fault:"client",...n});Object.setPrototypeOf(this,Qh.prototype)}}class zh extends an{name="ServiceUnavailableException";$fault="server";constructor(n){super({name:"ServiceUnavailableException",$fault:"server",...n});Object.setPrototypeOf(this,zh.prototype)}}class Ch extends an{name="ServiceQuotaExceededException";$fault="client";reason;constructor(n){super({name:"ServiceQuotaExceededException",$fault:"client",...n});Object.setPrototypeOf(this,Ch.prototype),this.reason=n.reason}}class Vh extends an{name="DryRunOperationException";$fault="client";responseCode;constructor(n){super({name:"DryRunOperationException",$fault:"client",...n});Object.setPrototypeOf(this,Vh.prototype),this.responseCode=n.responseCode}}var vE=Vw.TypeRegistry.for("smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming"),Xl=[-3,"smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming","CodeWhispererStreamingServiceException",0,[],[]];vE.registerError(Xl,an);var Vt=Vw.TypeRegistry.for("com.amazon.aws.codewhisperer"),ll=[-3,"com.amazon.aws.codewhisperer","AccessDeniedException",{["error"]:"client",["httpError"]:403},["message","reason"],[0,0],1];Vt.registerError(ll,Yh);var Jl=[-3,"com.amazon.aws.codewhisperer","ConflictException",{["error"]:"client",["httpError"]:409},["message","reason"],[0,0],1];Vt.registerError(Jl,Fh);var Ql=[-3,"com.amazon.aws.codewhisperer","DryRunOperationException",{["error"]:"client"},["message","responseCode"],[0,[1,32]]];Vt.registerError(Ql,Vh);var pE=[-3,"com.amazon.aws.codewhisperer","InternalServerException",{["error"]:"server",["httpError"]:500},["message","reason"],[0,0],1];Vt.registerError(pE,Xh);var zl=[-3,"com.amazon.aws.codewhisperer","ResourceNotFoundException",{["error"]:"client",["httpError"]:404},["message"],[0],1];Vt.registerError(zl,Qh);var Cl=[-3,"com.amazon.aws.codewhisperer","ServiceQuotaExceededException",{["error"]:"client",["httpError"]:402},["message","reason"],[0,0],1];Vt.registerError(Cl,Ch);var Vl=[-3,"com.amazon.aws.codewhisperer","ServiceUnavailableException",{["error"]:"server",["httpError"]:503},["message"],[0],1];Vt.registerError(Vl,zh);var Kl=[-3,"com.amazon.aws.codewhisperer","ThrottlingException",{["error"]:"client",["httpError"]:429},["message","reason"],[0,0],1];Vt.registerError(Kl,lh);var xl=[-3,"com.amazon.aws.codewhisperer","ValidationException",{["error"]:"client",["httpError"]:400},["message","reason"],[0,0],1];Vt.registerError(xl,Jh);var n4=[vE,Vt];var Kw=[0,"com.amazon.aws.codewhisperer","SensitiveDocument",8,15],J=[0,"com.amazon.aws.codewhisperer","SensitiveString",8,0],jl=[0,"com.amazon.aws.codewhisperer","ToolDescription",8,0],Kh=[0,"com.amazon.aws.codewhisperer","ToolName",8,0],wn=[0,"com.amazon.aws.q","SensitiveString",8,0],kl=[3,"com.amazon.aws.codewhisperer","AdditionalContentEntry",0,["name","description","innerContext"],[[()=>J,0],[()=>J,0],[()=>J,0]],2],ql=[3,"com.amazon.aws.codewhisperer","AppStudioState",0,["namespace","propertyName","propertyContext","propertyValue"],[[()=>J,0],[()=>J,0],[()=>J,0],[()=>J,0]],3],ml=[3,"com.amazon.aws.codewhisperer","AssistantResponseEvent",0,["content","modelId"],[[()=>J,0],0],1],Zl=[3,"com.amazon.aws.codewhisperer","AssistantResponseMessage",0,["content","messageId","supplementaryWebLinks","references","followupPrompt","toolUses","cachePoint","reasoningContent"],[[()=>J,0],0,[()=>u4,0],()=>e4,[()=>t4,0],[()=>IQ,0],()=>xw,[()=>pQ,0]],1];var xw=[3,"com.amazon.aws.codewhisperer","CachePoint",0,["type"],[0],1],al=[3,"com.amazon.aws.codewhisperer","CitationEvent",0,["target","citationLink","citationText"],[()=>jQ,[()=>J,0],[()=>J,0]],2],vl=[3,"com.amazon.aws.codewhisperer","ClientCacheConfig",0,["useClientCachingOnly"],[2]],pl=[3,"com.amazon.aws.codewhisperer","CodeDescription",0,["href"],[[()=>J,0]],1],nJ=[3,"com.amazon.aws.codewhisperer","CodeEvent",0,["content"],[[()=>J,0]],1],tJ=[3,"com.amazon.aws.codewhisperer","CodeReferenceEvent",0,["references"],[()=>e4]],iJ=[3,"com.amazon.aws.codewhisperer","ConsoleState",0,["region","consoleUrl","serviceId","serviceConsolePage","serviceSubconsolePage","taskName","uxErrorMessage"],[0,[()=>J,0],0,0,0,[()=>J,0],[()=>J,0]]],rJ=[3,"com.amazon.aws.codewhisperer","ContextUsageEvent",0,["contextUsagePercentage"],[1]],sJ=[3,"com.amazon.aws.codewhisperer","ConversationState",0,["currentMessage","chatTriggerType","conversationId","workspaceId","history","customizationArn","agentContinuationId","agentTaskType"],[[()=>y4,0],0,0,0,[()=>EQ,0],0,0,0],2],fJ=[3,"com.amazon.aws.codewhisperer","DiagnosticLocation",0,["uri","range"],[[()=>J,0],()=>jw],2],_J=[3,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformation",0,["location","message"],[[()=>fJ,0],[()=>J,0]],2],hJ=[3,"com.amazon.aws.codewhisperer","DocumentBlock",0,["name","format","source"],[0,0,[()=>ZQ,0]],3],cJ=[3,"com.amazon.aws.codewhisperer","DocumentCitationEvent",0,["source","title","location","sourceContent"],[[()=>J,0],[()=>J,0],[()=>mQ,0],[()=>SQ,0]]],oJ=[3,"com.amazon.aws.codewhisperer","DocumentCitationSearchResultSpan",0,["searchResultIndex","start","end"],[1,1,1]],wJ=[3,"com.amazon.aws.codewhisperer","DocumentCitationSourceContent",0,["text"],[[()=>J,0]]],zw=[3,"com.amazon.aws.codewhisperer","DocumentCitationSpan",0,["documentIndex","start","end"],[1,1,1]],eJ=[3,"com.amazon.aws.codewhisperer","DocumentCitationWebLocation",0,["url","domain"],[[()=>J,0],[()=>J,0]]],uJ=[3,"com.amazon.aws.codewhisperer","DocumentSymbol",0,["name","type","source"],[0,0,0],2],yJ=[3,"com.amazon.aws.codewhisperer","DryRunSucceedEvent",0,[],[]],dJ=[3,"com.amazon.aws.codewhisperer","EditorState",0,["document","cursorState","relevantDocuments","useRelevantDocuments","workspaceFolders"],[[()=>s4,0],()=>kQ,[()=>OQ,0],2,[()=>HQ,0]]],AJ=[3,"com.amazon.aws.codewhisperer","EnvironmentVariable",0,["key","value"],[[()=>J,0],[()=>J,0]]],RJ=[3,"com.amazon.aws.codewhisperer","EnvState",0,["operatingSystem","currentWorkingDirectory","environmentVariables","timezoneOffset"],[0,[()=>J,0],[()=>LQ,0],1]],t4=[3,"com.amazon.aws.codewhisperer","FollowupPrompt",0,["content","userIntent"],[[()=>J,0],0],1],MJ=[3,"com.amazon.aws.codewhisperer","FollowupPromptEvent",0,["followupPrompt"],[[()=>t4,0]]],EJ=[3,"com.amazon.aws.codewhisperer","GitState",0,["status"],[[()=>J,0]]],TJ=[3,"com.amazon.aws.codewhisperer","ImageBlock",0,["format","source"],[0,[()=>aQ,0]],2],gJ=[3,"com.amazon.aws.codewhisperer","IntentsEvent",0,["intents"],[[()=>VQ,0]]],SJ=[3,"com.amazon.aws.codewhisperer","InvalidStateEvent",0,["reason","message"],[0,0],2],LJ=[3,"com.amazon.aws.codewhisperer","MessageMetadataEvent",0,["conversationId","utteranceId"],[0,0]],$J=[3,"com.amazon.aws.codewhisperer","MetadataEvent",0,["tokenUsage"],[()=>VJ]],OJ=[3,"com.amazon.aws.codewhisperer","MeteringEvent",0,["usage","unit","unitPlural"],[1,0,0]],Cw=[3,"com.amazon.aws.codewhisperer","Position",0,["line","character"],[1,1],2],i4=[3,"com.amazon.aws.codewhisperer","ProgrammingLanguage",0,["languageName"],[0],1],jw=[3,"com.amazon.aws.codewhisperer","Range",0,["start","end"],[()=>Cw,()=>Cw],2],UJ=[3,"com.amazon.aws.codewhisperer","ReasoningContentEvent",8,["text","redactedContent","signature"],[[()=>J,0],21,[()=>J,0]]],bJ=[3,"com.amazon.aws.codewhisperer","ReasoningText",8,["text","signature"],[[()=>J,0],[()=>J,0]],1],NJ=[3,"com.amazon.aws.codewhisperer","Reference",0,["licenseName","repository","url","recommendationContentSpan"],[0,0,0,()=>r4]],BJ=[3,"com.amazon.aws.codewhisperer","RelevantTextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols","type"],[[()=>J,0],()=>i4,[()=>J,0],()=>w4,0],1],IJ=[3,"com.amazon.aws.codewhisperer","RuntimeDiagnostic",0,["source","severity","message"],[[()=>J,0],0,[()=>J,0]],3],HJ=[3,"com.amazon.aws.codewhisperer","ShellHistoryEntry",0,["command","directory","exitCode","stdout","stderr"],[[()=>J,0],[()=>J,0],1,[()=>J,0],[()=>J,0]],1],GJ=[3,"com.amazon.aws.codewhisperer","ShellState",0,["shellName","shellHistory"],[0,[()=>UQ,0]],1],r4=[3,"com.amazon.aws.codewhisperer","Span",0,["start","end"],[1,1]],WJ=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLink",0,["url","title","snippet"],[[()=>J,0],[()=>J,0],[()=>J,0]],2],DJ=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLinksEvent",0,["supplementaryWebLinks"],[[()=>u4,0]]],s4=[3,"com.amazon.aws.codewhisperer","TextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols"],[[()=>J,0],()=>i4,[()=>J,0],()=>w4],1],PJ=[3,"com.amazon.aws.codewhisperer","TextDocumentDiagnostic",0,["document","range","source","severity","message","code","codeDescription","tags","relatedInformation","data"],[[()=>s4,0],()=>jw,[()=>J,0],0,[()=>J,0],[()=>J,0],[()=>pl,0],64,[()=>TQ,0],[()=>J,0]],5],YJ=[3,"com.amazon.aws.codewhisperer","ToolInputSchema",0,["json"],[[()=>Kw,0]]],f4=[3,"com.amazon.aws.codewhisperer","ToolResult",0,["toolUseId","content","status","toolName"],[0,[()=>bQ,0],0,[()=>Kh,0]],2],FJ=[3,"com.amazon.aws.codewhisperer","ToolResultEvent",0,["toolResult"],[[()=>f4,0]]],XJ=[3,"com.amazon.aws.codewhisperer","ToolSpecification",0,["inputSchema","name","description"],[[()=>YJ,0],[()=>Kh,0],[()=>jl,0]],2],lJ=[3,"com.amazon.aws.codewhisperer","ToolUse",0,["toolUseId","name","input"],[0,[()=>Kh,0],[()=>Kw,0]],3],JJ=[3,"com.amazon.aws.codewhisperer","ToolUseEvent",0,["toolUseId","name","input","stop"],[0,[()=>Kh,0],[()=>J,0],2],2];var QJ=[3,"com.amazon.aws.codewhisperer","UserInputMessage",0,["content","userInputMessageContext","userIntent","origin","images","documents","modelId","cachePoint","clientCacheConfig"],[[()=>J,0],[()=>zJ,0],0,0,[()=>$Q,0],[()=>gQ,0],0,()=>xw,()=>vl],1],zJ=[3,"com.amazon.aws.codewhisperer","UserInputMessageContext",0,["editorState","shellState","gitState","envState","appStudioContext","diagnostic","consoleState","userSettings","additionalContext","toolResults","tools"],[[()=>dJ,0],[()=>GJ,0],[()=>EJ,0],[()=>RJ,0],[()=>ql,0],[()=>qQ,0],[()=>iJ,0],()=>CJ,[()=>MQ,0],[()=>NQ,0],[()=>BQ,0]]],CJ=[3,"com.amazon.aws.codewhisperer","UserSettings",0,["hasConsentedToCrossRegionCalls"],[2]];var VJ=[3,"com.amazon.aws.codewhisperer.internal","TokenUsage",0,["uncachedInputTokens","outputTokens","totalTokens","cacheReadInputTokens","cacheWriteInputTokens","contextUsagePercentage","normalizedTokenUsage"],[1,1,1,1,1,1,1],3];var KJ=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseRequest",0,["conversationState","profileArn","agentMode","additionalModelRequestFields"],[[()=>sJ,0],0,[0,{["httpHeader"]:"x-amzn-kiro-agent-mode"}],15],1],xJ=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseResponse",0,["conversationId","generateAssistantResponseResponse"],[[0,{["httpHeader"]:"x-amzn-codewhisperer-conversation-id"}],[()=>xQ,16]],2];var jJ=[3,"com.amazon.aws.q","InteractionComponentsEvent",0,["interactionComponentEntries"],[[()=>PQ,0]],1],kw=[3,"com.amazon.aws.q.interactioncomponents","Action",0,["webLink","moduleLink"],[[()=>RQ,0],[()=>iQ,0]]],qw=[3,"com.amazon.aws.q.interactioncomponents","Alert",0,["type","content"],[0,[()=>GQ,0]],2],kJ=[3,"com.amazon.aws.q.interactioncomponents","AlertComponent",0,["text"],[[()=>Hf,0]]],qJ=[3,"com.amazon.aws.q.interactioncomponents","Clarification",0,["questions","dismissible"],[[()=>DQ,0],2],1],mJ=[3,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOption",0,["label","value"],[[()=>wn,0],[()=>wn,0]],2],ZJ=[3,"com.amazon.aws.q.interactioncomponents","ClarificationQuestion",0,["question","options","allowCustom","skippable"],[[()=>wn,0],[()=>WQ,0],2,2],2],aJ=[3,"com.amazon.aws.q.interactioncomponents","CloudWatchTroubleshootingLink",0,["label","investigationPayload","defaultText"],[[()=>wn,0],[()=>wn,0],[()=>wn,0]],2],_4=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdate",0,["transition"],[[()=>vJ,0]]],vJ=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdateTransition",0,["currentState","nextState"],[[()=>wn,0],[()=>wn,0]],2],pJ=[3,"com.amazon.aws.q.interactioncomponents","InlineArtifact",0,["dsl","summary","title","artifactLabel"],[[()=>wn,0],[()=>wn,0],[()=>wn,0],[()=>wn,0]],4],nQ=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponent",0,["text","alert","infrastructureUpdate","progress","step","taskDetails","taskReference","suggestions","section","resource","resourceList","action","clarification","inlineArtifact"],[[()=>Hf,0],[()=>qw,0],[()=>_4,0],[()=>h4,0],[()=>o4,0],[()=>yQ,0],()=>AQ,[()=>cQ,0],[()=>sQ,0],[()=>mw,0],[()=>c4,0],[()=>kw,0],[()=>qJ,0],[()=>pJ,0]]],tQ=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntry",0,["interactionComponent","interactionComponentId"],[[()=>nQ,0],0],1],iQ=[3,"com.amazon.aws.q.interactioncomponents","ModuleLink",0,["cloudWatchTroubleshootingLink"],[[()=>aJ,0]]],h4=[3,"com.amazon.aws.q.interactioncomponents","Progress",0,["content"],[[()=>YQ,0]],1],rQ=[3,"com.amazon.aws.q.interactioncomponents","ProgressComponent",0,["step"],[[()=>o4,0]]],mw=[3,"com.amazon.aws.q.interactioncomponents","Resource",0,["title","link","description","type","ARN","resourceJsonString"],[[()=>wn,0],[()=>wn,0],[()=>wn,0],[()=>wn,0],[()=>wn,0],[()=>wn,0]],6],c4=[3,"com.amazon.aws.q.interactioncomponents","ResourceList",0,["items","action"],[[()=>FQ,0],[()=>kw,0]],1],sQ=[3,"com.amazon.aws.q.interactioncomponents","Section",0,["title","content","action"],[[()=>wn,0],[()=>XQ,0],[()=>kw,0]],2],fQ=[3,"com.amazon.aws.q.interactioncomponents","SectionComponent",0,["text","alert","resource","resourceList"],[[()=>Hf,0],[()=>qw,0],[()=>mw,0],[()=>c4,0]]],o4=[3,"com.amazon.aws.q.interactioncomponents","Step",0,["id","state","label","content"],[1,0,[()=>wn,0],[()=>lQ,0]],3],_Q=[3,"com.amazon.aws.q.interactioncomponents","StepComponent",0,["text"],[[()=>Hf,0]]],hQ=[3,"com.amazon.aws.q.interactioncomponents","Suggestion",0,["value"],[[()=>wn,0]],1],cQ=[3,"com.amazon.aws.q.interactioncomponents","Suggestions",0,["items"],[[()=>JQ,0]],1],oQ=[3,"com.amazon.aws.q.interactioncomponents","TaskAction",0,["label","payload","note","primary","disabled","confirmation"],[[()=>wn,0],[()=>KQ,0],[()=>eQ,0],2,2,[()=>wQ,0]],2],wQ=[3,"com.amazon.aws.q.interactioncomponents","TaskActionConfirmation",0,["content"],[[()=>wn,0]]],eQ=[3,"com.amazon.aws.q.interactioncomponents","TaskActionNote",0,["content","type"],[[()=>wn,0],0],1],uQ=[3,"com.amazon.aws.q.interactioncomponents","TaskComponent",0,["text","infrastructureUpdate","alert","progress"],[[()=>Hf,0],[()=>_4,0],[()=>qw,0],[()=>h4,0]]],yQ=[3,"com.amazon.aws.q.interactioncomponents","TaskDetails",0,["overview","content","actions"],[[()=>dQ,0],[()=>zQ,0],[()=>QQ,0]],2],dQ=[3,"com.amazon.aws.q.interactioncomponents","TaskOverview",0,["label","description"],[[()=>wn,0],[()=>wn,0]],2],AQ=[3,"com.amazon.aws.q.interactioncomponents","TaskReference",0,["taskId"],[0],1],Hf=[3,"com.amazon.aws.q.interactioncomponents","Text",0,["content"],[[()=>wn,0]],1],RQ=[3,"com.amazon.aws.q.interactioncomponents","WebLink",0,["label","url"],[[()=>wn,0],[()=>wn,0]],2];var MQ=[1,"com.amazon.aws.codewhisperer","AdditionalContentList",0,[()=>kl,0]],EQ=[1,"com.amazon.aws.codewhisperer","ChatHistory",0,[()=>y4,0]],TQ=[1,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformationList",0,[()=>_J,0]];var gQ=[1,"com.amazon.aws.codewhisperer","DocumentBlocks",0,[()=>hJ,0]],SQ=[1,"com.amazon.aws.codewhisperer","DocumentCitationSourceContents",0,[()=>wJ,0]],w4=[1,"com.amazon.aws.codewhisperer","DocumentSymbols",0,()=>uJ],LQ=[1,"com.amazon.aws.codewhisperer","EnvironmentVariables",0,[()=>AJ,0]],$Q=[1,"com.amazon.aws.codewhisperer","ImageBlocks",0,[()=>TJ,0]],e4=[1,"com.amazon.aws.codewhisperer","References",0,()=>NJ],OQ=[1,"com.amazon.aws.codewhisperer","RelevantDocumentList",0,[()=>BJ,0]],UQ=[1,"com.amazon.aws.codewhisperer","ShellHistory",0,[()=>HJ,0]],u4=[1,"com.amazon.aws.codewhisperer","SupplementaryWebLinks",0,[()=>WJ,0]],bQ=[1,"com.amazon.aws.codewhisperer","ToolResultContent",0,[()=>tz,0]],NQ=[1,"com.amazon.aws.codewhisperer","ToolResults",0,[()=>f4,0]],BQ=[1,"com.amazon.aws.codewhisperer","Tools",0,[()=>nz,0]],IQ=[1,"com.amazon.aws.codewhisperer","ToolUses",0,[()=>lJ,0]],HQ=[1,"com.amazon.aws.codewhisperer","WorkspaceFolderList",0,[()=>J,0]],GQ=[1,"com.amazon.aws.q.interactioncomponents","AlertComponentList",0,[()=>kJ,0]],WQ=[1,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOptionsList",0,[()=>mJ,0]],DQ=[1,"com.amazon.aws.q.interactioncomponents","ClarificationQuestionList",0,[()=>ZJ,0]],PQ=[1,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntryList",0,[()=>tQ,0]],YQ=[1,"com.amazon.aws.q.interactioncomponents","ProgressComponentList",0,[()=>rQ,0]],FQ=[1,"com.amazon.aws.q.interactioncomponents","Resources",0,[()=>mw,0]],XQ=[1,"com.amazon.aws.q.interactioncomponents","SectionComponentList",0,[()=>fQ,0]],lQ=[1,"com.amazon.aws.q.interactioncomponents","StepComponentList",0,[()=>_Q,0]],JQ=[1,"com.amazon.aws.q.interactioncomponents","SuggestionList",0,[()=>hQ,0]],QQ=[1,"com.amazon.aws.q.interactioncomponents","TaskActionList",0,[()=>oQ,0]],zQ=[1,"com.amazon.aws.q.interactioncomponents","TaskComponentList",0,[()=>uQ,0]],CQ=[2,"com.amazon.aws.codewhisperer","IntentData",8,0,()=>vQ],VQ=[2,"com.amazon.aws.codewhisperer","IntentMap",0,[0,0],[()=>CQ,0]],KQ=[2,"com.amazon.aws.q.interactioncomponents","TaskActionPayload",0,[0,0],[()=>wn,0]],y4=[4,"com.amazon.aws.codewhisperer","ChatMessage",0,["userInputMessage","assistantResponseMessage"],[[()=>QJ,0],[()=>Zl,0]]],xQ=[4,"com.amazon.aws.codewhisperer","ChatResponseStream",{["streaming"]:1},["messageMetadataEvent","assistantResponseEvent","reasoningContentEvent","dryRunSucceedEvent","codeReferenceEvent","supplementaryWebLinksEvent","followupPromptEvent","codeEvent","intentsEvent","interactionComponentsEvent","toolUseEvent","toolResultEvent","metadataEvent","meteringEvent","contextUsageEvent","citationEvent","documentCitationEvent","invalidStateEvent","error"],[()=>LJ,[()=>ml,0],[()=>UJ,0],()=>yJ,()=>tJ,[()=>DJ,0],[()=>MJ,0],[()=>nJ,0],[()=>gJ,0],[()=>jJ,0],[()=>JJ,0],[()=>FJ,0],()=>$J,()=>OJ,()=>rJ,[()=>al,0],[()=>cJ,0],()=>SJ,[()=>pE,0]]],jQ=[4,"com.amazon.aws.codewhisperer","CitationTarget",0,["location","range"],[1,()=>r4]],kQ=[4,"com.amazon.aws.codewhisperer","CursorState",0,["position","range"],[()=>Cw,()=>jw]],qQ=[4,"com.amazon.aws.codewhisperer","Diagnostic",0,["textDocumentDiagnostic","runtimeDiagnostic"],[[()=>PJ,0],[()=>IJ,0]]],mQ=[4,"com.amazon.aws.codewhisperer","DocumentCitationLocation",0,["documentPage","documentChar","documentChunk","searchResult","web"],[()=>zw,()=>zw,()=>zw,()=>oJ,[()=>eJ,0]]],ZQ=[4,"com.amazon.aws.codewhisperer","DocumentSource",8,["bytes"],[21]];var aQ=[4,"com.amazon.aws.codewhisperer","ImageSource",8,["bytes"],[21]],vQ=[4,"com.amazon.aws.codewhisperer","IntentDataType",0,["string"],[0]],pQ=[4,"com.amazon.aws.codewhisperer","ReasoningContent",8,["reasoningText","redactedContent"],[[()=>bJ,0],21]];var nz=[4,"com.amazon.aws.codewhisperer","Tool",0,["toolSpecification","cachePoint"],[[()=>XJ,0],()=>xw]],tz=[4,"com.amazon.aws.codewhisperer","ToolResultContentBlock",0,["text","json"],[[()=>J,0],[()=>Kw,0]]];var d4=[9,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponse",{["http"]:["POST","/generateAssistantResponse",200]},()=>KJ,()=>xJ];var M4=(n)=>{return{apiVersion:"2023-11-27",base64Decoder:n?.base64Decoder??es.fromBase64,base64Encoder:n?.base64Encoder??es.toBase64,disableHostPrefix:n?.disableHostPrefix??!1,endpointProvider:n?.endpointProvider??aE,extensions:n?.extensions??[],httpAuthSchemeProvider:n?.httpAuthSchemeProvider??T1,httpAuthSchemes:n?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(t)=>t.getIdentityProvider("smithy.api#httpBearerAuth"),signer:new R4.HttpBearerAuthSigner}],logger:n?.logger??new rn.NoOpLogger,protocol:n?.protocol??A4.AwsRestJsonProtocol,protocolSettings:n?.protocolSettings??{defaultNamespace:"com.amazon.aws.codewhisperer.streaming",errorTypeRegistries:n4,version:"2023-11-27",serviceTarget:"AmazonCodeWhispererStreamingService"},serviceId:n?.serviceId??"CodeWhispererStreaming",urlParser:n?.urlParser??lw.parseUrl,utf8Decoder:n?.utf8Decoder??hr.fromUtf8,utf8Encoder:n?.utf8Encoder??hr.toUtf8}};var S4=(n)=>{rn.emitWarningIfUnsupportedVersion(process.version);let t=Xw.resolveDefaultsModeConfig(n),i=()=>t().then(rn.loadConfigsForDefaultMode),r=M4(n);E4.emitWarningIfUnsupportedVersion(process.version);let s={profile:n?.profile,logger:r.logger};return{...r,...n,runtime:"node",defaultsMode:t,authSchemePreference:n?.authSchemePreference??ri.loadConfig(T4.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,s),bodyLengthChecker:n?.bodyLengthChecker??Fw.calculateBodyLength,defaultUserAgentProvider:n?.defaultUserAgentProvider??Ct.createDefaultUserAgentProvider({serviceId:r.serviceId,clientVersion:$1.version}),eventStreamSerdeProvider:n?.eventStreamSerdeProvider??Wh.eventStreamSerdeProvider,httpAuthSchemes:n?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(f)=>f.getIdentityProvider("smithy.api#httpBearerAuth")||(async(h)=>{return await Pw(h)(h)}),signer:new g4.HttpBearerAuthSigner}],maxAttempts:n?.maxAttempts??ri.loadConfig(yn.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,n),region:n?.region??ri.loadConfig(un.NODE_REGION_CONFIG_OPTIONS,{...un.NODE_REGION_CONFIG_FILE_OPTIONS,...s}),requestHandler:xh.NodeHttpHandler.create(n?.requestHandler??i),retryMode:n?.retryMode??ri.loadConfig({...yn.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await i()).retryMode||Bn.DEFAULT_RETRY_MODE},n),sha256:n?.sha256??Yw.Hash.bind(null,"sha256"),streamCollector:n?.streamCollector??xh.streamCollector,useDualstackEndpoint:n?.useDualstackEndpoint??ri.loadConfig(un.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,s),useFipsEndpoint:n?.useFipsEndpoint??ri.loadConfig(un.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,s),userAgentAppId:n?.userAgentAppId??ri.loadConfig(Ct.NODE_APP_ID_CONFIG_OPTIONS,s)}};var rt=k(gt(),1);var vn=k(kn(),1);var L4=(n)=>{let{httpAuthSchemes:t,httpAuthSchemeProvider:i,token:r}=n;return{setHttpAuthScheme(s){let f=t.findIndex((h)=>h.schemeId===s.schemeId);if(f===-1)t.push(s);else t.splice(f,1,s)},httpAuthSchemes(){return t},setHttpAuthSchemeProvider(s){i=s},httpAuthSchemeProvider(){return i},setToken(s){r=s},token(){return r}}},$4=(n)=>{return{httpAuthSchemes:n.httpAuthSchemes(),httpAuthSchemeProvider:n.httpAuthSchemeProvider(),token:n.token()}};var O4=(n,t)=>{let i=Object.assign(rt.getAwsRegionExtensionConfiguration(n),rn.getDefaultExtensionConfiguration(n),vn.getHttpHandlerExtensionConfiguration(n),L4(n));return t.forEach((r)=>r.configure(i)),Object.assign(n,rt.resolveAwsRegionExtensionConfiguration(i),rn.resolveDefaultRuntimeConfig(i),vn.resolveHttpHandlerRuntimeConfig(i),$4(i))};class Zw extends rn.Client{config;constructor(...[n]){let t=S4(n||{});super(t);this.initConfig=t;let i=S1(t),r=ii.resolveUserAgentConfig(i),s=yn.resolveRetryConfig(r),f=un.resolveRegionConfig(s),h=bi.resolveHostHeaderConfig(f),_=ht.resolveEndpointConfig(h),c=it.resolveDefaultAwsRegionalEndpointsConfig(_),o=Yo.resolveEventStreamSerdeConfig(c),w=g1(o),e=O4(w,n?.extensions||[]);this.config=e,this.middlewareStack.use(U4.getSchemaSerdePlugin(this.config)),this.middlewareStack.use(ii.getUserAgentPlugin(this.config)),this.middlewareStack.use(yn.getRetryPlugin(this.config)),this.middlewareStack.use(Tf.getContentLengthPlugin(this.config)),this.middlewareStack.use(bi.getHostHeaderPlugin(this.config)),this.middlewareStack.use(Mf.getLoggerPlugin(this.config)),this.middlewareStack.use(Ef.getRecursionDetectionPlugin(this.config)),this.middlewareStack.use(ys.getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:E1,identityProviderConfigProvider:async(u)=>new ys.DefaultIdentityProviderConfig({"smithy.api#httpBearerAuth":u.token})})),this.middlewareStack.use(ys.getHttpSigningPlugin(this.config))}destroy(){super.destroy()}}class aw extends rn.Command.classBuilder().ep(L1).m(function(n,t,i,r){return[ht.getEndpointPlugin(i,n.getEndpointParameterInstructions())]}).s("AmazonCodeWhispererStreamingService","GenerateAssistantResponse",{eventStream:{output:!0}}).n("CodeWhispererStreamingClient","GenerateAssistantResponseCommand").sc(d4).build(){}import{randomUUID as se}from"crypto";import{createHash as iz}from"crypto";function b4(n){return typeof n==="object"&&n!==null&&"canonicalVersion"in n&&n.canonicalVersion===1&&"messages"in n&&Array.isArray(n.messages)}function vw(n){if(Array.isArray(n))return n.map(vw);if(typeof n!=="object"||n===null)return n;return Object.fromEntries(Object.entries(n).sort(([t],[i])=>t.localeCompare(i)).map(([t,i])=>[t,vw(i)]))}function jh(n){return iz("sha256").update(JSON.stringify(vw(n))).digest("hex")}function et(n){return jh({text:n.text,toolCalls:n.toolCalls.map((t)=>({id:t.id,name:t.name,input:t.input}))})}function si(n){return n.filter((t)=>t.type==="text").map((t)=>t.text).join("")}function N4(n){let t=Vs[n];if(!t)throw Error(`Unsupported model: ${n}. Supported models: ${Ku.join(", ")}`);return t}var B4=new Set(["claude-opus-4-8","claude-opus-4-7","claude-sonnet-5","claude-sonnet-4-6","gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),I4=["low","medium","high","xhigh","max"];function Kt(n){for(let t of I4){let i=`-${t}`;if(n.endsWith(i)){let r=n.slice(0,-i.length);if(B4.has(r))return{wireId:N4(r),effort:t}}}return{wireId:N4(n),effort:void 0}}function rz(n){for(let t of I4){let i=`-${t}`;if(n.endsWith(i)){let r=n.slice(0,-i.length);if(B4.has(r))return r}}if(n.endsWith("-thinking")){let t=n.slice(0,-9);if(Vs[t])return t}return n}function H4(n){return l(rz(n))}var sz=["low","medium","high","xhigh","max"];function fz(n){return typeof n==="string"&&sz.some((t)=>t===n)}var G4=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),W4=new Set(["claude-opus-4.7","claude-opus-4.8","claude-sonnet-5",...G4]),_z=new Set(["claude-opus-4.5","claude-opus-4.6","claude-opus-4.6-1m","claude-sonnet-4.6","claude-sonnet-4.6-1m",...W4]);function or(n){return _z.has(n)}function pw(n){return W4.has(n)}function D4(n,t){if(G4.has(n))return{reasoning:{effort:t}};return{output_config:{effort:t}}}function hz(n,t){if(!or(n))return;if(t==="xhigh"&&!pw(n))return"max";return t}function cz(n,t){if(!or(t))return;let i;if(n<=1e4)i="low";else if(n<=20000)i="medium";else if(n<=28000)i="high";else i="max";return i}function P4(n){let t;if(or(n.model))t={wireId:n.model,effort:void 0};else try{t=Kt(n.model)}catch(r){if(r instanceof Error&&r.message.startsWith("Unsupported model:"))return;throw r}if(!or(t.wireId))return;let i=[t.effort,n.reasoningEffort,n.configEffort];for(let r of i)if(fz(r))return hz(t.wireId,r);if(!n.think)return;if(n.autoEffortMapping??!0)return cz(n.budget,t.wireId);return"medium"}var Y4=1024,F4=128000,oz=new Set(["claude-sonnet-5"]);function Hi(n,t){let i;try{i=Kt(n).wireId}catch{return{ok:!1,code:"unsupported_output_token_limit",message:`Output-token limiting is not available for unsupported model ${n}`}}if(!oz.has(i))return{ok:!1,code:"unsupported_output_token_limit",message:`Kiro has no probe-confirmed native output-token control for model ${n}`};if(!Number.isInteger(t)||t<Y4||t>F4)return{ok:!1,code:"invalid_output_token_limit",message:`Kiro requires output-token limits for ${n} to be an integer from ${Y4} through ${F4}`};return{ok:!0,wireModel:i,additionalModelRequestFields:{max_tokens:t}}}class Mn extends Error{code;param;name="RequestTransformError";constructor(n,t="invalid_request",i){super(n);this.code=t;this.param=i}}import{randomUUID as Rz}from"crypto";function wz(n){let t=atob(n),i=new Uint8Array(t.length);for(let r=0;r<t.length;r++)i[r]=t.charCodeAt(r);return i}function X4(n){let t=[],i=0;for(let r of n){if(t.length>=4)break;if(i+r.data.length>3750000)break;t.push(r),i+=r.data.length}return{images:t.map((r)=>({format:r.mediaType.split("/")[1]||"png",source:{bytes:wz(r.data)}})),omitted:n.length-t.length}}function ez(n,t){if(!n.startsWith("data:"))throw new Mn(`Image ${t} must use a data URL because Kiro cannot fetch remote image URLs`,"unsupported_image_source");let[i="",r]=n.split(",",2);if(!r)throw new Mn(`Image ${t} contains an invalid data URL`,"invalid_image");return{mediaType:i.split(";")[0]?.replace("data:","")||"image/jpeg",data:r}}function uz(n){let t=[];for(let i of n){if(i.type!=="image")continue;if(i.data!==void 0){t.push({mediaType:i.mediaType??"image/jpeg",data:i.data});continue}if(i.url!==void 0)t.push(ez(i.url,i.path))}return t}function yz(n){return n.flatMap((t)=>t.type==="tool_result"?[{toolUseId:t.toolCallId,content:t.content.map((i)=>({text:i.text})),status:t.isError?"error":"success"}]:[])}function l4(n,t){let i={content:si(n.content),modelId:t,origin:Hn.ORIGIN_AI_EDITOR},r=yz(n.content);if(r.length>0)i.userInputMessageContext={toolResults:r};let s=uz(n.content);if(s.length>0){let f=X4(s);if(f.omitted>0)throw new Mn(`Message ${n.path} exceeds Kiro's limit of 4 images and 3.75 MB of base64 image data`,"too_many_images");i.images=f.images}return i}function dz(n){if(n===void 0)return;return n.content.kind==="reasoning_text"?{reasoningText:{text:n.content.text,signature:n.content.signature}}:{redactedContent:n.content.bytes}}function Az(n,t){let i=dz(t),r={content:si(n.content),...i!==void 0?{reasoningContent:i}:{}},s=[...n.content.flatMap((f)=>f.type==="tool_use"?[{toolUseId:f.id,name:f.name,input:f.input}]:[]),...n.toolCalls.map((f)=>({toolUseId:f.id,name:f.name,input:f.input}))];if(s.length>0)r.toolUses=s;return r}function J4(n,t,i=[]){let r=new Map(i.map((f)=>[f.insertBeforeMessage,f])),s=[];for(let[f,h]of n.entries()){if(h.role==="assistant"){s.push({assistantResponseMessage:Az(h,r.get(f))});continue}if(h.role==="user"||h.role==="tool")s.push({userInputMessage:l4(h,t)})}return s}function Q4(n){return n.some((t)=>Boolean(t.assistantResponseMessage?.toolUses)||Boolean(t.userInputMessage?.userInputMessageContext?.toolResults))}function z4(n){let t=new Set;for(let i of n)for(let r of i.assistantResponseMessage?.toolUses??[])if(r.name)t.add(r.name);return t}function C4(n,t){return l4(n,t)}function V4(n,t){return{type:"text",text:n,path:t}}function Mz(n){return{...n,content:n.content.map((t)=>t.type==="tool_result"?{...t,content:t.content.map((i)=>({...i}))}:{...t}),toolCalls:n.toolCalls.map((t)=>({...t}))}}function Ez(n){for(let t of n){if(t.role==="system"||t.role==="developer")continue;let i=t.content.filter((s)=>s.type==="text");if(i.length<=1)continue;let r=i[1];throw new Mn(`Message ${t.path} contains multiple text content blocks, but Kiro exposes only one text field and cannot preserve their boundaries`,"unsupported_content_block_projection",r?.path??t.path)}}function Tz(n){let t=n.messages.filter((_)=>_.role==="system"||_.role==="developer");if(t.length>0&&n.projectionMode==="safe")throw new Mn("Kiro rejected the tested structured instruction channel; safe mode cannot project system/developer/instructions","unsupported_instruction_projection");for(let _ of t)if(_.content.some((c)=>c.type!=="text")||_.toolCalls.length>0)throw new Mn(`Instruction ${_.path} contains non-text content that legacy projection cannot represent`,"unsupported_instruction_projection");let i=[],r=new Map;for(let[_,c]of n.messages.entries()){if(c.role==="system"||c.role==="developer")continue;r.set(_,i.length),i.push(Mz(c))}if(t.length===0)return{messages:i,projectedIndexByOriginal:r};let s=t.flatMap((_)=>_.content.map((c)=>c.type==="text"?c.text:"")).join(`
|
|
241
288
|
|
|
242
|
-
`)
|
|
243
|
-
`))}catch(R){if(h!==void 0)return;let y=R instanceof Error?R:TypeError("SDK stream failed with a non-Error reason",{cause:R});A("upstream-error",y)}},cancel(E){A("consumer-cancel",E)}}),{headers:{"Content-Type":"application/x-ndjson; charset=utf-8"}})}import{createHash as UX}from"crypto";import{Agent as bX}from"http";import{Agent as $X}from"https";var z_=Q(jo(),1);var $y=new Map,Ly=new Map,LX=3;function Cf(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function OX(n){let t=n.conversationState;if(!Cf(t))return;let i=t.currentMessage;if(!Cf(i))return;let s=i.userInputMessage;if(!Cf(s))return;let r=s.modelId;return typeof r==="string"?r:void 0}function BX(n,t,i,s,r=Oy(s),e={value:n.access}){return{region:t,endpoint:i,token:()=>Promise.resolve({token:e.value}),maxAttempts:LX,retryMode:"standard",customUserAgent:[[Rn.USER_AGENT]],requestHandler:r}}function Oy(n){if(n){let t=new br(n,{keepAlive:!0,maxSockets:50});return new z_.NodeHttpHandler({httpAgent:t,httpsAgent:t})}return new z_.NodeHttpHandler({httpAgent:new bX({keepAlive:!0,maxSockets:50}),httpsAgent:new $X({keepAlive:!0,maxSockets:50})})}function NX(n){return UX("sha256").update("kiro-provider-sdk-account-v1\x00").update(n.email??n.refresh).digest("hex")}function By(n,t,i,s,r,e){let f=s??`https://q.${t}.amazonaws.com`,o=JSON.stringify([e??NX(n),t,f,r??null]),h=Ly.get(o);if(!h)h={handler:Oy(r)},Ly.set(o,h);let u=JSON.stringify([o,i??null]),c=$y.get(u);if(c)return c.tokenState.value=n.access,c.client;let _={value:n.access},w=new N_(BX(n,t,f,r,h.handler,_));if(w.middlewareStack.add((l)=>async(A)=>{if(A.request instanceof xn.HttpRequest)A.request.headers["x-amzn-kiro-agent-mode"]="vibe";return l(A)},{step:"build",name:"addKiroHeaders"}),i)w.middlewareStack.add((l)=>async(A)=>{if(A.request instanceof xn.HttpRequest&&typeof A.request.body==="string")try{let d=JSON.parse(A.request.body);if(Cf(d)){let E=OX(d);if(E)d.additionalModelRequestFields=VE(E,i),A.request.body=JSON.stringify(d)}}catch(d){if(!(d instanceof SyntaxError))throw d}return l(A)},{step:"build",name:"addEffortConfig",priority:"high"});return $y.set(u,{client:w,tokenState:_}),w}function pi(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function GX(n){if(!pi(n))return!1;let t=n.conversationState;return pi(t)&&typeof t.conversationId==="string"&&pi(t.currentMessage)&&typeof t.chatTriggerType==="string"}function HX(n,t){let i=typeof n==="string"?JSON.parse(n):n;if(!pi(i))return{think:t.endsWith("-thinking"),budget:20000};let s=i.providerOptions,r=pi(s)?s.thinkingConfig:void 0,e=i.thinkingConfig,f=pi(r)?r:pi(e)?e:void 0,o=f?.thinkingBudget??f?.budget_tokens;return{think:t.endsWith("-thinking")||f!==void 0,budget:typeof o==="number"?o:20000}}function WX(n,t,i){return v(n,t,"upstream_error",i)}async function FX(n,t){let{think:i,budget:s}=HX(n.body,n.model),r=new Set,e=new Map,f=0,o=0,h=n.affinity&&n.affinityStore?n.affinityStore.getSessionAffinity(n.affinity.keyHash):void 0,u=h?.accountId,c,_=h?.conversationId;while(!0){if(t.aborted)throw di(t);if(o+=1,o>n.config.max_request_iterations)return{kind:"response",response:v(500,`Exceeded max iterations (${n.config.max_request_iterations})`,"request_error","max_request_iterations")};n.accountManager.reconcileFromDb();let w=n.accountManager.selectHealthyAccount(u);if(!w)return{kind:"response",response:v(503,"All accounts are unhealthy or rate-limited","service_unavailable","no_healthy_accounts")};let l=Date.now();if(n.affinity&&n.affinityStore)if(!h){let y=n.affinityStore.claimSessionAffinity(n.affinity.keyHash,w.id,Q_(),l,n.config.session_affinity_ttl_ms,n.config.session_affinity_max_entries);if(h=y,u=y.accountId,_=y.conversationId,y.accountId!==w.id)continue}else if(h.accountId===w.id)h=n.affinityStore.claimSessionAffinity(n.affinity.keyHash,w.id,h.conversationId,l,n.config.session_affinity_ttl_ms,n.config.session_affinity_max_entries),_=h.conversationId;else h=n.affinityStore.rebindSessionAffinity(n.affinity.keyHash,w.id,Q_(),l,n.config.session_affinity_ttl_ms,n.config.session_affinity_max_entries),_=h.conversationId;else if(c!==w.id)c=w.id,_=Q_();u=w.id;let A=await Ay(w.id,t),d=!0,E=w,R=!1;try{let y=n.accountManager.toAuthDetails(w);E=await tr(n.tokenRefresher.refreshIfNeeded(w,y,t),t);let T=n.accountManager.toAuthDetails(E),S=$e.safeParse(n.config.effort),I=oy(n.body,n.model,T,i,s,{autoEffortMapping:n.config.auto_effort_mapping,conversationId:_,...S.success?{effort:S.data}:{}}),C=(n.makeClient??By)(T,I.region,I.effort,n.config.test_upstream_endpoint,$s(n.config),E.id),sn={conversationState:I.conversationState,...I.profileArn?{profileArn:I.profileArn}:{}};if(!GX(sn))throw TypeError("Transformed request is not a valid SDK command input");let b=new G_(sn);R=!0;let $=await tr(C.send(b,{abortSignal:t}),t);if(n.stream)return d=!1,{kind:"stream",sdkResponse:$,model:n.model,conversationId:I.conversationId,releaseAccount:A};let N=await uy($,n.model,I.conversationId,t);if(t.aborted)throw di(t);return{kind:"response",response:Response.json(N,{headers:{"Content-Type":"application/json"}})}}catch(y){if(t.aborted)throw di(t);if(!R)throw y;let T=P_(y),S=T.status===500?(e.get(E.id)??0)+1:0;if(T.status===500)e.set(E.id,S);let I=cy(T,{accountId:E.id,accountCount:n.accountManager.getAccountCount(),retryCount:f,maxRetries:n.config.rate_limit_max_retries,serverErrorCount:S,retryDelayMs:n.config.rate_limit_retry_delay_ms,forcedRefreshAccountIds:r});switch(I.action){case"refresh-then-retry":await tr(n.tokenRefresher.forceRefresh(E,t),t);continue;case"retry":f+=1,await _y(I.retryAfterMs??0,t);continue;case"switch":if(T.reason==="TEMPORARILY_SUSPENDED")n.accountManager.markUnhealthy(E,`InvalidTokenException: Account Suspended: ${T.message}`);else n.accountManager.markRateLimited(E,Date.now()+(I.retryAfterMs??n.config.rate_limit_retry_delay_ms));if(u=void 0,c=void 0,!n.affinityStore)_=void 0;continue;case"fail":if(T.reason==="TEMPORARILY_SUSPENDED")n.accountManager.markUnhealthy(E,`InvalidTokenException: Account Suspended: ${T.message}`);return{kind:"response",response:WX(I.terminalStatus??I.status??500,T.message,T.code)}}}finally{if(d)A()}}}async function ir(n){let t=My(n.deadlineSignal,n.config.request_timeout_ms),i,s,r=!1;try{if(n.affinity)i=await ly(n.affinity.keyHash,t.signal);let e=await FX(n,t.signal);if(e.kind==="response")return e.response;s=e.releaseAccount;let f=s,o=i,h=(n.createStreamResponse??by)(e,t.signal,n.config.stream_idle_timeout_ms,()=>{f(),o?.(),t.dispose()});return s=void 0,i=void 0,r=!0,h}catch(e){if(e instanceof Kn)return v(400,e.message,"invalid_request_error",e.code);if(t.signal.aborted)return v(504,"Request deadline exceeded","timeout_error","request_timeout");let f=P_(e);return v(500,f.message,"internal_error",f.code)}finally{if(!r)s?.(),i?.(),t.dispose()}}var Re=Object.freeze({input:Object.freeze(["text"]),output:Object.freeze(["text"])}),In=Object.freeze({input:Object.freeze(["text","image"]),output:Object.freeze(["text"])}),fn=Object.freeze({input:Object.freeze(["text","image","pdf"]),output:Object.freeze(["text"])}),Ny=Object.freeze(["auto","claude-sonnet-4","claude-sonnet-4-5","claude-sonnet-4-6","claude-sonnet-4-6-low","claude-sonnet-4-6-medium","claude-sonnet-4-6-high","claude-sonnet-4-6-max","claude-sonnet-5","claude-sonnet-5-low","claude-sonnet-5-medium","claude-sonnet-5-high","claude-sonnet-5-xhigh","claude-sonnet-5-max","claude-haiku-4-5","claude-opus-4-5","claude-opus-4-6","claude-opus-4-7","claude-opus-4-7-low","claude-opus-4-7-medium","claude-opus-4-7-high","claude-opus-4-7-xhigh","claude-opus-4-7-max","claude-opus-4-8","claude-opus-4-8-low","claude-opus-4-8-medium","claude-opus-4-8-high","claude-opus-4-8-xhigh","claude-opus-4-8-max","claude-opus-4-8-thinking","deepseek-3.2","glm-5","minimax-m2.5","minimax-m2.1","qwen3-coder-next","gpt-5.6-sol","gpt-5.6-sol-low","gpt-5.6-sol-medium","gpt-5.6-sol-high","gpt-5.6-sol-xhigh","gpt-5.6-sol-max","gpt-5.6-terra","gpt-5.6-terra-low","gpt-5.6-terra-medium","gpt-5.6-terra-high","gpt-5.6-terra-xhigh","gpt-5.6-terra-max","gpt-5.6-luna","gpt-5.6-luna-low","gpt-5.6-luna-medium","gpt-5.6-luna-high","gpt-5.6-luna-xhigh","gpt-5.6-luna-max"]),xf=Object.freeze([{id:"auto",wireId:"auto",name:"Auto (1.0x)",contextLimit:D("auto"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-4",wireId:"claude-sonnet-4",name:"Claude Sonnet 4.0 (1.3x)",contextLimit:D("claude-sonnet-4"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-4-5",wireId:"claude-sonnet-4.5",name:"Claude Sonnet 4.5 (1.3x)",contextLimit:D("claude-sonnet-4-5"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-4-6",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (1.3x)",contextLimit:D("claude-sonnet-4-6"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-4-6-low",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (low) (1.3x)",contextLimit:D("claude-sonnet-4-6"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-4-6-medium",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (medium) (1.3x)",contextLimit:D("claude-sonnet-4-6"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-4-6-high",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (high) (1.3x)",contextLimit:D("claude-sonnet-4-6"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-4-6-max",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (max) (1.3x)",contextLimit:D("claude-sonnet-4-6"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-5",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (1.3x)",contextLimit:D("claude-sonnet-5"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-5-low",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (low) (1.3x)",contextLimit:D("claude-sonnet-5"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-5-medium",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (medium) (1.3x)",contextLimit:D("claude-sonnet-5"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-5-high",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (high) (1.3x)",contextLimit:D("claude-sonnet-5"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-5-xhigh",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (xhigh) (1.3x)",contextLimit:D("claude-sonnet-5"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-5-max",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (max) (1.3x)",contextLimit:D("claude-sonnet-5"),outputLimit:64000,modalities:fn},{id:"claude-haiku-4-5",wireId:"claude-haiku-4.5",name:"Claude Haiku 4.5 (0.4x)",contextLimit:D("claude-haiku-4-5"),outputLimit:64000,modalities:In},{id:"claude-opus-4-5",wireId:"claude-opus-4.5",name:"Claude Opus 4.5 (2.2x)",contextLimit:D("claude-opus-4-5"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-6",wireId:"claude-opus-4.6",name:"Claude Opus 4.6 (2.2x)",contextLimit:D("claude-opus-4-6"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-7",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (2.2x)",contextLimit:D("claude-opus-4-7"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-7-low",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (low) (2.2x)",contextLimit:D("claude-opus-4-7"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-7-medium",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (medium) (2.2x)",contextLimit:D("claude-opus-4-7"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-7-high",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (high) (2.2x)",contextLimit:D("claude-opus-4-7"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-7-xhigh",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (xhigh) (2.2x)",contextLimit:D("claude-opus-4-7"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-7-max",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (max) (2.2x)",contextLimit:D("claude-opus-4-7"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-8",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (2.2x)",contextLimit:D("claude-opus-4-8"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-8-low",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (low) (2.2x)",contextLimit:D("claude-opus-4-8"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-8-medium",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (medium) (2.2x)",contextLimit:D("claude-opus-4-8"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-8-high",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (high) (2.2x)",contextLimit:D("claude-opus-4-8"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-8-xhigh",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (xhigh) (2.2x)",contextLimit:D("claude-opus-4-8"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-8-max",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (max) (2.2x)",contextLimit:D("claude-opus-4-8"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-8-thinking",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 Thinking (2.2x)",contextLimit:D("claude-opus-4-8"),outputLimit:64000,modalities:fn},{id:"deepseek-3.2",wireId:"deepseek-3.2",name:"DeepSeek 3.2 (0.25x)",contextLimit:D("deepseek-3.2"),outputLimit:64000,modalities:Re},{id:"glm-5",wireId:"glm-5",name:"GLM-5 (0.5x)",contextLimit:D("glm-5"),outputLimit:64000,modalities:Re},{id:"minimax-m2.5",wireId:"minimax-m2.5",name:"MiniMax M2.5 (0.25x)",contextLimit:D("minimax-m2.5"),outputLimit:64000,modalities:Re},{id:"minimax-m2.1",wireId:"minimax-m2.1",name:"MiniMax M2.1 (0.15x)",contextLimit:D("minimax-m2.1"),outputLimit:64000,modalities:Re},{id:"qwen3-coder-next",wireId:"qwen3-coder-next",name:"Qwen3 Coder Next (0.05x)",contextLimit:D("qwen3-coder-next"),outputLimit:64000,modalities:Re},{id:"gpt-5.6-sol",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (2.4x)",contextLimit:D("gpt-5.6-sol"),outputLimit:64000,modalities:In},{id:"gpt-5.6-sol-low",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (low) (2.4x)",contextLimit:D("gpt-5.6-sol"),outputLimit:64000,modalities:In},{id:"gpt-5.6-sol-medium",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (medium) (2.4x)",contextLimit:D("gpt-5.6-sol"),outputLimit:64000,modalities:In},{id:"gpt-5.6-sol-high",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (high) (2.4x)",contextLimit:D("gpt-5.6-sol"),outputLimit:64000,modalities:In},{id:"gpt-5.6-sol-xhigh",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (xhigh) (2.4x)",contextLimit:D("gpt-5.6-sol"),outputLimit:64000,modalities:In},{id:"gpt-5.6-sol-max",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (max) (2.4x)",contextLimit:D("gpt-5.6-sol"),outputLimit:64000,modalities:In},{id:"gpt-5.6-terra",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (1.2x)",contextLimit:D("gpt-5.6-terra"),outputLimit:64000,modalities:In},{id:"gpt-5.6-terra-low",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (low) (1.2x)",contextLimit:D("gpt-5.6-terra"),outputLimit:64000,modalities:In},{id:"gpt-5.6-terra-medium",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (medium) (1.2x)",contextLimit:D("gpt-5.6-terra"),outputLimit:64000,modalities:In},{id:"gpt-5.6-terra-high",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (high) (1.2x)",contextLimit:D("gpt-5.6-terra"),outputLimit:64000,modalities:In},{id:"gpt-5.6-terra-xhigh",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (xhigh) (1.2x)",contextLimit:D("gpt-5.6-terra"),outputLimit:64000,modalities:In},{id:"gpt-5.6-terra-max",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (max) (1.2x)",contextLimit:D("gpt-5.6-terra"),outputLimit:64000,modalities:In},{id:"gpt-5.6-luna",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna",contextLimit:D("gpt-5.6-luna"),outputLimit:64000,modalities:In},{id:"gpt-5.6-luna-low",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (low)",contextLimit:D("gpt-5.6-luna"),outputLimit:64000,modalities:In},{id:"gpt-5.6-luna-medium",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (medium)",contextLimit:D("gpt-5.6-luna"),outputLimit:64000,modalities:In},{id:"gpt-5.6-luna-high",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (high)",contextLimit:D("gpt-5.6-luna"),outputLimit:64000,modalities:In},{id:"gpt-5.6-luna-xhigh",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (xhigh)",contextLimit:D("gpt-5.6-luna"),outputLimit:64000,modalities:In},{id:"gpt-5.6-luna-max",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (max)",contextLimit:D("gpt-5.6-luna"),outputLimit:64000,modalities:In}]);var ns=M.record(M.unknown()),PX=new Set(Ny),DX=M.object({type:M.literal("text"),text:M.string()}).passthrough(),YX=M.object({type:M.literal("image_url"),image_url:M.object({url:M.string(),detail:M.string().optional()}).passthrough()}).passthrough(),mX=M.object({type:M.literal("image"),source:M.object({type:M.string(),data:M.string(),media_type:M.string().optional()}).passthrough()}).passthrough(),JX=M.object({type:M.literal("tool_result"),tool_use_id:M.string().min(1),content:M.unknown()}).passthrough(),XX=M.object({type:M.literal("tool_use"),id:M.string().min(1),name:M.string().min(1),input:M.unknown()}).passthrough(),zX=M.object({type:M.literal("thinking"),thinking:M.string().optional(),text:M.string().optional()}).passthrough(),QX=M.discriminatedUnion("type",[DX,YX,mX,JX,XX,zX]),Kf=M.union([M.string(),M.array(QX)]);function Gy(n){try{return JSON.parse(n),!0}catch(t){if(t instanceof SyntaxError)return!1;throw t}}function CX(n){return n.trim().length===0?"{}":n}var xX=M.object({id:M.string().min(1),type:M.literal("function"),function:M.object({name:M.string().min(1),arguments:M.string().refine(Gy,"function arguments must contain valid JSON")}).passthrough()}).passthrough(),KX=M.object({role:M.literal("system"),content:Kf}).passthrough(),kX=M.object({role:M.literal("user"),content:Kf}).passthrough(),qX=M.object({role:M.literal("assistant"),content:Kf.nullable().optional(),tool_calls:M.array(xX).min(1).optional()}).passthrough().refine((n)=>n.content!==null&&n.content!==void 0?!0:n.tool_calls!==void 0,{message:"assistant message requires content or tool_calls"}),VX=M.object({role:M.literal("tool"),content:Kf,tool_call_id:M.string().min(1)}).passthrough(),jX=M.union([KX,kX,qX,VX]),aX=M.object({type:M.literal("function"),function:M.object({name:M.string().min(1),description:M.string().optional(),parameters:ns.optional()}).passthrough()}).passthrough(),vX=M.object({name:M.string().min(1),description:M.string().optional(),input_schema:ns.optional()}).passthrough(),kf=M.object({model:M.string().refine((n)=>PX.has(n),{message:"model is not supported"}),stream:M.boolean().default(!1),messages:M.array(jX).min(1),tools:M.array(M.union([aX,vX])).optional(),user:M.string().optional(),prompt_cache_key:M.string().optional(),reasoning_effort:M.enum(["low","medium","high","xhigh","max"]).optional()}).passthrough(),ZX=M.object({type:M.literal("input_text"),text:M.string()}).passthrough(),pX=M.object({type:M.literal("output_text"),text:M.string()}).passthrough(),nz=M.object({type:M.literal("input_image"),image_url:M.string()}).passthrough(),tz=M.object({type:M.literal("encrypted_content"),encrypted_content:M.string()}).passthrough(),iz=new Set(["input_text","output_text","input_image","encrypted_content"]),sz=M.object({type:M.string()}).passthrough().refine((n)=>!iz.has(n.type),{message:"known content parts must have a valid payload"}),Hy=M.union([ZX,pX,nz,tz,sz]),rz=M.object({type:M.literal("message").optional(),role:M.enum(["system","developer","user","assistant"]),content:M.union([M.string(),M.array(Hy)])}).passthrough(),ez=M.object({type:M.literal("agent_message"),author:M.string().min(1),recipient:M.string().min(1),content:M.array(Hy)}).passthrough(),oz=M.object({type:M.literal("function_call"),call_id:M.string().min(1),namespace:M.string().min(1).optional(),name:M.string().min(1),arguments:M.string().transform(CX).refine(Gy,"function arguments must contain valid JSON")}).passthrough(),fz=M.object({type:M.literal("custom_tool_call"),call_id:M.string().min(1),namespace:M.string().min(1).optional(),name:M.string().min(1),input:M.string()}).passthrough(),Wy=M.union([M.string(),M.array(M.object({type:M.string(),text:M.string().optional()}).passthrough())]),hz=M.object({type:M.literal("function_call_output"),call_id:M.string().min(1),output:Wy}).passthrough(),uz=M.object({type:M.literal("custom_tool_call_output"),call_id:M.string().min(1),output:Wy}).passthrough(),Fy=M.object({type:M.literal("function"),name:M.string().min(1),description:M.string().optional(),parameters:ns.optional(),strict:M.boolean().optional()}).passthrough(),qf=M.object({type:M.literal("custom"),name:M.string().min(1),description:M.string().optional(),format:M.object({type:M.literal("grammar"),syntax:M.string().min(1),definition:M.string()}).passthrough().optional()}).passthrough(),cz=M.union([Fy,qf]),_z=M.object({type:M.literal("namespace"),name:M.string().min(1),description:M.string().optional(),tools:M.array(cz)}).passthrough(),wz=M.object({type:M.literal("function"),name:M.string().min(1),description:M.string().optional(),parameters:ns.optional(),inputSchema:ns.optional(),strict:M.boolean().optional()}).passthrough().transform((n)=>({type:"function",name:n.name,...n.description!==void 0?{description:n.description}:{},...n.parameters!==void 0?{parameters:n.parameters}:n.inputSchema!==void 0?{parameters:n.inputSchema}:{},...n.strict!==void 0?{strict:n.strict}:{}})),lz=M.object({type:M.literal("function").optional(),name:M.string().min(1),description:M.string().optional(),parameters:ns.optional(),inputSchema:ns.optional(),strict:M.boolean().optional()}).passthrough().transform((n)=>({type:"function",name:n.name,...n.description!==void 0?{description:n.description}:{},...n.parameters!==void 0?{parameters:n.parameters}:n.inputSchema!==void 0?{parameters:n.inputSchema}:{},...n.strict!==void 0?{strict:n.strict}:{}})),Az=M.union([lz,qf]),Mz=M.object({type:M.literal("namespace"),name:M.string().min(1),description:M.string().optional(),tools:M.array(Az)}).passthrough().transform((n)=>({type:"namespace",name:n.name,...n.description!==void 0?{description:n.description}:{},tools:n.tools})),dz=new Set(["function","custom","namespace"]),Py=M.object({type:M.string()}).passthrough().refine((n)=>!dz.has(n.type),{message:"known tools must have a valid payload"}),Rz=M.union([Fy,qf,_z]),Ez=M.union([Rz,Py]),yz=M.union([wz,qf,Mz,Py]),Tz=M.object({type:M.literal("additional_tools"),role:M.string().optional(),tools:M.array(yz)}).passthrough(),gz=M.object({type:M.literal("summary_text"),text:M.string()}).passthrough(),Sz=M.object({type:M.literal("reasoning_text"),reasoning_text:M.string()}).passthrough(),Iz=M.object({type:M.literal("reasoning"),summary:M.array(gz).nullable().optional(),content:M.array(Sz).nullable().optional(),encrypted_content:M.string().nullable().optional()}).passthrough(),Uz=new Set(["message","agent_message","function_call","custom_tool_call","function_call_output","custom_tool_call_output","additional_tools","reasoning"]),bz=M.object({type:M.string()}).passthrough().refine((n)=>!Uz.has(n.type),{message:"known input items must have a valid payload"}),$z=M.union([rz,ez,oz,fz,hz,uz,Tz,Iz,bz]),Lz=M.object({effort:M.enum(["none","minimal","low","medium","high","xhigh","max"]).optional(),summary:M.unknown().optional()}).passthrough(),Oz=M.object({model:M.string(),input:M.union([M.string(),M.array($z)]),instructions:M.string().optional(),stream:M.boolean().default(!1),tools:M.array(Ez).optional(),tool_choice:M.literal("auto").optional(),parallel_tool_calls:M.boolean().optional(),reasoning:Lz.nullable().optional(),include:M.array(M.string()).optional(),store:M.boolean().optional(),text:M.unknown().optional(),service_tier:M.unknown().optional(),prompt_cache_key:M.string().optional(),client_metadata:M.unknown().optional(),previous_response_id:M.string().optional(),conversation:M.unknown().optional()}).passthrough();function Vf(n){let t=kf.safeParse(n);if(t.success)return{ok:!0,value:t.data};let i=t.error.issues.map((s)=>{return`${s.path.length>0?s.path.join("."):"request"}: ${s.message}`}).join(", ");return{ok:!1,response:v(400,`Invalid request: ${i}`,"invalid_request_error","invalid_request")}}function Dy(n){let t=Oz.safeParse(n);if(t.success)return{ok:!0,value:t.data};let i=t.error.issues.map((s)=>{return`${s.path.length>0?s.path.join("."):"request"}: ${s.message}`}).join(", ");return{ok:!1,response:v(400,`Invalid request: ${i}`,"invalid_request_error","invalid_request")}}import{createHash as Bz}from"crypto";function Nz(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function C_(n){if(n===null||typeof n!=="object")return JSON.stringify(n);if(Array.isArray(n))return`[${n.map(C_).join(",")}]`;return`{${Object.entries(n).filter(([,i])=>i!==void 0).sort(([i],[s])=>i.localeCompare(s)).map(([i,s])=>`${JSON.stringify(i)}:${C_(s)}`).join(",")}}`}function yi(n,t,i,s){return{keyHash:Bz("sha256").update("kiro-provider-session-affinity-v1\x00").update(n).update("\x00").update(t).update("\x00").update(i).update("\x00").update(C_(s)).digest("hex"),source:i}}function Gz(n,t){if(!Nz(n))return;let i=n[t];return typeof i==="string"&&i.length>0?i:void 0}function Hz(n){if(typeof n==="string")return{role:"user",content:n};return n.find((i)=>i.type==="message"&&i.role==="user")??n[0]}function Wz(n){return n.messages.find((t)=>t.role==="user")??n.messages[0]}function Fz(n){return n.messages.find((t)=>t.role==="user")??n.messages[0]}function Yy(n,t){if(!t)return;for(let s of["thread_id","session_id","conversation_id"]){let r=Gz(n.client_metadata,s);if(r!==void 0){let e=`responses.client_metadata.${s}`;return yi(t,"responses",e,r)}}if(n.prompt_cache_key&&n.prompt_cache_key.length>0)return yi(t,"responses","responses.prompt_cache_key",n.prompt_cache_key);let i=Hz(n.input);return i===void 0?void 0:yi(t,"responses","responses.initial_input",i)}function my(n,t){if(!t)return;if(n.prompt_cache_key&&n.prompt_cache_key.length>0)return yi(t,"chat","chat.prompt_cache_key",n.prompt_cache_key);let i=Wz(n);if(i===void 0)return;if(n.user&&n.user.length>0)return yi(t,"chat","chat.user_and_initial_input",{user:n.user,initial:i});return yi(t,"chat","chat.initial_input",i)}function Jy(n,t){if(!t)return;let i=Fz(n);if(i===void 0)return;let s=n.metadata?.user_id;if(s)return yi(t,"anthropic","anthropic.user_and_initial_input",{userId:s,initial:i});return yi(t,"anthropic","anthropic.initial_input",i)}class K_ extends Error{limit;name="RequestBodyTooLargeError";constructor(n){super(`Request body exceeds the ${n} byte limit`);this.limit=n}}function x_(n){return n.reason instanceof Error?n.reason:new DOMException("Request deadline exceeded","TimeoutError")}async function Pz(n,t,i){let s=n.body?.getReader();if(!s)return{ok:!0,text:""};let r=[],e=0,f,o=new Promise((u,c)=>{f=c}),h=()=>{let u=x_(i.combined);f?.(u),cn(()=>s.cancel(u))};i.combined.addEventListener("abort",h,{once:!0});try{while(!0){if(i.combined.aborted)throw x_(i.combined);let _=await Promise.race([s.read(),o]);if(i.combined.aborted)throw x_(i.combined);if(_.done)break;if(e+=_.value.byteLength,e>t)throw new K_(t);r.push(_.value)}let u=new Uint8Array(e),c=0;for(let _ of r)u.set(_,c),c+=_.byteLength;return{ok:!0,text:new TextDecoder().decode(u)}}catch(u){if(u instanceof K_)return cn(()=>s.cancel(u)),{ok:!1,response:v(413,u.message,"invalid_request_error","request_too_large")};if(i.deadline.aborted)return cn(()=>s.cancel(u)),{ok:!1,response:v(504,"Request deadline exceeded","timeout_error","request_timeout")};if(i.client.aborted)return cn(()=>s.cancel(u)),{ok:!1,response:v(499,"Client closed request","request_aborted","client_disconnected")};throw u}finally{i.combined.removeEventListener("abort",h)}}function Dz(n,t,i){let r=(n.body??new ReadableStream({start:(R)=>R.close()})).getReader(),e=new TextDecoder,f=new TextEncoder,o="",h,u,c=f.encode(`data: ${JSON.stringify({error:{message:"Upstream stream error",type:"upstream_error"}})}
|
|
289
|
+
`),f=i.findIndex((_)=>_.role==="user");if(f<0){i.unshift({role:"user",content:[V4(s,"legacy-user-prefix")],toolCalls:[],path:"legacy-user-prefix"});for(let[_,c]of r)r.set(_,c+1);return{messages:i,projectedIndexByOriginal:r}}let h=i[f];if(!h)return{messages:i,projectedIndexByOriginal:r};return i[f]={...h,content:[V4(`${s}
|
|
244
290
|
|
|
245
|
-
`),_=(R)=>{if(h!==void 0)return!1;return h=R,!0},w=()=>{t.deadline.removeEventListener("abort",d)},l=()=>{t.client.removeEventListener("abort",E)},A=(R,y)=>{if(!_(R))return;Wn(w,l,()=>{if(R==="normal-complete")u?.enqueue(f.encode(`data: [DONE]
|
|
291
|
+
`,"legacy-user-prefix"),...h.content]},{messages:i,projectedIndexByOriginal:r}}function gz(n,t){let i=new Set(t.map((f)=>f.wireName)),r=new Map,s=new Set;for(let[f,h]of n.entries()){let _=[...h.toolCalls,...h.content.flatMap((c)=>c.type==="tool_use"?[{id:c.id,name:c.name,input:c.input,path:c.path}]:[])];for(let c of _){if(!i.has(c.name))throw new Mn(`Tool call ${c.id} references ${c.name} without an exact declaration`,"missing_tool_declaration");if(r.has(c.id))throw new Mn(`Duplicate tool call id ${c.id}`,"invalid_tool_history");r.set(c.id,{name:c.name,index:f})}for(let c of h.content){if(c.type!=="tool_result")continue;let o=r.get(c.toolCallId);if(!o||o.index>=f||s.has(c.toolCallId))throw new Mn(`Tool result ${c.toolCallId} has no earlier unique matching call`,"invalid_tool_history");s.add(c.toolCallId)}}}function Sz(n){return n.map((t)=>({toolSpecification:{name:t.wireName,description:t.description??"",inputSchema:{json:{...t.inputSchema}}}}))}function K4(n,t,i,r=!1,s=20000,f={}){if(!b4(n))throw new Mn("CanonicalRequest is required before Kiro projection","canonical_request_required");let h=n;if(h.model!==t)throw new Mn(`CanonicalRequest model ${h.model} does not match pipeline model ${t}`,"canonical_model_mismatch");if(h.messages.length===0)throw new Mn("No messages","empty_input");Ez(h.messages);let{wireId:_,effort:c}=Kt(t),o=Tz(h);if(o.messages.length===0)throw new Mn("No executable messages","empty_input");gz(o.messages,h.tools);let w=(f.resolvedReasoningReplays??[]).map((S)=>{let L=o.projectedIndexByOriginal.get(S.insertBeforeMessage);if(L===void 0)throw new Mn("Reasoning replay does not reference an assistant output message","invalid_reasoning_replay");return{...S,insertBeforeMessage:L}}),e=o.messages.at(-1);if(!e)throw new Mn("No executable messages","empty_input");let u=e.role==="assistant",y=u?o.messages:o.messages.slice(0,-1),A=w.filter((S)=>S.insertBeforeMessage<y.length),R=J4(y,_,A),M=u?{content:"",modelId:_,origin:Hn.ORIGIN_AI_EDITOR}:C4(e,_),E=h.toolChoice==="auto"?Sz(h.tools):[];if(E.length>0)M.userInputMessageContext??={},M.userInputMessageContext.tools=E;if(Q4(R)&&h.toolChoice==="auto"){let S=new Set(E.map((b)=>b.toolSpecification.name)),L=[...z4(R)].filter((b)=>!S.has(b));if(L.length>0)throw new Mn(`Tool history is missing exact declarations for: ${L.join(", ")}`,"missing_tool_declaration")}let g=f.conversationId??Rz(),T={conversationState:{chatTriggerType:Hn.CHAT_TRIGGER_TYPE_MANUAL,conversationId:g,currentMessage:{userInputMessage:M},...R.length>0?{history:R}:{}},...i.profileArn?{profileArn:i.profileArn}:{}};return c===void 0?{request:T,resolved:_,convId:g}:{request:T,resolved:_,convId:g,variantEffort:c}}function x4(n,t,i,r=!1,s=20000,f){let{request:h,resolved:_,convId:c}=K4(n,t,i,r,s,{conversationId:f?.conversationId,resolvedReasoningReplays:f?.resolvedReasoningReplays}),o=P4({model:t,think:r,budget:s,reasoningEffort:n.reasoningEffort,configEffort:f?.effort,autoEffortMapping:f?.autoEffortMapping}),w=n.outputTokenLimit,e=w===void 0?void 0:Hi(t,w);if(e?.ok===!1)throw new Mn(e.message,e.code);return{conversationState:h.conversationState,...h.profileArn?{profileArn:h.profileArn}:{},...e?.ok===!0?{additionalModelRequestFields:e.additionalModelRequestFields}:{},streaming:!0,effectiveModel:_,conversationId:c,region:Vu(i.profileArn)??i.region,...o?{effort:o}:{}}}function kh(n){return Math.ceil(n.length/4)}function qh(){return{text:"",signature:"",signatureConflict:!1,redactedChunks:[]}}function mh(n,t){if(!t)return;if(n.text+=t.text??"",t.signature!==void 0&&t.signature.length>0){if(n.signature.length>0&&n.signature!==t.signature)n.signatureConflict=!0;n.signature=t.signature}if(t.redactedContent&&t.redactedContent.byteLength>0)n.redactedChunks.push(t.redactedContent)}function Gf(n){let t=n.redactedChunks.reduce((h,_)=>h+_.byteLength,0),i;if(t>0){i=new Uint8Array(t);let h=0;for(let _ of n.redactedChunks)i.set(_,h),h+=_.byteLength}let r=n.text.length>0&&i!==void 0,s=n.text.length>0&&n.signature.length>0&&!n.signatureConflict&&i===void 0,f=n.text.length===0&&i!==void 0;return{text:n.text,...s?{signature:n.signature}:{},...!r&&f?{redactedContent:i}:{}}}async function Zh(n,t){if(t?.aborted)return{kind:"aborted"};let i=n.next();if(!t)return{kind:"event",result:await i};return new Promise((r,s)=>{let f=()=>r({kind:"aborted"});t.addEventListener("abort",f,{once:!0}),i.then((h)=>{t.removeEventListener("abort",f),r({kind:"event",result:h})},(h)=>{t.removeEventListener("abort",f),s(h)})})}function ah(n,t){if(!t?.name||!t.toolUseId)return;let i=n.get(t.toolUseId);if(i){i.input+=t.input??"";return}n.set(t.toolUseId,{toolUseId:t.toolUseId,name:t.name,input:t.input??""})}function j4(n){let t=[],i=0;for(let r of n.values()){let s=r.input;try{s=JSON.stringify(JSON.parse(r.input))}catch{s=r.input}t.push({type:"content_block_start",index:i,content_block:{type:"tool_use",id:r.toolUseId,name:r.name,input:{}}},{type:"content_block_delta",index:i,delta:{type:"input_json_delta",partial_json:s}},{type:"content_block_stop",index:i}),i+=1}return t}function vh(n,t){let i=t.metadataEvent?.tokenUsage;if(i)n.outputTokens=i.outputTokens??n.outputTokens,n.totalTokens=i.totalTokens??n.totalTokens,n.inputTokens=i.inputTokens??(i.uncachedInputTokens===void 0?n.inputTokens:i.uncachedInputTokens+(i.cacheReadInputTokens??0)+(i.cacheWriteInputTokens??0));n.contextUsagePercentage=t.contextUsageEvent?.contextUsagePercentage??t.metadataEvent?.contextUsagePercentage??i?.contextUsagePercentage??n.contextUsagePercentage}function ph(n,t,i){let r=n.outputTokens??kh(t),s=n.inputTokens;if(s===void 0&&n.totalTokens!==void 0)s=Math.max(0,n.totalTokens-r);if(s===void 0&&n.contextUsagePercentage!==void 0&&n.contextUsagePercentage>0){let f=Math.round(H4(i)*n.contextUsagePercentage/100);s=Math.max(0,f-r)}return{inputTokens:s??0,outputTokens:r}}class k4 extends Error{name="MissingSdkEventStreamError";constructor(){super("SDK response has no event stream")}}async function q4(n,t,i,r,s={}){let f=n.generateAssistantResponseResponse;if(!f)throw new k4;let h=f[Symbol.asyncIterator](),_=new Map,c={},o="",w=qh(),e=!1,u=!1;try{while(!0){let T=await Zh(h,r);if(T.kind==="aborted"){if(h.return)await h.return();u=!0;break}if(T.result.done){e=!0;break}let S=T.result.value;vh(c,S),mh(w,S.reasoningContentEvent),o+=S.assistantResponseEvent?.content??"",ah(_,S.toolUseEvent)}}finally{if(!e&&!u&&h.return)await h.return()}let y=ph(c,o,t),A=Gf(w),R={text:o,toolCalls:Array.from(_.values(),(T)=>({id:T.toolUseId,name:T.name,input:T.input}))},M=(s.fingerprintOutput??et)(R),E=s.captureReasoning?.(A,M),g={role:"assistant",content:o,...A.text?{reasoning_content:A.text}:{},...s.emitAnthropicReasoningMetadata&&A.signature!==void 0?{reasoning_signature:A.signature}:{},...s.emitAnthropicReasoningMetadata&&A.redactedContent!==void 0?{reasoning_redacted_content:Buffer.from(A.redactedContent).toString("base64")}:{},...s.emitEncryptedReasoning&&E!==void 0?{reasoning_encrypted_content:E}:{},..._.size>0?{tool_calls:Array.from(_.values(),(T)=>({id:T.toolUseId,type:"function",function:{name:T.name,arguments:T.input}}))}:{}};return{id:i,object:"chat.completion",created:Math.floor(Date.now()/1000),model:t,choices:[{index:0,message:g,finish_reason:_.size>0?"tool_calls":"stop"}],usage:{prompt_tokens:y.inputTokens,completion_tokens:y.outputTokens,total_tokens:y.inputTokens+y.outputTokens}}}var Lz=[/input is too long/i,/CONTENT_LENGTH_EXCEEDS_THRESHOLD/i],$z=/econnreset|etimedout|enotfound|network|fetch failed|socket/i;function n0(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function ne(n,t){let i=n[t];return typeof i==="string"?i:void 0}function Oz(n){let t=n.$metadata;if(!n0(t))return;let i=t.httpStatusCode;return typeof i==="number"?i:void 0}function Uz(n){let t=n.$response;if(!n0(t))return;let i=t.headers;if(!n0(i))return;let r={};for(let[s,f]of Object.entries(i))if(typeof f==="string")r[s]=f;else if(typeof f==="number")r[s]=String(f);return Object.keys(r).length>0?r:void 0}function te(n){if(!n0(n))return{message:n instanceof Error?n.message:String(n)};let t=Oz(n),i=ne(n,"message")??String(n),r=ne(n,"name"),s=ne(n,"reason"),f=Uz(n);return{message:i,...t!==void 0?{status:t}:{},...r!==void 0?{code:r}:{},...s!==void 0?{reason:s}:{},...f!==void 0?{headers:f}:{}}}function bz(n){let t=Object.entries(n??{}).find(([r])=>r.toLowerCase()==="retry-after"),i=Number.parseInt(t?.[1]??"60",10);return Number.isFinite(i)&&i>=0?i*1000:60000}function Nz(n){return Lz.some((t)=>t.test(n))}function m4(n,t){if(n.reason==="INVALID_MODEL_ID"){let i=n.status??400;return{action:"fail",status:i,terminalStatus:i}}if(n.reason==="TEMPORARILY_SUSPENDED")return t.accountCount>1?{action:"switch",...n.status!==void 0?{status:n.status}:{}}:{action:"fail",...n.status!==void 0?{status:n.status}:{},terminalStatus:n.status??403};switch(n.status){case 400:return{action:"fail",status:400,terminalStatus:Nz(n.message)?413:400};case 401:return t.retryCount<t.maxRetries?{action:"retry",status:401}:{action:"fail",status:401,terminalStatus:401};case 402:return{action:"fail",status:402,terminalStatus:402};case 403:if(Gr(n.message)){if(!t.forcedRefreshAccountIds.has(t.accountId))return t.forcedRefreshAccountIds.add(t.accountId),{action:"refresh-then-retry",status:403};return t.accountCount>1?{action:"switch",status:403}:{action:"fail",status:403,terminalStatus:403}}if(t.accountCount>1)return{action:"switch",status:403};return t.retryCount<t.maxRetries?{action:"retry",status:403,retryAfterMs:t.retryDelayMs*2**t.retryCount}:{action:"fail",status:403,terminalStatus:403};case 429:{let i=bz(n.headers);return t.accountCount>1?{action:"switch",status:429,retryAfterMs:i}:{action:"retry",status:429,retryAfterMs:i}}case 500:return t.serverErrorCount<5?{action:"retry",status:500,retryAfterMs:1000*2**Math.max(0,t.serverErrorCount-1)}:{action:"switch",status:500};case void 0:if($z.test(n.message))return t.retryCount<t.maxRetries?{action:"retry",retryAfterMs:t.retryDelayMs*2**t.retryCount}:{action:"fail",terminalStatus:500};return{action:"fail",terminalStatus:500};default:return{action:"fail",status:n.status,terminalStatus:n.status}}}var Bz=new Map,Iz=new Map;function Gi(n){return n.reason instanceof Error?n.reason:new DOMException("The request was aborted","AbortError")}function ds(n,t){if(t.aborted)return Promise.reject(Gi(t));return new Promise((i,r)=>{let s=()=>r(Gi(t));t.addEventListener("abort",s,{once:!0}),n.then((f)=>{t.removeEventListener("abort",s),i(f)},(f)=>{t.removeEventListener("abort",s),r(f)})})}function Z4(n,t){if(n<=0)return Promise.resolve();return ds(Bun.sleep(n),t)}async function a4(n,t,i){let r=n.get(t);if(!r)r={tail:Promise.resolve(),waiters:0},n.set(t,r);let s=r,f=s.tail,h,_=new Promise((e)=>{h=e});if(!h)throw TypeError("Queue release was not initialized");let c=h;s.waiters+=1,s.tail=f.catch(()=>{return}).then(()=>_);let o=()=>{if(s.waiters-=1,s.waiters!==0)return;s.tail.finally(()=>{if(s.waiters===0&&n.get(t)===s)n.delete(t)})};try{await ds(f,i)}catch(e){throw c(),o(),e}let w=!1;return()=>{if(w)return;w=!0,c(),o()}}function v4(n,t){return a4(Bz,n,t)}function p4(n,t){return a4(Iz,n,t)}function nT(n,t){if(n)return{signal:n,dispose:()=>{return}};let i=new AbortController,r=setTimeout(()=>i.abort(new DOMException("Request deadline exceeded","TimeoutError")),t);return{signal:i.signal,dispose:()=>clearTimeout(r)}}function tT(n,t,i){let r=[];if(n.type==="content_block_delta"){if(n.delta?.type==="text_delta")r.push({index:0,delta:{content:n.delta.text??""},finish_reason:null});else if(n.delta?.type==="thinking_delta"){if(n.delta.thinking)r.push({index:0,delta:{reasoning_content:n.delta.thinking},finish_reason:null})}else if(n.delta?.type==="input_json_delta")r.push({index:0,delta:{tool_calls:[{index:n.index,function:{arguments:n.delta.partial_json??""}}]},finish_reason:null})}else if(n.type==="content_block_start"&&n.content_block?.type==="tool_use")r.push({index:0,delta:{tool_calls:[{index:n.index,id:n.content_block.id,type:"function",function:{name:n.content_block.name,arguments:""}}]},finish_reason:null});else if(n.type==="message_delta")r.push({index:0,delta:{},finish_reason:n.delta?.stop_reason==="tool_use"?"tool_calls":"stop"});else return null;if(r.length===0)return null;let s={id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1000),model:i,choices:r};if(n.type!=="message_delta")return s;let f=n.usage?.input_tokens??0,h=n.usage?.output_tokens??0;return{...s,usage:{prompt_tokens:f,completion_tokens:h,total_tokens:f+h}}}function iT(n,t){if(n==="thinking"){if(t.thinkingBlockIndex!==null)return[];let r=t.nextBlockIndex++;return t.thinkingBlockIndex=r,[{type:"content_block_start",index:r,content_block:{type:"thinking",thinking:""}}]}if(t.textBlockIndex!==null)return[];let i=t.nextBlockIndex++;return t.textBlockIndex=i,[{type:"content_block_start",index:i,content_block:{type:"text",text:""}}]}function t0(n,t){if(n===null||t.stoppedBlocks.has(n))return[];return t.stoppedBlocks.add(n),[{type:"content_block_stop",index:n}]}function rT(n,t){if(!n)return[];let i=iT("text",t),r=t.textBlockIndex;if(r===null)return i;return i.push({type:"content_block_delta",index:r,delta:{type:"text_delta",text:n}}),i}function sT(n,t){let i=iT("thinking",t),r=t.thinkingBlockIndex;if(r===null)return i;return i.push({type:"content_block_delta",index:r,delta:{type:"thinking_delta",thinking:n}}),i}class fT extends Error{name="MissingSdkEventStreamError";constructor(){super("SDK response has no event stream")}}function Hz(n){let t=n.metadataEvent?.tokenUsage;return typeof t==="object"&&t!==null}function Gz(n){let t=n,i=Object.keys(t).filter((r)=>(r.endsWith("Event")||r==="error"||r==="$unknown")&&t[r]!==void 0).sort();return i.length>0?i:["unknown"]}function Wz(n){try{let t=n.return?.();if(t)Promise.resolve(t).catch(()=>{return})}catch{}}function Wf(n,t,i){return{id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1000),model:t,choices:[{index:0,delta:i,finish_reason:null}]}}async function*_T(n,t,i,r,s={}){let f=n.generateAssistantResponseResponse;if(!f)throw new fT;let h={thinkingRequested:!0,buffer:"",inThinking:!1,thinkingExtracted:!1,thinkingBlockIndex:null,textBlockIndex:null,nextBlockIndex:0,stoppedBlocks:new Set},_=new Map,c={},o=qh(),w=f[Symbol.asyncIterator](),e="",u=!1,y=!1,A=!1,R=!1,M=!1,E=!1,g=($)=>tT($,i,t);try{while(!0){let $=await Zh(w,r);if($.kind==="aborted"){if(w.return)await w.return();E=!0;return}if($.result.done){M=!0;break}let U=$.result.value;if(s.onRawEvent?.(Gz(U)),vh(c,U),mh(o,U.reasoningContentEvent),Hz(U)){s.onCompletionMetadata?.(),E=!0,Wz(w);break}if(s.emitAnthropicReasoningMetadata){if(o.signatureConflict)throw TypeError("Kiro emitted conflicting reasoning signatures");if(o.text.length>0&&o.redactedChunks.length>0)throw TypeError("Kiro mixed visible and redacted reasoning payloads");if(y&&U.reasoningContentEvent?.signature!==void 0&&U.reasoningContentEvent.signature.length>0)throw TypeError("Kiro emitted a reasoning signature after assistant output began")}let X=U.reasoningContentEvent?.text;if(X){if(y)h.thinkingBlockIndex=null,y=!1;u=!0;for(let W of sT(X,h)){let K=g(W);if(K)yield K}}let H=U.assistantResponseEvent?.content;if(H){if(s.emitAnthropicReasoningMetadata){let W=Gf(o);if(u&&!A&&W.signature!==void 0)A=!0,yield Wf(i,t,{reasoning_signature:W.signature});if(!u&&!R&&W.redactedContent!==void 0)R=!0,yield Wf(i,t,{reasoning_redacted_content:Buffer.from(W.redactedContent).toString("base64")})}if(e+=H,u&&!y){for(let W of t0(h.thinkingBlockIndex,h)){let K=g(W);if(K)yield K}y=!0}for(let W of rT(H,h)){let K=g(W);if(K)yield K}}if(U.toolUseEvent)ah(_,U.toolUseEvent)}}finally{if(!M&&!E&&w.return)await w.return()}let T=Gf(o);if(s.emitAnthropicReasoningMetadata){if(u&&!y&&!A&&T.signature!==void 0)A=!0,yield Wf(i,t,{reasoning_signature:T.signature});if(!R&&T.redactedContent!==void 0)R=!0,yield Wf(i,t,{reasoning_redacted_content:Buffer.from(T.redactedContent).toString("base64")})}if(u&&!y)for(let $ of t0(h.thinkingBlockIndex,h)){let U=g($);if(U)yield U}for(let $ of t0(h.textBlockIndex,h)){let U=g($);if(U)yield U}for(let $ of j4(_)){let U=g($);if(U)yield U}let S={text:e,toolCalls:[..._.values()].map(($)=>({id:$.toolUseId,name:$.name,input:$.input}))},L=(s.fingerprintOutput??et)(S),b=s.captureReasoning?.(T,L);if(s.emitEncryptedReasoning&&b!==void 0)yield Wf(i,t,{reasoning_encrypted_content:b});let I=ph(c,e,t),Z=g({type:"message_delta",delta:{type:"message_delta",stop_reason:_.size>0?"tool_use":"end_turn"},usage:{input_tokens:I.inputTokens,output_tokens:I.outputTokens,cache_creation_input_tokens:0,cache_read_input_tokens:0}});if(Z)yield Z}class hT extends Error{timeoutMs;name="StreamIdleTimeoutError";constructor(n){super(`SDK stream idle timeout after ${n}ms`);this.timeoutMs=n}}function cT(n,t,i,r){let s=new Map,f=0,h,_=()=>JSON.stringify(Object.fromEntries([...s.entries()].sort())),c=()=>({model:n.model,conversation_hash:ft(n.conversationId),raw_event_count:f,last_event_type:h,event_type_counts:_()}),o=new AbortController,w=AbortSignal.any([t,o.signal]),e=_T(n.sdkResponse,n.model,n.conversationId,w,{...n.captureReasoning?{captureReasoning:n.captureReasoning}:{},emitEncryptedReasoning:n.emitEncryptedReasoning,emitAnthropicReasoningMetadata:n.emitAnthropicReasoningMetadata,...n.fingerprintOutput?{fingerprintOutput:n.fingerprintOutput}:{},onCompletionMetadata:()=>{dn("info","sdk_stream_completion_metadata_terminal",{model:n.model,conversation_hash:ft(n.conversationId)})},onRawEvent:(L)=>{f+=1,h=L.join("+");for(let b of L)s.set(b,(s.get(b)??0)+1)}})[Symbol.asyncIterator](),u=new TextEncoder,y,A,R,M=()=>{if(A===void 0)return;clearTimeout(A),A=void 0},E=(L)=>{if(y!==void 0)return!1;return y=L,!0},g=()=>{w.removeEventListener("abort",S)},T=(L,b)=>{if(!E(L))return;if(zn(g,M,()=>{if(L==="normal-complete")R?.close();else if(L!=="consumer-cancel")R?.error(b)},r),L!=="normal-complete"&&L!=="consumer-cancel")zn(()=>{if(!o.signal.aborted)o.abort(b)});An(()=>e.return?.(void 0))},S=()=>{T("external-abort",Gi(w))};return new Response(new ReadableStream({start(L){if(R=L,w.addEventListener("abort",S,{once:!0}),w.aborted)S()},async pull(L){if(y!==void 0)return;A=setTimeout(()=>{A=void 0;let b=new hT(i);dn("warn","sdk_stream_idle_timeout",{...c(),idle_timeout_ms:i}),T("idle-timeout",b)},i);try{let b=await e.next();if(y!==void 0)return;if(M(),b.done){dn("info","sdk_stream_completed",c()),T("normal-complete");return}L.enqueue(u.encode(`${JSON.stringify(b.value)}
|
|
292
|
+
`))}catch(b){if(y!==void 0)return;let I=b instanceof Error?b:TypeError("SDK stream failed with a non-Error reason",{cause:b});dn("warn","sdk_stream_upstream_error",{...c(),error_type:I.name}),T("upstream-error",I)}},cancel(L){T("consumer-cancel",L)}}),{headers:{"Content-Type":"application/x-ndjson; charset=utf-8"}})}import{createHash as Dz}from"crypto";import{Agent as Pz}from"http";import{Agent as Yz}from"https";var re=k(wh(),1);var oT=new Map,wT=new Map,Fz=3,ie=50;function wr(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function Xz(n){let t=n.conversationState;if(!wr(t))return;let i=t.currentMessage;if(!wr(i))return;let r=i.userInputMessage;if(!wr(r))return;let s=r.modelId;return typeof s==="string"?s:void 0}function eT(n,t){let i=wr(n)?{...n}:{};for(let[r,s]of Object.entries(t)){let f=i[r];i[r]=wr(f)&&wr(s)?eT(f,s):s}return i}function lz(n,t,i,r,s=uT(r,!1),f={value:n.access}){return{region:t,endpoint:i,token:()=>Promise.resolve({token:f.value}),maxAttempts:Fz,retryMode:"standard",customUserAgent:[[Hn.USER_AGENT]],requestHandler:s}}function uT(n,t){if(n){let i=new zs(n,{keepAlive:t,maxSockets:ie});return new re.NodeHttpHandler({httpAgent:i,httpsAgent:i})}return new re.NodeHttpHandler({httpAgent:new Pz({keepAlive:t,maxSockets:ie}),httpsAgent:new Yz({keepAlive:t,maxSockets:ie})})}function Jz(n){return Dz("sha256").update("kiro-provider-sdk-account-v1\x00").update(n.email??n.refresh).digest("hex")}function yT(n,t,i,r,s,f,h=!1){let _=r??`https://q.${t}.amazonaws.com`,c=JSON.stringify([f??Jz(n),t,_,s??null,h]),o=wT.get(c),w=o!==void 0;if(!o)o={handler:uT(s,h)},wT.set(c,o);let e=JSON.stringify([c,i??null]),u=oT.get(e);if(f!==void 0)dn("info","sdk_connection_pool_selected",{account_hash:ft(f),region:t,effort:i??null,http_keep_alive:h,transport_pool_hit:w,sdk_client_pool_hit:u!==void 0});if(u)return u.tokenState.value=n.access,u.client;let y={value:n.access},A=new Zw(lz(n,t,_,s,o.handler,y));if(A.middlewareStack.add((R)=>async(M)=>{if(M.request instanceof vn.HttpRequest)M.request.headers["x-amzn-kiro-agent-mode"]="vibe";return R(M)},{step:"build",name:"addKiroHeaders"}),i)A.middlewareStack.add((R)=>async(M)=>{if(M.request instanceof vn.HttpRequest&&typeof M.request.body==="string")try{let E=JSON.parse(M.request.body);if(wr(E)){let g=Xz(E);if(g)E.additionalModelRequestFields=eT(E.additionalModelRequestFields,D4(g,i)),M.request.body=JSON.stringify(E)}}catch(E){if(!(E instanceof SyntaxError))throw E}return R(M)},{step:"build",name:"addEffortConfig",priority:"high"});return oT.set(e,{client:A,tokenState:y}),A}function i0(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function Qz(n){if(!i0(n))return!1;let t=n.conversationState;return i0(t)&&typeof t.conversationId==="string"&&i0(t.currentMessage)&&typeof t.chatTriggerType==="string"}function zz(n,t){return{think:t.endsWith("-thinking")||n.thinking?.enabled===!0,budget:n.thinking?.budgetTokens??20000}}function Cz(n,t,i){return fn(n,t,"upstream_error",i)}function dT(n){let t=new Map(n.tools.map((i)=>[i.wireName,i]));return(i)=>et({text:i.text,toolCalls:i.toolCalls.map((r)=>{let s=t.get(r.name);if(!s)return r;if(s.publicType!=="custom")return{...r,name:s.name};let f=r.input;try{let h=JSON.parse(r.input);if(i0(h)&&Object.keys(h).length===1&&typeof h.input==="string")f=h.input}catch{}return{...r,name:s.name,input:f}})})}function fe(){return{kind:"response",response:fn(503,"The account bound to signed reasoning replay is currently unavailable","service_unavailable","reasoning_replay_account_unavailable")}}function Vz(n,t){if(n.body.reasoningReplays.length===0)return{replays:[]};if(!n.tenantId)throw new Sn("Reasoning replay requires an authenticated tenant context","reasoning_replay_context_required");let i=t?.accountId,r=t?.conversationId,s=[];for(let f of n.body.reasoningReplays){if(f.lookup.kind==="anthropic-direct"){if(i===void 0||r===void 0)throw new Sn("Anthropic signed thinking replay requires an existing account/conversation affinity","reasoning_replay_context_required");s.push({insertBeforeMessage:f.insertBeforeMessage,content:f.lookup.content});continue}let h=n.reasoningReplayStore;if(!h)throw new Sn("Reasoning replay storage is unavailable","reasoning_replay_store_unavailable",!0);let _={tenantId:n.tenantId,model:n.body.model,outputFingerprint:f.outputFingerprint,...i!==void 0?{accountId:i}:{},...r!==void 0?{conversationId:r}:{}},c=f.lookup.kind==="responses-token"?h.resolveResponses(f.lookup.encryptedContent,_,f.insertBeforeMessage):h.resolveChat(f.lookup.reasoningText,_,f.insertBeforeMessage);if(i!==void 0&&i!==c.accountId||r!==void 0&&r!==c.conversationId)throw new Sn("Reasoning replay items resolve to different accounts or conversations","reasoning_replay_context_mismatch");i=c.accountId,r=c.conversationId,s.push(c.replay)}return{...i!==void 0?{accountId:i}:{},...r!==void 0?{conversationId:r}:{},replays:s}}function Kz(n,t,i){let r=n.body,s=r.includeEncryptedReasoning===!0,f=r.protocol==="anthropic-messages";if(!n.reasoningReplayStore||!n.tenantId)return{emitEncryptedReasoning:s,emitAnthropicReasoningMetadata:f,...r?{fingerprintOutput:dT(r)}:{}};return{captureReasoning:(h,_)=>n.reasoningReplayStore?.store(h,{tenantId:n.tenantId,model:r.model,accountId:t,conversationId:i,outputFingerprint:_}),emitEncryptedReasoning:s,emitAnthropicReasoningMetadata:f,fingerprintOutput:dT(r)}}async function xz(n,t){let{think:i,budget:r}=zz(n.body,n.model),s=new Set,f=new Map,h=0,_=0,c=n.affinity&&n.affinityStore?n.affinityStore.getSessionAffinity(n.affinity.keyHash):void 0,o=Vz(n,c),w=o.accountId!==void 0,e=o.accountId??c?.accountId,u,y=o.conversationId??c?.conversationId;while(!0){if(t.aborted)throw Gi(t);if(_+=1,_>n.config.max_request_iterations)return{kind:"response",response:fn(500,`Exceeded max iterations (${n.config.max_request_iterations})`,"request_error","max_request_iterations")};n.accountManager.reconcileFromDb();let A=n.accountManager.selectHealthyAccount(e);if(!A||o.accountId!==void 0&&A.id!==o.accountId){if(w)return fe();return{kind:"response",response:fn(503,"All accounts are unhealthy or rate-limited","service_unavailable","no_healthy_accounts")}}let R=Date.now();if(n.affinity&&n.affinityStore)if(!c){let S=n.affinityStore.claimSessionAffinity(n.affinity.keyHash,A.id,y??se(),R,n.config.session_affinity_ttl_ms,n.config.session_affinity_max_entries);if(c=S,e=S.accountId,y=S.conversationId,w&&(S.accountId!==o.accountId||S.conversationId!==o.conversationId))throw new Sn("Session affinity conflicts with signed reasoning replay","reasoning_replay_context_mismatch");if(S.accountId!==A.id)continue}else if(c.accountId===A.id)c=n.affinityStore.claimSessionAffinity(n.affinity.keyHash,A.id,c.conversationId,R,n.config.session_affinity_ttl_ms,n.config.session_affinity_max_entries),y=c.conversationId;else c=n.affinityStore.rebindSessionAffinity(n.affinity.keyHash,A.id,se(),R,n.config.session_affinity_ttl_ms,n.config.session_affinity_max_entries),y=c.conversationId;else if(!w&&u!==A.id)u=A.id,y=se();e=A.id,dn("info","upstream_affinity_selected",{projection_mode:n.config.protocol_projection_mode,session_affinity_mode:n.config.session_affinity_mode,affinity_source:n.affinity?.source,affinity_bound:n.affinity!==void 0,account_hash:ft(A.id),conversation_hash:y===void 0?void 0:ft(y),reasoning_replay_locked:w});let M=await p4(A.id,t),E=!0,g=A,T=!1;try{let S=n.accountManager.toAuthDetails(A);g=await ds(n.tokenRefresher.refreshIfNeeded(A,S,t),t);let L=n.accountManager.toAuthDetails(g),b=zf.safeParse(n.config.effort),I=x4(n.body,n.model,L,i,r,{autoEffortMapping:n.config.auto_effort_mapping,conversationId:y,resolvedReasoningReplays:o.replays,...b.success?{effort:b.data}:{}}),$=(n.makeClient??yT)(L,I.region,I.effort,n.config.test_upstream_endpoint,Qr(n.config),g.id,n.config.sdk_http_keep_alive),U={conversationState:I.conversationState,...I.profileArn?{profileArn:I.profileArn}:{},...I.additionalModelRequestFields?{additionalModelRequestFields:I.additionalModelRequestFields}:{}};if(!Qz(U))throw TypeError("Transformed request is not a valid SDK command input");let X=new aw(U);T=!0;let H=await ds($.send(X,{abortSignal:t}),t),W=Kz(n,g.id,I.conversationId);if(n.stream)return E=!1,{kind:"stream",sdkResponse:H,model:n.model,conversationId:I.conversationId,...W,releaseAccount:M};let K=await q4(H,n.model,I.conversationId,t,W);if(t.aborted)throw Gi(t);return{kind:"response",response:Response.json(K,{headers:{"Content-Type":"application/json"}})}}catch(S){if(t.aborted)throw Gi(t);if(!T){if(S instanceof Mn||S instanceof Sn)throw S;if(w)return fe();throw S}let L=te(S),b=L.status===500?(f.get(g.id)??0)+1:0;if(L.status===500)f.set(g.id,b);let I=m4(L,{accountId:g.id,accountCount:n.accountManager.getAccountCount(),retryCount:h,maxRetries:n.config.rate_limit_max_retries,serverErrorCount:b,retryDelayMs:n.config.rate_limit_retry_delay_ms,forcedRefreshAccountIds:s});switch(I.action){case"refresh-then-retry":await ds(n.tokenRefresher.forceRefresh(g,t),t);continue;case"retry":h+=1,await Z4(I.retryAfterMs??0,t);continue;case"switch":if(w)return fe();if(L.reason==="TEMPORARILY_SUSPENDED")n.accountManager.markUnhealthy(g,`InvalidTokenException: Account Suspended: ${L.message}`);else n.accountManager.markRateLimited(g,Date.now()+(I.retryAfterMs??n.config.rate_limit_retry_delay_ms));if(e=void 0,u=void 0,!n.affinityStore)y=void 0;continue;case"fail":if(L.reason==="TEMPORARILY_SUSPENDED")n.accountManager.markUnhealthy(g,`InvalidTokenException: Account Suspended: ${L.message}`);return{kind:"response",response:Cz(I.terminalStatus??I.status??500,L.message,L.code)}}}finally{if(E)M()}}}async function As(n){let t=nT(n.deadlineSignal,n.config.request_timeout_ms),i,r,s=!1;try{if(n.affinity)i=await v4(n.affinity.keyHash,t.signal);let f=await xz(n,t.signal);if(f.kind==="response")return f.response;r=f.releaseAccount;let h=r,_=i,c=(n.createStreamResponse??cT)(f,t.signal,n.config.stream_idle_timeout_ms,()=>{h(),_?.(),t.dispose()});return r=void 0,i=void 0,s=!0,c}catch(f){if(f instanceof Mn)return fn(400,f.message,"invalid_request_error",f.code,f.param);if(f instanceof Sn)return fn(f.retryable?503:400,f.message,f.retryable?"service_unavailable":"invalid_request_error",f.code);if(t.signal.aborted)return fn(504,"Request deadline exceeded","timeout_error","request_timeout");let h=te(f);return fn(500,h.message,"internal_error",h.code)}finally{if(!s)r?.(),i?.(),t.dispose()}}function Y(n,t,i){return i===void 0?{ok:!1,code:n,message:t}:{ok:!1,code:n,message:t,param:i}}var jz=new Set(["model","stream","stream_options","messages","tools","tool_choice","parallel_tool_calls","user","prompt_cache_key","reasoning_effort","max_tokens","max_completion_tokens","temperature","top_p","response_format","n","stop","seed","presence_penalty","frequency_penalty","logit_bias","logprobs","top_logprobs","modalities","audio","prediction","store","metadata","service_tier"]),kz=["temperature","top_p","response_format","n","stop","seed","presence_penalty","frequency_penalty","logit_bias","logprobs","top_logprobs","modalities","audio","prediction","metadata","service_tier"];function r0(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function pn(n,t,i){for(let r of Object.keys(n)){if(i.has(r))continue;return Y("unsupported_parameter",`Chat field ${t}.${r} is not supported`,`${t}.${r}`)}return{ok:!0,value:void 0}}function s0(n,t){return{type:"text",text:n,path:t}}function qz(n,t){if(typeof n==="string")return{ok:!0,value:[s0(n,t)]};if(!Array.isArray(n))return{ok:!0,value:[]};let i=[];for(let[r,s]of n.entries()){let f=`${t}.${r}`;switch(s.type){case"text":{let h=pn(s,f,new Set(["type","text"]));if(!h.ok)return h;i.push(s0(s.text,`${f}.text`));break}case"image_url":{let h=pn(s,f,new Set(["type","image_url"]));if(!h.ok)return h;let _=pn(s.image_url,`${f}.image_url`,new Set(["url","detail"]));if(!_.ok)return _;if(s.image_url.detail!==void 0)return Y("unsupported_parameter","Chat image detail cannot be represented by the Kiro upstream",`${f}.image_url.detail`);if(!s.image_url.url.startsWith("data:"))return Y("unsupported_image_source","Chat images must use data URLs because Kiro cannot fetch remote image URLs",`${f}.image_url.url`);i.push({type:"image",url:s.image_url.url,path:`${f}.image_url.url`});break}case"image":{let h=pn(s,f,new Set(["type","source"]));if(!h.ok)return h;let _=pn(s.source,`${f}.source`,new Set(["type","data","media_type"]));if(!_.ok)return _;if(s.source.type!=="base64")return Y("unsupported_image_source","Chat image sources must use type=base64",`${f}.source.type`);i.push({type:"image",data:s.source.data,...s.source.media_type!==void 0?{mediaType:s.source.media_type}:{},path:`${f}.source`});break}case"tool_use":{let h=pn(s,f,new Set(["type","id","name","input"]));if(!h.ok)return h;i.push({type:"tool_use",id:s.id,name:s.name,input:s.input,path:f});break}case"tool_result":{let h=pn(s,f,new Set(["type","tool_use_id","content","is_error"]));if(!h.ok)return h;let _=mz(s.content,`${f}.content`);if(!_.ok)return _;i.push({type:"tool_result",toolCallId:s.tool_use_id,content:_.value,isError:s.is_error===!0,path:f});break}case"thinking":return Y("unsupported_content_part",`Chat content part ${f} uses unsupported type thinking`,f)}}return{ok:!0,value:i}}function mz(n,t){if(typeof n==="string")return{ok:!0,value:[s0(n,t)]};if(!Array.isArray(n))return Y("unsupported_tool_result_content",`Tool result ${t} must be a string or an array of text blocks`,t);let i=[];for(let[r,s]of n.entries()){if(!r0(s)||s.type!=="text"||typeof s.text!=="string")return Y("unsupported_tool_result_content",`Tool result ${t}.${r} must be a text block`,`${t}.${r}`);let f=pn(s,`${t}.${r}`,new Set(["type","text"]));if(!f.ok)return f;i.push(s0(s.text,`${t}.${r}.text`))}return{ok:!0,value:i}}function Zz(n,t){let i=pn(n,t,new Set(["id","type","function"]));if(!i.ok)return i;let r=pn(n.function,`${t}.function`,new Set(["name","arguments"]));if(!r.ok)return r;try{return{ok:!0,value:{id:n.id,name:n.function.name,input:JSON.parse(n.function.arguments),path:t}}}catch(s){if(!(s instanceof SyntaxError))throw s;return Y("invalid_tool_history",`Tool call ${t} contains invalid JSON arguments`,`${t}.function.arguments`)}}function az(n){let t=[],i=new Set;for(let[r,s]of(n??[]).entries()){let f=`tools.${r}`,h=r0(s.function)?s.function:void 0;if(h!==void 0){let e=pn(s,f,new Set(["type","function"]));if(!e.ok)return e;let u=pn(h,`${f}.function`,new Set(["name","description","parameters","strict"]));if(!u.ok)return u;if(h.strict===!0)return Y("unsupported_strict_tools","Chat function strict=true cannot be guaranteed by the Kiro upstream",`${f}.function.strict`)}else{let e=pn(s,f,new Set(["name","description","input_schema"]));if(!e.ok)return e}let _=typeof h?.name==="string"?h.name:s.name;if(typeof _!=="string"||_.length===0)return Y("invalid_tool_declaration",`Tool declaration ${f} requires a name`,f);let c=_;if(i.has(c))return Y("invalid_tool_declaration",`Duplicate tool declaration ${c}`,f);i.add(c);let o=typeof h?.description==="string"?h.description:typeof s.description==="string"?s.description:void 0,w=h!==void 0?r0(h.parameters)?h.parameters:{}:r0(s.input_schema)?s.input_schema:{};t.push({publicType:"function",name:c,wireName:c,...o!==void 0?{description:o}:{},inputSchema:w,...h!==void 0?{strict:!1}:{},path:f})}return{ok:!0,value:t}}function vz(n,t){let i=new Set(t.map((f)=>f.wireName)),r=new Map,s=new Set;for(let[f,h]of n.entries()){for(let _ of h.toolCalls){if(!i.has(_.name))return Y("missing_tool_declaration",`Tool call ${_.id} references ${_.name} without an exact tool declaration`,_.path);if(r.has(_.id))return Y("invalid_tool_history",`Duplicate tool call id ${_.id}`,_.path);r.set(_.id,{name:_.name,index:f})}for(let _ of h.content){if(_.type!=="tool_result")continue;let c=r.get(_.toolCallId);if(!c||c.index>=f||s.has(_.toolCallId))return Y("invalid_tool_history",`Tool result ${_.toolCallId} has no earlier unique matching call`,_.path);s.add(_.toolCallId)}}return{ok:!0,value:void 0}}function AT(n,t){for(let o of Object.keys(n))if(!jz.has(o))return Y("unsupported_parameter",`Chat parameter ${o} is not supported`,o);if(n.stream_options!==void 0){let o=pn(n.stream_options,"stream_options",new Set(["include_usage"]));if(!o.ok)return o;if(!n.stream)return Y("unsupported_parameter","Chat stream_options requires stream=true","stream_options")}for(let o of kz)if(n[o]!==void 0)return Y("unsupported_parameter",`Chat parameter ${o} cannot be represented by the Kiro upstream`,o);if(n.store===!0)return Y("unsupported_parameter","Chat parameter store=true is not supported","store");if(n.max_tokens!==void 0&&n.max_completion_tokens!==void 0)return Y("conflicting_output_token_limits","Chat max_tokens and max_completion_tokens cannot both be supplied","max_completion_tokens");let i=n.max_completion_tokens??n.max_tokens,r=n.max_completion_tokens!==void 0?"max_completion_tokens":"max_tokens";if(i!==void 0){let o=Hi(n.model,i);if(!o.ok)return Y(o.code,o.message,r)}if(n.parallel_tool_calls===!1)return Y("unsupported_parallel_tool_calls","parallel_tool_calls=false cannot be guaranteed by the Kiro upstream","parallel_tool_calls");if(n.tool_choice==="required"||typeof n.tool_choice==="object"&&n.tool_choice!==null)return Y("unsupported_tool_choice","Required or named tool choice cannot be represented by the Kiro upstream","tool_choice");let s=az(n.tools);if(!s.ok)return s;let f=[],h=[];for(let[o,w]of n.messages.entries()){let e=`messages.${o}`,u=w.role==="assistant"?new Set(["role","content","tool_calls","reasoning_content"]):w.role==="tool"?new Set(["role","content","tool_call_id"]):new Set(["role","content"]);for(let E of Object.keys(w))if(!u.has(E))return Y("unsupported_message_field",`Chat message field ${e}.${E} is not supported`,`${e}.${E}`);if(t==="safe"&&(w.role==="system"||w.role==="developer"))return Y("unsupported_instruction_projection",`${w.role} messages cannot be projected losslessly to Kiro; use legacy-user-prefix explicitly to migrate`,e);let y=qz(w.content,`${e}.content`);if(!y.ok)return y;let A=[];if(w.role==="assistant")for(let[E,g]of(w.tool_calls??[]).entries()){let T=Zz(g,`${e}.tool_calls.${E}`);if(!T.ok)return T;A.push(T.value)}let R=y.value;if(w.role==="tool"){let E=R.filter((g)=>g.type==="text");if(E.length!==R.length)return Y("unsupported_tool_result_content",`Chat tool message ${e} may contain text only`,`${e}.content`);R=[{type:"tool_result",toolCallId:w.tool_call_id,content:E,isError:!1,path:e}]}let M={role:w.role,content:R,toolCalls:A,path:e};if(w.role==="assistant"&&w.reasoning_content!==void 0)h.push({lookup:{kind:"chat-hash",reasoningText:w.reasoning_content},outputFingerprint:et({text:si(R),toolCalls:(w.tool_calls??[]).map((E)=>({id:E.id,name:E.function.name,input:E.function.arguments}))}),insertBeforeMessage:f.length,path:`${e}.reasoning_content`});f.push(M)}let _=vz(f,s.value);if(!_.ok)return _;let c=new Set;for(let o of f){for(let w of o.toolCalls)c.add(w.id);for(let w of o.content)if(w.type==="tool_result")c.delete(w.toolCallId)}if(n.tool_choice==="none"&&c.size>0)return Y("unsupported_tool_choice","tool_choice=none cannot be used while tool calls are awaiting results","tool_choice");return{ok:!0,value:{canonicalVersion:1,protocol:"chat-completions",projectionMode:t,model:n.model,stream:n.stream,messages:f,tools:s.value,toolChoice:n.tool_choice==="none"?"none":"auto",...n.reasoning_effort!==void 0?{reasoningEffort:n.reasoning_effort,requestedReasoningEffort:n.reasoning_effort}:{},...i!==void 0?{outputTokenLimit:i}:{},reasoningReplays:h,includeEncryptedReasoning:!1,...n.prompt_cache_key!==void 0?{promptCacheKey:n.prompt_cache_key}:{}}}}var Df=Object.freeze({input:Object.freeze(["text"]),output:Object.freeze(["text"])}),In=Object.freeze({input:Object.freeze(["text","image"]),output:Object.freeze(["text"])}),en=Object.freeze({input:Object.freeze(["text","image","pdf"]),output:Object.freeze(["text"])}),RT=Object.freeze(["auto","claude-sonnet-4","claude-sonnet-4-5","claude-sonnet-4-6","claude-sonnet-4-6-low","claude-sonnet-4-6-medium","claude-sonnet-4-6-high","claude-sonnet-4-6-max","claude-sonnet-5","claude-sonnet-5-low","claude-sonnet-5-medium","claude-sonnet-5-high","claude-sonnet-5-xhigh","claude-sonnet-5-max","claude-haiku-4-5","claude-opus-4-5","claude-opus-4-6","claude-opus-4-7","claude-opus-4-7-low","claude-opus-4-7-medium","claude-opus-4-7-high","claude-opus-4-7-xhigh","claude-opus-4-7-max","claude-opus-4-8","claude-opus-4-8-low","claude-opus-4-8-medium","claude-opus-4-8-high","claude-opus-4-8-xhigh","claude-opus-4-8-max","claude-opus-4-8-thinking","deepseek-3.2","glm-5","minimax-m2.5","minimax-m2.1","qwen3-coder-next","gpt-5.6-sol","gpt-5.6-sol-low","gpt-5.6-sol-medium","gpt-5.6-sol-high","gpt-5.6-sol-xhigh","gpt-5.6-sol-max","gpt-5.6-terra","gpt-5.6-terra-low","gpt-5.6-terra-medium","gpt-5.6-terra-high","gpt-5.6-terra-xhigh","gpt-5.6-terra-max","gpt-5.6-luna","gpt-5.6-luna-low","gpt-5.6-luna-medium","gpt-5.6-luna-high","gpt-5.6-luna-xhigh","gpt-5.6-luna-max"]),f0=Object.freeze([{id:"auto",wireId:"auto",name:"Auto (1.0x)",contextLimit:l("auto"),outputLimit:64000,modalities:en},{id:"claude-sonnet-4",wireId:"claude-sonnet-4",name:"Claude Sonnet 4.0 (1.3x)",contextLimit:l("claude-sonnet-4"),outputLimit:64000,modalities:en},{id:"claude-sonnet-4-5",wireId:"claude-sonnet-4.5",name:"Claude Sonnet 4.5 (1.3x)",contextLimit:l("claude-sonnet-4-5"),outputLimit:64000,modalities:en},{id:"claude-sonnet-4-6",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (1.3x)",contextLimit:l("claude-sonnet-4-6"),outputLimit:64000,modalities:en},{id:"claude-sonnet-4-6-low",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (low) (1.3x)",contextLimit:l("claude-sonnet-4-6"),outputLimit:64000,modalities:en},{id:"claude-sonnet-4-6-medium",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (medium) (1.3x)",contextLimit:l("claude-sonnet-4-6"),outputLimit:64000,modalities:en},{id:"claude-sonnet-4-6-high",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (high) (1.3x)",contextLimit:l("claude-sonnet-4-6"),outputLimit:64000,modalities:en},{id:"claude-sonnet-4-6-max",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (max) (1.3x)",contextLimit:l("claude-sonnet-4-6"),outputLimit:64000,modalities:en},{id:"claude-sonnet-5",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (1.3x)",contextLimit:l("claude-sonnet-5"),outputLimit:64000,modalities:en},{id:"claude-sonnet-5-low",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (low) (1.3x)",contextLimit:l("claude-sonnet-5"),outputLimit:64000,modalities:en},{id:"claude-sonnet-5-medium",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (medium) (1.3x)",contextLimit:l("claude-sonnet-5"),outputLimit:64000,modalities:en},{id:"claude-sonnet-5-high",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (high) (1.3x)",contextLimit:l("claude-sonnet-5"),outputLimit:64000,modalities:en},{id:"claude-sonnet-5-xhigh",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (xhigh) (1.3x)",contextLimit:l("claude-sonnet-5"),outputLimit:64000,modalities:en},{id:"claude-sonnet-5-max",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (max) (1.3x)",contextLimit:l("claude-sonnet-5"),outputLimit:64000,modalities:en},{id:"claude-haiku-4-5",wireId:"claude-haiku-4.5",name:"Claude Haiku 4.5 (0.4x)",contextLimit:l("claude-haiku-4-5"),outputLimit:64000,modalities:In},{id:"claude-opus-4-5",wireId:"claude-opus-4.5",name:"Claude Opus 4.5 (2.2x)",contextLimit:l("claude-opus-4-5"),outputLimit:64000,modalities:en},{id:"claude-opus-4-6",wireId:"claude-opus-4.6",name:"Claude Opus 4.6 (2.2x)",contextLimit:l("claude-opus-4-6"),outputLimit:64000,modalities:en},{id:"claude-opus-4-7",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (2.2x)",contextLimit:l("claude-opus-4-7"),outputLimit:64000,modalities:en},{id:"claude-opus-4-7-low",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (low) (2.2x)",contextLimit:l("claude-opus-4-7"),outputLimit:64000,modalities:en},{id:"claude-opus-4-7-medium",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (medium) (2.2x)",contextLimit:l("claude-opus-4-7"),outputLimit:64000,modalities:en},{id:"claude-opus-4-7-high",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (high) (2.2x)",contextLimit:l("claude-opus-4-7"),outputLimit:64000,modalities:en},{id:"claude-opus-4-7-xhigh",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (xhigh) (2.2x)",contextLimit:l("claude-opus-4-7"),outputLimit:64000,modalities:en},{id:"claude-opus-4-7-max",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (max) (2.2x)",contextLimit:l("claude-opus-4-7"),outputLimit:64000,modalities:en},{id:"claude-opus-4-8",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (2.2x)",contextLimit:l("claude-opus-4-8"),outputLimit:64000,modalities:en},{id:"claude-opus-4-8-low",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (low) (2.2x)",contextLimit:l("claude-opus-4-8"),outputLimit:64000,modalities:en},{id:"claude-opus-4-8-medium",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (medium) (2.2x)",contextLimit:l("claude-opus-4-8"),outputLimit:64000,modalities:en},{id:"claude-opus-4-8-high",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (high) (2.2x)",contextLimit:l("claude-opus-4-8"),outputLimit:64000,modalities:en},{id:"claude-opus-4-8-xhigh",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (xhigh) (2.2x)",contextLimit:l("claude-opus-4-8"),outputLimit:64000,modalities:en},{id:"claude-opus-4-8-max",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (max) (2.2x)",contextLimit:l("claude-opus-4-8"),outputLimit:64000,modalities:en},{id:"claude-opus-4-8-thinking",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 Thinking (2.2x)",contextLimit:l("claude-opus-4-8"),outputLimit:64000,modalities:en},{id:"deepseek-3.2",wireId:"deepseek-3.2",name:"DeepSeek 3.2 (0.25x)",contextLimit:l("deepseek-3.2"),outputLimit:64000,modalities:Df},{id:"glm-5",wireId:"glm-5",name:"GLM-5 (0.5x)",contextLimit:l("glm-5"),outputLimit:64000,modalities:Df},{id:"minimax-m2.5",wireId:"minimax-m2.5",name:"MiniMax M2.5 (0.25x)",contextLimit:l("minimax-m2.5"),outputLimit:64000,modalities:Df},{id:"minimax-m2.1",wireId:"minimax-m2.1",name:"MiniMax M2.1 (0.15x)",contextLimit:l("minimax-m2.1"),outputLimit:64000,modalities:Df},{id:"qwen3-coder-next",wireId:"qwen3-coder-next",name:"Qwen3 Coder Next (0.05x)",contextLimit:l("qwen3-coder-next"),outputLimit:64000,modalities:Df},{id:"gpt-5.6-sol",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (2.4x)",contextLimit:l("gpt-5.6-sol"),outputLimit:64000,modalities:In},{id:"gpt-5.6-sol-low",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (low) (2.4x)",contextLimit:l("gpt-5.6-sol"),outputLimit:64000,modalities:In},{id:"gpt-5.6-sol-medium",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (medium) (2.4x)",contextLimit:l("gpt-5.6-sol"),outputLimit:64000,modalities:In},{id:"gpt-5.6-sol-high",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (high) (2.4x)",contextLimit:l("gpt-5.6-sol"),outputLimit:64000,modalities:In},{id:"gpt-5.6-sol-xhigh",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (xhigh) (2.4x)",contextLimit:l("gpt-5.6-sol"),outputLimit:64000,modalities:In},{id:"gpt-5.6-sol-max",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (max) (2.4x)",contextLimit:l("gpt-5.6-sol"),outputLimit:64000,modalities:In},{id:"gpt-5.6-terra",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (1.2x)",contextLimit:l("gpt-5.6-terra"),outputLimit:64000,modalities:In},{id:"gpt-5.6-terra-low",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (low) (1.2x)",contextLimit:l("gpt-5.6-terra"),outputLimit:64000,modalities:In},{id:"gpt-5.6-terra-medium",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (medium) (1.2x)",contextLimit:l("gpt-5.6-terra"),outputLimit:64000,modalities:In},{id:"gpt-5.6-terra-high",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (high) (1.2x)",contextLimit:l("gpt-5.6-terra"),outputLimit:64000,modalities:In},{id:"gpt-5.6-terra-xhigh",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (xhigh) (1.2x)",contextLimit:l("gpt-5.6-terra"),outputLimit:64000,modalities:In},{id:"gpt-5.6-terra-max",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (max) (1.2x)",contextLimit:l("gpt-5.6-terra"),outputLimit:64000,modalities:In},{id:"gpt-5.6-luna",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna",contextLimit:l("gpt-5.6-luna"),outputLimit:64000,modalities:In},{id:"gpt-5.6-luna-low",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (low)",contextLimit:l("gpt-5.6-luna"),outputLimit:64000,modalities:In},{id:"gpt-5.6-luna-medium",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (medium)",contextLimit:l("gpt-5.6-luna"),outputLimit:64000,modalities:In},{id:"gpt-5.6-luna-high",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (high)",contextLimit:l("gpt-5.6-luna"),outputLimit:64000,modalities:In},{id:"gpt-5.6-luna-xhigh",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (xhigh)",contextLimit:l("gpt-5.6-luna"),outputLimit:64000,modalities:In},{id:"gpt-5.6-luna-max",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (max)",contextLimit:l("gpt-5.6-luna"),outputLimit:64000,modalities:In}]);var er=d.record(d.unknown()),pz=new Set(RT),nC=d.record(d.string()).superRefine((n,t)=>{let i=Object.entries(n);if(i.length>16)t.addIssue({code:d.ZodIssueCode.custom,message:"metadata must contain at most 16 entries"});for(let[r,s]of i){if(r.length>64)t.addIssue({code:d.ZodIssueCode.custom,message:"metadata keys must contain at most 64 characters",path:[r]});if(s.length>512)t.addIssue({code:d.ZodIssueCode.custom,message:"metadata values must contain at most 512 characters",path:[r]})}}),tC=d.object({type:d.literal("text"),text:d.string()}).passthrough(),iC=d.object({type:d.literal("image_url"),image_url:d.object({url:d.string(),detail:d.string().optional()}).passthrough()}).passthrough(),rC=d.object({type:d.literal("image"),source:d.object({type:d.string(),data:d.string(),media_type:d.string().optional()}).passthrough()}).passthrough(),sC=d.object({type:d.literal("tool_result"),tool_use_id:d.string().min(1),content:d.unknown()}).passthrough(),fC=d.object({type:d.literal("tool_use"),id:d.string().min(1),name:d.string().min(1),input:d.unknown()}).passthrough(),_C=d.object({type:d.literal("thinking"),thinking:d.string().optional(),text:d.string().optional()}).passthrough(),hC=d.discriminatedUnion("type",[tC,iC,rC,sC,fC,_C]),Pf=d.union([d.string(),d.array(hC)]);function MT(n){try{return JSON.parse(n),!0}catch(t){if(t instanceof SyntaxError)return!1;throw t}}function cC(n){return n.trim().length===0?"{}":n}var oC=d.object({id:d.string().min(1),type:d.literal("function"),function:d.object({name:d.string().min(1),arguments:d.string().refine(MT,"function arguments must contain valid JSON")}).passthrough()}).passthrough(),wC=d.object({role:d.literal("system"),content:Pf}).passthrough(),eC=d.object({role:d.literal("developer"),content:Pf}).passthrough(),uC=d.object({role:d.literal("user"),content:Pf}).passthrough(),yC=d.object({role:d.literal("assistant"),content:Pf.nullable().optional(),tool_calls:d.array(oC).min(1).optional(),reasoning_content:d.string().optional()}).passthrough().refine((n)=>n.content!==null&&n.content!==void 0?!0:n.tool_calls!==void 0,{message:"assistant message requires content or tool_calls"}),dC=d.object({role:d.literal("tool"),content:Pf,tool_call_id:d.string().min(1)}).passthrough(),AC=d.union([wC,eC,uC,yC,dC]),RC=d.object({type:d.literal("function"),function:d.object({name:d.string().min(1),description:d.string().optional(),parameters:er.optional()}).passthrough()}).passthrough(),MC=d.object({name:d.string().min(1),description:d.string().optional(),input_schema:er.optional()}).passthrough(),EC=d.object({model:d.string().refine((n)=>pz.has(n),{message:"model is not supported"}),stream:d.boolean().default(!1),stream_options:d.object({include_usage:d.boolean().optional()}).passthrough().optional(),messages:d.array(AC).min(1),tools:d.array(d.union([RC,MC])).optional(),user:d.string().optional(),prompt_cache_key:d.string().optional(),reasoning_effort:d.enum(["low","medium","high","xhigh","max"]).optional(),tool_choice:d.union([d.enum(["auto","none","required"]),d.object({type:d.literal("function"),function:d.object({name:d.string().min(1)}).passthrough()}).passthrough()]).optional(),parallel_tool_calls:d.boolean().optional(),max_tokens:d.number().int().positive().optional(),max_completion_tokens:d.number().int().positive().optional(),temperature:d.number().optional(),top_p:d.number().optional(),response_format:d.unknown().optional(),n:d.number().int().positive().optional(),stop:d.unknown().optional(),seed:d.number().int().optional(),presence_penalty:d.number().optional(),frequency_penalty:d.number().optional(),logit_bias:d.unknown().optional(),logprobs:d.boolean().optional(),top_logprobs:d.number().int().optional(),modalities:d.unknown().optional(),audio:d.unknown().optional(),prediction:d.unknown().optional(),store:d.boolean().optional(),metadata:d.unknown().optional(),service_tier:d.unknown().optional()}).passthrough(),TC=d.object({type:d.literal("input_text"),text:d.string()}).passthrough(),gC=d.object({type:d.literal("output_text"),text:d.string()}).passthrough(),SC=d.object({type:d.literal("input_image"),image_url:d.string()}).passthrough(),LC=d.object({type:d.literal("encrypted_content"),encrypted_content:d.string()}).passthrough(),$C=new Set(["input_text","output_text","input_image","encrypted_content"]),OC=d.object({type:d.string()}).passthrough().refine((n)=>!$C.has(n.type),{message:"known content parts must have a valid payload"}),ET=d.union([TC,gC,SC,LC,OC]),UC=d.object({type:d.literal("message").optional(),id:d.string().optional(),status:d.string().optional(),role:d.enum(["system","developer","user","assistant"]),content:d.union([d.string(),d.array(ET)])}).passthrough(),bC=d.object({type:d.literal("agent_message"),author:d.string().min(1),recipient:d.string().min(1),content:d.array(ET)}).passthrough(),NC=d.object({type:d.literal("function_call"),id:d.string().optional(),status:d.string().optional(),call_id:d.string().min(1),namespace:d.string().min(1).optional(),name:d.string().min(1),arguments:d.string().transform(cC).refine(MT,"function arguments must contain valid JSON")}).passthrough(),BC=d.object({type:d.literal("custom_tool_call"),id:d.string().optional(),status:d.string().optional(),call_id:d.string().min(1),namespace:d.string().min(1).optional(),name:d.string().min(1),input:d.string()}).passthrough(),TT=d.union([d.string(),d.array(d.object({type:d.string(),text:d.string().optional()}).passthrough())]),IC=d.object({type:d.literal("function_call_output"),id:d.string().optional(),status:d.string().optional(),call_id:d.string().min(1),output:TT}).passthrough(),HC=d.object({type:d.literal("custom_tool_call_output"),id:d.string().optional(),status:d.string().optional(),call_id:d.string().min(1),output:TT}).passthrough(),gT=d.object({type:d.literal("function"),name:d.string().min(1),description:d.string().optional(),parameters:er.optional(),strict:d.boolean().optional()}).passthrough(),_0=d.object({type:d.literal("custom"),name:d.string().min(1),description:d.string().optional(),format:d.object({type:d.literal("grammar"),syntax:d.string().min(1),definition:d.string()}).passthrough().optional()}).passthrough(),GC=d.union([gT,_0]),WC=d.object({type:d.literal("namespace"),name:d.string().min(1),description:d.string().optional(),tools:d.array(GC)}).passthrough(),DC=d.object({type:d.literal("function"),name:d.string().min(1),description:d.string().optional(),parameters:er.optional(),inputSchema:er.optional(),strict:d.boolean().optional()}).passthrough().transform((n)=>({...n,type:"function",...n.parameters!==void 0?{parameters:n.parameters}:n.inputSchema!==void 0?{parameters:n.inputSchema}:{}})),PC=d.object({type:d.literal("function").optional(),name:d.string().min(1),description:d.string().optional(),parameters:er.optional(),inputSchema:er.optional(),strict:d.boolean().optional()}).passthrough().transform((n)=>({...n,type:"function",...n.parameters!==void 0?{parameters:n.parameters}:n.inputSchema!==void 0?{parameters:n.inputSchema}:{}})),YC=d.union([PC,_0]),FC=d.object({type:d.literal("namespace"),name:d.string().min(1),description:d.string().optional(),tools:d.array(YC)}).passthrough().transform((n)=>({...n,type:"namespace"})),XC=new Set(["function","custom","namespace"]),ST=d.object({type:d.string()}).passthrough().refine((n)=>!XC.has(n.type),{message:"known tools must have a valid payload"}),lC=d.union([gT,_0,WC]),JC=d.union([lC,ST]),QC=d.union([DC,_0,FC,ST]),zC=d.object({type:d.literal("additional_tools"),role:d.string().optional(),tools:d.array(QC)}).passthrough(),CC=d.object({type:d.literal("summary_text"),text:d.string()}).passthrough(),VC=d.object({type:d.literal("reasoning_text"),reasoning_text:d.string()}).passthrough(),KC=d.object({type:d.literal("reasoning"),id:d.string().optional(),status:d.string().optional(),summary:d.array(CC).nullable().optional(),content:d.array(VC).nullable().optional(),encrypted_content:d.string().nullable().optional()}).passthrough(),xC=new Set(["message","agent_message","function_call","custom_tool_call","function_call_output","custom_tool_call_output","additional_tools","reasoning"]),jC=d.object({type:d.string()}).passthrough().refine((n)=>!xC.has(n.type),{message:"known input items must have a valid payload"}),kC=d.union([UC,bC,NC,BC,IC,HC,zC,KC,jC]),qC=d.object({effort:d.enum(["none","minimal","low","medium","high","xhigh","max"]).optional(),summary:d.unknown().optional()}).passthrough(),mC=d.object({model:d.string(),input:d.union([d.string(),d.array(kC)]),instructions:d.string().optional(),stream:d.boolean().default(!1),tools:d.array(JC).optional(),tool_choice:d.union([d.enum(["auto","none","required"]),d.record(d.unknown())]).optional(),parallel_tool_calls:d.boolean().optional(),reasoning:qC.nullable().optional(),include:d.array(d.string()).optional(),store:d.boolean().optional(),text:d.unknown().optional(),service_tier:d.unknown().optional(),max_output_tokens:d.number().int().positive().optional(),temperature:d.number().optional(),top_p:d.number().optional(),truncation:d.unknown().optional(),background:d.boolean().optional(),max_tool_calls:d.number().int().positive().optional(),prompt_cache_key:d.string().optional(),metadata:nC.optional(),client_metadata:d.unknown().optional(),previous_response_id:d.string().optional(),conversation:d.unknown().optional()}).passthrough();function LT(n){let t=EC.safeParse(n);if(t.success)return{ok:!0,value:t.data};let i=t.error.issues.map((r)=>{return`${r.path.length>0?r.path.join("."):"request"}: ${r.message}`}).join(", ");return{ok:!1,response:fn(400,`Invalid request: ${i}`,"invalid_request_error","invalid_request")}}function $T(n){let t=mC.safeParse(n);if(t.success)return{ok:!0,value:t.data};let i=t.error.issues.map((r)=>{return`${r.path.length>0?r.path.join("."):"request"}: ${r.message}`}).join(", ");return{ok:!1,response:fn(400,`Invalid request: ${i}`,"invalid_request_error","invalid_request")}}import{createHash as ZC}from"crypto";function aC(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function _e(n){if(n===null||typeof n!=="object")return JSON.stringify(n);if(Array.isArray(n))return`[${n.map(_e).join(",")}]`;return`{${Object.entries(n).filter(([,i])=>i!==void 0).sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>`${JSON.stringify(i)}:${_e(r)}`).join(",")}}`}function fi(n,t,i,r){return{keyHash:ZC("sha256").update("kiro-provider-session-affinity-v1\x00").update(n).update("\x00").update(t).update("\x00").update(i).update("\x00").update(_e(r)).digest("hex"),source:i}}function OT(n,t){if(!aC(n))return;let i=n[t];return typeof i==="string"&&i.length>0?i:void 0}function vC(n){if(typeof n==="string")return{role:"user",content:n};return n.find((i)=>i.type==="message"&&i.role==="user")??n[0]}function pC(n){return n.messages.find((t)=>t.role==="user")??n.messages[0]}function nV(n){return n.messages.find((t)=>t.role==="user")??n.messages[0]}function UT(n,t,i="explicit-only"){if(!t)return;for(let s of["zuno_session_id","kiro_provider_session_id"]){let f=OT(n.metadata,s);if(f!==void 0){let h=`responses.metadata.${s}`;return fi(t,"responses",h,f)}}for(let s of["thread_id","session_id","conversation_id"]){let f=OT(n.client_metadata,s);if(f!==void 0){let h=`responses.client_metadata.${s}`;return fi(t,"responses",h,f)}}if(n.prompt_cache_key&&n.prompt_cache_key.length>0)return fi(t,"responses","responses.prompt_cache_key",n.prompt_cache_key);if(i!=="legacy-initial-input")return;let r=vC(n.input);return r===void 0?void 0:fi(t,"responses","responses.initial_input",r)}function bT(n,t,i="explicit-only"){if(!t)return;if(n.prompt_cache_key&&n.prompt_cache_key.length>0)return fi(t,"chat","chat.prompt_cache_key",n.prompt_cache_key);if(i!=="legacy-initial-input")return;let r=pC(n);if(r===void 0)return;if(n.user&&n.user.length>0)return fi(t,"chat","chat.user_and_initial_input",{user:n.user,initial:r});return fi(t,"chat","chat.initial_input",r)}function NT(n,t,i="explicit-only"){if(!t)return;if(i!=="legacy-initial-input")return;let r=nV(n);if(r===void 0)return;let s=n.metadata?.user_id;if(s)return fi(t,"anthropic","anthropic.user_and_initial_input",{userId:s,initial:r});return fi(t,"anthropic","anthropic.initial_input",r)}class ce extends Error{limit;name="RequestBodyTooLargeError";constructor(n){super(`Request body exceeds the ${n} byte limit`);this.limit=n}}function he(n){return n.reason instanceof Error?n.reason:new DOMException("Request deadline exceeded","TimeoutError")}async function tV(n,t,i){let r=n.body?.getReader();if(!r)return{ok:!0,text:""};let s=[],f=0,h,_=new Promise((o,w)=>{h=w}),c=()=>{let o=he(i.combined);h?.(o),An(()=>r.cancel(o))};i.combined.addEventListener("abort",c,{once:!0});try{while(!0){if(i.combined.aborted)throw he(i.combined);let e=await Promise.race([r.read(),_]);if(i.combined.aborted)throw he(i.combined);if(e.done)break;if(f+=e.value.byteLength,f>t)throw new ce(t);s.push(e.value)}let o=new Uint8Array(f),w=0;for(let e of s)o.set(e,w),w+=e.byteLength;return{ok:!0,text:new TextDecoder().decode(o)}}catch(o){if(o instanceof ce)return An(()=>r.cancel(o)),{ok:!1,response:fn(413,o.message,"invalid_request_error","request_too_large")};if(i.deadline.aborted)return An(()=>r.cancel(o)),{ok:!1,response:fn(504,"Request deadline exceeded","timeout_error","request_timeout")};if(i.client.aborted)return An(()=>r.cancel(o)),{ok:!1,response:fn(499,"Client closed request","request_aborted","client_disconnected")};throw o}finally{i.combined.removeEventListener("abort",c)}}function iV(n,t,i,r=!1){let f=(n.body??new ReadableStream({start:(T)=>T.close()})).getReader(),h=new TextDecoder,_=new TextEncoder,c="",o,w,e=_.encode(`data: ${JSON.stringify({error:{message:"Upstream stream error",type:"upstream_error"}})}
|
|
246
293
|
|
|
247
|
-
`)
|
|
248
|
-
`);if(y>=0){let I=o.slice(0,y).trimEnd();if(o=o.slice(y+1),I.length>0){R.enqueue(f.encode(`data: ${I}
|
|
294
|
+
`),u=(T)=>{if(o!==void 0)return!1;return o=T,!0},y=()=>{t.deadline.removeEventListener("abort",M)},A=()=>{t.client.removeEventListener("abort",E)},R=(T,S)=>{if(!u(T))return;zn(y,A,()=>{if(T==="normal-complete")w?.enqueue(_.encode(`data: [DONE]
|
|
249
295
|
|
|
250
|
-
`));
|
|
296
|
+
`));else if(T==="deadline"||T==="upstream-error")w?.enqueue(e)},()=>{if(T!=="consumer-cancel")w?.close()},i),An(()=>f.cancel(S))},M=()=>{R("deadline",t.deadline.reason instanceof Error?t.deadline.reason:new DOMException("Request deadline exceeded","TimeoutError"))},E=()=>{R("client-abort",t.client.reason instanceof Error?t.client.reason:new DOMException("Client closed request","AbortError"))},g=(T)=>{let S;try{S=JSON.parse(T)}catch{return[T]}if(typeof S!=="object"||S===null||Array.isArray(S))return[T];let L=S,b=L.choices;if(!("usage"in L)||!Array.isArray(b))return[T];let{usage:I,...Z}=L;if(b.length===0)return r?[T]:[];let $=JSON.stringify(Z);if(!r)return[$];return[$,JSON.stringify({...Z,choices:[],usage:I})]};return new Response(new ReadableStream({start(T){if(w=T,t.deadline.addEventListener("abort",M,{once:!0}),t.client.addEventListener("abort",E,{once:!0}),t.deadline.aborted)M();else if(t.client.aborted)E()},async pull(T){if(o!==void 0)return;try{while(!0){if(o!==void 0)return;let S=c.indexOf(`
|
|
297
|
+
`);if(S>=0){let I=c.slice(0,S).trimEnd();if(c=c.slice(S+1),I.length>0){let Z=g(I);if(Z.length===0)continue;for(let $ of Z)T.enqueue(_.encode(`data: ${$}
|
|
251
298
|
|
|
252
|
-
`));return}
|
|
299
|
+
`));return}continue}let L=await f.read();if(o!==void 0)return;if(!L.done){c+=h.decode(L.value,{stream:!0});continue}c+=h.decode();let b=c.trim();if(c="",b.length>0){let I=g(b);if(I.length>0){for(let Z of I)T.enqueue(_.encode(`data: ${Z}
|
|
253
300
|
|
|
254
|
-
`)}function xz(n){if(typeof n==="string")return n;if(Array.isArray(n)){let t=n.flatMap((i)=>Cy(i)&&i.type==="text"&&typeof i.text==="string"?[i.text]:[]).join("");if(t.length>0)return t}try{return JSON.stringify(n)}catch{return String(n)}}function Kz(n){switch(n.type){case"text":return typeof n.text==="string"?{...n,text:n.text}:void 0;case"image":{if(!Cy(n.source))return;if(typeof n.source.type!=="string"||typeof n.source.data!=="string")return;return{...n}}case"tool_use":return typeof n.id==="string"&&typeof n.name==="string"?{...n,input:n.input??{}}:void 0;case"tool_result":{if(typeof n.tool_use_id!=="string")return;let t=xz(n.content);return{...n,content:t}}case"thinking":case"redacted_thinking":return;default:return}}function kz(n){let t=[];for(let i of n){if(typeof i.content==="string"){t.push({role:i.role,content:i.content});continue}let s=i.content.flatMap((r)=>{let e=Kz(r);return e?[e]:[]});if(s.length===0)return;t.push({role:i.role,content:s})}return t}function k_(n,t={}){let i=zz.safeParse(n);if(!i.success)return{ok:!1,message:`Invalid request: ${Qz(i.error)}`};if(t.requireMaxTokens===!0&&i.data.max_tokens===void 0)return{ok:!1,message:"Invalid request: max_tokens is required"};if(i.data.tool_choice?.type==="any"||i.data.tool_choice?.type==="tool")return{ok:!1,message:`Invalid request: tool_choice.type ${i.data.tool_choice.type} is not supported because the Kiro upstream has no structured forced-tool control`};if(i.data.tool_choice?.disable_parallel_tool_use===!0)return{ok:!1,message:"Invalid request: disable_parallel_tool_use is not supported by the Kiro upstream"};let s=kz(i.data.messages);if(!s)return{ok:!1,message:"Invalid request: every message must contain a supported content block"};let r=Cz(i.data.system),e=new Set;for(let u of i.data.tools??[]){if(e.has(u.name))return{ok:!1,message:`Invalid request: duplicate tool name ${u.name}`};e.add(u.name)}let f=i.data.tool_choice?.type==="none"?[]:i.data.tools,o=i.data.thinking?.type==="enabled"||i.data.thinking?.type==="adaptive"?{budget_tokens:i.data.thinking.budget_tokens??20000}:void 0,h={model:i.data.model,stream:i.data.stream,...i.data.max_tokens!==void 0?{max_tokens:i.data.max_tokens}:{},messages:s,...r?{system:r}:{},...f!==void 0?{tools:f}:{},...o?{thinkingConfig:o}:{},...i.data.output_config?.effort?{reasoning_effort:i.data.output_config.effort}:{}};return{ok:!0,value:{source:i.data,body:h}}}import{randomUUID as Ky}from"crypto";function Mt(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function xy(n){if(!Mt(n))return;if(typeof n.prompt_tokens!=="number"||typeof n.completion_tokens!=="number"||typeof n.total_tokens!=="number")return;return{inputTokens:n.prompt_tokens,outputTokens:n.completion_tokens,totalTokens:n.total_tokens}}function jf(n){if(!Mt(n)||!Array.isArray(n.choices))return;let t=xy(n.usage);if(!t)return;let i=n.choices[0];if(!Mt(i)||!Mt(i.message))return;let s=i.message;if(typeof s.content!=="string")return;let r=s.reasoning_content;if(r!==void 0&&typeof r!=="string")return;let e=[];if(s.tool_calls!==void 0){if(!Array.isArray(s.tool_calls))return;for(let f of s.tool_calls){if(!Mt(f)||typeof f.id!=="string"||!Mt(f.function)||typeof f.function.name!=="string"||typeof f.function.arguments!=="string")return;e.push({id:f.id,name:f.function.name,arguments:f.function.arguments})}}return{message:{content:s.content,reasoningContent:r,toolCalls:e},usage:t}}function qz(n){if(!Mt(n)||typeof n.index!=="number"||!Mt(n.function))return;let t=n.id,i=n.function.name,s=n.function.arguments;if(t!==void 0&&typeof t!=="string"||i!==void 0&&typeof i!=="string"||typeof s!=="string")return;return{index:n.index,id:t,name:i,arguments:s}}function Vz(n){if(!Mt(n))return;let t=["content","reasoning_content","tool_calls"].filter((s)=>n[s]!==void 0);if(t.length===0)return{kind:"empty"};if(t.length!==1)return;if(typeof n.content==="string")return{kind:"text",text:n.content};if(typeof n.reasoning_content==="string")return{kind:"reasoning",text:n.reasoning_content};if(!Array.isArray(n.tool_calls))return;let i=[];for(let s of n.tool_calls){let r=qz(s);if(!r)return;i.push(r)}return{kind:"tool_calls",calls:i}}function sr(n){let t;try{t=JSON.parse(n)}catch(f){if(f instanceof SyntaxError)return;throw f}if(!Mt(t)||t.object!=="chat.completion.chunk"||!Array.isArray(t.choices))return;let i=t.choices[0];if(!Mt(i))return;let s=Vz(i.delta),r=i.finish_reason;if(!s||r!==null&&r!=="stop"&&r!=="tool_calls")return;let e=t.usage===void 0?void 0:xy(t.usage);if(t.usage!==void 0&&!e)return;return{delta:s,finishReason:r,usage:e}}function jz(n,t){return`event: ${n}
|
|
301
|
+
`));return}}R("normal-complete");return}}catch(S){if(o!==void 0)return;R("upstream-error",S)}},cancel(T){R("consumer-cancel",T)}}),{status:n.status,headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive"}})}async function BT(n,t,i){let r=new AbortController,s=setTimeout(()=>r.abort(new DOMException("Request deadline exceeded","TimeoutError")),t.request_timeout_ms),f=AbortSignal.any([r.signal,n.signal]),h={combined:f,deadline:r.signal,client:n.signal},_=await tV(n,t.max_request_body_bytes,h);if(!_.ok)return clearTimeout(s),_.response;let c;try{c=JSON.parse(_.text)}catch(R){if(clearTimeout(s),!(R instanceof SyntaxError))throw R;return fn(400,"Request body must contain valid JSON","invalid_request_error","invalid_json")}let o=LT(c);if(!o.ok)return clearTimeout(s),o.response;let w=bT(o.value,i.tenantId,t.session_affinity_mode),e=AT(o.value,t.protocol_projection_mode);if(!e.ok)return dn("warn","protocol_projection_rejected",{protocol:"chat-completions",projection_mode:t.protocol_projection_mode,code:e.code,param:e.param}),clearTimeout(s),fn(400,e.message,"invalid_request_error",e.code,e.param);let u,y=!1,A=()=>{zn(()=>clearTimeout(s),()=>u?.restore())};try{u=i.createRequestIdleTimeoutLease?.(),u?.disable();let R=await(i.runPipeline??As)({body:e.value,model:o.value.model,stream:o.value.stream,config:t,accountManager:i.accountManager,tokenRefresher:i.tokenRefresher,...w?{affinity:w}:{},...i.affinityStore?{affinityStore:i.affinityStore}:{},tenantId:i.tenantId,...i.reasoningReplayStore?{reasoningReplayStore:i.reasoningReplayStore}:{},deadlineSignal:f,...i.makeClient?{makeClient:i.makeClient}:{}});if(n.signal.aborted&&!r.signal.aborted)return An(()=>R.body?.cancel()),fn(499,"Client closed request","request_aborted","client_disconnected");let M=R.headers.get("Content-Type")??"";if(!o.value.stream||M.includes("application/json"))return R;if(!M.includes("application/x-ndjson"))return An(()=>R.body?.cancel()),fn(500,"Pipeline returned an unsupported streaming response","internal_error","invalid_pipeline_response");let E=iV(R,h,A,o.value.stream_options?.include_usage===!0);return y=!0,E}finally{if(!y)A()}}function IT(){return new Response(JSON.stringify({status:"ok"}),{status:200,headers:{"Content-Type":"application/json"}})}var HT=d.object({type:d.string().min(1)}).passthrough(),rV=d.object({role:d.enum(["user","assistant"]),content:d.union([d.string(),d.array(HT)])}).passthrough(),sV=d.object({name:d.string().min(1),description:d.string().optional(),input_schema:d.record(d.unknown()).optional()}).passthrough(),fV=d.object({type:d.enum(["auto","any","tool","none"]),name:d.string().min(1).optional(),disable_parallel_tool_use:d.boolean().optional()}).passthrough().refine((n)=>n.type!=="tool"||n.name!==void 0,{message:"tool_choice.name is required when tool_choice.type is tool"}),_V=d.object({type:d.enum(["enabled","adaptive","disabled"]),budget_tokens:d.number().int().positive().optional()}).passthrough(),hV=d.object({model:d.string().min(1),max_tokens:d.number().int().positive().optional(),messages:d.array(rV).min(1),system:d.union([d.string(),d.array(HT)]).optional(),stream:d.boolean().default(!1),tools:d.array(sV).optional(),tool_choice:fV.optional(),thinking:_V.optional(),output_config:d.object({effort:d.enum(["low","medium","high","xhigh","max"]).optional()}).passthrough().optional(),metadata:d.object({user_id:d.string().min(1).optional()}).passthrough().optional()}).passthrough(),cV=new Set(["model","max_tokens","messages","system","stream","tools","tool_choice","thinking","output_config","metadata"]);function we(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function on(n,t,i){return{ok:!1,message:n,...t!==void 0?{code:t}:{},...i!==void 0?{param:i}:{}}}function Ut(n,t,i,r="unsupported_parameter"){for(let s of Object.keys(n)){if(i.has(s))continue;return on(`Invalid request: ${t}.${s} is not supported`,r,`${t}.${s}`)}return}function oe(n){return we(n)&&n.ok===!1&&typeof n.message==="string"}function oV(n){return n.issues.map((t)=>{return`${t.path.length>0?t.path.join("."):"request"}: ${t.message}`}).join(", ")}function Rs(n,t){return{type:"text",text:n,path:t}}function wV(n){if(n===void 0)return[];if(typeof n==="string")return[Rs(n,"system")];let t=[];for(let[i,r]of n.entries()){let s=`system.${i}`,f=Ut(r,s,new Set(["type","text"]));if(f)return f;if(r.type!=="text"||typeof r.text!=="string")return on(`Invalid request: system.${i} must be a text block`,"unsupported_instruction_projection",s);t.push(Rs(r.text,`system.${i}.text`))}return t}function eV(n,t){if(typeof n==="string")return[Rs(n,t)];if(!Array.isArray(n))return on(`Invalid request: ${t} must be a string or text block array`,"unsupported_tool_result_content",t);let i=[];for(let[r,s]of n.entries()){if(!we(s)||s.type!=="text"||typeof s.text!=="string")return on(`Invalid request: ${t}.${r} must be a text block`,"unsupported_tool_result_content",`${t}.${r}`);let f=Ut(s,`${t}.${r}`,new Set(["type","text"]));if(f)return f;i.push(Rs(s.text,`${t}.${r}.text`))}return i}function uV(n,t){if(n.type==="thinking"){let i=Ut(n,t,new Set(["type","thinking","signature"]),"invalid_reasoning_replay");if(i)return i;if(typeof n.thinking!=="string"||typeof n.signature!=="string")return on(`Invalid request: ${t} requires thinking text and signature`,"invalid_reasoning_replay",t);return{kind:"reasoning_text",text:n.thinking,signature:n.signature}}if(n.type==="redacted_thinking"){let i=Ut(n,t,new Set(["type","data"]),"invalid_reasoning_replay");if(i)return i;let r=n.data;if(typeof r!=="string")return on(`Invalid request: ${t} requires base64 redacted data`,"invalid_reasoning_replay",t);try{let s=Buffer.from(r,"base64"),f=r.replace(/=+$/u,"");if(s.toString("base64").replace(/=+$/u,"")!==f)throw TypeError("invalid base64");return{kind:"redacted_content",bytes:Uint8Array.from(s)}}catch{return on(`Invalid request: ${t} contains invalid base64 redacted data`,"invalid_reasoning_replay",t)}}return on(`Invalid request: ${t} is not a reasoning block`,void 0,t)}function yV(n,t){let i=`messages.${t}`;for(let h of Object.keys(n))if(h!=="role"&&h!=="content")return on(`Invalid request: ${i}.${h} is not supported`,"unsupported_message_field",`${i}.${h}`);if(typeof n.content==="string")return{message:{role:n.role,content:[Rs(n.content,`${i}.content`)],toolCalls:[],path:i}};let r=[],s=[],f;for(let[h,_]of n.content.entries()){let c=`${i}.content.${h}`;switch(_.type){case"text":{let o=Ut(_,c,new Set(["type","text"]));if(o)return o;if(typeof _.text!=="string")return on(`Invalid request: ${c}.text must be a string`,void 0,`${c}.text`);r.push(Rs(_.text,`${c}.text`));break}case"image":{let o=Ut(_,c,new Set(["type","source"]));if(o)return o;if(!we(_.source)||_.source.type!=="base64"||typeof _.source.data!=="string")return on(`Invalid request: ${c} requires a base64 image source`,"unsupported_image_source",c);let w=Ut(_.source,`${c}.source`,new Set(["type","data","media_type"]));if(w)return w;r.push({type:"image",data:_.source.data,...typeof _.source.media_type==="string"?{mediaType:_.source.media_type}:{},path:c});break}case"tool_use":{let o=Ut(_,c,new Set(["type","id","name","input"]));if(o)return o;if(typeof _.id!=="string"||typeof _.name!=="string")return on(`Invalid request: ${c} requires id and name`,"invalid_tool_history",c);s.push({id:_.id,name:_.name,input:_.input??{},path:c});break}case"tool_result":{let o=Ut(_,c,new Set(["type","tool_use_id","content","is_error"]));if(o)return o;if(typeof _.tool_use_id!=="string")return on(`Invalid request: ${c} requires tool_use_id`,"invalid_tool_history",c);let w=eV(_.content,`${c}.content`);if(oe(w))return w;r.push({type:"tool_result",toolCallId:_.tool_use_id,content:w,isError:_.is_error===!0,path:c});break}case"thinking":case"redacted_thinking":{if(n.role!=="assistant"||f!==void 0)return on(`Invalid request: ${c} is not a valid single assistant reasoning block`,"invalid_reasoning_replay",c);let o=uV(_,c);if("ok"in o)return o;f=o;break}default:return on(`Invalid request: unsupported content block ${_.type} at ${c}`,"unsupported_content_part",c)}}return{message:{role:n.role,content:r,toolCalls:s,path:i},...f!==void 0?{replay:f}:{}}}function dV(n){let t=[],i=new Set;for(let[r,s]of(n??[]).entries()){for(let f of Object.keys(s))if(f!=="name"&&f!=="description"&&f!=="input_schema")return on(`Invalid request: tools.${r}.${f} is not supported`,"unsupported_tool_field",`tools.${r}.${f}`);if(i.has(s.name))return on(`Invalid request: duplicate tool name ${s.name}`,"invalid_tool_declaration",`tools.${r}.name`);i.add(s.name),t.push({publicType:"function",name:s.name,wireName:s.name,...s.description!==void 0?{description:s.description}:{},inputSchema:s.input_schema??{},path:`tools.${r}`})}return t}function AV(n,t){let i=new Set(t.map((f)=>f.wireName)),r=new Map,s=new Set;for(let[f,h]of n.entries()){for(let _ of h.toolCalls){if(!i.has(_.name))return on(`Invalid request: tool call ${_.id} has no exact declaration for ${_.name}`,"missing_tool_declaration",_.path);if(r.has(_.id))return on(`Invalid request: duplicate tool call id ${_.id}`,"invalid_tool_history",_.path);r.set(_.id,f)}for(let _ of h.content){if(_.type!=="tool_result")continue;let c=r.get(_.toolCallId);if(c===void 0||c>=f||s.has(_.toolCallId))return on(`Invalid request: tool result ${_.toolCallId} has no earlier unique call`,"invalid_tool_history",_.path);s.add(_.toolCallId)}}return}function ee(n,t={},i="safe"){let r=hV.safeParse(n);if(!r.success){let y=r.error.issues[0]?.path;return on(`Invalid request: ${oV(r.error)}`,void 0,y&&y.length>0?y.join("."):void 0)}let s=r.data;try{Kt(s.model)}catch{return on(`Invalid request: model ${s.model} is not supported`,"unsupported_model","model")}for(let y of Object.keys(s))if(!cV.has(y))return on(`Invalid request: parameter ${y} is not supported`,"unsupported_parameter",y);if(t.requireMaxTokens===!0&&s.max_tokens===void 0)return on("Invalid request: max_tokens is required",void 0,"max_tokens");if(s.max_tokens!==void 0){let y=Hi(s.model,s.max_tokens);if(!y.ok)return on(`Invalid request: max_tokens: ${y.message}`,y.code,"max_tokens")}if(s.tool_choice?.type==="any"||s.tool_choice?.type==="tool")return on(`Invalid request: tool_choice.type ${s.tool_choice.type} is not supported because Kiro has no forced-tool control`,"unsupported_tool_choice","tool_choice.type");if(s.tool_choice){let y=Ut(s.tool_choice,"tool_choice",new Set(["type","name","disable_parallel_tool_use"]));if(y)return y;if(s.tool_choice.name!==void 0)return on("Invalid request: tool_choice.name is only meaningful for unsupported forced-tool selection","unsupported_tool_choice","tool_choice.name")}if(s.tool_choice?.disable_parallel_tool_use===!0)return on("Invalid request: disable_parallel_tool_use cannot be guaranteed by Kiro","unsupported_parallel_tool_calls","tool_choice.disable_parallel_tool_use");if(s.output_config){for(let y of Object.keys(s.output_config))if(y!=="effort")return on(`Invalid request: output_config.${y} is not supported`,"unsupported_parameter",`output_config.${y}`)}if(s.thinking){for(let y of Object.keys(s.thinking))if(y!=="type"&&y!=="budget_tokens")return on(`Invalid request: thinking.${y} is not supported`,"unsupported_parameter",`thinking.${y}`)}if(s.metadata){let y=Ut(s.metadata,"metadata",new Set(["user_id"]));if(y)return y}let f=wV(s.system);if(oe(f))return f;if(f.length>0&&i==="safe")return on("Invalid request: system cannot be projected losslessly to Kiro in safe mode; enable legacy-user-prefix explicitly to migrate","unsupported_instruction_projection","system");let h=dV(s.tools);if(oe(h))return h;let _=[],c=[];if(f.length>0)_.push({role:"system",content:f,toolCalls:[],path:"system"});for(let[y,A]of s.messages.entries()){let R=yV(A,y);if("ok"in R)return R;if(R.replay!==void 0)c.push({lookup:{kind:"anthropic-direct",content:R.replay},outputFingerprint:et({text:si(R.message.content),toolCalls:R.message.toolCalls.map((M)=>({id:M.id,name:M.name,input:JSON.stringify(M.input)}))}),insertBeforeMessage:_.length,path:R.message.path});_.push(R.message)}let o=AV(_,h);if(o)return o;let w=new Set;for(let y of _){for(let A of y.toolCalls)w.add(A.id);for(let A of y.content)if(A.type==="tool_result")w.delete(A.toolCallId)}if(s.tool_choice?.type==="none"&&w.size>0)return on("Invalid request: tool_choice none cannot be used while tool calls await results","unsupported_tool_choice","tool_choice");let e=s.thinking?.type==="enabled"||s.thinking?.type==="adaptive",u={canonicalVersion:1,protocol:"anthropic-messages",projectionMode:i,model:s.model,stream:s.stream,messages:_,tools:h,toolChoice:s.tool_choice?.type==="none"?"none":"auto",...s.output_config?.effort!==void 0?{reasoningEffort:s.output_config.effort,requestedReasoningEffort:s.output_config.effort}:{},...s.thinking!==void 0?{thinking:{enabled:e,...s.thinking.budget_tokens!==void 0?{budgetTokens:s.thinking.budget_tokens}:{}}}:{},...s.max_tokens!==void 0?{outputTokenLimit:s.max_tokens}:{},reasoningReplays:c,includeEncryptedReasoning:!1};return{ok:!0,value:{source:s,body:u}}}import{randomUUID as WT}from"crypto";function bt(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function GT(n){if(!bt(n))return;if(typeof n.prompt_tokens!=="number"||typeof n.completion_tokens!=="number"||typeof n.total_tokens!=="number")return;return{inputTokens:n.prompt_tokens,outputTokens:n.completion_tokens,totalTokens:n.total_tokens}}function h0(n){if(!bt(n)||!Array.isArray(n.choices))return;let t=GT(n.usage);if(!t)return;let i=n.choices[0];if(!bt(i)||!bt(i.message))return;let r=i.message;if(typeof r.content!=="string")return;let s=r.reasoning_content;if(s!==void 0&&typeof s!=="string")return;let f=r.reasoning_signature;if(f!==void 0&&typeof f!=="string")return;let h=r.reasoning_redacted_content;if(h!==void 0&&typeof h!=="string")return;let _=r.reasoning_encrypted_content;if(_!==void 0&&typeof _!=="string")return;let c=[];if(r.tool_calls!==void 0){if(!Array.isArray(r.tool_calls))return;for(let o of r.tool_calls){if(!bt(o)||typeof o.id!=="string"||!bt(o.function)||typeof o.function.name!=="string"||typeof o.function.arguments!=="string")return;c.push({id:o.id,name:o.function.name,arguments:o.function.arguments})}}return{message:{content:r.content,reasoningContent:s,reasoningSignature:f,reasoningRedactedContent:h,reasoningEncryptedContent:_,toolCalls:c},usage:t}}function RV(n){if(!bt(n)||typeof n.index!=="number"||!bt(n.function))return;let t=n.id,i=n.function.name,r=n.function.arguments;if(t!==void 0&&typeof t!=="string"||i!==void 0&&typeof i!=="string"||typeof r!=="string")return;return{index:n.index,id:t,name:i,arguments:r}}function MV(n){if(!bt(n))return;let t=["content","reasoning_content","reasoning_signature","reasoning_redacted_content","reasoning_encrypted_content","tool_calls"].filter((r)=>n[r]!==void 0);if(t.length===0)return{kind:"empty"};if(t.length!==1)return;if(typeof n.content==="string")return{kind:"text",text:n.content};if(typeof n.reasoning_content==="string")return{kind:"reasoning",text:n.reasoning_content};if(typeof n.reasoning_signature==="string")return{kind:"reasoning_signature",signature:n.reasoning_signature};if(typeof n.reasoning_redacted_content==="string")return{kind:"reasoning_redacted",data:n.reasoning_redacted_content};if(typeof n.reasoning_encrypted_content==="string")return{kind:"reasoning_encrypted",encryptedContent:n.reasoning_encrypted_content};if(!Array.isArray(n.tool_calls))return;let i=[];for(let r of n.tool_calls){let s=RV(r);if(!s)return;i.push(s)}return{kind:"tool_calls",calls:i}}function Ms(n){let t;try{t=JSON.parse(n)}catch(h){if(h instanceof SyntaxError)return;throw h}if(!bt(t)||t.object!=="chat.completion.chunk"||!Array.isArray(t.choices))return;let i=t.choices[0];if(!bt(i))return;let r=MV(i.delta),s=i.finish_reason;if(!r||s!==null&&s!=="stop"&&s!=="tool_calls")return;let f=t.usage===void 0?void 0:GT(t.usage);if(t.usage!==void 0&&!f)return;return{delta:r,finishReason:s,usage:f}}function EV(n,t){return`event: ${n}
|
|
255
302
|
data: ${JSON.stringify(t)}
|
|
256
303
|
|
|
257
|
-
`}function
|
|
258
|
-
`);if(
|
|
304
|
+
`}function TV(n){return{input_tokens:n.inputTokens,output_tokens:n.outputTokens,cache_creation_input_tokens:0,cache_read_input_tokens:0}}function ue(n){try{let t=JSON.parse(n);return typeof t==="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch(t){if(t instanceof SyntaxError)return;throw t}}function DT(n,t){let i=[];if(n.message.reasoningRedactedContent)i.push({type:"redacted_thinking",data:n.message.reasoningRedactedContent});else if(n.message.reasoningContent&&n.message.reasoningSignature)i.push({type:"thinking",thinking:n.message.reasoningContent,signature:n.message.reasoningSignature});if(n.message.content.length>0)i.push({type:"text",text:n.message.content});for(let r of n.message.toolCalls){let s=ue(r.arguments);if(!s)return Pn(502,`Upstream returned invalid JSON arguments for tool ${r.name}`,"api_error");i.push({type:"tool_use",id:r.id,name:r.name,input:s})}return Response.json({id:`msg_${WT()}`,type:"message",role:"assistant",model:t,content:i,stop_reason:n.message.toolCalls.length>0?"tool_use":"end_turn",stop_sequence:null,usage:TV(n.usage)})}function PT(n,t){let r=(n.body??new ReadableStream({start:(P)=>P.close()})).getReader(),s=new TextEncoder,f=new TextDecoder,h=`msg_${WT()}`,_=new Map,c="",o=0,w,e,u=!1,y=!1,A,R=!1,M=!1,E,g,T=(P,z)=>{g?.enqueue(s.encode(EV(P,z)))},S=(P)=>{if(E!==void 0)return!1;return E=P,!0},L=()=>{t.signals.deadline.removeEventListener("abort",$)},b=()=>{t.signals.client.removeEventListener("abort",U)},I=(P,z,x)=>{if(!S(P))return;zn(L,b,()=>{if(!x||!g)return;g.enqueue(s.encode(hy(x.message,x.type??"api_error")))},()=>{if(P!=="consumer-cancel")g?.close()},t.finalize),An(()=>r.cancel(z))},Z=(P)=>{I("upstream-protocol-error",void 0,{message:P})},$=()=>{let P=t.signals.deadline.reason instanceof Error?t.signals.deadline.reason:new DOMException("Request deadline exceeded","TimeoutError");I("deadline",P,{message:"Request deadline exceeded"})},U=()=>{let P=t.signals.client.reason instanceof Error?t.signals.client.reason:new DOMException("Client closed request","AbortError");I("client-abort",P)},X=()=>{if(!R||M||w===void 0)return;M=!0,T("content_block_stop",{type:"content_block_stop",index:w})},H=()=>{if(!u||y||e===void 0)return;if(A!==void 0)T("content_block_delta",{type:"content_block_delta",index:e,delta:{type:"signature_delta",signature:A}}),A=void 0;y=!0,T("content_block_stop",{type:"content_block_stop",index:e})},W=(P)=>{switch(P.kind){case"empty":return!1;case"reasoning":{if(!u)e=o,o+=1,u=!0,T("content_block_start",{type:"content_block_start",index:e,content_block:{type:"thinking",thinking:"",signature:""}});return T("content_block_delta",{type:"content_block_delta",index:e,delta:{type:"thinking_delta",thinking:P.text}}),!0}case"reasoning_signature":if(u&&!y&&e!==void 0)T("content_block_delta",{type:"content_block_delta",index:e,delta:{type:"signature_delta",signature:P.signature}});else A=P.signature;return!1;case"reasoning_redacted":{if(u)return Z("Upstream mixed visible and redacted reasoning payloads"),!1;let z=o;return o+=1,T("content_block_start",{type:"content_block_start",index:z,content_block:{type:"redacted_thinking",data:P.data}}),T("content_block_stop",{type:"content_block_stop",index:z}),!0}case"reasoning_encrypted":return!1;case"text":{if(H(),!R)w=o,o+=1,R=!0,T("content_block_start",{type:"content_block_start",index:w,content_block:{type:"text",text:""}});return T("content_block_delta",{type:"content_block_delta",index:w,delta:{type:"text_delta",text:P.text}}),!0}case"tool_calls":{H();for(let z of P.calls){let x=_.get(z.index)??{id:"",name:"",arguments:""};if(x.id.length===0&&z.id!==void 0)x.id=z.id;if(x.name.length===0&&z.name!==void 0)x.name=z.name;x.arguments+=z.arguments,_.set(z.index,x)}return!1}}},K=(P)=>{let z=[..._.entries()].sort(([q],[v])=>q-v);if(z.some(([,q])=>{return q.id.length===0||q.name.length===0||!ue(q.arguments)})){Z("Malformed upstream tool call");return}X(),H();for(let[,q]of z){let v=o;if(o+=1,!ue(q.arguments)||q.id.length===0||q.name.length===0){Z("Malformed upstream tool call");return}if(T("content_block_start",{type:"content_block_start",index:v,content_block:{type:"tool_use",id:q.id,name:q.name,input:{}}}),q.arguments.length>0)T("content_block_delta",{type:"content_block_delta",index:v,delta:{type:"input_json_delta",partial_json:q.arguments}});T("content_block_stop",{type:"content_block_stop",index:v})}T("message_delta",{type:"message_delta",delta:{stop_reason:z.length>0?"tool_use":"end_turn",stop_sequence:null},usage:{output_tokens:P.outputTokens}}),T("message_stop",{type:"message_stop"}),I("normal-complete")};return new Response(new ReadableStream({start(P){if(g=P,T("message_start",{type:"message_start",message:{id:h,type:"message",role:"assistant",model:t.model,content:[],stop_reason:null,stop_sequence:null,usage:{input_tokens:t.inputTokens,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0}}}),t.signals.deadline.addEventListener("abort",$,{once:!0}),t.signals.client.addEventListener("abort",U,{once:!0}),t.signals.deadline.aborted)$();else if(t.signals.client.aborted)U()},async pull(){if(E!==void 0)return;try{while(E===void 0){let P=c.indexOf(`
|
|
305
|
+
`);if(P>=0){let q=c.slice(0,P).trimEnd();if(c=c.slice(P+1),q.length===0)continue;let v=Ms(q);if(!v){Z("Malformed upstream stream");return}let Di=W(v.delta);if(v.finishReason!==null){if(!v.usage){Z("Terminal upstream chunk omitted usage");return}K(v.usage);return}if(Di)return;continue}let z=await r.read();if(E!==void 0)return;if(!z.done){c+=f.decode(z.value,{stream:!0});continue}c+=f.decode();let x=c.trim();if(c="",x.length>0){let q=Ms(x);if(!q){Z("Malformed upstream stream");return}if(W(q.delta),q.finishReason!==null&&q.usage){K(q.usage);return}}Z("Upstream stream ended before completion");return}}catch(P){if(E!==void 0)return;I("upstream-error",P,{message:"Upstream stream error"})}},cancel(P){I("consumer-cancel",P)}}),{headers:{"Cache-Control":"no-cache","Content-Type":"text/event-stream; charset=utf-8","x-kiro-token-count-mode":"estimate"}})}class de extends Error{limit;name="RequestBodyTooLargeError";constructor(n){super(`Request body exceeds the ${n} byte limit`);this.limit=n}}function ye(n){return n.reason instanceof Error?n.reason:new DOMException("Request deadline exceeded","TimeoutError")}async function gV(n,t,i){let r=n.body?.getReader();if(!r)return{ok:!0,text:""};let s=[],f=0,h,_=new Promise((o,w)=>{h=w}),c=()=>{let o=ye(i.combined);h?.(o),An(()=>r.cancel(o))};i.combined.addEventListener("abort",c,{once:!0});try{while(!0){if(i.combined.aborted)throw ye(i.combined);let e=await Promise.race([r.read(),_]);if(i.combined.aborted)throw ye(i.combined);if(e.done)break;if(f+=e.value.byteLength,f>t)throw new de(t);s.push(e.value)}let o=new Uint8Array(f),w=0;for(let e of s)o.set(e,w),w+=e.byteLength;return{ok:!0,text:new TextDecoder().decode(o)}}catch(o){if(o instanceof de)return An(()=>r.cancel(o)),{ok:!1,response:Pn(413,o.message,"request_too_large")};if(i.deadline.aborted)return An(()=>r.cancel(o)),{ok:!1,response:Pn(504,"Request deadline exceeded","api_error")};if(i.client.aborted)return An(()=>r.cancel(o)),{ok:!1,response:Pn(499,"Client closed request","api_error")};throw o}finally{i.combined.removeEventListener("abort",c)}}async function YT(n,t,i){let r=await gV(n,t.max_request_body_bytes,i);if(!r.ok)return r;try{return{ok:!0,value:JSON.parse(r.text)}}catch(s){if(!(s instanceof SyntaxError))throw s;return{ok:!1,response:Pn(400,"Request body must contain valid JSON","invalid_request_error")}}}function SV(n){if(n===429)return"rate_limit_error";if(n===503)return"overloaded_error";if(n===401)return"authentication_error";if(n===403)return"permission_error";if(n===404)return"not_found_error";if(n>=400&&n<500)return"invalid_request_error";return"api_error"}async function LV(n){let t=`Upstream request failed with HTTP ${n.status}`;try{let i=await n.json();if(typeof i==="object"&&i!==null&&"error"in i&&typeof i.error==="object"&&i.error!==null&&"message"in i.error&&typeof i.error.message==="string")t=i.error.message}catch{}return Pn(n.status,t,SV(n.status))}function FT(n,t){let i=new AbortController,r=setTimeout(()=>i.abort(new DOMException("Request deadline exceeded","TimeoutError")),t.request_timeout_ms);return{signals:{combined:AbortSignal.any([i.signal,n.signal]),deadline:i.signal,client:n.signal},finalize:()=>clearTimeout(r)}}function XT(n){return Math.max(1,kh(JSON.stringify(n)))}async function lT(n,t,i){let r=FT(n,t),s=await YT(n,t,r.signals);if(!s.ok)return r.finalize(),s.response;let f=ee(s.value,{requireMaxTokens:!0},t.protocol_projection_mode);if(!f.ok)return dn("warn","protocol_projection_rejected",{protocol:"anthropic-messages",projection_mode:t.protocol_projection_mode,code:f.code,param:f.param}),r.finalize(),Pn(400,f.message,"invalid_request_error");let h=NT(f.value.source,i.tenantId,t.session_affinity_mode),_,c=!1,o=()=>{zn(r.finalize,()=>_?.restore())};try{_=i.createRequestIdleTimeoutLease?.(),_?.disable();let w=await(i.runPipeline??As)({body:f.value.body,model:f.value.body.model,stream:f.value.source.stream,config:t,accountManager:i.accountManager,tokenRefresher:i.tokenRefresher,...h?{affinity:h}:{},...i.affinityStore?{affinityStore:i.affinityStore}:{},tenantId:i.tenantId,...i.reasoningReplayStore?{reasoningReplayStore:i.reasoningReplayStore}:{},deadlineSignal:r.signals.combined,...i.makeClient?{makeClient:i.makeClient}:{}});if(n.signal.aborted&&!r.signals.deadline.aborted)return An(()=>w.body?.cancel()),Pn(499,"Client closed request","api_error");let e=w.headers.get("Content-Type")??"";if(!w.ok)return await LV(w);if(f.value.source.stream&&e.includes("application/x-ndjson")){let u=PT(w,{model:f.value.body.model,inputTokens:XT(f.value.body),signals:r.signals,finalize:o});return c=!0,u}if(e.includes("application/json")){if(f.value.source.stream)return Pn(502,"Pipeline returned a non-streaming response for a streaming request","api_error");let u=h0(await w.json());if(u)return DT(u,f.value.body.model);return Pn(502,"Pipeline returned an invalid non-streaming response","api_error")}return An(()=>w.body?.cancel()),Pn(502,"Pipeline returned an unsupported response","api_error")}finally{if(!c)o()}}async function JT(n,t){let i=FT(n,t);try{let r=await YT(n,t,i.signals);if(!r.ok)return r.response;let s=ee(r.value,{},t.protocol_projection_mode);if(!s.ok)return Pn(400,s.message,"invalid_request_error");let f=XT(s.value.body);return Response.json({input_tokens:f},{headers:{"x-kiro-token-count-mode":"estimate"}})}finally{i.finalize()}}var $V=1700000000,OV=/-(low|medium|high|xhigh|max)$/;function UV(n){if(!or(n))return[];return(pw(n)?["low","medium","high","xhigh","max"]:["low","medium","high","max"]).map((i)=>({effort:i,description:`${i} reasoning effort`}))}function bV(n){if(!or(n.wireId))return null;let t=OV.exec(n.id)?.[1];if(t==="low"||t==="medium"||t==="high"||t==="xhigh"||t==="max")return t;return"medium"}function NV(n){return n.modalities.input.includes("image")?["text","image"]:["text"]}function BV(n,t){return{slug:n.id,display_name:n.name,description:null,default_reasoning_level:bV(n),supported_reasoning_levels:UV(n.wireId),shell_type:"unified_exec",visibility:"list",supported_in_api:!0,priority:f0.length-t,upgrade:null,base_instructions:"",include_skills_usage_instructions:!1,include_plugin_usage_instructions:!1,include_apps_usage_instructions:!1,supports_reasoning_summary_parameter:!1,support_verbosity:!1,default_verbosity:null,apply_patch_tool_type:null,web_search_tool_type:null,truncation_policy:{mode:"tokens",limit:n.contextLimit},supports_image_detail_original:!1,context_window:n.contextLimit,max_context_window:n.contextLimit,auto_compact_token_limit:Math.floor(n.contextLimit*0.9),effective_context_window_percent:95,experimental_supported_tools:[],input_modalities:NV(n),supports_search_tool:!1,use_responses_lite:!1,node_repl_auto_review_required:!1,node_repl_disabled:!1}}function QT(){let n=f0.map((i)=>({id:i.id,object:"model",created:$V,owned_by:"kiro",name:i.name,context_limit:i.contextLimit,output_limit:i.outputLimit,modalities:i.modalities})),t=f0.map(BV);return new Response(JSON.stringify({object:"list",data:n,models:t}),{status:200,headers:{"Content-Type":"application/json"}})}function zT(n,t){try{if(n.reconcileFromDb(),n.getAccountCount()===0)return Response.json({status:"not_ready",reason:"no_active_accounts"},{status:503});if(t){let r=t.readiness();if(!r.writable)return Response.json({status:"not_ready",reason:"reasoning_replay_database_not_writable"},{status:503});if(!r.keyringAvailable)return Response.json({status:"not_ready",reason:"reasoning_replay_keyring_unavailable"},{status:503});if(r.missingKeyIds.length>0)return Response.json({status:"not_ready",reason:"reasoning_replay_key_coverage_incomplete",missing_key_ids:r.missingKeyIds},{status:503})}return Response.json({status:"ready"})}catch{return Response.json({status:"not_ready",reason:"authentication_store_unavailable"},{status:503})}}import{randomUUID as c0}from"crypto";var IV="kiro_custom_",HV="kiro_ns_";function Yf(n){switch(n.kind){case"function":return JSON.stringify(["function",n.name]);case"custom":return JSON.stringify(["custom",n.name]);case"namespace":return JSON.stringify(["namespace",n.toolType,n.namespace,n.name])}}function CT(...n){let t=n.filter((i)=>i!==void 0&&i.length>0);return t.length>0?t.join(`
|
|
259
306
|
|
|
260
|
-
`):void 0}function a_(n){return{type:"object",properties:{input:{type:"string"}},required:["input"],additionalProperties:!1}}function oQ(n){return{type:"function",function:{name:n.name,...n.description!==void 0?{description:n.description}:{},...n.parameters!==void 0?{parameters:n.parameters}:{}}}}function oT(n){if(n.namespace!==void 0)return{kind:"namespace",namespace:n.namespace,name:n.name,toolType:n.type==="custom_tool_call"?"custom":"function"};if(n.type==="custom_tool_call")return{kind:"custom",name:n.name};return{kind:"function",name:n.name}}function v_(n){return n.kind==="custom"||n.kind==="namespace"&&n.toolType==="custom"}function sT(n){return n.type==="function_call"||n.type==="custom_tool_call"}function fQ(n){return n.type==="additional_tools"}function rT(n){return n.type==="function"||n.type==="custom"||n.type==="namespace"}function hQ(n){return n.type==="function_call_output"||n.type==="custom_tool_call_output"}function uQ(n){return n.startsWith("kiro_custom_")||n.startsWith("kiro_ns_")}function eT(n){return n.trim().length===0?"{}":n}function cQ(n){let t;try{t=JSON.parse(n)}catch(i){if(i instanceof SyntaxError)return{ok:!1,code:"invalid_custom_tool_input",message:"Custom tool arguments must be valid JSON"};throw i}if(typeof t!=="object"||t===null||Array.isArray(t)||Object.keys(t).length!==1||typeof t.input!=="string")return{ok:!1,code:"invalid_custom_tool_input",message:'Custom tool arguments must contain exactly {"input": string}'};return{ok:!0,input:t.input}}class fT{internalTools;#n;#t;constructor(n){this.internalTools=n.internalTools,this.#n=n.wireNameByIdentity,this.#t=n.identityByWireName}lowerCall(n){let t=oT(n),i=this.#n.get(rr(t))??n.name;return{id:n.call_id,type:"function",function:{name:i,arguments:n.type==="custom_tool_call"?JSON.stringify({input:n.input}):n.arguments}}}restoreCalls(n){let t=[];for(let i of n){let s=this.#t.get(i.name);if(!s){if(uQ(i.name))return{ok:!1,code:"unknown_tool_alias",message:`Upstream returned unregistered tool alias ${i.name}`};t.push({id:i.itemId,type:"function_call",call_id:i.id,name:i.name,arguments:eT(i.arguments)});continue}if(v_(s)){let r=cQ(i.arguments);if(!r.ok)return r;t.push({id:i.itemId,type:"custom_tool_call",call_id:i.id,...s.kind==="namespace"?{namespace:s.namespace}:{},name:s.name,input:r.input});continue}t.push({id:i.itemId,type:"function_call",call_id:i.id,...s.kind==="namespace"?{namespace:s.namespace}:{},name:s.name,arguments:eT(i.arguments)})}return{ok:!0,items:t}}}function _Q(n){let t=new Set;for(let i of n.tools){if(t.has(i.name))return!0;t.add(i.name)}return!1}function hT(n){let t=new Map,i=new Map,s=new Set,r=[],e=typeof n.input==="string"?[]:n.input;for(let R of e)if(sT(R)&&R.type==="function_call"&&R.namespace===void 0)s.add(R.name);let f=(R)=>{if(R.type==="namespace"){if(_Q(R))return{ok:!1,code:"invalid_tool_declaration",message:`Namespace ${R.name} contains duplicate child names`};for(let I of R.tools){let F={kind:"namespace",namespace:R.name,name:I.name,toolType:I.type},C=rr(F);if(t.has(C))continue;t.set(C,{identity:F,tool:{type:"function",function:{name:"",...iT(R.description,I.description)!==void 0?{description:iT(R.description,I.description)}:{},parameters:I.type==="custom"?a_(I.format):I.parameters??{type:"object"}}}})}return}let y=i.get(R.name);if(y!==void 0&&y!==R.type)return{ok:!1,code:"invalid_tool_declaration",message:`Tool name ${R.name} is declared as both function and custom`};if(i.set(R.name,R.type),R.type==="function")s.add(R.name);let T={kind:R.type,name:R.name},S=rr(T);if(t.has(S))return;t.set(S,{identity:T,tool:R.type==="function"?oQ(R):{type:"function",function:{name:"",...R.description!==void 0?{description:R.description}:{},parameters:a_(R.format)}}});return};for(let R of n.tools??[]){if(!rT(R))continue;let y=f(R);if(y)return y}for(let R of e){if(!fQ(R))continue;for(let y of R.tools){if(!rT(y))continue;let T=f(y);if(T)return T}}let o=new Map;for(let[R,y]of e.entries()){if(!sT(y))continue;if(o.has(y.call_id))return{ok:!1,code:"invalid_tool_history",message:`Duplicate tool call id ${y.call_id}`};let T={index:R,identity:oT(y)};o.set(y.call_id,T),r.push(T)}let h=new Set;for(let[R,y]of e.entries()){if(!hQ(y))continue;if(h.has(y.call_id))return{ok:!1,code:"invalid_tool_history",message:`Duplicate tool output id ${y.call_id}`};h.add(y.call_id);let T=o.get(y.call_id);if(!T){if(y.type==="custom_tool_call_output")return{ok:!1,code:"invalid_tool_history",message:`Custom output ${y.call_id} has no matching call`};continue}let S=v_(T.identity),I=y.type==="custom_tool_call_output"&&S||y.type==="function_call_output"&&!S;if(T.index>=R||!I)return{ok:!1,code:"invalid_tool_history",message:`Tool output ${y.call_id} is out of order or has the wrong type`}}let u=[...t.values()];for(let R of r){let y=rr(R.identity);if(R.identity.kind==="function"||t.has(y))continue;t.set(y,{identity:R.identity,tool:{type:"function",function:{name:"",parameters:v_(R.identity)?a_(void 0):{type:"object"}}}}),u.push(t.get(y))}let c=new Set(s),_=new Map,w=new Map,l=0,A=0,d=(R)=>{for(;;){let y=R==="custom"?`kiro_custom_${l++}`:`kiro_ns_${A++}`;if(c.has(y))continue;return c.add(y),y}},E=[];for(let R of u){let y=rr(R.identity),T=R.identity.kind==="function"?R.identity.name:d(R.identity.kind);_.set(y,T),w.set(T,R.identity),E.push({type:"function",function:{...R.tool.function,name:T}})}for(let R of s){let y={kind:"function",name:R};_.set(rr(y),R),w.set(R,y)}return{ok:!0,bridge:new fT({internalTools:E,wireNameByIdentity:_,identityByWireName:w})}}function wQ(n){return n.type==="message"||n.type===void 0&&"role"in n&&"content"in n}function lQ(n){return n.type==="agent_message"}function AQ(n){return n.type==="function_call"}function MQ(n){return n.type==="custom_tool_call"}function dQ(n){return n.type==="function_call_output"}function RQ(n){return n.type==="custom_tool_call_output"}function uT(n){return n.type==="additional_tools"}function EQ(n){return n.type==="reasoning"}function cT(n,t){let i=[];for(let s of n){if((s.type==="input_text"||s.type==="output_text")&&"text"in s&&typeof s.text==="string"){i.push({type:"text",text:s.text});continue}if(s.type==="input_image"&&"image_url"in s&&typeof s.image_url==="string"){i.push({type:"image_url",image_url:{url:s.image_url}});continue}t.count++}return i}function yQ(n,t){return typeof n==="string"?n:cT(n,t)}function TQ(n){return typeof n==="string"?[{type:"text",text:n}]:n}function gQ(n){if(n==="minimal")return"low";if(n==="low"||n==="medium"||n==="high"||n==="xhigh"||n==="max")return n;return}function SQ(n){if(typeof n==="string")return n;return n.flatMap((t)=>t.text===void 0?[]:[t.text]).join(`
|
|
261
|
-
`)}function _T(n){let t=hT(n);if(!t.ok)return{ok:!1,code:t.code,message:t.message};let i=t.bridge,s=[],r=[...i.internalTools],e=n.tools!==void 0||typeof n.input!=="string"&&n.input.some((w)=>uT(w)),f={count:0},o=0,h=0,u=!1;if(n.instructions&&n.instructions.length>0)s.push({role:"system",content:n.instructions});if(typeof n.input==="string")s.push({role:"user",content:n.input}),u=!0;else for(let w of n.input){if(EQ(w))continue;if(AQ(w)||MQ(w)){s.push({role:"assistant",tool_calls:[i.lowerCall(w)]}),u=!0;continue}if(wQ(w)){let l=yQ(w.content,f);if(w.role==="assistant")s.push({role:"assistant",content:TQ(l)}),u=!0;else if(s.push({role:w.role==="developer"?"system":w.role,content:l}),w.role==="user")u=!0;continue}if(lQ(w)){let l=cT(w.content,f);s.push({role:"user",content:l}),u=!0;continue}if(dQ(w)||RQ(w)){s.push({role:"user",content:[{type:"tool_result",tool_use_id:w.call_id,content:SQ(w.output)}]}),u=!0;continue}if(uT(w)){h+=w.tools.filter((l)=>l.type!=="function"&&l.type!=="custom"&&l.type!=="namespace").length;continue}o++}if(f.count,!u)return{ok:!1,code:"empty_input"};let c=gQ(n.reasoning?.effort);return{ok:!0,body:{model:n.model,stream:n.stream,messages:s,...r.length>0||e?{tools:r}:{},...n.tool_choice!==void 0?{tool_choice:n.tool_choice}:{},...c!==void 0?{reasoning_effort:c}:{}},bridge:i}}import{randomUUID as Te}from"crypto";function wT(n){return{type:"response.created",sequence_number:n.sequenceNumber,response:{id:n.responseId,object:"response",status:"in_progress",model:n.model,created_at:Math.floor(Date.now()/1000),output:[]}}}function Ee(n){return{type:"response.output_item.added",sequence_number:n.sequenceNumber,output_index:n.outputIndex,item:n.item}}function lT(n){return{type:"response.output_text.delta",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,content_index:n.contentIndex,delta:n.delta}}function Z_(n){return{type:"response.reasoning_summary_text.delta",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,summary_index:n.summaryIndex,delta:n.delta}}function p_(n){return{type:"response.reasoning_summary_text.done",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,summary_index:n.summaryIndex,text:n.text}}function ye(n){return{type:"response.output_item.done",sequence_number:n.sequenceNumber,output_index:n.outputIndex,item:n.item}}function AT(n){return{type:"response.completed",sequence_number:n.sequenceNumber,response:{id:n.responseId,object:"response",status:"completed",model:n.model,output:n.output,usage:n.usage}}}function MT(n){return{type:"response.failed",sequence_number:n.sequenceNumber,response:{id:n.responseId,object:"response",status:"failed",model:n.model,error:n.error}}}function dT(n){return{type:"response.function_call_arguments.delta",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,delta:n.delta}}function RT(n){return{type:"response.custom_tool_call_input.delta",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,delta:n.delta}}function ET(n){return`event: ${n.type}
|
|
307
|
+
`):void 0}function VT(){return{type:"object",properties:{input:{type:"string"}},required:["input"],additionalProperties:!1}}function GV(n){return{type:"function",function:{name:n.name,...n.description!==void 0?{description:n.description}:{},...n.parameters!==void 0?{parameters:n.parameters}:{}}}}function jT(n){if(n.namespace!==void 0)return{kind:"namespace",namespace:n.namespace,name:n.name,toolType:n.type==="custom_tool_call"?"custom":"function"};if(n.type==="custom_tool_call")return{kind:"custom",name:n.name};return{kind:"function",name:n.name}}function Ae(n){return n.kind==="custom"||n.kind==="namespace"&&n.toolType==="custom"}function KT(n){return n.type==="function_call"||n.type==="custom_tool_call"}function WV(n){return n.type==="additional_tools"}function xT(n){return n.type==="function"||n.type==="custom"||n.type==="namespace"}function DV(n){return n.type==="function_call_output"||n.type==="custom_tool_call_output"}function PV(n){return n.trim().length===0?"{}":n}function YV(n){let t;try{t=JSON.parse(n)}catch(i){if(i instanceof SyntaxError)return{ok:!1,code:"invalid_custom_tool_input",message:"Custom tool arguments must be valid JSON"};throw i}if(typeof t!=="object"||t===null||Array.isArray(t)||Object.keys(t).length!==1||typeof t.input!=="string")return{ok:!1,code:"invalid_custom_tool_input",message:'Custom tool arguments must contain exactly {"input": string}'};return{ok:!0,input:t.input}}class kT{internalTools;declarations;#n;#t;constructor(n){this.internalTools=n.internalTools,this.declarations=n.declarations,this.#n=n.wireNameByIdentity,this.#t=n.identityByWireName}lowerCall(n){let t=jT(n),i=this.#n.get(Yf(t))??n.name;return{id:n.call_id,type:"function",function:{name:i,arguments:n.type==="custom_tool_call"?JSON.stringify({input:n.input}):n.arguments}}}restoreCalls(n){let t=[];for(let i of n){let r=this.#t.get(i.name);if(!r)return{ok:!1,code:"unknown_tool_alias",message:`Upstream returned undeclared tool ${i.name}`};if(Ae(r)){let s=YV(i.arguments);if(!s.ok)return s;t.push({id:i.itemId,type:"custom_tool_call",call_id:i.id,...r.kind==="namespace"?{namespace:r.namespace}:{},name:r.name,input:s.input});continue}t.push({id:i.itemId,type:"function_call",call_id:i.id,...r.kind==="namespace"?{namespace:r.namespace}:{},name:r.name,arguments:PV(i.arguments)})}return{ok:!0,items:t}}}function FV(n){let t=new Set;for(let i of n.tools){if(t.has(i.name))return!0;t.add(i.name)}return!1}function qT(n){let t=new Map,i=new Map,r=new Set,s=[],f=typeof n.input==="string"?[]:n.input;for(let T of f)if(KT(T)&&T.type==="function_call"&&T.namespace===void 0)r.add(T.name);let h=(T)=>{let S=Yf(T.identity),L=t.get(S);if(L!==void 0){if(L.fingerprint===T.fingerprint)return;return{ok:!1,code:"invalid_tool_declaration",message:`Tool ${T.path} conflicts with ${L.path}`}}t.set(S,T);return},_=(T,S,L,b)=>{if(T.type==="namespace"){if(FV(T))return{ok:!1,code:"invalid_tool_declaration",message:`Namespace ${T.name} contains duplicate child names`};for(let[U,X]of T.tools.entries()){let H={kind:"namespace",namespace:T.name,name:X.name,toolType:X.type},W=`${S}.tools.${U}`,K={type:"function",function:{name:"",...CT(T.description,X.description)!==void 0?{description:CT(T.description,X.description)}:{},parameters:X.type==="custom"?VT():X.parameters??{type:"object"}}},P=h({identity:H,tool:K,path:W,origin:L,...b!==void 0?{sourceMetadata:{role:b}}:{},...X.type==="function"?{strict:!1}:{},fingerprint:jh({identity:H,tool:K,origin:L,sourceRole:b})});if(P)return P}return}let I=i.get(T.name);if(I!==void 0&&I!==T.type)return{ok:!1,code:"invalid_tool_declaration",message:`Tool name ${T.name} is declared as both function and custom`};if(i.set(T.name,T.type),T.type==="function")r.add(T.name);let Z={kind:T.type,name:T.name},$=T.type==="function"?GV(T):{type:"function",function:{name:"",...T.description!==void 0?{description:T.description}:{},parameters:VT()}};return h({identity:Z,tool:$,path:S,origin:L,...b!==void 0?{sourceMetadata:{role:b}}:{},...T.type==="function"?{strict:!1}:{},fingerprint:jh({identity:Z,tool:$,origin:L,sourceRole:b})})};for(let[T,S]of(n.tools??[]).entries()){if(!xT(S))continue;let L=_(S,`tools.${T}`,"request");if(L)return L}for(let[T,S]of f.entries()){if(!WV(S))continue;for(let[L,b]of S.tools.entries()){if(!xT(b))continue;let I=_(b,`input.${T}.tools.${L}`,"input",S.role);if(I)return I}}let c=new Map;for(let[T,S]of f.entries()){if(!KT(S))continue;if(c.has(S.call_id))return{ok:!1,code:"invalid_tool_history",message:`Duplicate tool call id ${S.call_id}`};let L={index:T,identity:jT(S)};c.set(S.call_id,L),s.push(L)}let o=new Set;for(let[T,S]of f.entries()){if(!DV(S))continue;if(o.has(S.call_id))return{ok:!1,code:"invalid_tool_history",message:`Duplicate tool output id ${S.call_id}`};o.add(S.call_id);let L=c.get(S.call_id);if(!L)return{ok:!1,code:"invalid_tool_history",message:`Tool output ${S.call_id} has no matching call`};let b=Ae(L.identity),I=S.type==="custom_tool_call_output"&&b||S.type==="function_call_output"&&!b;if(L.index>=T||!I)return{ok:!1,code:"invalid_tool_history",message:`Tool output ${S.call_id} is out of order or has the wrong type`}}let w=[...t.values()];for(let T of s){let S=Yf(T.identity);if(t.has(S))continue;return{ok:!1,code:"missing_tool_declaration",message:`Historical ${T.identity.kind} tool call has no exact declaration; resend the original tool declaration`}}let e=new Set(r),u=new Map,y=new Map,A=0,R=0,M=(T)=>{for(;;){let S=T==="custom"?`${IV}${A++}`:`${HV}${R++}`;if(e.has(S))continue;return e.add(S),S}},E=[],g=[];for(let T of w){let S=Yf(T.identity),L=T.identity.kind==="function"?T.identity.name:M(T.identity.kind);u.set(S,L),y.set(L,T.identity),E.push({type:"function",function:{...T.tool.function,name:L}}),g.push({publicType:Ae(T.identity)?"custom":"function",publicName:T.identity.kind==="namespace"?`${T.identity.namespace}.${T.identity.name}`:T.identity.name,wireName:L,...T.tool.function.description!==void 0?{description:T.tool.function.description}:{},parameters:T.tool.function.parameters??{},path:T.path,origin:T.origin,...T.strict!==void 0?{strict:T.strict}:{},...T.sourceMetadata!==void 0?{sourceMetadata:T.sourceMetadata}:{}})}for(let T of r){let S={kind:"function",name:T};u.set(Yf(S),T),y.set(T,S)}return{ok:!0,bridge:new kT({internalTools:E,declarations:g,wireNameByIdentity:u,identityByWireName:y})}}var XV=new Set(["model","input","instructions","stream","tools","tool_choice","parallel_tool_calls","reasoning","include","store","text","service_tier","prompt_cache_key","metadata","client_metadata","previous_response_id","conversation","max_output_tokens","temperature","top_p","truncation","background","max_tool_calls"]),lV=["temperature","top_p","truncation","background","max_tool_calls","service_tier"],JV=new Set(["type","id","status","role","content"]),QV=new Set(["type","id","status","call_id","namespace","name","arguments"]),zV=new Set(["type","id","status","call_id","namespace","name","input"]),CV=new Set(["type","id","status","call_id","output"]),VV=new Set(["type","role","tools"]),KV=new Set(["type","id","status","summary","content","encrypted_content"]);function mT(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function st(n,t,i){for(let r of Object.keys(n)){if(i.has(r))continue;return Y("unsupported_parameter",`Responses field ${t}.${r} is not supported`,`${t}.${r}`)}return{ok:!0,value:void 0}}function Wi(n,t,i=[]){let r=Object.fromEntries(i.filter((s)=>n[s]!==void 0).map((s)=>[s,n[s]]));return{path:t,...typeof n.id==="string"?{sourceId:n.id}:{},...typeof n.status==="string"?{sourceStatus:n.status}:{},...Object.keys(r).length>0?{sourceMetadata:r}:{}}}function Re(n){return n.type==="message"||n.type===void 0&&"role"in n}function xV(n){return n.type==="agent_message"}function Me(n){return n.type==="function_call"}function Ee(n){return n.type==="custom_tool_call"}function ZT(n){return n.type==="function_call_output"}function aT(n){return n.type==="custom_tool_call_output"}function Te(n){return n.type==="additional_tools"}function ge(n){return n.type==="reasoning"}function ur(n,t){return{type:"text",text:n,path:t}}function jV(n,t){let i=[];for(let[r,s]of n.entries()){let f=`${t}.${r}`;if((s.type==="input_text"||s.type==="output_text")&&"text"in s&&typeof s.text==="string"){let h=s.type==="input_text"?new Set(["type","text"]):new Set(["type","text","annotations","logprobs"]),_=st(s,f,h);if(!_.ok)return _;i.push({...ur(s.text,`${f}.text`),...Wi(s,`${f}.text`,["annotations","logprobs"])});continue}if(s.type==="input_image"&&"image_url"in s&&typeof s.image_url==="string"){let h=st(s,f,new Set(["type","image_url"]));if(!h.ok)return h;if(!s.image_url.startsWith("data:"))return Y("unsupported_image_source","Responses images must use data URLs because Kiro cannot fetch remote image URLs",`${f}.image_url`);i.push({type:"image",url:s.image_url,path:f});continue}return Y("unsupported_content_part",`Responses content part ${f} of type ${s.type} is not supported`,f)}return{ok:!0,value:i}}function vT(n,t){return typeof n==="string"?{ok:!0,value:[ur(n,t)]}:jV(n,t)}function kV(n,t){if(typeof n==="string")return{ok:!0,value:[ur(n,t)]};let i=[];for(let[r,s]of n.entries()){let f=`${t}.${r}`;if(s.type!=="input_text"&&s.type!=="output_text"&&s.type!=="text"||typeof s.text!=="string")return Y("unsupported_tool_result_content",`Tool output ${f} must be a text block`,f);let h=st(s,f,s.type==="output_text"?new Set(["type","text","annotations","logprobs"]):new Set(["type","text"]));if(!h.ok)return h;i.push({...ur(s.text,`${f}.text`),...Wi(s,`${f}.text`,["annotations","logprobs"])})}return{ok:!0,value:i}}function qV(n,t){if(Re(n))return st(n,t,JV);if(Me(n))return st(n,t,QV);if(Ee(n))return st(n,t,zV);if(ZT(n)||aT(n))return st(n,t,CV);if(Te(n)){let i=st(n,t,VV);if(!i.ok)return i;if(n.role!==void 0&&n.role!=="developer")return Y("unsupported_additional_tools_role","additional_tools.role must be developer when provided",`${t}.role`);return{ok:!0,value:void 0}}if(ge(n)){let i=st(n,t,KV);if(!i.ok)return i;for(let[r,s]of(n.summary??[]).entries()){let f=`${t}.summary.${r}`,h=st(s,f,new Set(["type","text"]));if(!h.ok)return h}for(let[r,s]of(n.content??[]).entries()){let f=`${t}.content.${r}`,h=st(s,f,new Set(["type","reasoning_text"]));if(!h.ok)return h}}return{ok:!0,value:void 0}}function mV(n){if(n==="minimal")return"low";if(n==="low"||n==="medium"||n==="high"||n==="xhigh"||n==="max")return n;return}function ZV(n){if(n===void 0)return{ok:!0,value:void 0};if(!mT(n))return Y("unsupported_parameter","Responses text must request the default text format","text");let t=Object.keys(n);if(t.length===0)return{ok:!0,value:void 0};if(t.length===1&&t[0]==="format"){let i=n.format;if(mT(i)&&i.type==="text"&&Object.keys(i).length===1)return{ok:!0,value:void 0}}return Y("unsupported_structured_output","Structured Responses text output cannot be represented by the Kiro upstream","text")}function aV(n){let t=n.reasoning;if(t===void 0||t===null)return{ok:!0,value:void 0};for(let i of Object.keys(t))if(i!=="effort"&&i!=="summary")return Y("unsupported_parameter",`Responses reasoning.${i} is not supported`,`reasoning.${i}`);if(t.summary!==void 0)return Y("unsupported_reasoning_summary","reasoning.summary cannot be guaranteed by the Kiro upstream","reasoning.summary");return{ok:!0,value:void 0}}function vV(n,t){let i="",r=[],s=!1;for(let f=t+1;f<n.length;f+=1){let h=n[f];if(!h)continue;if(Re(h)){if(h.role!=="assistant")break;let _=vT(h.content,`input.${f}.content`);if(!_.ok)return _;i+=si(_.value),s=!0;continue}if(Me(h)){r.push({id:h.call_id,name:h.namespace===void 0?h.name:`${h.namespace}.${h.name}`,input:h.arguments}),s=!0;continue}if(Ee(h)){r.push({id:h.call_id,name:h.namespace===void 0?h.name:`${h.namespace}.${h.name}`,input:h.input}),s=!0;continue}if(ge(h))continue;break}if(!s)return Y("invalid_reasoning_replay",`Reasoning item input.${t} has no associated assistant output`,`input.${t}`);return{ok:!0,value:et({text:i,toolCalls:r})}}function pV(n){let t=(i,r,s)=>{if(i.type==="namespace")return Y("unsupported_tool_type","Responses namespace tools cannot be represented without changing tool identity",r);if(i.type!=="function"&&i.type!=="custom")return Y(i.type.startsWith("web_search")?"unsupported_web_search":"unsupported_tool_type",`Responses tool type ${i.type} is not supported by the Kiro upstream`,r);if(i.type==="function"){let h=new Set(["type","name","description","parameters","strict"]);if(s)h.add("inputSchema");let _=st(i,r,h);if(!_.ok)return _;if(s&&i.parameters!==void 0&&i.inputSchema!==void 0)return Y("invalid_tool_declaration",`Responses tool ${r} cannot specify both parameters and inputSchema`,r);if(i.strict===!0)return Y("unsupported_strict_tools","strict=true cannot be guaranteed by the Kiro upstream",`${r}.strict`);return{ok:!0,value:void 0}}let f=st(i,r,new Set(["type","name","description","format"]));if(!f.ok)return f;if(i.format!==void 0)return Y("unsupported_custom_tool_format","Custom tool grammar cannot be enforced by the Kiro upstream",`${r}.format`);return{ok:!0,value:void 0}};for(let[i,r]of(n.tools??[]).entries()){let s=t(r,`tools.${i}`,!1);if(!s.ok)return s}if(typeof n.input!=="string")for(let[i,r]of n.input.entries()){if(!Te(r))continue;for(let[s,f]of r.tools.entries()){let h=t(f,`input.${i}.tools.${s}`,!0);if(!h.ok)return h}}return{ok:!0,value:void 0}}function pT(n,t="safe"){try{Kt(n.model)}catch{return Y("unsupported_model",`Responses model ${n.model} is not supported`,"model")}for(let M of Object.keys(n))if(!XV.has(M))return Y("unsupported_parameter",`Responses parameter ${M} is not supported`,M);for(let M of lV)if(n[M]!==void 0)return Y("unsupported_parameter",`Responses parameter ${M} cannot be represented by the Kiro upstream`,M);if(n.previous_response_id!==void 0||n.conversation!==void 0)return Y("unsupported_stateful_responses","Stateful Responses continuation is not supported; resend the complete input",n.previous_response_id!==void 0?"previous_response_id":"conversation");if(n.store===!0)return Y("unsupported_parameter","Responses store=true is not supported","store");if(n.parallel_tool_calls===!1)return Y("unsupported_parallel_tool_calls","parallel_tool_calls=false cannot be guaranteed by the Kiro upstream","parallel_tool_calls");if(n.tool_choice==="required"||typeof n.tool_choice==="object"&&n.tool_choice!==null)return Y("unsupported_tool_choice","Required, named, or constrained tool choice cannot be represented by the Kiro upstream","tool_choice");let i=n.include??[],r=i.find((M)=>M!=="reasoning.encrypted_content");if(r!==void 0)return Y("unsupported_parameter",`Responses include value ${r} is not supported`,"include");let s=ZV(n.text);if(!s.ok)return s;let f=aV(n);if(!f.ok)return f;if(n.max_output_tokens!==void 0){let M=Hi(n.model,n.max_output_tokens);if(!M.ok)return Y(M.code,M.message,"max_output_tokens")}let h=pV(n);if(!h.ok)return h;let _=qT(n);if(!_.ok)return _;let c=_.bridge,o=c.declarations.map((M)=>({publicType:M.publicType,name:M.publicName,wireName:M.wireName,...M.description!==void 0?{description:M.description}:{},inputSchema:M.parameters,path:M.path,origin:M.origin,...M.strict!==void 0?{strict:M.strict}:{},...M.sourceMetadata!==void 0?{sourceMetadata:M.sourceMetadata}:{}})),w=[],e=[],u=n.instructions!==void 0?ur(n.instructions,"instructions"):void 0;if(n.instructions!==void 0&&n.instructions.length>0){if(t==="safe")return Y("unsupported_instruction_projection","Responses instructions cannot be projected losslessly to Kiro; use legacy-user-prefix explicitly to migrate","instructions");w.push({role:"developer",content:[ur(n.instructions,"instructions")],toolCalls:[],path:"instructions"})}let y=!1;if(typeof n.input==="string")w.push({role:"user",content:[ur(n.input,"input")],toolCalls:[],path:"input"}),y=!0;else for(let[M,E]of n.input.entries()){let g=`input.${M}`,T=qV(E,g);if(!T.ok)return T;if(ge(E)){let S=E.summary!==void 0&&E.summary!==null&&E.summary.length>0,L=E.content!==void 0&&E.content!==null&&E.content.length>0;if(S||L)return Y("unsupported_reasoning_plaintext_replay","Reasoning replay must use encrypted_content without plaintext summary/content",g);if(typeof E.encrypted_content!=="string"||!E.encrypted_content.startsWith("kr1_"))return Y("invalid_reasoning_replay","Reasoning replay requires a kiro-provider kr1_ encrypted_content token",`${g}.encrypted_content`);let b=vV(n.input,M);if(!b.ok)return b;e.push({lookup:{kind:"responses-token",encryptedContent:E.encrypted_content},outputFingerprint:b.value,insertBeforeMessage:w.length,...Wi(E,g)});continue}if(Me(E)||Ee(E)){if(E.namespace!==void 0)return Y("unsupported_tool_namespace","Namespaced tool calls cannot be represented without changing tool identity",`${g}.namespace`);let S=c.lowerCall(E),L;try{L=JSON.parse(S.function.arguments)}catch(b){if(!(b instanceof SyntaxError))throw b;return Y("invalid_tool_history",`Tool call ${E.call_id} contains invalid JSON arguments`,g)}w.push({role:"assistant",content:[],toolCalls:[{id:E.call_id,name:S.function.name,input:L,...Wi(E,g)}],...Wi(E,g)}),y=!0;continue}if(Re(E)){if(t==="safe"&&(E.role==="system"||E.role==="developer"))return Y("unsupported_instruction_projection",`${E.role} input cannot be projected losslessly to Kiro; use legacy-user-prefix explicitly to migrate`,g);let S=vT(E.content,`${g}.content`);if(!S.ok)return S;w.push({role:E.role,content:S.value,toolCalls:[],...Wi(E,g)}),y=!0;continue}if(xV(E))return Y("unsupported_input_item","agent_message author/recipient semantics cannot be represented by the Kiro upstream",g);if(ZT(E)||aT(E)){let S=kV(E.output,`${g}.output`);if(!S.ok)return S;w.push({role:"tool",content:[{type:"tool_result",toolCallId:E.call_id,content:S.value,isError:!1,...Wi(E,g)}],toolCalls:[],...Wi(E,g)}),y=!0;continue}if(Te(E))continue;return Y("unsupported_input_item",`Responses input item ${g} of type ${E.type} is not supported`,g)}if(!y)return Y("empty_input","input produced no executable messages","input");let A=new Set;for(let M of w){for(let E of M.toolCalls)A.add(E.id);for(let E of M.content)if(E.type==="tool_result")A.delete(E.toolCallId)}if(n.tool_choice==="none"&&A.size>0)return Y("unsupported_tool_choice","tool_choice=none cannot be used while tool calls are awaiting results","tool_choice");let R=mV(n.reasoning?.effort);return{ok:!0,body:{canonicalVersion:1,protocol:"responses",projectionMode:t,model:n.model,stream:n.stream,messages:w,tools:o,toolChoice:n.tool_choice==="none"?"none":"auto",...R!==void 0?{reasoningEffort:R}:{},...n.reasoning?.effort!==void 0?{requestedReasoningEffort:n.reasoning.effort}:{},...n.max_output_tokens!==void 0?{outputTokenLimit:n.max_output_tokens}:{},...u!==void 0?{instructions:u}:{},reasoningReplays:e,includeEncryptedReasoning:i.includes("reasoning.encrypted_content"),...n.prompt_cache_key!==void 0?{promptCacheKey:n.prompt_cache_key}:{},...n.metadata!==void 0?{metadata:n.metadata}:{}},bridge:c}}import{randomUUID as gs}from"crypto";function nK(n){if(n.publicType==="custom")return{type:"custom",name:n.name,...n.description!==void 0?{description:n.description}:{}};return{type:"function",name:n.name,...n.description!==void 0?{description:n.description}:{},parameters:n.inputSchema,strict:!1}}function n2(n){return{instructions:n.instructions?.text??null,maxOutputTokens:n.outputTokenLimit??null,metadata:n.metadata??{},reasoningEffort:n.requestedReasoningEffort??null,toolChoice:n.toolChoice,tools:n.tools.filter((t)=>t.origin==="request").map(nK)}}var tK={instructions:null,maxOutputTokens:null,metadata:{},reasoningEffort:null,toolChoice:"auto",tools:[]};function yr(n){let t=n.configuration??tK;return{id:n.id,object:"response",created_at:n.createdAt??Math.floor(Date.now()/1000),completed_at:n.status==="completed"?n.completedAt??Math.floor(Date.now()/1000):null,status:n.status,background:!1,error:n.error??null,incomplete_details:null,instructions:t.instructions,max_output_tokens:t.maxOutputTokens,max_tool_calls:null,metadata:t.metadata,model:n.model,output:n.output??[],parallel_tool_calls:!0,previous_response_id:null,reasoning:{effort:t.reasoningEffort,summary:null},service_tier:null,store:!1,temperature:null,text:{format:{type:"text"}},tool_choice:t.toolChoice,tools:t.tools,top_logprobs:null,top_p:null,truncation:"disabled",user:null,usage:n.usage??null}}function t2(n){return{type:"response.created",sequence_number:n.sequenceNumber,response:yr({id:n.responseId,model:n.model,status:"in_progress",...n.createdAt!==void 0?{createdAt:n.createdAt}:{},...n.configuration!==void 0?{configuration:n.configuration}:{}})}}function i2(n){return{type:"response.in_progress",sequence_number:n.sequenceNumber,response:yr({id:n.responseId,model:n.model,status:"in_progress",...n.createdAt!==void 0?{createdAt:n.createdAt}:{},...n.configuration!==void 0?{configuration:n.configuration}:{}})}}function Es(n){return{type:"response.output_item.added",sequence_number:n.sequenceNumber,output_index:n.outputIndex,item:n.item}}function r2(n){return{type:"response.output_text.delta",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,content_index:n.contentIndex,delta:n.delta}}function s2(n){return{type:"response.content_part.added",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,content_index:n.contentIndex,part:n.part}}function f2(n){return{type:"response.output_text.done",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,content_index:n.contentIndex,text:n.text}}function _2(n){return{type:"response.content_part.done",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,content_index:n.contentIndex,part:n.part}}function Se(n){return{type:"response.reasoning_summary_text.delta",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,summary_index:n.summaryIndex,delta:n.delta}}function Le(n){return{type:"response.reasoning_summary_text.done",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,summary_index:n.summaryIndex,text:n.text}}function Ts(n){return{type:"response.output_item.done",sequence_number:n.sequenceNumber,output_index:n.outputIndex,item:n.item}}function h2(n){return{type:"response.completed",sequence_number:n.sequenceNumber,response:yr({id:n.responseId,model:n.model,status:"completed",output:n.output,usage:n.usage,...n.createdAt!==void 0?{createdAt:n.createdAt}:{},...n.completedAt!==void 0?{completedAt:n.completedAt}:{},...n.configuration!==void 0?{configuration:n.configuration}:{}})}}function c2(n){return{type:"response.failed",sequence_number:n.sequenceNumber,response:yr({id:n.responseId,model:n.model,status:"failed",error:n.error,...n.createdAt!==void 0?{createdAt:n.createdAt}:{},...n.configuration!==void 0?{configuration:n.configuration}:{}})}}function o2(n){return{type:"response.function_call_arguments.delta",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,delta:n.delta}}function w2(n){return{type:"response.custom_tool_call_input.delta",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,delta:n.delta}}function e2(n){return{type:"response.function_call_arguments.done",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,arguments:n.arguments}}function u2(n){return{type:"response.custom_tool_call_input.done",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,input:n.input}}function y2(n){return`event: ${n.type}
|
|
262
308
|
data: ${JSON.stringify(n)}
|
|
263
309
|
|
|
264
|
-
`}function
|
|
265
|
-
`);if(
|
|
310
|
+
`}function d2(n,t){let i=t.signals,s=(n.body??new ReadableStream({start:(D)=>D.close()})).getReader(),f=new TextDecoder,h=new TextEncoder,_=`resp_${gs()}`,c=`msg_${gs()}`,o=Math.floor(Date.now()/1000),w=new Map,e=new Map,u=[],y="",A="",R,M,E="",g,T=0,S=0,L,b,I,Z,$=!1,U=(D,j)=>{u.push(h.encode(y2(j(S)))),S+=1},X=(D)=>{if($||L===void 0||L==="consumer-cancel"||u.length>0)return;$=!0,D.close()},H=(D)=>{if($)return!1;let j=D.desiredSize;if(u.length>0&&j!==null&&j>0){let hn=u.shift();if(!hn)return!1;return D.enqueue(hn),X(D),!0}return X(D),!1},W=(D)=>{if(L!==void 0)return!1;return L=D,!0},K=()=>{i.deadline.removeEventListener("abort",q)},P=()=>{i.client.removeEventListener("abort",v)},z=(D,j,hn)=>{if(!W(D))return;if(I=hn,D==="consumer-cancel")u.length=0;zn(K,P,()=>{if(!Z)return;if(D==="normal-complete"){if(!b)throw TypeError("Responses stream completed without terminal data");U(Z,(Ln)=>h2({responseId:_,model:t.model,output:b?.output??[],usage:b?.usage??{input_tokens:0,output_tokens:0,total_tokens:0},sequenceNumber:Ln,createdAt:o,completedAt:Math.floor(Date.now()/1000),configuration:t.configuration}))}else if(D==="deadline"||D==="upstream-error"||D==="upstream-protocol-error"){let Ln=I??{code:"upstream_error",message:"Upstream stream error"};U(Z,(tt)=>c2({responseId:_,model:t.model,error:Ln,sequenceNumber:tt,createdAt:o,configuration:t.configuration}))}},t.finalize,()=>{if(Z)H(Z)}),An(()=>s.cancel(j))},x=(D,j="upstream_error")=>{z("upstream-protocol-error",void 0,{code:j,message:D})},q=()=>{let D=i.deadline.reason instanceof Error?i.deadline.reason:new DOMException("Request deadline exceeded","TimeoutError");z("deadline",D,{code:"upstream_error",message:"Request deadline exceeded"})},v=()=>{let D=i.client.reason instanceof Error?i.client.reason:new DOMException("Client closed request","AbortError");z("client-abort",D)},Di=(D)=>{if(!M)return;let j={id:M.id,type:"reasoning",summary:[{type:"summary_text",text:M.text}],...g!==void 0?{encrypted_content:g}:{}};U(D,(hn)=>Le({itemId:M?.id??"",outputIndex:M?.outputIndex??0,summaryIndex:0,text:M?.text??"",sequenceNumber:hn})),U(D,(hn)=>Ts({item:j,outputIndex:M?.outputIndex??0,sequenceNumber:hn})),e.set(M.outputIndex,j),M=void 0},$2=(D)=>{if(E.length===0)return;let j={id:`rs_${gs()}`,outputIndex:T,text:E};T+=1,E="",U(D,(Ln)=>Es({item:{id:j.id,type:"reasoning",summary:[]},outputIndex:j.outputIndex,sequenceNumber:Ln})),U(D,(Ln)=>Se({itemId:j.id,outputIndex:j.outputIndex,summaryIndex:0,delta:j.text,sequenceNumber:Ln})),U(D,(Ln)=>Le({itemId:j.id,outputIndex:j.outputIndex,summaryIndex:0,text:j.text,sequenceNumber:Ln}));let hn={id:j.id,type:"reasoning",summary:[{type:"summary_text",text:j.text}],...g!==void 0?{encrypted_content:g}:{}};U(D,(Ln)=>Ts({item:hn,outputIndex:j.outputIndex,sequenceNumber:Ln})),e.set(j.outputIndex,hn)},Be=(D,j)=>{switch(j.kind){case"empty":return;case"reasoning":{if(R!==void 0){E+=j.text;return}if(!M)M={id:`rs_${gs()}`,outputIndex:T,text:""},T+=1,U(D,(hn)=>Es({item:{id:M?.id??"",type:"reasoning",summary:[]},outputIndex:M?.outputIndex??0,sequenceNumber:hn}));M.text+=j.text,U(D,(hn)=>Se({itemId:M?.id??"",outputIndex:M?.outputIndex??0,summaryIndex:0,delta:j.text,sequenceNumber:hn}));return}case"reasoning_encrypted":g=j.encryptedContent;return;case"reasoning_signature":case"reasoning_redacted":return;case"text":{if(Di(D),R===void 0)R=T,T+=1,U(D,(hn)=>Es({item:{id:c,type:"message",role:"assistant",status:"in_progress",content:[]},outputIndex:R??0,sequenceNumber:hn})),U(D,(hn)=>s2({itemId:c,outputIndex:R??0,contentIndex:0,part:{type:"output_text",text:"",annotations:[]},sequenceNumber:hn}));A+=j.text,U(D,(hn)=>r2({itemId:c,outputIndex:R??0,contentIndex:0,delta:j.text,sequenceNumber:hn}));return}case"tool_calls":Di(D);for(let hn of j.calls){let Ln=w.get(hn.index)??{itemId:`fc_${gs()}`,id:"",name:"",arguments:""};if(Ln.id.length===0&&hn.id!==void 0)Ln.id=hn.id;if(Ln.name.length===0&&hn.name!==void 0)Ln.name=hn.name;Ln.arguments+=hn.arguments,w.set(hn.index,Ln)}return}},Ie=(D,j)=>{if([...w.values()].some((p)=>p.id.length===0||p.name.length===0)){x("Malformed upstream tool call");return}let tt=[...w.entries()].sort(([p],[En])=>p-En).map(([,p])=>({itemId:p.itemId,id:p.id,name:p.name,arguments:p.arguments.trim().length===0?"{}":p.arguments})),ut=t.bridge?.restoreCalls(tt)??{ok:!0,items:tt.map((p)=>({id:p.itemId,type:"function_call",call_id:p.id,name:p.name,arguments:p.arguments}))};if(!ut.ok){x(ut.message,"upstream_protocol_error");return}if(Di(D),R!==void 0){let p={id:c,type:"message",role:"assistant",status:"completed",content:[{type:"output_text",text:A,annotations:[]}]};U(D,(En)=>f2({itemId:c,outputIndex:R??0,contentIndex:0,text:A,sequenceNumber:En})),U(D,(En)=>_2({itemId:c,outputIndex:R??0,contentIndex:0,part:{type:"output_text",text:A,annotations:[]},sequenceNumber:En})),U(D,(En)=>Ts({item:p,outputIndex:R??0,sequenceNumber:En})),e.set(R,p)}if($2(D),g!==void 0){let p=!1;for(let[En,_i]of e){if(_i.type!=="reasoning")continue;e.set(En,{..._i,encrypted_content:g}),p=!0}if(!p){let En=T;T+=1;let _i={id:`rs_${gs()}`,type:"reasoning",summary:[],encrypted_content:g};U(D,(dr)=>Es({item:{id:_i.id,type:"reasoning",summary:[]},outputIndex:En,sequenceNumber:dr})),U(D,(dr)=>Ts({item:_i,outputIndex:En,sequenceNumber:dr})),e.set(En,_i)}}for(let p of ut.items){let En=T;T+=1;let _i=p.type==="function_call"?{...p,arguments:""}:{...p,input:""};if(U(D,(yt)=>Es({item:_i,outputIndex:En,sequenceNumber:yt})),p.type==="function_call")U(D,(yt)=>o2({itemId:p.id,outputIndex:En,delta:p.arguments,sequenceNumber:yt})),U(D,(yt)=>e2({itemId:p.id,outputIndex:En,arguments:p.arguments,sequenceNumber:yt}));else U(D,(yt)=>w2({itemId:p.id,outputIndex:En,delta:p.input,sequenceNumber:yt})),U(D,(yt)=>u2({itemId:p.id,outputIndex:En,input:p.input,sequenceNumber:yt}));let dr={...p,status:"completed"};U(D,(yt)=>Ts({item:dr,outputIndex:En,sequenceNumber:yt})),e.set(En,dr)}b={output:[...e.entries()].sort(([p],[En])=>p-En).map(([,p])=>p),usage:{input_tokens:j.inputTokens,output_tokens:j.outputTokens,total_tokens:j.totalTokens}},z("normal-complete")};return new Response(new ReadableStream({start(D){if(Z=D,U(D,(j)=>t2({responseId:_,model:t.model,sequenceNumber:j,createdAt:o,configuration:t.configuration})),U(D,(j)=>i2({responseId:_,model:t.model,sequenceNumber:j,createdAt:o,configuration:t.configuration})),i.deadline.addEventListener("abort",q,{once:!0}),i.client.addEventListener("abort",v,{once:!0}),i.deadline.aborted)q();else if(i.client.aborted)v();H(D)},async pull(D){if(H(D))return;if(L!==void 0)return;try{while(L===void 0){let j=y.indexOf(`
|
|
311
|
+
`);if(j>=0){let tt=y.slice(0,j).trimEnd();if(y=y.slice(j+1),tt.length===0)continue;let ut=Ms(tt);if(!ut){x("Malformed upstream stream");return}if(Be(D,ut.delta),ut.finishReason!==null){if(!ut.usage){x("Terminal upstream chunk omitted usage");return}Ie(D,ut.usage);return}if(ut.delta.kind!=="tool_calls"&&ut.delta.kind!=="empty"){if(H(D))return}continue}let hn=await s.read();if(L!==void 0)return;if(!hn.done){y+=f.decode(hn.value,{stream:!0});continue}y+=f.decode();let Ln=y.trim();if(y="",Ln.length>0){let tt=Ms(Ln);if(!tt){x("Malformed upstream stream");return}if(Be(D,tt.delta),tt.finishReason!==null&&tt.usage){Ie(D,tt.usage);return}}x("Upstream stream ended before completion");return}}catch(j){if(L!==void 0)return;z("upstream-error",j,{code:"upstream_error",message:"Upstream stream error"})}},cancel(D){z("consumer-cancel",D)}}),{headers:{"Cache-Control":"no-cache","Content-Type":"text/event-stream; charset=utf-8"}})}class Oe extends Error{limit;name="RequestBodyTooLargeError";constructor(n){super(`Request body exceeds the ${n} byte limit`);this.limit=n}}function $e(n){return n.reason instanceof Error?n.reason:new DOMException("Request deadline exceeded","TimeoutError")}async function iK(n,t,i){let r=n.body?.getReader();if(!r)return{ok:!0,text:""};let s=[],f=0,h,_=new Promise((o,w)=>{h=w}),c=()=>{let o=$e(i.combined);h?.(o),r.cancel(o)};i.combined.addEventListener("abort",c,{once:!0});try{while(!0){if(i.combined.aborted)throw $e(i.combined);let e=await Promise.race([r.read(),_]);if(i.combined.aborted)throw $e(i.combined);if(e.done)break;if(f+=e.value.byteLength,f>t)throw new Oe(t);s.push(e.value)}let o=new Uint8Array(f),w=0;for(let e of s)o.set(e,w),w+=e.byteLength;return{ok:!0,text:new TextDecoder().decode(o)}}catch(o){if(o instanceof Oe)return r.cancel(o).catch(()=>{return}),{ok:!1,response:fn(413,o.message,"invalid_request_error","request_too_large")};if(i.deadline.aborted)return r.cancel(o).catch(()=>{return}),{ok:!1,response:fn(504,"Request deadline exceeded","timeout_error","request_timeout")};if(i.client.aborted)return r.cancel(o).catch(()=>{return}),{ok:!1,response:fn(499,"Client closed request","request_aborted","client_disconnected")};throw o}finally{i.combined.removeEventListener("abort",c)}}function rK(n,t,i,r){let s=i.restoreCalls(n.message.toolCalls.map((h)=>({itemId:`fc_${c0()}`,id:h.id,name:h.name,arguments:h.arguments})));if(!s.ok)return fn(502,s.message,"upstream_error","upstream_protocol_error");let f=[];if(n.message.reasoningContent||n.message.reasoningEncryptedContent){let h={id:`rs_${c0()}`,type:"reasoning",summary:n.message.reasoningContent?[{type:"summary_text",text:n.message.reasoningContent}]:[],...n.message.reasoningEncryptedContent?{encrypted_content:n.message.reasoningEncryptedContent}:{}};f.push(h)}if(n.message.content.length>0){let h={id:`msg_${c0()}`,type:"message",role:"assistant",status:"completed",content:[{type:"output_text",text:n.message.content,annotations:[]}]};f.push(h)}return f.push(...s.items),Response.json(yr({id:`resp_${c0()}`,status:"completed",model:t,output:f,usage:{input_tokens:n.usage.inputTokens,output_tokens:n.usage.outputTokens,total_tokens:n.usage.totalTokens},configuration:r}))}async function A2(n,t,i){let r=new AbortController,s=setTimeout(()=>r.abort(new DOMException("Request deadline exceeded","TimeoutError")),t.request_timeout_ms),f=AbortSignal.any([r.signal,n.signal]),h={combined:f,deadline:r.signal,client:n.signal},_=await iK(n,t.max_request_body_bytes,h);if(!_.ok)return clearTimeout(s),_.response;let c;try{c=JSON.parse(_.text)}catch(E){if(clearTimeout(s),!(E instanceof SyntaxError))throw E;return fn(400,"Request body must contain valid JSON","invalid_request_error","invalid_json")}let o=$T(c);if(!o.ok)return clearTimeout(s),o.response;let w=UT(o.value,i.tenantId,t.session_affinity_mode),e=pT(o.value,t.protocol_projection_mode);if(!e.ok)return dn("warn","protocol_projection_rejected",{protocol:"responses",projection_mode:t.protocol_projection_mode,code:e.code,param:e.param}),clearTimeout(s),fn(400,e.message??"input produced no messages","invalid_request_error",e.code,e.param);let u=n2(e.body),y=o.value.stream,A,R=!1,M=()=>{zn(()=>clearTimeout(s),()=>A?.restore())};try{A=i.createRequestIdleTimeoutLease?.(),A?.disable();let E=await(i.runPipeline??As)({body:e.body,model:e.body.model,stream:y,config:t,accountManager:i.accountManager,tokenRefresher:i.tokenRefresher,...w?{affinity:w}:{},...i.affinityStore?{affinityStore:i.affinityStore}:{},tenantId:i.tenantId,...i.reasoningReplayStore?{reasoningReplayStore:i.reasoningReplayStore}:{},deadlineSignal:f,...i.makeClient?{makeClient:i.makeClient}:{}});if(n.signal.aborted&&!r.signal.aborted)return An(()=>E.body?.cancel()),fn(499,"Client closed request","request_aborted","client_disconnected");let g=E.headers.get("Content-Type")??"";if(y&&g.includes("application/x-ndjson")){let T=d2(E,{model:e.body.model,signals:h,finalize:M,bridge:e.bridge,configuration:u});return R=!0,T}if(g.includes("application/json")){if(y||!E.ok)return E;let T=await E.json(),S=h0(T);if(S)return rK(S,e.body.model,e.bridge,u);return fn(500,"Pipeline returned an invalid non-streaming response","internal_error","invalid_pipeline_response")}return An(()=>E.body?.cancel()),fn(500,"Pipeline returned an unsupported response","internal_error","invalid_pipeline_response")}finally{if(!R)M()}}var sK=10;function fK(n,t){let i="idle";return{disable:()=>{if(i!=="idle")return;i="disabled",t.timeout(n,0)},restore:()=>{if(i!=="disabled")return;i="restored",t.timeout(n,sK)}}}function _K(n,t){return async(i,r)=>{let s=new URL(i.url);if(i.method==="GET"&&s.pathname==="/health")return IT();let f=s.pathname==="/v1/messages"||s.pathname==="/v1/messages/count_tokens",h=f?ic(i,n.api_keys,(w,e)=>Pn(w,e,"authentication_error")):ic(i,n.api_keys);if(!h.ok)return h.response;let _=t.createRequestIdleTimeoutLease??fK,c=r?()=>_(i,r):void 0,o={accountManager:t.accountManager,tokenRefresher:t.tokenRefresher,tenantId:h.tenantId,...t.affinityStore?{affinityStore:t.affinityStore}:{},...t.reasoningReplayStore?{reasoningReplayStore:t.reasoningReplayStore}:{},...t.makeClient?{makeClient:t.makeClient}:{},...c?{createRequestIdleTimeoutLease:c}:{}};try{if(i.method==="POST"&&s.pathname==="/v1/chat/completions"){if(!n.enable_legacy_chat_completions)return fn(404,"Legacy Chat Completions is disabled; set enable_legacy_chat_completions to true","invalid_request_error","legacy_chat_completions_disabled");return await BT(i,n,o)}if(i.method==="POST"&&s.pathname==="/v1/responses")return await A2(i,n,o);if(i.method==="POST"&&s.pathname==="/v1/messages")return await lT(i,n,o);if(i.method==="POST"&&s.pathname==="/v1/messages/count_tokens")return await JT(i,n);if(i.method==="GET"&&s.pathname==="/v1/models")return QT();if(i.method==="GET"&&s.pathname==="/ready")return zT(t.accountManager,t.reasoningReplayStore);return fn(404,"Route not found","invalid_request_error","not_found")}catch(w){let e=w instanceof Error?w.message:"Internal server error";if(f)return Pn(500,e,"api_error");return fn(500,e,"internal_error","internal_error")}}}function hK(n,t={}){if(n.protocol_projection_mode==="legacy-user-prefix")dn("warn","legacy_protocol_projection_enabled",{projection_mode:n.protocol_projection_mode,planned_removal:"v0.7.0"});if(n.session_affinity_mode==="legacy-initial-input")dn("warn","legacy_session_affinity_enabled",{session_affinity_mode:n.session_affinity_mode,risk:"identical_initial_input_can_alias_independent_sessions",planned_removal:"v0.7.0"});let i=t.createDatabase?.()??new qi,r=t.createReasoningReplayStore?.(i,n)??new Z0(i,n),s=Qr(n);if(n.auth_source==="opencode-shared"){let _=n.opencode_auth_db_path??$s(),c=t.createOpenCodeAuthStore?.(_)??new e0(_),o=new V0(c,n.account_selection_strategy),w=t.createOpenCodeTokenRefresher?t.createOpenCodeTokenRefresher(o,c,n.token_expiry_buffer_ms,s):new K0(o,c,n.token_expiry_buffer_ms,s);return{accountManager:o,tokenRefresher:w,affinityStore:i,reasoningReplayStore:r}}let f=new M0(i.getAccounts(),n.account_selection_strategy,i),h=t.createTokenRefresher?t.createTokenRefresher(f,n.token_expiry_buffer_ms,s):new C0(f,n.token_expiry_buffer_ms,s);return{accountManager:f,tokenRefresher:h,affinityStore:i,reasoningReplayStore:r}}function cK(n,t){return{hostname:n.host,port:n.port,fetch:_K(n,t)}}function R2(n){return Bun.serve(cK(n,hK(n)))}import{parseArgs as Ue}from"util";var o0=`Usage: kiro-provider <command> [options]
|
|
266
312
|
|
|
267
313
|
Commands:
|
|
268
314
|
serve [--config <path>] [--host <host>] [--port <port>] [--proxy <url>]
|
|
@@ -277,10 +323,10 @@ Commands:
|
|
|
277
323
|
Remove an account from the local compatibility store and write a tombstone.
|
|
278
324
|
|
|
279
325
|
Options:
|
|
280
|
-
-h, --help Show this help.`;class
|
|
326
|
+
-h, --help Show this help.`;class Ss extends Error{constructor(n){super(n);this.name="CliUsageError"}}function oK(n){let t=Ue({args:[...n],options:{config:{type:"string"},host:{type:"string"},port:{type:"string"},proxy:{type:"string"},help:{type:"boolean",short:"h"}},strict:!0,allowPositionals:!1});if(t.values.help)return{kind:"help"};let i=t.values.port===void 0?void 0:Number(t.values.port);if(i!==void 0&&(!Number.isInteger(i)||i<1||i>65535))throw new Ss(`Invalid port: ${t.values.port}`);return{kind:"serve",...t.values.config?{configPath:t.values.config}:{},...t.values.host?{host:t.values.host}:{},...i!==void 0?{port:i}:{},...t.values.proxy!==void 0?{proxy:t.values.proxy}:{}}}function wK(n){let t=Ue({args:[...n],options:{config:{type:"string"},"start-url":{type:"string"},region:{type:"string"}},strict:!0,allowPositionals:!1});return{kind:"login",...t.values.config?{configPath:t.values.config}:{},...t.values["start-url"]?{startUrl:t.values["start-url"]}:{},...t.values.region?{region:t.values.region}:{}}}function eK(n){let t=Ue({args:[...n],options:{from:{type:"string"},config:{type:"string"},help:{type:"boolean",short:"h"}},strict:!0,allowPositionals:!1});if(t.values.help)return{kind:"help"};return{kind:"accounts-import",...t.values.from?{from:t.values.from}:{},...t.values.config?{configPath:t.values.config}:{}}}function uK(n){let t=n[0];switch(t){case"list":if(n.length!==1)throw new Ss("accounts list takes no arguments");return{kind:"accounts-list"};case"import":return eK(n.slice(1));case"remove":{let i=n[1];if(!i||n.length!==2)throw new Ss("accounts remove requires exactly one <id|email>");return{kind:"accounts-remove",identifier:i}}default:throw new Ss(t===void 0?"accounts requires list, import, or remove":`Unknown accounts command: ${t}`)}}function be(n){let t=n[0];switch(t){case void 0:case"--help":case"-h":return{kind:"help"};case"serve":return oK(n.slice(1));case"login":return wK(n.slice(1));case"accounts":return uK(n.slice(1));default:throw new Ss(`Unknown command: ${t}`)}}import{Database as yK}from"bun:sqlite";import{homedir as dK}from"os";import{join as M2}from"path";var AK=d.object({id:d.string().min(1),email:d.string().min(1),auth_method:d.string(),region:d.string(),oidc_region:d.string().nullable(),client_id:d.string().nullable(),client_secret:d.string().nullable(),profile_arn:d.string().nullable(),start_url:d.string().nullable(),refresh_token:d.string(),access_token:d.string(),expires_at:d.number(),rate_limit_reset:d.number().nullable(),is_healthy:d.number().nullable(),unhealthy_reason:d.string().nullable(),recovery_time:d.number().nullable(),fail_count:d.number().nullable(),last_used:d.number().nullable(),used_count:d.number().nullable(),limit_count:d.number().nullable(),last_sync:d.number().nullable(),overage_count:d.number().nullable()});function RK(n=process.env){let t=n.XDG_CONFIG_HOME??M2(dK(),".config");return M2(t,"opencode","kiro.db")}function Nt(n){return n===null||n===""?void 0:n}function MK(n){if(!n.refresh_token)return{kind:"skipped",reason:"missing refresh token"};if(!n.access_token)return{kind:"skipped",reason:"missing access token"};let t=Qi.safeParse(n.region);if(!t.success)return{kind:"skipped",reason:"missing or unsupported region"};if(n.auth_method!=="idc"&&n.auth_method!=="desktop")return{kind:"skipped",reason:"unsupported auth method"};if(n.auth_method==="idc"&&(!n.client_id||!n.client_secret))return{kind:"skipped",reason:"IDC client credentials missing"};let i=Nt(n.oidc_region),r=i===void 0?void 0:Qi.safeParse(i);if(r!==void 0&&!r.success)return{kind:"skipped",reason:"unsupported OIDC region"};return{kind:"usable",account:{id:n.id,email:n.email,authMethod:n.auth_method,region:t.data,...r?.success?{oidcRegion:r.data}:{},...Nt(n.client_id)?{clientId:Nt(n.client_id)}:{},...Nt(n.client_secret)?{clientSecret:Nt(n.client_secret)}:{},...Nt(n.profile_arn)?{profileArn:Nt(n.profile_arn)}:{},...Nt(n.start_url)?{startUrl:Nt(n.start_url)}:{},refreshToken:n.refresh_token,accessToken:n.access_token,expiresAt:n.expires_at,rateLimitResetTime:n.rate_limit_reset??0,isHealthy:n.is_healthy!==0,...Nt(n.unhealthy_reason)?{unhealthyReason:Nt(n.unhealthy_reason)}:{},...n.recovery_time===null?{}:{recoveryTime:n.recovery_time},failCount:n.fail_count??0,lastUsed:n.last_used??0,usedCount:n.used_count??0,limitCount:n.limit_count??0,lastSync:n.last_sync??0,overageCount:n.overage_count??0}}}function E2(n,t){let i=n.from??RK(),r=new yK(i,{readonly:!0,strict:!0}),s=0,f=0;try{let _=r.query(`SELECT
|
|
281
327
|
id, email, auth_method, region, oidc_region, client_id, client_secret,
|
|
282
328
|
profile_arn, start_url, refresh_token, access_token, expires_at,
|
|
283
329
|
rate_limit_reset, is_healthy, unhealthy_reason, recovery_time, fail_count,
|
|
284
330
|
last_used, used_count, limit_count, last_sync, overage_count
|
|
285
|
-
FROM accounts`).all();for(let
|
|
286
|
-
${
|
|
331
|
+
FROM accounts`).all();for(let c of _){let o=AK.safeParse(c);if(!o.success){f+=1,t.stdout("Skipped malformed source account row");continue}let w=MK(o.data);if(w.kind==="skipped"){f+=1,t.stdout(`Skipped ${o.data.email}: ${w.reason}`);continue}t.database.insertAccount(w.account),s+=1,t.stdout(`Imported ${w.account.email} ${w.account.authMethod} ${w.account.region}`)}}finally{r.close()}let h=t.database.getAccounts().length;return t.stdout(`Imported ${s}, skipped ${f}, total in DB now ${h}`),{imported:s,skipped:f,total:h}}import{createHash as SK}from"crypto";var EK=d.object({clientId:d.string().min(1),clientSecret:d.string().min(1)}),TK=d.object({verificationUri:d.string().min(1),verificationUriComplete:d.string().min(1),userCode:d.string().min(1),deviceCode:d.string().min(1),interval:d.number().positive().default(5),expiresIn:d.number().positive().default(600)}),gK=d.object({error:d.string().optional(),error_description:d.string().optional(),access_token:d.string().optional(),accessToken:d.string().optional(),refresh_token:d.string().optional(),refreshToken:d.string().optional(),expires_in:d.number().optional(),expiresIn:d.number().optional()}).passthrough();class nt extends Error{constructor(n,t){super(n,t);this.name="KiroIDCError"}}async function Ne(n){try{return await n.text()}catch(t){if(t instanceof Error)return"";throw t}}async function T2(n,t,i){let r=Q0(n),s=Cs(Ks.SSO_OIDC_ENDPOINT,r),f=t??Ks.BUILDER_ID_START_URL,h=await fetch(`${s}/client/register`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":Hn.USER_AGENT},body:JSON.stringify({clientName:"Kiro IDE",clientType:"public",scopes:Ks.SCOPES,grantTypes:["urn:ietf:params:oauth:grant-type:device_code","refresh_token"]}),...i?{proxy:i}:{}});if(!h.ok)throw new nt(`Client registration failed: ${h.status} ${await Ne(h)}`);let _=EK.safeParse(await h.json());if(!_.success)throw new nt("Client registration response missing clientId or clientSecret",{cause:_.error});let c=await fetch(`${s}/device_authorization`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":Hn.USER_AGENT},body:JSON.stringify({clientId:_.data.clientId,clientSecret:_.data.clientSecret,startUrl:f}),...i?{proxy:i}:{}});if(!c.ok)throw new nt(`Device authorization failed: ${c.status} ${await Ne(c)}`);let o=TK.safeParse(await c.json());if(!o.success)throw new nt("Device authorization response missing required fields",{cause:o.error});return{verificationUrl:o.data.verificationUri,verificationUriComplete:o.data.verificationUriComplete,userCode:o.data.userCode,deviceCode:o.data.deviceCode,clientId:_.data.clientId,clientSecret:_.data.clientSecret,interval:o.data.interval,expiresIn:o.data.expiresIn,region:r,startUrl:f}}async function g2(n,t,i,r,s,f,h=(c)=>new Promise((o)=>setTimeout(o,c)),_){if(!n||!t||!i)throw new nt("Missing required parameters for token polling");let c=Q0(f),o=Cs(Ks.SSO_OIDC_ENDPOINT,c),w=Math.floor(s/r),e=r*1000;for(let u=1;u<=w;u+=1){await h(e);let y=await fetch(`${o}/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":Hn.USER_AGENT},body:JSON.stringify({clientId:n,clientSecret:t,deviceCode:i,grantType:"urn:ietf:params:oauth:grant-type:device_code"}),..._?{proxy:_}:{}}),A=await Ne(y),R={};if(A)try{R=JSON.parse(A)}catch(S){throw new nt(`Token polling failed: invalid JSON response (HTTP ${y.status})`,{cause:S})}let M=gK.safeParse(R);if(!M.success)throw new nt(`Token polling failed: invalid response (HTTP ${y.status})`,{cause:M.error});let E=M.data;switch(E.error){case void 0:break;case"authorization_pending":continue;case"slow_down":e+=5000;continue;case"expired_token":throw new nt("Device code has expired. Please restart the authorization process.");case"access_denied":throw new nt("Authorization was denied by the user.");default:throw new nt(`Token polling failed: ${E.error} - ${E.error_description??""}`)}let g=E.access_token??E.accessToken,T=E.refresh_token??E.refreshToken;if(g&&T)return{refreshToken:T,accessToken:g,expiresAt:Date.now()+(E.expires_in??E.expiresIn??3600)*1000,email:"builder-id@aws.amazon.com",clientId:n,clientSecret:t,region:c,authMethod:"idc"};if(!y.ok)throw new nt(`Token request failed with status: ${y.status}`);throw new nt("Token polling failed: response did not contain tokens")}throw new nt("Token polling timed out. Authorization may have expired.")}function LK(n){if(n===void 0||n.trim()==="")return;let t=new URL(n.trim());return t.hash="",t.search="",t.pathname=`${t.pathname.replace(/\/start\/?$/,"").replace(/\/+$/,"")}/start`,t.toString()}function $K(n,t){return SK("sha256").update(`${n}:idc:${t}:`).digest("hex")}async function S2(n,t={},i={}){let r=i.authorize??T2,s=i.poll??g2,f=i.stdout??console.log,h=LK(t.startUrl),_=Qi.parse(t.region??n.default_region),c=Qr(n),o=await r(_,h,c);f(`Open this URL to sign in:
|
|
332
|
+
${o.verificationUriComplete}`);let w=await s(o.clientId,o.clientSecret,o.deviceCode,o.interval,o.expiresIn,_,void 0,c),e={id:$K(w.email,w.clientId),email:w.email,authMethod:"idc",region:_,oidcRegion:_,clientId:w.clientId,clientSecret:w.clientSecret,...h?{startUrl:h}:{},refreshToken:w.refreshToken,accessToken:w.accessToken,expiresAt:w.expiresAt,rateLimitResetTime:0,isHealthy:!0,failCount:0,usedCount:0,limitCount:0},u=i.openDb?.(Mi)??new qi(Mi);try{u.insertAccount(e)}finally{u.close()}f(`Login successful: ${e.email}`)}function OK(n){let t=n.isHealthy?"healthy":"unhealthy";return`${n.email} ${n.region} ${t} generation=${n.generation} used=${n.usedCount??0}/${n.limitCount??0}`}var UK={loadConfig:ke,startServer:R2,runLogin:S2,runImportAccounts:E2,openDb:(n)=>new qi(n),stdout:console.log,stderr:console.error};async function bK(n,t){switch(n.kind){case"help":return t.stdout(o0),0;case"serve":{let i={...n.host?{host:n.host}:{},...n.port!==void 0?{port:n.port}:{},...n.proxy!==void 0?{proxy_url:n.proxy}:{}},r=t.loadConfig({...n.configPath?{configPath:n.configPath}:{},overrides:i});if(r.test_upstream_endpoint)t.stderr(`WARNING: test_upstream_endpoint is set (${r.test_upstream_endpoint}); routing upstream to a NON-production endpoint. Unset it for normal use.`);let s=t.startServer(r);return t.stdout(`Listening on http://${s.hostname??r.host}:${s.port??r.port}`),0}case"login":{let i=t.loadConfig({...n.configPath?{configPath:n.configPath}:{}});if(i.auth_source==="opencode-shared")return t.stderr(`auth_source=opencode-shared uses ${i.opencode_auth_db_path??$s()} as the authentication authority. Run "opencode auth login" and select Kiro, or set auth_source to "local" before using kiro-provider login.`),1;return await t.runLogin(i,{...n.startUrl?{startUrl:n.startUrl}:{},...n.region?{region:n.region}:{}}),0}case"accounts-list":{let i=t.openDb(Mi);try{for(let r of i.getAccounts())t.stdout(OK(r))}finally{i.close()}return 0}case"accounts-import":{let i=t.openDb(Mi);try{t.runImportAccounts({...n.from?{from:n.from}:{}},{database:i,stdout:t.stdout}),t.stderr("WARNING: accounts import creates a snapshot; it does not share refresh-token state with opencode-kiro-auth.")}finally{i.close()}return 0}case"accounts-remove":{let i=t.openDb(Mi);try{let r=i.getAccounts().find((s)=>s.id===n.identifier||s.email===n.identifier);if(!r)return t.stderr(`Account not found: ${n.identifier}`),1;i.removeAccount(r.id),t.stdout(`Removed account ${r.email}`)}finally{i.close()}return 0}}}async function L2(n=process.argv.slice(2),t=UK){let i;try{i=be(n)}catch(r){return t.stderr(r instanceof Error?r.message:String(r)),t.stderr(o0),1}try{return await bK(i,t)}catch(r){return t.stderr(r instanceof Error?r.message:String(r)),1}}process.exitCode=await L2();
|