@sunerpy/kiro-provider 0.3.1 → 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 +457 -24
- package/dist/cli.js +260 -99
- package/package.json +5 -3
package/dist/cli.js
CHANGED
|
@@ -1,62 +1,130 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
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(`
|
|
4
5
|
`).join(`
|
|
5
|
-
`+
|
|
6
|
-
`)}function
|
|
7
|
-
`).map((
|
|
8
|
-
Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(w){if(!s.logger||s.logger?.constructor?.name==="NoOpLogger")console.warn("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.");else s.logger?.warn?.("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.")}if(typeof l.$responseBodyText<"u"){if(l.$response)l.$response.body=l.$responseBodyText}try{if(Qb.isInstance(r)){let{headers:w={},statusCode:A}=r,M=Object.entries(w);l.$metadata={httpStatusCode:A,requestId:lf(/^x-[\w-]+-request-?id$/,M),extendedRequestId:lf(/^x-[\w-]+-id-2$/,M),cfId:lf(/^x-[\w-]+-cf-id$/,M)}}}catch(w){}}throw l}},lf=(t,n)=>{return(n.find(([s])=>{return s.match(t)})||[void 0,void 0])[1]},zb=(t)=>(n,s)=>async(i)=>{let{operationSchema:r}=lu(s),[,e,f,o,c,h]=r??[],u=s.endpointV2?async()=>Jb(s.endpointV2):t.endpoint,l=await t.protocol.serializeRequest(wf(e,f,o,c,h),i.input,{...t,...s,endpoint:u});return n({...i,request:l})},_u={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},wu={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function Xb(t){return{applyToStack:(n)=>{n.add(zb(t),wu),n.add(kb(t),_u),t.protocol.setSerdeContext(t)}}}class Tt{name;namespace;traits;static assign(t,n){return Object.assign(t,n)}static[Symbol.hasInstance](t){let n=this.prototype.isPrototypeOf(t);if(!n&&typeof t==="object"&&t!==null)return t.symbol===this.symbol;return n}getName(){return this.namespace+"#"+this.name}}class qr extends Tt{static symbol=Symbol.for("@smithy/lis");name;traits;valueSchema;symbol=qr.symbol}var xb=(t,n,s,i)=>Tt.assign(new qr,{name:n,namespace:t,traits:s,valueSchema:i});class Cr extends Tt{static symbol=Symbol.for("@smithy/map");name;traits;keySchema;valueSchema;symbol=Cr.symbol}var qb=(t,n,s,i,r)=>Tt.assign(new Cr,{name:n,namespace:t,traits:s,keySchema:i,valueSchema:r});class Kr extends Tt{static symbol=Symbol.for("@smithy/ope");name;traits;input;output;symbol=Kr.symbol}var Cb=(t,n,s,i,r)=>Tt.assign(new Kr,{name:n,namespace:t,traits:s,input:i,output:r});class Ni extends Tt{static symbol=Symbol.for("@smithy/str");name;traits;memberNames;memberList;symbol=Ni.symbol}var Kb=(t,n,s,i,r)=>Tt.assign(new Ni,{name:n,namespace:t,traits:s,memberNames:i,memberList:r});class Vr extends Ni{static symbol=Symbol.for("@smithy/err");ctor;symbol=Vr.symbol}var Vb=(t,n,s,i,r,e)=>Tt.assign(new Vr,{name:n,namespace:t,traits:s,memberNames:i,memberList:r,ctor:null}),zr=[];function Pi(t){if(typeof t==="object")return t;if(t=t|0,zr[t])return zr[t];let n={},s=0;for(let i of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])if((t>>s++&1)===1)n[i]=1;return zr[t]=n}var Fi={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},Xr=[],xr={};class En{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=En.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(t,n){this.ref=t,this.memberName=n;let s=[],i=t,r=t;this._isMemberSchema=!1;while(_f(i))s.push(i[1]),i=i[0],r=kr(i),this._isMemberSchema=!0;if(s.length>0){this.memberTraits={};for(let e=s.length-1;e>=0;--e){let f=s[e];Object.assign(this.memberTraits,Pi(f))}}else this.memberTraits=0;if(r instanceof En){let e=this.memberTraits;Object.assign(this,r),this.memberTraits=Object.assign({},e,r.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=n??r.memberName;return}if(this.schema=kr(r),Au(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&&!n)throw Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](t){let n=this.prototype.isPrototypeOf(t);if(!n&&typeof t==="object"&&t!==null)return t.symbol===this.symbol;return n}static of(t){let n=typeof t==="function"||typeof t==="object"&&t!==null;if(typeof t==="number"){if(Xr[t])return Xr[t]}else if(typeof t==="string"){if(xr[t])return xr[t]}else if(n){if(t[Fi.ns])return t[Fi.ns]}let s=kr(t);if(s instanceof En)return s;if(_f(s)){let[r,e]=s;if(r instanceof En)return Object.assign(r.getMergedTraits(),Pi(e)),r;throw Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(t,null,2)}.`)}let i=new En(s);if(n)return t[Fi.ns]=i;if(typeof s==="string")return xr[s]=i;if(typeof s==="number")return Xr[s]=i;return i}getSchema(){let t=this.schema;if(Array.isArray(t)&&t[0]===0)return t[4];return t}getName(t=!1){let{name:n}=this;return!t&&n&&n.includes("#")?n.split("#")[1]:n||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){let t=this.getSchema();return typeof t==="number"?t>=64&&t<128:t[0]===1}isMapSchema(){let t=this.getSchema();return typeof t==="number"?t>=128&&t<=255:t[0]===2}isStructSchema(){let t=this.getSchema();if(typeof t!=="object")return!1;let n=t[0];return n===3||n===-3||n===4}isUnionSchema(){let t=this.getSchema();if(typeof t!=="object")return!1;return t[0]===4}isBlobSchema(){let t=this.getSchema();return t===21||t===42}isTimestampSchema(){let t=this.getSchema();return typeof t==="number"&&t>=4&&t<=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:t}=this.getMergedTraits();return!!t||this.getSchema()===42}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return Pi(this.memberTraits)}getOwnTraits(){return Pi(this.traits)}getKeySchema(){let[t,n]=[this.isDocumentSchema(),this.isMapSchema()];if(!t&&!n)throw Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);let s=this.getSchema(),i=t?15:s[4]??0;return Hi([i,0],"key")}getValueSchema(){let t=this.getSchema(),[n,s,i]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],r=typeof t==="number"?63&t:t&&typeof t==="object"&&(s||i)?t[3+t[0]]:n?15:void 0;if(r!=null)return Hi([r,0],s?"value":"member");throw Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(t){let n=this.getSchema();if(this.isStructSchema()&&n[4].includes(t)){let s=n[4].indexOf(t),i=n[5][s];return Hi(_f(i)?i:[i,0],t)}if(this.isDocumentSchema())return Hi([15,0],t);throw Error(`@smithy/core/schema - ${this.getName(!0)} has no member=${t}.`)}getMemberSchemas(){let t={};try{for(let[n,s]of this.structIterator())t[n]=s}catch(n){}return t}getEventStreamMember(){if(this.isStructSchema()){for(let[t,n]of this.structIterator())if(n.isStreaming()&&n.isStructSchema())return t}return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw Error("@smithy/core/schema - cannot iterate non-struct schema.");let t=this.getSchema(),n=t[4].length,s=t[Fi.it];if(s&&n===s.length){yield*s;return}s=Array(n);for(let i=0;i<n;++i){let r=t[4][i],e=Hi([t[5][i],0],r);yield s[i]=[r,e]}t[Fi.it]=s}}function Hi(t,n){if(t instanceof En)return Object.assign(t,{memberName:n,_isMemberSchema:!0});return new En(t,n)}var _f=(t)=>Array.isArray(t)&&t.length===2,Au=(t)=>Array.isArray(t)&&t.length>=5;class Wi extends Tt{static symbol=Symbol.for("@smithy/sim");name;schemaRef;traits;symbol=Wi.symbol}var jb=(t,n,s,i)=>Tt.assign(new Wi,{name:n,namespace:t,traits:i,schemaRef:s}),ab=(t,n,s,i)=>Tt.assign(new Wi,{name:n,namespace:t,traits:s,schemaRef:i}),pb={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 dn{namespace;schemas;exceptions;static registries=new Map;constructor(t,n=new Map,s=new Map){this.namespace=t,this.schemas=n,this.exceptions=s}static for(t){if(!dn.registries.has(t))dn.registries.set(t,new dn(t));return dn.registries.get(t)}copyFrom(t){let{schemas:n,exceptions:s}=this;for(let[i,r]of t.schemas)if(!n.has(i))n.set(i,r);for(let[i,r]of t.exceptions)if(!s.has(i))s.set(i,r)}register(t,n){let s=this.normalizeShapeId(t);for(let i of[this,dn.for(s.split("#")[0])])i.schemas.set(s,n)}getSchema(t){let n=this.normalizeShapeId(t);if(!this.schemas.has(n)){if(!t.includes("#")){let s="#"+t,i=[];for(let[r,e]of this.schemas.entries())if(r.endsWith(s))i.push(e);if(i.length===1)return i[0]}throw Error(`@smithy/core/schema - schema not found for ${n}`)}return this.schemas.get(n)}registerError(t,n){let s=t,i=s[1];for(let r of[this,dn.for(i)])r.schemas.set(i+"#"+s[2],s),r.exceptions.set(s,n)}getErrorCtor(t){let n=t;if(this.exceptions.has(n))return this.exceptions.get(n);return dn.for(n[1]).exceptions.get(n)}getBaseException(){for(let t of this.exceptions.keys())if(Array.isArray(t)){let[,n,s]=t,i=n+"#"+s;if(i.startsWith("smithy.ts.sdk.synthetic.")&&i.endsWith("ServiceException"))return t}return}find(t){for(let n of this.schemas.values())if(t(n))return n;return}clear(){this.schemas.clear(),this.exceptions.clear()}normalizeShapeId(t){if(t.includes("#"))return t;return this.namespace+"#"+t}}Zb.ErrorSchema=Vr;Zb.ListSchema=qr;Zb.MapSchema=Cr;Zb.NormalizedSchema=En;Zb.OperationSchema=Kr;Zb.SCHEMA=pb;Zb.Schema=Tt;Zb.SimpleSchema=Wi;Zb.StructureSchema=Ni;Zb.TypeRegistry=dn;Zb.deref=kr;Zb.deserializerMiddlewareOption=_u;Zb.error=Vb;Zb.getSchemaSerdePlugin=Xb;Zb.isStaticSchema=Au;Zb.list=xb;Zb.map=qb;Zb.op=Cb;Zb.operation=wf;Zb.serializerMiddlewareOption=wu;Zb.sim=jb;Zb.simAdapter=ab;Zb.simpleSchemaCacheN=Xr;Zb.simpleSchemaCacheS=xr;Zb.struct=Kb;Zb.traitsCache=zr;Zb.translateTraits=Pi});var Rn=Z((e2)=>{var{getSmithyContext:I4,normalizeProvider:y4}=nn();e2.getSmithyContext=I4;e2.normalizeProvider=y4;var{SMITHY_CONTEXT_KEY:O4,AlgorithmId:ar}=rs();e2.AlgorithmId=ar;var{NormalizedSchema:G4}=Nn(),es=(t,n)=>{let s=[];if(t)s.push(t);if(n)for(let i of n)s.push(i);return s},Wn=(t,n)=>{return`${t||"anonymous"}${n&&n.length>0?` (a.k.a. ${n.join(",")})`:""}`},Di=()=>{let t=[],n=[],s=!1,i=new Set,r=(l)=>l.sort((_,w)=>Mu[w.step]-Mu[_.step]||gu[w.priority||"normal"]-gu[_.priority||"normal"]),e=(l)=>{let _=!1,w=(A)=>{let M=es(A.name,A.aliases);if(M.includes(l)){_=!0;for(let d of M)i.delete(d);return!1}return!0};return t=t.filter(w),n=n.filter(w),_},f=(l)=>{let _=!1,w=(A)=>{if(A.middleware===l){_=!0;for(let M of es(A.name,A.aliases))i.delete(M);return!1}return!0};return t=t.filter(w),n=n.filter(w),_},o=(l)=>{return t.forEach((_)=>{l.add(_.middleware,{..._})}),n.forEach((_)=>{l.addRelativeTo(_.middleware,{..._})}),l.identifyOnResolve?.(u.identifyOnResolve()),l},c=(l)=>{let _=[];return l.before.forEach((w)=>{if(w.before.length===0&&w.after.length===0)_.push(w);else _.push(...c(w))}),_.push(l),l.after.reverse().forEach((w)=>{if(w.before.length===0&&w.after.length===0)_.push(w);else _.push(...c(w))}),_},h=(l=!1)=>{let _=[],w=[],A={};return t.forEach((d)=>{let E={...d,before:[],after:[]};for(let T of es(E.name,E.aliases))A[T]=E;_.push(E)}),n.forEach((d)=>{let E={...d,before:[],after:[]};for(let T of es(E.name,E.aliases))A[T]=E;w.push(E)}),w.forEach((d)=>{if(d.toMiddleware){let E=A[d.toMiddleware];if(E===void 0){if(l)return;throw Error(`${d.toMiddleware} is not found when adding ${Wn(d.name,d.aliases)} middleware ${d.relation} ${d.toMiddleware}`)}if(d.relation==="after")E.after.push(d);if(d.relation==="before")E.before.push(d)}}),r(_).map(c).reduce((d,E)=>{return d.push(...E),d},[])},u={add:(l,_={})=>{let{name:w,override:A,aliases:M}=_,d={step:"initialize",priority:"normal",middleware:l,..._},E=es(w,M);if(E.length>0){if(E.some((T)=>i.has(T))){if(!A)throw Error(`Duplicate middleware name '${Wn(w,M)}'`);for(let T of E){let U=t.findIndex((y)=>y.name===T||y.aliases?.some((D)=>D===T));if(U===-1)continue;let S=t[U];if(S.step!==d.step||d.priority!==S.priority)throw Error(`"${Wn(S.name,S.aliases)}" middleware with ${S.priority} priority in ${S.step} step cannot be overridden by "${Wn(w,M)}" middleware with ${d.priority} priority in ${d.step} step.`);t.splice(U,1)}}for(let T of E)i.add(T)}t.push(d)},addRelativeTo:(l,_)=>{let{name:w,override:A,aliases:M}=_,d={middleware:l,..._},E=es(w,M);if(E.length>0){if(E.some((T)=>i.has(T))){if(!A)throw Error(`Duplicate middleware name '${Wn(w,M)}'`);for(let T of E){let U=n.findIndex((y)=>y.name===T||y.aliases?.some((D)=>D===T));if(U===-1)continue;let S=n[U];if(S.toMiddleware!==d.toMiddleware||S.relation!==d.relation)throw Error(`"${Wn(S.name,S.aliases)}" middleware ${S.relation} "${S.toMiddleware}" middleware cannot be overridden by "${Wn(w,M)}" middleware ${d.relation} "${d.toMiddleware}" middleware.`);n.splice(U,1)}}for(let T of E)i.add(T)}n.push(d)},clone:()=>o(Di()),use:(l)=>{l.applyToStack(u)},remove:(l)=>{if(typeof l==="string")return e(l);else return f(l)},removeByTag:(l)=>{let _=!1,w=(A)=>{let{tags:M,name:d,aliases:E}=A;if(M&&M.includes(l)){let T=es(d,E);for(let U of T)i.delete(U);return _=!0,!1}return!0};return t=t.filter(w),n=n.filter(w),_},concat:(l)=>{let _=o(Di());return _.use(l),_.identifyOnResolve(s||_.identifyOnResolve()||(l.identifyOnResolve?.()??!1)),_},applyToStack:o,identify:()=>{return h(!0).map((l)=>{let _=l.step??l.relation+" "+l.toMiddleware;return Wn(l.name,l.aliases)+" - "+_})},identifyOnResolve(l){if(typeof l==="boolean")s=l;return s},resolve:(l,_)=>{for(let w of h().map((A)=>A.middleware).reverse())l=w(l,_);if(s)console.log(u.identify());return l}};return u},Mu={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},gu={high:3,normal:2,low:1},B4=(t)=>()=>{throw Error(t)},F4=(t)=>()=>Promise.reject(t),jr=()=>{let t=new WeakSet;return(n,s)=>{if(typeof s==="object"&&s!==null){if(t.has(s))return"[Circular]";t.add(s)}return s}},H4=(t)=>{return new Promise((n)=>setTimeout(n,t*1000))},Ru={minDelay:2,maxDelay:120},sn;(function(t){t.ABORTED="ABORTED",t.FAILURE="FAILURE",t.SUCCESS="SUCCESS",t.RETRY="RETRY",t.TIMEOUT="TIMEOUT"})(sn||(sn={}));var P4=(t)=>{if(t.state===sn.ABORTED){let n=Error(`${JSON.stringify({...t,reason:"Request was aborted"},jr())}`);throw n.name="AbortError",n}else if(t.state===sn.TIMEOUT){let n=Error(`${JSON.stringify({...t,reason:"Waiter has timed out"},jr())}`);throw n.name="TimeoutError",n}else if(t.state!==sn.SUCCESS)throw Error(`${JSON.stringify(t,jr())}`);return t},N4=async({minDelay:t,maxDelay:n,maxWaitTime:s,abortController:i,client:r,abortSignal:e},f,o)=>{let c={},[h,u]=[t*1000,n*1000],l=0,_=Date.now()+s*1000,w=Date.now()+60000,A=!1;while(!0){if(l>0){let E=m4(h,u,l,_);if(i?.signal?.aborted||e?.aborted)return c["AbortController signal aborted."]|=0,c["AbortController signal aborted."]+=1,{state:sn.ABORTED,observedResponses:c};if(Date.now()+E>_)return{state:sn.TIMEOUT,observedResponses:c};await H4(E/1000)}let{state:M,reason:d}=await o(r,f);if(d){let E=D4(d);c[E]|=0,c[E]+=1}if(M!==sn.RETRY)return{state:M,reason:d,final:d,observedResponses:c};if(l+=1,!A&&Date.now()>=w)W4(c,r),A=!0}},W4=(t={},n)=>{let s=Object.keys(t),i=0;for(let f of s){let o=t[f]|0;if(f.startsWith("403:"))i+=o}let r=n?.config?.logger,e=typeof r?.warn==="function"&&!r.constructor?.name?.includes?.("NoOpLogger")?r:console;if(i>=3||s[s.length-1]?.startsWith("403:"))e.warn("@smithy/util-waiter WARN - 403 status code encountered during waiter polling.")},D4=(t)=>{let n=t?.$response?.statusCode??t?.$metadata?.httpStatusCode;if(t?.$responseBodyText)return`${n?n+": ":""}Deserialization error for body: ${t.$responseBodyText}`;if(n){if(t?.$response||t?.message)return`${n??"Unknown"}: ${t?.message}`;return`${n}: OK`}return String(t?.message??JSON.stringify(t,jr())??"Unknown")},m4=(t,n,s,i)=>{let r=Math.log(n/t)/Math.log(2)+1;if(s>r)return n;let e=t*2**(s-1),f=Math.min(e,n),o=Y4(t,f);if(Date.now()+o>i){let c=i-Date.now();return Math.max(0,c-500)}return o},Y4=(t,n)=>t+Math.random()*(n-t),Q4=(t)=>{if(t.maxWaitTime<=0)throw Error("WaiterConfiguration.maxWaitTime must be greater than 0");else if(t.minDelay<=0)throw Error("WaiterConfiguration.minDelay must be greater than 0");else if(t.maxDelay<=0)throw Error("WaiterConfiguration.maxDelay must be greater than 0");else if(t.maxWaitTime<=t.minDelay)throw Error(`WaiterConfiguration.maxWaitTime [${t.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${t.minDelay}] for this waiter`);else if(t.maxDelay<t.minDelay)throw Error(`WaiterConfiguration.maxDelay [${t.maxDelay}] must be greater than WaiterConfiguration.minDelay [${t.minDelay}] for this waiter`)},du=(t)=>{let n,s=new Promise((i)=>{if(n=()=>i({state:sn.ABORTED}),typeof t.addEventListener==="function")t.addEventListener("abort",n);else t.onabort=n});return{clearListener(){if(typeof t.removeEventListener==="function")t.removeEventListener("abort",n)},aborted:s}},J4=async(t,n,s)=>{let i={...Ru,...t};Q4(i);let r=[N4(i,n,s)],e=[];if(t.abortSignal){let{aborted:f,clearListener:o}=du(t.abortSignal);e.push(o),r.push(f)}if(t.abortController?.signal){let{aborted:f,clearListener:o}=du(t.abortController.signal);e.push(o),r.push(f)}return Promise.race(r).then((f)=>{for(let o of e)o();return f})};class bu{config;middlewareStack=Di();initConfig;handlers;constructor(t){this.config=t;let{protocol:n,protocolSettings:s}=t;if(s){if(typeof n==="function")t.protocol=new n(s)}}send(t,n,s){let i=typeof n!=="function"?n:void 0,r=typeof n==="function"?n:s,e=i===void 0&&this.config.cacheMiddleware===!0,f;if(e){if(!this.handlers)this.handlers=new WeakMap;let o=this.handlers;if(o.has(t.constructor))f=o.get(t.constructor);else f=t.resolveMiddleware(this.middlewareStack,this.config,i),o.set(t.constructor,f)}else delete this.handlers,f=t.resolveMiddleware(this.middlewareStack,this.config,i);if(r)f(t).then((o)=>r(null,o.output),(o)=>r(o)).catch(()=>{});else return f(t).then((o)=>o.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}var Af="***SensitiveInformation***";function pr(t,n){if(n==null)return n;let s=G4.of(t);if(s.getMergedTraits().sensitive)return Af;if(s.isListSchema()){if(!!s.getValueSchema().getMergedTraits().sensitive)return Af}else if(s.isMapSchema()){if(!!s.getKeySchema().getMergedTraits().sensitive||!!s.getValueSchema().getMergedTraits().sensitive)return Af}else if(s.isStructSchema()&&typeof n==="object"){let i=n,r={};for(let[e,f]of s.structIterator())if(i[e]!=null)r[e]=pr(f,i[e]);return r}return n}class Zr{middlewareStack=Di();schema;static classBuilder(){return new Tu}resolveMiddlewareWithContext(t,n,s,{middlewareFn:i,clientName:r,commandName:e,inputFilterSensitiveLog:f,outputFilterSensitiveLog:o,smithyContext:c,additionalContext:h,CommandCtor:u}){for(let d of i.bind(this)(u,t,n,s))this.middlewareStack.use(d);let l=t.concat(this.middlewareStack),{logger:_}=n,w={logger:_,clientName:r,commandName:e,inputFilterSensitiveLog:f,outputFilterSensitiveLog:o,[O4]:{commandInstance:this,...c},...h},{requestHandler:A}=n,M=s??{};if(c.eventStream)M={isEventStream:!0,...M};return l.resolve((d)=>A.handle(d.request,M),w)}}class Tu{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(t){this._init=t}ep(t){return this._ep=t,this}m(t){return this._middlewareFn=t,this}s(t,n,s={}){return this._smithyContext={service:t,operation:n,...s},this}c(t={}){return this._additionalContext=t,this}n(t,n){return this._clientName=t,this._commandName=n,this}f(t=(s)=>s,n=(s)=>s){return this._inputFilterSensitiveLog=t,this._outputFilterSensitiveLog=n,this}ser(t){return this._serializer=t,this}de(t){return this._deserializer=t,this}sc(t){return this._operationSchema=t,this._smithyContext.operationSchema=t,this}build(){let t=this,n;return n=class extends Zr{input;static getEndpointParameterInstructions(){return t._ep}constructor(...[s]){super();this.input=s??{},t._init(this),this.schema=t._operationSchema}resolveMiddleware(s,i,r){let e=t._operationSchema,f=e?.[4]??e?.input,o=e?.[5]??e?.output;return this.resolveMiddlewareWithContext(s,i,r,{CommandCtor:n,middlewareFn:t._middlewareFn,clientName:t._clientName,commandName:t._commandName,inputFilterSensitiveLog:t._inputFilterSensitiveLog??(e?pr.bind(null,f):(c)=>c),outputFilterSensitiveLog:t._outputFilterSensitiveLog??(e?pr.bind(null,o):(c)=>c),smithyContext:t._smithyContext,additionalContext:t._additionalContext})}serialize=t._serializer;deserialize=t._deserializer}}}var k4="***SensitiveInformation***",z4=(t,n,s)=>{for(let[e,f]of Object.entries(t)){let o=async function(h,u,l){let _=new f(h);if(typeof u==="function")this.send(_,u);else if(typeof l==="function"){if(typeof u!=="object")throw Error(`Expected http options but got ${typeof u}`);this.send(_,u||{},l)}else return this.send(_,u)},c=(e[0].toLowerCase()+e.slice(1)).replace(/Command$/,"");n.prototype[c]=o}let{paginators:i={},waiters:r={}}=s??{};for(let[e,f]of Object.entries(i))if(n.prototype[e]===void 0)n.prototype[e]=function(o={},c,...h){return f({...c,client:this},o,...h)};for(let[e,f]of Object.entries(r))if(n.prototype[e]===void 0)n.prototype[e]=async function(o={},c,...h){let u=c;if(typeof c==="number")u={maxWaitTime:c};return f({...u,client:this},o,...h)}};class Js extends Error{$fault;$response;$retryable;$metadata;constructor(t){super(t.message);Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=t.name,this.$fault=t.$fault,this.$metadata=t.$metadata}static isInstance(t){if(!t)return!1;let n=t;return Js.prototype.isPrototypeOf(n)||Boolean(n.$fault)&&Boolean(n.$metadata)&&(n.$fault==="client"||n.$fault==="server")}static[Symbol.hasInstance](t){if(!t)return!1;let n=t;if(this===Js)return Js.isInstance(t);if(Js.isInstance(t)){if(n.name&&this.name)return this.prototype.isPrototypeOf(t)||n.name===this.name;return this.prototype.isPrototypeOf(t)}return!1}}var Su=(t,n={})=>{Object.entries(n).filter(([,i])=>i!==void 0).forEach(([i,r])=>{if(t[i]==null||t[i]==="")t[i]=r});let s=t.message||t.Message||"UnknownError";return t.message=s,delete t.Message,t},$u=({output:t,parsedBody:n,exceptionCtor:s,errorCode:i})=>{let r=x4(t),e=r.httpStatusCode?r.httpStatusCode+"":void 0,f=new s({name:n?.code||n?.Code||i||e||"UnknownError",$fault:"client",$metadata:r});throw Su(f,n)},X4=(t)=>{return({output:n,parsedBody:s,errorCode:i})=>{$u({output:n,parsedBody:s,exceptionCtor:t,errorCode:i})}},x4=(t)=>({httpStatusCode:t.statusCode,requestId:t.headers["x-amzn-requestid"]??t.headers["x-amzn-request-id"]??t.headers["x-amz-request-id"],extendedRequestId:t.headers["x-amz-id-2"],cfId:t.headers["x-amz-cf-id"]}),q4=(t)=>{switch(t){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{}}},Eu=!1,C4=(t)=>{if(t&&!Eu&&parseInt(t.substring(1,t.indexOf(".")))<16)Eu=!0},Uu=Object.values(ar),Lu=(t)=>{let n=[];for(let s in ar){let i=ar[s];if(t[i]===void 0)continue;n.push({algorithmId:()=>i,checksumConstructor:()=>t[i]})}for(let[s,i]of Object.entries(t.checksumAlgorithms??{}))n.push({algorithmId:()=>s,checksumConstructor:()=>i});return{addChecksumAlgorithm(s){t.checksumAlgorithms=t.checksumAlgorithms??{};let i=s.algorithmId(),r=s.checksumConstructor();if(Uu.includes(i))t.checksumAlgorithms[i.toUpperCase()]=r;else t.checksumAlgorithms[i]=r;n.push(s)},checksumAlgorithms(){return n}}},Iu=(t)=>{let n={};return t.checksumAlgorithms().forEach((s)=>{let i=s.algorithmId();if(Uu.includes(i))n[i]=s.checksumConstructor()}),n},yu=(t)=>{return{setRetryStrategy(n){t.retryStrategy=n},retryStrategy(){return t.retryStrategy}}},Ou=(t)=>{let n={};return n.retryStrategy=t.retryStrategy(),n},Gu=(t)=>{return Object.assign(Lu(t),yu(t))},K4=Gu,V4=(t)=>{return Object.assign(Iu(t),Ou(t))},j4=(t)=>Array.isArray(t)?t:[t],Bu=(t)=>{for(let s in t)if(Object.prototype.hasOwnProperty.call(t,s)&&t[s]["#text"]!==void 0)t[s]=t[s]["#text"];else if(typeof t[s]==="object"&&t[s]!==null)t[s]=Bu(t[s]);return t},a4=(t)=>{return t!=null};class Fu{trace(){}debug(){}info(){}warn(){}error(){}}function Hu(t,n,s){let i,r,e;if(typeof n>"u"&&typeof s>"u")i={},e=t;else if(i=t,typeof n==="function")return r=n,e=s,v4(i,r,e);else e=n;for(let f of Object.keys(e)){if(!Array.isArray(e[f])){i[f]=e[f];continue}Pu(i,null,e,f)}return i}var p4=(t)=>{let n={};for(let[s,i]of Object.entries(t||{}))n[s]=[,i];return n},Z4=(t,n)=>{let s={};for(let i in n)Pu(s,t,n,i);return s},v4=(t,n,s)=>{return Hu(t,Object.entries(s).reduce((i,[r,e])=>{if(Array.isArray(e))i[r]=e;else if(typeof e==="function")i[r]=[n,e()];else i[r]=[n,e];return i},{}))},Pu=(t,n,s,i)=>{if(n!==null){let f=s[i];if(typeof f==="function")f=[,f];let[o=t2,c=n2,h=i]=f;if(typeof o==="function"&&o(n[h])||typeof o!=="function"&&!!o)t[i]=c(n[h]);return}let[r,e]=s[i];if(typeof e==="function"){let f,o=r===void 0&&(f=e())!=null,c=typeof r==="function"&&!!r(void 0)||typeof r!=="function"&&!!r;if(o)t[i]=f;else if(c)t[i]=e()}else{let f=r===void 0&&e!=null,o=typeof r==="function"&&!!r(e)||typeof r!=="function"&&!!r;if(f||o)t[i]=e}},t2=(t)=>t!=null,n2=(t)=>t,s2=(t)=>{if(t!==t)return"NaN";switch(t){case 1/0:return"Infinity";case-1/0:return"-Infinity";default:return t}},i2=(t)=>t.toISOString().replace(".000Z","Z"),Mf=(t)=>{if(t==null)return{};if(Array.isArray(t))return t.filter((n)=>n!=null).map(Mf);if(typeof t==="object"){let n={};for(let s of Object.keys(t)){if(t[s]==null)continue;n[s]=Mf(t[s])}return n}return t};function r2(t,n,s,i){return function(e,f,o,c,h={}){let u=Object.assign({},t,e);return Zr.classBuilder().ep(u).m(function(l,_,w,A){let M=f.call(this,l,_,w,A);return M.unshift(i(w,l.getEndpointParameterInstructions())),M}).s(n,o,h).n(s,o.charAt(0).toUpperCase()+o.slice(1)+"Command").sc(c).build()}}e2.Client=bu;e2.Command=Zr;e2.NoOpLogger=Fu;e2.SENSITIVE_STRING=k4;e2.ServiceException=Js;e2.WaiterState=sn;e2._json=Mf;e2.checkExceptions=P4;e2.constructStack=Di;e2.convertMap=p4;e2.createAggregatedClient=z4;e2.createWaiter=J4;e2.decorateServiceException=Su;e2.emitWarningIfUnsupportedVersion=C4;e2.getArrayIfSingleItem=j4;e2.getChecksumConfiguration=Lu;e2.getDefaultClientConfiguration=K4;e2.getDefaultExtensionConfiguration=Gu;e2.getRetryConfiguration=yu;e2.getValueFromTextNode=Bu;e2.invalidFunction=B4;e2.invalidProvider=F4;e2.isSerializableHeaderValue=a4;e2.loadConfigsForDefaultMode=q4;e2.makeBuilder=r2;e2.map=Hu;e2.resolveChecksumRuntimeConfig=Iu;e2.resolveDefaultRuntimeConfig=V4;e2.resolveRetryRuntimeConfig=Ou;e2.schemaLogFilter=pr;e2.serializeDateTime=i2;e2.serializeFloat=s2;e2.take=Z4;e2.throwDefaultError=$u;e2.waiterServiceDefaults=Ru;e2.withBaseException=X4});var St=Z((qT)=>{var{homedir:q2}=nt("os"),{sep:C2,join:mi}=nt("path"),{createHash:K2}=nt("crypto"),{readFile:zu}=nt("fs/promises"),{IniSectionType:vr}=rs(),{normalizeProvider:te}=Rn(),{isValidHostLabel:V2}=nn();class ks extends Error{name="ProviderError";tryNextLink;constructor(t,n=!0){let s,i=!0;if(typeof n==="boolean")s=void 0,i=n;else if(n!=null&&typeof n==="object")s=n.logger,i=n.tryNextLink??!0;super(t);this.tryNextLink=i,Object.setPrototypeOf(this,ks.prototype),s?.debug?.(`@smithy/property-provider ${i?"->":"(!)"} ${t}`)}static from(t,n=!0){return Object.assign(new this(t.message,n),t)}}class Yi extends ks{name="CredentialsProviderError";constructor(t,n=!0){super(t,n);Object.setPrototypeOf(this,Yi.prototype)}}class bf extends ks{name="TokenProviderError";constructor(t,n=!0){super(t,n);Object.setPrototypeOf(this,bf.prototype)}}var Xu=(...t)=>async()=>{if(t.length===0)throw new ks("No providers in chain");let n;for(let s of t)try{return await s()}catch(i){if(n=i,i?.tryNextLink)continue;throw i}throw n},xu=(t)=>()=>Promise.resolve(t),Tf=(t,n,s)=>{let i,r,e,f=!1,o=async()=>{if(!r)r=t();try{i=await r,e=!0,f=!1}finally{r=void 0}return i};if(n===void 0)return async(c)=>{if(!e||c?.forceRefresh)i=await o();return i};return async(c)=>{if(!e||c?.forceRefresh)i=await o();if(f)return i;if(s&&!s(i))return f=!0,i;if(n(i))return await o(),i;return i}},bn=(t,n,s)=>{if(!(n in t))return;if(t[n]==="true")return!0;if(t[n]==="false")return!1;throw Error(`Cannot load ${s} "${n}". Expected "true" or "false", got ${t[n]}.`)},j2=(t,n,s)=>{if(!(n in t))return;let i=parseInt(t[n],10);if(Number.isNaN(i))throw TypeError(`Cannot load ${s} '${n}'. Expected number, got '${t[n]}'.`);return i},Xt;(function(t){t.ENV="env",t.CONFIG="shared config entry"})(Xt||(Xt={}));var gf={},a2=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},Qi=()=>{let{HOME:t,USERPROFILE:n,HOMEPATH:s,HOMEDRIVE:i=`C:${C2}`}=process.env;if(t)return t;if(n)return n;if(s)return`${i}${s}`;let r=a2();if(!gf[r])gf[r]=q2();return gf[r]},qu="AWS_PROFILE",Cu="default",Ku=(t)=>t.profile||process.env[qu]||Cu,Vu=(t)=>{let s=K2("sha1").update(t).digest("hex");return mi(Qi(),".aws","sso","cache",`${s}.json`)},ne={},p2=async(t)=>{if(ne[t])return ne[t];let n=Vu(t),s=await zu(n,"utf8");return JSON.parse(s)},os=".",Z2=(t)=>Object.entries(t).filter(([n])=>{let s=n.indexOf(os);if(s===-1)return!1;return Object.values(vr).includes(n.substring(0,s))}).reduce((n,[s,i])=>{let r=s.indexOf(os),e=s.substring(0,r)===vr.PROFILE?s.substring(r+1):s;return n[e]=i,n},{...t.default&&{default:t.default}}),v2="AWS_CONFIG_FILE",ju=()=>process.env[v2]||mi(Qi(),".aws","config"),tT="AWS_SHARED_CREDENTIALS_FILE",nT=()=>process.env[tT]||mi(Qi(),".aws","credentials"),sT=/^([\w-]+)\s(["'])?([\w-@+.%:/]+)\2$/,iT=["__proto__","profile __proto__"],Ef=(t)=>{let n={},s,i;for(let r of t.split(/\r?\n/)){let e=r.split(/(^|\s)[;#]/)[0].trim();if(e[0]==="["&&e[e.length-1]==="]"){s=void 0,i=void 0;let o=e.substring(1,e.length-1),c=sT.exec(o);if(c){let[,h,,u]=c;if(Object.values(vr).includes(h))s=[h,u].join(os)}else s=o;if(iT.includes(o))throw Error(`Found invalid profile name "${o}"`)}else if(s){let o=e.indexOf("=");if(![0,-1].includes(o)){let[c,h]=[e.substring(0,o).trim(),e.substring(o+1).trim()];if(h==="")i=c;else{if(i&&r.trimStart()===r)i=void 0;n[s]=n[s]||{};let u=i?[i,c].join(os):c;n[s][u]=h}}}}return n},df={},se={},ie=(t,n)=>{if(se[t]!==void 0)return se[t];if(!df[t]||n?.ignoreCache)df[t]=zu(t,"utf8");return df[t]},Nu=()=>({}),Sf=async(t={})=>{let{filepath:n=nT(),configFilepath:s=ju()}=t,i=Qi(),r="~/",e=n;if(n.startsWith("~/"))e=mi(i,n.slice(2));let f=s;if(s.startsWith("~/"))f=mi(i,s.slice(2));let o=await Promise.all([ie(f,{ignoreCache:t.ignoreCache}).then(Ef).then(Z2).catch(Nu),ie(e,{ignoreCache:t.ignoreCache}).then(Ef).catch(Nu)]);return{configFile:o[0],credentialsFile:o[1]}},rT=(t)=>Object.entries(t).filter(([n])=>n.startsWith(vr.SSO_SESSION+os)).reduce((n,[s,i])=>({...n,[s.substring(s.indexOf(os)+1)]:i}),{}),eT=()=>({}),oT=async(t={})=>ie(t.configFilepath??ju()).then(Ef).then(rT).catch(eT),fT=(...t)=>{let n={};for(let s of t)for(let[i,r]of Object.entries(s))if(n[i]!==void 0)Object.assign(n[i],r);else n[i]=r;return n},cT=async(t)=>{let n=await Sf(t);return fT(n.configFile,n.credentialsFile)},hT={getFileRecord(){return se},interceptFile(t,n){se[t]=Promise.resolve(n)},getTokenRecord(){return ne},interceptToken(t,n){ne[t]=n}};function au(t){try{let n=new Set(Array.from(t.match(/([A-Z_]){3,}/g)??[]));return n.delete("CONFIG"),n.delete("CONFIG_PREFIX_SEPARATOR"),n.delete("ENV"),[...n].join(", ")}catch(n){return t}}var uT=(t,n)=>async()=>{try{let s=t(process.env,n);if(s===void 0)throw Error();return s}catch(s){throw new Yi(s.message||`Not found in ENV: ${au(t.toString())}`,{logger:n?.logger})}},lT=(t,{preferredFile:n="config",...s}={})=>async()=>{let i=Ku(s),{configFile:r,credentialsFile:e}=await Sf(s),f=e[i]||{},o=r[i]||{},c=n==="config"?{...f,...o}:{...o,...f};try{let u=t(c,n==="config"?r:e);if(u===void 0)throw Error();return u}catch(h){throw new Yi(h.message||`Not found in config files w/ profile [${i}]: ${au(t.toString())}`,{logger:s.logger})}},_T=(t)=>typeof t==="function",pu=(t)=>_T(t)?async()=>await t():xu(t),Rf=({environmentVariableSelector:t,configFileSelector:n,default:s},i={})=>{let{signingName:r,logger:e}=i;return Tf(Xu(uT(t,{signingName:r,logger:e}),lT(n,i),pu(s)))},$f="AWS_USE_DUALSTACK_ENDPOINT",Uf="use_dualstack_endpoint",wT=!1,AT={environmentVariableSelector:(t)=>bn(t,$f,Xt.ENV),configFileSelector:(t)=>bn(t,Uf,Xt.CONFIG),default:!1},MT={environmentVariableSelector:(t)=>bn(t,$f,Xt.ENV),configFileSelector:(t)=>bn(t,Uf,Xt.CONFIG),default:void 0},Lf="AWS_USE_FIPS_ENDPOINT",If="use_fips_endpoint",gT=!1,dT={environmentVariableSelector:(t)=>bn(t,Lf,Xt.ENV),configFileSelector:(t)=>bn(t,If,Xt.CONFIG),default:!1},ET={environmentVariableSelector:(t)=>bn(t,Lf,Xt.ENV),configFileSelector:(t)=>bn(t,If,Xt.CONFIG),default:void 0},RT=(t)=>{let{tls:n,endpoint:s,urlParser:i,useDualstackEndpoint:r}=t;return Object.assign(t,{tls:n??!0,endpoint:te(typeof s==="string"?i(s):s),isCustomEndpoint:!0,useDualstackEndpoint:te(r??!1)})},bT=async(t)=>{let{tls:n=!0}=t,s=await t.region();if(!new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/).test(s))throw Error("Invalid region in client config");let r=await t.useDualstackEndpoint(),e=await t.useFipsEndpoint(),{hostname:f}=await t.regionInfoProvider(s,{useDualstackEndpoint:r,useFipsEndpoint:e})??{};if(!f)throw Error("Cannot resolve hostname from client config");return t.urlParser(`${n?"https:":"http:"}//${f}`)},TT=(t)=>{let n=te(t.useDualstackEndpoint??!1),{endpoint:s,useFipsEndpoint:i,urlParser:r,tls:e}=t;return Object.assign(t,{tls:e??!0,endpoint:s?te(typeof s==="string"?r(s):s):()=>bT({...t,useDualstackEndpoint:n,useFipsEndpoint:i}),isCustomEndpoint:!!s,useDualstackEndpoint:n})},ST="AWS_EXECUTION_ENV",Wu="AWS_REGION",Du="AWS_DEFAULT_REGION",$T="AWS_EC2_METADATA_DISABLED",UT=["in-region","cross-region","mobile","standard","legacy"],LT="/latest/meta-data/placement/region",IT="/latest/api/token",yT="x-aws-ec2-metadata-token",OT="x-aws-ec2-metadata-token-ttl-seconds",mu=1000,GT=60000,Zu=0,vu=async()=>{if(process.env[$T])return;if(Date.now()<Zu)return;try{let t=BT(),n=(await Qu({...t,path:IT,method:"PUT",headers:{[OT]:"21600"}})).toString();return(await Qu({...t,path:LT,method:"GET",headers:{[yT]:n}})).toString().trim()||Yu()}catch{return Yu()}},Yu=()=>{Zu=Date.now()+GT;return},BT=()=>{let t=process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT;if(t){let n=new URL(t);return{hostname:n.hostname.replace(/^\[(.+)]$/,"$1"),port:n.port?Number(n.port):void 0}}if(process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE==="IPv6")return{hostname:"fd00:ec2::254"};return{hostname:"169.254.169.254"}},Qu=async(t)=>{let{request:n}=nt("http");return new Promise((s,i)=>{let r=n({hostname:t.hostname,port:t.port,path:t.path,method:t.method,headers:t.headers,timeout:mu,signal:AbortSignal.timeout(mu)});r.on("error",(e)=>{i(e),r.destroy()}),r.on("timeout",()=>{i(Error("TimeoutError from instance metadata service")),r.destroy()}),r.on("response",(e)=>{let{statusCode:f=400}=e;if(f<200||f>=300){i(Object.assign(Error("Error response received from instance metadata service"),{statusCode:f})),r.destroy();return}let o=[];e.on("data",(c)=>o.push(c)),e.on("end",()=>{s(Buffer.concat(o)),r.destroy()})}),r.end()})},tl="AWS_REGION",nl="region",sl={environmentVariableSelector:(t)=>t[tl],configFileSelector:(t)=>t[nl],default:async()=>{let t=await vu();if(t)return t;throw Error("Region is missing")}},FT={preferredFile:"credentials"},Ju=new Set,HT=(t,n=V2)=>{if(!Ju.has(t)&&!n(t))if(t==="*")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="${t}" is not a valid hostname component.`);else Ju.add(t)},il=(t)=>typeof t==="string"&&(t.startsWith("fips-")||t.endsWith("-fips")),PT=(t)=>il(t)?["fips-aws-global","aws-fips"].includes(t)?"us-east-1":t.replace(/fips-(dkr-|prod-)?|-fips/,""):t,NT=(t)=>{let{region:n,useFipsEndpoint:s}=t;if(!n)throw Error("Region is missing");return Object.assign(t,{region:async()=>{let i=typeof n==="function"?await n():n,r=PT(i);return HT(r),r},useFipsEndpoint:async()=>{let i=typeof n==="string"?n:await n();if(il(i))return!0;return typeof s!=="function"?Promise.resolve(!!s):s()}})},ku=(t=[],{useFipsEndpoint:n,useDualstackEndpoint:s})=>t.find(({tags:i})=>n===i.includes("fips")&&s===i.includes("dualstack"))?.hostname,WT=(t,{regionHostname:n,partitionHostname:s})=>n?n:s?s.replace("{region}",t):void 0,DT=(t,{partitionHash:n})=>Object.keys(n||{}).find((s)=>n[s].regions.includes(t))??"aws",mT=(t,{signingRegion:n,regionRegex:s,useFipsEndpoint:i})=>{if(n)return n;else if(i){let r=s.replace("\\\\","\\").replace(/^\^/g,"\\.").replace(/\$$/g,"\\."),e=t.match(r);if(e)return e[0].slice(1,-1)}},YT=(t,{useFipsEndpoint:n=!1,useDualstackEndpoint:s=!1,signingService:i,regionHash:r,partitionHash:e})=>{let f=DT(t,{partitionHash:e}),o=t in r?t:e[f]?.endpoint??t,c={useFipsEndpoint:n,useDualstackEndpoint:s},h=ku(r[o]?.variants,c),u=ku(e[f]?.variants,c),l=WT(o,{regionHostname:h,partitionHostname:u});if(l===void 0)throw Error(`Endpoint resolution failed for: ${{resolvedRegion:o,useFipsEndpoint:n,useDualstackEndpoint:s}}`);let _=mT(l,{signingRegion:r[o]?.signingRegion,regionRegex:e[f].regionRegex,useFipsEndpoint:n});return{partition:f,signingService:i,hostname:l,..._&&{signingRegion:_},...r[o]?.signingService&&{signingService:r[o].signingService}}},QT="AWS_DEFAULTS_MODE",JT="defaults_mode",kT={environmentVariableSelector:(t)=>{return t[QT]},configFileSelector:(t)=>{return t[JT]},default:"legacy"},zT=({region:t=Rf(sl),defaultsMode:n=Rf(kT)}={})=>Tf(async()=>{let s=typeof n==="function"?await n():n;switch(s?.toLowerCase()){case"auto":return XT(t);case"in-region":case"cross-region":case"mobile":case"standard":case"legacy":return Promise.resolve(s?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw Error(`Invalid parameter for "defaultsMode", expect ${UT.join(", ")}, got ${s}`)}}),XT=async(t)=>{if(t){let n=typeof t==="function"?await t():t,s=await xT();if(!s)return"standard";if(n===s)return"in-region";else return"cross-region"}return"standard"},xT=async()=>{if(process.env[ST]&&(process.env[Wu]||process.env[Du]))return process.env[Wu]??process.env[Du];return vu()};qT.CONFIG_PREFIX_SEPARATOR=os;qT.CONFIG_USE_DUALSTACK_ENDPOINT=Uf;qT.CONFIG_USE_FIPS_ENDPOINT=If;qT.CredentialsProviderError=Yi;qT.DEFAULT_PROFILE=Cu;qT.DEFAULT_USE_DUALSTACK_ENDPOINT=wT;qT.DEFAULT_USE_FIPS_ENDPOINT=gT;qT.ENV_PROFILE=qu;qT.ENV_USE_DUALSTACK_ENDPOINT=$f;qT.ENV_USE_FIPS_ENDPOINT=Lf;qT.NODE_REGION_CONFIG_FILE_OPTIONS=FT;qT.NODE_REGION_CONFIG_OPTIONS=sl;qT.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS=AT;qT.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS=dT;qT.ProviderError=ks;qT.REGION_ENV_NAME=tl;qT.REGION_INI_NAME=nl;qT.SelectorType=Xt;qT.TokenProviderError=bf;qT.booleanSelector=bn;qT.chain=Xu;qT.externalDataInterceptor=hT;qT.fromStatic=pu;qT.fromValue=xu;qT.getHomeDir=Qi;qT.getProfileName=Ku;qT.getRegionInfo=YT;qT.getSSOTokenFilepath=Vu;qT.getSSOTokenFromFile=p2;qT.loadConfig=Rf;qT.loadSharedConfigFiles=Sf;qT.loadSsoSessionData=oT;qT.memoize=Tf;qT.nodeDualstackConfigSelectors=MT;qT.nodeFipsConfigSelectors=ET;qT.numberSelector=j2;qT.parseKnownFiles=cT;qT.readFile=ie;qT.resolveCustomEndpointsConfig=RT;qT.resolveDefaultsModeConfig=zT;qT.resolveEndpointsConfig=TT;qT.resolveRegionConfig=NT});var fs=Z((E5)=>{var{CONFIG_PREFIX_SEPARATOR:rl,loadConfig:N6}=St(),{toEndpointV1:re,getSmithyContext:W6,normalizeProvider:yf,isValidHostLabel:fl}=nn();E5.isValidHostLabel=fl;E5.middlewareEndpointToEndpointV1=re;E5.toEndpointV1=re;var{EndpointURLScheme:Bf}=rs(),el="AWS_ENDPOINT_URL",ol="endpoint_url",D6=(t)=>({environmentVariableSelector:(n)=>{let s=t.split(" ").map((e)=>e.toUpperCase()),i=n[[el,...s].join("_")];if(i)return i;let r=n[el];if(r)return r;return},configFileSelector:(n,s)=>{if(s&&n.services){let r=s[["services",n.services].join(rl)];if(r){let e=t.split(" ").map((o)=>o.toLowerCase()),f=r[[e.join("_"),ol].join(rl)];if(f)return f}}let i=n[ol];if(i)return i;return},default:void 0}),ee=async(t)=>N6(D6(t??""))(),m6=async(t)=>{let n=t?.Bucket||"";if(typeof t.Bucket==="string")t.Bucket=n.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"));if(z6(n)){if(t.ForcePathStyle===!0)throw Error("Path-style addressing cannot be used with ARN buckets")}else if(!k6(n)||n.indexOf(".")!==-1&&!String(t.Endpoint).startsWith("http:")||n.toLowerCase()!==n||n.length<3)t.ForcePathStyle=!0;if(t.DisableMultiRegionAccessPoints)t.disableMultiRegionAccessPoints=!0,t.DisableMRAP=!0;return t},Y6=/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/,Q6=/(\d+\.){3}\d+/,J6=/\.\./,k6=(t)=>Y6.test(t)&&!Q6.test(t)&&!J6.test(t),z6=(t)=>{let[n,s,i,,,r]=t.split(":"),e=n==="arn"&&t.split(":").length>=6,f=Boolean(e&&s&&i&&r);if(e&&!f)throw Error(`Invalid ARN: ${t} was an invalid ARN.`);return f},X6=(t,n,s,i=!1)=>{let r=async()=>{let e;if(i)e=s.clientContextParams?.[t]??s[t]??s[n];else e=s[t]??s[n];if(typeof e==="function")return e();return e};if(t==="credentialScope"||n==="CredentialScope")return async()=>{let e=typeof s.credentials==="function"?await s.credentials():s.credentials;return e?.credentialScope??e?.CredentialScope};if(t==="accountId"||n==="AccountId")return async()=>{let e=typeof s.credentials==="function"?await s.credentials():s.credentials;return e?.accountId??e?.AccountId};if(t==="endpoint"||n==="endpoint")return async()=>{if(s.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:c,path:h}=e;return`${f}//${o}${c?":"+c:""}${h}`}}return e};return r};function cl(t){return async(n,s,i,r)=>{if(!i.isCustomEndpoint){let o;if(i.serviceConfiguredEndpoint)o=await i.serviceConfiguredEndpoint();else o=await t(i.serviceId);if(o)i.endpoint=()=>Promise.resolve(re(o)),i.isCustomEndpoint=!0}let e=await hl(n,s,i);if(typeof i.endpointProvider!=="function")throw Error("config.endpointProvider is not set.");let f=i.endpointProvider(e,r);if(i.isCustomEndpoint&&i.endpoint){let o=await i.endpoint();if(o?.headers){f.headers??={};for(let[c,h]of Object.entries(o.headers))f.headers[c]=Array.isArray(h)?h:[h]}}return f}}var hl=async(t,n,s)=>{let i={},r=n?.getEndpointParameterInstructions?.()||{};for(let[e,f]of Object.entries(r))switch(f.type){case"staticContextParams":i[e]=f.value;break;case"contextParams":i[e]=t[f.name];break;case"clientContextParams":case"builtInParams":i[e]=await X6(f.name,e,s,f.type!=="builtInParams")();break;case"operationContextParams":i[e]=f.get(t);break;default:throw Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(f))}if(Object.keys(r).length===0)Object.assign(i,s);if(String(s.serviceId).toLowerCase()==="s3")await m6(i);return i};function x6(t,n,s){if(!t.__smithy_context)t.__smithy_context={features:{}};else if(!t.__smithy_context.features)t.__smithy_context.features={};t.__smithy_context.features[n]=s}function ul(t){let n=cl(t);return({config:s,instructions:i})=>{return(r,e)=>async(f)=>{if(s.isCustomEndpoint)x6(e,"ENDPOINT_OVERRIDE","N");let o=await n(f.input,{getEndpointParameterInstructions(){return i}},{...s},e);e.endpointV2=o,e.authSchemes=o.properties?.authSchemes;let c=e.authSchemes?.[0];if(c){e.signing_region=c.signingRegion,e.signing_service=c.signingName;let u=W6(e)?.selectedHttpAuthScheme?.httpAuthOption;if(u)u.signingProperties=Object.assign(u.signingProperties||{},{signing_region:c.signingRegion,signingRegion:c.signingRegion,signing_service:c.signingName,signingName:c.signingName,signingRegionSet:c.signingRegionSet},c.properties)}return r({...f})}}}var q6={name:"serializerMiddleware"},ll={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:q6.name};function C6(t){let n=ul(t);return(s,i)=>({applyToStack:(r)=>{r.addRelativeTo(n({config:s,instructions:i}),ll)}})}function K6(t){return(n)=>{let s=n.tls??!0,{endpoint:i,useDualstackEndpoint:r,useFipsEndpoint:e}=n,f=i!=null?async()=>re(await yf(i)()):void 0,c=Object.assign(n,{endpoint:f,tls:s,isCustomEndpoint:!!i,useDualstackEndpoint:yf(r??!1),useFipsEndpoint:yf(e??!1)}),h=void 0;return c.serviceConfiguredEndpoint=async()=>{if(n.serviceId&&!h)h=t(n.serviceId);return h},c}}class Ff{nodes;root;conditions;results;constructor(t,n,s,i){this.nodes=t,this.root=n,this.conditions=s,this.results=i}static from(t,n,s,i){return new Ff(t,n,s,i)}}class _l{capacity;data=new Map;parameters=[];constructor({size:t,params:n}){if(this.capacity=t??50,n)this.parameters=n}get(t,n){let s=this.hash(t);if(s===!1)return n();if(!this.data.has(s)){if(this.data.size>this.capacity+10){let i=this.data.keys(),r=0;while(!0){let{value:e,done:f}=i.next();if(this.data.delete(e),f||++r>10)break}}this.data.set(s,n())}return this.data.get(s)}size(){return this.data.size}hash(t){let n="",{parameters:s}=this;if(s.length===0)return!1;for(let i of s){let r=String(t[i]??"");if(r.includes("|;"))return!1;n+=r+"|;"}return n}}class wt extends Error{constructor(t){super(t);this.name="EndpointError"}}var Ji="endpoints";function Dn(t){if(typeof t!=="object"||t==null)return t;if("ref"in t)return`$${Dn(t.ref)}`;if("fn"in t)return`${t.fn}(${(t.argv||[]).map(Dn).join(", ")})`;return JSON.stringify(t,null,2)}var wl={},V6=(t,n)=>t===n;function j6(...t){for(let n of t)if(n!=null)return n;return}var a6=(t)=>{let n=t.split("."),s=[];for(let i of n){let r=i.indexOf("[");if(r!==-1){if(i.indexOf("]")!==i.length-1)throw new wt(`Path: '${t}' does not end with ']'`);let e=i.slice(r+1,-1);if(Number.isNaN(parseInt(e)))throw new wt(`Invalid array index: '${e}' in path: '${t}'`);if(r!==0)s.push(i.slice(0,r));s.push(e)}else s.push(i)}return s},Al=(t,n)=>a6(n).reduce((s,i)=>{if(typeof s!=="object")throw new wt(`Index '${i}' in '${n}' not found in '${JSON.stringify(t)}'`);else if(Array.isArray(s)){let r=parseInt(i);return s[r<0?s.length+r:r]}return s[i]},t),p6=(t)=>t!=null;function Z6(t,n,s){return t?n:s}var v6=(t)=>!t,t5=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}$"),Ml=(t)=>t5.test(t)||t.startsWith("[")&&t.endsWith("]"),Of={[Bf.HTTP]:80,[Bf.HTTPS]:443},n5=(t)=>{let n=(()=>{try{if(t instanceof URL)return t;if(typeof t==="object"&&"hostname"in t){let{hostname:_,port:w,protocol:A="",path:M="",query:d={}}=t,E=new URL(`${A}//${_}${w?`:${w}`:""}${M}`);return E.search=Object.entries(d).map(([T,U])=>`${T}=${U}`).join("&"),E}return new URL(t)}catch(_){return null}})();if(!n)return console.error(`Unable to parse ${JSON.stringify(t)} as a whatwg URL.`),null;let s=n.href,{host:i,hostname:r,pathname:e,protocol:f,search:o}=n;if(o)return null;let c=f.slice(0,-1);if(!Object.values(Bf).includes(c))return null;let h=Ml(r),u=s.includes(`${i}:${Of[c]}`)||typeof t==="string"&&t.includes(`${i}:${Of[c]}`),l=`${i}${u?`:${Of[c]}`:""}`;return{scheme:c,authority:l,path:e,normalizedPath:e.endsWith("/")?e:`${e}/`,isIp:h}};function s5(t,n,s){if(s===1)return[t];if(t==="")return[""];let i=t.split(n);if(s===0)return i;return i.slice(0,s-1).concat(i.slice(1).join(n))}var i5=(t,n)=>t===n,r5=(t,n,s,i)=>{if(t==null||n>=s||t.length<s||/[^\u0000-\u007f]/.test(t))return null;if(!i)return t.substring(n,s);return t.substring(t.length-s,t.length-n)},e5=(t)=>encodeURIComponent(t).replace(/[!*'()]/g,(n)=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`),o5={booleanEquals:V6,coalesce:j6,getAttr:Al,isSet:p6,isValidHostLabel:fl,ite:Z6,not:v6,parseURL:n5,split:s5,stringEquals:i5,substring:r5,uriEncode:e5},gl=(t,n)=>{let s=[],{referenceRecord:i,endpointParams:r}=n,e=0;while(e<t.length){let f=t.indexOf("{",e);if(f===-1){s.push(t.slice(e));break}s.push(t.slice(e,f));let o=t.indexOf("}",f);if(o===-1){s.push(t.slice(f));break}if(t[f+1]==="{"&&t[o+1]==="}")s.push(t.slice(f+1,o)),e=o+2;let c=t.substring(f+1,o);if(c.includes("#")){let[h,u]=c.split("#");s.push(Al(i[h]??r[h],u))}else s.push(i[c]??r[c]);e=o+1}return s.join("")},f5=({ref:t},n)=>{return n.referenceRecord[t]??n.endpointParams[t]},ki=(t,n,s)=>{if(typeof t==="string")return gl(t,s);else if(t.fn)return El.callFunction(t,s);else if(t.ref)return f5(t,s);throw new wt(`'${n}': ${String(t)} is not a string, function or reference.`)},dl=({fn:t,argv:n},s)=>{let i=Array(n.length);for(let f=0;f<i.length;++f){let o=n[f];if(typeof o==="boolean"||typeof o==="number")i[f]=o;else i[f]=El.evaluateExpression(o,"arg",s)}let r=t.indexOf(".");if(r!==-1){let o=wl[t.slice(0,r)]?.[t.slice(r+1)];if(typeof o==="function")return o(...i)}let e=o5[t];if(typeof e==="function")return e(...i);throw Error(`function ${t} not loaded in endpointFunctions.`)},El={evaluateExpression:ki,callFunction:dl},Rl=(t,n)=>{let{assign:s}=t;if(s&&s in n.referenceRecord)throw new wt(`'${s}' is already defined in Reference Record.`);let i=dl(t,n);n.logger?.debug?.(`${Ji} evaluateCondition: ${Dn(t)} = ${Dn(i)}`);let r=i===""?!0:!!i;if(s!=null)return{result:r,toAssign:{name:s,value:i}};return{result:r}},bl=(t,n)=>Object.entries(t??{}).reduce((s,[i,r])=>{return s[i]=r.map((e)=>{let f=ki(e,"Header value entry",n);if(typeof f!=="string")throw new wt(`Header '${i}' value '${f}' is not a string`);return f}),s},{}),Hf=(t,n)=>Object.entries(t).reduce((s,[i,r])=>{return s[i]=Sl.getEndpointProperty(r,n),s},{}),Tl=(t,n)=>{if(Array.isArray(t))return t.map((s)=>Tl(s,n));switch(typeof t){case"string":return gl(t,n);case"object":if(t===null)throw new wt(`Unexpected endpoint property: ${t}`);return Sl.getEndpointProperties(t,n);case"boolean":return t;default:throw new wt(`Unexpected endpoint property type: ${typeof t}`)}},Sl={getEndpointProperty:Tl,getEndpointProperties:Hf},$l=(t,n)=>{let s=ki(t,"Endpoint URL",n);if(typeof s==="string")try{return new URL(s)}catch(i){throw console.error(`Failed to construct URL with ${s}`,i),i}throw new wt(`Endpoint URL must be a string, got ${typeof s}`)},Gf=1e8,c5=(t,n)=>{let{nodes:s,root:i,results:r,conditions:e}=t,f=i,o={},c={referenceRecord:o,endpointParams:n.endpointParams,logger:n.logger};while(f!==1&&f!==-1&&f<Gf){let h=3*(Math.abs(f)-1),[u,l,_]=[s[h],s[h+1],s[h+2]],[w,A,M]=e[u],d=Rl({fn:w,assign:M,argv:A},c);if(d.toAssign){let{name:E,value:T}=d.toAssign;o[E]=T}f=f>=0===d.result?l:_}if(f>=Gf){let h=r[f-Gf];if(h[0]===-1){let[,w]=h;throw new wt(ki(w,"Error",c))}let[u,l,_]=h;return{url:$l(u,c),properties:Hf(l,c),headers:bl(_??{},c)}}throw new wt("No matching endpoint.")},Pf=(t=[],n)=>{let s={},i={...n,referenceRecord:{...n.referenceRecord}},r=!1;for(let e of t){let{result:f,toAssign:o}=Rl(e,i);if(!f)return{result:f};if(o)r=!0,s[o.name]=o.value,i.referenceRecord[o.name]=o.value,n.logger?.debug?.(`${Ji} assign: ${o.name} := ${Dn(o.value)}`)}if(r)return{result:!0,referenceRecord:s};return{result:!0}},h5=(t,n)=>{let{conditions:s,endpoint:i}=t,{result:r,referenceRecord:e}=Pf(s,n);if(!r)return;let f=e?{...n,referenceRecord:{...n.referenceRecord,...e}}:n,{url:o,properties:c,headers:h}=i;n.logger?.debug?.(`${Ji} Resolving endpoint from template: ${Dn(i)}`);let u={url:$l(o,f)};if(h!=null)u.headers=bl(h,f);if(c!=null)u.properties=Hf(c,f);return u},u5=(t,n)=>{let{conditions:s,error:i}=t,{result:r,referenceRecord:e}=Pf(s,n);if(!r)return;let f=e?{...n,referenceRecord:{...n.referenceRecord,...e}}:n;throw new wt(ki(i,"Error",f))},Ul=(t,n)=>{for(let s of t)if(s.type==="endpoint"){let i=h5(s,n);if(i)return i}else if(s.type==="error")u5(s,n);else if(s.type==="tree"){let i=Ll.evaluateTreeRule(s,n);if(i)return i}else throw new wt(`Unknown endpoint rule: ${s}`);throw new wt("Rules evaluation failed")},l5=(t,n)=>{let{conditions:s,rules:i}=t,{result:r,referenceRecord:e}=Pf(s,n);if(!r)return;let f=e?{...n,referenceRecord:{...n.referenceRecord,...e}}:n;return Ll.evaluateRules(i,f)},Ll={evaluateRules:Ul,evaluateTreeRule:l5},_5=(t,n)=>{let{endpointParams:s,logger:i}=n,{parameters:r,rules:e}=t;n.logger?.debug?.(`${Ji} Initial EndpointParams: ${Dn(s)}`);for(let o in r){let c=r[o],h=s[o];if(h==null&&c.default!=null){s[o]=c.default;continue}if(c.required&&h==null)throw new wt(`Missing required parameter: '${o}'`)}let f=Ul(e,{endpointParams:s,logger:i,referenceRecord:{}});return n.logger?.debug?.(`${Ji} Resolved endpoint: ${Dn(f)}`),f},w5=(t)=>{let{endpoint:n}=t;if(n===void 0)t.endpoint=async()=>{throw Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint.")};return t},A5=cl(ee),M5=K6(ee),g5=ul(ee),d5=C6(ee);E5.BinaryDecisionDiagram=Ff;E5.EndpointCache=_l;E5.EndpointError=wt;E5.customEndpointFunctions=wl;E5.decideEndpoint=c5;E5.endpointMiddleware=g5;E5.endpointMiddlewareOptions=ll;E5.getEndpointFromInstructions=A5;E5.getEndpointPlugin=d5;E5.isIpAddress=Ml;E5.resolveEndpoint=_5;E5.resolveEndpointConfig=M5;E5.resolveEndpointRequiredConfig=w5;E5.resolveParams=hl});var $t=Z((uS)=>{var{createHmac:D5,createHash:m5,getRandomValues:Y5}=nt("crypto"),{ReadStream:Q5,lstatSync:J5,fstatSync:k5}=nt("fs"),{HttpResponse:z5}=nn(),{toEndpointV1:X5}=fs(),{Readable:zs,Writable:Pl,PassThrough:Il}=nt("stream"),Nl=(t)=>typeof ArrayBuffer==="function"&&t instanceof ArrayBuffer||Object.prototype.toString.call(t)==="[object ArrayBuffer]",xs=(t,n=0,s=t.byteLength-n)=>{if(!Nl(t))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof t} (${t})`);return Buffer.from(t,n,s)},he=(t,n)=>{if(typeof t!=="string")throw TypeError(`The "input" argument must be of type string. Received type ${typeof t} (${t})`);return n?Buffer.from(t,n):Buffer.from(t)},x5=/^[A-Za-z0-9+/]*={0,2}$/,Wl=(t)=>{if(t.length*3%4!==0)throw TypeError("Incorrect padding on base64 string.");if(!x5.exec(t))throw TypeError("Invalid base64 string.");let n=he(t,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)},ue=(t)=>{let n=he(t,"utf8");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT)},kf=(t)=>{let n;if(typeof t==="string")n=ue(t);else n=t;if(typeof n!=="object"||typeof n.byteOffset!=="number"||typeof n.byteLength!=="number")throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");return xs(n.buffer,n.byteOffset,n.byteLength).toString("base64")};function q5(t,n,s,i){return class r extends Uint8Array{static fromString(e,f="utf-8"){if(typeof e==="string"){if(f==="base64")return r.mutate(i(e));return r.mutate(n(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 s(this);return t(this)}}}var Dl=(t)=>{if(typeof t==="string")return t;if(typeof t!=="object"||typeof t.byteOffset!=="number"||typeof t.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return xs(t.buffer,t.byteOffset,t.byteLength).toString("utf8")},dt=Array.from({length:256},(t,n)=>n.toString(16).padStart(2,"0"));function C5(t){if(typeof crypto<"u"&&typeof crypto.randomUUID==="function")return()=>crypto.randomUUID();return()=>{let n=new Uint8Array(16);return t(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128,dt[n[0]]+dt[n[1]]+dt[n[2]]+dt[n[3]]+"-"+dt[n[4]]+dt[n[5]]+"-"+dt[n[6]]+dt[n[7]]+"-"+dt[n[8]]+dt[n[9]]+"-"+dt[n[10]]+dt[n[11]]+dt[n[12]]+dt[n[13]]+dt[n[14]]+dt[n[15]]}}var K5=(t,n,s=(i)=>i)=>t,V5=(t)=>{switch(t){case"true":return!0;case"false":return!1;default:throw Error(`Unable to parse boolean value "${t}"`)}},j5=(t)=>{if(t===null||t===void 0)return;if(typeof t==="number"){if(t===0||t===1)qi.warn(fe(`Expected boolean, got ${typeof t}: ${t}`));if(t===0)return!1;if(t===1)return!0}if(typeof t==="string"){let n=t.toLowerCase();if(n==="false"||n==="true")qi.warn(fe(`Expected boolean, got ${typeof t}: ${t}`));if(n==="false")return!1;if(n==="true")return!0}if(typeof t==="boolean")return t;throw TypeError(`Expected boolean, got ${typeof t}: ${t}`)},Xi=(t)=>{if(t===null||t===void 0)return;if(typeof t==="string"){let n=parseFloat(t);if(!Number.isNaN(n)){if(String(n)!==String(t))qi.warn(fe(`Expected number but observed string: ${t}`));return n}}if(typeof t==="number")return t;throw TypeError(`Expected number, got ${typeof t}: ${t}`)},a5=Math.ceil(340282346638528860000000000000000000000),oe=(t)=>{let n=Xi(t);if(n!==void 0&&!Number.isNaN(n)&&n!==1/0&&n!==-1/0){if(Math.abs(n)>a5)throw TypeError(`Expected 32-bit float, got ${t}`)}return n},xi=(t)=>{if(t===null||t===void 0)return;if(Number.isInteger(t)&&!Number.isNaN(t))return t;throw TypeError(`Expected integer, got ${typeof t}: ${t}`)},p5=xi,mf=(t)=>zf(t,32),Yf=(t)=>zf(t,16),Qf=(t)=>zf(t,8),zf=(t,n)=>{let s=xi(t);if(s!==void 0&&Z5(s,n)!==s)throw TypeError(`Expected ${n}-bit integer, got ${t}`);return s},Z5=(t,n)=>{switch(n){case 32:return Int32Array.of(t)[0];case 16:return Int16Array.of(t)[0];case 8:return Int8Array.of(t)[0]}},v5=(t,n)=>{if(t===null||t===void 0){if(n)throw TypeError(`Expected a non-null value for ${n}`);throw TypeError("Expected a non-null value")}return t},ml=(t)=>{if(t===null||t===void 0)return;if(typeof t==="object"&&!Array.isArray(t))return t;let n=Array.isArray(t)?"array":typeof t;throw TypeError(`Expected object, got ${n}: ${t}`)},t8=(t)=>{if(t===null||t===void 0)return;if(typeof t==="string")return t;if(["boolean","number","bigint"].includes(typeof t))return qi.warn(fe(`Expected string, got ${typeof t}: ${t}`)),String(t);throw TypeError(`Expected string, got ${typeof t}: ${t}`)},n8=(t)=>{if(t===null||t===void 0)return;let n=ml(t),s=[];for(let i in n)if(n[i]!=null)s.push(i);if(s.length===0)throw TypeError("Unions must have exactly one non-null member. None were found.");if(s.length>1)throw TypeError(`Unions must have exactly one non-null member. Keys ${s} were not null.`);return n},Xf=(t)=>{if(typeof t=="string")return Xi(Ks(t));return Xi(t)},s8=Xf,Yl=(t)=>{if(typeof t=="string")return oe(Ks(t));return oe(t)},i8=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,Ks=(t)=>{let n=t.match(i8);if(n===null||n[0].length!==t.length)throw TypeError("Expected real number, got implicit NaN");return parseFloat(t)},xf=(t)=>{if(typeof t=="string")return Ql(t);return Xi(t)},r8=xf,e8=xf,o8=(t)=>{if(typeof t=="string")return Ql(t);return oe(t)},Ql=(t)=>{switch(t){case"NaN":return NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;default:throw Error(`Unable to parse float value: ${t}`)}},Jl=(t)=>{if(typeof t==="string")return xi(Ks(t));return xi(t)},f8=Jl,c8=(t)=>{if(typeof t==="string")return mf(Ks(t));return mf(t)},qs=(t)=>{if(typeof t==="string")return Yf(Ks(t));return Yf(t)},kl=(t)=>{if(typeof t==="string")return Qf(Ks(t));return Qf(t)},fe=(t)=>{return String(TypeError(t).stack||t).split(`
|
|
9
|
-
`).slice(0,5).filter((
|
|
10
|
-
`)},
|
|
11
|
-
Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(c){if(!
|
|
12
|
-
`),
|
|
13
|
-
`),
|
|
14
|
-
`)}
|
|
15
|
-
${
|
|
16
|
-
`)}})};function
|
|
17
|
-
`),
|
|
18
|
-
`)}),
|
|
19
|
-
`),
|
|
20
|
-
`),
|
|
21
|
-
`)}
|
|
22
|
-
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(t,{transformToByteArray:s,transformToString:async(r)=>{let e=await s();if(r==="base64")return t_(e);else if(r==="hex")return ql(e);else if(r===void 0||r==="utf8"||r==="utf-8")return sS(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(n)throw Error(Bl);if(n=!0,Fl(t))return i(t);else if(en(t))return t;else throw Error(`Cannot transform payload to web stream, got ${t}`)}})},Fl=(t)=>typeof Blob==="function"&&t instanceof Blob,o_=(t)=>{if(we(t))return r_(t);if(en(t))return e_(t);return new Promise((n,s)=>{let i=new f_,r=t;r.pipe(i),r.on("error",(e)=>{i.end(),s(e)}),i.on("error",s),i.on("finish",function(){let e=_e(this.bufferedBytes);n(e)})})};class f_ extends Pl{bufferedBytes=[];_write(t,n,s){this.bufferedBytes.push(t),s()}}var Hl="The stream has already been transformed.",eS=(t)=>{if(!(t instanceof zs))try{return rS(t)}catch(i){let r=t?.__proto__?.constructor?.name||t;throw Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${r}`)}let n=!1,s=async()=>{if(n)throw Error(Hl);return n=!0,await o_(t)};return Object.assign(t,{transformToByteArray:s,transformToString:async(i)=>{let r=await s();if(i===void 0||Buffer.isEncoding(i))return xs(r.buffer,r.byteOffset,r.byteLength).toString(i);else return new TextDecoder(i).decode(r)},transformToWebStream:()=>{if(n)throw Error(Hl);if(t.readableFlowing!==null)throw Error("The stream has been consumed by other callbacks.");if(typeof zs.toWeb!=="function")throw Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");return n=!0,zs.toWeb(t)}})};async function oS(t){if(typeof t.stream==="function")t=t.stream();return t.tee()}async function fS(t){if(en(t)||we(t))return oS(t);let n=new Il,s=new Il;return t.pipe(n),t.pipe(s),[n,s]}class c_ extends q5(Dl,ue,kf,Wl){}var cS=Y5,h_=C5(cS),hS=h_;uS.ChecksumStream=Zl;uS.Hash=pl;uS.LazyJsonString=cs;uS.NumericValue=le;uS.Uint8ArrayBlobAdapter=c_;uS._parseEpochTimestamp=N8;uS._parseRfc3339DateTimeWithOffset=W8;uS._parseRfc7231DateTime=D8;uS.calculateBodyLength=k8;uS.concatBytes=_e;uS.copyDocumentWithTransform=K5;uS.createBufferedReadable=a8;uS.createChecksumStream=V8;uS.dateToUtcString=u8;uS.deserializerMiddleware=Kl;uS.deserializerMiddlewareOption=jl;uS.expectBoolean=j5;uS.expectByte=Qf;uS.expectFloat32=oe;uS.expectInt=p5;uS.expectInt32=mf;uS.expectLong=xi;uS.expectNonNull=v5;uS.expectNumber=Xi;uS.expectObject=ml;uS.expectShort=Yf;uS.expectString=t8;uS.expectUnion=n8;uS.fromArrayBuffer=xs;uS.fromBase64=Wl;uS.fromHex=J8;uS.fromString=he;uS.fromUtf8=ue;uS.generateIdempotencyToken=hS;uS.getAwsChunkedEncodingStream=Z8;uS.getSerdePlugin=z8;uS.handleFloat=r8;uS.headStream=tS;uS.isArrayBuffer=Nl;uS.isBlob=we;uS.isReadableStream=en;uS.limitedParseDouble=xf;uS.limitedParseFloat=e8;uS.limitedParseFloat32=o8;uS.logger=qi;uS.nv=Q8;uS.parseBoolean=V5;uS.parseEpochTimestamp=R8;uS.parseRfc3339DateTime=_8;uS.parseRfc3339DateTimeWithOffset=A8;uS.parseRfc7231DateTime=E8;uS.quoteHeader=O8;uS.sdkStreamMixin=eS;uS.serializerMiddleware=Vl;uS.serializerMiddlewareOption=al;uS.splitEvery=m8;uS.splitHeader=Y8;uS.splitStream=fS;uS.streamCollector=o_;uS.strictParseByte=kl;uS.strictParseDouble=Xf;uS.strictParseFloat=s8;uS.strictParseFloat32=Yl;uS.strictParseInt=f8;uS.strictParseInt32=c8;uS.strictParseLong=Jl;uS.strictParseShort=qs;uS.toBase64=kf;uS.toHex=ql;uS.toUint8Array=Cl;uS.toUtf8=Dl;uS.v4=h_});var tc=Z((p$)=>{var{createReadStream:G$}=nt("fs"),{Writable:B$}=nt("stream"),{toUint8Array:Vs,concatBytes:F$}=$t(),{createHash:Ci,createHmac:H$}=nt("crypto"),u_=nt("zlib");async function M_(t,n,s=1048576){let i=t.size,r=0;while(r<i){let e=t.slice(r,Math.min(i,r+s));n(new Uint8Array(await e.arrayBuffer())),r+=e.size}}var P$=async function(n,s){let i=new n;return await M_(s,(r)=>{i.update(r)}),i.digest()};class pf extends B${hash;constructor(t,n){super(n);this.hash=t}_write(t,n,s){try{this.hash.update(Vs(t))}catch(i){return s(i)}s()}}var N$=(t,n)=>new Promise((s,i)=>{if(!W$(n)){i(Error("Unable to calculate hash for non-file streams."));return}let r=G$(n.path,{start:n.start,end:n.end}),e=new t,f=new pf(e);r.pipe(f),r.on("error",(o)=>{f.end(),i(o)}),f.on("error",i),f.on("finish",function(){e.digest().then(s).catch(i)})}),W$=(t)=>typeof t.path==="string",D$=(t,n)=>{if(n.readableFlowing!==null)throw Error("Unable to calculate hash for flowing readable stream");let s=new t,i=new pf(s);return n.pipe(i),new Promise((r,e)=>{n.on("error",(f)=>{i.end(),e(f)}),i.on("error",e),i.on("finish",()=>{s.digest().then(r).catch(e)})})};class Zf{digestLength=16;state=Uint32Array.from(l_);writeBuffer=new DataView(new ArrayBuffer(64));bufferLength=0;bytesHashed=0;update(t){let n=Vs(t),s=0,i=n.byteLength;this.bytesHashed+=i;while(i>0)if(this.writeBuffer.setUint8(this.bufferLength++,n[s++]),--i,this.bufferLength===64)jf(this.state,this.writeBuffer),this.bufferLength=0}async digest(){let t=Uint32Array.from(this.state),n=new DataView(this.writeBuffer.buffer.slice(0)),s=this.bufferLength,i=this.bytesHashed*8;if(n.setUint8(s++,128),this.bufferLength%64>=56){for(let f=s;f<64;++f)n.setUint8(f,0);jf(t,n),s=0}for(let f=s;f<56;++f)n.setUint8(f,0);n.setUint32(56,i>>>0,!0),n.setUint32(60,Math.floor(i/4294967296),!0),jf(t,n);let r=new Uint8Array(16),e=new DataView(r.buffer);for(let f=0;f<4;++f)e.setUint32(f*4,t[f],!0);return r}reset(){this.state.set(l_),this.writeBuffer=new DataView(new ArrayBuffer(64)),this.bufferLength=0,this.bytesHashed=0}}var l_=[1732584193,4023233417,2562383102,271733878],Yn=4294967295,m$=Uint8Array.of(7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21),Y$=Array.from({length:64},(t,n)=>Math.abs(Math.sin(n+1))*4294967296>>>0);function jf(t,n){let s=t[0],i=t[1],r=t[2],e=t[3];for(let f=0;f<64;++f){let o,c;if(f<16)o=i&r|~i&e,c=f;else if(f<32)o=e&i|r&~e,c=(5*f+1)%16;else if(f<48)o=i^r^e,c=(3*f+5)%16;else o=r^(i|~e),c=7*f%16;let h=n.getUint32(c*4,!0),u=e;e=r,r=i;let l=m$[(f>>4)*4+(f&3)],_=(s+o&Yn)+(h+Y$[f]&Yn)&Yn;i=i+((_<<l|_>>>32-l)>>>0)&Yn,s=u}t[0]=t[0]+s&Yn,t[1]=t[1]+i&Yn,t[2]=t[2]+r&Yn,t[3]=t[3]+e&Yn}var Q$=(()=>{try{return Ci("md5"),!0}catch{return!1}})(),g_=Q$?J$():Zf;function J$(){return class{digestLength=16;hash=Ci("md5");update(n){this.hash.update(Vs(n))}async digest(){let n=this.hash.copy().digest();return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}reset(){this.hash=Ci("md5")}}}var d_=new Uint32Array(256);for(let t=0;t<256;++t){let n=t;for(let s=0;s<8;++s)n=n&1?3988292384^n>>>1:n>>>1;d_[t]=n>>>0}var af=4294967295;class vf{digestLength=4;checksum=af;update(t){for(let n=0;n<t.length;++n)this.checksum=this.checksum>>>8^d_[(this.checksum^t[n])&255]}digestSync(){return(this.checksum^af)>>>0}async digest(){let t=this.digestSync(),n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t,!1),n}reset(){this.checksum=af}}var __=typeof u_.crc32==="function"?u_.crc32:void 0,E_=__?k$(__):vf;function k$(t){return class{digestLength=4;value=0;update(s){this.value=t(s,this.value)}digestSync(){return this.value>>>0}async digest(){let s=new Uint8Array(4);return new DataView(s.buffer).setUint32(0,this.digestSync(),!1),s}reset(){this.value=0}}}var At=64,w_=32,z$=9007199254740991;class Sn{digestLength=w_;state=Int32Array.from(A_);w;buffer=new Uint8Array(64);bufferLength=0;bytesHashed=0;finished=!1;inner;outer;constructor(t){if(t){let n=Sn.normalizeKey(t);this.inner=new Sn,this.outer=new Sn;let{inner:s,outer:i}=this,r=new Uint8Array(At*2);for(let e=0;e<At;++e)r[e]=54^n[e],r[e+At]=92^n[e];s.update(r.subarray(0,At)),i.update(r.subarray(At))}}update(t){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.inner){this.inner.update(t);return}let n=Vs(t),s=0,{byteLength:i}=n;if(this.bytesHashed+=i,this.bytesHashed*8>z$)throw Error("Cannot hash more than 2^53 - 1 bits");while(i>0)if(this.buffer[this.bufferLength++]=n[s++],i--,this.bufferLength===At)this.hashBuffer(),this.bufferLength=0}async digest(){let{inner:t,outer:n}=this;if(t&&n){if(this.finished)throw Error("Attempted to digest an already finished HMAC.");this.finished=!0;let s=t.digestSync();return n.update(s),n.digestSync()}return this.digestSync()}reset(){this.state=Int32Array.from(A_),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0}digestSync(){let t=this.state.slice(),n=this.buffer.slice(),s=this.bufferLength,i=this.bytesHashed*8,r=new DataView(n.buffer,n.byteOffset,n.byteLength);if(r.setUint8(s++,128),(s-1)%At>=At-8){for(let f=s;f<At;++f)r.setUint8(f,0);this.hashBufferWith(t,n),s=0}for(let f=s;f<At-8;++f)r.setUint8(f,0);r.setUint32(At-8,Math.floor(i/4294967296),!1),r.setUint32(At-4,i,!1),this.hashBufferWith(t,n);let e=new Uint8Array(w_);for(let f=0;f<8;++f)e[f*4]=t[f]>>>24&255,e[f*4+1]=t[f]>>>16&255,e[f*4+2]=t[f]>>>8&255,e[f*4+3]=t[f]>>>0&255;return e}static normalizeKey(t){let n=Vs(t);if(n.byteLength>At){let s=new Sn;s.update(n);let i=s.digestSync(),r=new Uint8Array(At);return r.set(i),r}if(n.byteLength<At){let s=new Uint8Array(At);return s.set(n),s}return n}hashBuffer(){this.hashBufferWith(this.state,this.buffer)}hashBufferWith(t,n){let s=this.w??=new Int32Array(64),i=t[0],r=t[1],e=t[2],f=t[3],o=t[4],c=t[5],h=t[6],u=t[7];for(let l=0;l<At;++l){if(l<16)s[l]=(n[l*4]&255)<<24|(n[l*4+1]&255)<<16|(n[l*4+2]&255)<<8|n[l*4+3]&255;else{let A=s[l-2],M=(A>>>17|A<<15)^(A>>>19|A<<13)^A>>>10;A=s[l-15];let d=(A>>>7|A<<25)^(A>>>18|A<<14)^A>>>3;s[l]=(M+s[l-7]|0)+(d+s[l-16]|0)}let _=(((o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7))+(o&c^~o&h)|0)+(u+(X$[l]+s[l]|0)|0)|0,w=((i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10))+(i&r^i&e^r&e)|0;u=h,h=c,c=o,o=f+_|0,f=e,e=r,r=i,i=_+w|0}t[0]+=i,t[1]+=r,t[2]+=e,t[3]+=f,t[4]+=o,t[5]+=c,t[6]+=h,t[7]+=u}}var A_=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),X$=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]),x$=(()=>{try{return Ci("sha256"),!0}catch{return!1}})(),R_=x$?q$():Sn;function q$(){return class{digestLength=32;secret;hash;isHmac;finished=!1;constructor(n){this.secret=n,this.isHmac=!!n,this.hash=this.createHash()}update(n){if(this.finished)throw Error("Attempted to update an already finished hash.");this.hash.update(n)}async digest(){let n;if(this.isHmac)this.finished=!0,n=this.hash.digest();else n=this.hash.copy().digest();return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}reset(){this.hash=this.createHash(),this.finished=!1}createHash(){return this.secret?H$("sha256",C$(this.secret)):Ci("sha256")}}}function C$(t){if(typeof t==="string")return t;if(ArrayBuffer.isView(t))return Buffer.from(t.buffer,t.byteOffset,t.byteLength);return Buffer.from(t)}var{digest:K$,sign:V$,importKey:j$}=globalThis?.crypto?.subtle??{},Ae=typeof K$==="function"&&typeof V$==="function"&&typeof j$==="function"?globalThis.crypto.subtle:void 0,a$=8388608;class b_{digestLength=32;secret;pending=[];pendingBytes=0;fallback;finished=!1;constructor(t){if(t)this.secret=Vs(t)}update(t){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.fallback){this.fallback.update(t);return}if(this.pending.push(t.slice()),this.pendingBytes+=t.byteLength,this.pendingBytes>=a$)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 t=F$(this.pending);if(Ae){if(this.secret){this.finished=!0;let i=await Ae.importKey("raw",this.secret,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await Ae.sign("HMAC",i,t);return new Uint8Array(r)}let s=await Ae.digest("SHA-256",t);return new Uint8Array(s)}let n=new Sn(this.secret);return n.update(t),n.digest()}reset(){this.pending=[],this.pendingBytes=0,this.fallback=void 0,this.finished=!1}switchToFallback(){let t=new Sn(this.secret);for(let n of this.pending)t.update(n);this.fallback=t,this.pending=[],this.pendingBytes=0}}p$.Crc32=E_;p$.Crc32Js=vf;p$.Crc32Node=E_;p$.Md5=g_;p$.Md5Js=Zf;p$.Md5Node=g_;p$.Sha256=R_;p$.Sha256Js=Sn;p$.Sha256Node=R_;p$.Sha256WebCrypto=b_;p$.blobHasher=P$;p$.blobReader=M_;p$.fileStreamHasher=N$;p$.readableStreamHasher=D$});var Me=Z((NU)=>{var{Crc32:$_}=tc(),{toHex:js,fromHex:_U,toUtf8:wU,fromUtf8:AU}=$t(),{Readable:MU}=nt("stream");class as{bytes;constructor(t){if(this.bytes=t,t.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(t){if(t>9223372036854776000||t<-9223372036854776000)throw Error(`${t} is too large (or, if negative, too small) to represent as an Int64`);let n=new Uint8Array(8);for(let s=7,i=Math.abs(Math.round(t));s>-1&&i>0;s--,i/=256)n[s]=i;if(t<0)T_(n);return new as(n)}valueOf(){let t=this.bytes.slice(0),n=t[0]&128;if(n)T_(t);return parseInt(js(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}}function T_(t){for(let n=0;n<8;n++)t[n]^=255;for(let n=7;n>-1;n--)if(t[n]++,t[n]!==0)break}class nc{toUtf8;fromUtf8;constructor(t,n){this.toUtf8=t,this.fromUtf8=n}format(t){let n=[];for(let r of Object.keys(t)){let e=this.fromUtf8(r);n.push(Uint8Array.from([e.byteLength]),e,this.formatHeaderValue(t[r]))}let s=new Uint8Array(n.reduce((r,e)=>r+e.byteLength,0)),i=0;for(let r of n)s.set(r,i),i+=r.byteLength;return s}formatHeaderValue(t){switch(t.type){case"boolean":return Uint8Array.from([t.value?rt.boolTrue:rt.boolFalse]);case"byte":return Uint8Array.from([rt.byte,t.value]);case"short":let n=new DataView(new ArrayBuffer(3));return n.setUint8(0,rt.short),n.setInt16(1,t.value,!1),new Uint8Array(n.buffer);case"integer":let s=new DataView(new ArrayBuffer(5));return s.setUint8(0,rt.integer),s.setInt32(1,t.value,!1),new Uint8Array(s.buffer);case"long":let i=new Uint8Array(9);return i[0]=rt.long,i.set(t.value.bytes,1),i;case"binary":let r=new DataView(new ArrayBuffer(3+t.value.byteLength));r.setUint8(0,rt.byteArray),r.setUint16(1,t.value.byteLength,!1);let e=new Uint8Array(r.buffer);return e.set(t.value,3),e;case"string":let f=this.fromUtf8(t.value),o=new DataView(new ArrayBuffer(3+f.byteLength));o.setUint8(0,rt.string),o.setUint16(1,f.byteLength,!1);let c=new Uint8Array(o.buffer);return c.set(f,3),c;case"timestamp":let h=new Uint8Array(9);return h[0]=rt.timestamp,h.set(as.fromNumber(t.value.valueOf()).bytes,1),h;case"uuid":if(!UU.test(t.value))throw Error(`Invalid UUID received: ${t.value}`);let u=new Uint8Array(17);return u[0]=rt.uuid,u.set(_U(t.value.replace(/-/g,"")),1),u}}parse(t){let n={},s=0;while(s<t.byteLength){let i=t.getUint8(s++),r=this.toUtf8(new Uint8Array(t.buffer,t.byteOffset+s,i));switch(s+=i,t.getUint8(s++)){case rt.boolTrue:n[r]={type:S_,value:!0};break;case rt.boolFalse:n[r]={type:S_,value:!1};break;case rt.byte:n[r]={type:gU,value:t.getInt8(s++)};break;case rt.short:n[r]={type:dU,value:t.getInt16(s,!1)},s+=2;break;case rt.integer:n[r]={type:EU,value:t.getInt32(s,!1)},s+=4;break;case rt.long:n[r]={type:RU,value:new as(new Uint8Array(t.buffer,t.byteOffset+s,8))},s+=8;break;case rt.byteArray:let e=t.getUint16(s,!1);s+=2,n[r]={type:bU,value:new Uint8Array(t.buffer,t.byteOffset+s,e)},s+=e;break;case rt.string:let f=t.getUint16(s,!1);s+=2,n[r]={type:TU,value:this.toUtf8(new Uint8Array(t.buffer,t.byteOffset+s,f))},s+=f;break;case rt.timestamp:n[r]={type:SU,value:new Date(new as(new Uint8Array(t.buffer,t.byteOffset+s,8)).valueOf())},s+=8;break;case rt.uuid:let o=new Uint8Array(t.buffer,t.byteOffset+s,16);s+=16,n[r]={type:$U,value:`${js(o.subarray(0,4))}-${js(o.subarray(4,6))}-${js(o.subarray(6,8))}-${js(o.subarray(8,10))}-${js(o.subarray(10))}`};break;default:throw Error("Unrecognized header type tag")}}return n}}var rt;(function(t){t[t.boolTrue=0]="boolTrue",t[t.boolFalse=1]="boolFalse",t[t.byte=2]="byte",t[t.short=3]="short",t[t.integer=4]="integer",t[t.long=5]="long",t[t.byteArray=6]="byteArray",t[t.string=7]="string",t[t.timestamp=8]="timestamp",t[t.uuid=9]="uuid"})(rt||(rt={}));var S_="boolean",gU="byte",dU="short",EU="integer",RU="long",bU="binary",TU="string",SU="timestamp",$U="uuid",UU=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,U_=4,Qn=U_*2,hs=4,LU=Qn+hs*2;function IU({byteLength:t,byteOffset:n,buffer:s}){if(t<LU)throw Error("Provided message too short to accommodate event stream message overhead");let i=new DataView(s,n,t),r=i.getUint32(0,!1);if(t!==r)throw Error("Reported message length does not match received message length");let e=i.getUint32(U_,!1),f=i.getUint32(Qn,!1),o=i.getUint32(t-hs,!1),c=new $_;if(c.update(new Uint8Array(s,n,Qn)),f!==c.digestSync())throw Error(`The prelude checksum specified in the message (${f}) does not match the calculated CRC32 checksum (${c.digestSync()})`);if(c.update(new Uint8Array(s,n+Qn,t-(Qn+hs))),o!==c.digestSync())throw Error(`The message checksum (${c.digestSync()}) did not match the expected value of ${o}`);return{headers:new DataView(s,n+Qn+hs,e),body:new Uint8Array(s,n+Qn+hs+e,r-e-(Qn+hs+hs))}}class sc{headerMarshaller;messageBuffer;isEndOfStream;constructor(t,n){this.headerMarshaller=new nc(t,n),this.messageBuffer=[],this.isEndOfStream=!1}feed(t){this.messageBuffer.push(this.decode(t))}endOfStream(){this.isEndOfStream=!0}getMessage(){let t=this.messageBuffer.pop(),n=this.isEndOfStream;return{getMessage(){return t},isEndOfStream(){return n}}}getAvailableMessages(){let t=this.messageBuffer;this.messageBuffer=[];let n=this.isEndOfStream;return{getMessages(){return t},isEndOfStream(){return n}}}encode({headers:t,body:n}){let s=this.headerMarshaller.format(t),i=s.byteLength+n.byteLength+16,r=new Uint8Array(i),e=new DataView(r.buffer,r.byteOffset,r.byteLength),f=new $_;return e.setUint32(0,i,!1),e.setUint32(4,s.byteLength,!1),f.update(r.subarray(0,8)),e.setUint32(8,f.digestSync(),!1),r.set(s,12),r.set(n,s.byteLength+12),f.update(r.subarray(8,i-4)),e.setUint32(i-4,f.digestSync(),!1),r}decode(t){let{headers:n,body:s}=IU(t);return{headers:this.headerMarshaller.parse(n),body:s}}formatHeaders(t){return this.headerMarshaller.format(t)}}class ic{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.inputStream)yield this.options.decoder.decode(t)}}class rc{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.messageStream)yield this.options.encoder.encode(t);if(this.options.includeEndFrame)yield new Uint8Array(0)}}class ec{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.messageStream){let n=await this.options.deserializer(t);if(n===void 0)continue;yield n}}}class oc{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.inputStream)yield this.options.serializer(t)}}function L_(t){let n=0,s=0,i=null,r=null,e=(o)=>{if(typeof o!=="number")throw Error("Attempted to allocate an event message where size was not a number: "+o);n=o,s=4,i=new Uint8Array(o),new DataView(i.buffer).setUint32(0,o,!1)},f=async function*(){let o=t[Symbol.asyncIterator]();while(!0){let{value:c,done:h}=await o.next();if(h){if(!n)return;else if(n===s)yield i;else throw Error("Truncated event message received.");return}let u=c.length,l=0;while(l<u){if(!i){let w=u-l;if(!r)r=new Uint8Array(4);let A=Math.min(4-s,w);if(r.set(c.slice(l,l+A),s),s+=A,l+=A,s<4)break;e(new DataView(r.buffer).getUint32(0,!1)),r=null}let _=Math.min(n-s,u-l);if(i.set(c.slice(l,l+_),s),s+=_,l+=_,n&&n===s)yield i,i=null,n=0,s=0}}};return{[Symbol.asyncIterator]:f}}function yU(t,n){let s=fc(n.deserializer,n.toUtf8);return{[Symbol.asyncIterator]:async function*(){for await(let i of t){let r=n.eventStreamCodec.decode(i),e=await s(r);if(e===void 0)continue;yield e}}}}function fc(t,n){return async function(s){let{value:i}=s.headers[":message-type"];if(i==="error"){let r=Error(s.headers[":error-message"].value||"UnknownError");throw r.name=s.headers[":error-code"].value,r}else if(i==="exception"){let r=s.headers[":exception-type"].value,e={[r]:s},f=await t(e);if(f.$unknown){let o=Error(n(s.body));throw o.name=r,o}throw f[r]}else if(i==="event"){let r={[s.headers[":event-type"].value]:s},e=await t(r);if(e.$unknown)return;return e}else throw Error(`Unrecognizable event type: ${s.headers[":event-type"].value}`)}}var cc=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:n,utf8Decoder:s}){this.eventStreamCodec=new sc(n,s),this.utfEncoder=n}deserialize(n,s){let i=L_(n);return new ec({messageStream:new ic({inputStream:i,decoder:this.eventStreamCodec}),deserializer:fc(s,this.utfEncoder)})}serialize(n,s){return new rc({messageStream:new oc({inputStream:n,serializer:s}),encoder:this.eventStreamCodec,includeEndFrame:!0})}},OU=(t)=>new cc(t);class hc{universalMarshaller;constructor({utf8Encoder:t,utf8Decoder:n}){this.universalMarshaller=new cc({utf8Decoder:n,utf8Encoder:t})}deserialize(t,n){let s=typeof t[Symbol.asyncIterator]==="function"?t:BU(t);return this.universalMarshaller.deserialize(s,n)}serialize(t,n){return MU.from(this.universalMarshaller.serialize(t,n))}}var GU=(t)=>new hc(t);async function*BU(t){let n=!1,s=!1,i=[];t.on("error",(r)=>{if(!n)n=!0;if(r)throw r}),t.on("data",(r)=>{i.push(r)}),t.on("end",()=>{n=!0});while(!s){let r=await new Promise((e)=>setTimeout(()=>e(i.shift()),0));if(r)yield r;s=n&&i.length===0}}var FU=(t)=>({[Symbol.asyncIterator]:async function*(){let n=t.getReader();try{while(!0){let{done:s,value:i}=await n.read();if(s)return;yield i}}finally{n.releaseLock()}}}),HU=(t)=>{let n=t[Symbol.asyncIterator]();return new ReadableStream({async pull(s){let{done:i,value:r}=await n.next();if(i)return s.close();s.enqueue(r)}})},PU=(t)=>Object.assign(t,{eventStreamMarshaller:t.eventStreamSerdeProvider(t)});class I_{marshaller;serializer;deserializer;serdeContext;defaultContentType;constructor({marshaller:t,serializer:n,deserializer:s,serdeContext:i,defaultContentType:r}){this.marshaller=t,this.serializer=n,this.deserializer=s,this.serdeContext=i,this.defaultContentType=r}async serializeEventStream({eventStream:t,requestSchema:n,initialRequest:s}){let i=this.marshaller,r=n.getEventStreamMember(),e=n.getMemberSchema(r),f=this.serializer,o=this.defaultContentType,c=Symbol("initialRequestMarker"),h={async*[Symbol.asyncIterator](){if(s){let u={":event-type":{type:"string",value:"initial-request"},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:o}};f.write(n,s);let l=f.flush();yield{[c]:!0,headers:u,body:l}}for await(let u of t)yield u}};return i.serialize(h,(u)=>{if(u[c])return{headers:u.headers,body:u.body};let l="";for(let E in u)if(E!=="__type"){l=E;break}let{additionalHeaders:_,body:w,eventType:A,explicitPayloadContentType:M}=this.writeEventBody(l,e,u);return{headers:{":event-type":{type:"string",value:A},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:M??o},..._},body:w}})}async deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:s}){let i=this.marshaller,r=n.getEventStreamMember(),f=n.getMemberSchema(r).getMemberSchemas(),o=Symbol("initialResponseMarker"),c=i.deserialize(t.body,async(l)=>{let _="";for(let A in l)if(A!=="__type"){_=A;break}let w=l[_].body;if(_==="initial-response"){let A=await this.deserializer.read(n,w);return delete A[r],{[o]:!0,...A}}else if(_ in f){let A=f[_];if(A.isStructSchema()){let M={},d=!1;for(let[E,T]of A.structIterator()){let{eventHeader:U,eventPayload:S}=T.getMergedTraits();if(d=d||Boolean(U||S),S){if(T.isBlobSchema())M[E]=w;else if(T.isStringSchema())M[E]=(this.serdeContext?.utf8Encoder??wU)(w);else if(T.isStructSchema())M[E]=await this.deserializer.read(T,w)}else if(U){let y=l[_].headers[E]?.value;if(y!=null)if(T.isNumericSchema())if(y&&typeof y==="object"&&"bytes"in y)M[E]=BigInt(y.toString());else M[E]=Number(y);else M[E]=y}}if(d)return{[_]:M};if(w.byteLength===0)return{[_]:{}}}return{[_]:await this.deserializer.read(A,w)}}else return{$unknown:l}}),h=c[Symbol.asyncIterator](),u=await h.next();if(u.done)return c;if(u.value?.[o]){if(!n)throw Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");for(let l in u.value)s[l]=u.value[l]}return{async*[Symbol.asyncIterator](){if(!u?.value?.[o])yield u.value;while(!0){let{done:l,value:_}=await h.next();if(l)break;yield _}}}}writeEventBody(t,n,s){let i=this.serializer,r=t,e=null,f,o=(()=>{return n.getSchema()[4].includes(t)})(),c={};if(!o){let[l,_]=s[t];r=l,i.write(15,_)}else{let l=n.getMemberSchema(t);if(l.isStructSchema()){for(let[_,w]of l.structIterator()){let{eventHeader:A,eventPayload:M}=w.getMergedTraits();if(M)e=_;else if(A){let d=s[t][_],E="binary";if(w.isNumericSchema())if(-2147483648<=d&&d<=2147483647)E="integer";else E="long";else if(w.isTimestampSchema())E="timestamp";else if(w.isStringSchema())E="string";else if(w.isBooleanSchema())E="boolean";if(d!=null)c[_]={type:E,value:d},delete s[t][_]}}if(e!==null){let _=l.getMemberSchema(e);if(_.isBlobSchema())f="application/octet-stream";else if(_.isStringSchema())f="text/plain";i.write(_,s[t][e])}else i.write(l,s[t])}else if(l.isUnitSchema())i.write(l,{});else throw Error("@smithy/core/event-streams - non-struct member not supported in event stream union.")}let h=i.flush()??new Uint8Array;return{body:typeof h==="string"?(this.serdeContext?.utf8Decoder??AU)(h):h,eventType:r,explicitPayloadContentType:f,additionalHeaders:c}}}NU.EventStreamCodec=sc;NU.EventStreamMarshaller=hc;NU.EventStreamSerde=I_;NU.HeaderMarshaller=nc;NU.Int64=as;NU.MessageDecoderStream=ic;NU.MessageEncoderStream=rc;NU.SmithyMessageDecoderStream=ec;NU.SmithyMessageEncoderStream=oc;NU.UniversalEventStreamMarshaller=cc;NU.eventStreamSerdeProvider=GU;NU.getChunkedStream=L_;NU.getMessageUnmarshaller=fc;NU.getUnmarshalledStream=yU;NU.iterableToReadableStream=HU;NU.readableStreamToIterable=FU;NU.resolveEventStreamSerdeConfig=PU;NU.universalEventStreamSerdeProvider=OU});var Ut=Z((bL)=>{var{Uint8ArrayBlobAdapter:uc,sdkStreamMixin:vU,splitEvery:tL,splitHeader:B_,fromBase64:y_,_parseEpochTimestamp:nL,_parseRfc7231DateTime:sL,_parseRfc3339DateTimeWithOffset:iL,LazyJsonString:F_,NumericValue:rL,toUtf8:H_,fromUtf8:eL,generateIdempotencyToken:oL,toBase64:O_,dateToUtcString:fL,quoteHeader:cL}=$t(),{TypeRegistry:hL,NormalizedSchema:on,translateTraits:P_}=Nn(),{HttpRequest:ps,HttpResponse:N_,isValidHostname:W_}=nn(),{parseQueryString:uL,parseUrl:lL}=nn();bL.HttpRequest=ps;bL.HttpResponse=N_;bL.isValidHostname=W_;bL.parseQueryString=uL;bL.parseUrl=lL;var{FieldPosition:_L}=rs(),us=async(t=new Uint8Array,n)=>{if(t instanceof Uint8Array)return uc.mutate(t);if(!t)return uc.mutate(new Uint8Array);let s=n.streamCollector(t);return uc.mutate(await s)};function Vi(t){return encodeURIComponent(t).replace(/[!'()*]/g,function(n){return"%"+n.charCodeAt(0).toString(16).toUpperCase()})}class Zs{serdeContext;setSerdeContext(t){this.serdeContext=t}}class ge extends Zs{options;compositeErrorRegistry;constructor(t){super();this.options=t,this.compositeErrorRegistry=hL.for(t.defaultNamespace);for(let n of t.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(n)}getRequestType(){return ps}getResponseType(){return N_}setSerdeContext(t){if(this.serdeContext=t,this.serializer.setSerdeContext(t),this.deserializer.setSerdeContext(t),this.getPayloadCodec())this.getPayloadCodec().setSerdeContext(t)}updateServiceEndpoint(t,n){if("url"in n){if(t.protocol=n.url.protocol,t.hostname=n.url.hostname,t.port=n.url.port?Number(n.url.port):void 0,t.path=n.url.pathname,t.fragment=n.url.hash||void 0,t.username=n.url.username||void 0,t.password=n.url.password||void 0,!t.query)t.query={};for(let[s,i]of n.url.searchParams.entries())t.query[s]=i;if(n.headers)for(let s in n.headers)t.headers[s]=n.headers[s].join(", ");return t}else{if(t.protocol=n.protocol,t.hostname=n.hostname,t.port=n.port?Number(n.port):void 0,t.path=n.path,t.query={...n.query},n.headers)for(let s in n.headers)t.headers[s]=n.headers[s];return t}}setHostPrefix(t,n,s){if(this.serdeContext?.disableHostPrefix)return;let i=on.of(n.input),r=P_(n.traits??{});if(r.endpoint){let e=r.endpoint?.[0];if(typeof e==="string"){for(let[f,o]of i.structIterator()){if(!o.getMergedTraits().hostLabel)continue;let c=s[f];if(typeof c!=="string")throw Error(`@smithy/core/schema - ${f} in input must be a string as hostLabel.`);e=e.replace(`{${f}}`,c)}if(t.hostname=e+t.hostname,!W_(t.hostname))throw Error(`[${t.hostname}] is not a valid hostname.`)}}}deserializeMetadata(t){return{httpStatusCode:t.statusCode,requestId:t.headers["x-amzn-requestid"]??t.headers["x-amzn-request-id"]??t.headers["x-amz-request-id"],extendedRequestId:t.headers["x-amz-id-2"],cfId:t.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream:t,requestSchema:n,initialRequest:s}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:t,requestSchema:n,initialRequest:s})}async deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:s}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:s})}async loadEventStreamCapability(){let{EventStreamSerde:t,eventStreamSerdeProvider:n}=Me(),s=this.resolveEventStreamMarshaller(n);return new t({marshaller:s,serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}resolveEventStreamMarshaller(t){let n=this.serdeContext;if(n.eventStreamMarshaller)return n.eventStreamMarshaller;return t(this.serdeContext)}getDefaultContentType(){throw Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(t,n,s,i,r){return[]}getEventStreamMarshaller(){let t=this.serdeContext;if(!t.eventStreamMarshaller)throw Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return t.eventStreamMarshaller}}class D_ extends ge{async serializeRequest(t,n,s){let i=n&&typeof n==="object"?n:{},r=this.serializer,e={},f={},o=await s.endpoint(),c=on.of(t?.input),h=[],u=[],l=!1,_,w=new ps({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:e,headers:f,body:void 0});if(o){this.updateServiceEndpoint(w,o),this.setHostPrefix(w,t,i);let A=P_(t.traits);if(A.http){w.method=A.http[0];let[M,d]=A.http[1].split("?");if(w.path=="/")w.path=M;else w.path+=M;let E=new URLSearchParams(d??"");for(let[T,U]of E)e[T]=U}}for(let[A,M]of c.structIterator()){let d=M.getMergedTraits()??{},E=i[A];if(E==null&&!M.isIdempotencyToken()){if(d.httpLabel){if(w.path.includes(`{${A}+}`)||w.path.includes(`{${A}}`))throw Error(`No value provided for input HTTP label: ${A}.`)}continue}if(d.httpPayload)if(M.isStreaming())if(M.isStructSchema()){if(i[A])_=await this.serializeEventStream({eventStream:i[A],requestSchema:c})}else _=E;else r.write(M,E),_=r.flush();else if(d.httpLabel){r.write(M,E);let T=r.flush();if(w.path.includes(`{${A}+}`))w.path=w.path.replace(`{${A}+}`,T.split("/").map(Vi).join("/"));else if(w.path.includes(`{${A}}`))w.path=w.path.replace(`{${A}}`,Vi(T))}else if(d.httpHeader)r.write(M,E),f[d.httpHeader.toLowerCase()]=String(r.flush());else if(typeof d.httpPrefixHeaders==="string")for(let T in E){let U=E[T],S=d.httpPrefixHeaders+T;r.write([M.getValueSchema(),{httpHeader:S}],U),f[S.toLowerCase()]=r.flush()}else if(d.httpQuery||d.httpQueryParams)this.serializeQuery(M,E,e);else l=!0,h.push(A),u.push(M)}if(l&&i){let[A,M]=(c.getName(!0)??"#Unknown").split("#"),d=c.getSchema()[6],E=[3,A,M,c.getMergedTraits(),h,u,void 0];if(d)E[6]=d;else E.pop();r.write(E,i),_=r.flush()}return w.headers=f,w.query=e,w.body=_,w}serializeQuery(t,n,s){let i=this.serializer,r=t.getMergedTraits();if(r.httpQueryParams){for(let e in n)if(!(e in s)){let f=n[e],o=t.getValueSchema();Object.assign(o.getMergedTraits(),{...r,httpQuery:e,httpQueryParams:void 0}),this.serializeQuery(o,f,s)}return}if(t.isListSchema()){let e=!!t.getMergedTraits().sparse,f=[];for(let o of n){i.write([t.getValueSchema(),r],o);let c=i.flush();if(e||c!==void 0)f.push(c)}s[r.httpQuery]=f}else i.write([t,r],n),s[r.httpQuery]=i.flush()}async deserializeResponse(t,n,s){let i=this.deserializer,r=on.of(t.output),e={};if(s.statusCode>=300){let o=await us(s.body,n);if(o.byteLength>0)Object.assign(e,await i.read(15,o));throw await this.handleError(t,n,s,e,this.deserializeMetadata(s)),Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(let o in s.headers){let c=s.headers[o];delete s.headers[o],s.headers[o.toLowerCase()]=c}let f=await this.deserializeHttpMessage(r,n,s,e);if(f.length){let o=await us(s.body,n);if(o.byteLength>0){let c=await i.read(r,o);for(let h of f)if(c[h]!=null)e[h]=c[h]}}else if(f.discardResponseBody)await us(s.body,n);return e.$metadata=this.deserializeMetadata(s),e}async deserializeHttpMessage(t,n,s,i,r){let e;if(i instanceof Set)e=r;else e=i;let f=!0,o=this.deserializer,c=on.of(t),h=[];for(let[u,l]of c.structIterator()){let _=l.getMemberTraits();if(_.httpPayload){if(f=!1,l.isStreaming())if(l.isStructSchema())e[u]=await this.deserializeEventStream({response:s,responseSchema:c});else e[u]=vU(s.body);else if(s.body){let A=await us(s.body,n);if(A.byteLength>0)e[u]=await o.read(l,A)}}else if(_.httpHeader){let w=String(_.httpHeader).toLowerCase(),A=s.headers[w];if(A!=null)if(l.isListSchema()){let M=l.getValueSchema();M.getMergedTraits().httpHeader=w;let d;if(M.isTimestampSchema()&&M.getSchema()===4)d=tL(A,",",2);else d=B_(A);let E=[];for(let T of d)E.push(await o.read(M,T.trim()));e[u]=E}else e[u]=await o.read(l,A)}else if(_.httpPrefixHeaders!==void 0){e[u]={};for(let w in s.headers)if(w.startsWith(_.httpPrefixHeaders)){let A=s.headers[w],M=l.getValueSchema();M.getMergedTraits().httpHeader=w,e[u][w.slice(_.httpPrefixHeaders.length)]=await o.read(M,A)}}else if(_.httpResponseCode)e[u]=s.statusCode;else h.push(u)}return h.discardResponseBody=f,h}}class m_ extends ge{async serializeRequest(t,n,s){let i=this.serializer,r={},e={},f=await s.endpoint(),o=on.of(t?.input),c=o.getSchema(),h,u=n&&typeof n==="object"?n:{},l=new ps({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:r,headers:e,body:void 0});if(f)this.updateServiceEndpoint(l,f),this.setHostPrefix(l,t,u);if(u){let _=o.getEventStreamMember();if(_){if(u[_]){let w={};for(let[A,M]of o.structIterator())if(A!==_&&u[A])i.write(M,u[A]),w[A]=i.flush();h=await this.serializeEventStream({eventStream:u[_],requestSchema:o,initialRequest:w})}}else i.write(c,u),h=i.flush()}return l.headers=Object.assign(l.headers,e),l.query=r,l.body=h,l.method="POST",l}async deserializeResponse(t,n,s){let i=this.deserializer,r=on.of(t.output),e={};if(s.statusCode>=300){let o=await us(s.body,n);if(o.byteLength>0)Object.assign(e,await i.read(15,o));throw await this.handleError(t,n,s,e,this.deserializeMetadata(s)),Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(let o in s.headers){let c=s.headers[o];delete s.headers[o],s.headers[o.toLowerCase()]=c}let f=r.getEventStreamMember();if(f)e[f]=await this.deserializeEventStream({response:s,responseSchema:r,initialResponseContainer:e});else{let o=await us(s.body,n);if(o.byteLength>0)Object.assign(e,await i.read(r,o))}return e.$metadata=this.deserializeMetadata(s),e}}var Y_=(t,n,s,i,r,e)=>{if(n!=null&&n[s]!==void 0){let f=i();if(f==null||f.length<=0)throw Error("Empty value provided for input HTTP label: "+s+".");t=t.replace(r,e?f.split("/").map((o)=>Vi(o)).join("/"):Vi(f))}else throw Error("No value provided for input HTTP label: "+s+".");return t};function wL(t,n){return new lc(t,n)}class lc{input;context;query={};method="";headers={};path="";body=null;hostname="";resolvePathStack=[];constructor(t,n){this.input=t,this.context=n}async build(){let{hostname:t,protocol:n="https",port:s,path:i}=await this.context.endpoint();this.path=i;for(let r of this.resolvePathStack)r(this.path);return new ps({protocol:n,hostname:this.hostname||t,port:s,method:this.method,path:this.path,query:this.query,body:this.body,headers:this.headers})}hn(t){return this.hostname=t,this}bp(t){return this.resolvePathStack.push((n)=>{this.path=`${n?.endsWith("/")?n.slice(0,-1):n||""}`+t}),this}p(t,n,s,i){return this.resolvePathStack.push((r)=>{this.path=Y_(r,this.input,t,n,s,i)}),this}h(t){return this.headers=t,this}q(t){return this.query=t,this}b(t){return this.body=t,this}m(t){return this.method=t,this}}function _c(t,n){if(n.timestampFormat.useTrait){if(t.isTimestampSchema()&&(t.getSchema()===5||t.getSchema()===6||t.getSchema()===7))return t.getSchema()}let{httpLabel:s,httpPrefixHeaders:i,httpHeader:r,httpQuery:e}=t.getMergedTraits();return(n.httpBindings?typeof i==="string"||Boolean(r)?6:Boolean(e)||Boolean(s)?5:void 0:void 0)??n.timestampFormat.default}class wc extends Zs{settings;constructor(t){super();this.settings=t}read(t,n){let s=on.of(t);if(s.isListSchema())return B_(n).map((i)=>this.read(s.getValueSchema(),i));if(s.isBlobSchema())return(this.serdeContext?.base64Decoder??y_)(n);if(s.isTimestampSchema())switch(_c(s,this.settings)){case 5:return iL(n);case 6:return sL(n);case 7:return nL(n);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",n),new Date(n)}if(s.isStringSchema()){let i=s.getMergedTraits().mediaType,r=n;if(i){if(s.getMergedTraits().httpHeader)r=this.base64ToUtf8(r);if(i==="application/json"||i.endsWith("+json"))r=F_.from(r);return r}}if(s.isNumericSchema())return Number(n);if(s.isBigIntegerSchema())return BigInt(n);if(s.isBigDecimalSchema())return new rL(n,"bigDecimal");if(s.isBooleanSchema())return String(n).toLowerCase()==="true";return n}base64ToUtf8(t){return(this.serdeContext?.utf8Encoder??H_)((this.serdeContext?.base64Decoder??y_)(t))}}class Q_ extends Zs{codecDeserializer;stringDeserializer;constructor(t,n){super();this.codecDeserializer=t,this.stringDeserializer=new wc(n)}setSerdeContext(t){this.stringDeserializer.setSerdeContext(t),this.codecDeserializer.setSerdeContext(t),this.serdeContext=t}read(t,n){let s=on.of(t),i=s.getMergedTraits(),r=this.serdeContext?.utf8Encoder??H_;if(i.httpHeader||i.httpResponseCode)return this.stringDeserializer.read(s,r(n));if(i.httpPayload){if(s.isBlobSchema()){let e=this.serdeContext?.utf8Decoder??eL;if(typeof n==="string")return e(n);return n}else if(s.isStringSchema()){if("byteLength"in n)return r(n);return n}}return this.codecDeserializer.read(s,n)}}class Ac extends Zs{settings;stringBuffer="";constructor(t){super();this.settings=t}write(t,n){let s=on.of(t);switch(typeof n){case"object":if(n===null){this.stringBuffer="null";return}if(s.isTimestampSchema()){if(!(n instanceof Date))throw Error(`@smithy/core/protocols - received non-Date value ${n} when schema expected Date in ${s.getName(!0)}`);switch(_c(s,this.settings)){case 5:this.stringBuffer=n.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=fL(n);break;case 7:this.stringBuffer=String(n.getTime()/1000);break;default:console.warn("Missing timestamp format, using epoch seconds",n),this.stringBuffer=String(n.getTime()/1000)}return}if(s.isBlobSchema()&&"byteLength"in n){this.stringBuffer=(this.serdeContext?.base64Encoder??O_)(n);return}if(s.isListSchema()&&Array.isArray(n)){let e="";for(let f of n){this.write([s.getValueSchema(),s.getMergedTraits()],f);let o=this.flush(),c=s.getValueSchema().isTimestampSchema()?o:cL(o);if(e!=="")e+=", ";e+=c}this.stringBuffer=e;return}this.stringBuffer=JSON.stringify(n,null,2);break;case"string":let i=s.getMergedTraits().mediaType,r=n;if(i){if(i==="application/json"||i.endsWith("+json"))r=F_.from(r);if(s.getMergedTraits().httpHeader){this.stringBuffer=(this.serdeContext?.base64Encoder??O_)(r.toString());return}}this.stringBuffer=n;break;default:if(s.isIdempotencyToken())this.stringBuffer=oL();else this.stringBuffer=String(n)}}flush(){let t=this.stringBuffer;return this.stringBuffer="",t}}class J_{codecSerializer;stringSerializer;buffer;constructor(t,n,s=new Ac(n)){this.codecSerializer=t,this.stringSerializer=s}setSerdeContext(t){this.codecSerializer.setSerdeContext(t),this.stringSerializer.setSerdeContext(t)}write(t,n){let s=on.of(t),i=s.getMergedTraits();if(i.httpHeader||i.httpLabel||i.httpQuery){this.stringSerializer.write(s,n),this.buffer=this.stringSerializer.flush();return}return this.codecSerializer.write(s,n)}flush(){if(this.buffer!==void 0){let t=this.buffer;return this.buffer=void 0,t}return this.codecSerializer.flush()}}class k_{name;kind;values;constructor({name:t,kind:n=_L.HEADER,values:s=[]}){this.name=t,this.kind=n,this.values=s}add(t){this.values.push(t)}set(t){this.values=t}remove(t){this.values=this.values.filter((n)=>n!==t)}toString(){return this.values.map((t)=>t.includes(",")||t.includes(" ")?`"${t}"`:t).join(", ")}get(){return this.values}}class z_{entries={};encoding;constructor({fields:t=[],encoding:n="utf-8"}){t.forEach(this.setField.bind(this)),this.encoding=n}setField(t){this.entries[t.name.toLowerCase()]=t}getField(t){return this.entries[t.toLowerCase()]}removeField(t){delete this.entries[t.toLowerCase()]}getByType(t){return Object.values(this.entries).filter((n)=>n.kind===t)}}var AL=(t)=>{return{setHttpHandler(n){t.httpHandler=n},httpHandler(){return t.httpHandler},updateHttpClientConfig(n,s){t.httpHandler?.updateHttpClientConfig(n,s)},httpHandlerConfigs(){return t.httpHandler.httpHandlerConfigs()}}},ML=(t)=>{return{httpHandler:t.httpHandler()}},G_="content-length";function X_(t){return(n)=>async(s)=>{let i=s.request;if(ps.isInstance(i)){let{body:r,headers:e}=i;if(r&&Object.keys(e).map((f)=>f.toLowerCase()).indexOf(G_)===-1)try{let f=t(r);i.headers={...i.headers,[G_]:String(f)}}catch(f){}}return n({...s,request:i})}}var x_={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},gL=(t)=>({applyToStack:(n)=>{n.add(X_(t.bodyLengthChecker),x_)}}),Ki=(t)=>encodeURIComponent(t).replace(/[!'()*]/g,dL),dL=(t)=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`,EL=(t)=>t.split("/").map(Ki).join("/");function RL(t){let n=[];for(let s of Object.keys(t).sort()){let i=t[s];if(s=Ki(s),Array.isArray(i))for(let r=0,e=i.length;r<e;r++)n.push(`${s}=${Ki(i[r])}`);else{let r=s;if(i||typeof i==="string")r+=`=${Ki(i)}`;n.push(r)}}return n.join("&")}bL.Field=k_;bL.Fields=z_;bL.FromStringShapeDeserializer=wc;bL.HttpBindingProtocol=D_;bL.HttpInterceptingShapeDeserializer=Q_;bL.HttpInterceptingShapeSerializer=J_;bL.HttpProtocol=ge;bL.RequestBuilder=lc;bL.RpcProtocol=m_;bL.SerdeContext=Zs;bL.ToStringShapeSerializer=Ac;bL.buildQueryString=RL;bL.collectBody=us;bL.contentLengthMiddleware=X_;bL.contentLengthMiddlewareOptions=x_;bL.determineTimestampFormat=_c;bL.escapeUri=Ki;bL.escapeUriPath=EL;bL.extendedEncodeURIComponent=Vi;bL.getContentLengthPlugin=gL;bL.getHttpHandlerExtensionConfiguration=AL;bL.requestBuilder=wL;bL.resolveHttpHandlerRuntimeConfig=ML;bL.resolvedPath=Y_});var vi=Z((RI)=>{var{Readable:aL}=nt("stream"),{NoOpLogger:pL,normalizeProvider:q_}=Rn(),{HttpResponse:C_,HttpRequest:Ee}=Ut(),{parseRfc7231DateTime:ZL,v4:K_}=$t(),V_=(t)=>t?.body instanceof aL||typeof ReadableStream<"u"&&t?.body instanceof ReadableStream,vL=["AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"],tI=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],nI=["TimeoutError","RequestTimeout","RequestTimeoutException"],sI=[500,502,503,504],iI=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],rI=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],Ec=(t)=>t?.$retryable!==void 0,j_=(t)=>vL.includes(t.name),a_=(t)=>t.$metadata?.clockSkewCorrected,p_=(t)=>{let n=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);if(!(t&&t instanceof TypeError))return!1;return n.has(t.message)},ai=(t)=>t.$metadata?.httpStatusCode===429||tI.includes(t.name)||t.$retryable?.throttling==!0,pi=(t,n=0)=>Ec(t)||a_(t)||t.name==="InvalidSignatureException"&&t.message?.includes("Signature expired")||nI.includes(t.name)||iI.includes(t?.code||"")||rI.includes(t?.code||"")||sI.includes(t.$metadata?.httpStatusCode||0)||p_(t)||v_(t)||t.cause!==void 0&&n<=10&&pi(t.cause,n+1),Z_=(t)=>{if(t.$metadata?.httpStatusCode!==void 0){let n=t.$metadata.httpStatusCode;if(500<=n&&n<=599&&!pi(t))return!0;return!1}return!1};function v_(t){return t.code==="ERR_HTTP2_STREAM_ERROR"&&t.message.includes("NGHTTP2_REFUSED_STREAM")}var tw=100,be=20000,nw=500,Re=500,sw=5,iw=10,Rc=1,Te="amz-sdk-invocation-id",Se="amz-sdk-request";function rw(t,n){if(!C_.isInstance(t))return;for(let s of Object.keys(t.headers)){let i=s.toLowerCase();if(i==="retry-after"){let r=t.headers[s],e=NaN;if(r.endsWith("GMT"))try{e=(ZL(r).getTime()-Date.now())/1000}catch(f){n?.trace?.("Failed to parse retry-after header"),n?.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(i==="x-amz-retry-after"){let r=t.headers[s],e=Number(r);if(isNaN(e)){n?.trace?.(`Failed to parse x-amz-retry-after=${r}`);return}return new Date(Date.now()+e)}}}function eI(t,n){return rw(t,n)}var ew=(t)=>{if(t instanceof Error)return t;if(t instanceof Object)return Object.assign(Error(),t);if(typeof t==="string")return Error(t);return Error(`AWS SDK error wrapper for ${t}`)};function ow(t){return(n)=>(s,i)=>async(r)=>{let e=await n.retryStrategy(),f=await n.maxAttempts();if(fI(e)){e=e;let o=await e.acquireInitialRetryToken((i.partition_id??"")+(i.__retryLongPoll?":longpoll":"")),c=Error(),h=0,u=0,{request:l}=r,_=Ee.isInstance(l);if(_)l.headers[Te]=K_();while(!0)try{if(_)l.headers[Se]=`attempt=${h+1}; max=${f}`;let{response:w,output:A}=await s(r);return e.recordSuccess(o),A.$metadata.attempts=h+1,A.$metadata.totalRetryDelay=u,{response:w,output:A}}catch(w){let A=cI(w,n.logger);if(c=ew(w),_&&t(l))throw(i.logger instanceof pL?console:i.logger)?.warn("An error was encountered in a non-retryable streaming request."),c;try{o=await e.refreshRetryTokenForRetry(o,A)}catch(d){if(!c.$metadata)c.$metadata={};throw c.$metadata.attempts=h+1,c.$metadata.totalRetryDelay=u,c}h=o.getRetryCount();let M=o.getRetryDelay();if(u+=(o?.$retryLog?.acquisitionDelay??0)+M,M>0)await oI(M)}}else{if(e=e,e?.mode)i.userAgent=[...i.userAgent||[],["cfg/retry-mode",e.mode]];return e.retry(s,r)}}}var oI=(t)=>new Promise((n)=>setTimeout(n,t)),fI=(t)=>typeof t.acquireInitialRetryToken<"u"&&typeof t.refreshRetryTokenForRetry<"u"&&typeof t.recordSuccess<"u",cI=(t,n)=>{let s={error:t,errorType:hI(t)},i=rw(t.$response,n);if(i)s.retryAfterHint=i;return s},hI=(t)=>{if(ai(t))return"THROTTLING";if(pi(t))return"TRANSIENT";if(Z_(t))return"SERVER_ERROR";return"CLIENT_ERROR"},fw={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function uI(t){let n=ow(t);return(s)=>({applyToStack:(i)=>{i.add(n(s),fw)}})}class Zi{static setTimeoutFn=(t,n)=>setTimeout(t,n);beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(t){this.beta=t?.beta??0.7,this.minCapacity=t?.minCapacity??1,this.minFillRate=t?.minFillRate??0.5,this.scaleConstant=t?.scaleConstant??0.4,this.smooth=t?.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(t){let n;this.updateMeasuredRate();let s=t;if(s?.errorType==="THROTTLING"||ai(s?.error??t)){let e=!this.enabled?this.measuredTxRate:Math.min(this.measuredTxRate,this.fillRate);this.lastMaxRate=e,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),n=this.cubicThrottle(e),this.enableTokenBucket()}else this.calculateTimeWindow(),n=this.cubicSuccess(this.getCurrentTimeInSeconds());let r=Math.min(n,2*this.measuredTxRate);this.updateTokenBucketRate(r)}getCurrentTimeInSeconds(){return Date.now()/1000}async acquireTokenBucket(t){if(!this.enabled)return;this.refillTokenBucket();while(t>this.availableTokens){let n=(t-this.availableTokens)/this.fillRate*1000;await new Promise((s)=>Zi.setTimeoutFn(s,n)),this.refillTokenBucket()}this.availableTokens=this.availableTokens-t}refillTokenBucket(){let t=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=t;return}let n=(t-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+n),this.lastTimestamp=t}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,0.3333333333333333))}cubicThrottle(t){return this.getPrecise(t*this.beta)}cubicSuccess(t){return this.getPrecise(this.scaleConstant*Math.pow(t-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(t){this.refillTokenBucket(),this.fillRate=Math.max(t,this.minFillRate),this.maxCapacity=Math.max(t,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){let t=this.getCurrentTimeInSeconds(),n=Math.floor(t*2)/2;if(this.requestCount++,n>this.lastTxRateBucket){let s=this.requestCount/(n-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(s*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=n}}getPrecise(t){return parseFloat(t.toFixed(8))}}class lt{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return lt.v2026?50:100}static throttlingDelay(){return lt.v2026?1000:500}static cost(){return lt.v2026?14:5}static throttlingCost(){return lt.v2026?5:10}static modifiedCostType(){return lt.v2026?"THROTTLING":"TRANSIENT"}}class cw{x=lt.delay();computeNextBackoffDelay(t){let n=Math.random(),s=2,i=n*Math.min(this.x*2**t,be);return Math.floor(i)}setDelayBase(t){this.x=t}}class Mc{delay;count;cost;longPoll;$retryLog={acquisitionDelay:0};constructor(t,n,s,i){this.delay=t,this.count=n,this.cost=s,this.longPoll=i}getRetryCount(){return this.count}getRetryDelay(){return Math.min(be,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var $n;(function(t){t.STANDARD="standard",t.ADAPTIVE="adaptive"})($n||($n={}));var ls=3,hw=$n.STANDARD,de={incompatible:1,attempts:2,capacity:3},ji=class{mode=$n.STANDARD;retryBackoffStrategy;capacity=Re;maxAttemptsProvider;baseDelay;constructor(n){if(typeof n==="number")this.maxAttemptsProvider=async()=>n;else if(typeof n==="function")this.maxAttemptsProvider=n;else if(n&&typeof n==="object")this.maxAttemptsProvider=async()=>n.maxAttempts,this.baseDelay=n.baseDelay,this.retryBackoffStrategy=n.backoff;this.maxAttemptsProvider??=async()=>ls,this.baseDelay??=lt.delay(),this.retryBackoffStrategy??=new cw}async acquireInitialRetryToken(n){return new Mc(lt.delay(),0,void 0,lt.v2026&&n.includes(":longpoll"))}async refreshRetryTokenForRetry(n,s){let i=await this.getMaxAttempts(),r=this.retryCode(n,s,i),e=r===0,f=n.isLongPoll?.();if(e||f){let o=s.errorType;this.retryBackoffStrategy.setDelayBase(o==="THROTTLING"?lt.throttlingDelay():this.baseDelay);let c=this.retryBackoffStrategy.computeNextBackoffDelay(n.getRetryCount()),h=c;if(s.retryAfterHint instanceof Date)h=Math.max(c,Math.min(s.retryAfterHint.getTime()-Date.now(),c+5000));if(!e){let u=lt.v2026&&r===de.capacity&&f?h:0;if(u>0)await new Promise((l)=>setTimeout(l,u))}else{let u=this.getCapacityCost(o);this.capacity-=u;let l=new Mc(0,n.getRetryCount()+1,u,n.isLongPoll?.()??!1);return await new Promise((_)=>setTimeout(_,h)),l.$retryLog.acquisitionDelay=h,l}}throw Error("No retry token available")}recordSuccess(n){this.capacity=Math.min(Re,this.capacity+(n.getRetryCost()??Rc))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(n){return console.warn(`Max attempts provider could not resolve. Using default of ${ls}`),ls}}retryCode(n,s,i){let r=n.getRetryCount()+1,e=this.isRetryableError(s.errorType)?0:de.incompatible,f=r<i?0:de.attempts,o=this.capacity>=this.getCapacityCost(s.errorType)?0:de.capacity;return e||f||o}getCapacityCost(n){return n===lt.modifiedCostType()?lt.throttlingCost():lt.cost()}isRetryableError(n){return n==="THROTTLING"||n==="TRANSIENT"}},uw=class{mode=$n.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(n,s){let{rateLimiter:i}=s??{};this.rateLimiter=i??new Zi,this.standardRetryStrategy=s?new ji({maxAttempts:typeof n==="number"?n:3,...s}):new ji(n)}async acquireInitialRetryToken(n){let s=await this.standardRetryStrategy.acquireInitialRetryToken(n);return await this.rateLimiter.getSendToken(),s}async refreshRetryTokenForRetry(n,s){this.rateLimiter.updateClientSendingRate(s);let i=await this.standardRetryStrategy.refreshRetryTokenForRetry(n,s);return await this.rateLimiter.getSendToken(),i}recordSuccess(n){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(n)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}};class lw extends ji{computeNextBackoffDelay;constructor(t,n=lt.delay()){super(typeof t==="function"?t:async()=>t);if(typeof n==="number")this.computeNextBackoffDelay=()=>n;else this.computeNextBackoffDelay=n;this.retryBackoffStrategy.computeNextBackoffDelay=(s)=>{let i=s+1;return this.computeNextBackoffDelay(i)}}}var lI=(t,n)=>{let s=t,i=Rc,r=sw,e=iw,f=t,o=(l)=>l.name==="TimeoutError"?e:r,c=(l)=>o(l)<=f;return Object.freeze({hasRetryTokens:c,retrieveRetryTokens:(l)=>{if(!c(l))throw Error("No retry token available");let _=o(l);return f-=_,_},releaseRetryTokens:(l)=>{f+=l??i,f=Math.min(f,s)}})},_w=(t,n)=>Math.floor(Math.min(be,Math.random()*2**n*t)),ww=(t)=>{if(!t)return!1;return Ec(t)||j_(t)||ai(t)||pi(t)};class bc{maxAttemptsProvider;retryDecider;delayDecider;retryQuota;mode=$n.STANDARD;constructor(t,n){this.maxAttemptsProvider=t,this.retryDecider=n?.retryDecider??ww,this.delayDecider=n?.delayDecider??_w,this.retryQuota=n?.retryQuota??lI(Re)}shouldRetry(t,n,s){return n<s&&this.retryDecider(t)&&this.retryQuota.hasRetryTokens(t)}async getMaxAttempts(){let t;try{t=await this.maxAttemptsProvider()}catch(n){t=ls}return t}async retry(t,n,s){let i,r=0,e=0,f=await this.getMaxAttempts(),{request:o}=n;if(Ee.isInstance(o))o.headers[Te]=K_();while(!0)try{if(Ee.isInstance(o))o.headers[Se]=`attempt=${r+1}; max=${f}`;if(s?.beforeRequest)await s.beforeRequest();let{response:c,output:h}=await t(n);if(s?.afterRequest)s.afterRequest(c);return this.retryQuota.releaseRetryTokens(i),h.$metadata.attempts=r+1,h.$metadata.totalRetryDelay=e,{response:c,output:h}}catch(c){let h=ew(c);if(r++,this.shouldRetry(h,r,f)){i=this.retryQuota.retrieveRetryTokens(h);let u=this.delayDecider(ai(h)?nw:tw,r),l=_I(h.$response),_=Math.max(l||0,u);e+=_,await new Promise((w)=>setTimeout(w,_));continue}if(!h.$metadata)h.$metadata={};throw h.$metadata.attempts=r,h.$metadata.totalRetryDelay=e,h}}}var _I=(t)=>{if(!C_.isInstance(t))return;let n=Object.keys(t.headers).find((e)=>e.toLowerCase()==="retry-after");if(!n)return;let s=t.headers[n],i=Number(s);if(!Number.isNaN(i))return Math.min(i*1000,20000);let r=new Date(s);return Math.min(r.getTime()-Date.now(),20000)};class Aw extends bc{rateLimiter;constructor(t,n){let{rateLimiter:s,...i}=n??{};super(t,i);this.rateLimiter=s??new Zi,this.mode=$n.ADAPTIVE}async retry(t,n){return super.retry(t,n,{beforeRequest:async()=>{return this.rateLimiter.getSendToken()},afterRequest:(s)=>{this.rateLimiter.updateClientSendingRate(s)}})}}var gc="AWS_MAX_ATTEMPTS",dc="max_attempts",wI={environmentVariableSelector:(t)=>{let n=t[gc];if(!n)return;let s=parseInt(n);if(Number.isNaN(s))throw Error(`Environment variable ${gc} mast be a number, got "${n}"`);return s},configFileSelector:(t)=>{let n=t[dc];if(!n)return;let s=parseInt(n);if(Number.isNaN(s))throw Error(`Shared config file entry ${dc} mast be a number, got "${n}"`);return s},default:ls},AI=(t,n)=>{let{retryStrategy:s,retryMode:i}=t,{defaultMaxAttempts:r=ls,defaultBaseDelay:e=lt.delay()}=n??{},f=q_(t.maxAttempts??r),o=s?Promise.resolve(s):void 0,c=async()=>{let h=await f();if(await q_(i)()===$n.ADAPTIVE)return new uw(f,{maxAttempts:h,baseDelay:e});return new ji({maxAttempts:h,baseDelay:e})};return Object.assign(t,{maxAttempts:f,retryStrategy:()=>o??=c()})},Mw="AWS_RETRY_MODE",gw="retry_mode",MI={environmentVariableSelector:(t)=>t[Mw],configFileSelector:(t)=>t[gw],default:hw},dw=()=>(t)=>async(n)=>{let{request:s}=n;if(Ee.isInstance(s))delete s.headers[Te],delete s.headers[Se];return t(n)},Ew={name:"omitRetryHeadersMiddleware",tags:["RETRY","HEADERS","OMIT_RETRY_HEADERS"],relation:"before",toMiddleware:"awsAuthMiddleware",override:!0},gI=(t)=>({applyToStack:(n)=>{n.addRelativeTo(dw(),Ew)}}),dI=ow(V_),EI=uI(V_);RI.AdaptiveRetryStrategy=uw;RI.CONFIG_MAX_ATTEMPTS=dc;RI.CONFIG_RETRY_MODE=gw;RI.ConfiguredRetryStrategy=lw;RI.DEFAULT_MAX_ATTEMPTS=ls;RI.DEFAULT_RETRY_DELAY_BASE=tw;RI.DEFAULT_RETRY_MODE=hw;RI.DefaultRateLimiter=Zi;RI.DeprecatedAdaptiveRetryStrategy=Aw;RI.DeprecatedStandardRetryStrategy=bc;RI.ENV_MAX_ATTEMPTS=gc;RI.ENV_RETRY_MODE=Mw;RI.INITIAL_RETRY_TOKENS=Re;RI.INVOCATION_ID_HEADER=Te;RI.MAXIMUM_RETRY_DELAY=be;RI.NODE_MAX_ATTEMPT_CONFIG_OPTIONS=wI;RI.NODE_RETRY_MODE_CONFIG_OPTIONS=MI;RI.NO_RETRY_INCREMENT=Rc;RI.REQUEST_HEADER=Se;RI.RETRY_COST=sw;RI.RETRY_MODES=$n;RI.Retry=lt;RI.StandardRetryStrategy=ji;RI.THROTTLING_RETRY_DELAY_BASE=nw;RI.TIMEOUT_RETRY_COST=iw;RI.defaultDelayDecider=_w;RI.defaultRetryDecider=ww;RI.getOmitRetryHeadersPlugin=gI;RI.getRetryAfterHint=eI;RI.getRetryPlugin=EI;RI.isBrowserNetworkError=p_;RI.isClockSkewCorrectedError=a_;RI.isClockSkewError=j_;RI.isNodeJsHttp2TransientError=v_;RI.isRetryableByTrait=Ec;RI.isServerError=Z_;RI.isThrottlingError=ai;RI.isTransientError=pi;RI.omitRetryHeadersMiddleware=dw;RI.omitRetryHeadersMiddlewareOptions=Ew;RI.resolveRetryConfig=AI;RI.retryMiddleware=dI;RI.retryMiddlewareOptions=fw});var bw=Z((hy)=>{var Jn={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")},Tc=["true","1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA??"");if(!Tc)globalThis.awslambda=globalThis.awslambda||{};class $e{static PROTECTED_KEYS=Jn;isProtectedKey(t){return Object.values(Jn).includes(t)}getRequestId(){return this.get(Jn.REQUEST_ID)??"-"}getXRayTraceId(){return this.get(Jn.X_RAY_TRACE_ID)}getTenantId(){return this.get(Jn.TENANT_ID)}getTraceparent(){return this.get(Jn.TRACEPARENT)}getTracestate(){return this.get(Jn.TRACESTATE)}getBaggage(){return this.get(Jn.BAGGAGE)}}class Rw extends $e{currentContext;getContext(){return this.currentContext}hasContext(){return this.currentContext!==void 0}get(t){return this.currentContext?.[t]}set(t,n){if(this.isProtectedKey(t))throw Error(`Cannot modify protected Lambda context field: ${String(t)}`);this.currentContext=this.currentContext||{},this.currentContext[t]=n}run(t,n){return this.currentContext=t,n()}}class $c extends $e{als;static async create(){let t=new $c,n=await import("async_hooks");return t.als=new n.AsyncLocalStorage,t}getContext(){return this.als.getStore()}hasContext(){return this.als.getStore()!==void 0}get(t){return this.als.getStore()?.[t]}set(t,n){if(this.isProtectedKey(t))throw Error(`Cannot modify protected Lambda context field: ${String(t)}`);let s=this.als.getStore();if(!s)throw Error("No context available");s[t]=n}run(t,n){return this.als.run(t,n)}}hy.InvokeStore=void 0;(function(t){let n=null;async function s(i){if(!n)n=(async()=>{let e=i===!0||"AWS_LAMBDA_MAX_CONCURRENCY"in process.env?await $c.create():new Rw;if(!Tc&&globalThis.awslambda?.InvokeStore)return globalThis.awslambda.InvokeStore;else if(!Tc&&globalThis.awslambda)return globalThis.awslambda.InvokeStore=e,e;else return e})();return n}t.getInstanceAsync=s,t._testing=process.env.AWS_LAMBDA_BENCHMARK_MODE==="1"?{reset:()=>{if(n=null,globalThis.awslambda?.InvokeStore)delete globalThis.awslambda.InvokeStore;globalThis.awslambda={InvokeStore:void 0}}}:void 0})(hy.InvokeStore||(hy.InvokeStore={}));hy.InvokeStoreBase=$e});var kn=Z((Iy)=>{var{getSmithyContext:Uc}=nn();Iy.getSmithyContext=Uc;var{HttpRequest:Lc}=Ut(),{requestBuilder:ly}=Ut();Iy.requestBuilder=ly;var{HttpApiKeyAuthLocation:Tw}=rs(),_y=(t,n)=>{if(!n||n.length===0)return t;let s=[];for(let i of n)for(let r of t)if(r.schemeId.split("#")[1]===i)s.push(r);for(let i of t)if(!s.find(({schemeId:r})=>r===i.schemeId))s.push(i);return s};function wy(t){let n=new Map;for(let s of t)n.set(s.schemeId,s);return n}var Ic=(t,n)=>(s,i)=>async(r)=>{let e=t.httpAuthSchemeProvider(await n.httpAuthSchemeParametersProvider(t,i,r.input)),f=t.authSchemePreference?await t.authSchemePreference():[],o=_y(e,f),c=wy(t.httpAuthSchemes),h=Uc(i),u=[];for(let l of o){let _=c.get(l.schemeId);if(!_){u.push(`HttpAuthScheme \`${l.schemeId}\` was not enabled for this service.`);continue}let w=_.identityProvider(await n.identityProviderConfigProvider(t));if(!w){u.push(`HttpAuthScheme \`${l.schemeId}\` did not have an IdentityProvider configured.`);continue}let{identityProperties:A={},signingProperties:M={}}=l.propertiesExtractor?.(t,i)||{};l.identityProperties=Object.assign(l.identityProperties||{},A),l.signingProperties=Object.assign(l.signingProperties||{},M),h.selectedHttpAuthScheme={httpAuthOption:l,identity:await w(l.identityProperties),signer:_.signer};break}if(!h.selectedHttpAuthScheme)throw Error(u.join(`
|
|
23
|
-
`));return s(r)},Sw={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},Ay=(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s})=>({applyToStack:(i)=>{i.addRelativeTo(Ic(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s}),Sw)}}),$w={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"serializerMiddleware"},My=(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s})=>({applyToStack:(i)=>{i.addRelativeTo(Ic(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s}),$w)}}),gy=(t)=>(n)=>{throw n},dy=(t,n)=>{},Uw=(t)=>(n,s)=>async(i)=>{if(!Lc.isInstance(i.request))return n(i);let e=Uc(s).selectedHttpAuthScheme;if(!e)throw Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:f={}},identity:o,signer:c}=e,h=await n({...i,request:await c.sign(i.request,o,f)}).catch((c.errorHandler||gy)(f));return(c.successHandler||dy)(h.response,f),h},Lw={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},Ey=(t)=>({applyToStack:(n)=>{n.addRelativeTo(Uw(),Lw)}}),Ry=(t)=>{if(typeof t==="function")return t;let n=Promise.resolve(t);return()=>n},by=async(t,n,s,i=(e)=>e,...r)=>{let e=new t(s);return e=i(e)??e,await n.send(e,...r)};function Ty(t,n,s,i,r){return async function*(f,o,...c){let h=o,u=f.startingToken??h[s],l=!0,_;while(l){if(h[s]=u,r)h[r]=h[r]??f.pageSize;if(f.client instanceof t)_=await by(n,f.client,o,f.withCommand,...c);else throw Error(`Invalid client, expected instance of ${t.name}`);yield _;let w=u;u=Sy(_,i),l=!!(u&&(!f.stopOnSameToken||u!==w))}return}}var Sy=(t,n)=>{let s=t,i=n.split(".");for(let r of i){if(!s||typeof s!=="object")return;s=s[r]}return s};function $y(t,n,s){if(!t.__smithy_context)t.__smithy_context={features:{}};else if(!t.__smithy_context.features)t.__smithy_context.features={};t.__smithy_context.features[n]=s}class Iw{authSchemes=new Map;constructor(t){for(let n in t){let s=t[n];if(s!==void 0)this.authSchemes.set(n,s)}}getIdentityProvider(t){return this.authSchemes.get(t)}}class yw{async sign(t,n,s){if(!s)throw Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing");if(!s.name)throw Error("request could not be signed with `apiKey` since the `name` signer property is missing");if(!s.in)throw Error("request could not be signed with `apiKey` since the `in` signer property is missing");if(!n.apiKey)throw Error("request could not be signed with `apiKey` since the `apiKey` is not defined");let i=Lc.clone(t);if(s.in===Tw.QUERY)i.query[s.name]=n.apiKey;else if(s.in===Tw.HEADER)i.headers[s.name]=s.scheme?`${s.scheme} ${n.apiKey}`:n.apiKey;else throw Error("request can only be signed with `apiKey` locations `query` or `header`, but found: `"+s.in+"`");return i}}class Ow{async sign(t,n,s){let i=Lc.clone(t);if(!n.token)throw Error("request could not be signed with `token` since the `token` is not defined");return i.headers.Authorization=`Bearer ${n.token}`,i}}class Gw{async sign(t,n,s){return t}}var Bw=(t)=>function(s){return Hw(s)&&s.expiration.getTime()-Date.now()<t},Fw=300000,Uy=Bw(Fw),Hw=(t)=>t.expiration!==void 0,Ly=(t,n,s)=>{if(t===void 0)return;let i=typeof t!=="function"?async()=>Promise.resolve(t):t,r,e,f,o=!1,c=async(h)=>{if(!e)e=i(h);try{r=await e,f=!0,o=!1}finally{e=void 0}return r};if(n===void 0)return async(h)=>{if(!f||h?.forceRefresh)r=await c(h);return r};return async(h)=>{if(!f||h?.forceRefresh)r=await c(h);if(o)return r;if(!s(r))return o=!0,r;if(n(r))return await c(h),r;return r}};Iy.DefaultIdentityProviderConfig=Iw;Iy.EXPIRATION_MS=Fw;Iy.HttpApiKeyAuthSigner=yw;Iy.HttpBearerAuthSigner=Ow;Iy.NoAuthSigner=Gw;Iy.createIsIdentityExpiredFunction=Bw;Iy.createPaginator=Ty;Iy.doesIdentityRequireRefresh=Hw;Iy.getHttpAuthSchemeEndpointRuleSetPlugin=Ay;Iy.getHttpAuthSchemePlugin=My;Iy.getHttpSigningPlugin=Ey;Iy.httpAuthSchemeEndpointRuleSetMiddlewareOptions=Sw;Iy.httpAuthSchemeMiddleware=Ic;Iy.httpAuthSchemeMiddlewareOptions=$w;Iy.httpSigningMiddleware=Uw;Iy.httpSigningMiddlewareOptions=Lw;Iy.isIdentityExpired=Uy;Iy.memoizeIdentityProvider=Ly;Iy.normalizeProvider=Ry;Iy.setFeature=$y});var Pw=Z((tr,yc)=>{(function(t,n){typeof tr=="object"&&typeof yc=="object"?yc.exports=n():typeof define=="function"&&define.amd?define([],n):typeof tr=="object"?tr.bowser=n():t.bowser=n()})(tr,function(){return function(t){var n={};function s(i){if(n[i])return n[i].exports;var r=n[i]={i,l:!1,exports:{}};return t[i].call(r.exports,r,r.exports,s),r.l=!0,r.exports}return s.m=t,s.c=n,s.d=function(i,r,e){s.o(i,r)||Object.defineProperty(i,r,{enumerable:!0,get:e})},s.r=function(i){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(i,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(i,"__esModule",{value:!0})},s.t=function(i,r){if(1&r&&(i=s(i)),8&r)return i;if(4&r&&typeof i=="object"&&i&&i.__esModule)return i;var e=Object.create(null);if(s.r(e),Object.defineProperty(e,"default",{enumerable:!0,value:i}),2&r&&typeof i!="string")for(var f in i)s.d(e,f,function(o){return i[o]}.bind(null,f));return e},s.n=function(i){var r=i&&i.__esModule?function(){return i.default}:function(){return i};return s.d(r,"a",r),r},s.o=function(i,r){return Object.prototype.hasOwnProperty.call(i,r)},s.p="",s(s.s=90)}({17:function(t,n,s){n.__esModule=!0,n.default=void 0;var i=s(18),r=function(){function e(){}return e.getFirstMatch=function(f,o){var c=o.match(f);return c&&c.length>0&&c[1]||""},e.getSecondMatch=function(f,o){var c=o.match(f);return c&&c.length>1&&c[2]||""},e.matchAndReturnConst=function(f,o,c){if(f.test(o))return c},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(u){return parseInt(u,10)||0});o.push(0);var c=o[0],h=o[1];if(c===10)switch(h){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}},e.getAndroidVersionName=function(f){var o=f.split(".").splice(0,2).map(function(c){return parseInt(c,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,c){c===void 0&&(c=!1);var h=e.getVersionPrecision(f),u=e.getVersionPrecision(o),l=Math.max(h,u),_=0,w=e.map([f,o],function(A){var M=l-e.getVersionPrecision(A),d=A+Array(M+1).join(".0");return e.map(d.split("."),function(E){return Array(20-E.length).join("0")+E}).reverse()});for(c&&(_=l-Math.min(h,u)),l-=1;l>=_;){if(w[0][l]>w[1][l])return 1;if(w[0][l]===w[1][l]){if(l===_)return 0;l-=1}else if(w[0][l]<w[1][l])return-1}},e.map=function(f,o){var c,h=[];if(Array.prototype.map)return Array.prototype.map.call(f,o);for(c=0;c<f.length;c+=1)h.push(o(f[c]));return h},e.find=function(f,o){var c,h;if(Array.prototype.find)return Array.prototype.find.call(f,o);for(c=0,h=f.length;c<h;c+=1){var u=f[c];if(o(u,c))return u}},e.assign=function(f){for(var o,c,h=f,u=arguments.length,l=Array(u>1?u-1:0),_=1;_<u;_++)l[_-1]=arguments[_];if(Object.assign)return Object.assign.apply(Object,[f].concat(l));var w=function(){var A=l[o];typeof A=="object"&&A!==null&&Object.keys(A).forEach(function(M){h[M]=A[M]})};for(o=0,c=l.length;o<c;o+=1)w();return f},e.getBrowserAlias=function(f){return i.BROWSER_ALIASES_MAP[f]},e.getBrowserTypeByAlias=function(f){return i.BROWSER_MAP[f]||""},e}();n.default=r,t.exports=n.default},18:function(t,n,s){n.__esModule=!0,n.ENGINE_MAP=n.OS_MAP=n.PLATFORMS_MAP=n.BROWSER_MAP=n.BROWSER_ALIASES_MAP=void 0,n.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"},n.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"},n.PLATFORMS_MAP={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},n.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"},n.ENGINE_MAP={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"}},90:function(t,n,s){n.__esModule=!0,n.default=void 0;var i,r=(i=s(91))&&i.__esModule?i:{default:i},e=s(18);function f(c,h){for(var u=0;u<h.length;u++){var l=h[u];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(c,l.key,l)}}var o=function(){function c(){}var h,u,l;return c.getParser=function(_,w,A){if(w===void 0&&(w=!1),A===void 0&&(A=null),typeof _!="string")throw Error("UserAgent should be a string");return new r.default(_,w,A)},c.parse=function(_,w){return w===void 0&&(w=null),new r.default(_,w).getResult()},h=c,l=[{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}}],(u=null)&&f(h.prototype,u),l&&f(h,l),c}();n.default=o,t.exports=n.default},91:function(t,n,s){n.__esModule=!0,n.default=void 0;var i=c(s(92)),r=c(s(93)),e=c(s(94)),f=c(s(95)),o=c(s(17));function c(u){return u&&u.__esModule?u:{default:u}}var h=function(){function u(_,w,A){if(w===void 0&&(w=!1),A===void 0&&(A=null),_==null||_==="")throw Error("UserAgent parameter can't be empty");this._ua=_;var M=!1;typeof w=="boolean"?(M=w,this._hints=A):this._hints=w!=null&&typeof w=="object"?w:null,this.parsedResult={},M!==!0&&this.parse()}var l=u.prototype;return l.getHints=function(){return this._hints},l.hasBrand=function(_){if(!this._hints||!Array.isArray(this._hints.brands))return!1;var w=_.toLowerCase();return this._hints.brands.some(function(A){return A.brand&&A.brand.toLowerCase()===w})},l.getBrandVersion=function(_){if(this._hints&&Array.isArray(this._hints.brands)){var w=_.toLowerCase(),A=this._hints.brands.find(function(M){return M.brand&&M.brand.toLowerCase()===w});return A?A.version:void 0}},l.getUA=function(){return this._ua},l.test=function(_){return _.test(this._ua)},l.parseBrowser=function(){var _=this;this.parsedResult.browser={};var w=o.default.find(i.default,function(A){if(typeof A.test=="function")return A.test(_);if(Array.isArray(A.test))return A.test.some(function(M){return _.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.browser=w.describe(this.getUA(),this)),this.parsedResult.browser},l.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},l.getBrowserName=function(_){return _?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},l.getBrowserVersion=function(){return this.getBrowser().version},l.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},l.parseOS=function(){var _=this;this.parsedResult.os={};var w=o.default.find(r.default,function(A){if(typeof A.test=="function")return A.test(_);if(Array.isArray(A.test))return A.test.some(function(M){return _.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.os=w.describe(this.getUA())),this.parsedResult.os},l.getOSName=function(_){var w=this.getOS().name;return _?String(w).toLowerCase()||"":w||""},l.getOSVersion=function(){return this.getOS().version},l.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},l.getPlatformType=function(_){_===void 0&&(_=!1);var w=this.getPlatform().type;return _?String(w).toLowerCase()||"":w||""},l.parsePlatform=function(){var _=this;this.parsedResult.platform={};var w=o.default.find(e.default,function(A){if(typeof A.test=="function")return A.test(_);if(Array.isArray(A.test))return A.test.some(function(M){return _.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.platform=w.describe(this.getUA())),this.parsedResult.platform},l.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},l.getEngineName=function(_){return _?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},l.parseEngine=function(){var _=this;this.parsedResult.engine={};var w=o.default.find(f.default,function(A){if(typeof A.test=="function")return A.test(_);if(Array.isArray(A.test))return A.test.some(function(M){return _.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.engine=w.describe(this.getUA())),this.parsedResult.engine},l.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},l.getResult=function(){return o.default.assign({},this.parsedResult)},l.satisfies=function(_){var w=this,A={},M=0,d={},E=0;if(Object.keys(_).forEach(function(J){var G=_[J];typeof G=="string"?(d[J]=G,E+=1):typeof G=="object"&&(A[J]=G,M+=1)}),M>0){var T=Object.keys(A),U=o.default.find(T,function(J){return w.isOS(J)});if(U){var S=this.satisfies(A[U]);if(S!==void 0)return S}var y=o.default.find(T,function(J){return w.isPlatform(J)});if(y){var D=this.satisfies(A[y]);if(D!==void 0)return D}}if(E>0){var q=Object.keys(d),tt=o.default.find(q,function(J){return w.isBrowser(J,!0)});if(tt!==void 0)return this.compareVersion(d[tt])}},l.isBrowser=function(_,w){w===void 0&&(w=!1);var A=this.getBrowserName().toLowerCase(),M=_.toLowerCase(),d=o.default.getBrowserTypeByAlias(M);return w&&d&&(M=d.toLowerCase()),M===A},l.compareVersion=function(_){var w=[0],A=_,M=!1,d=this.getBrowserVersion();if(typeof d=="string")return _[0]===">"||_[0]==="<"?(A=_.substr(1),_[1]==="="?(M=!0,A=_.substr(2)):w=[],_[0]===">"?w.push(1):w.push(-1)):_[0]==="="?A=_.substr(1):_[0]==="~"&&(M=!0,A=_.substr(1)),w.indexOf(o.default.compareVersions(d,A,M))>-1},l.isOS=function(_){return this.getOSName(!0)===String(_).toLowerCase()},l.isPlatform=function(_){return this.getPlatformType(!0)===String(_).toLowerCase()},l.isEngine=function(_){return this.getEngineName(!0)===String(_).toLowerCase()},l.is=function(_,w){return w===void 0&&(w=!1),this.isBrowser(_,w)||this.isOS(_)||this.isPlatform(_)},l.some=function(_){var w=this;return _===void 0&&(_=[]),_.some(function(A){return w.is(A)})},u}();n.default=h,t.exports=n.default},92:function(t,n,s){n.__esModule=!0,n.default=void 0;var i,r=(i=s(17))&&i.__esModule?i:{default:i},e=/version\/(\d+(\.?_?\d+)+)/i,f=[{test:[/gptbot/i],describe:function(o){var c={name:"GPTBot"},h=r.default.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/chatgpt-user/i],describe:function(o){var c={name:"ChatGPT-User"},h=r.default.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/oai-searchbot/i],describe:function(o){var c={name:"OAI-SearchBot"},h=r.default.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(o){var c={name:"ClaudeBot"},h=r.default.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(o){var c={name:"Omgilibot"},h=r.default.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/diffbot/i],describe:function(o){var c={name:"Diffbot"},h=r.default.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/perplexitybot/i],describe:function(o){var c={name:"PerplexityBot"},h=r.default.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/perplexity-user/i],describe:function(o){var c={name:"Perplexity-User"},h=r.default.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/youbot/i],describe:function(o){var c={name:"YouBot"},h=r.default.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/meta-webindexer/i],describe:function(o){var c={name:"Meta-WebIndexer"},h=r.default.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/meta-externalads/i],describe:function(o){var c={name:"Meta-ExternalAds"},h=r.default.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/meta-externalagent/i],describe:function(o){var c={name:"Meta-ExternalAgent"},h=r.default.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/meta-externalfetcher/i],describe:function(o){var c={name:"Meta-ExternalFetcher"},h=r.default.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/googlebot/i],describe:function(o){var c={name:"Googlebot"},h=r.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/linespider/i],describe:function(o){var c={name:"Linespider"},h=r.default.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/amazonbot/i],describe:function(o){var c={name:"AmazonBot"},h=r.default.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/bingbot/i],describe:function(o){var c={name:"BingCrawler"},h=r.default.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/baiduspider/i],describe:function(o){var c={name:"BaiduSpider"},h=r.default.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/duckduckbot/i],describe:function(o){var c={name:"DuckDuckBot"},h=r.default.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/ia_archiver/i],describe:function(o){var c={name:"InternetArchiveCrawler"},h=r.default.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(o){var c={name:"SlackBot"},h=r.default.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),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(o){var c={name:"Opera"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/opr\/|opios/i],describe:function(o){var c={name:"Opera"},h=r.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/SamsungBrowser/i],describe:function(o){var c={name:"Samsung Internet for Android"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/Whale/i],describe:function(o){var c={name:"NAVER Whale Browser"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/PaleMoon/i],describe:function(o){var c={name:"Pale Moon"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/MZBrowser/i],describe:function(o){var c={name:"MZ Browser"},h=r.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/focus/i],describe:function(o){var c={name:"Focus"},h=r.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/swing/i],describe:function(o){var c={name:"Swing"},h=r.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/coast/i],describe:function(o){var c={name:"Opera Coast"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(o){var c={name:"Opera Touch"},h=r.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/yabrowser/i],describe:function(o){var c={name:"Yandex Browser"},h=r.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/ucbrowser/i],describe:function(o){var c={name:"UC Browser"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/Maxthon|mxios/i],describe:function(o){var c={name:"Maxthon"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/epiphany/i],describe:function(o){var c={name:"Epiphany"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/puffin/i],describe:function(o){var c={name:"Puffin"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/sleipnir/i],describe:function(o){var c={name:"Sleipnir"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/k-meleon/i],describe:function(o){var c={name:"K-Meleon"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/micromessenger/i],describe:function(o){var c={name:"WeChat"},h=r.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/qqbrowser/i],describe:function(o){var c={name:/qqbrowserlite/i.test(o)?"QQ Browser Lite":"QQ Browser"},h=r.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/msie|trident/i],describe:function(o){var c={name:"Internet Explorer"},h=r.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/\sedg\//i],describe:function(o){var c={name:"Microsoft Edge"},h=r.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/edg([ea]|ios)/i],describe:function(o){var c={name:"Microsoft Edge"},h=r.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/vivaldi/i],describe:function(o){var c={name:"Vivaldi"},h=r.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/seamonkey/i],describe:function(o){var c={name:"SeaMonkey"},h=r.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/sailfish/i],describe:function(o){var c={name:"Sailfish"},h=r.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,o);return h&&(c.version=h),c}},{test:[/silk/i],describe:function(o){var c={name:"Amazon Silk"},h=r.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/phantom/i],describe:function(o){var c={name:"PhantomJS"},h=r.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/slimerjs/i],describe:function(o){var c={name:"SlimerJS"},h=r.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(o){var c={name:"BlackBerry"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/(web|hpw)[o0]s/i],describe:function(o){var c={name:"WebOS Browser"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/bada/i],describe:function(o){var c={name:"Bada"},h=r.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/tizen/i],describe:function(o){var c={name:"Tizen"},h=r.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/qupzilla/i],describe:function(o){var c={name:"QupZilla"},h=r.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/librewolf/i],describe:function(o){var c={name:"LibreWolf"},h=r.default.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/firefox|iceweasel|fxios/i],describe:function(o){var c={name:"Firefox"},h=r.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/electron/i],describe:function(o){var c={name:"Electron"},h=r.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe:function(o){var c={name:"Sogou Browser"},h=r.default.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,o),u=r.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,o),l=r.default.getFirstMatch(/se ([\d.]+)x/i,o),_=h||u||l;return _&&(c.version=_),c}},{test:[/MiuiBrowser/i],describe:function(o){var c={name:"Miui"},h=r.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){return!!o.hasBrand("DuckDuckGo")||o.test(/\sDdg\/[\d.]+$/i)},describe:function(o,c){var h={name:"DuckDuckGo"};if(c){var u=c.getBrandVersion("DuckDuckGo");if(u)return h.version=u,h}var l=r.default.getFirstMatch(/\sDdg\/([\d.]+)$/i,o);return l&&(h.version=l),h}},{test:function(o){return o.hasBrand("Brave")},describe:function(o,c){var h={name:"Brave"};if(c){var u=c.getBrandVersion("Brave");if(u)return h.version=u,h}return h}},{test:[/chromium/i],describe:function(o){var c={name:"Chromium"},h=r.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/chrome|crios|crmo/i],describe:function(o){var c={name:"Chrome"},h=r.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/GSA/i],describe:function(o){var c={name:"Google Search"},h=r.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){var c=!o.test(/like android/i),h=o.test(/android/i);return c&&h},describe:function(o){var c={name:"Android Browser"},h=r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/playstation 4/i],describe:function(o){var c={name:"PlayStation 4"},h=r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/safari|applewebkit/i],describe:function(o){var c={name:"Safari"},h=r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/.*/i],describe:function(o){var c=o.search("\\(")!==-1?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:r.default.getFirstMatch(c,o),version:r.default.getSecondMatch(c,o)}}}];n.default=f,t.exports=n.default},93:function(t,n,s){n.__esModule=!0,n.default=void 0;var i,r=(i=s(17))&&i.__esModule?i:{default:i},e=s(18),f=[{test:[/Roku\/DVP/],describe:function(o){var c=r.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,o);return{name:e.OS_MAP.Roku,version:c}}},{test:[/windows phone/i],describe:function(o){var c=r.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.WindowsPhone,version:c}}},{test:[/windows /i],describe:function(o){var c=r.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,o),h=r.default.getWindowsVersionName(c);return{name:e.OS_MAP.Windows,version:c,versionName:h}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(o){var c={name:e.OS_MAP.iOS},h=r.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,o);return h&&(c.version=h),c}},{test:[/macintosh/i],describe:function(o){var c=r.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,o).replace(/[_\s]/g,"."),h=r.default.getMacOSVersionName(c),u={name:e.OS_MAP.MacOS,version:c};return h&&(u.versionName=h),u}},{test:[/(ipod|iphone|ipad)/i],describe:function(o){var c=r.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,o).replace(/[_\s]/g,".");return{name:e.OS_MAP.iOS,version:c}}},{test:[/OpenHarmony/i],describe:function(o){var c=r.default.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.HarmonyOS,version:c}}},{test:function(o){var c=!o.test(/like android/i),h=o.test(/android/i);return c&&h},describe:function(o){var c=r.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,o),h=r.default.getAndroidVersionName(c),u={name:e.OS_MAP.Android,version:c};return h&&(u.versionName=h),u}},{test:[/(web|hpw)[o0]s/i],describe:function(o){var c=r.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,o),h={name:e.OS_MAP.WebOS};return c&&c.length&&(h.version=c),h}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(o){var c=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:c}}},{test:[/bada/i],describe:function(o){var c=r.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.Bada,version:c}}},{test:[/tizen/i],describe:function(o){var c=r.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.Tizen,version:c}}},{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 c=r.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.PlayStation4,version:c}}}];n.default=f,t.exports=n.default},94:function(t,n,s){n.__esModule=!0,n.default=void 0;var i,r=(i=s(17))&&i.__esModule?i:{default:i},e=s(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 c=r.default.getFirstMatch(/(can-l01)/i,o)&&"Nova",h={type:e.PLATFORMS_MAP.mobile,vendor:"Huawei"};return c&&(h.model=c),h}},{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 c=o.test(/ipod|iphone/i),h=o.test(/like (ipod|iphone)/i);return c&&!h},describe:function(o){var c=r.default.getFirstMatch(/(ipod|iphone)/i,o);return{type:e.PLATFORMS_MAP.mobile,vendor:"Apple",model:c}}},{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 c=r.default.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,o),h={type:e.PLATFORMS_MAP.mobile,vendor:"Nokia"};return c&&(h.model=c),h}},{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 c=Number(String(o.getOSVersion()).split(".")[0]);return o.getOSName(!0)==="android"&&c>=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}}}];n.default=f,t.exports=n.default},95:function(t,n,s){n.__esModule=!0,n.default=void 0;var i,r=(i=s(17))&&i.__esModule?i:{default:i},e=s(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 c=r.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,o);return{name:e.ENGINE_MAP.EdgeHTML,version:c}}},{test:[/trident/i],describe:function(o){var c={name:e.ENGINE_MAP.Trident},h=r.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){return o.test(/presto/i)},describe:function(o){var c={name:e.ENGINE_MAP.Presto},h=r.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){var c=o.test(/gecko/i),h=o.test(/like gecko/i);return c&&!h},describe:function(o){var c={name:e.ENGINE_MAP.Gecko},h=r.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:e.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(o){var c={name:e.ENGINE_MAP.WebKit},h=r.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}}];n.default=f,t.exports=n.default}})})});var xt=Z((XO)=>{var{Retry:jy,RETRY_MODES:Nw}=vi(),{HttpRequest:Pc,parseUrl:ay}=Ut(),{InvokeStore:Ww}=bw(),{normalizeProvider:py}=kn(),{platform:Zy,release:vy}=nt("os"),{versions:Oc,env:Dw}=nt("process"),{isValidHostLabel:tO,isIpAddress:kw,customEndpointFunctions:nO}=fs(),{EndpointError:sO,resolveEndpoint:iO}=fs();XO.EndpointError=sO;XO.isIpAddress=kw;XO.resolveEndpoint=iO;var{loadConfig:rO,NODE_REGION_CONFIG_OPTIONS:zw,NODE_REGION_CONFIG_FILE_OPTIONS:Xw}=St(),{REGION_ENV_NAME:eO,REGION_INI_NAME:oO,resolveRegionConfig:fO}=St();XO.NODE_REGION_CONFIG_FILE_OPTIONS=Xw;XO.NODE_REGION_CONFIG_OPTIONS=zw;XO.REGION_ENV_NAME=eO;XO.REGION_INI_NAME=oO;XO.resolveRegionConfig=fO;var Le={warningEmitted:!1},cO=(t)=>{if(t&&!Le.warningEmitted){if(process.env.AWS_SDK_JS_NODE_VERSION_SUPPORT_WARNING_DISABLED==="true"){Le.warningEmitted=!0;return}let n=parseInt(t.substring(1,t.indexOf("."))),s=22;if(n<s)Le.warningEmitted=!0,process.emitWarning(`NodeVersionSupportWarning: The AWS SDK for JavaScript (v3)
|
|
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
|
+
`).slice(0,5).filter((t)=>!t.includes("stackTraceWarning")).join(`
|
|
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)
|
|
24
25
|
versions published after the first week of January 2027
|
|
25
|
-
will require node >=${
|
|
26
|
+
will require node >=${i}. You are running node ${n}.
|
|
26
27
|
|
|
27
28
|
To continue receiving updates to AWS services, bug fixes,
|
|
28
|
-
and security updates please upgrade to node >=${
|
|
29
|
+
and security updates please upgrade to node >=${i}.
|
|
29
30
|
|
|
30
|
-
More information can be found at: https://a.co/c895JFp`)}},hO=()=>(t,n)=>async(s)=>{return n.__retryLongPoll=!0,t(s)},uO={name:"longPollMiddleware",tags:["RETRY"],step:"initialize",override:!0},lO=(t)=>({applyToStack:(n)=>{n.add(hO(),uO)}});function _O(t,n,s){if(!t.$source)t.$source={};return t.$source[n]=s,t}jy.v2026||=typeof process==="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function fn(t,n,s){if(!t.__aws_sdk_context)t.__aws_sdk_context={features:{}};else if(!t.__aws_sdk_context.features)t.__aws_sdk_context.features={};t.__aws_sdk_context.features[n]=s}function wO(t,n,s){if(!t.$source)t.$source={};return t.$source[n]=s,t}function AO(t){return t}var xw=(t)=>(n)=>async(s)=>{if(!Pc.isInstance(s.request))return n(s);let{request:i}=s,{handlerProtocol:r=""}=t.requestHandler.metadata||{};if(r.indexOf("h2")>=0&&!i.headers[":authority"])delete i.headers.host,i.headers[":authority"]=i.hostname+(i.port?":"+i.port:"");else if(!i.headers.host){let e=i.hostname;if(i.port!=null)e+=`:${i.port}`;i.headers.host=e}return n(s)},qw={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},MO=(t)=>({applyToStack:(n)=>{n.add(xw(t),qw)}}),Cw=()=>(t,n)=>async(s)=>{try{let i=await t(s),{clientName:r,commandName:e,logger:f,dynamoDbDocumentClientOptions:o={}}=n,{overrideInputFilterSensitiveLog:c,overrideOutputFilterSensitiveLog:h}=o,u=c??n.inputFilterSensitiveLog,l=h??n.outputFilterSensitiveLog,{$metadata:_,...w}=i.output;return f?.info?.({clientName:r,commandName:e,input:u(s.input),output:l(w),metadata:_}),i}catch(i){let{clientName:r,commandName:e,logger:f,dynamoDbDocumentClientOptions:o={}}=n,{overrideInputFilterSensitiveLog:c}=o,h=c??n.inputFilterSensitiveLog;throw f?.error?.({clientName:r,commandName:e,input:h(s.input),error:i,metadata:i.$metadata}),i}},Kw={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},gO=(t)=>({applyToStack:(n)=>{n.add(Cw(),Kw)}}),Vw={step:"build",tags:["RECURSION_DETECTION","TRACE_CONTEXT_PROPAGATION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},dO="AWS_LAMBDA_FUNCTION_NAME",EO="_X_AMZN_TRACE_ID",Gc="X-Amzn-Trace-Id",Hc="traceparent",jw="tracestate",aw="baggage",pw=()=>(t)=>async(n)=>{let{request:s}=n;if(!Pc.isInstance(s))return t(n);let i;{let r=Object.keys(s.headers??{}).find((e)=>e.toLowerCase()===Gc.toLowerCase())??Gc;if(!s.headers.hasOwnProperty(r)){let e=process.env[dO],f=process.env[EO];i??=await Ww.getInstanceAsync();let c=i?.getXRayTraceId()??f,h=(u)=>typeof u==="string"&&u.length>0;if(h(e)&&h(c))s.headers[Gc]=c}}if(RO(s.headers),!s.headers[Hc]){let e=(i??=await Ww.getInstanceAsync())?.getTraceparent?.();if(e){s.headers[Hc]=e;let f=i?.getTracestate?.();if(f)s.headers[jw]=f;let o=i?.getBaggage?.();if(o)s.headers[aw]=o}}return t(n)};function RO(t){for(let n of Object.keys(t)){let s=n.toLowerCase();if(n!==s&&(s===Hc||s===jw||s===aw))t[s]=t[n],delete t[n]}}var bO=(t)=>({applyToStack:(n)=>{n.add(pw(),Vw)}}),Nc=void 0;function TO(t){if(t===void 0)return!0;return typeof t==="string"&&t.length<=50}function SO(t){let n=py(t.userAgentAppId??Nc),{customUserAgent:s}=t;return Object.assign(t,{customUserAgent:typeof s==="string"?[[s]]:s,userAgentAppId:async()=>{let i=await n();if(!TO(i)){let r=t.logger?.constructor?.name==="NoOpLogger"||!t.logger?console:t.logger;if(typeof i!=="string")r?.warn("userAgentAppId must be a string or undefined.");else if(i.length>50)r?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return i}})}var Zw={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"},vw=Zw,tA="",nA=(t)=>{let{partitions:n}=vw;for(let i of n){let{regions:r,outputs:e}=i;for(let[f,o]of Object.entries(r))if(f===t)return{...e,...o}}for(let i of n){let{regionRegex:r,outputs:e}=i;if(new RegExp(r).test(t))return{...e}}let s=n.find((i)=>i.id==="aws");if(!s)throw Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...s.outputs}},sA=(t,n="")=>{vw=t,tA=n},$O=()=>{sA(Zw,"")},iA=()=>tA,UO=/\d{12}\.ddb/;async function LO(t,n,s){if(s.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor")fn(t,"PROTOCOL_RPC_V2_CBOR","M");if(typeof n.retryStrategy==="function"){let e=await n.retryStrategy();if(typeof e.mode==="string")switch(e.mode){case Nw.ADAPTIVE:fn(t,"RETRY_MODE_ADAPTIVE","F");break;case Nw.STANDARD:fn(t,"RETRY_MODE_STANDARD","E");break}}if(typeof n.accountIdEndpointMode==="function"){let e=t.endpointV2;if(String(e?.url?.hostname).match(UO))fn(t,"ACCOUNT_ID_ENDPOINT","O");switch(await n.accountIdEndpointMode?.()){case"disabled":fn(t,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":fn(t,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":fn(t,"ACCOUNT_ID_MODE_REQUIRED","R");break}}let r=t.__smithy_context?.selectedHttpAuthScheme?.identity;if(r?.$source){let e=r;if(e.accountId)fn(t,"RESOLVED_ACCOUNT_ID","T");for(let[f,o]of Object.entries(e.$source??{}))fn(t,f,o)}}var mw="user-agent",Bc="x-amz-user-agent",Yw=" ",Fc="/",IO=/[^!$%&'*+\-.^_`|~\w]/g,yO=/[^!$%&'*+\-.^_`|~\w#]/g,Qw="-",OO=1024;function GO(t){let n="";for(let s in t){let i=t[s];if(n.length+i.length+1<=OO){if(n.length)n+=","+i;else n+=i;continue}break}return n}var rA=(t)=>(n,s)=>async(i)=>{let{request:r}=i;if(!Pc.isInstance(r))return n(i);let{headers:e}=r,f=s?.userAgent?.map(Ue)||[],o=(await t.defaultUserAgentProvider()).map(Ue);await LO(s,t,i);let c=s;o.push(`m/${GO(Object.assign({},s.__smithy_context?.features,c.__aws_sdk_context?.features))}`);let h=t?.customUserAgent?.map(Ue)||[],u=await t.userAgentAppId();if(u)o.push(Ue(["app",`${u}`]));let l=iA(),_=(l?[l]:[]).concat([...o,...f,...h]).join(Yw),w=[...o.filter((A)=>A.startsWith("aws-sdk-")),...h].join(Yw);if(t.runtime!=="browser"){if(w)e[Bc]=e[Bc]?`${e[mw]} ${w}`:w;e[mw]=_}else e[Bc]=_;return n({...i,request:r})},Ue=(t)=>{let n=t[0].split(Fc).map((f)=>f.replace(IO,Qw)).join(Fc),s=t[1]?.replace(yO,Qw),i=n.indexOf(Fc),r=n.substring(0,i),e=n.substring(i+1);if(r==="api")e=e.toLowerCase();return[r,e,s].filter((f)=>f&&f.length>0).reduce((f,o,c)=>{switch(c){case 0:return o;case 1:return`${f}/${o}`;default:return`${f}#${o}`}},"")},eA={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},BO=(t)=>({applyToStack:(n)=>{n.add(rA(t),eA)}}),FO=()=>{let t=["deno","bun","llrt"];for(let n of t)if(Oc[n])return[`md/${n}`,Oc[n]];return["md/nodejs",Oc.node]},oA={isCrtAvailable:!1},HO=()=>{if(oA.isCrtAvailable)return["md/crt-avail"];return null},fA=({serviceId:t,clientVersion:n})=>{let s=FO();return async(i)=>{let r=[["aws-sdk-js",n],["ua","2.1"],[`os/${Zy()}`,vy()],["lang/js"],s],e=HO();if(e)r.push(e);if(t)r.push([`api/${t}`,n]);if(Dw.AWS_EXECUTION_ENV)r.push([`exec-env/${Dw.AWS_EXECUTION_ENV}`]);let f=await i?.userAgentAppId?.();return f?[...r,[`app/${f}`]]:[...r]}},PO=fA,cA="AWS_SDK_UA_APP_ID",hA="sdk_ua_app_id",NO="sdk-ua-app-id",WO={environmentVariableSelector:(t)=>t[cA],configFileSelector:(t)=>t[hA]??t[NO],default:Nc},DO=({serviceId:t,clientVersion:n})=>async(s)=>{let i=Pw(),r=i.parse??i.default.parse??(()=>""),e=typeof window<"u"&&window?.navigator?.userAgent?r(window.navigator.userAgent):void 0,f=[["aws-sdk-js",n],["ua","2.1"],[`os/${e?.os?.name||"other"}`,e?.os?.version],["lang/js"],["md/browser",`${e?.browser?.name??"unknown"}_${e?.browser?.version??"unknown"}`]];if(t)f.push([`api/${t}`,n]);let o=await s?.userAgentAppId?.();if(o)f.push([`app/${o}`]);return f},mO={os(t){if(/iPhone|iPad|iPod/.test(t))return"iOS";if(/Macintosh|Mac OS X/.test(t))return"macOS";if(/Windows NT/.test(t))return"Windows";if(/Android/.test(t))return"Android";if(/Linux/.test(t))return"Linux";return},browser(t){if(/EdgiOS|EdgA|Edg\//.test(t))return"Microsoft Edge";if(/Firefox\//.test(t))return"Firefox";if(/Chrome\//.test(t))return"Chrome";if(/Safari\//.test(t))return"Safari";return}},Wc=(t,n=!1)=>{if(n){for(let s of t.split("."))if(!Wc(s))return!1;return!0}if(!tO(t))return!1;if(t.length<3||t.length>63)return!1;if(t!==t.toLowerCase())return!1;if(kw(t))return!1;return!0},Jw=":",YO="/",uA=(t)=>{let n=t.split(Jw);if(n.length<6)return null;let[s,i,r,e,f,...o]=n;if(s!=="arn"||i===""||r===""||o.join(Jw)==="")return null;let c=o.map((h)=>h.split(YO)).flat();return{partition:i,service:r,region:e,accountId:f,resourceId:c}},lA={isVirtualHostableS3Bucket:Wc,parseArn:uA,partition:nA};nO.aws=lA;var QO=(t)=>{if(typeof t.endpointProvider!=="function")throw Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client.");let{endpoint:n}=t;if(n===void 0)t.endpoint=async()=>{return _A(t.endpointProvider({Region:typeof t.region==="function"?await t.region():t.region,UseDualStack:typeof t.useDualstackEndpoint==="function"?await t.useDualstackEndpoint():t.useDualstackEndpoint,UseFIPS:typeof t.useFipsEndpoint==="function"?await t.useFipsEndpoint():t.useFipsEndpoint,Endpoint:void 0},{logger:t.logger}))};return t},_A=(t)=>ay(t.url);function JO(t={}){return rO({...zw,async default(){if(!wA.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"}},{...Xw,...t})}var wA={silence:!1},kO=(t)=>{return{setRegion(n){t.region=n},region(){return t.region}}},zO=(t)=>{return{region:t.region()}};XO.DEFAULT_UA_APP_ID=Nc;XO.NODE_APP_ID_CONFIG_OPTIONS=WO;XO.UA_APP_ID_ENV_NAME=cA;XO.UA_APP_ID_INI_NAME=hA;XO.awsEndpointFunctions=lA;XO.createDefaultUserAgentProvider=fA;XO.createUserAgentStringParsingProvider=DO;XO.crtAvailability=oA;XO.defaultUserAgent=PO;XO.emitWarningIfUnsupportedVersion=cO;XO.fallback=mO;XO.getAwsRegionExtensionConfiguration=kO;XO.getHostHeaderPlugin=MO;XO.getLoggerPlugin=gO;XO.getLongPollPlugin=lO;XO.getRecursionDetectionPlugin=bO;XO.getUserAgentMiddlewareOptions=eA;XO.getUserAgentPlugin=BO;XO.getUserAgentPrefix=iA;XO.hostHeaderMiddleware=xw;XO.hostHeaderMiddlewareOptions=qw;XO.isVirtualHostableS3Bucket=Wc;XO.loggerMiddleware=Cw;XO.loggerMiddlewareOptions=Kw;XO.parseArn=uA;XO.partition=nA;XO.recursionDetectionMiddleware=pw;XO.recursionDetectionMiddlewareOptions=Vw;XO.resolveAwsRegionExtensionConfiguration=zO;XO.resolveDefaultAwsRegionalEndpointsConfig=QO;XO.resolveHostHeaderConfig=AO;XO.resolveUserAgentConfig=SO;XO.setCredentialFeature=_O;XO.setFeature=fn;XO.setPartitionInfo=sA;XO.setTokenFeature=wO;XO.state=Le;XO.stsRegionDefaultResolver=JO;XO.stsRegionWarning=wA;XO.toEndpointV1=_A;XO.useDefaultPartitionInfo=$O;XO.userAgentMiddleware=rA});var CA=Z((vG)=>{var{fromUtf8:bA,fromHex:zG,toHex:_s,toUint8Array:rr,isArrayBuffer:XG}=$t(),{normalizeProvider:TA}=Rn(),{escapeUri:Ie,HttpRequest:UA}=Ut();class LA{format(t){let n=[];for(let r of Object.keys(t)){let e=bA(r);n.push(Uint8Array.from([e.byteLength]),e,this.formatHeaderValue(t[r]))}let s=new Uint8Array(n.reduce((r,e)=>r+e.byteLength,0)),i=0;for(let r of n)s.set(r,i),i+=r.byteLength;return s}formatHeaderValue(t){switch(t.type){case"boolean":return Uint8Array.from([t.value?Wt.boolTrue:Wt.boolFalse]);case"byte":return Uint8Array.from([Wt.byte,t.value]);case"short":let n=new DataView(new ArrayBuffer(3));return n.setUint8(0,Wt.short),n.setInt16(1,t.value,!1),new Uint8Array(n.buffer);case"integer":let s=new DataView(new ArrayBuffer(5));return s.setUint8(0,Wt.integer),s.setInt32(1,t.value,!1),new Uint8Array(s.buffer);case"long":let i=new Uint8Array(9);return i[0]=Wt.long,i.set(t.value.bytes,1),i;case"binary":let r=new DataView(new ArrayBuffer(3+t.value.byteLength));r.setUint8(0,Wt.byteArray),r.setUint16(1,t.value.byteLength,!1);let e=new Uint8Array(r.buffer);return e.set(t.value,3),e;case"string":let f=bA(t.value),o=new DataView(new ArrayBuffer(3+f.byteLength));o.setUint8(0,Wt.string),o.setUint16(1,f.byteLength,!1);let c=new Uint8Array(o.buffer);return c.set(f,3),c;case"timestamp":let h=new Uint8Array(9);return h[0]=Wt.timestamp,h.set(Qc.fromNumber(t.value.valueOf()).bytes,1),h;case"uuid":if(!xG.test(t.value))throw Error(`Invalid UUID received: ${t.value}`);let u=new Uint8Array(17);return u[0]=Wt.uuid,u.set(zG(t.value.replace(/-/g,"")),1),u}}}var Wt;(function(t){t[t.boolTrue=0]="boolTrue",t[t.boolFalse=1]="boolFalse",t[t.byte=2]="byte",t[t.short=3]="short",t[t.integer=4]="integer",t[t.long=5]="long",t[t.byteArray=6]="byteArray",t[t.string=7]="string",t[t.timestamp=8]="timestamp",t[t.uuid=9]="uuid"})(Wt||(Wt={}));var xG=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class Qc{bytes;constructor(t){if(this.bytes=t,t.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(t){if(t>9223372036854776000||t<-9223372036854776000)throw Error(`${t} is too large (or, if negative, too small) to represent as an Int64`);let n=new Uint8Array(8);for(let s=7,i=Math.abs(Math.round(t));s>-1&&i>0;s--,i/=256)n[s]=i;if(t<0)SA(n);return new Qc(n)}valueOf(){let t=this.bytes.slice(0),n=t[0]&128;if(n)SA(t);return parseInt(_s(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}}function SA(t){for(let n=0;n<8;n++)t[n]^=255;for(let n=7;n>-1;n--)if(t[n]++,t[n]!==0)break}var IA="X-Amz-Algorithm",yA="X-Amz-Credential",Jc="X-Amz-Date",OA="X-Amz-SignedHeaders",GA="X-Amz-Expires",kc="X-Amz-Signature",zc="X-Amz-Security-Token",qG="X-Amz-Region-Set",Xc="authorization",xc=Jc.toLowerCase(),BA="date",FA=[Xc,xc,BA],HA=kc.toLowerCase(),Fe="x-amz-content-sha256",PA=zc.toLowerCase(),CG="host",NA={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},WA=/^proxy-/,DA=/^sec-/,KG=[/^proxy-/i,/^sec-/i],ye="AWS4-HMAC-SHA256",VG="AWS4-ECDSA-P256-SHA256",mA="AWS4-HMAC-SHA256-PAYLOAD",YA="UNSIGNED-PAYLOAD",QA=50,qc="aws4_request",JA=604800,kA=({query:t={}})=>{let n=[],s={};for(let i of Object.keys(t)){if(i.toLowerCase()===HA)continue;let r=Ie(i);n.push(r);let e=t[i];if(typeof e==="string")s[r]=`${r}=${Ie(e)}`;else if(Array.isArray(e))s[r]=e.slice(0).reduce((f,o)=>f.concat([`${r}=${Ie(o)}`]),[]).sort().join("&")}return n.sort().map((i)=>s[i]).filter((i)=>i).join("&")},jG=(t)=>aG(t).toISOString().replace(/\.\d{3}Z$/,"Z"),aG=(t)=>{if(typeof t==="number")return new Date(t*1000);if(typeof t==="string"){if(Number(t))return new Date(Number(t)*1000);return new Date(t)}return t};class Cc{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:t,credentials:n,region:s,service:i,sha256:r,uriEscapePath:e=!0}){this.service=i,this.sha256=r,this.uriEscapePath=e,this.applyChecksum=typeof t==="boolean"?t:!0,this.regionProvider=TA(s),this.credentialProvider=TA(n)}createCanonicalRequest(t,n,s){let i=Object.keys(n).sort();return`${t.method}
|
|
31
|
-
${this.getCanonicalPath(
|
|
32
|
-
${
|
|
33
|
-
${
|
|
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
|
+
${this.getCanonicalPath(n)}
|
|
33
|
+
${x1(n)}
|
|
34
|
+
${r.map((s)=>`${s}:${t[s]}`).join(`
|
|
34
35
|
`)}
|
|
35
36
|
|
|
36
|
-
${
|
|
37
|
-
${
|
|
38
|
-
${t}
|
|
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
|
-
${
|
|
41
|
-
`);return this.signString(A,{signingDate:s,signingRegion:o,signingService:e,eventStreamCredentials:f})}async signMessage(t,{signingDate:n=new Date,signingRegion:s,signingService:i,eventStreamCredentials:r}){return this.signEvent({headers:this.headerFormatter.format(t.message.headers),payload:t.message.body},{signingDate:n,signingRegion:s,signingService:i,priorSignature:t.priorSignature,eventStreamCredentials:r}).then((f)=>{return{message:t.message,signature:f}})}async signString(t,{signingDate:n=new Date,signingRegion:s,signingService:i,eventStreamCredentials:r}={}){let e=r??await this.credentialProvider();this.validateResolvedCredentials(e);let f=s??await this.regionProvider(),{shortDate:o}=this.formatDate(n),c=new this.sha256(await this.getSigningKey(e,f,o,i));return c.update(rr(t)),_s(await c.digest())}async signRequest(t,{signingDate:n=new Date,signableHeaders:s,unsignableHeaders:i,signingRegion:r,signingService:e}={}){let f=await this.credentialProvider();this.validateResolvedCredentials(f);let o=r??await this.regionProvider(),c=Yc(t),{longDate:h,shortDate:u}=this.formatDate(n),l=Ge(u,o,e??this.service);if(c.headers[xc]=h,f.sessionToken)c.headers[PA]=f.sessionToken;let _=await Be(c,this.sha256);if(!XA(Fe,c.headers)&&this.applyChecksum)c.headers[Fe]=_;let w=mc(c,i,s),A=await this.getSignature(h,l,this.getSigningKey(f,o,u,e),this.createCanonicalRequest(c,w,_));return c.headers[Xc]=`${ye} Credential=${f.accessKeyId}/${l}, SignedHeaders=${this.getCanonicalHeaderList(w)}, Signature=${A}`,c}async getSignature(t,n,s,i){let r=await this.createStringToSign(t,n,i,ye),e=new this.sha256(await s);return e.update(rr(r)),_s(await e.digest())}getSigningKey(t,n,s,i){return zA(this.sha256,t,s,n,i||this.service)}}var ZG={SignatureV4a:null};vG.ALGORITHM_IDENTIFIER=ye;vG.ALGORITHM_IDENTIFIER_V4A=VG;vG.ALGORITHM_QUERY_PARAM=IA;vG.ALWAYS_UNSIGNABLE_HEADERS=NA;vG.AMZ_DATE_HEADER=xc;vG.AMZ_DATE_QUERY_PARAM=Jc;vG.AUTH_HEADER=Xc;vG.CREDENTIAL_QUERY_PARAM=yA;vG.DATE_HEADER=BA;vG.EVENT_ALGORITHM_IDENTIFIER=mA;vG.EXPIRES_QUERY_PARAM=GA;vG.GENERATED_HEADERS=FA;vG.HOST_HEADER=CG;vG.KEY_TYPE_IDENTIFIER=qc;vG.MAX_CACHE_SIZE=QA;vG.MAX_PRESIGNED_TTL=JA;vG.PROXY_HEADER_PATTERN=WA;vG.REGION_SET_PARAM=qG;vG.SEC_HEADER_PATTERN=DA;vG.SHA256_HEADER=Fe;vG.SIGNATURE_HEADER=HA;vG.SIGNATURE_QUERY_PARAM=kc;vG.SIGNED_HEADERS_QUERY_PARAM=OA;vG.SignatureV4=qA;vG.SignatureV4Base=Cc;vG.TOKEN_HEADER=PA;vG.TOKEN_QUERY_PARAM=zc;vG.UNSIGNABLE_PATTERNS=KG;vG.UNSIGNED_PAYLOAD=YA;vG.clearCredentialCache=pG;vG.createScope=Ge;vG.getCanonicalHeaders=mc;vG.getCanonicalQuery=kA;vG.getPayloadHash=Be;vG.getSigningKey=zA;vG.hasHeader=XA;vG.moveHeadersToQuery=xA;vG.prepareRequest=Yc;vG.signatureV4aContainer=ZG});var jc=Z((ZB)=>{var{HttpResponse:QB,HttpRequest:tM}=Ut(),{normalizeProvider:er,memoizeIdentityProvider:JB,isIdentityExpired:kB,doesIdentityRequireRefresh:zB}=kn(),{ProviderError:KA}=St(),{setCredentialFeature:XB}=xt(),{SignatureV4:VA}=CA(),jA=(t)=>QB.isInstance(t)?t.headers?.date??t.headers?.Date:void 0,Kc=(t)=>new Date(Date.now()+t),xB=(t,n)=>Math.abs(Kc(n).getTime()-t)>=300000,aA=(t,n)=>{let s=Date.parse(t);if(xB(s,n))return s-Date.now();return n},or=(t,n)=>{if(!n)throw Error(`Property \`${t}\` is not resolved for AWS SDK SigV4Auth`);return n},Vc=async(t)=>{let n=or("context",t.context),s=or("config",t.config),i=n.endpointV2?.properties?.authSchemes?.[0],e=await or("signer",s.signer)(i),f=t?.signingRegion,o=t?.signingRegionSet,c=t?.signingName;return{config:s,signer:e,signingRegion:f,signingRegionSet:o,signingName:c}};class He{async sign(t,n,s){if(!tM.isInstance(t))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let i=await Vc(s),{config:r,signer:e}=i,{signingRegion:f,signingName:o}=i,c=s.context;if(c?.authSchemes?.length??!1){let[u,l]=c.authSchemes;if(u?.name==="sigv4a"&&l?.name==="sigv4")f=l?.signingRegion??f,o=l?.signingName??o}return s._preRequestSystemClockOffset=r.systemClockOffset,await e.sign(t,{signingDate:Kc(r.systemClockOffset),signingRegion:f,signingService:o})}errorHandler(t){return(n)=>{let s=n,i=s.ServerTime??jA(s.$response);if(i){let r=or("config",t.config),e=t._preRequestSystemClockOffset,f=aA(i,r.systemClockOffset);if((f!==r.systemClockOffset||e!==void 0&&e!==f)&&s.$metadata)r.systemClockOffset=f,s.$metadata.clockSkewCorrected=!0}throw n}}successHandler(t,n){let s=jA(t);if(s){let i=or("config",n.config);i.systemClockOffset=aA(s,i.systemClockOffset)}}}var qB=He;class nM extends He{async sign(t,n,s){if(!tM.isInstance(t))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let{config:i,signer:r,signingRegion:e,signingRegionSet:f,signingName:o}=await Vc(s),h=(await i.sigv4aSigningRegionSet?.()??f??[e]).join(",");return s._preRequestSystemClockOffset=i.systemClockOffset,await r.sign(t,{signingDate:Kc(i.systemClockOffset),signingRegion:h,signingService:o})}}var pA=(t)=>typeof t==="string"&&t.length>0?t.split(",").map((n)=>n.trim()):[],sM=(t)=>`AWS_BEARER_TOKEN_${t.replace(/[\s-]/g,"_").toUpperCase()}`,ZA="AWS_AUTH_SCHEME_PREFERENCE",vA="auth_scheme_preference",CB={environmentVariableSelector:(t,n)=>{if(n?.signingName){if(sM(n.signingName)in t)return["httpBearerAuth"]}if(!(ZA in t))return;return pA(t[ZA])},configFileSelector:(t)=>{if(!(vA in t))return;return pA(t[vA])},default:[]},KB=(t)=>{return t.sigv4aSigningRegionSet=er(t.sigv4aSigningRegionSet),t},VB={environmentVariableSelector(t){if(t.AWS_SIGV4A_SIGNING_REGION_SET)return t.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((n)=>n.trim());throw new KA("AWS_SIGV4A_SIGNING_REGION_SET not set in env.",{tryNextLink:!0})},configFileSelector(t){if(t.sigv4a_signing_region_set)return(t.sigv4a_signing_region_set??"").split(",").map((n)=>n.trim());throw new KA("sigv4a_signing_region_set not set in profile.",{tryNextLink:!0})},default:void 0},iM=(t)=>{let n=t.credentials,s=!!t.credentials,i=void 0;Object.defineProperty(t,"credentials",{set(h){if(h&&h!==n&&h!==i)s=!0;n=h;let u=aB(t,{credentials:n,credentialDefaultProvider:t.credentialDefaultProvider}),l=pB(t,u);if(s&&!l.attributed){let _=typeof n==="object"&&n!==null;i=async(w)=>{let M=await l(w);if(_&&(!M.$source||Object.keys(M.$source).length===0))return XB(M,"CREDENTIALS_CODE","e");return M},i.memoized=l.memoized,i.configBound=l.configBound,i.attributed=!0}else i=l},get(){return i},enumerable:!0,configurable:!0}),t.credentials=n;let{signingEscapePath:r=!0,systemClockOffset:e=t.systemClockOffset||0,sha256:f}=t,o;if(t.signer)o=er(t.signer);else if(t.regionInfoProvider)o=()=>er(t.region)().then(async(h)=>[await t.regionInfoProvider(h,{useFipsEndpoint:await t.useFipsEndpoint(),useDualstackEndpoint:await t.useDualstackEndpoint()})||{},h]).then(([h,u])=>{let{signingRegion:l,signingService:_}=h;t.signingRegion=t.signingRegion||l||u,t.signingName=t.signingName||_||t.serviceId;let w={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:f,uriEscapePath:r};return new(t.signerConstructor||VA)(w)});else o=async(h)=>{h=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:await er(t.region)(),properties:{}},h);let{signingRegion:u,signingName:l}=h;t.signingRegion=t.signingRegion||u,t.signingName=t.signingName||l||t.serviceId;let _={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:f,uriEscapePath:r};return new(t.signerConstructor||VA)(_)};return Object.assign(t,{systemClockOffset:e,signingEscapePath:r,signer:o})},jB=iM;function aB(t,{credentials:n,credentialDefaultProvider:s}){let i;if(n)if(!n?.memoized)i=JB(n,kB,zB);else i=n;else if(s)i=er(s(Object.assign({},t,{parentClientConfig:t})));else i=async()=>{throw Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")};return i.memoized=!0,i}function pB(t,n){if(n.configBound)return n;let s=async(i)=>n({...i,callerClientConfig:t});return s.memoized=n.memoized,s.configBound=!0,s}ZB.AWSSDKSigV4Signer=qB;ZB.AwsSdkSigV4ASigner=nM;ZB.AwsSdkSigV4Signer=He;ZB.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS=CB;ZB.NODE_SIGV4A_CONFIG_OPTIONS=VB;ZB.getBearerTokenEnvKey=sM;ZB.resolveAWSSDKSigV4Config=jB;ZB.resolveAwsSdkSigV4AConfig=KB;ZB.resolveAwsSdkSigV4Config=iM;ZB.validateSigningProperties=Vc});var Ye=Z((b3)=>{var{buildQueryString:uM,HttpResponse:lM}=Ut(),Pe=nt("https"),{Readable:h3}=nt("stream"),ac=nt("http2"),{streamCollector:u3}=$t();b3.streamCollector=u3;function We(t){let n=t&&typeof t==="object"&&"reason"in t?t.reason:void 0;if(n){if(n instanceof Error){let r=Error("Request aborted");return r.name="AbortError",r.cause=n,r}let i=Error(String(n));return i.name="AbortError",i}let s=Error("Request aborted");return s.name="AbortError",s}var l3=["ECONNRESET","EPIPE","ETIMEDOUT"],_M=(t)=>{let n={};for(let s in t){let i=t[s];n[s]=Array.isArray(i)?i.join(","):i}return n},Mt={setTimeout:(t,n)=>setTimeout(t,n),clearTimeout:(t)=>clearTimeout(t)},eM=1000,_3=(t,n,s=0)=>{if(!s)return-1;let i=(r)=>{let e=Mt.setTimeout(()=>{t.destroy(),n(Object.assign(Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${s} ms.`),{name:"TimeoutError"}))},s-r),f=(o)=>{if(o?.connecting)o.on("connect",()=>{Mt.clearTimeout(e)});else Mt.clearTimeout(e)};if(t.socket)f(t.socket);else t.on("socket",f)};if(s<2000)return i(0),0;return Mt.setTimeout(i.bind(null,eM),eM)},w3=(t,n,s=0,i,r)=>{if(s)return Mt.setTimeout(()=>{let e=`@smithy/node-http-handler - [${i?"ERROR":"WARN"}] a request has exceeded the configured ${s} ms requestTimeout.`;if(i){let f=Object.assign(Error(e),{name:"TimeoutError",code:"ETIMEDOUT"});t.destroy(f),n(f)}else e+=" Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.",r?.warn?.(e)},s);return-1},A3=3000,M3=(t,{keepAlive:n,keepAliveMsecs:s},i=A3)=>{if(n!==!0)return-1;let r=()=>{if(t.socket)t.socket.setKeepAlive(n,s||0);else t.on("socket",(e)=>{e.setKeepAlive(n,s||0)})};if(i===0)return r(),0;return Mt.setTimeout(r,i)},oM=3000,g3=(t,n,s=0)=>{let i=(r)=>{let e=s-r,f=()=>{t.destroy(),n(Object.assign(Error(`@smithy/node-http-handler - the request socket timed out after ${s} ms of inactivity (configured by client requestHandler).`),{name:"TimeoutError"}))};if(t.socket)t.socket.setTimeout(e,f),t.on("close",()=>t.socket?.removeListener("timeout",f));else t.setTimeout(e,f)};if(0<s&&s<6000)return i(0),0;return Mt.setTimeout(i.bind(null,s===0?0:oM),oM)},fM=6000;async function wM(t,n,s=fM,i=!1){let r=n.headers,e=r?r.Expect||r.expect:void 0,f=-1,o=!0;if(!i&&e==="100-continue")o=await Promise.race([new Promise((c)=>{f=Number(Mt.setTimeout(()=>c(!0),Math.max(fM,s)))}),new Promise((c)=>{t.on("continue",()=>{Mt.clearTimeout(f),c(!0)}),t.on("response",()=>{Mt.clearTimeout(f),c(!1)}),t.on("error",()=>{Mt.clearTimeout(f),c(!1)})})]);if(o)d3(t,n.body)}function d3(t,n){if(n instanceof h3){n.pipe(t);return}if(n){let s=Buffer.isBuffer(n);if(s||typeof n==="string"){if(s&&n.byteLength===0)t.end();else t.end(n);return}let r=n;if(typeof r==="object"&&r.buffer&&typeof r.byteOffset==="number"&&typeof r.byteLength==="number"){t.end(Buffer.from(r.buffer,r.byteOffset,r.byteLength));return}t.end(Buffer.from(n));return}t.end()}var E3=0,Ne=void 0,cM=void 0;class De{config;configProvider;socketWarningTimestamp=0;externalAgent=!1;metadata={handlerProtocol:"http/1.1"};static create(t){if(typeof t?.handle==="function")return t;return new De(t)}static checkSocketUsage(t,n,s=console){let{sockets:i,requests:r,maxSockets:e}=t;if(typeof e!=="number"||e===1/0)return n;let f=15000;if(Date.now()-f<n)return n;if(i&&r)for(let o in i){let c=i[o]?.length??0,h=r[o]?.length??0;if(c>=e&&h>=2*e)return s?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${c} and ${h} additional requests are enqueued.
|
|
40
|
+
${t}
|
|
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.
|
|
42
43
|
See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html
|
|
43
|
-
or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`),Date.now()}return n}constructor(t){this.configProvider=new Promise((n,s)=>{if(typeof t==="function")t().then((i)=>{n(this.resolveDefaultConfig(i))}).catch(s);else n(this.resolveDefaultConfig(t))})}destroy(){this.config?.httpAgent?.destroy(),this.config?.httpsAgent?.destroy()}async handle(t,{abortSignal:n,requestTimeout:s}={}){if(!this.config)this.config=await this.configProvider;let i=this.config,r=t.protocol==="https:";if(!r&&!this.config.httpAgent)this.config.httpAgent=await this.config.httpAgentProvider();return new Promise((e,f)=>{let o=void 0,c=-1,h=-1,u=-1,l=-1,_=-1,w=()=>{Mt.clearTimeout(c),Mt.clearTimeout(h),Mt.clearTimeout(u),Mt.clearTimeout(l),Mt.clearTimeout(_)},A=async(R)=>{await o,w(),e(R)},M=async(R)=>{await o,w(),f(R)};if(n?.aborted){let R=We(n);M(R);return}let d=t.headers,E=d?(d.Expect??d.expect)==="100-continue":!1,T=r?i.httpsAgent:i.httpAgent;if(E&&!this.externalAgent)T=new(r?Pe.Agent:Ne)({keepAlive:!1,maxSockets:1/0});c=Mt.setTimeout(()=>{this.socketWarningTimestamp=De.checkSocketUsage(T,this.socketWarningTimestamp,i.logger)},i.socketAcquisitionWarningTimeout??(i.requestTimeout??2000)+(i.connectionTimeout??1000));let U=t.query?uM(t.query):"",S=void 0;if(t.username!=null||t.password!=null){let R=t.username??"",W=t.password??"";S=`${R}:${W}`}let y=t.path;if(U)y+=`?${U}`;if(t.fragment)y+=`#${t.fragment}`;let D=t.hostname??"";if(D[0]==="["&&D.endsWith("]"))D=t.hostname.slice(1,-1);else D=t.hostname;let q={headers:t.headers,host:D,method:t.method,path:y,port:t.port,agent:T,auth:S},J=(r?Pe.request:cM)(q,(R)=>{let W=new lM({statusCode:R.statusCode||-1,reason:R.statusMessage,headers:_M(R.headers),body:R});A({response:W})});if(J.on("error",(R)=>{if(l3.includes(R.code))M(Object.assign(R,{name:"TimeoutError"}));else M(R)}),n){let R=()=>{J.destroy();let W=We(n);M(W)};if(typeof n.addEventListener==="function"){let W=n;W.addEventListener("abort",R,{once:!0}),J.once("close",()=>W.removeEventListener("abort",R))}else n.onabort=R}let G=s??i.requestTimeout;h=_3(J,M,i.connectionTimeout),u=w3(J,M,G,i.throwOnRequestTimeout,i.logger??console),l=g3(J,M,i.socketTimeout);let K=q.agent;if(typeof K==="object"&&"keepAlive"in K)_=M3(J,{keepAlive:K.keepAlive,keepAliveMsecs:K.keepAliveMsecs});o=wM(J,t,G,this.externalAgent).catch((R)=>{return w(),f(R)})})}updateHttpClientConfig(t,n){this.config=void 0,this.configProvider=this.configProvider.then((s)=>{return{...s,[t]:n}})}httpHandlerConfigs(){return this.config??{}}resolveDefaultConfig(t){let{requestTimeout:n,connectionTimeout:s,socketTimeout:i,socketAcquisitionWarningTimeout:r,httpAgent:e,httpsAgent:f,throwOnRequestTimeout:o,logger:c}=t||{},h=!0,u=50;return{connectionTimeout:s,requestTimeout:n,socketTimeout:i,socketAcquisitionWarningTimeout:r,throwOnRequestTimeout:o,httpAgentProvider:async()=>{let l=nt("http"),{Agent:_,request:w}=l.default??l;if(cM=w,Ne=_,e instanceof Ne||typeof e?.destroy==="function")return this.externalAgent=!0,e;return new Ne({keepAlive:!0,maxSockets:50,...e})},httpsAgent:(()=>{if(f instanceof Pe.Agent||typeof f?.destroy==="function")return this.externalAgent=!0,f;return new Pe.Agent({keepAlive:!0,maxSockets:50,...f})})(),logger:c}}}var R3=new Uint16Array(1);class me{id=R3[0]++;total=0;max=0;session;refs=0;constructor(t){t.unref(),this.session=t}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 AM{sessions=[];maxConcurrency=0;constructor(t){this.sessions=(t??[]).map((n)=>new me(n))}poll(){let t=!1;for(let n of this.sessions){if(n.deref().destroyed){t=!0;continue}if(!this.maxConcurrency||n.useCount()<this.maxConcurrency)return n}if(t){for(let n of this.sessions)if(n.deref().destroyed)this.remove(n)}}offerLast(t){this.sessions.push(t)}remove(t){let n=this.sessions.indexOf(t);if(n>-1)this.sessions.splice(n,1)}[Symbol.iterator](){return this.sessions[Symbol.iterator]()}setMaxConcurrency(t){this.maxConcurrency=t}destroy(t){this.remove(t),t.destroy()}}class MM{config;connectOptions;connectionPools=new Map;constructor(t){if(this.config=t,this.config.maxConcurrency&&this.config.maxConcurrency<=0)throw RangeError("maxConcurrency must be greater than zero.")}lease(t,n){let s=this.getUrlString(t),i=this.getPool(s);if(!this.config.disableConcurrency&&!n.isEventStream){let c=i.poll();if(c)return c.retain(),c}let r=new me(this.connect(s)),e=r.deref();if(this.config.maxConcurrency)e.settings({maxConcurrentStreams:this.config.maxConcurrency},(c)=>{if(c)throw Error("Fail to set maxConcurrentStreams to "+this.config.maxConcurrency+"when creating new session for "+t.destination.toString())});let f=()=>{this.removeFromPoolAndClose(s,r)},o=()=>{this.removeFromPoolAndCheckedDestroy(s,r)};if(e.on("goaway",f),e.on("error",o),e.on("frameError",o),e.on("close",o),n.requestTimeout)e.setTimeout(n.requestTimeout,o);return i.offerLast(r),r.retain(),r}release(t,n){n.free()}createIsolatedSession(t,n){let s=this.getUrlString(t),i=new me(this.connect(s)),r=i.deref();r.settings({maxConcurrentStreams:1});let e=()=>{i.destroy()};if(r.on("error",e),r.on("frameError",e),r.on("close",e),n.requestTimeout)r.setTimeout(n.requestTimeout,e);return i.retain(),i}destroy(){for(let[t,n]of this.connectionPools){for(let s of[...n])s.destroy();this.connectionPools.delete(t)}}setMaxConcurrentStreams(t){if(t&&t<=0)throw RangeError("maxConcurrentStreams must be greater than zero.");this.config.maxConcurrency=t;for(let n of this.connectionPools.values())n.setMaxConcurrency(t)}setDisableConcurrentStreams(t){this.config.disableConcurrency=t}setNodeHttp2ConnectOptions(t){this.connectOptions=t}debug(){let t={};for(let[n,s]of this.connectionPools){let i=[];for(let r of s)i.push({id:r.id,active:r.useCount(),maxConcurrent:r.max,totalRequests:r.total});t[n]={sessions:i}}return t}removeFromPoolAndClose(t,n){this.connectionPools.get(t)?.remove(n),n.close()}removeFromPoolAndCheckedDestroy(t,n){this.connectionPools.get(t)?.remove(n),n.destroy()}getPool(t){if(!this.connectionPools.has(t)){let n=new AM;if(this.config.maxConcurrency)n.setMaxConcurrency(this.config.maxConcurrency);this.connectionPools.set(t,n)}return this.connectionPools.get(t)}getUrlString(t){return t.destination.toString()}connect(t){return this.connectOptions===void 0?ac.connect(t):ac.connect(t,this.connectOptions)}}var{constants:hM}=ac;class pc{config;configProvider;metadata={handlerProtocol:"h2"};connectionManager=new MM({});static create(t){if(typeof t?.handle==="function")return t;return new pc(t)}constructor(t){this.configProvider=new Promise((n,s)=>{if(typeof t==="function")t().then((i)=>{n(i||{})}).catch(s);else n(t||{})})}destroy(){this.connectionManager.destroy()}async handle(t,{abortSignal:n,requestTimeout:s,isEventStream:i}={}){if(!this.config){this.config=await this.configProvider;let{disableConcurrentStreams:c,maxConcurrentStreams:h,nodeHttp2ConnectOptions:u}=this.config;if(this.connectionManager.setDisableConcurrentStreams(c??!1),h)this.connectionManager.setMaxConcurrentStreams(h);if(u)this.connectionManager.setNodeHttp2ConnectOptions(u)}let{requestTimeout:r,disableConcurrentStreams:e}=this.config,f=e||i,o=s??r;return new Promise((c,h)=>{let u=!1,l=void 0,_=async(W)=>{await l,c(W)},w=async(W)=>{await l,h(W)};if(n?.aborted){u=!0;let W=We(n);w(W);return}let{hostname:A,method:M,port:d,protocol:E,query:T}=t,U="";if(t.username!=null||t.password!=null){let W=t.username??"",k=t.password??"";U=`${W}:${k}@`}let S=`${E}//${U}${A}${d?`:${d}`:""}`,y={destination:new URL(S)},D={requestTimeout:this.config?.sessionTimeout,isEventStream:i},q=f?this.connectionManager.createIsolatedSession(y,D):this.connectionManager.lease(y,D),tt=q.deref(),J=(W)=>{if(f)q.destroy();u=!0,w(W)},G=T?uM(T):"",K=t.path;if(G)K+=`?${G}`;if(t.fragment)K+=`#${t.fragment}`;let R=tt.request({...t.headers,[hM.HTTP2_HEADER_PATH]:K,[hM.HTTP2_HEADER_METHOD]:M});if(o)R.setTimeout(o,()=>{R.close();let W=Error(`Stream timed out because of no activity for ${o} ms`);W.name="TimeoutError",J(W)});if(n){let W=()=>{R.close();let k=We(n);J(k)};if(typeof n.addEventListener==="function"){let k=n;k.addEventListener("abort",W,{once:!0}),R.once("close",()=>k.removeEventListener("abort",W))}else n.onabort=W}R.on("frameError",(W,k,st)=>{J(Error(`Frame type id ${W} in stream id ${st} has failed with code ${k}.`))}),R.on("error",J),R.on("aborted",()=>{J(Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${R.rstCode}.`))}),R.on("response",(W)=>{let k=new lM({statusCode:W[":status"]??-1,headers:_M(W),body:R});if(u=!0,_({response:k}),f)tt.close()}),R.on("close",()=>{if(f)q.destroy();else this.connectionManager.release(y,q);if(!u)J(Error("Unexpected error: http2 request did not get a response"))}),l=wM(R,t,o)})}updateHttpClientConfig(t,n){this.config=void 0,this.configProvider=this.configProvider.then((s)=>{return{...s,[t]:n}})}httpHandlerConfigs(){return this.config??{}}}b3.DEFAULT_REQUEST_TIMEOUT=E3;b3.NodeHttp2Handler=pc;b3.NodeHttpHandler=De});var yM=Z((iF)=>{var{nv:L3,NumericValue:bM,calculateBodyLength:I3,_parseEpochTimestamp:gM,fromBase64:TM,generateIdempotencyToken:y3}=$t(),{HttpRequest:O3,collectBody:G3,SerdeContext:ih,RpcProtocol:B3}=Ut(),{NormalizedSchema:rh,deref:F3,TypeRegistry:dM}=Nn(),{getSmithyContext:H3}=nn();function ei(t){return typeof Buffer<"u"?Buffer.alloc(t):new Uint8Array(t)}var eh=Symbol("@smithy/core/cbor::tagSymbol");function oh(t){return t[eh]=!0,t}var SM=typeof Buffer<"u",fh=new TextDecoder,C=ei(0),ch=!1,qt=new DataView(C.buffer,C.byteOffset,C.byteLength),Y=0;function P3(t){C=t,ch=SM&&C instanceof Buffer,qt=new DataView(C.buffer,C.byteOffset,C.byteLength)}function Xn(t,n){if(t>=n)throw Error("unexpected end of (decode) payload.");let s=(C[t]&224)>>5,i=C[t]&31;if(i===31&&2<=s&&s<=5)return N3(t,n);switch(s){case 0:case 1:case 6:{let r,e;if(i<24)r=i,e=1;else switch(i){case 24:if(n-t<2)cn(1);r=C[t+1],e=2;break;case 25:if(n-t<3)cn(2);r=qt.getUint16(t+1),e=3;break;case 26:if(n-t<5)cn(4);r=qt.getUint32(t+1),e=5;break;case 27:if(n-t<9)cn(8);{let f=qt.getUint32(t+1);if(f<2097152)r=f*4294967296+qt.getUint32(t+5);else r=qt.getBigUint64(t+1)}e=9;break;default:uh(i)}if(s===0)return Y=e,th(r);else if(s===1){let f;if(typeof r==="bigint")f=BigInt(-1)-r;else f=-1-r;return Y=e,th(f)}else return z3(t,n,i,r,e)}case 3:return hr(t,n);case 5:return D3(t,n);case 4:return Q3(t,n);case 2:return hh(t,n);default:return X3(t,n)}}function N3(t,n){let s=(C[t]&224)>>5;if((C[t]&31)===31)switch(s){case 3:return C3(t,n);case 5:return x3(t,n);case 4:return q3(t,n);case 2:return K3(t,n)}}function W3(t,n){let s=t>>7,i=(t&124)>>2,r=(t&3)<<8|n,e=s===0?1:-1;if(i===0){if(r===0)return 0;return e*(Math.pow(2,-14)*(r/1024))}else if(i===31){if(r===0)return e*(1/0);return NaN}return e*(Math.pow(2,i-15)*(1+r/1024))}function D3(t,n){let s=ur(t,n);if(s<15)return Y3(t,n,s);return m3(t,n,s)}function m3(t,n,s){let i=Y;t+=i;let r=t,e=Object.create(null);for(let f=0;f<s;++f){let o=hr(t,n);if(t+=Y,(C[t]&224)>>5===3)e[o]=hr(t,n);else e[o]=Xn(t,n);t+=Y}return Y=i+(t-r),Object.setPrototypeOf(e,Object.prototype),e}function Y3(t,n,s){let i=Y;t+=i;let r=t,e={};for(let f=0;f<s;++f){let o=hr(t,n);t+=Y,e[o]=Xn(t,n),t+=Y}return Y=i+(t-r),e}function Q3(t,n){let s=ur(t,n),i=Y;t+=i;let r=t,e=Array(s);for(let f=0;f<s;++f)e[f]=Xn(t,n),t+=Y;return Y=i+(t-r),e}function hr(t,n){let s=ur(t,n),i=Y;if(t+=i,n-t<s)cn(s);if(Y=i+s,s<24)return k3(t,s);if(ch)return C.toString("utf-8",t,t+s);return fh.decode(C.subarray(t,t+s))}var EM=Array(2048),Zc=new Uint16Array(2048),fr=0;function J3(){fr=fr+1&65535}function k3(t,n){let s=n;for(let f=0;f<n;++f)s=s*31+C[t+f]|0;let i=s>>>0&2047,r=EM[i];if(r!==void 0){if(r.length===n){let f=!0;for(let o=0;o<n;++o)if(r.charCodeAt(o)!==C[t+o]){f=!1;break}if(f)return Zc[i]=fr,r}}let e=ch?C.toString("utf-8",t,t+n):fh.decode(C.subarray(t,t+n));if(Zc[i]!==fr)EM[i]=e,Zc[i]=fr;return e}function hh(t,n){let s=ur(t,n),i=Y;if(t+=i,n-t<s)cn(s);let r=C.subarray(t,t+s);return Y=i+s,r}function z3(t,n,s,i,r){if(s===2||s===3){let e=ur(t+r,n),f=BigInt(0),o=t+r+Y;for(let c=o;c<o+e;++c)f=f<<BigInt(8)|BigInt(C[c]);return Y=r+Y+e,s===3?-f-BigInt(1):f}else if(s===4){let e=Xn(t+r,n),[f,o]=e,c=o<0?-1:1,h="0".repeat(Math.abs(f)+1)+String(BigInt(c)*BigInt(o)),u,l=o<0?"-":"";if(u=f===0?h:h.slice(0,h.length+f)+"."+h.slice(f),u=u.replace(/^0+/g,""),u==="")u="0";if(u[0]===".")u="0"+u;return u=l+u,Y=r+Y,L3(u)}else{let e=Xn(t+r,n);return Y=r+Y,oh({tag:th(i),value:e})}}function X3(t,n){let s=C[t]&31;switch(s){case 21:case 20:return Y=1,s===21;case 22:return Y=1,null;case 23:return Y=1,null;case 25:if(n-t<3)throw Error("incomplete float16 at end of buf.");return Y=3,W3(C[t+1],C[t+2]);case 26:if(n-t<5)throw Error("incomplete float32 at end of buf.");return Y=5,qt.getFloat32(t+1);case 27:if(n-t<9)throw Error("incomplete float64 at end of buf.");return Y=9,qt.getFloat64(t+1);default:uh(s)}}function ur(t,n){let s=C[t]&31;if(s<24)return Y=1,s;switch(s){case 24:if(n-t<2)cn(1);return Y=2,C[t+1];case 25:if(n-t<3)cn(2);return Y=3,qt.getUint16(t+1);case 26:if(n-t<5)cn(4);return Y=5,qt.getUint32(t+1);case 27:if(n-t<9)cn(8);return Y=9,V3(qt.getBigUint64(t+1));default:uh(s)}}function x3(t,n){t+=1;let s=t,i={};for(;t<n;){if(C[t]===255)return Y=t-s+2,i;let r=hr(t,n);t+=Y,i[r]=Xn(t,n),t+=Y}throw Error("expected break marker.")}function q3(t,n){t+=1;let s=[];for(let i=t;t<n;){if(C[t]===255)return Y=t-i+2,s;s.push(Xn(t,n)),t+=Y}throw Error("expected break marker.")}function C3(t,n){t+=1;let s=[];for(let i=t;t<n;){if(C[t]===255){let c=ei(s.length);if(c.set(s,0),Y=t-i+2,SM)return c.toString("utf-8",0,c.length);return fh.decode(c)}let r=(C[t]&224)>>5,e=C[t]&31;if(r!==3)$M(r);if(e===31)throw Error("nested indefinite string.");let f=hh(t,n);t+=Y;for(let c=0;c<f.length;++c)s.push(f[c])}throw Error("expected break marker.")}function K3(t,n){t+=1;let s=[];for(let i=t;t<n;){if(C[t]===255){let c=ei(s.length);return c.set(s,0),Y=t-i+2,c}let r=(C[t]&224)>>5,e=C[t]&31;if(r!==2)$M(r);if(e===31)throw Error("nested indefinite string.");let f=hh(t,n);t+=Y;for(let c=0;c<f.length;++c)s.push(f[c])}throw Error("expected break marker.")}function th(t){if(typeof t==="number")return t;let n=Number(t);if(Number.MIN_SAFE_INTEGER<=n&&n<=Number.MAX_SAFE_INTEGER)return n;return t}function V3(t){let n=Number(t);if(n<Number.MIN_SAFE_INTEGER||Number.MAX_SAFE_INTEGER<n)console.warn(Error(`@smithy/core/cbor - truncating BigInt(${t}) to ${n} with loss of precision.`));return n}function cn(t){throw Error(`length ${t} greater than remaining buf len.`)}function uh(t){throw Error(`unexpected minor value ${t}.`)}function $M(t){throw Error(`unexpected major type ${t} in indefinite string.`)}var j3=typeof Buffer<"u",ii=new Map,cr=0,nh=!1,a3=2048,H=ei(a3),Dt=new DataView(H.buffer,H.byteOffset,H.byteLength),I=0;function p3(t){let n=[t];while(n.length){let s=n.pop();if(typeof s==="string"){let i=s.length;if(j3)if(ri(i*3+9),i>23)vc(3,Buffer.byteLength(s)),I+=H.write(s,I);else v3(s);else{let r=i*3;ri(r+9);let e=I,o=new TextEncoder().encodeInto(s,H.subarray(I+9)).written,c;if(o<24)c=1;else if(o<256)c=2;else if(o<65536)c=3;else if(o<4294967296)c=5;else c=9;if(c<9)H.copyWithin(e+c,e+9,e+9+o);I=e,ws(3,o),I+=o}continue}if(H.byteLength-I<9)ri(64);if(typeof s==="number"){if(Number.isInteger(s)){let i=s>=0,r=i?0:1,e=i?s:-s-1;if(e<24)H[I++]=r<<5|e;else if(e<256)H[I++]=r<<5|24,H[I++]=e;else if(e<65536)H[I++]=r<<5|25,H[I++]=e>>8,H[I++]=e&255;else if(e<4294967296)H[I++]=r<<5|26,Dt.setUint32(I,e),I+=4;else{H[I++]=r<<5|27;let f=e/4294967296|0,o=e-f*4294967296|0;Dt.setUint32(I,f),Dt.setUint32(I+4,o),I+=8}continue}H[I++]=251,Dt.setFloat64(I,s),I+=8;continue}else if(typeof s==="bigint"){let i=s>=0,r=i?0:1,e=i?s:-s-BigInt(1);if(e<BigInt("18446744073709551616")){let f=Number(e);if(f<4294967296)ws(r,f);else H[I++]=r<<5|27,Dt.setBigUint64(I,e),I+=8}else{let f=e.toString(2),o=new Uint8Array(Math.ceil(f.length/8)),c=e,h=0;while(o.byteLength-++h>=0)o[o.byteLength-h]=Number(c&BigInt(255)),c>>=BigInt(8);ri(o.byteLength*2+16),H[I++]=i?194:195,vc(2,o.byteLength),H.set(o,I),I+=o.byteLength}continue}else if(s===null){H[I++]=246;continue}else if(typeof s==="boolean"){H[I++]=224|(s?21:20);continue}else if(typeof s>"u")throw Error("@smithy/core/cbor: client may not serialize undefined value.");else if(Array.isArray(s)){ws(4,s.length),ri(s.length*9+64);for(let i=s.length-1;i>=0;--i)n.push(s[i]);continue}else if(typeof s.byteLength==="number"){ri(s.length*2+9),ws(2,s.length),H.set(s,I),I+=s.byteLength;continue}else if(typeof s==="object"){if(s instanceof bM){let e=s.string.indexOf("."),f=e===-1?0:e-s.string.length+1,o=BigInt(s.string.replace(".",""));H[I++]=196,ws(4,2),n.push(o),n.push(f);continue}if(s[eh])if("tag"in s&&"value"in s){n.push(s.value),vc(6,s.tag);continue}else throw Error("tag encountered with missing fields, need 'tag' and 'value', found: "+JSON.stringify(s));let i=Object.keys(s),r=i.length;ws(5,r);for(let e=r-1;e>=0;--e)n.push(s[i[e]]),n.push(i[e]);continue}throw Error(`data type ${s?.constructor?.name??typeof s} not compatible for encoding.`)}}function Z3(){cr=cr+1&65535,nh=!1}function RM(){let t=ei(I);return t.set(H.subarray(0,I),0),I=0,t}function sh(t){let n=H;if(H=ei(t),n)if(n.copy)n.copy(H,0,0,n.byteLength);else H.set(n,0);Dt=new DataView(H.buffer,H.byteOffset,H.byteLength)}function v3(t){let n=ii.get(t);if(n!==void 0){H.set(n.bytes,I),I+=n.bytes.length,n.epoch=cr;return}let s=I,i=Buffer.byteLength(t);ws(3,i),I+=H.write(t,I);let r=Uint8Array.prototype.slice.call(H,s,I);if(ii.size>=2048){if(nh)return;let e=0;for(let[f,o]of ii){if(e>=1024)break;if(o.epoch!==cr)ii.delete(f),e++}if(e===0){nh=!0;return}}if(ii.size<2048)ii.set(t,{epoch:cr,bytes:r})}function ri(t){if(H.byteLength-I<t)if(I<16000000)sh(Math.max(H.byteLength*4,H.byteLength+t));else sh(H.byteLength+t+16000000)}function vc(t,n){if(n<24)H[I++]=t<<5|n;else if(n<256)H[I++]=t<<5|24,H[I++]=n;else if(n<65536)H[I++]=t<<5|25,Dt.setUint16(I,n),I+=2;else if(n<4294967296)H[I++]=t<<5|26,Dt.setUint32(I,n),I+=4;else H[I++]=t<<5|27,Dt.setBigUint64(I,typeof n==="bigint"?n:BigInt(n)),I+=8}function ws(t,n){if(n<24)H[I++]=t<<5|n;else if(n<256)H[I++]=t<<5|24,H[I++]=n;else if(n<65536)H[I++]=t<<5|25,H[I++]=n>>8,H[I++]=n&255;else if(n<4294967296)H[I++]=t<<5|26,Dt.setUint32(I,n),I+=4;else{H[I++]=t<<5|27;let s=n/4294967296|0,i=n-s*4294967296|0;Dt.setUint32(I,s),Dt.setUint32(I+4,i),I+=8}}var Je={deserialize(t){return J3(),P3(t),Xn(0,t.length)},serialize(t){Z3();try{return p3(t),RM()}catch(n){throw RM(),n}},resizeEncodingBuffer(t){sh(t)}},UM=(t,n)=>{return G3(t,n).then(async(s)=>{if(s.length)try{return Je.deserialize(s)}catch(i){throw Object.defineProperty(i,"$responseBodyText",{value:n.utf8Encoder(s)}),i}return{}})},Qe=(t)=>{return oh({tag:1,value:t.getTime()/1000})},tF=async(t,n)=>{let s=await UM(t,n);return s.message=s.message??s.Message,s},LM=(t,n)=>{let s=(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(n.__type!==void 0)return s(n.__type);let i;for(let r in n)if(r.toLowerCase()==="code"){i=r;break}if(i&&n[i]!==void 0)return s(n[i])},nF=(t)=>{if(String(t.headers["smithy-protocol"]).toLowerCase()!=="rpc-v2-cbor")throw Error("Malformed RPCv2 CBOR response, status: "+t.statusCode)},sF=async(t,n,s,i,r)=>{let e=await t.endpoint(),{hostname:f,protocol:o="https",port:c,path:h}=e,u={protocol:o,hostname:f,port:c,method:"POST",path:h.endsWith("/")?h.slice(0,-1)+s:h+s,headers:{...n}};if(i!==void 0)u.hostname=i;if(e.headers)for(let l in e.headers)u.headers[l]=e.headers[l];if(r!==void 0){u.body=r;try{u.headers["content-length"]=String(I3(r))}catch(l){}}return new O3(u)};class lh extends ih{createSerializer(){let t=new _h;return t.setSerdeContext(this.serdeContext),t}createDeserializer(){let t=new wh;return t.setSerdeContext(this.serdeContext),t}}class _h extends ih{value;write(t,n){this.value=this.serialize(t,n)}serialize(t,n){let s=rh.of(t);if(n==null){if(s.isIdempotencyToken())return y3();return n}if(s.isBlobSchema()){if(typeof n==="string")return(this.serdeContext?.base64Decoder??TM)(n);return n}if(s.isTimestampSchema()){if(typeof n==="number"||typeof n==="bigint")return Qe(new Date(Number(n)/1000|0));return Qe(n)}if(typeof n==="function"||typeof n==="object"){let i=n;if(s.isListSchema()&&Array.isArray(i)){let e=!!s.getMergedTraits().sparse,f=[],o=0;for(let c of i){let h=this.serialize(s.getValueSchema(),c);if(h!=null||e)f[o++]=h}return f}if(i instanceof Date)return Qe(i);let r={};if(s.isMapSchema()){let e=!!s.getMergedTraits().sparse;for(let f in i){let o=this.serialize(s.getValueSchema(),i[f]);if(o!=null||e)r[f]=o}}else if(s.isStructSchema()){for(let[f,o]of s.structIterator()){let c=this.serialize(o,i[f]);if(c!=null)r[f]=c}if(s.isUnionSchema()&&Array.isArray(i.$unknown)){let[f,o]=i.$unknown;r[f]=o}else if(typeof i.__type==="string"){for(let f in i)if(!(f in r))r[f]=this.serialize(15,i[f])}}else if(s.isDocumentSchema())for(let e in i)r[e]=this.serialize(s.getValueSchema(),i[e]);else if(s.isBigDecimalSchema())return i;return r}return n}flush(){let t=Je.serialize(this.value);return this.value=void 0,t}}class wh extends ih{read(t,n){let s=Je.deserialize(n);return this.readValue(t,s)}readValue(t,n){let s=rh.of(t);if(s.isTimestampSchema()){if(typeof n==="number")return gM(n);if(typeof n==="object"){if(n.tag===1&&"value"in n)return gM(n.value)}}if(s.isBlobSchema()){if(typeof n==="string")return(this.serdeContext?.base64Decoder??TM)(n);return n}if(typeof n>"u"||typeof n==="boolean"||typeof n==="number"||typeof n==="string"||typeof n==="bigint"||typeof n==="symbol")return n;else if(typeof n==="object"){if(n===null)return null;if("byteLength"in n)return n;if(n instanceof Date)return n;if(s.isDocumentSchema())return n;if(s.isListSchema()){let r=[],e=s.getValueSchema();for(let f of n){let o=this.readValue(e,f);r.push(o)}return r}let i={};if(s.isMapSchema()){let r=s.getValueSchema();for(let e in n){let f=this.readValue(r,n[e]);i[e]=f}}else if(s.isStructSchema()){let r=s.isUnionSchema(),e;if(r){e=new Set;for(let f in n)if(f!=="__type")e.add(f)}for(let[f,o]of s.structIterator()){if(r)e.delete(f);if(n[f]!=null)i[f]=this.readValue(o,n[f])}if(r&&e?.size===1){let f=!0;for(let o in i){f=!1;break}if(f){let o=e.values().next().value;i.$unknown=[o,n[o]]}}else if(typeof n.__type==="string"){for(let f in n)if(!(f in i))i[f]=n[f]}}else if(n instanceof bM)return n;return i}else return n}}class IM extends B3{codec=new lh;serializer=this.codec.createSerializer();deserializer=this.codec.createDeserializer();constructor({defaultNamespace:t,errorTypeRegistries:n}){super({defaultNamespace:t,errorTypeRegistries:n})}getShapeId(){return"smithy.protocols#rpcv2Cbor"}getPayloadCodec(){return this.codec}async serializeRequest(t,n,s){let i=await super.serializeRequest(t,n,s);if(Object.assign(i.headers,{"content-type":this.getDefaultContentType(),"smithy-protocol":"rpc-v2-cbor",accept:this.getDefaultContentType()}),F3(t.input)==="unit")delete i.body,delete i.headers["content-type"];else{if(!i.body)this.serializer.write(15,{}),i.body=this.serializer.flush();try{i.headers["content-length"]=String(i.body.byteLength)}catch(o){}}let{service:r,operation:e}=H3(s),f=`/service/${r}/operation/${e}`;if(i.path.endsWith("/"))i.path+=f.slice(1);else i.path+=f;return i}async deserializeResponse(t,n,s){return super.deserializeResponse(t,n,s)}async handleError(t,n,s,i,r){let e=LM(s,i)??"Unknown",f={$metadata:r,$fault:s.statusCode<=500?"client":"server"},o=this.options.defaultNamespace;if(e.includes("#"))[o]=e.split("#");let c=this.compositeErrorRegistry,h=dM.for(o);c.copyFrom(h);let u;try{u=c.getSchema(e)}catch(d){if(i.Message)i.message=i.Message;let E=dM.for("smithy.ts.sdk.synthetic."+o);c.copyFrom(E);let T=c.getBaseException();if(T){let U=c.getErrorCtor(T);throw Object.assign(new U({name:e}),f,i)}throw Object.assign(Error(e),f,i)}let l=rh.of(u),_=c.getErrorCtor(u),w=i.message??i.Message??"Unknown",A=new _({}),M={};for(let[d,E]of l.structIterator())M[d]=this.deserializer.readValue(E,i[d]);throw Object.assign(A,f,{$fault:l.getMergedTraits().error,message:w},M)}getDefaultContentType(){return"application/cbor"}}iF.CborCodec=lh;iF.CborShapeDeserializer=wh;iF.CborShapeSerializer=_h;iF.SmithyRpcV2CborProtocol=IM;iF.buildHttpRpcRequest=sF;iF.cbor=Je;iF.checkCborResponse=nF;iF.dateToTag=Qe;iF.loadSmithyRpcV2CborErrorCode=LM;iF.parseCborBody=UM;iF.parseCborErrorBody=tF;iF.tag=oh;iF.tagSymbol=eh});var OM=Z((UF)=>{var dF=/[&<>"]/g,EF={"&":"&","<":"<",">":">",'"':"""};function RF(t){return t.replace(dF,(n)=>EF[n])}var bF=/[&"'<>\r\n\u0085\u2028]/g,TF={"&":"&",'"':""","'":"'","<":"<",">":">","\r":"
","\n":"
","\x85":"…","\u2028":"
"};function SF(t){return t.replace(bF,(n)=>TF[n])}class Ah{value;constructor(t){this.value=t}toString(){return SF(""+this.value)}}class lr{name;children;attributes={};static of(t,n,s){let i=new lr(t);if(n!==void 0)i.addChildNode(new Ah(n));if(s!==void 0)i.withName(s);return i}constructor(t,n=[]){this.name=t,this.children=n}withName(t){return this.name=t,this}addAttribute(t,n){return this.attributes[t]=n,this}addChildNode(t){return this.children.push(t),this}removeAttribute(t){return delete this.attributes[t],this}n(t){return this.name=t,this}c(t){return this.children.push(t),this}a(t,n){if(n!=null)this.attributes[t]=n;return this}cc(t,n,s=n){if(t[n]!=null){let i=lr.of(n,t[n]).withName(s);this.c(i)}}l(t,n,s,i){if(t[n]!=null)i().map((e)=>{e.withName(s),this.c(e)})}lc(t,n,s,i){if(t[n]!=null){let r=i(),e=new lr(s);r.map((f)=>{e.c(f)}),this.c(e)}}toString(){let t=Boolean(this.children.length),n=`<${this.name}`,s=this.attributes;for(let i of Object.keys(s)){let r=s[i];if(r!=null)n+=` ${i}="${RF(""+r)}"`}return n+=!t?"/>":`>${this.children.map((i)=>i.toString()).join("")}</${this.name}>`}}function $F(t){return new Mh(t).parse()}class Mh{x;i=0;z;constructor(t){this.x=t,this.x=t.replace(/\r\n?/g,`
|
|
44
|
-
`),this.z=this.x.length}parse(){let
|
|
45
|
-
`.includes(
|
|
46
|
-
>/`.includes(
|
|
47
|
-
>/?`.includes(
|
|
48
|
-
`))return{tag:
|
|
49
|
-
`))continue;c["#text"]="#text"in c?c["#text"]+h:h}for(let h of e)if(h.tag in c)if(Array.isArray(c[h.tag]))c[h.tag].push(h.value);else c[h.tag]=[c[h.tag],h.value];else c[h.tag]=h.value;for(let[h,u]of Object.entries(i))c[h]=u;return Object.setPrototypeOf(c,Object.prototype),{tag:n,value:c}}static ENTITIES={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};skipDoctype(){let t=this;t.i+=9;let n=0;while(t.i<t.z){let s=t.x[t.i];if(s==="[")++n;else if(s==="]")--n;else if(s===">"&&n===0){++t.i;return}++t.i}throw Error("@aws-sdk XML parse error: unclosed DOCTYPE.")}decodeEntities(t){return t.replace(/&(?:#x([0-9a-fA-F]{1,6})|#(\d{1,7})|([a-zA-Z][a-zA-Z0-9]{0,30}));/g,(n,s,i,r)=>{if(s)return String.fromCharCode(parseInt(s,16));if(i)return String.fromCharCode(parseInt(i,10));return Mh.ENTITIES[r]??""})}}UF.XmlNode=lr;UF.XmlText=Ah;UF.parseXML=$F});var yh=Z((zF)=>{var{SmithyRpcV2CborProtocol:OF,loadSmithyRpcV2CborErrorCode:GF}=yM(),{TypeRegistry:GM,NormalizedSchema:ft,deref:WM}=Nn(),{decorateServiceException:BM,getValueFromTextNode:DM}=Rn(),{collectBody:dh,determineTimestampFormat:Xe,RpcProtocol:mM,HttpBindingProtocol:YM,HttpInterceptingShapeSerializer:QM,HttpInterceptingShapeDeserializer:JM,FromStringShapeDeserializer:BF,extendedEncodeURIComponent:FM}=Ut(),{NumericValue:hn,toUtf8:kM,fromBase64:zM,LazyJsonString:XM,parseEpochTimestamp:FF,parseRfc7231DateTime:HF,parseRfc3339DateTimeWithOffset:PF,toBase64:ke,dateToUtcString:ze,generateIdempotencyToken:Eh,expectUnion:NF}=$t(),{parseXML:xM,XmlNode:Ct,XmlText:HM}=OM();class oi{queryCompat;errorRegistry;constructor(t=!1){this.queryCompat=t}resolveRestContentType(t,n){let s=n.getMemberSchemas(),i=Object.values(s).find((r)=>{return!!r.getMergedTraits().httpPayload});if(i){let r=i.getMergedTraits().mediaType;if(r)return r;else if(i.isStringSchema())return"text/plain";else if(i.isBlobSchema())return"application/octet-stream";else return t}else if(!n.isUnitSchema()){if(Object.values(s).find((e)=>{let{httpQuery:f,httpQueryParams:o,httpHeader:c,httpLabel:h,httpPrefixHeaders:u}=e.getMergedTraits();return!f&&!o&&!c&&!h&&u===void 0}))return t}}async getErrorSchemaOrThrowBaseException(t,n,s,i,r,e){let f=t;if(t.includes("#"))[,f]=t.split("#");let o={$metadata:r,$fault:s.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(t),errorMetadata:o}}catch(c){i.message=i.message??i.Message??"UnknownError";let h=this.errorRegistry,u=h.getBaseException();if(u){let w=h.getErrorCtor(u)??Error;throw this.decorateServiceException(Object.assign(new w({name:f}),o),i)}let l=i,_=l?.message??l?.Message??l?.Error?.Message??l?.Error?.message;throw this.decorateServiceException(Object.assign(Error(_),{name:f},o),i)}}compose(t,n,s){let i=s;if(n.includes("#"))[i]=n.split("#");let r=GM.for(i),e=GM.for("smithy.ts.sdk.synthetic."+s);t.copyFrom(r),t.copyFrom(e),this.errorRegistry=t}decorateServiceException(t,n={}){if(this.queryCompat){let s=t.Message??n.Message,i=BM(t,n);if(s)i.message=s;let r=i.Error??{};r.Type=i.Error?.Type,r.Code=i.Error?.Code,r.Message=i.Error?.message??i.Error?.Message??s,i.Error=r;let e=i.$metadata.requestId;if(e)i.RequestId=e;return i}return BM(t,n)}setQueryCompatError(t,n){let s=n.headers?.["x-amzn-query-error"];if(t!==void 0&&s!=null){let[i,r]=s.split(";"),e=Object.keys(t),f={Code:i,Type:r};t.Code=i,t.Type=r;for(let o=0;o<e.length;o++){let c=e[o];f[c==="message"?"Message":c]=t[c]}delete f.__type,t.Error=f}}queryCompatOutput(t,n){if(t.Error)n.Error=t.Error;if(t.Type)n.Type=t.Type;if(t.Code)n.Code=t.Code}findQueryCompatibleError(t,n){try{return t.getSchema(n)}catch(s){return t.find((i)=>ft.of(i).getMergedTraits().awsQueryError?.[0]===n)}}}class qM extends OF{awsQueryCompatible;mixin;constructor({defaultNamespace:t,errorTypeRegistries:n,awsQueryCompatible:s}){super({defaultNamespace:t,errorTypeRegistries:n});this.awsQueryCompatible=!!s,this.mixin=new oi(this.awsQueryCompatible)}async serializeRequest(t,n,s){let i=await super.serializeRequest(t,n,s);if(this.awsQueryCompatible)i.headers["x-amzn-query-mode"]="true";return i}async handleError(t,n,s,i,r){if(this.awsQueryCompatible)this.mixin.setQueryCompatError(i,s);let e=(()=>{let w=s.headers["x-amzn-query-error"];if(w&&this.awsQueryCompatible)return w.split(";")[0];return GF(s,i)??"Unknown"})();this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace);let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,s,i,r,this.awsQueryCompatible?this.mixin.findQueryCompatibleError:void 0),c=ft.of(f),h=i.message??i.Message??"UnknownError",l=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({}),_={};for(let[w,A]of c.structIterator())if(i[w]!=null)_[w]=this.deserializer.readValue(A,i[w]);if(this.awsQueryCompatible)this.mixin.queryCompatOutput(i,_);throw this.mixin.decorateServiceException(Object.assign(l,o,{$fault:c.getMergedTraits().error,message:h},_),i)}}var WF=(t)=>{if(t==null)return t;if(typeof t==="number"||typeof t==="bigint"){let n=Error(`Received number ${t} where a string was expected.`);return n.name="Warning",console.warn(n),String(t)}if(typeof t==="boolean"){let n=Error(`Received boolean ${t} where a string was expected.`);return n.name="Warning",console.warn(n),String(t)}return t},DF=(t)=>{if(t==null)return t;if(typeof t==="string"){let n=t.toLowerCase();if(t!==""&&n!=="false"&&n!=="true"){let s=Error(`Received string "${t}" where a boolean was expected.`);s.name="Warning",console.warn(s)}return t!==""&&n!=="false"}return t},mF=(t)=>{if(t==null)return t;if(typeof t==="string"){let n=Number(t);if(n.toString()!==t){let s=Error(`Received string "${t}" where a number was expected.`);return s.name="Warning",console.warn(s),t}return n}return t};class xn{serdeContext;setSerdeContext(t){this.serdeContext=t}}class Rh{from;to;keys;constructor(t,n){this.from=t,this.to=n;let s=Object.keys(this.from),i=new Set(s);i.delete("__type"),this.keys=i}mark(t){this.keys.delete(t)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){let t=this.keys.values().next().value,n=this.from[t];this.to.$unknown=[t,n]}}}function YF(t,n,s){if(s?.source){let i=s.source;if(typeof n==="number"){if(n>Number.MAX_SAFE_INTEGER||n<Number.MIN_SAFE_INTEGER||i!==String(n))if(i.includes("."))return new hn(i,"bigDecimal");else return BigInt(i)}}return n}var CM=(t,n)=>dh(t,n).then((s)=>(n?.utf8Encoder??kM)(s)),bh=(t,n)=>CM(t,n).then((s)=>{if(s.length)try{return JSON.parse(s)}catch(i){if(i?.name==="SyntaxError")Object.defineProperty(i,"$responseBodyText",{value:s});throw i}return{}}),QF=async(t,n)=>{let s=await bh(t,n);return s.message=s.message??s.Message,s},PM=(t,n)=>Object.keys(t).find((s)=>s.toLowerCase()===n.toLowerCase()),gh=(t)=>{let n=t;if(typeof n==="number")n=n.toString();if(n.indexOf(",")>=0)n=n.split(",")[0];if(n.indexOf(":")>=0)n=n.split(":")[0];if(n.indexOf("#")>=0)n=n.split("#")[1];return n},KM=(t,n)=>{return jM(t,n,["header","code","type"])},VM=(t,n,s=!1)=>{return jM(t,n,s?["code","header","type"]:["type","code","header"])},jM=({headers:t},n,s)=>{while(s.length>0)switch(s.shift()){case"header":let r=PM(t??{},"x-amzn-errortype");if(r!==void 0)return gh(t[r]);break;case"code":let e=PM(n??{},"code");if(e&&n[e]!==void 0)return gh(n[e]);break;case"type":if(n?.__type!==void 0)return gh(n.__type);break}};class Th extends xn{settings;constructor(t){super();this.settings=t}async read(t,n){return this._read(t,typeof n==="string"?JSON.parse(n,YF):await bh(n,this.serdeContext))}readObject(t,n){return this._read(t,n)}_read(t,n){let s=n!==null&&typeof n==="object",i=ft.of(t);if(s){if(i.isStructSchema()){let e=n,f=i.isUnionSchema(),o={},c=void 0,{jsonName:h}=this.settings;if(h)c={};let u;if(f)u=new Rh(e,o);for(let[l,_]of i.structIterator()){let w=l;if(h)w=_.getMergedTraits().jsonName??w,c[w]=l;if(f)u.mark(w);if(e[w]!=null)o[l]=this._read(_,e[w])}if(f)u.writeUnknown();else if(typeof e.__type==="string")for(let l in e){let _=e[l],w=h?c[l]??l:l;if(!(w in o))o[w]=_}return o}if(Array.isArray(n)&&i.isListSchema()){let e=i.getValueSchema(),f=[];for(let o of n)f.push(this._read(e,o));return f}if(i.isMapSchema()){let e=i.getValueSchema(),f={};for(let o in n)f[o]=this._read(e,n[o]);return f}}if(i.isBlobSchema()&&typeof n==="string")return zM(n);let r=i.getMergedTraits().mediaType;if(i.isStringSchema()&&typeof n==="string"&&r){if(r==="application/json"||r.endsWith("+json"))return XM.from(n);return n}if(i.isTimestampSchema()&&n!=null)switch(Xe(i,this.settings)){case 5:return PF(n);case 6:return HF(n);case 7:return FF(n);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",n),new Date(n)}if(i.isBigIntegerSchema()&&(typeof n==="number"||typeof n==="string"))return BigInt(n);if(i.isBigDecimalSchema()&&n!=null){if(n instanceof hn)return n;let e=n;if(e.type==="bigDecimal"&&"string"in e)return new hn(e.string,e.type);return new hn(String(n),"bigDecimal")}if(i.isNumericSchema()&&typeof n==="string"){switch(n){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return n}if(i.isDocumentSchema())if(s){let e=Array.isArray(n)?[]:{};for(let f in n){let o=n[f];if(o instanceof hn)e[f]=o;else e[f]=this._read(i,o)}return e}else return structuredClone(n);return n}}var NM=String.fromCharCode(925);class aM{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,(t,n)=>{if(n instanceof hn){let s=`${NM+"nv"+this.counter++}_`+n.string;return this.values.set(`"${s}"`,n.string),s}if(typeof n==="bigint"){let s=n.toString(),i=`${NM+"b"+this.counter++}_`+s;return this.values.set(`"${i}"`,s),i}return n}}replaceInJson(t){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 t;for(let[n,s]of this.values)t=t.replace(n,s);return t}}class Sh extends xn{settings;buffer;useReplacer=!1;rootSchema;constructor(t){super();this.settings=t}write(t,n){this.rootSchema=ft.of(t),this.buffer=this._write(this.rootSchema,n)}flush(){let{rootSchema:t,useReplacer:n}=this;if(this.rootSchema=void 0,this.useReplacer=!1,t?.isStructSchema()||t?.isDocumentSchema()){if(!n)return JSON.stringify(this.buffer);let s=new aM;return s.replaceInJson(JSON.stringify(this.buffer,s.createReplacer(),0))}return this.buffer}writeDiscriminatedDocument(t,n){if(this.write(t,n),typeof this.buffer==="object")this.buffer.__type=ft.of(t).getName(!0)}_write(t,n,s){let i=n!==null&&typeof n==="object",r=ft.of(t);if(i){if(r.isStructSchema()){let e=n,f={},{jsonName:o}=this.settings,c=void 0;if(o)c={};let h=0;for(let[u,l]of r.structIterator()){let _=this._write(l,e[u],r);if(_!==void 0){let w=u;if(o)w=l.getMergedTraits().jsonName??u,c[u]=w;f[w]=_,h++}}if(r.isUnionSchema()&&h===0){let{$unknown:u}=e;if(Array.isArray(u)){let[l,_]=u;f[l]=this._write(15,_)}}else if(typeof e.__type==="string")for(let u in e){let l=e[u],_=o?c[u]??u:u;if(!(_ in f))f[_]=this._write(15,l)}return f}if(Array.isArray(n)&&r.isListSchema()){let e=r.getValueSchema(),f=[],o=!!r.getMergedTraits().sparse;for(let c of n)if(o||c!=null)f.push(this._write(e,c));return f}if(r.isMapSchema()){let e=r.getValueSchema(),f={},o=!!r.getMergedTraits().sparse;for(let c in n){let h=n[c];if(o||h!=null)f[c]=this._write(e,h)}return f}if(n instanceof Uint8Array&&(r.isBlobSchema()||r.isDocumentSchema())){if(r===this.rootSchema)return n;return(this.serdeContext?.base64Encoder??ke)(n)}if(n instanceof Date&&(r.isTimestampSchema()||r.isDocumentSchema()))switch(Xe(r,this.settings)){case 5:return n.toISOString().replace(".000Z","Z");case 6:return ze(n);case 7:return n.getTime()/1000;default:return console.warn("Missing timestamp format, using epoch seconds",n),n.getTime()/1000}if(n instanceof hn)this.useReplacer=!0}if(n===null&&s?.isStructSchema())return;if(r.isStringSchema()){if(typeof n>"u"&&r.isIdempotencyToken())return Eh();let e=r.getMergedTraits().mediaType;if(n!=null&&e){if(e==="application/json"||e.endsWith("+json"))return XM.from(n)}return n}if(typeof n==="number"&&r.isNumericSchema()){if(Math.abs(n)===1/0||isNaN(n))return String(n);return n}if(typeof n==="string"&&r.isBlobSchema()){if(r===this.rootSchema)return n;return(this.serdeContext?.base64Encoder??ke)(n)}if(typeof n==="bigint")this.useReplacer=!0;if(r.isDocumentSchema())if(i){let e=Array.isArray(n)?[]:{};for(let f in n){let o=n[f];if(o instanceof hn)this.useReplacer=!0,e[f]=o;else e[f]=this._write(r,o)}return e}else return structuredClone(n);return n}}class xe extends xn{settings;constructor(t){super();this.settings=t}createSerializer(){let t=new Sh(this.settings);return t.setSerdeContext(this.serdeContext),t}createDeserializer(){let t=new Th(this.settings);return t.setSerdeContext(this.serdeContext),t}}class qe extends mM{serializer;deserializer;serviceTarget;codec;mixin;awsQueryCompatible;constructor({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:i,jsonCodec:r}){super({defaultNamespace:t,errorTypeRegistries:n});this.serviceTarget=s,this.codec=r??new xe({timestampFormat:{useTrait:!0,default:7},jsonName:!1}),this.serializer=this.codec.createSerializer(),this.deserializer=this.codec.createDeserializer(),this.awsQueryCompatible=!!i,this.mixin=new oi(this.awsQueryCompatible)}async serializeRequest(t,n,s){let i=await super.serializeRequest(t,n,s);if(!i.path.endsWith("/"))i.path+="/";if(i.headers["content-type"]=`application/x-amz-json-${this.getJsonRpcVersion()}`,i.headers["x-amz-target"]=`${this.serviceTarget}.${t.name}`,this.awsQueryCompatible)i.headers["x-amzn-query-mode"]="true";if(WM(t.input)==="unit"||!i.body)i.body="{}";return i}getPayloadCodec(){return this.codec}async handleError(t,n,s,i,r){let{awsQueryCompatible:e}=this;if(e)this.mixin.setQueryCompatError(i,s);let f=VM(s,i,e)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,f,this.options.defaultNamespace);let{errorSchema:o,errorMetadata:c}=await this.mixin.getErrorSchemaOrThrowBaseException(f,this.options.defaultNamespace,s,i,r,e?this.mixin.findQueryCompatibleError:void 0),h=ft.of(o),u=i.message??i.Message??"UnknownError",_=new(this.compositeErrorRegistry.getErrorCtor(o)??Error)({}),w={},A=this.codec.createDeserializer();for(let[M,d]of h.structIterator())if(i[M]!=null)w[M]=A.readObject(d,i[M]);if(e)this.mixin.queryCompatOutput(i,w);throw this.mixin.decorateServiceException(Object.assign(_,c,{$fault:h.getMergedTraits().error,message:u},w),i)}}class pM extends qe{constructor({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:i,jsonCodec:r}){super({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:i,jsonCodec:r})}getShapeId(){return"aws.protocols#awsJson1_0"}getJsonRpcVersion(){return"1.0"}getDefaultContentType(){return"application/x-amz-json-1.0"}}class ZM extends qe{constructor({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:i,jsonCodec:r}){super({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:i,jsonCodec:r})}getShapeId(){return"aws.protocols#awsJson1_1"}getJsonRpcVersion(){return"1.1"}getDefaultContentType(){return"application/x-amz-json-1.1"}}class vM extends YM{serializer;deserializer;codec;mixin=new oi;constructor({defaultNamespace:t,errorTypeRegistries:n}){super({defaultNamespace:t,errorTypeRegistries:n});let s={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=new xe(s),this.serializer=new QM(this.codec.createSerializer(),s),this.deserializer=new JM(this.codec.createDeserializer(),s)}getShapeId(){return"aws.protocols#restJson1"}getPayloadCodec(){return this.codec}setSerdeContext(t){this.codec.setSerdeContext(t),super.setSerdeContext(t)}async serializeRequest(t,n,s){let i=await super.serializeRequest(t,n,s),r=ft.of(t.input);if(!i.headers["content-type"]){let e=this.mixin.resolveRestContentType(this.getDefaultContentType(),r);if(e)i.headers["content-type"]=e}if(i.body==null&&i.headers["content-type"]===this.getDefaultContentType())i.body="{}";return i}async deserializeResponse(t,n,s){let i=await super.deserializeResponse(t,n,s),r=ft.of(t.output);for(let[e,f]of r.structIterator())if(f.getMemberTraits().httpPayload&&!(e in i))i[e]=null;return i}async handleError(t,n,s,i,r){let e=KM(s,i)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace);let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,s,i,r),c=ft.of(f),h=i.message??i.Message??"UnknownError",l=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({});await this.deserializeHttpMessage(f,n,s,i);let _={},w=this.codec.createDeserializer();for(let[A,M]of c.structIterator()){let d=M.getMergedTraits().jsonName??A;_[A]=w.readObject(M,i[d])}throw this.mixin.decorateServiceException(Object.assign(l,o,{$fault:c.getMergedTraits().error,message:h},_),i)}getDefaultContentType(){return"application/json"}}var JF=(t)=>{if(t==null)return;if(typeof t==="object"&&"__type"in t)delete t.__type;return NF(t)};class Ce extends xn{settings;stringDeserializer;constructor(t){super();this.settings=t,this.stringDeserializer=new BF(t)}setSerdeContext(t){this.serdeContext=t,this.stringDeserializer.setSerdeContext(t)}read(t,n,s){let i=ft.of(t),r=i.getMemberSchemas();if(i.isStructSchema()&&i.isMemberSchema()&&!!Object.values(r).find((c)=>{return!!c.getMemberTraits().eventPayload})){let c={},h=Object.keys(r)[0];if(r[h].isBlobSchema())c[h]=n;else c[h]=this.read(r[h],n);return c}let f=(this.serdeContext?.utf8Encoder??kM)(n),o=this.parseXml(f);return this.readSchema(t,s?o[s]:o)}readSchema(t,n){let s=ft.of(t);if(s.isUnitSchema())return;let i=s.getMergedTraits();if(s.isListSchema()&&!Array.isArray(n))return this.readSchema(s,[n]);if(n==null)return n;if(typeof n==="object"){let r=!!i.xmlFlattened;if(s.isListSchema()){let f=s.getValueSchema(),o=[],c=f.getMergedTraits().xmlName??"member",h=r?n:(n[0]??n)[c];if(h==null)return o;let u=Array.isArray(h)?h:[h];for(let l of u)o.push(this.readSchema(f,l));return o}let e={};if(s.isMapSchema()){let f=s.getKeySchema(),o=s.getValueSchema(),c;if(r)c=Array.isArray(n)?n:[n];else c=Array.isArray(n.entry)?n.entry:[n.entry];let h=f.getMergedTraits().xmlName??"key",u=o.getMergedTraits().xmlName??"value";for(let l of c){let _=l[h],w=l[u];e[_]=this.readSchema(o,w)}return e}if(s.isStructSchema()){let f=s.isUnionSchema(),o;if(f)o=new Rh(n,e);for(let[c,h]of s.structIterator()){let u=h.getMergedTraits(),l=!u.httpPayload?h.getMemberTraits().xmlName??c:u.xmlName??h.getName();if(f)o.mark(l);if(n[l]!=null)e[c]=this.readSchema(h,n[l])}if(f)o.writeUnknown();return e}if(s.isDocumentSchema())return n;throw Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${s.getName(!0)}`)}if(s.isListSchema())return[];if(s.isMapSchema()||s.isStructSchema())return{};return this.stringDeserializer.read(s,n)}parseXml(t){if(t.length){let n;try{n=xM(t)}catch(e){if(e&&typeof e==="object")Object.defineProperty(e,"$responseBodyText",{value:t});throw e}let s="#text",i=Object.keys(n)[0],r=n[i];if(r[s])r[i]=r[s],delete r[s];return DM(r)}return{}}}class $h extends xn{settings;buffer;constructor(t){super();this.settings=t}write(t,n,s=""){if(this.buffer===void 0)this.buffer="";let i=ft.of(t);if(s&&!s.endsWith("."))s+=".";if(i.isBlobSchema()){if(typeof n==="string"||n instanceof Uint8Array)this.writeKey(s),this.writeValue((this.serdeContext?.base64Encoder??ke)(n))}else if(i.isBooleanSchema()||i.isNumericSchema()||i.isStringSchema()){if(n!=null)this.writeKey(s),this.writeValue(String(n));else if(i.isIdempotencyToken())this.writeKey(s),this.writeValue(Eh())}else if(i.isBigIntegerSchema()){if(n!=null)this.writeKey(s),this.writeValue(String(n))}else if(i.isBigDecimalSchema()){if(n!=null)this.writeKey(s),this.writeValue(n instanceof hn?n.string:String(n))}else if(i.isTimestampSchema()){if(n instanceof Date)switch(this.writeKey(s),Xe(i,this.settings)){case 5:this.writeValue(n.toISOString().replace(".000Z","Z"));break;case 6:this.writeValue(ze(n));break;case 7:this.writeValue(String(n.getTime()/1000));break}}else if(i.isDocumentSchema())if(Array.isArray(n))this.write(79,n,s);else if(n instanceof Date)this.write(4,n,s);else if(n instanceof Uint8Array)this.write(21,n,s);else if(n&&typeof n==="object")this.write(143,n,s);else this.writeKey(s),this.writeValue(String(n));else if(i.isListSchema()){if(Array.isArray(n))if(n.length===0){if(this.settings.serializeEmptyLists)this.writeKey(s),this.writeValue("")}else{let r=i.getValueSchema(),e=this.settings.flattenLists||i.getMergedTraits().xmlFlattened,f=1;for(let o of n){if(o==null)continue;let c=r.getMergedTraits(),h=this.getKey("member",c.xmlName,c.ec2QueryName),u=e?`${s}${f}`:`${s}${h}.${f}`;this.write(r,o,u),++f}}}else if(i.isMapSchema()){if(n&&typeof n==="object"){let r=i.getKeySchema(),e=i.getValueSchema(),f=i.getMergedTraits().xmlFlattened,o=1;for(let c in n){let h=n[c];if(h==null)continue;let u=r.getMergedTraits(),l=this.getKey("key",u.xmlName,u.ec2QueryName),_=f?`${s}${o}.${l}`:`${s}entry.${o}.${l}`,w=e.getMergedTraits(),A=this.getKey("value",w.xmlName,w.ec2QueryName),M=f?`${s}${o}.${A}`:`${s}entry.${o}.${A}`;this.write(r,c,_),this.write(e,h,M),++o}}}else if(i.isStructSchema()){if(n&&typeof n==="object"){let r=!1;for(let[e,f]of i.structIterator()){if(n[e]==null&&!f.isIdempotencyToken())continue;let o=f.getMergedTraits(),c=this.getKey(e,o.xmlName,o.ec2QueryName,"struct"),h=`${s}${c}`;this.write(f,n[e],h),r=!0}if(!r&&i.isUnionSchema()){let{$unknown:e}=n;if(Array.isArray(e)){let[f,o]=e,c=`${s}${f}`;this.write(15,o,c)}}}}else if(i.isUnitSchema());else throw Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${i.getName(!0)}`)}flush(){if(this.buffer===void 0)throw Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer.");let t=this.buffer;return delete this.buffer,t}getKey(t,n,s,i){let{ec2:r,capitalizeKeys:e}=this.settings;if(r&&s)return s;let f=n??t;if(e&&i==="struct")return f[0].toUpperCase()+f.slice(1);return f}writeKey(t){if(t.endsWith("."))t=t.slice(0,t.length-1);this.buffer+=`&${FM(t)}=`}writeValue(t){this.buffer+=FM(t)}}class Uh extends mM{options;serializer;deserializer;mixin=new oi;constructor(t){super({defaultNamespace:t.defaultNamespace,errorTypeRegistries:t.errorTypeRegistries});this.options=t;let n={timestampFormat:{useTrait:!0,default:5},httpBindings:!1,xmlNamespace:t.xmlNamespace,serviceNamespace:t.defaultNamespace,serializeEmptyLists:!0};this.serializer=new $h(n),this.deserializer=new Ce(n)}getShapeId(){return"aws.protocols#awsQuery"}setSerdeContext(t){this.serializer.setSerdeContext(t),this.deserializer.setSerdeContext(t)}getPayloadCodec(){throw Error("AWSQuery protocol has no payload codec.")}async serializeRequest(t,n,s){let i=await super.serializeRequest(t,n,s);if(!i.path.endsWith("/"))i.path+="/";if(i.headers["content-type"]="application/x-www-form-urlencoded",WM(t.input)==="unit"||!i.body)i.body="";let r=t.name.split("#")[1]??t.name;if(i.body=`Action=${r}&Version=${this.options.version}`+i.body,i.body.endsWith("&"))i.body=i.body.slice(-1);return i}async deserializeResponse(t,n,s){let i=this.deserializer,r=ft.of(t.output),e={};if(s.statusCode>=300){let h=await dh(s.body,n);if(h.byteLength>0)Object.assign(e,await i.read(15,h));await this.handleError(t,n,s,e,this.deserializeMetadata(s))}for(let h in s.headers){let u=s.headers[h];delete s.headers[h],s.headers[h.toLowerCase()]=u}let f=t.name.split("#")[1]??t.name,o=r.isStructSchema()&&this.useNestedResult()?f+"Result":void 0,c=await dh(s.body,n);if(c.byteLength>0)Object.assign(e,await i.read(r,c,o));return e.$metadata=this.deserializeMetadata(s),e}useNestedResult(){return!0}async handleError(t,n,s,i,r){let e=this.loadQueryErrorCode(s,i)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace);let f=this.loadQueryError(i)??{},o=this.loadQueryErrorMessage(i);f.message=o,f.Error={Type:f.Type,Code:f.Code,Message:o};let{errorSchema:c,errorMetadata:h}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,s,f,r,this.mixin.findQueryCompatibleError),u=ft.of(c),_=new(this.compositeErrorRegistry.getErrorCtor(c)??Error)({}),w={Type:f.Error.Type,Code:f.Error.Code,Error:f.Error};for(let[A,M]of u.structIterator()){let d=M.getMergedTraits().xmlName??A,E=f[d]??i[d];w[A]=this.deserializer.readSchema(M,E)}throw this.mixin.decorateServiceException(Object.assign(_,h,{$fault:u.getMergedTraits().error,message:o},w),i)}loadQueryErrorCode(t,n){let s=(n.Errors?.[0]?.Error??n.Errors?.Error??n.Error)?.Code;if(s!==void 0)return s;if(t.statusCode==404)return"NotFound"}loadQueryError(t){return t.Errors?.[0]?.Error??t.Errors?.Error??t.Error}loadQueryErrorMessage(t){let n=this.loadQueryError(t);return n?.message??n?.Message??t.message??t.Message??"Unknown"}getDefaultContentType(){return"application/x-www-form-urlencoded"}}class t1 extends Uh{options;constructor(t){super(t);this.options=t;let n={capitalizeKeys:!0,flattenLists:!0,serializeEmptyLists:!1,ec2:!0};Object.assign(this.serializer.settings,n)}getShapeId(){return"aws.protocols#ec2Query"}useNestedResult(){return!1}}var n1=(t,n)=>CM(t,n).then((s)=>{if(s.length){let i;try{i=xM(s)}catch(o){if(o&&typeof o==="object")Object.defineProperty(o,"$responseBodyText",{value:s});throw o}let r="#text",e=Object.keys(i)[0],f=i[e];if(f[r])f[e]=f[r],delete f[r];return DM(f)}return{}}),kF=async(t,n)=>{let s=await n1(t,n);if(s.Error)s.Error.message=s.Error.message??s.Error.Message;return s},s1=(t,n)=>{if(n?.Error?.Code!==void 0)return n.Error.Code;if(n?.Code!==void 0)return n.Code;if(t.statusCode==404)return"NotFound"};class Lh extends xn{settings;stringBuffer;byteBuffer;buffer;constructor(t){super();this.settings=t}write(t,n){let s=ft.of(t);if(s.isStringSchema()&&typeof n==="string")this.stringBuffer=n;else if(s.isBlobSchema())this.byteBuffer="byteLength"in n?n:(this.serdeContext?.base64Decoder??zM)(n);else{this.buffer=this.writeStruct(s,n,void 0);let i=s.getMergedTraits();if(i.httpPayload&&!i.xmlName)this.buffer.withName(s.getName())}}flush(){if(this.byteBuffer!==void 0){let n=this.byteBuffer;return delete this.byteBuffer,n}if(this.stringBuffer!==void 0){let n=this.stringBuffer;return delete this.stringBuffer,n}let t=this.buffer;if(this.settings.xmlNamespace){if(!t?.attributes?.xmlns)t.addAttribute("xmlns",this.settings.xmlNamespace)}return delete this.buffer,t.toString()}writeStruct(t,n,s){let i=t.getMergedTraits(),r=t.isMemberSchema()&&!i.httpPayload?t.getMemberTraits().xmlName??t.getMemberName():i.xmlName??t.getName();if(!r||!t.isStructSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${t.getName(!0)}.`);let e=Ct.of(r),[f,o]=this.getXmlnsAttribute(t,s);for(let[h,u]of t.structIterator()){let l=n[h];if(l!=null||u.isIdempotencyToken()){if(u.getMergedTraits().xmlAttribute){e.addAttribute(u.getMergedTraits().xmlName??h,this.writeSimple(u,l));continue}if(u.isListSchema())this.writeList(u,l,e,o);else if(u.isMapSchema())this.writeMap(u,l,e,o);else if(u.isStructSchema())e.addChildNode(this.writeStruct(u,l,o));else{let _=Ct.of(u.getMergedTraits().xmlName??u.getMemberName());this.writeSimpleInto(u,l,_,o),e.addChildNode(_)}}}let{$unknown:c}=n;if(c&&t.isUnionSchema()&&Array.isArray(c)&&Object.keys(n).length===1){let[h,u]=c,l=Ct.of(h);if(typeof u!=="string")if(n instanceof Ct||n instanceof HM)e.addChildNode(n);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,u,l,o),e.addChildNode(l)}if(o)e.addAttribute(f,o);return e}writeList(t,n,s,i){if(!t.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${t.getName(!0)}`);let r=t.getMergedTraits(),e=t.getValueSchema(),f=e.getMergedTraits(),o=!!f.sparse,c=!!r.xmlFlattened,[h,u]=this.getXmlnsAttribute(t,i),l=(_,w)=>{if(e.isListSchema())this.writeList(e,Array.isArray(w)?w:[w],_,u);else if(e.isMapSchema())this.writeMap(e,w,_,u);else if(e.isStructSchema()){let A=this.writeStruct(e,w,u);_.addChildNode(A.withName(c?r.xmlName??t.getMemberName():f.xmlName??"member"))}else{let A=Ct.of(c?r.xmlName??t.getMemberName():f.xmlName??"member");this.writeSimpleInto(e,w,A,u),_.addChildNode(A)}};if(c){for(let _ of n)if(o||_!=null)l(s,_)}else{let _=Ct.of(r.xmlName??t.getMemberName());if(u)_.addAttribute(h,u);for(let w of n)if(o||w!=null)l(_,w);s.addChildNode(_)}}writeMap(t,n,s,i,r=!1){if(!t.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${t.getName(!0)}`);let e=t.getMergedTraits(),f=t.getKeySchema(),c=f.getMergedTraits().xmlName??"key",h=t.getValueSchema(),u=h.getMergedTraits(),l=u.xmlName??"value",_=!!u.sparse,w=!!e.xmlFlattened,[A,M]=this.getXmlnsAttribute(t,i),d=(E,T,U)=>{let S=Ct.of(c,T),[y,D]=this.getXmlnsAttribute(f,M);if(D)S.addAttribute(y,D);E.addChildNode(S);let q=Ct.of(l);if(h.isListSchema())this.writeList(h,U,q,M);else if(h.isMapSchema())this.writeMap(h,U,q,M,!0);else if(h.isStructSchema())q=this.writeStruct(h,U,M);else this.writeSimpleInto(h,U,q,M);E.addChildNode(q)};if(w)for(let E in n){let T=n[E];if(_||T!=null){let U=Ct.of(e.xmlName??t.getMemberName());d(U,E,T),s.addChildNode(U)}}else{let E;if(!r){if(E=Ct.of(e.xmlName??t.getMemberName()),M)E.addAttribute(A,M);s.addChildNode(E)}for(let T in n){let U=n[T];if(_||U!=null){let S=Ct.of("entry");d(S,T,U),(r?s:E).addChildNode(S)}}}}writeSimple(t,n){if(n===null)throw Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value.");let s=ft.of(t),i=null;if(n&&typeof n==="object")if(s.isBlobSchema())i=(this.serdeContext?.base64Encoder??ke)(n);else if(s.isTimestampSchema()&&n instanceof Date)switch(Xe(s,this.settings)){case 5:i=n.toISOString().replace(".000Z","Z");break;case 6:i=ze(n);break;case 7:i=String(n.getTime()/1000);break;default:console.warn("Missing timestamp format, using http date",n),i=ze(n);break}else if(s.isBigDecimalSchema()&&n){if(n instanceof hn)return n.string;return String(n)}else if(s.isMapSchema()||s.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: ${s.getName(!0)}`);if(s.isBooleanSchema()||s.isNumericSchema()||s.isBigIntegerSchema()||s.isBigDecimalSchema())i=String(n);if(s.isStringSchema())if(n===void 0&&s.isIdempotencyToken())i=Eh();else i=String(n);if(i===null)throw Error(`Unhandled schema-value pair ${s.getName(!0)}=${n}`);return i}writeSimpleInto(t,n,s,i){let r=this.writeSimple(t,n),e=ft.of(t),f=new HM(r),[o,c]=this.getXmlnsAttribute(e,i);if(c)s.addAttribute(o,c);s.addChildNode(f)}getXmlnsAttribute(t,n){let s=t.getMergedTraits(),[i,r]=s.xmlNamespace??[];if(r&&r!==n)return[i?`xmlns:${i}`:"xmlns",r];return[void 0,void 0]}}class Ih extends xn{settings;constructor(t){super();this.settings=t}createSerializer(){let t=new Lh(this.settings);return t.setSerdeContext(this.serdeContext),t}createDeserializer(){let t=new Ce(this.settings);return t.setSerdeContext(this.serdeContext),t}}class i1 extends YM{codec;serializer;deserializer;mixin=new oi;constructor(t){super(t);let n={timestampFormat:{useTrait:!0,default:5},httpBindings:!0,xmlNamespace:t.xmlNamespace,serviceNamespace:t.defaultNamespace};this.codec=new Ih(n),this.serializer=new QM(this.codec.createSerializer(),n),this.deserializer=new JM(this.codec.createDeserializer(),n)}getPayloadCodec(){return this.codec}getShapeId(){return"aws.protocols#restXml"}async serializeRequest(t,n,s){let i=await super.serializeRequest(t,n,s),r=ft.of(t.input);if(!i.headers["content-type"]){let e=this.mixin.resolveRestContentType(this.getDefaultContentType(),r);if(e)i.headers["content-type"]=e}if(typeof i.body==="string"&&i.headers["content-type"]===this.getDefaultContentType()&&!i.body.startsWith("<?xml ")&&!this.hasUnstructuredPayloadBinding(r))i.body='<?xml version="1.0" encoding="UTF-8"?>'+i.body;return i}async deserializeResponse(t,n,s){return super.deserializeResponse(t,n,s)}async handleError(t,n,s,i,r){let e=s1(s,i)??"Unknown";if(this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace),i.Error&&typeof i.Error==="object"){for(let A of Object.keys(i.Error))if(i[A]=i.Error[A],A.toLowerCase()==="message")i.message=i.Error[A]}if(i.RequestId&&!r.requestId)r.requestId=i.RequestId;let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,s,i,r),c=ft.of(f),h=i.Error?.message??i.Error?.Message??i.message??i.Message??"UnknownError",l=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({});await this.deserializeHttpMessage(f,n,s,i);let _={},w=this.codec.createDeserializer();for(let[A,M]of c.structIterator()){let d=M.getMergedTraits().xmlName??A,E=i.Error?.[d]??i[d];_[A]=w.readSchema(M,E)}throw this.mixin.decorateServiceException(Object.assign(l,o,{$fault:c.getMergedTraits().error,message:h},_),i)}getDefaultContentType(){return"application/xml"}hasUnstructuredPayloadBinding(t){for(let[,n]of t.structIterator())if(n.getMergedTraits().httpPayload)return!(n.isStructSchema()||n.isMapSchema()||n.isListSchema());return!1}}zF.AwsEc2QueryProtocol=t1;zF.AwsJson1_0Protocol=pM;zF.AwsJson1_1Protocol=ZM;zF.AwsJsonRpcProtocol=qe;zF.AwsQueryProtocol=Uh;zF.AwsRestJsonProtocol=vM;zF.AwsRestXmlProtocol=i1;zF.AwsSmithyRpcV2CborProtocol=qM;zF.JsonCodec=xe;zF.JsonShapeDeserializer=Th;zF.JsonShapeSerializer=Sh;zF.QueryShapeSerializer=$h;zF.XmlCodec=Ih;zF.XmlShapeDeserializer=Ce;zF.XmlShapeSerializer=Lh;zF._toBool=DF;zF._toNum=mF;zF._toStr=WF;zF.awsExpectUnion=JF;zF.loadJsonRpcErrorCode=VM;zF.loadRestJsonErrorCode=KM;zF.loadRestXmlErrorCode=s1;zF.parseJsonBody=bh;zF.parseJsonErrorBody=QF;zF.parseXmlBody=n1;zF.parseXmlErrorBody=kF});var Ph=Z((GN)=>{var{awsEndpointFunctions:MH,emitWarningIfUnsupportedVersion:gH,createDefaultUserAgentProvider:dH,NODE_APP_ID_CONFIG_OPTIONS:EH,getAwsRegionExtensionConfiguration:RH,resolveAwsRegionExtensionConfiguration:bH,resolveUserAgentConfig:TH,resolveHostHeaderConfig:SH,getUserAgentPlugin:$H,getHostHeaderPlugin:UH,getLoggerPlugin:LH,getRecursionDetectionPlugin:IH}=xt(),{NoAuthSigner:yH,getHttpAuthSchemeEndpointRuleSetPlugin:OH,DefaultIdentityProviderConfig:GH,getHttpSigningPlugin:BH}=kn(),{normalizeProvider:c1,getSmithyContext:FH,ServiceException:HH,NoOpLogger:PH,emitWarningIfUnsupportedVersion:NH,loadConfigsForDefaultMode:WH,getDefaultExtensionConfiguration:DH,resolveDefaultRuntimeConfig:mH,Client:h1,makeBuilder:YH,createAggregatedClient:QH}=Rn(),{Command:JH}=Rn();GN.$Command=JH;GN.__Client=h1;var{resolveDefaultsModeConfig:kH,loadConfig:As,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:zH,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:XH,NODE_REGION_CONFIG_OPTIONS:xH,NODE_REGION_CONFIG_FILE_OPTIONS:qH,resolveRegionConfig:CH}=St(),{BinaryDecisionDiagram:KH,EndpointCache:VH,decideEndpoint:jH,customEndpointFunctions:aH,resolveEndpointConfig:pH,getEndpointPlugin:ZH}=fs(),{parseUrl:vH,getHttpHandlerExtensionConfiguration:tP,resolveHttpHandlerRuntimeConfig:nP,getContentLengthPlugin:sP}=Ut(),{DEFAULT_RETRY_MODE:iP,NODE_RETRY_MODE_CONFIG_OPTIONS:rP,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:eP,resolveRetryConfig:oP,getRetryPlugin:fP}=vi(),{TypeRegistry:u1,getSchemaSerdePlugin:cP}=Nn(),{resolveAwsSdkSigV4Config:hP,AwsSdkSigV4Signer:uP,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:lP}=jc(),{toUtf8:_P,fromUtf8:wP,toBase64:AP,fromBase64:MP,calculateBodyLength:gP}=$t(),{streamCollector:dP,NodeHttpHandler:EP}=Ye(),{AwsRestJsonProtocol:RP}=yh(),{Sha256:bP}=tc(),TP=async(t,n,s)=>{return{operation:FH(n).operation,region:await c1(t.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()}};function SP(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:t.region},propertiesExtractor:(n,s)=>({signingProperties:{config:n,context:s}})}}function $P(t){return{schemeId:"smithy.api#noAuth"}}var UP=(t)=>{let n=[];switch(t.operation){case"CreateToken":{n.push($P());break}default:n.push(SP(t))}return n},LP=(t)=>{let n=hP(t);return Object.assign(n,{authSchemePreference:c1(t.authSchemePreference??[])})},IP=(t)=>{return Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"})},yP={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},OP="3.997.32",GP={version:OP},_r="ref",Ms=-1,Ke=!0,r1="isSet",l1="PartitionResult",Ve="booleanEquals",Oh="getAttr",e1={[_r]:"Endpoint"},Gh={[_r]:l1},fi={},o1=[{[_r]:"Region"}],f1={conditions:[[r1,[e1]],[r1,o1],["aws.partition",o1,l1],[Ve,[{[_r]:"UseFIPS"},Ke]],[Ve,[{[_r]:"UseDualStack"},Ke]],[Ve,[{fn:Oh,argv:[Gh,"supportsDualStack"]},Ke]],[Ve,[{fn:Oh,argv:[Gh,"supportsFIPS"]},Ke]],["stringEquals",[{fn:Oh,argv:[Gh,"name"]},"aws-us-gov"]]],results:[[Ms],[Ms,"Invalid Configuration: FIPS and custom endpoint are not supported"],[Ms,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[e1,fi],["https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",fi],[Ms,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://oidc.{Region}.amazonaws.com",fi],["https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",fi],[Ms,"FIPS is enabled but this partition does not support FIPS"],["https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",fi],[Ms,"DualStack is enabled but this partition does not support DualStack"],["https://oidc.{Region}.{PartitionResult#dnsSuffix}",fi],[Ms,"Invalid Configuration: Missing Region"]]},BP=2,Lt=1e8,FP=new Int32Array([-1,1,-1,0,13,3,1,4,Lt+12,2,5,Lt+12,3,8,6,4,7,Lt+11,5,Lt+9,Lt+10,4,11,9,6,10,Lt+8,7,Lt+6,Lt+7,5,12,Lt+5,6,Lt+4,Lt+5,3,Lt+1,14,4,Lt+2,Lt+3]),HP=KH.from(FP,BP,f1.conditions,f1.results),PP=new VH({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),NP=(t,n={})=>{return PP.get(t,()=>jH(HP,{endpointParams:t,logger:n.logger}))};aH.aws=MH;class Rt extends HH{constructor(t){super(t);Object.setPrototypeOf(this,Rt.prototype)}}class je extends Rt{name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(t){super({name:"AccessDeniedException",$fault:"client",...t});Object.setPrototypeOf(this,je.prototype),this.error=t.error,this.reason=t.reason,this.error_description=t.error_description}}class ae extends Rt{name="AuthorizationPendingException";$fault="client";error;error_description;constructor(t){super({name:"AuthorizationPendingException",$fault:"client",...t});Object.setPrototypeOf(this,ae.prototype),this.error=t.error,this.error_description=t.error_description}}class pe extends Rt{name="ExpiredTokenException";$fault="client";error;error_description;constructor(t){super({name:"ExpiredTokenException",$fault:"client",...t});Object.setPrototypeOf(this,pe.prototype),this.error=t.error,this.error_description=t.error_description}}class Ze extends Rt{name="InternalServerException";$fault="server";error;error_description;constructor(t){super({name:"InternalServerException",$fault:"server",...t});Object.setPrototypeOf(this,Ze.prototype),this.error=t.error,this.error_description=t.error_description}}class ve extends Rt{name="InvalidClientException";$fault="client";error;error_description;constructor(t){super({name:"InvalidClientException",$fault:"client",...t});Object.setPrototypeOf(this,ve.prototype),this.error=t.error,this.error_description=t.error_description}}class to extends Rt{name="InvalidGrantException";$fault="client";error;error_description;constructor(t){super({name:"InvalidGrantException",$fault:"client",...t});Object.setPrototypeOf(this,to.prototype),this.error=t.error,this.error_description=t.error_description}}class no extends Rt{name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(t){super({name:"InvalidRequestException",$fault:"client",...t});Object.setPrototypeOf(this,no.prototype),this.error=t.error,this.reason=t.reason,this.error_description=t.error_description}}class so extends Rt{name="InvalidScopeException";$fault="client";error;error_description;constructor(t){super({name:"InvalidScopeException",$fault:"client",...t});Object.setPrototypeOf(this,so.prototype),this.error=t.error,this.error_description=t.error_description}}class io extends Rt{name="SlowDownException";$fault="client";error;error_description;constructor(t){super({name:"SlowDownException",$fault:"client",...t});Object.setPrototypeOf(this,io.prototype),this.error=t.error,this.error_description=t.error_description}}class ro extends Rt{name="UnauthorizedClientException";$fault="client";error;error_description;constructor(t){super({name:"UnauthorizedClientException",$fault:"client",...t});Object.setPrototypeOf(this,ro.prototype),this.error=t.error,this.error_description=t.error_description}}class eo extends Rt{name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(t){super({name:"UnsupportedGrantTypeException",$fault:"client",...t});Object.setPrototypeOf(this,eo.prototype),this.error=t.error,this.error_description=t.error_description}}var WP="AccessDeniedException",DP="AuthorizationPendingException",mP="AccessToken",YP="ClientSecret",QP="CreateToken",JP="CreateTokenRequest",kP="CreateTokenResponse",zP="CodeVerifier",XP="ExpiredTokenException",xP="InvalidClientException",qP="InvalidGrantException",CP="InvalidRequestException",KP="InternalServerException",VP="InvalidScopeException",jP="IdToken",aP="RefreshToken",pP="SlowDownException",ZP="UnauthorizedClientException",vP="UnsupportedGrantTypeException",tN="accessToken",un="client",nN="clientId",sN="clientSecret",iN="codeVerifier",rN="code",eN="deviceCode",et="error",oN="expiresIn",Kt="error_description",fN="grantType",cN="http",Vt="httpError",hN="idToken",_1="reason",w1="refreshToken",uN="redirectUri",A1="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",lN="scope",_N="server",wN="tokenType",ct="com.amazonaws.ssooidc",M1=u1.for(A1),g1=[-3,A1,"SSOOIDCServiceException",0,[],[]];M1.registerError(g1,Rt);var mt=u1.for(ct),d1=[-3,ct,WP,{[et]:un,[Vt]:400},[et,_1,Kt],[0,0,0]];mt.registerError(d1,je);var E1=[-3,ct,DP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];mt.registerError(E1,ae);var R1=[-3,ct,XP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];mt.registerError(R1,pe);var b1=[-3,ct,KP,{[et]:_N,[Vt]:500},[et,Kt],[0,0]];mt.registerError(b1,Ze);var T1=[-3,ct,xP,{[et]:un,[Vt]:401},[et,Kt],[0,0]];mt.registerError(T1,ve);var S1=[-3,ct,qP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];mt.registerError(S1,to);var $1=[-3,ct,CP,{[et]:un,[Vt]:400},[et,_1,Kt],[0,0,0]];mt.registerError($1,no);var U1=[-3,ct,VP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];mt.registerError(U1,so);var L1=[-3,ct,pP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];mt.registerError(L1,io);var I1=[-3,ct,ZP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];mt.registerError(I1,ro);var y1=[-3,ct,vP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];mt.registerError(y1,eo);var O1=[M1,mt],AN=[0,ct,mP,8,0],MN=[0,ct,YP,8,0],gN=[0,ct,zP,8,0],dN=[0,ct,jP,8,0],G1=[0,ct,aP,8,0],B1=[3,ct,JP,0,[nN,sN,fN,eN,rN,w1,lN,uN,iN],[0,[()=>MN,0],0,0,0,[()=>G1,0],64,0,[()=>gN,0]],3],F1=[3,ct,kP,0,[tN,wN,oN,w1,hN],[[()=>AN,0],0,1,[()=>G1,0],[()=>dN,0]]],H1=[9,ct,QP,{[cN]:["POST","/token",200]},()=>B1,()=>F1],EN=(t)=>{return{apiVersion:"2019-06-10",base64Decoder:t?.base64Decoder??MP,base64Encoder:t?.base64Encoder??AP,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??NP,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??UP,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(n)=>n.getIdentityProvider("aws.auth#sigv4"),signer:new uP},{schemeId:"smithy.api#noAuth",identityProvider:(n)=>n.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new yH}],logger:t?.logger??new PH,protocol:t?.protocol??RP,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:O1,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:t?.serviceId??"SSO OIDC",sha256:t?.sha256??bP,urlParser:t?.urlParser??vH,utf8Decoder:t?.utf8Decoder??wP,utf8Encoder:t?.utf8Encoder??_P}},RN=(t)=>{NH(process.version);let n=kH(t),s=()=>n().then(WH),i=EN(t);gH(process.version);let r={profile:t?.profile,logger:i.logger};return{...i,...t,runtime:"node",defaultsMode:n,authSchemePreference:t?.authSchemePreference??As(lP,r),bodyLengthChecker:t?.bodyLengthChecker??gP,defaultUserAgentProvider:t?.defaultUserAgentProvider??dH({serviceId:i.serviceId,clientVersion:GP.version}),maxAttempts:t?.maxAttempts??As(eP,t),region:t?.region??As(xH,{...qH,...r}),requestHandler:EP.create(t?.requestHandler??s),retryMode:t?.retryMode??As({...rP,default:async()=>(await s()).retryMode||iP},t),streamCollector:t?.streamCollector??dP,useDualstackEndpoint:t?.useDualstackEndpoint??As(XH,r),useFipsEndpoint:t?.useFipsEndpoint??As(zH,r),userAgentAppId:t?.userAgentAppId??As(EH,r)}},bN=(t)=>{let{httpAuthSchemes:n,httpAuthSchemeProvider:s,credentials:i}=t;return{setHttpAuthScheme(r){let e=n.findIndex((f)=>f.schemeId===r.schemeId);if(e===-1)n.push(r);else n.splice(e,1,r)},httpAuthSchemes(){return n},setHttpAuthSchemeProvider(r){s=r},httpAuthSchemeProvider(){return s},setCredentials(r){i=r},credentials(){return i}}},TN=(t)=>{return{httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),credentials:t.credentials()}},SN=(t,n)=>{let s=Object.assign(RH(t),DH(t),tP(t),bN(t));return n.forEach((i)=>i.configure(s)),Object.assign(t,bH(s),mH(s),nP(s),TN(s))};class Bh extends h1{config;constructor(...[t]){let n=RN(t||{});super(n);this.initConfig=n;let s=IP(n),i=TH(s),r=oP(i),e=CH(r),f=SH(e),o=pH(f),c=LP(o),h=SN(c,t?.extensions||[]);this.config=h,this.middlewareStack.use(cP(this.config)),this.middlewareStack.use($H(this.config)),this.middlewareStack.use(fP(this.config)),this.middlewareStack.use(sP(this.config)),this.middlewareStack.use(UH(this.config)),this.middlewareStack.use(LH(this.config)),this.middlewareStack.use(IH(this.config)),this.middlewareStack.use(OH(this.config,{httpAuthSchemeParametersProvider:TP,identityProviderConfigProvider:async(u)=>new GH({"aws.auth#sigv4":u.credentials})})),this.middlewareStack.use(BH(this.config))}destroy(){super.destroy()}}var $N=YH(yP,"AWSSSOOIDCService","SSOOIDCClient",ZH),UN={},LN=(t,n,s,i)=>[];class Fh extends $N(UN,LN,"CreateToken",H1){}var IN={CreateTokenCommand:Fh};class Hh extends Bh{}QH(IN,Hh);var yN={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},ON={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"};GN.AccessDeniedException=je;GN.AccessDeniedException$=d1;GN.AccessDeniedExceptionReason=yN;GN.AuthorizationPendingException=ae;GN.AuthorizationPendingException$=E1;GN.CreateToken$=H1;GN.CreateTokenCommand=Fh;GN.CreateTokenRequest$=B1;GN.CreateTokenResponse$=F1;GN.ExpiredTokenException=pe;GN.ExpiredTokenException$=R1;GN.InternalServerException=Ze;GN.InternalServerException$=b1;GN.InvalidClientException=ve;GN.InvalidClientException$=T1;GN.InvalidGrantException=to;GN.InvalidGrantException$=S1;GN.InvalidRequestException=no;GN.InvalidRequestException$=$1;GN.InvalidRequestExceptionReason=ON;GN.InvalidScopeException=so;GN.InvalidScopeException$=U1;GN.SSOOIDC=Hh;GN.SSOOIDCClient=Bh;GN.SSOOIDCServiceException=Rt;GN.SSOOIDCServiceException$=g1;GN.SlowDownException=io;GN.SlowDownException$=L1;GN.UnauthorizedClientException=ro;GN.UnauthorizedClientException$=I1;GN.UnsupportedGrantTypeException=eo;GN.UnsupportedGrantTypeException$=y1;GN.errorTypeRegistries=O1});import{existsSync as sR,readFileSync as iR}from"fs";import{homedir as rR}from"os";import{join as G0}from"path";var g={};Xd(g,{void:()=>yE,util:()=>x,unknown:()=>LE,union:()=>FE,undefined:()=>SE,tuple:()=>NE,transformer:()=>xE,symbol:()=>TE,string:()=>I0,strictObject:()=>BE,setErrorMap:()=>Cd,set:()=>mE,record:()=>WE,quotelessJson:()=>xd,promise:()=>XE,preprocess:()=>KE,pipeline:()=>VE,ostring:()=>jE,optional:()=>qE,onumber:()=>aE,oboolean:()=>pE,objectUtil:()=>Jo,object:()=>GE,number:()=>y0,nullable:()=>CE,null:()=>$E,never:()=>IE,nativeEnum:()=>zE,nan:()=>EE,map:()=>DE,makeIssue:()=>gi,literal:()=>JE,lazy:()=>QE,late:()=>gE,isValid:()=>yn,isDirty:()=>Sr,isAsync:()=>Ss,isAborted:()=>Tr,intersection:()=>PE,instanceof:()=>dE,getParsedType:()=>at,getErrorMap:()=>Ts,function:()=>YE,enum:()=>kE,effect:()=>xE,discriminatedUnion:()=>HE,defaultErrorMap:()=>An,datetimeRegex:()=>$0,date:()=>bE,custom:()=>L0,coerce:()=>ZE,boolean:()=>O0,bigint:()=>RE,array:()=>OE,any:()=>UE,addIssueToContext:()=>L,ZodVoid:()=>Ei,ZodUnknown:()=>On,ZodUnion:()=>Os,ZodUndefined:()=>Is,ZodType:()=>z,ZodTuple:()=>Zt,ZodTransformer:()=>zt,ZodSymbol:()=>di,ZodString:()=>Yt,ZodSet:()=>pn,ZodSchema:()=>z,ZodRecord:()=>Ri,ZodReadonly:()=>Ws,ZodPromise:()=>Zn,ZodPipeline:()=>Si,ZodParsedType:()=>$,ZodOptional:()=>Jt,ZodObject:()=>it,ZodNumber:()=>Gn,ZodNullable:()=>gn,ZodNull:()=>ys,ZodNever:()=>pt,ZodNativeEnum:()=>Hs,ZodNaN:()=>Ti,ZodMap:()=>bi,ZodLiteral:()=>Fs,ZodLazy:()=>Bs,ZodIssueCode:()=>b,ZodIntersection:()=>Gs,ZodFunction:()=>Us,ZodFirstPartyTypeKind:()=>N,ZodError:()=>bt,ZodEnum:()=>Fn,ZodEffects:()=>zt,ZodDiscriminatedUnion:()=>$r,ZodDefault:()=>Ps,ZodDate:()=>jn,ZodCatch:()=>Ns,ZodBranded:()=>Ur,ZodBoolean:()=>Ls,ZodBigInt:()=>Bn,ZodArray:()=>Qt,ZodAny:()=>an,Schema:()=>z,ParseStatus:()=>_t,OK:()=>gt,NEVER:()=>vE,INVALID:()=>P,EMPTY_PATH:()=>Kd,DIRTY:()=>Vn,BRAND:()=>ME});var x;(function(t){t.assertEqual=(r)=>{};function n(r){}t.assertIs=n;function s(r){throw Error()}t.assertNever=s,t.arrayToEnum=(r)=>{let e={};for(let f of r)e[f]=f;return e},t.getValidEnumValues=(r)=>{let e=t.objectKeys(r).filter((o)=>typeof r[r[o]]!=="number"),f={};for(let o of e)f[o]=r[o];return t.objectValues(f)},t.objectValues=(r)=>{return t.objectKeys(r).map(function(e){return r[e]})},t.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},t.find=(r,e)=>{for(let f of r)if(e(f))return f;return},t.isInteger=typeof Number.isInteger==="function"?(r)=>Number.isInteger(r):(r)=>typeof r==="number"&&Number.isFinite(r)&&Math.floor(r)===r;function i(r,e=" | "){return r.map((f)=>typeof f==="string"?`'${f}'`:f).join(e)}t.joinValues=i,t.jsonStringifyReplacer=(r,e)=>{if(typeof e==="bigint")return e.toString();return e}})(x||(x={}));var Jo;(function(t){t.mergeShapes=(n,s)=>{return{...n,...s}}})(Jo||(Jo={}));var $=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),at=(t)=>{switch(typeof t){case"undefined":return $.undefined;case"string":return $.string;case"number":return Number.isNaN(t)?$.nan:$.number;case"boolean":return $.boolean;case"function":return $.function;case"bigint":return $.bigint;case"symbol":return $.symbol;case"object":if(Array.isArray(t))return $.array;if(t===null)return $.null;if(t.then&&typeof t.then==="function"&&t.catch&&typeof t.catch==="function")return $.promise;if(typeof Map<"u"&&t instanceof Map)return $.map;if(typeof Set<"u"&&t instanceof Set)return $.set;if(typeof Date<"u"&&t instanceof Date)return $.date;return $.object;default:return $.unknown}};var b=x.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"]),xd=(t)=>{return JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:")};class bt extends Error{get errors(){return this.issues}constructor(t){super();this.issues=[],this.addIssue=(s)=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let n=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,n);else this.__proto__=n;this.name="ZodError",this.issues=t}format(t){let n=t||function(r){return r.message},s={_errors:[]},i=(r)=>{for(let e of r.issues)if(e.code==="invalid_union")e.unionErrors.map(i);else if(e.code==="invalid_return_type")i(e.returnTypeError);else if(e.code==="invalid_arguments")i(e.argumentsError);else if(e.path.length===0)s._errors.push(n(e));else{let f=s,o=0;while(o<e.path.length){let c=e.path[o];if(o!==e.path.length-1)f[c]=f[c]||{_errors:[]};else f[c]=f[c]||{_errors:[]},f[c]._errors.push(n(e));f=f[c],o++}}};return i(this),s}static assert(t){if(!(t instanceof bt))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=(n)=>n.message){let n={},s=[];for(let i of this.issues)if(i.path.length>0){let r=i.path[0];n[r]=n[r]||[],n[r].push(t(i))}else s.push(t(i));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}bt.create=(t)=>{return new bt(t)};var qd=(t,n)=>{let s;switch(t.code){case b.invalid_type:if(t.received===$.undefined)s="Required";else s=`Expected ${t.expected}, received ${t.received}`;break;case b.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(t.expected,x.jsonStringifyReplacer)}`;break;case b.unrecognized_keys:s=`Unrecognized key(s) in object: ${x.joinValues(t.keys,", ")}`;break;case b.invalid_union:s="Invalid input";break;case b.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${x.joinValues(t.options)}`;break;case b.invalid_enum_value:s=`Invalid enum value. Expected ${x.joinValues(t.options)}, received '${t.received}'`;break;case b.invalid_arguments:s="Invalid function arguments";break;case b.invalid_return_type:s="Invalid function return type";break;case b.invalid_date:s="Invalid date";break;case b.invalid_string:if(typeof t.validation==="object")if("includes"in t.validation){if(s=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position==="number")s=`${s} at one or more positions greater than or equal to ${t.validation.position}`}else if("startsWith"in t.validation)s=`Invalid input: must start with "${t.validation.startsWith}"`;else if("endsWith"in t.validation)s=`Invalid input: must end with "${t.validation.endsWith}"`;else x.assertNever(t.validation);else if(t.validation!=="regex")s=`Invalid ${t.validation}`;else s="Invalid";break;case b.too_small:if(t.type==="array")s=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`;else if(t.type==="string")s=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`;else if(t.type==="number")s=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`;else if(t.type==="bigint")s=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`;else if(t.type==="date")s=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`;else s="Invalid input";break;case b.too_big:if(t.type==="array")s=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`;else if(t.type==="string")s=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`;else if(t.type==="number")s=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`;else if(t.type==="bigint")s=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`;else if(t.type==="date")s=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`;else s="Invalid input";break;case b.custom:s="Invalid input";break;case b.invalid_intersection_types:s="Intersection results could not be merged";break;case b.not_multiple_of:s=`Number must be a multiple of ${t.multipleOf}`;break;case b.not_finite:s="Number must be finite";break;default:s=n.defaultError,x.assertNever(t)}return{message:s}},An=qd;var E0=An;function Cd(t){E0=t}function Ts(){return E0}var gi=(t)=>{let{data:n,path:s,errorMaps:i,issueData:r}=t,e=[...s,...r.path||[]],f={...r,path:e};if(r.message!==void 0)return{...r,path:e,message:r.message};let o="",c=i.filter((h)=>!!h).slice().reverse();for(let h of c)o=h(f,{data:n,defaultError:o}).message;return{...r,path:e,message:o}},Kd=[];function L(t,n){let s=Ts(),i=gi({issueData:n,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,s,s===An?void 0:An].filter((r)=>!!r)});t.common.issues.push(i)}class _t{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(t,n){let s=[];for(let i of n){if(i.status==="aborted")return P;if(i.status==="dirty")t.dirty();s.push(i.value)}return{status:t.value,value:s}}static async mergeObjectAsync(t,n){let s=[];for(let i of n){let r=await i.key,e=await i.value;s.push({key:r,value:e})}return _t.mergeObjectSync(t,s)}static mergeObjectSync(t,n){let s={};for(let i of n){let{key:r,value:e}=i;if(r.status==="aborted")return P;if(e.status==="aborted")return P;if(r.status==="dirty")t.dirty();if(e.status==="dirty")t.dirty();if(r.value!=="__proto__"&&(typeof e.value<"u"||i.alwaysSet))s[r.value]=e.value}return{status:t.value,value:s}}}var P=Object.freeze({status:"aborted"}),Vn=(t)=>({status:"dirty",value:t}),gt=(t)=>({status:"valid",value:t}),Tr=(t)=>t.status==="aborted",Sr=(t)=>t.status==="dirty",yn=(t)=>t.status==="valid",Ss=(t)=>typeof Promise<"u"&&t instanceof Promise;var O;(function(t){t.errToObj=(n)=>typeof n==="string"?{message:n}:n||{},t.toString=(n)=>typeof n==="string"?n:n?.message})(O||(O={}));class kt{constructor(t,n,s,i){this._cachedPath=[],this.parent=t,this.data=n,this._path=s,this._key=i}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 R0=(t,n)=>{if(yn(n))return{success:!0,data:n.value};else{if(!t.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let s=new bt(t.common.issues);return this._error=s,this._error}}}};function Q(t){if(!t)return{};let{errorMap:n,invalid_type_error:s,required_error:i,description:r}=t;if(n&&(s||i))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(n)return{errorMap:n,description:r};return{errorMap:(f,o)=>{let{message:c}=t;if(f.code==="invalid_enum_value")return{message:c??o.defaultError};if(typeof o.data>"u")return{message:c??i??o.defaultError};if(f.code!=="invalid_type")return{message:o.defaultError};return{message:c??s??o.defaultError}},description:r}}class z{get description(){return this._def.description}_getType(t){return at(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:at(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new _t,ctx:{common:t.parent.common,data:t.data,parsedType:at(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Ss(n))throw Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let s=this.safeParse(t,n);if(s.success)return s.data;throw s.error}safeParse(t,n){let s={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:at(t)},i=this._parseSync({data:t,path:s.path,parent:s});return R0(s,i)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:at(t)};if(!this["~standard"].async)try{let s=this._parseSync({data:t,path:[],parent:n});return yn(s)?{value:s.value}:{issues:n.common.issues}}catch(s){if(s?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then((s)=>yn(s)?{value:s.value}:{issues:n.common.issues})}async parseAsync(t,n){let s=await this.safeParseAsync(t,n);if(s.success)return s.data;throw s.error}async safeParseAsync(t,n){let s={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:at(t)},i=this._parse({data:t,path:s.path,parent:s}),r=await(Ss(i)?i:Promise.resolve(i));return R0(s,r)}refine(t,n){let s=(i)=>{if(typeof n==="string"||typeof n>"u")return{message:n};else if(typeof n==="function")return n(i);else return n};return this._refinement((i,r)=>{let e=t(i),f=()=>r.addIssue({code:b.custom,...s(i)});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(t,n){return this._refinement((s,i)=>{if(!t(s))return i.addIssue(typeof n==="function"?n(s,i):n),!1;else return!0})}_refinement(t){return new zt({schema:this,typeName:N.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,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:(n)=>this["~validate"](n)}}optional(){return Jt.create(this,this._def)}nullable(){return gn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Qt.create(this)}promise(){return Zn.create(this,this._def)}or(t){return Os.create([this,t],this._def)}and(t){return Gs.create(this,t,this._def)}transform(t){return new zt({...Q(this._def),schema:this,typeName:N.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t==="function"?t:()=>t;return new Ps({...Q(this._def),innerType:this,defaultValue:n,typeName:N.ZodDefault})}brand(){return new Ur({typeName:N.ZodBranded,type:this,...Q(this._def)})}catch(t){let n=typeof t==="function"?t:()=>t;return new Ns({...Q(this._def),innerType:this,catchValue:n,typeName:N.ZodCatch})}describe(t){return new this.constructor({...this._def,description:t})}pipe(t){return Si.create(this,t)}readonly(){return Ws.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var Vd=/^c[^\s-]{8,}$/i,jd=/^[0-9a-z]+$/,ad=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pd=/^[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,Zd=/^[a-z0-9_-]{21}$/i,vd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,tE=/^[-+]?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)?)??$/,nE=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sE="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ko,iE=/^(?:(?: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])$/,rE=/^(?:(?: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])$/,eE=/^(([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]))$/,oE=/^(([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])$/,fE=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,cE=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,T0="((\\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])))",hE=new RegExp(`^${T0}$`);function S0(t){let n="[0-5]\\d";if(t.precision)n=`${n}\\.\\d{${t.precision}}`;else if(t.precision==null)n=`${n}(\\.\\d+)?`;let s=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${n})${s}`}function uE(t){return new RegExp(`^${S0(t)}$`)}function $0(t){let n=`${T0}T${S0(t)}`,s=[];if(s.push(t.local?"Z?":"Z"),t.offset)s.push("([+-]\\d{2}:?\\d{2})");return n=`${n}(${s.join("|")})`,new RegExp(`^${n}$`)}function lE(t,n){if((n==="v4"||!n)&&iE.test(t))return!0;if((n==="v6"||!n)&&eE.test(t))return!0;return!1}function _E(t,n){if(!vd.test(t))return!1;try{let[s]=t.split(".");if(!s)return!1;let i=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),r=JSON.parse(atob(i));if(typeof r!=="object"||r===null)return!1;if("typ"in r&&r?.typ!=="JWT")return!1;if(!r.alg)return!1;if(n&&r.alg!==n)return!1;return!0}catch{return!1}}function wE(t,n){if((n==="v4"||!n)&&rE.test(t))return!0;if((n==="v6"||!n)&&oE.test(t))return!0;return!1}class Yt extends z{_parse(t){if(this._def.coerce)t.data=String(t.data);if(this._getType(t)!==$.string){let r=this._getOrReturnCtx(t);return L(r,{code:b.invalid_type,expected:$.string,received:r.parsedType}),P}let s=new _t,i=void 0;for(let r of this._def.checks)if(r.kind==="min"){if(t.data.length<r.value)i=this._getOrReturnCtx(t,i),L(i,{code:b.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),s.dirty()}else if(r.kind==="max"){if(t.data.length>r.value)i=this._getOrReturnCtx(t,i),L(i,{code:b.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),s.dirty()}else if(r.kind==="length"){let e=t.data.length>r.value,f=t.data.length<r.value;if(e||f){if(i=this._getOrReturnCtx(t,i),e)L(i,{code:b.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message});else if(f)L(i,{code:b.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message});s.dirty()}}else if(r.kind==="email"){if(!nE.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"email",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="emoji"){if(!ko)ko=new RegExp(sE,"u");if(!ko.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"emoji",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="uuid"){if(!pd.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"uuid",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="nanoid"){if(!Zd.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"nanoid",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="cuid"){if(!Vd.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"cuid",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="cuid2"){if(!jd.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"cuid2",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="ulid"){if(!ad.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"ulid",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),L(i,{validation:"url",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="regex"){if(r.regex.lastIndex=0,!r.regex.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"regex",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="trim")t.data=t.data.trim();else if(r.kind==="includes"){if(!t.data.includes(r.value,r.position))i=this._getOrReturnCtx(t,i),L(i,{code:b.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),s.dirty()}else if(r.kind==="toLowerCase")t.data=t.data.toLowerCase();else if(r.kind==="toUpperCase")t.data=t.data.toUpperCase();else if(r.kind==="startsWith"){if(!t.data.startsWith(r.value))i=this._getOrReturnCtx(t,i),L(i,{code:b.invalid_string,validation:{startsWith:r.value},message:r.message}),s.dirty()}else if(r.kind==="endsWith"){if(!t.data.endsWith(r.value))i=this._getOrReturnCtx(t,i),L(i,{code:b.invalid_string,validation:{endsWith:r.value},message:r.message}),s.dirty()}else if(r.kind==="datetime"){if(!$0(r).test(t.data))i=this._getOrReturnCtx(t,i),L(i,{code:b.invalid_string,validation:"datetime",message:r.message}),s.dirty()}else if(r.kind==="date"){if(!hE.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{code:b.invalid_string,validation:"date",message:r.message}),s.dirty()}else if(r.kind==="time"){if(!uE(r).test(t.data))i=this._getOrReturnCtx(t,i),L(i,{code:b.invalid_string,validation:"time",message:r.message}),s.dirty()}else if(r.kind==="duration"){if(!tE.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"duration",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="ip"){if(!lE(t.data,r.version))i=this._getOrReturnCtx(t,i),L(i,{validation:"ip",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="jwt"){if(!_E(t.data,r.alg))i=this._getOrReturnCtx(t,i),L(i,{validation:"jwt",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="cidr"){if(!wE(t.data,r.version))i=this._getOrReturnCtx(t,i),L(i,{validation:"cidr",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="base64"){if(!fE.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"base64",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="base64url"){if(!cE.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"base64url",code:b.invalid_string,message:r.message}),s.dirty()}else x.assertNever(r);return{status:s.value,value:t.data}}_regex(t,n,s){return this.refinement((i)=>t.test(i),{validation:n,code:b.invalid_string,...O.errToObj(s)})}_addCheck(t){return new Yt({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...O.errToObj(t)})}url(t){return this._addCheck({kind:"url",...O.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...O.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...O.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...O.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...O.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...O.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...O.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...O.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...O.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...O.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...O.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...O.errToObj(t)})}datetime(t){if(typeof t==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t});return this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...O.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){if(typeof t==="string")return this._addCheck({kind:"time",precision:null,message:t});return this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...O.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...O.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...O.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...O.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...O.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...O.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...O.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...O.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...O.errToObj(n)})}nonempty(t){return this.min(1,O.errToObj(t))}trim(){return new Yt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Yt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Yt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((t)=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find((t)=>t.kind==="date")}get isTime(){return!!this._def.checks.find((t)=>t.kind==="time")}get isDuration(){return!!this._def.checks.find((t)=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find((t)=>t.kind==="email")}get isURL(){return!!this._def.checks.find((t)=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find((t)=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find((t)=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((t)=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((t)=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((t)=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find((t)=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find((t)=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find((t)=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find((t)=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find((t)=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t}get maxLength(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t}}Yt.create=(t)=>{return new Yt({checks:[],typeName:N.ZodString,coerce:t?.coerce??!1,...Q(t)})};function AE(t,n){let s=(t.toString().split(".")[1]||"").length,i=(n.toString().split(".")[1]||"").length,r=s>i?s:i,e=Number.parseInt(t.toFixed(r).replace(".","")),f=Number.parseInt(n.toFixed(r).replace(".",""));return e%f/10**r}class Gn extends z{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce)t.data=Number(t.data);if(this._getType(t)!==$.number){let r=this._getOrReturnCtx(t);return L(r,{code:b.invalid_type,expected:$.number,received:r.parsedType}),P}let s=void 0,i=new _t;for(let r of this._def.checks)if(r.kind==="int"){if(!x.isInteger(t.data))s=this._getOrReturnCtx(t,s),L(s,{code:b.invalid_type,expected:"integer",received:"float",message:r.message}),i.dirty()}else if(r.kind==="min"){if(r.inclusive?t.data<r.value:t.data<=r.value)s=this._getOrReturnCtx(t,s),L(s,{code:b.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),i.dirty()}else if(r.kind==="max"){if(r.inclusive?t.data>r.value:t.data>=r.value)s=this._getOrReturnCtx(t,s),L(s,{code:b.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),i.dirty()}else if(r.kind==="multipleOf"){if(AE(t.data,r.value)!==0)s=this._getOrReturnCtx(t,s),L(s,{code:b.not_multiple_of,multipleOf:r.value,message:r.message}),i.dirty()}else if(r.kind==="finite"){if(!Number.isFinite(t.data))s=this._getOrReturnCtx(t,s),L(s,{code:b.not_finite,message:r.message}),i.dirty()}else x.assertNever(r);return{status:i.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,O.toString(n))}gt(t,n){return this.setLimit("min",t,!1,O.toString(n))}lte(t,n){return this.setLimit("max",t,!0,O.toString(n))}lt(t,n){return this.setLimit("max",t,!1,O.toString(n))}setLimit(t,n,s,i){return new Gn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:s,message:O.toString(i)}]})}_addCheck(t){return new Gn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:O.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:O.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:O.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t}get maxValue(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t}get isInt(){return!!this._def.checks.find((t)=>t.kind==="int"||t.kind==="multipleOf"&&x.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let s of this._def.checks)if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;else if(s.kind==="min"){if(n===null||s.value>n)n=s.value}else if(s.kind==="max"){if(t===null||s.value<t)t=s.value}return Number.isFinite(n)&&Number.isFinite(t)}}Gn.create=(t)=>{return new Gn({checks:[],typeName:N.ZodNumber,coerce:t?.coerce||!1,...Q(t)})};class Bn extends z{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==$.bigint)return this._getInvalidInput(t);let s=void 0,i=new _t;for(let r of this._def.checks)if(r.kind==="min"){if(r.inclusive?t.data<r.value:t.data<=r.value)s=this._getOrReturnCtx(t,s),L(s,{code:b.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),i.dirty()}else if(r.kind==="max"){if(r.inclusive?t.data>r.value:t.data>=r.value)s=this._getOrReturnCtx(t,s),L(s,{code:b.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),i.dirty()}else if(r.kind==="multipleOf"){if(t.data%r.value!==BigInt(0))s=this._getOrReturnCtx(t,s),L(s,{code:b.not_multiple_of,multipleOf:r.value,message:r.message}),i.dirty()}else x.assertNever(r);return{status:i.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return L(n,{code:b.invalid_type,expected:$.bigint,received:n.parsedType}),P}gte(t,n){return this.setLimit("min",t,!0,O.toString(n))}gt(t,n){return this.setLimit("min",t,!1,O.toString(n))}lte(t,n){return this.setLimit("max",t,!0,O.toString(n))}lt(t,n){return this.setLimit("max",t,!1,O.toString(n))}setLimit(t,n,s,i){return new Bn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:s,message:O.toString(i)}]})}_addCheck(t){return new Bn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:O.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:O.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t}get maxValue(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t}}Bn.create=(t)=>{return new Bn({checks:[],typeName:N.ZodBigInt,coerce:t?.coerce??!1,...Q(t)})};class Ls extends z{_parse(t){if(this._def.coerce)t.data=Boolean(t.data);if(this._getType(t)!==$.boolean){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.boolean,received:s.parsedType}),P}return gt(t.data)}}Ls.create=(t)=>{return new Ls({typeName:N.ZodBoolean,coerce:t?.coerce||!1,...Q(t)})};class jn extends z{_parse(t){if(this._def.coerce)t.data=new Date(t.data);if(this._getType(t)!==$.date){let r=this._getOrReturnCtx(t);return L(r,{code:b.invalid_type,expected:$.date,received:r.parsedType}),P}if(Number.isNaN(t.data.getTime())){let r=this._getOrReturnCtx(t);return L(r,{code:b.invalid_date}),P}let s=new _t,i=void 0;for(let r of this._def.checks)if(r.kind==="min"){if(t.data.getTime()<r.value)i=this._getOrReturnCtx(t,i),L(i,{code:b.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),s.dirty()}else if(r.kind==="max"){if(t.data.getTime()>r.value)i=this._getOrReturnCtx(t,i),L(i,{code:b.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),s.dirty()}else x.assertNever(r);return{status:s.value,value:new Date(t.data.getTime())}}_addCheck(t){return new jn({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:O.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:O.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t!=null?new Date(t):null}}jn.create=(t)=>{return new jn({checks:[],coerce:t?.coerce||!1,typeName:N.ZodDate,...Q(t)})};class di extends z{_parse(t){if(this._getType(t)!==$.symbol){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.symbol,received:s.parsedType}),P}return gt(t.data)}}di.create=(t)=>{return new di({typeName:N.ZodSymbol,...Q(t)})};class Is extends z{_parse(t){if(this._getType(t)!==$.undefined){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.undefined,received:s.parsedType}),P}return gt(t.data)}}Is.create=(t)=>{return new Is({typeName:N.ZodUndefined,...Q(t)})};class ys extends z{_parse(t){if(this._getType(t)!==$.null){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.null,received:s.parsedType}),P}return gt(t.data)}}ys.create=(t)=>{return new ys({typeName:N.ZodNull,...Q(t)})};class an extends z{constructor(){super(...arguments);this._any=!0}_parse(t){return gt(t.data)}}an.create=(t)=>{return new an({typeName:N.ZodAny,...Q(t)})};class On extends z{constructor(){super(...arguments);this._unknown=!0}_parse(t){return gt(t.data)}}On.create=(t)=>{return new On({typeName:N.ZodUnknown,...Q(t)})};class pt extends z{_parse(t){let n=this._getOrReturnCtx(t);return L(n,{code:b.invalid_type,expected:$.never,received:n.parsedType}),P}}pt.create=(t)=>{return new pt({typeName:N.ZodNever,...Q(t)})};class Ei extends z{_parse(t){if(this._getType(t)!==$.undefined){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.void,received:s.parsedType}),P}return gt(t.data)}}Ei.create=(t)=>{return new Ei({typeName:N.ZodVoid,...Q(t)})};class Qt extends z{_parse(t){let{ctx:n,status:s}=this._processInputParams(t),i=this._def;if(n.parsedType!==$.array)return L(n,{code:b.invalid_type,expected:$.array,received:n.parsedType}),P;if(i.exactLength!==null){let e=n.data.length>i.exactLength.value,f=n.data.length<i.exactLength.value;if(e||f)L(n,{code:e?b.too_big:b.too_small,minimum:f?i.exactLength.value:void 0,maximum:e?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),s.dirty()}if(i.minLength!==null){if(n.data.length<i.minLength.value)L(n,{code:b.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),s.dirty()}if(i.maxLength!==null){if(n.data.length>i.maxLength.value)L(n,{code:b.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),s.dirty()}if(n.common.async)return Promise.all([...n.data].map((e,f)=>{return i.type._parseAsync(new kt(n,e,n.path,f))})).then((e)=>{return _t.mergeArray(s,e)});let r=[...n.data].map((e,f)=>{return i.type._parseSync(new kt(n,e,n.path,f))});return _t.mergeArray(s,r)}get element(){return this._def.type}min(t,n){return new Qt({...this._def,minLength:{value:t,message:O.toString(n)}})}max(t,n){return new Qt({...this._def,maxLength:{value:t,message:O.toString(n)}})}length(t,n){return new Qt({...this._def,exactLength:{value:t,message:O.toString(n)}})}nonempty(t){return this.min(1,t)}}Qt.create=(t,n)=>{return new Qt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:N.ZodArray,...Q(n)})};function $s(t){if(t instanceof it){let n={};for(let s in t.shape){let i=t.shape[s];n[s]=Jt.create($s(i))}return new it({...t._def,shape:()=>n})}else if(t instanceof Qt)return new Qt({...t._def,type:$s(t.element)});else if(t instanceof Jt)return Jt.create($s(t.unwrap()));else if(t instanceof gn)return gn.create($s(t.unwrap()));else if(t instanceof Zt)return Zt.create(t.items.map((n)=>$s(n)));else return t}class it extends z{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=x.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==$.object){let c=this._getOrReturnCtx(t);return L(c,{code:b.invalid_type,expected:$.object,received:c.parsedType}),P}let{status:s,ctx:i}=this._processInputParams(t),{shape:r,keys:e}=this._getCached(),f=[];if(!(this._def.catchall instanceof pt&&this._def.unknownKeys==="strip")){for(let c in i.data)if(!e.includes(c))f.push(c)}let o=[];for(let c of e){let h=r[c],u=i.data[c];o.push({key:{status:"valid",value:c},value:h._parse(new kt(i,u,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof pt){let c=this._def.unknownKeys;if(c==="passthrough")for(let h of f)o.push({key:{status:"valid",value:h},value:{status:"valid",value:i.data[h]}});else if(c==="strict"){if(f.length>0)L(i,{code:b.unrecognized_keys,keys:f}),s.dirty()}else if(c==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let h of f){let u=i.data[h];o.push({key:{status:"valid",value:h},value:c._parse(new kt(i,u,i.path,h)),alwaysSet:h in i.data})}}if(i.common.async)return Promise.resolve().then(async()=>{let c=[];for(let h of o){let u=await h.key,l=await h.value;c.push({key:u,value:l,alwaysSet:h.alwaysSet})}return c}).then((c)=>{return _t.mergeObjectSync(s,c)});else return _t.mergeObjectSync(s,o)}get shape(){return this._def.shape()}strict(t){return O.errToObj,new it({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,s)=>{let i=this._def.errorMap?.(n,s).message??s.defaultError;if(n.code==="unrecognized_keys")return{message:O.errToObj(t).message??i};return{message:i}}}:{}})}strip(){return new it({...this._def,unknownKeys:"strip"})}passthrough(){return new it({...this._def,unknownKeys:"passthrough"})}extend(t){return new it({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new it({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:N.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new it({...this._def,catchall:t})}pick(t){let n={};for(let s of x.objectKeys(t))if(t[s]&&this.shape[s])n[s]=this.shape[s];return new it({...this._def,shape:()=>n})}omit(t){let n={};for(let s of x.objectKeys(this.shape))if(!t[s])n[s]=this.shape[s];return new it({...this._def,shape:()=>n})}deepPartial(){return $s(this)}partial(t){let n={};for(let s of x.objectKeys(this.shape)){let i=this.shape[s];if(t&&!t[s])n[s]=i;else n[s]=i.optional()}return new it({...this._def,shape:()=>n})}required(t){let n={};for(let s of x.objectKeys(this.shape))if(t&&!t[s])n[s]=this.shape[s];else{let r=this.shape[s];while(r instanceof Jt)r=r._def.innerType;n[s]=r}return new it({...this._def,shape:()=>n})}keyof(){return U0(x.objectKeys(this.shape))}}it.create=(t,n)=>{return new it({shape:()=>t,unknownKeys:"strip",catchall:pt.create(),typeName:N.ZodObject,...Q(n)})};it.strictCreate=(t,n)=>{return new it({shape:()=>t,unknownKeys:"strict",catchall:pt.create(),typeName:N.ZodObject,...Q(n)})};it.lazycreate=(t,n)=>{return new it({shape:t,unknownKeys:"strip",catchall:pt.create(),typeName:N.ZodObject,...Q(n)})};class Os extends z{_parse(t){let{ctx:n}=this._processInputParams(t),s=this._def.options;function i(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 n.common.issues.push(...f.ctx.common.issues),f.result;let e=r.map((f)=>new bt(f.ctx.common.issues));return L(n,{code:b.invalid_union,unionErrors:e}),P}if(n.common.async)return Promise.all(s.map(async(r)=>{let e={...n,common:{...n.common,issues:[]},parent:null};return{result:await r._parseAsync({data:n.data,path:n.path,parent:e}),ctx:e}})).then(i);else{let r=void 0,e=[];for(let o of s){let c={...n,common:{...n.common,issues:[]},parent:null},h=o._parseSync({data:n.data,path:n.path,parent:c});if(h.status==="valid")return h;else if(h.status==="dirty"&&!r)r={result:h,ctx:c};if(c.common.issues.length)e.push(c.common.issues)}if(r)return n.common.issues.push(...r.ctx.common.issues),r.result;let f=e.map((o)=>new bt(o));return L(n,{code:b.invalid_union,unionErrors:f}),P}}get options(){return this._def.options}}Os.create=(t,n)=>{return new Os({options:t,typeName:N.ZodUnion,...Q(n)})};var Mn=(t)=>{if(t instanceof Bs)return Mn(t.schema);else if(t instanceof zt)return Mn(t.innerType());else if(t instanceof Fs)return[t.value];else if(t instanceof Fn)return t.options;else if(t instanceof Hs)return x.objectValues(t.enum);else if(t instanceof Ps)return Mn(t._def.innerType);else if(t instanceof Is)return[void 0];else if(t instanceof ys)return[null];else if(t instanceof Jt)return[void 0,...Mn(t.unwrap())];else if(t instanceof gn)return[null,...Mn(t.unwrap())];else if(t instanceof Ur)return Mn(t.unwrap());else if(t instanceof Ws)return Mn(t.unwrap());else if(t instanceof Ns)return Mn(t._def.innerType);else return[]};class $r extends z{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==$.object)return L(n,{code:b.invalid_type,expected:$.object,received:n.parsedType}),P;let s=this.discriminator,i=n.data[s],r=this.optionsMap.get(i);if(!r)return L(n,{code:b.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),P;if(n.common.async)return r._parseAsync({data:n.data,path:n.path,parent:n});else return r._parseSync({data:n.data,path:n.path,parent:n})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,s){let i=new Map;for(let r of n){let e=Mn(r.shape[t]);if(!e.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let f of e){if(i.has(f))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(f)}`);i.set(f,r)}}return new $r({typeName:N.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...Q(s)})}}function zo(t,n){let s=at(t),i=at(n);if(t===n)return{valid:!0,data:t};else if(s===$.object&&i===$.object){let r=x.objectKeys(n),e=x.objectKeys(t).filter((o)=>r.indexOf(o)!==-1),f={...t,...n};for(let o of e){let c=zo(t[o],n[o]);if(!c.valid)return{valid:!1};f[o]=c.data}return{valid:!0,data:f}}else if(s===$.array&&i===$.array){if(t.length!==n.length)return{valid:!1};let r=[];for(let e=0;e<t.length;e++){let f=t[e],o=n[e],c=zo(f,o);if(!c.valid)return{valid:!1};r.push(c.data)}return{valid:!0,data:r}}else if(s===$.date&&i===$.date&&+t===+n)return{valid:!0,data:t};else return{valid:!1}}class Gs extends z{_parse(t){let{status:n,ctx:s}=this._processInputParams(t),i=(r,e)=>{if(Tr(r)||Tr(e))return P;let f=zo(r.value,e.value);if(!f.valid)return L(s,{code:b.invalid_intersection_types}),P;if(Sr(r)||Sr(e))n.dirty();return{status:n.value,value:f.data}};if(s.common.async)return Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([r,e])=>i(r,e));else return i(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}Gs.create=(t,n,s)=>{return new Gs({left:t,right:n,typeName:N.ZodIntersection,...Q(s)})};class Zt extends z{_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==$.array)return L(s,{code:b.invalid_type,expected:$.array,received:s.parsedType}),P;if(s.data.length<this._def.items.length)return L(s,{code:b.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),P;if(!this._def.rest&&s.data.length>this._def.items.length)L(s,{code:b.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty();let r=[...s.data].map((e,f)=>{let o=this._def.items[f]||this._def.rest;if(!o)return null;return o._parse(new kt(s,e,s.path,f))}).filter((e)=>!!e);if(s.common.async)return Promise.all(r).then((e)=>{return _t.mergeArray(n,e)});else return _t.mergeArray(n,r)}get items(){return this._def.items}rest(t){return new Zt({...this._def,rest:t})}}Zt.create=(t,n)=>{if(!Array.isArray(t))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Zt({items:t,typeName:N.ZodTuple,rest:null,...Q(n)})};class Ri extends z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==$.object)return L(s,{code:b.invalid_type,expected:$.object,received:s.parsedType}),P;let i=[],r=this._def.keyType,e=this._def.valueType;for(let f in s.data)i.push({key:r._parse(new kt(s,f,s.path,f)),value:e._parse(new kt(s,s.data[f],s.path,f)),alwaysSet:f in s.data});if(s.common.async)return _t.mergeObjectAsync(n,i);else return _t.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(t,n,s){if(n instanceof z)return new Ri({keyType:t,valueType:n,typeName:N.ZodRecord,...Q(s)});return new Ri({keyType:Yt.create(),valueType:t,typeName:N.ZodRecord,...Q(n)})}}class bi extends z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==$.map)return L(s,{code:b.invalid_type,expected:$.map,received:s.parsedType}),P;let i=this._def.keyType,r=this._def.valueType,e=[...s.data.entries()].map(([f,o],c)=>{return{key:i._parse(new kt(s,f,s.path,[c,"key"])),value:r._parse(new kt(s,o,s.path,[c,"value"]))}});if(s.common.async){let f=new Map;return Promise.resolve().then(async()=>{for(let o of e){let c=await o.key,h=await o.value;if(c.status==="aborted"||h.status==="aborted")return P;if(c.status==="dirty"||h.status==="dirty")n.dirty();f.set(c.value,h.value)}return{status:n.value,value:f}})}else{let f=new Map;for(let o of e){let{key:c,value:h}=o;if(c.status==="aborted"||h.status==="aborted")return P;if(c.status==="dirty"||h.status==="dirty")n.dirty();f.set(c.value,h.value)}return{status:n.value,value:f}}}}bi.create=(t,n,s)=>{return new bi({valueType:n,keyType:t,typeName:N.ZodMap,...Q(s)})};class pn extends z{_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==$.set)return L(s,{code:b.invalid_type,expected:$.set,received:s.parsedType}),P;let i=this._def;if(i.minSize!==null){if(s.data.size<i.minSize.value)L(s,{code:b.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()}if(i.maxSize!==null){if(s.data.size>i.maxSize.value)L(s,{code:b.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty()}let r=this._def.valueType;function e(o){let c=new Set;for(let h of o){if(h.status==="aborted")return P;if(h.status==="dirty")n.dirty();c.add(h.value)}return{status:n.value,value:c}}let f=[...s.data.values()].map((o,c)=>r._parse(new kt(s,o,s.path,c)));if(s.common.async)return Promise.all(f).then((o)=>e(o));else return e(f)}min(t,n){return new pn({...this._def,minSize:{value:t,message:O.toString(n)}})}max(t,n){return new pn({...this._def,maxSize:{value:t,message:O.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}pn.create=(t,n)=>{return new pn({valueType:t,minSize:null,maxSize:null,typeName:N.ZodSet,...Q(n)})};class Us extends z{constructor(){super(...arguments);this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==$.function)return L(n,{code:b.invalid_type,expected:$.function,received:n.parsedType}),P;function s(f,o){return gi({data:f,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ts(),An].filter((c)=>!!c),issueData:{code:b.invalid_arguments,argumentsError:o}})}function i(f,o){return gi({data:f,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ts(),An].filter((c)=>!!c),issueData:{code:b.invalid_return_type,returnTypeError:o}})}let r={errorMap:n.common.contextualErrorMap},e=n.data;if(this._def.returns instanceof Zn){let f=this;return gt(async function(...o){let c=new bt([]),h=await f._def.args.parseAsync(o,r).catch((_)=>{throw c.addIssue(s(o,_)),c}),u=await Reflect.apply(e,this,h);return await f._def.returns._def.type.parseAsync(u,r).catch((_)=>{throw c.addIssue(i(u,_)),c})})}else{let f=this;return gt(function(...o){let c=f._def.args.safeParse(o,r);if(!c.success)throw new bt([s(o,c.error)]);let h=Reflect.apply(e,this,c.data),u=f._def.returns.safeParse(h,r);if(!u.success)throw new bt([i(h,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Us({...this._def,args:Zt.create(t).rest(On.create())})}returns(t){return new Us({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,s){return new Us({args:t?t:Zt.create([]).rest(On.create()),returns:n||On.create(),typeName:N.ZodFunction,...Q(s)})}}class Bs extends z{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Bs.create=(t,n)=>{return new Bs({getter:t,typeName:N.ZodLazy,...Q(n)})};class Fs extends z{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return L(n,{received:n.data,code:b.invalid_literal,expected:this._def.value}),P}return{status:"valid",value:t.data}}get value(){return this._def.value}}Fs.create=(t,n)=>{return new Fs({value:t,typeName:N.ZodLiteral,...Q(n)})};function U0(t,n){return new Fn({values:t,typeName:N.ZodEnum,...Q(n)})}class Fn extends z{_parse(t){if(typeof t.data!=="string"){let n=this._getOrReturnCtx(t),s=this._def.values;return L(n,{expected:x.joinValues(s),received:n.parsedType,code:b.invalid_type}),P}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),s=this._def.values;return L(n,{received:n.data,code:b.invalid_enum_value,options:s}),P}return gt(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Fn.create(t,{...this._def,...n})}exclude(t,n=this._def){return Fn.create(this.options.filter((s)=>!t.includes(s)),{...this._def,...n})}}Fn.create=U0;class Hs extends z{_parse(t){let n=x.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(t);if(s.parsedType!==$.string&&s.parsedType!==$.number){let i=x.objectValues(n);return L(s,{expected:x.joinValues(i),received:s.parsedType,code:b.invalid_type}),P}if(!this._cache)this._cache=new Set(x.getValidEnumValues(this._def.values));if(!this._cache.has(t.data)){let i=x.objectValues(n);return L(s,{received:s.data,code:b.invalid_enum_value,options:i}),P}return gt(t.data)}get enum(){return this._def.values}}Hs.create=(t,n)=>{return new Hs({values:t,typeName:N.ZodNativeEnum,...Q(n)})};class Zn extends z{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==$.promise&&n.common.async===!1)return L(n,{code:b.invalid_type,expected:$.promise,received:n.parsedType}),P;let s=n.parsedType===$.promise?n.data:Promise.resolve(n.data);return gt(s.then((i)=>{return this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})}))}}Zn.create=(t,n)=>{return new Zn({type:t,typeName:N.ZodPromise,...Q(n)})};class zt extends z{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===N.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:s}=this._processInputParams(t),i=this._def.effect||null,r={addIssue:(e)=>{if(L(s,e),e.fatal)n.abort();else n.dirty()},get path(){return s.path}};if(r.addIssue=r.addIssue.bind(r),i.type==="preprocess"){let e=i.transform(s.data,r);if(s.common.async)return Promise.resolve(e).then(async(f)=>{if(n.value==="aborted")return P;let o=await this._def.schema._parseAsync({data:f,path:s.path,parent:s});if(o.status==="aborted")return P;if(o.status==="dirty")return Vn(o.value);if(n.value==="dirty")return Vn(o.value);return o});else{if(n.value==="aborted")return P;let f=this._def.schema._parseSync({data:e,path:s.path,parent:s});if(f.status==="aborted")return P;if(f.status==="dirty")return Vn(f.value);if(n.value==="dirty")return Vn(f.value);return f}}if(i.type==="refinement"){let e=(f)=>{let o=i.refinement(f,r);if(s.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(s.common.async===!1){let f=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(f.status==="aborted")return P;if(f.status==="dirty")n.dirty();return e(f.value),{status:n.value,value:f.value}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((f)=>{if(f.status==="aborted")return P;if(f.status==="dirty")n.dirty();return e(f.value).then(()=>{return{status:n.value,value:f.value}})})}if(i.type==="transform")if(s.common.async===!1){let e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!yn(e))return P;let f=i.transform(e.value,r);if(f instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:f}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((e)=>{if(!yn(e))return P;return Promise.resolve(i.transform(e.value,r)).then((f)=>({status:n.value,value:f}))});x.assertNever(i)}}zt.create=(t,n,s)=>{return new zt({schema:t,typeName:N.ZodEffects,effect:n,...Q(s)})};zt.createWithPreprocess=(t,n,s)=>{return new zt({schema:n,effect:{type:"preprocess",transform:t},typeName:N.ZodEffects,...Q(s)})};class Jt extends z{_parse(t){if(this._getType(t)===$.undefined)return gt(void 0);return this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Jt.create=(t,n)=>{return new Jt({innerType:t,typeName:N.ZodOptional,...Q(n)})};class gn extends z{_parse(t){if(this._getType(t)===$.null)return gt(null);return this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}gn.create=(t,n)=>{return new gn({innerType:t,typeName:N.ZodNullable,...Q(n)})};class Ps extends z{_parse(t){let{ctx:n}=this._processInputParams(t),s=n.data;if(n.parsedType===$.undefined)s=this._def.defaultValue();return this._def.innerType._parse({data:s,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Ps.create=(t,n)=>{return new Ps({innerType:t,typeName:N.ZodDefault,defaultValue:typeof n.default==="function"?n.default:()=>n.default,...Q(n)})};class Ns extends z{_parse(t){let{ctx:n}=this._processInputParams(t),s={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});if(Ss(i))return i.then((r)=>{return{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new bt(s.common.issues)},input:s.data})}});else return{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new bt(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Ns.create=(t,n)=>{return new Ns({innerType:t,typeName:N.ZodCatch,catchValue:typeof n.catch==="function"?n.catch:()=>n.catch,...Q(n)})};class Ti extends z{_parse(t){if(this._getType(t)!==$.nan){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.nan,received:s.parsedType}),P}return{status:"valid",value:t.data}}}Ti.create=(t)=>{return new Ti({typeName:N.ZodNaN,...Q(t)})};var ME=Symbol("zod_brand");class Ur extends z{_parse(t){let{ctx:n}=this._processInputParams(t),s=n.data;return this._def.type._parse({data:s,path:n.path,parent:n})}unwrap(){return this._def.type}}class Si extends z{_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.common.async)return(async()=>{let r=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});if(r.status==="aborted")return P;if(r.status==="dirty")return n.dirty(),Vn(r.value);else return this._def.out._parseAsync({data:r.value,path:s.path,parent:s})})();else{let i=this._def.in._parseSync({data:s.data,path:s.path,parent:s});if(i.status==="aborted")return P;if(i.status==="dirty")return n.dirty(),{status:"dirty",value:i.value};else return this._def.out._parseSync({data:i.value,path:s.path,parent:s})}}static create(t,n){return new Si({in:t,out:n,typeName:N.ZodPipeline})}}class Ws extends z{_parse(t){let n=this._def.innerType._parse(t),s=(i)=>{if(yn(i))i.value=Object.freeze(i.value);return i};return Ss(n)?n.then((i)=>s(i)):s(n)}unwrap(){return this._def.innerType}}Ws.create=(t,n)=>{return new Ws({innerType:t,typeName:N.ZodReadonly,...Q(n)})};function b0(t,n){let s=typeof t==="function"?t(n):typeof t==="string"?{message:t}:t;return typeof s==="string"?{message:s}:s}function L0(t,n={},s){if(t)return an.create().superRefine((i,r)=>{let e=t(i);if(e instanceof Promise)return e.then((f)=>{if(!f){let o=b0(n,i),c=o.fatal??s??!0;r.addIssue({code:"custom",...o,fatal:c})}});if(!e){let f=b0(n,i),o=f.fatal??s??!0;r.addIssue({code:"custom",...f,fatal:o})}return});return an.create()}var gE={object:it.lazycreate},N;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(N||(N={}));var dE=(t,n={message:`Input not instance of ${t.name}`})=>L0((s)=>s instanceof t,n),I0=Yt.create,y0=Gn.create,EE=Ti.create,RE=Bn.create,O0=Ls.create,bE=jn.create,TE=di.create,SE=Is.create,$E=ys.create,UE=an.create,LE=On.create,IE=pt.create,yE=Ei.create,OE=Qt.create,GE=it.create,BE=it.strictCreate,FE=Os.create,HE=$r.create,PE=Gs.create,NE=Zt.create,WE=Ri.create,DE=bi.create,mE=pn.create,YE=Us.create,QE=Bs.create,JE=Fs.create,kE=Fn.create,zE=Hs.create,XE=Zn.create,xE=zt.create,qE=Jt.create,CE=gn.create,KE=zt.createWithPreprocess,VE=Si.create,jE=()=>I0().optional(),aE=()=>y0().optional(),pE=()=>O0().optional(),ZE={string:(t)=>Yt.create({...t,coerce:!0}),number:(t)=>Gn.create({...t,coerce:!0}),boolean:(t)=>Ls.create({...t,coerce:!0}),bigint:(t)=>Bn.create({...t,coerce:!0}),date:(t)=>jn.create({...t,coerce:!0})};var vE=P;var Lr=g.enum(["low","medium","high","xhigh","max"]),vn=g.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 tR=g.array(g.string()).transform((t)=>t.map((n)=>n.trim()).filter((n)=>n.length>0)).refine((t)=>t.length>0,{message:"api_keys must contain at least one non-empty key"}),nR=g.preprocess((t)=>typeof t==="string"&&t.trim().length===0?null:t,g.string().trim().refine((t)=>URL.canParse(t),{message:"proxy_url must be a valid URL"}).refine((t)=>{if(!URL.canParse(t))return!1;let n=new URL(t).protocol;return n==="http:"||n==="https:"},{message:"proxy_url must be http(s)"}).nullable()).default(null),Xo=g.object({host:g.string().default("127.0.0.1"),port:g.number().default(8787),api_keys:tR,proxy_url:nR,default_region:g.string().default("us-east-1"),account_selection_strategy:g.enum(["sticky","round-robin","lowest-usage"]).default("lowest-usage"),rate_limit_max_retries:g.number().default(3),rate_limit_retry_delay_ms:g.number().default(5000),max_request_iterations:g.number().default(20),request_timeout_ms:g.number().default(120000),stream_idle_timeout_ms:g.number().default(60000),max_request_body_bytes:g.number().default(10485760),token_expiry_buffer_ms:g.number().default(300000),effort:Lr.nullable().default(null),auto_effort_mapping:g.boolean().default(!0),log_level:g.string().default("info"),test_upstream_endpoint:g.string().url().optional()});class $i extends Error{constructor(t,n){super(t,n);this.name="ConfigLoadError"}}var eR=Xo.partial();function oR(t){let n=t.XDG_CONFIG_HOME??G0(rR(),".config");return G0(n,"kiro-provider","config.json")}function fR(t){if(!sR(t))return{};try{let n=JSON.parse(iR(t,"utf8"));return eR.parse(n)}catch(n){if(n instanceof g.ZodError)throw new $i(`Invalid configuration file ${t}: ${B0(n)}`,{cause:n});if(n instanceof Error)throw new $i(`Unable to read configuration file ${t}: ${n.message}`,{cause:n});throw n}}function cR(t){let n=t.trim().toLowerCase();if(n==="true"||n==="1")return!0;if(n==="false"||n==="0")return!1;return t}function hR(t){let n={},s={KIRO_PROVIDER_HOST:"host",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[o,c]of Object.entries(s)){let h=t[o];if(h!==void 0)n[c]=h}let i={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"};for(let[o,c]of Object.entries(i)){let h=t[o];if(h!==void 0)n[c]=Number(h)}let r=t.KIRO_PROVIDER_API_KEYS;if(r!==void 0)n.api_keys=r.split(",");let e=t.KIRO_PROVIDER_PROXY_URL;if(e!==void 0)n.proxy_url=e.trim();let f=t.KIRO_PROVIDER_AUTO_EFFORT_MAPPING;if(f!==void 0)n.auto_effort_mapping=cR(f);return n}function B0(t){return t.issues.map((n)=>`${n.path.length>0?n.path.join("."):"config"}: ${n.message}`).join(", ")}function F0(t={}){let n=t.env??process.env,s=t.configPath??oR(n);try{return Xo.parse({...fR(s),...hR(n),...t.overrides})}catch(i){if(i instanceof $i)throw i;if(i instanceof g.ZodError)throw new $i(`Invalid configuration: ${B0(i)}`,{cause:i});throw i}}function Ir(t){let n=t.split("|"),s=n[0]??"";if(n.length<2)return{refreshToken:s,authMethod:"desktop"};if(n.at(-1)==="idc")return{refreshToken:s,clientId:n[1],clientSecret:n[2],authMethod:"idc"};return{refreshToken:s,authMethod:"desktop"}}function H0(t,n=120000){if(!t.access||!t.expires)return!0;return Date.now()>=t.expires-n}function yr(t){if(t.authMethod==="idc"){if(!t.clientId||!t.clientSecret)throw Error("Missing credentials");return`${t.refreshToken}|${t.clientId}|${t.clientSecret}|idc`}return`${t.refreshToken}|desktop`}function uR(t){if(!t)return!1;return t.includes("Invalid refresh token")||t.includes("Invalid grant provided")||t.includes("invalid_grant")||t.includes("ExpiredTokenException")||t.includes("InvalidTokenException")||t.includes("ExpiredClientException")||t.includes("Client is expired")||t.includes("HTTP_401")||t.includes("HTTP_403")}function Or(t){if(!t)return!1;let n=t.toLowerCase();return n.includes("bearer token included in the request is invalid")||n.includes("access token has expired")||n.includes("access_token expired")||n.includes("the access token expired")}function xo(t){return uR(t)}var P0=4;class N0 extends Error{accountId;constructor(t){super(`Account ${t} changed too frequently to update`);this.accountId=t;this.name="AccountConcurrentUpdateError"}}function lR(t){throw TypeError(`Unsupported account selection strategy: ${String(t)}`)}function Ui(t){return{...t}}function _R(t){return{refresh:yr({refreshToken:t.refreshToken,authMethod:t.authMethod,...t.clientId?{clientId:t.clientId}:{},...t.clientSecret?{clientSecret:t.clientSecret}:{},...t.profileArn?{profileArn:t.profileArn}:{}}),access:t.accessToken,expires:t.expiresAt,authMethod:t.authMethod,region:t.region,...t.oidcRegion?{oidcRegion:t.oidcRegion}:{},...t.clientId?{clientId:t.clientId}:{},...t.clientSecret?{clientSecret:t.clientSecret}:{},...t.email?{email:t.email}:{},...t.profileArn?{profileArn:t.profileArn}:{}}}class qo{strategy;database;accounts;stickyId;roundRobinCursor=0;constructor(t,n,s){this.strategy=n;this.database=s;this.accounts=t.map(Ui)}getAccountCount(){return this.accounts.length}getAccounts(){return this.accounts.map(Ui)}getMinWaitTime(){let t=Date.now(),n=this.accounts.map(({rateLimitResetTime:s})=>s-t).filter((s)=>s>0);return n.length===0?0:Math.min(...n)}reconcileFromDb(t=this.database){let n=new Map(this.accounts.map((s)=>[s.id,s]));if(this.accounts=t.getAccounts().map((s)=>{let i=n.get(s.id);return i?.generation===s.generation?i:Ui(s)}),this.stickyId&&!this.accounts.some(({id:s})=>s===this.stickyId))this.stickyId=void 0;return this.getAccounts()}selectHealthyAccount(){let t=Date.now(),n=this.accounts.filter((i)=>this.isSelectable(i,t)).sort((i,r)=>i.id.localeCompare(r.id));if(n.length===0)return null;let s=this.selectCandidate(n);return this.patchAccount(s.id,(i)=>({...i,isHealthy:!0,unhealthyReason:void 0,recoveryTime:void 0,lastUsed:t,usedCount:(i.usedCount??0)+1}))??null}getCurrentOrNext(){return this.selectHealthyAccount()}markRateLimited(t,n){return this.patchAccount(t.id,(s)=>({...s,rateLimitResetTime:n}))}markUnhealthy(t,n,s){let i=Date.now();return this.patchAccount(t.id,(r)=>{if(xo(n))return{...r,failCount:10,isHealthy:!1,unhealthyReason:n,recoveryTime:void 0,lastUsed:i};let e=r.failCount+1;return{...r,failCount:e,isHealthy:e<10,unhealthyReason:n,recoveryTime:e>=10?s??i+3600000:void 0,lastUsed:i}})}updateFromAuth(t,n){let s=Ir(n.refresh);for(let i=0;i<P0;i+=1){let r=i===0?t:this.database.getById(t.id);if(!r||!this.isSameLogin(t,r)){this.reconcileFromDb();return}let e={...r,refreshToken:s.refreshToken,accessToken:n.access,expiresAt:n.expires};if(this.database.updateExistingAccounts([e])===1){let f={...e,generation:r.generation+1};return this.replaceAccount(f),Ui(f)}}this.reconcileFromDb();return}toAuthDetails(t){return _R(t)}isSelectable(t,n){if(xo(t.unhealthyReason))return!1;if(t.rateLimitResetTime>n)return!1;if(t.isHealthy||Or(t.unhealthyReason))return!0;return t.recoveryTime!==void 0&&t.recoveryTime<=n}isSameLogin(t,n){return n.refreshToken===t.refreshToken&&n.authMethod===t.authMethod&&n.clientId===t.clientId&&n.email===t.email&&n.startUrl===t.startUrl}selectCandidate(t){switch(this.strategy){case"sticky":{let s=t.find(({id:i})=>i===this.stickyId)??t[0];if(!s)throw RangeError("Candidate list cannot be empty");return this.stickyId=s.id,s}case"round-robin":{let n=t[this.roundRobinCursor%t.length];if(!n)throw RangeError("Candidate list cannot be empty");return this.roundRobinCursor+=1,n}case"lowest-usage":{let n=[...t].sort((s,i)=>(s.usedCount??0)-(i.usedCount??0)||(s.lastUsed??0)-(i.lastUsed??0)||s.id.localeCompare(i.id))[0];if(!n)throw RangeError("Candidate list cannot be empty");return n}default:return lR(this.strategy)}}patchAccount(t,n){for(let s=0;s<P0;s+=1){let i=this.database.getById(t);if(!i){this.accounts=this.accounts.filter((e)=>e.id!==t);return}let r=n(i);if(this.database.updateExistingAccounts([r])===1){let e={...r,generation:i.generation+1};return this.replaceAccount(e),Ui(e)}}throw this.reconcileFromDb(),new N0(t)}replaceAccount(t){let n=this.accounts.findIndex(({id:s})=>s===t.id);if(n===-1)this.accounts.push(t);else this.accounts[n]=t}}var j0=m(Vo(),1);import*as tn from"net";import*as Ii from"tls";import VR from"assert";import*as x0 from"net";import*as q0 from"http";import{Agent as KR}from"https";var vt=Symbol("AgentBaseInternalState");class jo extends q0.Agent{constructor(t){super(t);this[vt]={}}isSecureEndpoint(t){if(t){if(typeof t.secureEndpoint==="boolean")return t.secureEndpoint;if(typeof t.protocol==="string")return t.protocol==="https:"}let{stack:n}=Error();if(typeof n!=="string")return!1;return n.split(`
|
|
50
|
-
|
|
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
|
+
`.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,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
|
+
SELECT accounts.*
|
|
52
|
+
FROM accounts
|
|
53
|
+
WHERE NOT EXISTS (
|
|
54
|
+
SELECT 1 FROM removed_accounts
|
|
55
|
+
WHERE removed_accounts.id = accounts.id
|
|
56
|
+
)
|
|
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
|
+
UPDATE accounts
|
|
59
|
+
SET last_used = ?,
|
|
60
|
+
used_count = COALESCE(used_count, 0) + 1
|
|
61
|
+
WHERE id = ?
|
|
62
|
+
AND NOT EXISTS (
|
|
63
|
+
SELECT 1 FROM removed_accounts
|
|
64
|
+
WHERE removed_accounts.id = accounts.id
|
|
65
|
+
)
|
|
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
|
+
UPDATE accounts
|
|
68
|
+
SET rate_limit_reset = MAX(COALESCE(rate_limit_reset, 0), ?)
|
|
69
|
+
WHERE id = ?
|
|
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
|
+
UPDATE accounts
|
|
72
|
+
SET fail_count = 10,
|
|
73
|
+
is_healthy = 0,
|
|
74
|
+
unhealthy_reason = ?,
|
|
75
|
+
recovery_time = NULL,
|
|
76
|
+
last_used = ?
|
|
77
|
+
WHERE id = ?
|
|
78
|
+
`).run(t,s,n);else this.db.query(`
|
|
79
|
+
UPDATE accounts
|
|
80
|
+
SET fail_count = COALESCE(fail_count, 0) + 1,
|
|
81
|
+
is_healthy =
|
|
82
|
+
CASE WHEN COALESCE(fail_count, 0) + 1 >= 10 THEN 0 ELSE 1 END,
|
|
83
|
+
unhealthy_reason = ?,
|
|
84
|
+
recovery_time =
|
|
85
|
+
CASE
|
|
86
|
+
WHEN COALESCE(fail_count, 0) + 1 >= 10 THEN ?
|
|
87
|
+
ELSE NULL
|
|
88
|
+
END,
|
|
89
|
+
last_used = ?
|
|
90
|
+
WHERE id = ?
|
|
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
|
+
UPDATE accounts
|
|
93
|
+
SET email = ?,
|
|
94
|
+
oidc_region = ?,
|
|
95
|
+
client_id = ?,
|
|
96
|
+
client_secret = ?,
|
|
97
|
+
profile_arn = ?,
|
|
98
|
+
start_url = ?,
|
|
99
|
+
refresh_token = ?,
|
|
100
|
+
access_token = ?,
|
|
101
|
+
expires_at = ?,
|
|
102
|
+
is_healthy = 1,
|
|
103
|
+
unhealthy_reason = NULL,
|
|
104
|
+
recovery_time = NULL,
|
|
105
|
+
fail_count = 0,
|
|
106
|
+
last_used = ?
|
|
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 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
|
+
SELECT accounts.*
|
|
110
|
+
FROM accounts
|
|
111
|
+
WHERE accounts.id = ?
|
|
112
|
+
AND NOT EXISTS (
|
|
113
|
+
SELECT 1 FROM removed_accounts
|
|
114
|
+
WHERE removed_accounts.id = accounts.id
|
|
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: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
|
|
51
118
|
\r
|
|
52
|
-
`);if(
|
|
53
|
-
`),A=
|
|
54
|
-
`;if(
|
|
55
|
-
`;let
|
|
56
|
-
`);let{connect:c,buffered:
|
|
57
|
-
`;if(
|
|
58
|
-
`;let c=
|
|
59
|
-
`);let{connect:h}=await c;if(t.emit("proxyConnect",h),this.emit("proxyConnect",h,t),h.statusCode===200){if(t.once("socket",V0),n.secureEndpoint)return ss("Upgrading socket connection to TLS"),Ii.connect({...po(Nr(n),"host","path","port"),socket:r});return r}throw r.destroy(),Error(`Proxy authentication failed with status ${h.statusCode} after retry`)}}Wr.protocols=["http","https"];function V0(t){setImmediate(()=>{t.resume()})}function po(t,...n){let s={},i;for(i in t)if(!n.includes(i))s[i]=t[i];return s}var a0=new Map;function Qs(t){return t.proxy_url||void 0}function p0(t){let n=a0.get(t);if(n!==void 0)return n;let s=new Wr(t,{keepAlive:!0,maxSockets:50});return a0.set(t,s),s}function Z0(t){return t===void 0?{}:{proxy:t}}var aR=vn.options;function v0(t){return aR.includes(t)}function Zo(t){if(!t||!v0(t))return"us-east-1";return t}function yi(t,n){let s=t.replace("{{region}}",n);try{return new URL(s),s}catch{throw Error(`Invalid URL generated: ${s}`)}}function tu(t){if(!t)return;let n=t.split(":");if(n.length<6)return;if(n[0]!=="arn")return;let s=n[3];if(typeof s!=="string"||!s)return;return v0(s)?s:void 0}var ot={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"},Oi={"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"},nu=Object.keys(Oi),vY=new Set(Object.keys(Oi).filter((t)=>t.includes("-1m")));var pR=200000,ZR={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 B(t){return ZR[t]??pR}var Gi={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 Hn extends Error{code;originalError;constructor(t,n,s){super(t);this.name="KiroTokenRefreshError",this.code=n,this.originalError=s}}function vo(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function Dr(t,n,s){let i=t[n];if(typeof i==="string"&&i)return i;let r=t[s];return typeof r==="string"&&r?r:void 0}function vR(t,n,s){let i=t[n];if(typeof i==="number")return i;let r=t[s];return typeof r==="number"?r:void 0}function tb(t,n){let s;try{s=JSON.parse(t)}catch{return{message:t,code:`HTTP_${n}`}}if(!vo(s))return{message:t,code:`HTTP_${n}`};let i=Dr(s,"message","error_description")??t,r=Dr(s,"__type","error")??`HTTP_${n}`;return{message:i,code:r}}function su(t){let n=t.userInfo;if(!vo(n))return;let s=n.email;return typeof s==="string"?s:void 0}async function iu(t,n,s){let i=Ir(t.refresh),r=t.authMethod==="idc",e=r?t.oidcRegion??t.region:t.region,f=yi(r?ot.REFRESH_IDC_URL:ot.REFRESH_URL,e);if(r&&(!i.clientId||!i.clientSecret))throw new Hn("Missing creds","MISSING_CREDENTIALS");let o=r?{refreshToken:i.refreshToken,clientId:i.clientId,clientSecret:i.clientSecret,grantType:"refresh_token"}:{refreshToken:i.refreshToken},c=r?`aws-sdk-js/${ot.SDK_VERSION} ua/2.1 os/other lang/js md/browser#unknown_unknown api/sso-oidc#${ot.SDK_VERSION} m/E ${ot.USER_AGENT}`:`aws-sdk-js/3.0.0 ${ot.USER_AGENT}-0.1.0 os/macos lang/js md/nodejs/18.0.0`;try{let h=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":c,Connection:"close"},body:JSON.stringify(o),...n?{signal:n}:{},...Z0(s)});if(!h.ok){let w=tb(await h.text(),h.status);throw new Hn(`Refresh failed: ${w.message}`,w.code)}let u=await h.json();if(!vo(u))throw new Hn("No access token","INVALID_RESPONSE");let l=Dr(u,"access_token","accessToken");if(!l)throw new Hn("No access token","INVALID_RESPONSE");let _={refreshToken:Dr(u,"refresh_token","refreshToken")??i.refreshToken,authMethod:t.authMethod,...i.clientId?{clientId:i.clientId}:{},...i.clientSecret?{clientSecret:i.clientSecret}:{}};return{refresh:yr(_),access:l,expires:Date.now()+(vR(u,"expires_in","expiresIn")??3600)*1000,authMethod:t.authMethod,region:t.region,...t.oidcRegion?{oidcRegion:t.oidcRegion}:{},...t.profileArn?{profileArn:t.profileArn}:{},...t.clientId?{clientId:t.clientId}:{},...t.clientSecret?{clientSecret:t.clientSecret}:{},...t.email||su(u)?{email:t.email??su(u)}:{}}}catch(h){if(h instanceof Hn)throw h;if(h instanceof Error&&h.name==="AbortError")throw h;throw new Hn(`Token refresh failed: ${h instanceof Error?h.message:"Unknown error"}`,"NETWORK_ERROR",h instanceof Error?h:void 0)}}class mr extends Error{accountId;constructor(t){super(`Account ${t} is no longer available`);this.accountId=t;this.name="AccountUnavailableError"}}class tf{accountManager;tokenExpiryBufferMs;proxyUrl;inFlight=new Map;constructor(t,n,s){this.accountManager=t;this.tokenExpiryBufferMs=n;this.proxyUrl=s}async refreshIfNeeded(t,n,s){if(!H0(n,this.tokenExpiryBufferMs)){let i=this.accountManager.getAccounts().find(({id:r})=>r===t.id);if(!i)throw new mr(t.id);return i}return this.startOrJoinRefresh(t,n,s)}async forceRefresh(t,n){return this.startOrJoinRefresh(t,this.accountManager.toAuthDetails(t),n)}startOrJoinRefresh(t,n,s){if(!("generation"in t)||typeof t.generation!=="number")throw new mr(t.id);let i={...t,generation:t.generation},r=`${i.id}:${i.generation}`,e=this.inFlight.get(r);if(e)return e;let f=this.runRefresh(i,n,s).finally(()=>{if(this.inFlight.get(r)===f)this.inFlight.delete(r)});return this.inFlight.set(r,f),f}async runRefresh(t,n,s){let i=await iu(n,s,this.proxyUrl),r=this.accountManager.updateFromAuth(t,i);if(!r)throw new mr(t.id);return r}}import{Database as nb}from"bun:sqlite";import{chmodSync as sb,existsSync as ib,mkdirSync as rb}from"fs";import{homedir as ru}from"os";import{dirname as eb,join as rf}from"path";function nf(t,n){return{id:t.id,email:t.email,auth_method:t.authMethod,region:t.region,oidc_region:t.oidcRegion??null,client_id:t.clientId??null,client_secret:t.clientSecret??null,profile_arn:t.profileArn??null,start_url:t.startUrl??null,refresh_token:t.refreshToken,access_token:t.accessToken,expires_at:t.expiresAt,rate_limit_reset:t.rateLimitResetTime,is_healthy:t.isHealthy?1:0,unhealthy_reason:t.unhealthyReason??null,recovery_time:t.recoveryTime??null,fail_count:t.failCount,last_used:t.lastUsed??0,used_count:t.usedCount??0,limit_count:t.limitCount??0,last_sync:t.lastSync??0,overage_count:t.overageCount??0,generation:n}}function Yr(t){return{id:t.id,email:t.email,authMethod:t.auth_method,region:t.region,oidcRegion:t.oidc_region??void 0,clientId:t.client_id??void 0,clientSecret:t.client_secret??void 0,profileArn:t.profile_arn??void 0,startUrl:t.start_url??void 0,refreshToken:t.refresh_token,accessToken:t.access_token,expiresAt:t.expires_at,rateLimitResetTime:t.rate_limit_reset,isHealthy:t.is_healthy===1,unhealthyReason:t.unhealthy_reason??void 0,recoveryTime:t.recovery_time??void 0,failCount:t.fail_count,lastUsed:t.last_used,usedCount:t.used_count,limitCount:t.limit_count,lastSync:t.last_sync,overageCount:t.overage_count,generation:t.generation}}function sf(t){return[t.id,t.email,t.auth_method,t.region??null,t.oidc_region??null,t.client_id??null,t.client_secret??null,t.profile_arn??null,t.start_url??null,t.refresh_token,t.access_token,t.expires_at,t.rate_limit_reset,t.is_healthy,t.unhealthy_reason??null,t.recovery_time??null,t.fail_count,t.last_used,t.used_count,t.limit_count,t.last_sync,t.overage_count,t.generation]}function ob(){let t=process.platform==="win32"?process.env.APPDATA??rf(ru(),"AppData","Roaming"):process.env.XDG_CONFIG_HOME??rf(ru(),".config");return rf(t,"kiro-provider","accounts.db")}var Pn=ob();class is{db;path;constructor(t=Pn){if(this.path=t,t!==":memory:")rb(eb(t),{recursive:!0});this.db=new nb(t,{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(`
|
|
60
128
|
CREATE TABLE IF NOT EXISTS accounts (
|
|
61
129
|
id TEXT PRIMARY KEY, email TEXT NOT NULL, auth_method TEXT NOT NULL,
|
|
62
130
|
region TEXT NOT NULL, oidc_region TEXT, client_id TEXT, client_secret TEXT,
|
|
@@ -68,30 +136,71 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
68
136
|
limit_count INTEGER DEFAULT 0, last_sync INTEGER DEFAULT 0,
|
|
69
137
|
overage_count INTEGER DEFAULT 0, generation INTEGER NOT NULL DEFAULT 1
|
|
70
138
|
)
|
|
71
|
-
`),!this.db.query("PRAGMA table_info(accounts)").all().some(({name:
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
139
|
+
`),!this.db.query("PRAGMA table_info(accounts)").all().some(({name:i})=>i==="generation"))this.db.run("ALTER TABLE accounts ADD COLUMN generation INTEGER NOT NULL DEFAULT 1");this.db.run(`
|
|
140
|
+
CREATE TABLE IF NOT EXISTS removed_accounts (
|
|
141
|
+
id TEXT PRIMARY KEY,
|
|
142
|
+
removed_at INTEGER NOT NULL,
|
|
143
|
+
last_generation INTEGER NOT NULL
|
|
144
|
+
)
|
|
145
|
+
`),this.db.run(`
|
|
146
|
+
CREATE TABLE IF NOT EXISTS session_affinity (
|
|
147
|
+
key_hash TEXT PRIMARY KEY,
|
|
148
|
+
account_id TEXT NOT NULL,
|
|
149
|
+
conversation_id TEXT NOT NULL,
|
|
150
|
+
created_at INTEGER NOT NULL,
|
|
151
|
+
last_seen INTEGER NOT NULL,
|
|
152
|
+
expires_at INTEGER NOT NULL
|
|
153
|
+
)
|
|
154
|
+
`),this.db.run(`
|
|
155
|
+
CREATE INDEX IF NOT EXISTS session_affinity_expires_at_idx
|
|
156
|
+
ON session_affinity (expires_at)
|
|
157
|
+
`),this.db.run(`
|
|
158
|
+
CREATE INDEX IF NOT EXISTS session_affinity_last_seen_idx
|
|
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)
|
|
186
|
+
`)})}getAccounts(){return this.db.query(`
|
|
78
187
|
SELECT accounts.* FROM accounts
|
|
79
188
|
WHERE NOT EXISTS (
|
|
80
189
|
SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
|
|
81
190
|
)
|
|
82
|
-
`).all().map(
|
|
191
|
+
`).all().map(w_)}getById(n){let t=this.db.query(`
|
|
83
192
|
SELECT accounts.* FROM accounts
|
|
84
193
|
WHERE accounts.id = ? AND NOT EXISTS (
|
|
85
194
|
SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
|
|
86
195
|
)
|
|
87
|
-
`).get(
|
|
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(`
|
|
88
197
|
INSERT OR REPLACE INTO accounts (
|
|
89
198
|
id, email, auth_method, region, oidc_region, client_id, client_secret,
|
|
90
199
|
profile_arn, start_url, refresh_token, access_token, expires_at,
|
|
91
200
|
rate_limit_reset, is_healthy, unhealthy_reason, recovery_time, fail_count,
|
|
92
201
|
last_used, used_count, limit_count, last_sync, overage_count, generation
|
|
93
202
|
) VALUES (${Array.from({length:23},()=>"?").join(", ")})
|
|
94
|
-
`).run(...
|
|
203
|
+
`).run(...v0(s)),this.clearRemovedAccountInternal(n.id),w_(s)})}updateExistingAccounts(n){return this.withImmediateTransaction(()=>{let t=0,i=this.db.query(`
|
|
95
204
|
UPDATE accounts SET
|
|
96
205
|
email = ?, auth_method = ?, region = ?, oidc_region = ?, client_id = ?,
|
|
97
206
|
client_secret = ?, profile_arn = ?, start_url = ?, refresh_token = ?,
|
|
@@ -102,70 +211,122 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
102
211
|
WHERE id = ? AND generation = ? AND NOT EXISTS (
|
|
103
212
|
SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
|
|
104
213
|
)
|
|
105
|
-
`);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(`
|
|
106
215
|
INSERT OR REPLACE INTO removed_accounts (id, removed_at, last_generation)
|
|
107
216
|
VALUES (?, ?, ?)
|
|
108
|
-
`).run(t,Date.now(),i)})}clearRemovedAccount(t){this.withImmediateTransaction(()=>this.clearRemovedAccountInternal(t))}close(){this.db.close()}clearRemovedAccountInternal(t){this.db.query("DELETE FROM removed_accounts WHERE id = ?").run(t)}withImmediateTransaction(t){this.db.exec("BEGIN IMMEDIATE");try{let n=t();return this.db.exec("COMMIT"),n}catch(n){throw this.db.exec("ROLLBACK"),n}finally{this.tightenPermissions()}}tightenPermissions(){if(this.path===":memory:")return;for(let t of[this.path,`${this.path}-wal`,`${this.path}-shm`])if(ib(t))sb(t,384)}}function V(t,n,s,i){let r={message:n,type:s};if(i!==void 0)r.code=i;return new Response(JSON.stringify({error:r}),{status:t,headers:{"Content-Type":"application/json"}})}var eu="Bearer ";function ou(t,n){let s=t.headers.get("Authorization");if(s===null)return{ok:!1,response:V(401,"Missing Authorization header.","authentication_error","missing_api_key")};if(!s.startsWith(eu))return{ok:!1,response:V(401,"Authorization header must use the Bearer scheme.","authentication_error","invalid_api_key")};let i=s.slice(eu.length);if(!n.includes(i))return{ok:!1,response:V(401,"Incorrect API key provided.","authentication_error","invalid_api_key")};return{ok:!0}}var zn=m(xt(),1);var nr=m(xt(),1);var sr=m(xt(),1);var Un=m(xt(),1);var Ht=m(xt(),1);var p=m(St(),1);var li=m(kn(),1),Tg=m(Nn(),1);var Dc=m(Me(),1);var ir=m(Ut(),1);var Nt=m(fs(),1);var v=m(vi(),1);var X=m(Rn(),1);var ti=m(kn(),1);var vs=m(Rn(),1);var AA=async(t,n,s)=>{return{operation:vs.getSmithyContext(n).operation}};function JG(t){return{schemeId:"smithy.api#httpBearerAuth",propertiesExtractor:({profile:n,filepath:s,configFilepath:i,ignoreCache:r},e)=>({identityProperties:{profile:n,filepath:s,configFilepath:i,ignoreCache:r}})}}var MA=(t)=>{let n=[];switch(t.operation){default:n.push(JG(t))}return n},gA=(t)=>{let n=ti.memoizeIdentityProvider(t.token,ti.isIdentityExpired,ti.doesIdentityRequireRefresh);return Object.assign(t,{authSchemePreference:vs.normalizeProvider(t.authSchemePreference??[]),token:n})};var dA=(t)=>{return Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"amazoncodewhispererstreamingservice"})},EA={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};var RA={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 Ag=m(xt(),1),Mg=m(jc(),1);var ci=m(St(),1);var It=m(St(),1);var rM=300000,si="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var P1=async(t,n={},s)=>{let{SSOOIDCClient:i}=await Promise.resolve().then(() => m(Ph(),1)),r=(f)=>n.clientConfig?.[f]??n.parentClientConfig?.[f]??s?.[f];return new i(Object.assign({},n.clientConfig??{},{region:t??n.clientConfig?.region,logger:r("logger"),userAgentAppId:r("userAgentAppId")}))};var N1=async(t,n,s={},i)=>{let{CreateTokenCommand:r}=await Promise.resolve().then(() => m(Ph(),1));return(await P1(n,s,i)).send(new r({clientId:t.clientId,clientSecret:t.clientSecret,refreshToken:t.refreshToken,grantType:"refresh_token"}))};var W1=m(St(),1);var Nh=(t)=>{if(t.expiration&&t.expiration.getTime()<Date.now())throw new W1.TokenProviderError(`Token is expired. ${si}`,!1)};var D1=m(St(),1);var qn=(t,n,s=!1)=>{if(typeof n>"u")throw new D1.TokenProviderError(`Value not present for '${t}' in SSO Token${s?". Cannot refresh":""}. ${si}`,!1)};var m1=m(St(),1);import{promises as lW}from"fs";var{writeFile:_W}=lW,Y1=(t,n)=>{let s=m1.getSSOTokenFilepath(t),i=JSON.stringify(n,null,2);return _W(s,i)};var Q1=new Date(0),J1=(t={})=>async({callerClientConfig:n}={})=>{t.logger?.debug("@aws-sdk/token-providers - fromSso");let s=await It.parseKnownFiles(t),i=It.getProfileName({profile:t.profile??n?.profile}),r=s[i];if(!r)throw new It.TokenProviderError(`Profile '${i}' could not be found in shared credentials file.`,!1);else if(!r.sso_session)throw new It.TokenProviderError(`Profile '${i}' is missing required property 'sso_session'.`);let e=r.sso_session,o=(await It.loadSsoSessionData(t))[e];if(!o)throw new It.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 It.TokenProviderError(`Sso session '${e}' is missing required property '${A}'.`,!1);let{sso_start_url:c,sso_region:h}=o,u;try{u=await It.getSSOTokenFromFile(e)}catch(A){throw new It.TokenProviderError(`The SSO session token associated with profile=${i} was not found or is invalid. ${si}`,!1)}qn("accessToken",u.accessToken),qn("expiresAt",u.expiresAt);let{accessToken:l,expiresAt:_}=u,w={token:l,expiration:new Date(_)};if(w.expiration.getTime()-Date.now()>rM)return w;if(Date.now()-Q1.getTime()<30000)return Nh(w),w;qn("clientId",u.clientId,!0),qn("clientSecret",u.clientSecret,!0),qn("refreshToken",u.refreshToken,!0);try{Q1.setTime(Date.now());let A=await N1(u,h,t,n);qn("accessToken",A.accessToken),qn("expiresIn",A.expiresIn);let M=new Date(Date.now()+A.expiresIn*1000);try{await Y1(e,{...u,accessToken:A.accessToken,expiresAt:M.toISOString(),refreshToken:A.refreshToken})}catch(d){}return{token:A.accessToken,expiration:M}}catch(A){return Nh(w),w}};var Wh=(t={})=>ci.memoize(ci.chain(J1(t),async()=>{throw new ci.TokenProviderError("Could not load token from any providers",!1)}),(n)=>n.expiration!==void 0&&n.expiration.getTime()-Date.now()<300000,(n)=>n.expiration!==void 0);var ln=m(xt(),1);var gg=m(kn(),1);var oo=m(Me(),1);var Dh=m($t(),1);var Ln=m(St(),1);var bo=m(Ye(),1);var mh=m($t(),1);var Yh=m(St(),1);var ht=m(vi(),1);var lg=m(yh(),1),_g=m(kn(),1);var Qh=m(Ut(),1);var hi=m($t(),1);var gs=m($t(),1);var Et=m(fs(),1);var wr="ref",ds=-1,fo=!0,k1="isSet",q1="PartitionResult",co="booleanEquals",Jh="getAttr",z1={[wr]:"Endpoint"},kh={[wr]:q1},ui={},X1=[{[wr]:"Region"}],x1={conditions:[[k1,[z1]],[k1,X1],["aws.partition",X1,q1],[co,[{[wr]:"UseFIPS"},fo]],[co,[{[wr]:"UseDualStack"},fo]],[co,[{fn:Jh,argv:[kh,"supportsDualStack"]},fo]],[co,[{fn:Jh,argv:[kh,"supportsFIPS"]},fo]],["stringEquals",[{fn:Jh,argv:[kh,"name"]},"aws-us-gov"]]],results:[[ds],[ds,"Invalid Configuration: FIPS and custom endpoint are not supported"],[ds,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[z1,ui],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",ui],[ds,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://amazoncodewhispererstreamingservice.{Region}.amazonaws.com",ui],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dnsSuffix}",ui],[ds,"FIPS is enabled but this partition does not support FIPS"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dualStackDnsSuffix}",ui],[ds,"DualStack is enabled but this partition does not support DualStack"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dnsSuffix}",ui],[ds,"Invalid Configuration: Missing Region"]]},wW=2,yt=1e8,AW=new Int32Array([-1,1,-1,0,13,3,1,4,yt+12,2,5,yt+12,3,8,6,4,7,yt+11,5,yt+9,yt+10,4,11,9,6,10,yt+8,7,yt+6,yt+7,5,12,yt+5,6,yt+4,yt+5,3,yt+1,14,4,yt+2,yt+3]),C1=Et.BinaryDecisionDiagram.from(AW,wW,x1.conditions,x1.results);var MW=new Et.EndpointCache({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),K1=(t,n={})=>{return MW.get(t,()=>Et.decideEndpoint(C1,{endpointParams:t,logger:n.logger}))};Et.customEndpointFunctions.aws=Ht.awsEndpointFunctions;var xh=m(Nn(),1);class Ot extends X.ServiceException{constructor(t){super(t);Object.setPrototypeOf(this,Ot.prototype)}}class ho extends Ot{name="AccessDeniedException";$fault="client";reason;constructor(t){super({name:"AccessDeniedException",$fault:"client",...t});Object.setPrototypeOf(this,ho.prototype),this.reason=t.reason}}class uo extends Ot{name="ConflictException";$fault="client";reason;constructor(t){super({name:"ConflictException",$fault:"client",...t});Object.setPrototypeOf(this,uo.prototype),this.reason=t.reason}}class lo extends Ot{name="InternalServerException";$fault="server";$retryable={};reason;constructor(t){super({name:"InternalServerException",$fault:"server",...t});Object.setPrototypeOf(this,lo.prototype),this.reason=t.reason}}class _o extends Ot{name="ThrottlingException";$fault="client";$retryable={throttling:!0};reason;constructor(t){super({name:"ThrottlingException",$fault:"client",...t});Object.setPrototypeOf(this,_o.prototype),this.reason=t.reason}}class wo extends Ot{name="ValidationException";$fault="client";reason;constructor(t){super({name:"ValidationException",$fault:"client",...t});Object.setPrototypeOf(this,wo.prototype),this.reason=t.reason}}class Ao extends Ot{name="ResourceNotFoundException";$fault="client";constructor(t){super({name:"ResourceNotFoundException",$fault:"client",...t});Object.setPrototypeOf(this,Ao.prototype)}}class Mo extends Ot{name="ServiceUnavailableException";$fault="server";constructor(t){super({name:"ServiceUnavailableException",$fault:"server",...t});Object.setPrototypeOf(this,Mo.prototype)}}class go extends Ot{name="ServiceQuotaExceededException";$fault="client";reason;constructor(t){super({name:"ServiceQuotaExceededException",$fault:"client",...t});Object.setPrototypeOf(this,go.prototype),this.reason=t.reason}}class Eo extends Ot{name="DryRunOperationException";$fault="client";responseCode;constructor(t){super({name:"DryRunOperationException",$fault:"client",...t});Object.setPrototypeOf(this,Eo.prototype),this.responseCode=t.responseCode}}var V1=xh.TypeRegistry.for("smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming"),gW=[-3,"smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming","CodeWhispererStreamingServiceException",0,[],[]];V1.registerError(gW,Ot);var _n=xh.TypeRegistry.for("com.amazon.aws.codewhisperer"),dW=[-3,"com.amazon.aws.codewhisperer","AccessDeniedException",{["error"]:"client",["httpError"]:403},["message","reason"],[0,0],1];_n.registerError(dW,ho);var EW=[-3,"com.amazon.aws.codewhisperer","ConflictException",{["error"]:"client",["httpError"]:409},["message","reason"],[0,0],1];_n.registerError(EW,uo);var RW=[-3,"com.amazon.aws.codewhisperer","DryRunOperationException",{["error"]:"client"},["message","responseCode"],[0,[1,32]]];_n.registerError(RW,Eo);var j1=[-3,"com.amazon.aws.codewhisperer","InternalServerException",{["error"]:"server",["httpError"]:500},["message","reason"],[0,0],1];_n.registerError(j1,lo);var bW=[-3,"com.amazon.aws.codewhisperer","ResourceNotFoundException",{["error"]:"client",["httpError"]:404},["message"],[0],1];_n.registerError(bW,Ao);var TW=[-3,"com.amazon.aws.codewhisperer","ServiceQuotaExceededException",{["error"]:"client",["httpError"]:402},["message","reason"],[0,0],1];_n.registerError(TW,go);var SW=[-3,"com.amazon.aws.codewhisperer","ServiceUnavailableException",{["error"]:"server",["httpError"]:503},["message"],[0],1];_n.registerError(SW,Mo);var $W=[-3,"com.amazon.aws.codewhisperer","ThrottlingException",{["error"]:"client",["httpError"]:429},["message","reason"],[0,0],1];_n.registerError($W,_o);var UW=[-3,"com.amazon.aws.codewhisperer","ValidationException",{["error"]:"client",["httpError"]:400},["message","reason"],[0,0],1];_n.registerError(UW,wo);var a1=[V1,_n];var qh=[0,"com.amazon.aws.codewhisperer","SensitiveDocument",8,15],F=[0,"com.amazon.aws.codewhisperer","SensitiveString",8,0],LW=[0,"com.amazon.aws.codewhisperer","ToolDescription",8,0],Ro=[0,"com.amazon.aws.codewhisperer","ToolName",8,0],j=[0,"com.amazon.aws.q","SensitiveString",8,0],IW=[3,"com.amazon.aws.codewhisperer","AdditionalContentEntry",0,["name","description","innerContext"],[[()=>F,0],[()=>F,0],[()=>F,0]],2],yW=[3,"com.amazon.aws.codewhisperer","AppStudioState",0,["namespace","propertyName","propertyContext","propertyValue"],[[()=>F,0],[()=>F,0],[()=>F,0],[()=>F,0]],3],OW=[3,"com.amazon.aws.codewhisperer","AssistantResponseEvent",0,["content","modelId"],[[()=>F,0],0],1],GW=[3,"com.amazon.aws.codewhisperer","AssistantResponseMessage",0,["content","messageId","supplementaryWebLinks","references","followupPrompt","toolUses","cachePoint","reasoningContent"],[[()=>F,0],0,[()=>cg,0],()=>fg,[()=>p1,0],[()=>c7,0],()=>Ch,[()=>H7,0]],1];var Ch=[3,"com.amazon.aws.codewhisperer","CachePoint",0,["type"],[0],1],BW=[3,"com.amazon.aws.codewhisperer","CitationEvent",0,["target","citationLink","citationText"],[()=>L7,[()=>F,0],[()=>F,0]],2],FW=[3,"com.amazon.aws.codewhisperer","ClientCacheConfig",0,["useClientCachingOnly"],[2]],HW=[3,"com.amazon.aws.codewhisperer","CodeDescription",0,["href"],[[()=>F,0]],1],PW=[3,"com.amazon.aws.codewhisperer","CodeEvent",0,["content"],[[()=>F,0]],1],NW=[3,"com.amazon.aws.codewhisperer","CodeReferenceEvent",0,["references"],[()=>fg]],WW=[3,"com.amazon.aws.codewhisperer","ConsoleState",0,["region","consoleUrl","serviceId","serviceConsolePage","serviceSubconsolePage","taskName","uxErrorMessage"],[0,[()=>F,0],0,0,0,[()=>F,0],[()=>F,0]]],DW=[3,"com.amazon.aws.codewhisperer","ContextUsageEvent",0,["contextUsagePercentage"],[1]],mW=[3,"com.amazon.aws.codewhisperer","ConversationState",0,["currentMessage","chatTriggerType","conversationId","workspaceId","history","customizationArn","agentContinuationId","agentTaskType"],[[()=>hg,0],0,0,0,[()=>pD,0],0,0,0],2],YW=[3,"com.amazon.aws.codewhisperer","DiagnosticLocation",0,["uri","range"],[[()=>F,0],()=>Kh],2],QW=[3,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformation",0,["location","message"],[[()=>YW,0],[()=>F,0]],2],JW=[3,"com.amazon.aws.codewhisperer","DocumentBlock",0,["name","format","source"],[0,0,[()=>G7,0]],3],kW=[3,"com.amazon.aws.codewhisperer","DocumentCitationEvent",0,["source","title","location","sourceContent"],[[()=>F,0],[()=>F,0],[()=>O7,0],[()=>t7,0]]],zW=[3,"com.amazon.aws.codewhisperer","DocumentCitationSearchResultSpan",0,["searchResultIndex","start","end"],[1,1,1]],XW=[3,"com.amazon.aws.codewhisperer","DocumentCitationSourceContent",0,["text"],[[()=>F,0]]],zh=[3,"com.amazon.aws.codewhisperer","DocumentCitationSpan",0,["documentIndex","start","end"],[1,1,1]],xW=[3,"com.amazon.aws.codewhisperer","DocumentCitationWebLocation",0,["url","domain"],[[()=>F,0],[()=>F,0]]],qW=[3,"com.amazon.aws.codewhisperer","DocumentSymbol",0,["name","type","source"],[0,0,0],2],CW=[3,"com.amazon.aws.codewhisperer","DryRunSucceedEvent",0,[],[]],KW=[3,"com.amazon.aws.codewhisperer","EditorState",0,["document","cursorState","relevantDocuments","useRelevantDocuments","workspaceFolders"],[[()=>tg,0],()=>I7,[()=>i7,0],2,[()=>h7,0]]],VW=[3,"com.amazon.aws.codewhisperer","EnvironmentVariable",0,["key","value"],[[()=>F,0],[()=>F,0]]],jW=[3,"com.amazon.aws.codewhisperer","EnvState",0,["operatingSystem","currentWorkingDirectory","environmentVariables","timezoneOffset"],[0,[()=>F,0],[()=>n7,0],1]],p1=[3,"com.amazon.aws.codewhisperer","FollowupPrompt",0,["content","userIntent"],[[()=>F,0],0],1],aW=[3,"com.amazon.aws.codewhisperer","FollowupPromptEvent",0,["followupPrompt"],[[()=>p1,0]]],pW=[3,"com.amazon.aws.codewhisperer","GitState",0,["status"],[[()=>F,0]]],ZW=[3,"com.amazon.aws.codewhisperer","ImageBlock",0,["format","source"],[0,[()=>B7,0]],2],vW=[3,"com.amazon.aws.codewhisperer","IntentsEvent",0,["intents"],[[()=>S7,0]]],tD=[3,"com.amazon.aws.codewhisperer","InvalidStateEvent",0,["reason","message"],[0,0],2],nD=[3,"com.amazon.aws.codewhisperer","MessageMetadataEvent",0,["conversationId","utteranceId"],[0,0]],sD=[3,"com.amazon.aws.codewhisperer","MetadataEvent",0,["tokenUsage"],[()=>SD]],iD=[3,"com.amazon.aws.codewhisperer","MeteringEvent",0,["usage","unit","unitPlural"],[1,0,0]],Xh=[3,"com.amazon.aws.codewhisperer","Position",0,["line","character"],[1,1],2],Z1=[3,"com.amazon.aws.codewhisperer","ProgrammingLanguage",0,["languageName"],[0],1],Kh=[3,"com.amazon.aws.codewhisperer","Range",0,["start","end"],[()=>Xh,()=>Xh],2],rD=[3,"com.amazon.aws.codewhisperer","ReasoningContentEvent",8,["text","redactedContent","signature"],[[()=>F,0],21,[()=>F,0]]],eD=[3,"com.amazon.aws.codewhisperer","ReasoningText",8,["text","signature"],[[()=>F,0],[()=>F,0]],1],oD=[3,"com.amazon.aws.codewhisperer","Reference",0,["licenseName","repository","url","recommendationContentSpan"],[0,0,0,()=>v1]],fD=[3,"com.amazon.aws.codewhisperer","RelevantTextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols","type"],[[()=>F,0],()=>Z1,[()=>F,0],()=>og,0],1],cD=[3,"com.amazon.aws.codewhisperer","RuntimeDiagnostic",0,["source","severity","message"],[[()=>F,0],0,[()=>F,0]],3],hD=[3,"com.amazon.aws.codewhisperer","ShellHistoryEntry",0,["command","directory","exitCode","stdout","stderr"],[[()=>F,0],[()=>F,0],1,[()=>F,0],[()=>F,0]],1],uD=[3,"com.amazon.aws.codewhisperer","ShellState",0,["shellName","shellHistory"],[0,[()=>r7,0]],1],v1=[3,"com.amazon.aws.codewhisperer","Span",0,["start","end"],[1,1]],lD=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLink",0,["url","title","snippet"],[[()=>F,0],[()=>F,0],[()=>F,0]],2],_D=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLinksEvent",0,["supplementaryWebLinks"],[[()=>cg,0]]],tg=[3,"com.amazon.aws.codewhisperer","TextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols"],[[()=>F,0],()=>Z1,[()=>F,0],()=>og],1],wD=[3,"com.amazon.aws.codewhisperer","TextDocumentDiagnostic",0,["document","range","source","severity","message","code","codeDescription","tags","relatedInformation","data"],[[()=>tg,0],()=>Kh,[()=>F,0],0,[()=>F,0],[()=>F,0],[()=>HW,0],64,[()=>ZD,0],[()=>F,0]],5],AD=[3,"com.amazon.aws.codewhisperer","ToolInputSchema",0,["json"],[[()=>qh,0]]],ng=[3,"com.amazon.aws.codewhisperer","ToolResult",0,["toolUseId","content","status","toolName"],[0,[()=>e7,0],0,[()=>Ro,0]],2],MD=[3,"com.amazon.aws.codewhisperer","ToolResultEvent",0,["toolResult"],[[()=>ng,0]]],gD=[3,"com.amazon.aws.codewhisperer","ToolSpecification",0,["inputSchema","name","description"],[[()=>AD,0],[()=>Ro,0],[()=>LW,0]],2],dD=[3,"com.amazon.aws.codewhisperer","ToolUse",0,["toolUseId","name","input"],[0,[()=>Ro,0],[()=>qh,0]],3],ED=[3,"com.amazon.aws.codewhisperer","ToolUseEvent",0,["toolUseId","name","input","stop"],[0,[()=>Ro,0],[()=>F,0],2],2];var RD=[3,"com.amazon.aws.codewhisperer","UserInputMessage",0,["content","userInputMessageContext","userIntent","origin","images","documents","modelId","cachePoint","clientCacheConfig"],[[()=>F,0],[()=>bD,0],0,0,[()=>s7,0],[()=>vD,0],0,()=>Ch,()=>FW],1],bD=[3,"com.amazon.aws.codewhisperer","UserInputMessageContext",0,["editorState","shellState","gitState","envState","appStudioContext","diagnostic","consoleState","userSettings","additionalContext","toolResults","tools"],[[()=>KW,0],[()=>uD,0],[()=>pW,0],[()=>jW,0],[()=>yW,0],[()=>y7,0],[()=>WW,0],()=>TD,[()=>aD,0],[()=>o7,0],[()=>f7,0]]],TD=[3,"com.amazon.aws.codewhisperer","UserSettings",0,["hasConsentedToCrossRegionCalls"],[2]];var SD=[3,"com.amazon.aws.codewhisperer.internal","TokenUsage",0,["uncachedInputTokens","outputTokens","totalTokens","cacheReadInputTokens","cacheWriteInputTokens","contextUsagePercentage","normalizedTokenUsage"],[1,1,1,1,1,1,1],3];var $D=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseRequest",0,["conversationState","profileArn","agentMode","additionalModelRequestFields"],[[()=>mW,0],0,[0,{["httpHeader"]:"x-amzn-kiro-agent-mode"}],15],1],UD=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseResponse",0,["conversationId","generateAssistantResponseResponse"],[[0,{["httpHeader"]:"x-amzn-codewhisperer-conversation-id"}],[()=>U7,16]],2];var LD=[3,"com.amazon.aws.q","InteractionComponentsEvent",0,["interactionComponentEntries"],[[()=>w7,0]],1],Vh=[3,"com.amazon.aws.q.interactioncomponents","Action",0,["webLink","moduleLink"],[[()=>jD,0],[()=>WD,0]]],jh=[3,"com.amazon.aws.q.interactioncomponents","Alert",0,["type","content"],[0,[()=>u7,0]],2],ID=[3,"com.amazon.aws.q.interactioncomponents","AlertComponent",0,["text"],[[()=>Ar,0]]],yD=[3,"com.amazon.aws.q.interactioncomponents","Clarification",0,["questions","dismissible"],[[()=>_7,0],2],1],OD=[3,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOption",0,["label","value"],[[()=>j,0],[()=>j,0]],2],GD=[3,"com.amazon.aws.q.interactioncomponents","ClarificationQuestion",0,["question","options","allowCustom","skippable"],[[()=>j,0],[()=>l7,0],2,2],2],BD=[3,"com.amazon.aws.q.interactioncomponents","CloudWatchTroubleshootingLink",0,["label","investigationPayload","defaultText"],[[()=>j,0],[()=>j,0],[()=>j,0]],2],sg=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdate",0,["transition"],[[()=>FD,0]]],FD=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdateTransition",0,["currentState","nextState"],[[()=>j,0],[()=>j,0]],2],HD=[3,"com.amazon.aws.q.interactioncomponents","InlineArtifact",0,["dsl","summary","title","artifactLabel"],[[()=>j,0],[()=>j,0],[()=>j,0],[()=>j,0]],4],PD=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponent",0,["text","alert","infrastructureUpdate","progress","step","taskDetails","taskReference","suggestions","section","resource","resourceList","action","clarification","inlineArtifact"],[[()=>Ar,0],[()=>jh,0],[()=>sg,0],[()=>ig,0],[()=>eg,0],[()=>CD,0],()=>VD,[()=>kD,0],[()=>mD,0],[()=>ah,0],[()=>rg,0],[()=>Vh,0],[()=>yD,0],[()=>HD,0]]],ND=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntry",0,["interactionComponent","interactionComponentId"],[[()=>PD,0],0],1],WD=[3,"com.amazon.aws.q.interactioncomponents","ModuleLink",0,["cloudWatchTroubleshootingLink"],[[()=>BD,0]]],ig=[3,"com.amazon.aws.q.interactioncomponents","Progress",0,["content"],[[()=>A7,0]],1],DD=[3,"com.amazon.aws.q.interactioncomponents","ProgressComponent",0,["step"],[[()=>eg,0]]],ah=[3,"com.amazon.aws.q.interactioncomponents","Resource",0,["title","link","description","type","ARN","resourceJsonString"],[[()=>j,0],[()=>j,0],[()=>j,0],[()=>j,0],[()=>j,0],[()=>j,0]],6],rg=[3,"com.amazon.aws.q.interactioncomponents","ResourceList",0,["items","action"],[[()=>M7,0],[()=>Vh,0]],1],mD=[3,"com.amazon.aws.q.interactioncomponents","Section",0,["title","content","action"],[[()=>j,0],[()=>g7,0],[()=>Vh,0]],2],YD=[3,"com.amazon.aws.q.interactioncomponents","SectionComponent",0,["text","alert","resource","resourceList"],[[()=>Ar,0],[()=>jh,0],[()=>ah,0],[()=>rg,0]]],eg=[3,"com.amazon.aws.q.interactioncomponents","Step",0,["id","state","label","content"],[1,0,[()=>j,0],[()=>d7,0]],3],QD=[3,"com.amazon.aws.q.interactioncomponents","StepComponent",0,["text"],[[()=>Ar,0]]],JD=[3,"com.amazon.aws.q.interactioncomponents","Suggestion",0,["value"],[[()=>j,0]],1],kD=[3,"com.amazon.aws.q.interactioncomponents","Suggestions",0,["items"],[[()=>E7,0]],1],zD=[3,"com.amazon.aws.q.interactioncomponents","TaskAction",0,["label","payload","note","primary","disabled","confirmation"],[[()=>j,0],[()=>$7,0],[()=>xD,0],2,2,[()=>XD,0]],2],XD=[3,"com.amazon.aws.q.interactioncomponents","TaskActionConfirmation",0,["content"],[[()=>j,0]]],xD=[3,"com.amazon.aws.q.interactioncomponents","TaskActionNote",0,["content","type"],[[()=>j,0],0],1],qD=[3,"com.amazon.aws.q.interactioncomponents","TaskComponent",0,["text","infrastructureUpdate","alert","progress"],[[()=>Ar,0],[()=>sg,0],[()=>jh,0],[()=>ig,0]]],CD=[3,"com.amazon.aws.q.interactioncomponents","TaskDetails",0,["overview","content","actions"],[[()=>KD,0],[()=>b7,0],[()=>R7,0]],2],KD=[3,"com.amazon.aws.q.interactioncomponents","TaskOverview",0,["label","description"],[[()=>j,0],[()=>j,0]],2],VD=[3,"com.amazon.aws.q.interactioncomponents","TaskReference",0,["taskId"],[0],1],Ar=[3,"com.amazon.aws.q.interactioncomponents","Text",0,["content"],[[()=>j,0]],1],jD=[3,"com.amazon.aws.q.interactioncomponents","WebLink",0,["label","url"],[[()=>j,0],[()=>j,0]],2];var aD=[1,"com.amazon.aws.codewhisperer","AdditionalContentList",0,[()=>IW,0]],pD=[1,"com.amazon.aws.codewhisperer","ChatHistory",0,[()=>hg,0]],ZD=[1,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformationList",0,[()=>QW,0]];var vD=[1,"com.amazon.aws.codewhisperer","DocumentBlocks",0,[()=>JW,0]],t7=[1,"com.amazon.aws.codewhisperer","DocumentCitationSourceContents",0,[()=>XW,0]],og=[1,"com.amazon.aws.codewhisperer","DocumentSymbols",0,()=>qW],n7=[1,"com.amazon.aws.codewhisperer","EnvironmentVariables",0,[()=>VW,0]],s7=[1,"com.amazon.aws.codewhisperer","ImageBlocks",0,[()=>ZW,0]],fg=[1,"com.amazon.aws.codewhisperer","References",0,()=>oD],i7=[1,"com.amazon.aws.codewhisperer","RelevantDocumentList",0,[()=>fD,0]],r7=[1,"com.amazon.aws.codewhisperer","ShellHistory",0,[()=>hD,0]],cg=[1,"com.amazon.aws.codewhisperer","SupplementaryWebLinks",0,[()=>lD,0]],e7=[1,"com.amazon.aws.codewhisperer","ToolResultContent",0,[()=>N7,0]],o7=[1,"com.amazon.aws.codewhisperer","ToolResults",0,[()=>ng,0]],f7=[1,"com.amazon.aws.codewhisperer","Tools",0,[()=>P7,0]],c7=[1,"com.amazon.aws.codewhisperer","ToolUses",0,[()=>dD,0]],h7=[1,"com.amazon.aws.codewhisperer","WorkspaceFolderList",0,[()=>F,0]],u7=[1,"com.amazon.aws.q.interactioncomponents","AlertComponentList",0,[()=>ID,0]],l7=[1,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOptionsList",0,[()=>OD,0]],_7=[1,"com.amazon.aws.q.interactioncomponents","ClarificationQuestionList",0,[()=>GD,0]],w7=[1,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntryList",0,[()=>ND,0]],A7=[1,"com.amazon.aws.q.interactioncomponents","ProgressComponentList",0,[()=>DD,0]],M7=[1,"com.amazon.aws.q.interactioncomponents","Resources",0,[()=>ah,0]],g7=[1,"com.amazon.aws.q.interactioncomponents","SectionComponentList",0,[()=>YD,0]],d7=[1,"com.amazon.aws.q.interactioncomponents","StepComponentList",0,[()=>QD,0]],E7=[1,"com.amazon.aws.q.interactioncomponents","SuggestionList",0,[()=>JD,0]],R7=[1,"com.amazon.aws.q.interactioncomponents","TaskActionList",0,[()=>zD,0]],b7=[1,"com.amazon.aws.q.interactioncomponents","TaskComponentList",0,[()=>qD,0]],T7=[2,"com.amazon.aws.codewhisperer","IntentData",8,0,()=>F7],S7=[2,"com.amazon.aws.codewhisperer","IntentMap",0,[0,0],[()=>T7,0]],$7=[2,"com.amazon.aws.q.interactioncomponents","TaskActionPayload",0,[0,0],[()=>j,0]],hg=[4,"com.amazon.aws.codewhisperer","ChatMessage",0,["userInputMessage","assistantResponseMessage"],[[()=>RD,0],[()=>GW,0]]],U7=[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"],[()=>nD,[()=>OW,0],[()=>rD,0],()=>CW,()=>NW,[()=>_D,0],[()=>aW,0],[()=>PW,0],[()=>vW,0],[()=>LD,0],[()=>ED,0],[()=>MD,0],()=>sD,()=>iD,()=>DW,[()=>BW,0],[()=>kW,0],()=>tD,[()=>j1,0]]],L7=[4,"com.amazon.aws.codewhisperer","CitationTarget",0,["location","range"],[1,()=>v1]],I7=[4,"com.amazon.aws.codewhisperer","CursorState",0,["position","range"],[()=>Xh,()=>Kh]],y7=[4,"com.amazon.aws.codewhisperer","Diagnostic",0,["textDocumentDiagnostic","runtimeDiagnostic"],[[()=>wD,0],[()=>cD,0]]],O7=[4,"com.amazon.aws.codewhisperer","DocumentCitationLocation",0,["documentPage","documentChar","documentChunk","searchResult","web"],[()=>zh,()=>zh,()=>zh,()=>zW,[()=>xW,0]]],G7=[4,"com.amazon.aws.codewhisperer","DocumentSource",8,["bytes"],[21]];var B7=[4,"com.amazon.aws.codewhisperer","ImageSource",8,["bytes"],[21]],F7=[4,"com.amazon.aws.codewhisperer","IntentDataType",0,["string"],[0]],H7=[4,"com.amazon.aws.codewhisperer","ReasoningContent",8,["reasoningText","redactedContent"],[[()=>eD,0],21]];var P7=[4,"com.amazon.aws.codewhisperer","Tool",0,["toolSpecification","cachePoint"],[[()=>gD,0],()=>Ch]],N7=[4,"com.amazon.aws.codewhisperer","ToolResultContentBlock",0,["text","json"],[[()=>F,0],[()=>qh,0]]];var ug=[9,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponse",{["http"]:["POST","/generateAssistantResponse",200]},()=>$D,()=>UD];var wg=(t)=>{return{apiVersion:"2023-11-27",base64Decoder:t?.base64Decoder??hi.fromBase64,base64Encoder:t?.base64Encoder??hi.toBase64,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??K1,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??MA,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(n)=>n.getIdentityProvider("smithy.api#httpBearerAuth"),signer:new _g.HttpBearerAuthSigner}],logger:t?.logger??new X.NoOpLogger,protocol:t?.protocol??lg.AwsRestJsonProtocol,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazon.aws.codewhisperer.streaming",errorTypeRegistries:a1,version:"2023-11-27",serviceTarget:"AmazonCodeWhispererStreamingService"},serviceId:t?.serviceId??"CodeWhispererStreaming",urlParser:t?.urlParser??Qh.parseUrl,utf8Decoder:t?.utf8Decoder??gs.fromUtf8,utf8Encoder:t?.utf8Encoder??gs.toUtf8}};var dg=(t)=>{X.emitWarningIfUnsupportedVersion(process.version);let n=Yh.resolveDefaultsModeConfig(t),s=()=>n().then(X.loadConfigsForDefaultMode),i=wg(t);Ag.emitWarningIfUnsupportedVersion(process.version);let r={profile:t?.profile,logger:i.logger};return{...i,...t,runtime:"node",defaultsMode:n,authSchemePreference:t?.authSchemePreference??Ln.loadConfig(Mg.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,r),bodyLengthChecker:t?.bodyLengthChecker??mh.calculateBodyLength,defaultUserAgentProvider:t?.defaultUserAgentProvider??ln.createDefaultUserAgentProvider({serviceId:i.serviceId,clientVersion:RA.version}),eventStreamSerdeProvider:t?.eventStreamSerdeProvider??oo.eventStreamSerdeProvider,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(e)=>e.getIdentityProvider("smithy.api#httpBearerAuth")||(async(f)=>{return await Wh(f)(f)}),signer:new gg.HttpBearerAuthSigner}],maxAttempts:t?.maxAttempts??Ln.loadConfig(v.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,t),region:t?.region??Ln.loadConfig(p.NODE_REGION_CONFIG_OPTIONS,{...p.NODE_REGION_CONFIG_FILE_OPTIONS,...r}),requestHandler:bo.NodeHttpHandler.create(t?.requestHandler??s),retryMode:t?.retryMode??Ln.loadConfig({...v.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await s()).retryMode||ht.DEFAULT_RETRY_MODE},t),sha256:t?.sha256??Dh.Hash.bind(null,"sha256"),streamCollector:t?.streamCollector??bo.streamCollector,useDualstackEndpoint:t?.useDualstackEndpoint??Ln.loadConfig(p.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,r),useFipsEndpoint:t?.useFipsEndpoint??Ln.loadConfig(p.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,r),userAgentAppId:t?.userAgentAppId??Ln.loadConfig(ln.NODE_APP_ID_CONFIG_OPTIONS,r)}};var Pt=m(xt(),1);var Gt=m(Ut(),1);var Eg=(t)=>{let{httpAuthSchemes:n,httpAuthSchemeProvider:s,token:i}=t;return{setHttpAuthScheme(r){let e=n.findIndex((f)=>f.schemeId===r.schemeId);if(e===-1)n.push(r);else n.splice(e,1,r)},httpAuthSchemes(){return n},setHttpAuthSchemeProvider(r){s=r},httpAuthSchemeProvider(){return s},setToken(r){i=r},token(){return i}}},Rg=(t)=>{return{httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),token:t.token()}};var bg=(t,n)=>{let s=Object.assign(Pt.getAwsRegionExtensionConfiguration(t),X.getDefaultExtensionConfiguration(t),Gt.getHttpHandlerExtensionConfiguration(t),Eg(t));return n.forEach((i)=>i.configure(s)),Object.assign(t,Pt.resolveAwsRegionExtensionConfiguration(s),X.resolveDefaultRuntimeConfig(s),Gt.resolveHttpHandlerRuntimeConfig(s),Rg(s))};class ph extends X.Client{config;constructor(...[t]){let n=dg(t||{});super(n);this.initConfig=n;let s=dA(n),i=Un.resolveUserAgentConfig(s),r=v.resolveRetryConfig(i),e=p.resolveRegionConfig(r),f=zn.resolveHostHeaderConfig(e),o=Nt.resolveEndpointConfig(f),c=Ht.resolveDefaultAwsRegionalEndpointsConfig(o),h=Dc.resolveEventStreamSerdeConfig(c),u=gA(h),l=bg(u,t?.extensions||[]);this.config=l,this.middlewareStack.use(Tg.getSchemaSerdePlugin(this.config)),this.middlewareStack.use(Un.getUserAgentPlugin(this.config)),this.middlewareStack.use(v.getRetryPlugin(this.config)),this.middlewareStack.use(ir.getContentLengthPlugin(this.config)),this.middlewareStack.use(zn.getHostHeaderPlugin(this.config)),this.middlewareStack.use(nr.getLoggerPlugin(this.config)),this.middlewareStack.use(sr.getRecursionDetectionPlugin(this.config)),this.middlewareStack.use(li.getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:AA,identityProviderConfigProvider:async(_)=>new li.DefaultIdentityProviderConfig({"smithy.api#httpBearerAuth":_.token})})),this.middlewareStack.use(li.getHttpSigningPlugin(this.config))}destroy(){super.destroy()}}class Zh extends X.Command.classBuilder().ep(EA).m(function(t,n,s,i){return[Nt.getEndpointPlugin(s,t.getEndpointParameterInstructions())]}).s("AmazonCodeWhispererStreamingService","GenerateAssistantResponse",{eventStream:{output:!0}}).n("CodeWhispererStreamingClient","GenerateAssistantResponseCommand").sc(ug).build(){}function Sg(t){let n=Oi[t];if(!n)throw Error(`Unsupported model: ${t}. Supported models: ${nu.join(", ")}`);return n}var $g=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"]),Ug=["low","medium","high","xhigh","max"];function To(t){for(let n of Ug){let s=`-${n}`;if(t.endsWith(s)){let i=t.slice(0,-s.length);if($g.has(i))return{wireId:Sg(i),effort:n}}}return{wireId:Sg(t),effort:void 0}}function W7(t){for(let n of Ug){let s=`-${n}`;if(t.endsWith(s)){let i=t.slice(0,-s.length);if($g.has(i))return i}}if(t.endsWith("-thinking")){let n=t.slice(0,-9);if(Oi[n])return n}return t}function Lg(t){return B(W7(t))}var D7=["low","medium","high","xhigh","max"];function m7(t){return typeof t==="string"&&D7.some((n)=>n===t)}var Ig=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),yg=new Set(["claude-opus-4.7","claude-opus-4.8","claude-sonnet-5",...Ig]),Y7=new Set(["claude-opus-4.5","claude-opus-4.6","claude-opus-4.6-1m","claude-sonnet-4.5","claude-sonnet-4.5-1m","claude-sonnet-4.6","claude-sonnet-4.6-1m",...yg]);function So(t){return Y7.has(t)}function Q7(t){return yg.has(t)}function Og(t,n){if(Ig.has(t))return{reasoning:{effort:n}};return{output_config:{effort:n}}}function J7(t,n){if(!So(t))return;if(n==="xhigh"&&!Q7(t))return"max";return n}function k7(t,n){if(!So(n))return;let s;if(t<=1e4)s="low";else if(t<=20000)s="medium";else if(t<=28000)s="high";else s="max";return s}function Gg(t){let n;if(So(t.model))n={wireId:t.model,effort:void 0};else try{n=To(t.model)}catch(i){if(i instanceof Error&&i.message.startsWith("Unsupported model:"))return;throw i}if(!So(n.wireId))return;let s=[n.effort,t.reasoningEffort,t.configEffort];for(let i of s)if(m7(i))return J7(n.wireId,i);if(!t.think)return;if(t.autoEffortMapping??!0)return k7(t.budget,n.wireId);return"medium"}import{randomUUID as K7}from"crypto";function Mr(t){return typeof t==="object"&&t!==null}function z7(t){let n=atob(t),s=new Uint8Array(n.length);for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s}function X7(t){let n=[];for(let s of t){if(!Mr(s)||s.type!=="image"||!Mr(s.source))continue;let i=s.source;if(i.type!=="base64"||typeof i.data!=="string")continue;n.push({mediaType:typeof i.media_type==="string"?i.media_type:"image/jpeg",data:i.data})}return n}function x7(t){let n=[];for(let s of t){if(!Mr(s)||s.type!=="image_url"||!Mr(s.image_url))continue;let i=s.image_url.url;if(typeof i!=="string"||!i.startsWith("data:"))continue;let[r="",e]=i.split(",",2);if(!e)continue;let f=r.split(";")[0]?.replace("data:","");n.push({mediaType:f||"image/jpeg",data:e})}return n}function $o(t){if(!Array.isArray(t))return[];return[...X7(t),...x7(t)]}function Uo(t){let n=[],s=0;for(let i of t){if(n.length>=4)break;if(s+i.data.length>3750000)break;n.push(i),s+=i.data.length}return{images:n.map((i)=>({format:i.mediaType.split("/")[1]||"png",source:{bytes:z7(i.data)}})),omitted:t.length-n.length}}function Lo(t){let n=[];for(let s of t){if(!Mr(s))continue;if(typeof s.text==="string")n.push(s.text);else if(s.type==="text"&&s.text)n.push(String(s.text))}return n.join("")}function vh(t){return typeof t==="object"&&t!==null}function Bg(t,n){for(let s of t){if(s.role!=="assistant")continue;if(s.tool_calls){for(let i of s.tool_calls)if(i.id===n)return i}if(Array.isArray(s.content)){for(let i of s.content)if(vh(i)&&i.type==="tool_use"&&i.id===n)return i}}return null}function Fg(t){let n=[];for(let s of t){if(n.length===0){n.push({...s});continue}let i=n[n.length-1];if(!i||s.role!==i.role){n.push({...s});continue}if(Array.isArray(i.content)&&Array.isArray(s.content))i.content.push(...s.content);else if(typeof i.content==="string"&&typeof s.content==="string")i.content+=`
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
217
|
+
`).run(n,Date.now(),r)})}clearRemovedAccount(n){this.withImmediateTransaction(()=>this.clearRemovedAccountInternal(n))}getSessionAffinity(n,t=Date.now()){let i=this.db.query(`
|
|
218
|
+
SELECT * FROM session_affinity
|
|
219
|
+
WHERE key_hash = ? AND expires_at > ?
|
|
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(`
|
|
221
|
+
INSERT OR IGNORE INTO session_affinity (
|
|
222
|
+
key_hash, account_id, conversation_id, created_at, last_seen, expires_at
|
|
223
|
+
) VALUES (?, ?, ?, ?, ?, ?)
|
|
224
|
+
`).run(n,t,i,r,r,r+s),this.db.query(`
|
|
225
|
+
UPDATE session_affinity
|
|
226
|
+
SET last_seen = ?, expires_at = ?
|
|
227
|
+
WHERE key_hash = ?
|
|
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(`
|
|
229
|
+
INSERT INTO session_affinity (
|
|
230
|
+
key_hash, account_id, conversation_id, created_at, last_seen, expires_at
|
|
231
|
+
) VALUES (?, ?, ?, ?, ?, ?)
|
|
232
|
+
ON CONFLICT(key_hash) DO UPDATE SET
|
|
233
|
+
account_id = excluded.account_id,
|
|
234
|
+
conversation_id = excluded.conversation_id,
|
|
235
|
+
created_at = excluded.created_at,
|
|
236
|
+
last_seen = excluded.last_seen,
|
|
237
|
+
expires_at = excluded.expires_at
|
|
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(`
|
|
255
|
+
DELETE FROM session_affinity
|
|
256
|
+
WHERE key_hash IN (
|
|
257
|
+
SELECT key_hash FROM session_affinity
|
|
258
|
+
WHERE key_hash != ?
|
|
259
|
+
ORDER BY last_seen ASC, key_hash ASC
|
|
260
|
+
LIMIT ?
|
|
261
|
+
)
|
|
262
|
+
`):this.db.query(`
|
|
263
|
+
DELETE FROM session_affinity
|
|
264
|
+
WHERE key_hash IN (
|
|
265
|
+
SELECT key_hash FROM session_affinity
|
|
266
|
+
ORDER BY last_seen ASC, key_hash ASC
|
|
267
|
+
LIMIT ?
|
|
268
|
+
)
|
|
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
|
|
285
|
+
data: ${JSON.stringify({type:"error",error:{type:t,message:n}})}
|
|
116
286
|
|
|
117
|
-
${e.content}`:e.content;if(e.toolUses)c.toolUses=[...c.toolUses??[],...e.toolUses]}else s.push({assistantResponseMessage:e})}return C7(s)}function Wg(t,n,s){if(!n)return t;let i=t.find((r)=>r.userInputMessage);if(i?.userInputMessage)i.userInputMessage.content=`${n}
|
|
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(`
|
|
118
288
|
|
|
119
|
-
|
|
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}
|
|
120
290
|
|
|
121
|
-
${s.content}`:`<thinking>${e}</thinking>`}if(i.length>0)s.toolUses=i;if(s.content||s.toolUses)t.push({assistantResponseMessage:s})}function t9(t){let n="",s=[],i=[];if(t.role==="tool"){let r=t.tool_results??[{content:t.content,tool_call_id:t.tool_call_id}];for(let e of r){if(typeof e.tool_call_id!=="string")continue;s.push({content:[{text:Bt(e)}],status:"success",toolUseId:e.tool_call_id})}}else if(Array.isArray(t.content)){n=Lo(t.content);for(let e of t.content){if(!wn(e)||e.type!=="tool_result"||typeof e.tool_use_id!=="string")continue;s.push({content:[{text:Bt(e.content??e)}],status:"success",toolUseId:e.tool_use_id})}let r=Uo($o(t.content));if(i.push(...r.images),r.omitted>0)n+=`
|
|
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"}})}
|
|
122
293
|
|
|
123
|
-
|
|
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]
|
|
124
295
|
|
|
125
|
-
`);if(
|
|
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: ${$}
|
|
126
298
|
|
|
127
|
-
|
|
128
|
-
${u}`:R}let _=h.at(-1);if(_?.role==="assistant"&&Bt(_)==="{")h.pop();let w=h.at(-1);if(!w)throw Error("Empty");let A=Ng(h,f),M=w.role==="user"&&!(Array.isArray(w.content)&&w.content.some((R)=>wn(R)&&R.type==="tool_result")),d=h.at(-2);if(M&&d?.role==="assistant"&&A.at(-1)?.userInputMessage){let R=Bt(d);if(R)A.push({assistantResponseMessage:{content:R}})}A=Wg(A,u,f);let E="[system: conversation continues]",T=[],U=[];if(w.role==="assistant")v7(A,w);else{if(A.at(-1)&&!A.at(-1)?.assistantResponseMessage)A.push({assistantResponseMessage:{content:"[system: conversation continues]"}});let R=t9(w);E=R.content,T=R.toolResults,U=R.images}let S=A.flatMap((R)=>R.assistantResponseMessage?.toolUses??[]),y=new Set(S.map((R)=>R.toolUseId)),D=[],q=[];for(let R of T)if(y.has(R.toolUseId))D.push(R);else{let W=n9(e.messages,R);if(W)q.push({call:W,result:R});else E+=`
|
|
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}
|
|
129
300
|
|
|
130
|
-
[Output for tool call ${R.toolUseId}]:
|
|
131
|
-
${R.content[0]?.text??""}`}if(q.length>0){if(!A.at(-1)||A.at(-1)?.assistantResponseMessage)A.push({userInputMessage:{content:"Running tools...",modelId:f,origin:ot.ORIGIN_AI_EDITOR}});A.push({assistantResponseMessage:{content:"I will execute the following tools.",toolUses:q.map(({call:R})=>R)}}),D.push(...q.map(({result:R})=>R))}let tt={content:E,modelId:f,origin:ot.ORIGIN_AI_EDITOR};if(U.length>0)tt.images=U;let J=Hg(e.tools).filter((R)=>typeof R.toolSpecification.name==="string").map((R)=>({toolSpecification:{...R.toolSpecification,name:R.toolSpecification.name??""}}));if(D.length>0||J.length>0){if(tt.userInputMessageContext={},D.length>0)tt.userInputMessageContext.toolResults=gr(D);if(J.length>0)tt.userInputMessageContext.tools=J}if(Dg(A)){let R=tt.userInputMessageContext?.tools??[],W=new Set(R.map((st)=>st.toolSpecification.name)),k=[...mg(A)].filter((st)=>!W.has(st));if(k.length>0)tt.userInputMessageContext??={},tt.userInputMessageContext.tools=[...R,...k.map((st)=>Z7(st,S))]}let G=K7(),K={conversationState:{chatTriggerType:ot.CHAT_TRIGGER_TYPE_MANUAL,conversationId:G,currentMessage:{userInputMessage:tt},...A.length>0?{history:A}:{}},...s.profileArn?{profileArn:s.profileArn}:{}};return o===void 0?{request:K,resolved:f,convId:G}:{request:K,resolved:f,convId:G,variantEffort:o}}function s9(t){let n=typeof t==="string"?JSON.parse(t):t;if(typeof n!=="object"||n===null||!("reasoning_effort"in n))return;let s=n.reasoning_effort;return typeof s==="string"||s===null?s:void 0}function Qg(t,n,s,i=!1,r=20000,e){let{request:f,resolved:o,convId:c}=Yg(t,n,s,i,r),h=Gg({model:n,think:i,budget:r,reasoningEffort:s9(t),configEffort:e?.effort,autoEffortMapping:e?.autoEffortMapping});return{conversationState:f.conversationState,...f.profileArn?{profileArn:f.profileArn}:{},streaming:!0,effectiveModel:o,conversationId:c,region:tu(s.profileArn)??s.region,...h?{effort:h}:{}}}function Jg(t){return Math.ceil(t.length/4)}async function Io(t,n){if(n?.aborted)return{kind:"aborted"};let s=t.next();if(!n)return{kind:"event",result:await s};return new Promise((i,r)=>{let e=()=>i({kind:"aborted"});n.addEventListener("abort",e,{once:!0}),s.then((f)=>{n.removeEventListener("abort",e),i({kind:"event",result:f})},(f)=>{n.removeEventListener("abort",e),r(f)})})}function dr(t,n){if(!n?.name||!n.toolUseId)return;let s=t.get(n.toolUseId);if(s){s.input+=n.input??"";return}t.set(n.toolUseId,{toolUseId:n.toolUseId,name:n.name,input:n.input??""})}function kg(t){let n=[],s=0;for(let i of t.values()){let r=i.input;try{r=JSON.stringify(JSON.parse(i.input))}catch{r=i.input}n.push({type:"content_block_start",index:s,content_block:{type:"tool_use",id:i.toolUseId,name:i.name,input:{}}},{type:"content_block_delta",index:s,delta:{type:"input_json_delta",partial_json:r}},{type:"content_block_stop",index:s}),s+=1}return n}function yo(t,n){let s=n.metadataEvent?.tokenUsage;if(s)t.outputTokens=s.outputTokens??t.outputTokens,t.totalTokens=s.totalTokens??t.totalTokens,t.inputTokens=s.inputTokens??(s.uncachedInputTokens===void 0?t.inputTokens:s.uncachedInputTokens+(s.cacheReadInputTokens??0)+(s.cacheWriteInputTokens??0));t.contextUsagePercentage=n.contextUsageEvent?.contextUsagePercentage??n.metadataEvent?.contextUsagePercentage??s?.contextUsagePercentage??t.contextUsagePercentage}function Oo(t,n,s){let i=t.outputTokens??Jg(n),r=t.inputTokens;if(r===void 0&&t.totalTokens!==void 0)r=Math.max(0,t.totalTokens-i);if(r===void 0&&t.contextUsagePercentage!==void 0&&t.contextUsagePercentage>0){let e=Math.round(Lg(s)*t.contextUsagePercentage/100);r=Math.max(0,e-i)}return{inputTokens:r??0,outputTokens:i}}class zg extends Error{name="MissingSdkEventStreamError";constructor(){super("SDK response has no event stream")}}async function Xg(t,n,s,i){let r=t.generateAssistantResponseResponse;if(!r)throw new zg;let e=r[Symbol.asyncIterator](),f=new Map,o={},c="",h="",u=!1,l=!1;try{while(!0){let A=await Io(e,i);if(A.kind==="aborted"){if(e.return)await e.return();l=!0;break}if(A.result.done){u=!0;break}let M=A.result.value;yo(o,M),h+=M.reasoningContentEvent?.text??"",c+=M.assistantResponseEvent?.content??"",dr(f,M.toolUseEvent)}}finally{if(!u&&!l&&e.return)await e.return()}let _=Oo(o,c,n),w={role:"assistant",content:c,...h?{reasoning_content:h}:{},...f.size>0?{tool_calls:Array.from(f.values(),(A)=>({id:A.toolUseId,type:"function",function:{name:A.name,arguments:A.input}}))}:{}};return{id:s,object:"chat.completion",created:Math.floor(Date.now()/1000),model:n,choices:[{index:0,message:w,finish_reason:f.size>0?"tool_calls":"stop"}],usage:{prompt_tokens:_.inputTokens,completion_tokens:_.outputTokens,total_tokens:_.inputTokens+_.outputTokens}}}var i9=[/input is too long/i,/CONTENT_LENGTH_EXCEEDS_THRESHOLD/i],r9=/econnreset|etimedout|enotfound|network|fetch failed|socket/i;function Go(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function t0(t,n){let s=t[n];return typeof s==="string"?s:void 0}function e9(t){let n=t.$metadata;if(!Go(n))return;let s=n.httpStatusCode;return typeof s==="number"?s:void 0}function o9(t){let n=t.$response;if(!Go(n))return;let s=n.headers;if(!Go(s))return;let i={};for(let[r,e]of Object.entries(s))if(typeof e==="string")i[r]=e;else if(typeof e==="number")i[r]=String(e);return Object.keys(i).length>0?i:void 0}function n0(t){if(!Go(t))return{message:t instanceof Error?t.message:String(t)};let n=e9(t),s=t0(t,"message")??String(t),i=t0(t,"name"),r=t0(t,"reason"),e=o9(t);return{message:s,...n!==void 0?{status:n}:{},...i!==void 0?{code:i}:{},...r!==void 0?{reason:r}:{},...e!==void 0?{headers:e}:{}}}function f9(t){let n=Object.entries(t??{}).find(([i])=>i.toLowerCase()==="retry-after"),s=Number.parseInt(n?.[1]??"60",10);return Number.isFinite(s)&&s>=0?s*1000:60000}function c9(t){return i9.some((n)=>n.test(t))}function xg(t,n){if(t.reason==="INVALID_MODEL_ID"){let s=t.status??400;return{action:"fail",status:s,terminalStatus:s}}if(t.reason==="TEMPORARILY_SUSPENDED")return n.accountCount>1?{action:"switch",...t.status!==void 0?{status:t.status}:{}}:{action:"fail",...t.status!==void 0?{status:t.status}:{},terminalStatus:t.status??403};switch(t.status){case 400:return{action:"fail",status:400,terminalStatus:c9(t.message)?413:400};case 401:return n.retryCount<n.maxRetries?{action:"retry",status:401}:{action:"fail",status:401,terminalStatus:401};case 402:return{action:"fail",status:402,terminalStatus:402};case 403:if(Or(t.message)){if(!n.forcedRefreshAccountIds.has(n.accountId))return n.forcedRefreshAccountIds.add(n.accountId),{action:"refresh-then-retry",status:403};return n.accountCount>1?{action:"switch",status:403}:{action:"fail",status:403,terminalStatus:403}}if(n.accountCount>1)return{action:"switch",status:403};return n.retryCount<n.maxRetries?{action:"retry",status:403,retryAfterMs:n.retryDelayMs*2**n.retryCount}:{action:"fail",status:403,terminalStatus:403};case 429:{let s=f9(t.headers);return n.accountCount>1?{action:"switch",status:429,retryAfterMs:s}:{action:"retry",status:429,retryAfterMs:s}}case 500:return n.serverErrorCount<5?{action:"retry",status:500,retryAfterMs:1000*2**Math.max(0,n.serverErrorCount-1)}:{action:"switch",status:500};case void 0:if(r9.test(t.message))return n.retryCount<n.maxRetries?{action:"retry",retryAfterMs:n.retryDelayMs*2**n.retryCount}:{action:"fail",terminalStatus:500};return{action:"fail",terminalStatus:500};default:return{action:"fail",status:t.status,terminalStatus:t.status}}}var qg=Promise.resolve();function In(t){return t.reason instanceof Error?t.reason:new DOMException("The request was aborted","AbortError")}function _i(t,n){if(n.aborted)return Promise.reject(In(n));return new Promise((s,i)=>{let r=()=>i(In(n));n.addEventListener("abort",r,{once:!0}),t.then((e)=>{n.removeEventListener("abort",r),s(e)},(e)=>{n.removeEventListener("abort",r),i(e)})})}function Cg(t,n){if(t<=0)return Promise.resolve();return _i(Bun.sleep(t),n)}async function Kg(t){let n=qg,s,i=new Promise((f)=>{s=f});if(!s)throw TypeError("Queue release was not initialized");let r=s;qg=n.catch(()=>{return}).then(()=>i);try{await _i(n,t)}catch(f){throw r(),f}let e=!1;return()=>{if(e)return;e=!0,r()}}function Vg(t,n){if(t)return{signal:t,dispose:()=>{return}};let s=new AbortController,i=setTimeout(()=>s.abort(new DOMException("Request deadline exceeded","TimeoutError")),n);return{signal:s.signal,dispose:()=>clearTimeout(i)}}var Er="<\uFF5CDSML\uFF5Cfunction_calls";function s0(){return`tool_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}function h9(t){let n=[],s=/```[\s\S]*?```/g;for(let e=s.exec(t);e!==null;e=s.exec(t))n.push([e.index,e.index+e[0].length]);let i=(e)=>n.some(([f,o])=>e>=f&&e<o),r=/`[^`\n]+`/g;for(let e=r.exec(t);e!==null;e=r.exec(t))if(!i(e.index))n.push([e.index,e.index+e[0].length]);return n}function Es(t,n,s){return s.some(([i,r])=>t<r&&n>i)}function u9(t){let n={},s=/<parameter\s+name="([^"]+)"\s*>([\s\S]*?)<\/parameter>/g;for(let i=s.exec(t);i!==null;i=s.exec(t)){let r=i[1];if(r===void 0)continue;let e=i[2]??"";try{n[r]=JSON.parse(e)}catch{n[r]=e}}return n}function jg(t,n){return{toolUseId:s0(),name:t,input:u9(n)}}function l9(t,n,s){let i=[],r=/<function_calls>[\s\S]*?<\/function_calls>/g;for(let f=r.exec(t);f!==null;f=r.exec(t)){let o=f.index,c=o+f[0].length;if(Es(o,c,n))continue;let h=/<invoke\s+name="([^"]+)"\s*>([\s\S]*?)<\/invoke>/g,u=[];for(let l=h.exec(f[0]);l!==null;l=h.exec(f[0])){let _=l[1];if(_)u.push(jg(_,l[2]??""))}if(u.length===0)continue;i.push({start:o,end:c,toolCalls:u}),s.push([o,c])}let e=/<invoke\s+name="([^"]+)"\s*>([\s\S]*?)<\/invoke>/g;for(let f=e.exec(t);f!==null;f=e.exec(t)){let o=f.index,c=o+f[0].length,h=f[1];if(!h||Es(o,c,n)||Es(o,c,s))continue;i.push({start:o,end:c,toolCalls:[jg(h,f[2]??"")]}),s.push([o,c])}return i}function _9(t,n,s){let i=[],r=0;for(;;){let e=t.indexOf(Er,r);if(e===-1)break;let f=t.slice(e+Er.length),o=/<\uFF5C[^>]*?end[^>]*?>|<\/\uFF5CDSML[^>]*?>/.exec(f),c=o!==null?e+Er.length+o.index+o[0].length:t.length;if(r=c,Es(e,c,n)||Es(e,c,s))continue;let h=t.slice(e,c),u=[],l=/name["\uFF5C=:\s]+["']?([A-Za-z0-9_]+)/.exec(h),_=/(\{[\s\S]*\})/.exec(h);if(l?.[1]&&_?.[1])try{u.push({toolUseId:s0(),name:l[1],input:JSON.parse(_[1])})}catch{}i.push({start:e,end:c,toolCalls:u}),s.push([e,c])}return i}function w9(t,n,s){let i=[],r=/\[Called\s+(\w+)\s+with\s+args:\s*(\{[^}]*(?:\{[^}]*\}[^}]*)*\})\]/gs;for(let e=r.exec(t);e!==null;e=r.exec(t)){let f=e.index,o=f+e[0].length,c=e[1],h=e[2];if(!c||!h||Es(f,o,n)||Es(f,o,s))continue;let u;try{u=JSON.parse(h)}catch{continue}i.push({start:f,end:o,toolCalls:[{toolUseId:s0(),name:c,input:u}]}),s.push([f,o])}return i}function ag(t){if(!t)return{toolCalls:[],cleanedText:t};let n=h9(t),s=[],i=[...l9(t,n,s),..._9(t,n,s),...w9(t,n,s)];if(i.length===0)return{toolCalls:[],cleanedText:t};i.sort((o,c)=>o.start-c.start);let r=[],e="",f=0;for(let o of i){if(o.start<f)continue;e+=t.slice(f,o.start),f=o.end,r.push(...o.toolCalls)}return e+=t.slice(f),{toolCalls:r,cleanedText:e}}var i0=["<function_calls","<invoke name=",Er],A9=Math.max(...i0.map((t)=>t.length));function pg(t){let n=-1;for(let s of i0){let i=t.indexOf(s);if(i!==-1&&(n===-1||i<n))n=i}return n}function M9(t){let n=Math.min(t.length,A9-1);for(let s=n;s>0;s--){let i=t.slice(t.length-s);for(let r of i0)if(r.length>s&&r.startsWith(i))return s}return 0}class r0{accumulated="";emitted=0;markerSeen=!1;push(t){if(!t)return"";if(this.accumulated+=t,!this.markerSeen&&pg(this.accumulated)!==-1)this.markerSeen=!0;let n;if(this.markerSeen){let i=pg(this.accumulated);n=i===-1?this.accumulated.length:i}else n=this.accumulated.length-M9(this.accumulated);if(n<=this.emitted)return"";let s=this.accumulated.slice(this.emitted,n);return this.emitted=n,s}get suppressing(){return this.markerSeen}finalize(){let{toolCalls:t,cleanedText:n}=ag(this.accumulated),s=n.length>this.emitted?n.slice(this.emitted):"";return{toolCalls:t,remainderText:s}}}function e0(t,n,s){let i=[];if(t.type==="content_block_delta"){if(t.delta?.type==="text_delta")i.push({index:0,delta:{content:t.delta.text??""},finish_reason:null});else if(t.delta?.type==="thinking_delta"){if(t.delta.thinking)i.push({index:0,delta:{reasoning_content:t.delta.thinking},finish_reason:null})}else if(t.delta?.type==="input_json_delta")i.push({index:0,delta:{tool_calls:[{index:t.index,function:{arguments:t.delta.partial_json??""}}]},finish_reason:null})}else if(t.type==="content_block_start"&&t.content_block?.type==="tool_use")i.push({index:0,delta:{tool_calls:[{index:t.index,id:t.content_block.id,type:"function",function:{name:t.content_block.name,arguments:""}}]},finish_reason:null});else if(t.type==="message_delta")i.push({index:0,delta:{},finish_reason:t.delta?.stop_reason==="tool_use"?"tool_calls":"stop"});else return null;if(i.length===0)return null;let r={id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1000),model:s,choices:i};if(t.type!=="message_delta")return r;let e=t.usage?.input_tokens??0,f=t.usage?.output_tokens??0;return{...r,usage:{prompt_tokens:e,completion_tokens:f,total_tokens:e+f}}}function o0(t,n){let s=/```[\s\S]*?```/g,i=[],r=s.exec(t);while(r!==null)i.push([r.index,r.index+r[0].length]),r=s.exec(t);let e=t.indexOf(n,0);while(e!==-1){if(!i.some(([o,c])=>e>=o&&e<c))return e;e=t.indexOf(n,e+n.length)}return-1}function Zg(t,n){if(t==="thinking"){if(n.thinkingBlockIndex!==null)return[];let i=n.nextBlockIndex++;return n.thinkingBlockIndex=i,[{type:"content_block_start",index:i,content_block:{type:"thinking",thinking:""}}]}if(n.textBlockIndex!==null)return[];let s=n.nextBlockIndex++;return n.textBlockIndex=s,[{type:"content_block_start",index:s,content_block:{type:"text",text:""}}]}function Rs(t,n){if(t===null||n.stoppedBlocks.has(t))return[];return n.stoppedBlocks.add(t),[{type:"content_block_stop",index:t}]}function Cn(t,n){if(!t)return[];let s=Zg("text",n),i=n.textBlockIndex;if(i===null)return s;return s.push({type:"content_block_delta",index:i,delta:{type:"text_delta",text:t}}),s}function Kn(t,n){let s=Zg("thinking",n),i=n.thinkingBlockIndex;if(i===null)return s;return s.push({type:"content_block_delta",index:i,delta:{type:"thinking_delta",thinking:t}}),s}var Bo="<thinking>",Fo="</thinking>";function vg(t,n){n.buffer+=t;let s=[];while(n.buffer.length>0){if(!n.inThinking&&!n.thinkingExtracted){let r=o0(n.buffer,Bo);if(r!==-1){let f=n.buffer.slice(0,r);s.push(...Cn(f,n)),n.buffer=n.buffer.slice(r+Bo.length),n.inThinking=!0;continue}let e=Math.max(0,n.buffer.length-Bo.length);if(e>0)s.push(...Cn(n.buffer.slice(0,e),n)),n.buffer=n.buffer.slice(e);break}if(n.inThinking){let r=o0(n.buffer,Fo);if(r!==-1){if(s.push(...Kn(n.buffer.slice(0,r),n)),n.buffer=n.buffer.slice(r+Fo.length),n.inThinking=!1,n.thinkingExtracted=!0,s.push(...Kn("",n)),s.push(...Rs(n.thinkingBlockIndex,n)),n.buffer.startsWith(`
|
|
132
|
-
|
|
133
|
-
`))n.buffer=n.buffer.slice(2);continue}let e=Math.max(0,n.buffer.length-Fo.length);if(e>0)s.push(...Kn(n.buffer.slice(0,e),n)),n.buffer=n.buffer.slice(e);break}let i=n.buffer;n.buffer="",s.push(...Cn(i,n))}return s}function td(t){if(!t.buffer)return[];let n=t.buffer;if(t.buffer="",!t.inThinking)return Cn(n,t);return[...Kn(n,t),...Kn("",t),...Rs(t.thinkingBlockIndex,t)]}class nd extends Error{name="MissingSdkEventStreamError";constructor(){super("SDK response has no event stream")}}async function*sd(t,n,s,i){let r=t.generateAssistantResponseResponse;if(!r)throw new nd;let e={thinkingRequested:!0,buffer:"",inThinking:!1,thinkingExtracted:!1,thinkingBlockIndex:null,textBlockIndex:null,nextBlockIndex:0,stoppedBlocks:new Set},f=new r0,o=new Map,c={},h=r[Symbol.asyncIterator](),u="",l=!1,_=!1,w=!1,A=!1,M=(S,y=!1)=>{if(y&&S.type==="content_block_delta"&&S.delta?.type==="text_delta"){let D=f.push(S.delta.text??"");if(!D)return null;return e0({...S,delta:{...S.delta,text:D}},s,n)}return e0(S,s,n)};try{while(!0){let S=await Io(h,i);if(S.kind==="aborted"){if(h.return)await h.return();A=!0;return}if(S.result.done){w=!0;break}let y=S.result.value;yo(c,y);let D=y.reasoningContentEvent?.text;if(D){if(_)e.thinkingBlockIndex=null,_=!1;l=!0;for(let tt of Kn(D,e)){let J=M(tt);if(J)yield J}continue}let q=y.assistantResponseEvent?.content;if(q){if(u+=q,l&&!_){for(let J of Rs(e.thinkingBlockIndex,e)){let G=M(J);if(G)yield G}_=!0}let tt=l?Cn(q,e):vg(q,e);for(let J of tt){let G=M(J,!0);if(G)yield G}continue}if(y.toolUseEvent)dr(o,y.toolUseEvent)}}finally{if(!w&&!A&&h.return)await h.return()}if(l&&!_)for(let S of Rs(e.thinkingBlockIndex,e)){let y=M(S);if(y)yield y}for(let S of td(e)){let y=M(S,S.delta?.type==="text_delta");if(y)yield y}let{toolCalls:d,remainderText:E}=f.finalize();for(let S of Cn(E,e)){let y=M(S);if(y)yield y}for(let S of Rs(e.textBlockIndex,e)){let y=M(S);if(y)yield y}for(let S of d)dr(o,{toolUseId:S.toolUseId,name:S.name,input:typeof S.input==="string"?S.input:JSON.stringify(S.input),stop:!0});for(let S of kg(o)){let y=M(S);if(y)yield y}let T=Oo(c,u,n),U=M({type:"message_delta",delta:{type:"message_delta",stop_reason:o.size>0?"tool_use":"end_turn"},usage:{input_tokens:T.inputTokens,output_tokens:T.outputTokens,cache_creation_input_tokens:0,cache_read_input_tokens:0}});if(U)yield U;M({type:"message_stop"})}class id extends Error{timeoutMs;name="StreamIdleTimeoutError";constructor(t){super(`SDK stream idle timeout after ${t}ms`);this.timeoutMs=t}}function rd(t,n,s,i){let r=new AbortController,e=AbortSignal.any([n,r.signal]),f=sd(t.sdkResponse,t.model,t.conversationId,e)[Symbol.asyncIterator](),o=new TextEncoder,c=!1,h,u=()=>{if(h===void 0)return;clearTimeout(h),h=void 0},l=()=>{if(c)return;c=!0,i()},_=async()=>{await f.return?.(void 0)};return new Response(new ReadableStream({async pull(w){let A;try{let M=await Promise.race([f.next(),new Promise((d,E)=>{let T=()=>{u(),E(In(e))};if(A=()=>e.removeEventListener("abort",T),e.addEventListener("abort",T,{once:!0}),h=setTimeout(()=>{h=void 0,E(new id(s))},s),e.aborted)T()})]);if(e.aborted)throw In(e);if(M.done){w.close(),l();return}w.enqueue(o.encode(`${JSON.stringify(M.value)}
|
|
134
|
-
`))}catch(M){if(u(),A?.(),r.signal.aborted)return;let d=M instanceof Error?M:TypeError("SDK stream failed with a non-Error reason",{cause:M});r.abort(d),w.error(d);try{await _()}finally{l()}}finally{u(),A?.()}},async cancel(){u(),r.abort();try{await _()}catch{return}finally{l()}}}),{headers:{"Content-Type":"application/x-ndjson; charset=utf-8"}})}var od=m(Ye(),1);var ed=new Map,g9=3;function Ho(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function d9(t){let n=t.conversationState;if(!Ho(n))return;let s=n.currentMessage;if(!Ho(s))return;let i=s.userInputMessage;if(!Ho(i))return;let r=i.modelId;return typeof r==="string"?r:void 0}function E9(t,n,s,i){let r=i?(()=>{let e=p0(i);return new od.NodeHttpHandler({httpAgent:e,httpsAgent:e})})():void 0;return{region:n,endpoint:s,token:()=>Promise.resolve({token:t.access}),maxAttempts:g9,retryMode:"standard",customUserAgent:[[ot.USER_AGENT]],...r?{requestHandler:r}:{}}}function fd(t,n,s,i,r){let e=i??`https://q.${n}.amazonaws.com`,f=JSON.stringify([n,t.email??null,s??null,e,r??null]),o=ed.get(f);if(o?.token===t.access)return o.client;let c=new ph(E9(t,n,e,r));if(c.middlewareStack.add((h)=>async(u)=>{if(u.request instanceof Gt.HttpRequest)u.request.headers["x-amzn-kiro-agent-mode"]="vibe";return h(u)},{step:"build",name:"addKiroHeaders"}),s)c.middlewareStack.add((h)=>async(u)=>{if(u.request instanceof Gt.HttpRequest&&typeof u.request.body==="string")try{let l=JSON.parse(u.request.body);if(Ho(l)){let _=d9(l);if(_)l.additionalModelRequestFields=Og(_,s),u.request.body=JSON.stringify(l)}}catch(l){if(!(l instanceof SyntaxError))throw l}return h(u)},{step:"build",name:"addEffortConfig",priority:"high"});return ed.set(f,{client:c,token:t.access}),c}function bs(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function R9(t){if(!bs(t))return!1;let n=t.conversationState;return bs(n)&&typeof n.conversationId==="string"&&bs(n.currentMessage)&&typeof n.chatTriggerType==="string"}function b9(t,n){let s=typeof t==="string"?JSON.parse(t):t;if(!bs(s))return{think:n.endsWith("-thinking"),budget:20000};let i=s.providerOptions,r=bs(i)?i.thinkingConfig:void 0,e=s.thinkingConfig,f=bs(r)?r:bs(e)?e:void 0,o=f?.thinkingBudget??f?.budget_tokens;return{think:n.endsWith("-thinking")||f!==void 0,budget:typeof o==="number"?o:20000}}function T9(t,n,s){return V(t,n,"upstream_error",s)}async function S9(t,n){let{think:s,budget:i}=b9(t.body,t.model),r=new Set,e=new Map,f=0,o=0;while(!0){if(n.aborted)throw In(n);if(o+=1,o>t.config.max_request_iterations)return{kind:"response",response:V(500,`Exceeded max iterations (${t.config.max_request_iterations})`,"request_error","max_request_iterations")};t.accountManager.reconcileFromDb();let c=t.accountManager.selectHealthyAccount();if(!c)return{kind:"response",response:V(503,"All accounts are unhealthy or rate-limited","service_unavailable","no_healthy_accounts")};let h=t.accountManager.toAuthDetails(c),u=await _i(t.tokenRefresher.refreshIfNeeded(c,h,n),n),l=t.accountManager.toAuthDetails(u),_=Lr.safeParse(t.config.effort),w=Qg(t.body,t.model,l,s,i,{autoEffortMapping:t.config.auto_effort_mapping,..._.success?{effort:_.data}:{}}),M=(t.makeClient??fd)(l,w.region,w.effort,t.config.test_upstream_endpoint,Qs(t.config)),d={conversationState:w.conversationState,...w.profileArn?{profileArn:w.profileArn}:{}};if(!R9(d))throw TypeError("Transformed request is not a valid SDK command input");let E=new Zh(d);try{let T=await _i(M.send(E,{abortSignal:n}),n);if(t.stream)return{kind:"stream",sdkResponse:T,model:t.model,conversationId:w.conversationId};let U=await Xg(T,t.model,w.conversationId,n);if(n.aborted)throw In(n);return{kind:"response",response:Response.json(U,{headers:{"Content-Type":"application/json"}})}}catch(T){if(n.aborted)throw In(n);let U=n0(T),S=U.status===500?(e.get(u.id)??0)+1:0;if(U.status===500)e.set(u.id,S);let y=xg(U,{accountId:u.id,accountCount:t.accountManager.getAccountCount(),retryCount:f,maxRetries:t.config.rate_limit_max_retries,serverErrorCount:S,retryDelayMs:t.config.rate_limit_retry_delay_ms,forcedRefreshAccountIds:r});switch(y.action){case"refresh-then-retry":await _i(t.tokenRefresher.forceRefresh(u,n),n);continue;case"retry":f+=1,await Cg(y.retryAfterMs??0,n);continue;case"switch":if(U.reason==="TEMPORARILY_SUSPENDED")t.accountManager.markUnhealthy(u,`InvalidTokenException: Account Suspended: ${U.message}`);else t.accountManager.markRateLimited(u,Date.now()+(y.retryAfterMs??t.config.rate_limit_retry_delay_ms));continue;case"fail":if(U.reason==="TEMPORARILY_SUSPENDED")t.accountManager.markUnhealthy(u,`InvalidTokenException: Account Suspended: ${U.message}`);return{kind:"response",response:T9(y.terminalStatus??y.status??500,U.message,U.code)}}}}}async function Po(t){let n=Vg(t.deadlineSignal,t.config.request_timeout_ms),s,i=!1;try{s=await Kg(n.signal);let r=await S9(t,n.signal);if(r.kind==="response")return r.response;let e=s;return s=void 0,i=!0,rd(r,n.signal,t.config.stream_idle_timeout_ms,()=>{e(),n.dispose()})}catch(r){if(n.signal.aborted)return V(504,"Request deadline exceeded","timeout_error","request_timeout");let e=n0(r);return V(500,e.message,"internal_error",e.code)}finally{if(!i)s?.(),n.dispose()}}var Rr=Object.freeze({input:Object.freeze(["text"]),output:Object.freeze(["text"])}),ut=Object.freeze({input:Object.freeze(["text","image"]),output:Object.freeze(["text"])}),a=Object.freeze({input:Object.freeze(["text","image","pdf"]),output:Object.freeze(["text"])}),cd=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"]),hd=Object.freeze([{id:"auto",wireId:"auto",name:"Auto (1.0x)",contextLimit:B("auto"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4",wireId:"claude-sonnet-4",name:"Claude Sonnet 4.0 (1.3x)",contextLimit:B("claude-sonnet-4"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-5",wireId:"claude-sonnet-4.5",name:"Claude Sonnet 4.5 (1.3x)",contextLimit:B("claude-sonnet-4-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6-low",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (low) (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6-medium",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (medium) (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6-high",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (high) (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6-max",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (max) (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-low",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (low) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-medium",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (medium) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-high",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (high) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-xhigh",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (xhigh) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-max",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (max) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-haiku-4-5",wireId:"claude-haiku-4.5",name:"Claude Haiku 4.5 (0.4x)",contextLimit:B("claude-haiku-4-5"),outputLimit:64000,modalities:ut},{id:"claude-opus-4-5",wireId:"claude-opus-4.5",name:"Claude Opus 4.5 (2.2x)",contextLimit:B("claude-opus-4-5"),outputLimit:64000,modalities:a},{id:"claude-opus-4-6",wireId:"claude-opus-4.6",name:"Claude Opus 4.6 (2.2x)",contextLimit:B("claude-opus-4-6"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-low",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (low) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-medium",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (medium) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-high",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (high) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-xhigh",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (xhigh) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-max",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (max) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-low",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (low) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-medium",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (medium) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-high",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (high) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-xhigh",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (xhigh) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-max",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (max) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-thinking",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 Thinking (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"deepseek-3.2",wireId:"deepseek-3.2",name:"DeepSeek 3.2 (0.25x)",contextLimit:B("deepseek-3.2"),outputLimit:64000,modalities:Rr},{id:"glm-5",wireId:"glm-5",name:"GLM-5 (0.5x)",contextLimit:B("glm-5"),outputLimit:64000,modalities:Rr},{id:"minimax-m2.5",wireId:"minimax-m2.5",name:"MiniMax M2.5 (0.25x)",contextLimit:B("minimax-m2.5"),outputLimit:64000,modalities:Rr},{id:"minimax-m2.1",wireId:"minimax-m2.1",name:"MiniMax M2.1 (0.15x)",contextLimit:B("minimax-m2.1"),outputLimit:64000,modalities:Rr},{id:"qwen3-coder-next",wireId:"qwen3-coder-next",name:"Qwen3 Coder Next (0.05x)",contextLimit:B("qwen3-coder-next"),outputLimit:64000,modalities:Rr},{id:"gpt-5.6-sol",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-low",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (low) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-medium",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (medium) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-high",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (high) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-xhigh",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (xhigh) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-max",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (max) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-low",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (low) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-medium",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (medium) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-high",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (high) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-xhigh",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (xhigh) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-max",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (max) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-low",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (low)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-medium",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (medium)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-high",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (high)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-xhigh",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (xhigh)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-max",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (max)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut}]);var f0=g.record(g.unknown()),$9=new Set(cd),U9=g.object({type:g.literal("text"),text:g.string()}).passthrough(),L9=g.object({type:g.literal("image_url"),image_url:g.object({url:g.string(),detail:g.string().optional()}).passthrough()}).passthrough(),I9=g.object({type:g.literal("image"),source:g.object({type:g.string(),data:g.string(),media_type:g.string().optional()}).passthrough()}).passthrough(),y9=g.object({type:g.literal("tool_result"),tool_use_id:g.string().min(1),content:g.unknown()}).passthrough(),O9=g.object({type:g.literal("tool_use"),id:g.string().min(1),name:g.string().min(1),input:g.unknown()}).passthrough(),G9=g.object({type:g.literal("thinking"),thinking:g.string().optional(),text:g.string().optional()}).passthrough(),B9=g.discriminatedUnion("type",[U9,L9,I9,y9,O9,G9]),No=g.union([g.string(),g.array(B9)]);function ud(t){try{return JSON.parse(t),!0}catch(n){if(n instanceof SyntaxError)return!1;throw n}}var F9=g.object({id:g.string().min(1),type:g.literal("function"),function:g.object({name:g.string().min(1),arguments:g.string().refine(ud,"function arguments must contain valid JSON")}).passthrough()}).passthrough(),H9=g.object({role:g.literal("system"),content:No}).passthrough(),P9=g.object({role:g.literal("user"),content:No}).passthrough(),N9=g.object({role:g.literal("assistant"),content:No.nullable().optional(),tool_calls:g.array(F9).min(1).optional()}).passthrough().refine((t)=>t.content!==null&&t.content!==void 0?!0:t.tool_calls!==void 0,{message:"assistant message requires content or tool_calls"}),W9=g.object({role:g.literal("tool"),content:No,tool_call_id:g.string().min(1)}).passthrough(),D9=g.union([H9,P9,N9,W9]),m9=g.object({type:g.literal("function"),function:g.object({name:g.string().min(1),description:g.string().optional(),parameters:f0.optional()}).passthrough()}).passthrough(),Y9=g.object({name:g.string().min(1),description:g.string().optional(),input_schema:f0.optional()}).passthrough(),Q9=g.object({model:g.string().refine((t)=>$9.has(t),{message:"model is not supported"}),stream:g.boolean().default(!1),messages:g.array(D9).min(1),tools:g.array(g.union([m9,Y9])).optional(),reasoning_effort:g.enum(["low","medium","high","xhigh","max"]).optional()}).passthrough(),J9=g.object({type:g.literal("input_text"),text:g.string()}).passthrough(),k9=g.object({type:g.literal("output_text"),text:g.string()}).passthrough(),z9=g.object({type:g.literal("input_image"),image_url:g.string()}).passthrough(),X9=new Set(["input_text","output_text","input_image"]),x9=g.object({type:g.string()}).passthrough().refine((t)=>!X9.has(t.type),{message:"known content parts must have a valid payload"}),q9=g.union([J9,k9,z9,x9]),C9=g.object({type:g.literal("message"),role:g.enum(["system","developer","user","assistant"]),content:g.array(q9)}).passthrough(),K9=g.object({type:g.literal("function_call"),call_id:g.string().min(1),name:g.string().min(1),arguments:g.string().refine(ud,"function arguments must contain valid JSON")}).passthrough(),V9=g.object({type:g.literal("function_call_output"),call_id:g.string().min(1),output:g.union([g.string(),g.array(g.object({type:g.string(),text:g.string().optional()}).passthrough())])}).passthrough(),j9=g.object({type:g.literal("additional_tools"),role:g.string().optional(),tools:g.array(g.object({type:g.string()}).passthrough())}).passthrough(),a9=g.object({type:g.literal("summary_text"),text:g.string()}).passthrough(),p9=g.object({type:g.literal("reasoning_text"),reasoning_text:g.string()}).passthrough(),Z9=g.object({type:g.literal("reasoning"),summary:g.array(a9).optional(),content:g.array(p9).optional(),encrypted_content:g.string().optional()}).passthrough(),v9=new Set(["message","function_call","function_call_output","additional_tools","reasoning"]),tm=g.object({type:g.string()}).passthrough().refine((t)=>!v9.has(t.type),{message:"known input items must have a valid payload"}),nm=g.union([C9,K9,V9,j9,Z9,tm]),sm=g.object({type:g.literal("function"),name:g.string().min(1),description:g.string().optional(),parameters:f0.optional(),strict:g.boolean().optional()}).passthrough(),im=g.object({effort:g.enum(["none","minimal","low","medium","high","xhigh"]).optional(),summary:g.unknown().optional()}).passthrough(),rm=g.object({model:g.string(),input:g.union([g.string(),g.array(nm)]),instructions:g.string().optional(),stream:g.boolean().default(!1),tools:g.array(sm).optional(),tool_choice:g.literal("auto").optional(),parallel_tool_calls:g.boolean().optional(),reasoning:im.nullable().optional(),include:g.array(g.string()).optional(),store:g.boolean().optional(),text:g.unknown().optional(),service_tier:g.unknown().optional(),prompt_cache_key:g.string().optional(),client_metadata:g.unknown().optional(),previous_response_id:g.string().optional()}).passthrough();function Wo(t){let n=Q9.safeParse(t);if(n.success)return{ok:!0,value:n.data};let s=n.error.issues.map((i)=>{return`${i.path.length>0?i.path.join("."):"request"}: ${i.message}`}).join(", ");return{ok:!1,response:V(400,`Invalid request: ${s}`,"invalid_request_error","invalid_request")}}function ld(t){let n=rm.safeParse(t);if(n.success)return{ok:!0,value:n.data};let s=n.error.issues.map((i)=>{return`${i.path.length>0?i.path.join("."):"request"}: ${i.message}`}).join(", ");return{ok:!1,response:V(400,`Invalid request: ${s}`,"invalid_request_error","invalid_request")}}class h0 extends Error{limit;name="RequestBodyTooLargeError";constructor(t){super(`Request body exceeds the ${t} byte limit`);this.limit=t}}function c0(t){return t.reason instanceof Error?t.reason:new DOMException("Request deadline exceeded","TimeoutError")}async function em(t,n,s){let i=t.body?.getReader();if(!i)return{ok:!0,text:""};let r=[],e=0,f,o=new Promise((h,u)=>{f=u}),c=()=>{let h=c0(s.combined);f?.(h),i.cancel(h)};s.combined.addEventListener("abort",c,{once:!0});try{while(!0){if(s.combined.aborted)throw c0(s.combined);let l=await Promise.race([i.read(),o]);if(s.combined.aborted)throw c0(s.combined);if(l.done)break;if(e+=l.value.byteLength,e>n)throw new h0(n);r.push(l.value)}let h=new Uint8Array(e),u=0;for(let l of r)h.set(l,u),u+=l.byteLength;return{ok:!0,text:new TextDecoder().decode(h)}}catch(h){if(h instanceof h0)return i.cancel(h).catch(()=>{return}),{ok:!1,response:V(413,h.message,"invalid_request_error","request_too_large")};if(s.deadline.aborted)return i.cancel(h).catch(()=>{return}),{ok:!1,response:V(504,"Request deadline exceeded","timeout_error","request_timeout")};if(s.client.aborted)return i.cancel(h).catch(()=>{return}),{ok:!1,response:V(499,"Client closed request","request_aborted","client_disconnected")};throw h}finally{s.combined.removeEventListener("abort",c)}}function om(t,n){let s=t.body;if(!s)return t;let i=s.getReader(),r=new TextDecoder,e=new TextEncoder,f="",o=!1,c=!1,h=()=>{if(c)return;c=!0,n()};return new Response(new ReadableStream({async pull(u){try{while(!0){let l=f.indexOf(`
|
|
135
|
-
`);if(l>=0){let A=f.slice(0,l).trimEnd();if(f=f.slice(l+1),A.length>0){u.enqueue(e.encode(`data: ${A}
|
|
136
|
-
|
|
137
|
-
`));return}continue}let _=await i.read();if(!_.done){f+=r.decode(_.value,{stream:!0});continue}f+=r.decode();let w=f.trim();if(f="",w.length>0){u.enqueue(e.encode(`data: ${w}
|
|
138
|
-
|
|
139
|
-
`));return}if(!o){o=!0,u.enqueue(e.encode(`data: [DONE]
|
|
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}
|
|
302
|
+
data: ${JSON.stringify(t)}
|
|
140
303
|
|
|
141
|
-
`));return}
|
|
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(`
|
|
142
306
|
|
|
143
|
-
`)),u.close(),h()}},cancel(u){i.cancel(u).catch(()=>{return}),h()}}),{status:t.status,headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive"}})}async function _d(t,n,s){let i=new AbortController,r=setTimeout(()=>i.abort(new DOMException("Request deadline exceeded","TimeoutError")),n.request_timeout_ms),e=AbortSignal.any([i.signal,t.signal]),f={combined:e,deadline:i.signal,client:t.signal},o=await em(t,n.max_request_body_bytes,f);if(!o.ok)return clearTimeout(r),o.response;let c;try{c=JSON.parse(o.text)}catch(_){if(clearTimeout(r),!(_ instanceof SyntaxError))throw _;return V(400,"Request body must contain valid JSON","invalid_request_error","invalid_json")}let h=Wo(c);if(!h.ok)return clearTimeout(r),h.response;let u=await Po({body:h.value,model:h.value.model,stream:h.value.stream,config:n,accountManager:s.accountManager,tokenRefresher:s.tokenRefresher,deadlineSignal:e,...s.makeClient?{makeClient:s.makeClient}:{}});if(t.signal.aborted&&!i.signal.aborted)return clearTimeout(r),V(499,"Client closed request","request_aborted","client_disconnected");let l=u.headers.get("Content-Type")??"";if(!h.value.stream||l.includes("application/json"))return clearTimeout(r),u;if(!l.includes("application/x-ndjson"))return clearTimeout(r),V(500,"Pipeline returned an unsupported streaming response","internal_error","invalid_pipeline_response");return om(u,()=>clearTimeout(r))}function wd(){return new Response(JSON.stringify({status:"ok"}),{status:200,headers:{"Content-Type":"application/json"}})}var fm=1700000000;function Ad(){let t=hd.map((n)=>({id:n.id,object:"model",created:fm,owned_by:"kiro",name:n.name,context_limit:n.contextLimit,output_limit:n.outputLimit,modalities:n.modalities}));return new Response(JSON.stringify({object:"list",data:t}),{status:200,headers:{"Content-Type":"application/json"}})}import{randomUUID as _0}from"crypto";function cm(t){return t.type==="message"}function hm(t){return t.type==="function_call"}function um(t){return t.type==="function_call_output"}function lm(t){return t.type==="additional_tools"}function _m(t){return t.type==="reasoning"}function wm(t,n){let s=[];for(let i of t){if((i.type==="input_text"||i.type==="output_text")&&"text"in i&&typeof i.text==="string"){s.push({type:"text",text:i.text});continue}if(i.type==="input_image"&&"image_url"in i&&typeof i.image_url==="string"){s.push({type:"image_url",image_url:{url:i.image_url}});continue}n.count++}return s}function Am(t){return[...(t.summary??[]).map((n)=>n.text),...(t.content??[]).map((n)=>n.reasoning_text)].filter((n)=>n.length>0).join(`
|
|
144
|
-
|
|
145
|
-
`)}function dm(t){return{type:"function",function:{name:t.name,...t.description!==void 0?{description:t.description}:{},...t.parameters!==void 0?{parameters:t.parameters}:{}}}}function Md(t){let n=[],s=(t.tools??[]).map(dm),i=new Set(s.map((l)=>l.function.name)),r={count:0},e=0,f=0,o=!1,c="";if(t.instructions&&t.instructions.length>0)n.push({role:"system",content:t.instructions});if(typeof t.input==="string")n.push({role:"user",content:t.input}),o=!0;else{let l=()=>{if(!c)return;n.push({role:"assistant",content:[u0(c)]}),c="",o=!0};for(let _ of t.input){if(_m(_)){let w=Am(_);if(w)c=c?`${c}
|
|
146
|
-
${w}`:w;continue}if(hm(_)){n.push({role:"assistant",...c?{content:[u0(c)]}:{},tool_calls:[{id:_.call_id,type:"function",function:{name:_.name,arguments:_.arguments}}]}),c="",o=!0;continue}if(cm(_)){if(_.role!=="assistant")l();let w=wm(_.content,r);if(_.role==="assistant")n.push({role:"assistant",content:c?[u0(c),...w]:w}),c="",o=!0;else if(n.push({role:_.role==="developer"?"system":_.role,content:w}),_.role==="user")o=!0;continue}if(um(_)){l(),n.push({role:"tool",tool_call_id:_.call_id,content:gm(_.output)}),o=!0;continue}if(lm(_)){for(let w of _.tools){if(w.type!=="function"||typeof w.name!=="string"||w.name.length===0||typeof w.parameters!=="object"||w.parameters===null||Array.isArray(w.parameters)||i.has(w.name)){f++;continue}s.push({type:"function",function:{name:w.name,...typeof w.description==="string"?{description:w.description}:{},parameters:Object.fromEntries(Object.entries(w.parameters))}}),i.add(w.name)}continue}l(),e++}l()}if(r.count,!o)return{ok:!1,code:"empty_input"};let h=Mm(t.reasoning?.effort);return{ok:!0,body:{model:t.model,stream:t.stream,messages:n,...s.length>0||t.tools!==void 0?{tools:s}:{},...t.tool_choice!==void 0?{tool_choice:t.tool_choice}:{},...h!==void 0?{reasoning_effort:h}:{}}}}import{randomUUID as mo}from"crypto";function gd(t){return{type:"response.created",sequence_number:t.sequenceNumber,response:{id:t.responseId,object:"response",status:"in_progress",model:t.model,output:[]}}}function l0(t){return{type:"response.output_item.added",sequence_number:t.sequenceNumber,output_index:t.outputIndex,item:t.item}}function dd(t){return{type:"response.output_text.delta",sequence_number:t.sequenceNumber,item_id:t.itemId,output_index:t.outputIndex,content_index:t.contentIndex,delta:t.delta}}function Ed(t){return{type:"response.reasoning_summary_text.delta",sequence_number:t.sequenceNumber,item_id:t.itemId,output_index:t.outputIndex,summary_index:t.summaryIndex,delta:t.delta}}function Rd(t){return{type:"response.reasoning_summary_text.done",sequence_number:t.sequenceNumber,item_id:t.itemId,output_index:t.outputIndex,summary_index:t.summaryIndex,text:t.text}}function Do(t){return{type:"response.output_item.done",sequence_number:t.sequenceNumber,output_index:t.outputIndex,item:t.item}}function bd(t){return{type:"response.completed",sequence_number:t.sequenceNumber,response:{id:t.responseId,object:"response",status:"completed",model:t.model,output:t.output,usage:t.usage}}}function Td(t){return{type:"response.failed",sequence_number:t.sequenceNumber,response:{id:t.responseId,object:"response",status:"failed",model:t.model,error:t.error}}}function Sd(t){return`event: ${t.type}
|
|
147
|
-
data: ${JSON.stringify(t)}
|
|
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}
|
|
308
|
+
data: ${JSON.stringify(n)}
|
|
148
309
|
|
|
149
|
-
`}function
|
|
150
|
-
`);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]
|
|
151
312
|
|
|
152
313
|
Commands:
|
|
153
314
|
serve [--config <path>] [--host <host>] [--port <port>] [--proxy <url>]
|
|
154
|
-
Start the
|
|
315
|
+
Start the Responses, Messages, and optional legacy Chat gateway.
|
|
155
316
|
login [--config <path>] [--start-url <url>] [--region <region>]
|
|
156
|
-
Sign in
|
|
317
|
+
Sign in to the local auth store. Shared mode uses "opencode auth login".
|
|
157
318
|
accounts list
|
|
158
|
-
List
|
|
319
|
+
List accounts in the local compatibility store.
|
|
159
320
|
accounts import [--from <path>] [--config <path>]
|
|
160
|
-
|
|
321
|
+
Snapshot authenticated accounts into the local compatibility store.
|
|
161
322
|
accounts remove <id|email>
|
|
162
|
-
Remove an account and write a tombstone.
|
|
323
|
+
Remove an account from the local compatibility store and write a tombstone.
|
|
163
324
|
|
|
164
325
|
Options:
|
|
165
|
-
-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
|
|
166
327
|
id, email, auth_method, region, oidc_region, client_id, client_secret,
|
|
167
328
|
profile_arn, start_url, refresh_token, access_token, expires_at,
|
|
168
329
|
rate_limit_reset, is_healthy, unhealthy_reason, recovery_time, fail_count,
|
|
169
330
|
last_used, used_count, limit_count, last_sync, overage_count
|
|
170
|
-
FROM accounts`).all();for(let c of
|
|
171
|
-
${
|
|
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();
|